So I’ve been messing around building a Dependency Injection container in my spare time. Mainly for my own amusement, but also to practice designing DSLs and to play with some C# 4 features like anonymous objects.
One of the first problems I came across was with requesting an interface that had been registered with a more specific generic type.
We have a representation of the registration of interface and its implementation via a factory method shown below:
public class FactoryRegistration : ObjectRegistration
{
public FactoryRegistration<T>(Type forType, Func<T> factoryFunction) : base(forType)
{
FactoryFunction = factoryFunction;
}
public Func<T> FactoryFunction { get; private set; }
}
public T Resolve<T>()
{
...snip...
var factoryRegistration = registration as FactoryRegistration<T>;
return (T) factoryRegistration.FactoryFunction();
}
new FactoryRegistration<Class>(typeof(IClass), () => new Class());
resolver.Resolve<IClass>();
var factoryRegistration = registration as FactoryRegistration<IClass>; return (T) factoryRegistration.FactoryFunction();
public Giraffe MakeGiraffe() {
return new Giraffe();
}
Func<Animal> someFunc = MakeGiraffe();
public interface IFactoryRegistration<out T>
{
Func<T> FactoryFunction { get; }
}
public class FactoryRegistration : ObjectRegistration, IFactoryRegistration<T>
{
public FactoryRegistration<T>(Type forType, Func factoryFunction) : base(forType)
{
FactoryFunction = factoryFunction;
}
public Func<T> FactoryFunction { get; private set; }
}
public T Resolve<T>()
{
...snip...
var factoryRegistration = registration as IFactoryRegistration<T>;
return (T) factoryRegistration.FactoryFunction();
}
Those cheeky little devils at Swisscom have found a novel way of restricting wifi sharing of their 3G dongles, resulting in the following error message when attempting to connect to a network in Windows 7:
“Your network administrator has blocked you from connecting to this network”
With a little searching I came across this solution, which allows you to fix it via an Administrators Command Prompt as follows:
netsh wlan delete filter permission=denyall networktype=infrastructure netsh wlan delete filter permission=denyall networktype=adhoc
Enjoy
(continued from Part 2)
Test 2
This was centred around the choice of disk drive. We’re building a slightly different project from before, but similar size (about 100k LOC) and structure (about 55 projects). This main difference this time was that MsBuild was being executed with the following property:
OutDir=c:\A\Single\Output\Directory
So we are cutting out a LOT of I/O. Every assembly, including the lib ones, are being copied only once per run. So this negates a lot of the purported benefits of SSD and RAM drives, but IMO it ends up being much more indicative of the kind of improvements you can get from good architecture (refer to Test 1). Finally, we are also cleaning each bin & obj directories before each pass:
HDD - 5 builds in 3:00 mins @ 36 seconds each
SSD - 5 builds in 2:37 mins @ 31 seconds each (~15% faster)
RAM* - 5 builds in 2:20 mins @ 28 seconds each (~23% faster)
I also ran another RAM disk run using the original project structure in Test 1
10 builds in 03:06 @ 00:18 per build (~80% faster than the original 91 seconds)
* The RAM Disk used can be found here: http://www.ltr-data.se/opencode.html/#ImDisk
Conclusions
So what can we infer from these results? Well, quite a lot really - but as always they come with caveats.
1. I/O is a killer. Getting rid of all those copy local references took nearly 90% off the build time.
2. Csc.exe is fast. Damn fast. Spinning up all those Win32 subprocesses costs a lot of time, and when you only have to do it once, the compile times drop to near 0.
3. Faster drives help. But they only Band-Aid over the symptoms, you’ll get much better results by addressing the root cause.
Now obviously I’m not suggesting that you go and refactor your entire codebase into a single project file. There are lots of things to consider when structuring .NET solutions; the make-up of your deployable artefacts, separating test & production code, vertical & horizontal partitioning of functionality, “code re-use” (although the alleged benefits of this is a topic for another day) etc etc. However, its worth keeping in mind, especially early in the project, the potential consequences of design choices.
Next time, I’ll be looking at the impact that CI tools can have on the speed of your build process.
PS. I discovered another little gem today. Sick of all those XML IntelliSense files clogging up your output folders? Try this little nugget, and shave 40% off your artefact sizes:
MsBuild.exe YourBuild.file /p:GenerateDocumentation=false;AllowedReferenceRelatedFileExtensions=none
(Continued from Part 1)
So, nothing like some hard figures to help sharpen the mind…
Test 1
This test was centred around project structure… that is, the number of csproj’s and the type of references each held to each other.
Our test machine was an i7 with 8 gigs of RAM and a 7200pm HDD, each run was held after a fresh reboot, no other programs running (save a terminal session). MsBuild was executed from within a small python script, and the timing information was output to the console. The measurements which follows aren’t particularly scientific, however I hope they serve as an indication of what is possible.
Original Structure (our baseline)
This was a solution file of approximately ~80 projects & 125k LOC. There was quite a number of projects with only a handful of .cs files, and every project file was set to CopyLocal = true for its non-mscorlib references. This basically amounted to a collective output of thousands of assemblies, with many copies of the same third-party DLL’s in each output directory (think, 100’s of copies of nhibernate.dll & nservicebus.dll). Our build times were:
10 builds in 15:18 mins @ 1:31 mins per build
Assembly/Weak references (CopyLocal = false)
That CopyLocal setting (or <private> node in the csproj XML) that I mentioned above was resulting in a huge amount of file I/O for each and every build. So, following Patrick Smacchia’s advice from the article I linked to in the first part of this series, I converted every reference (via a little tool I wrote) to CopyLocal = false, and ran another test run. An 81% improvement… not bad.
10 builds in 3:08 mins @ 0:18 mins per build
Single Project file
Watching all those MsBuild instances scroll up my terminal window (apart from being ridiculously hypnotic), I noticed something else. MsBuild shelling out to csc.exe takes a rather long time, maybe a second or two each and every time. However, once its running the compilation itself is very, very quick. So, with the help of ReSharper (CTRL + R + O is your friend), I merged all the code into a single project file. The results are impressive - almost 2 orders of magnitude improvement!
10 builds in 16 secs @ 1.6 secs per build
Ok, so now we are starting to see where the bottlenecks lie in our build process. Next, I’ll be looking at the impact of various drives (HDD, SSD and RAMDisks) on compilation times.
So, my current role has us dealing with a build, deployment and integration test cycle of about 2 hours. Given the 50-odd developers spread across 6-7 teams, this is not a particularly nice situation. Apart from it being a PITA, a feedback loop of this length results in plenty of negative consequences, a selection of which include:
We get into a situation where we are no longer “continually integrating” our work, but moving back to the dark old days of hourly or nightly builds (or not at all!). Instead of speeding up, the teams are slowing down, releases become less frequent and quality inevitably falls.
So, considering the amount of lost development resource this was costing the company (2 hours times N developers = a lot of money and more importantly time), I was tasked with improving the situation in any way that we could. Some outcomes were possible, some not, some resulted in great improvements, others only minor gains. But it did mean that I did possibly more research into the MsBuild system, csc.exe, .NET assembly structures and Visual Studio project files than is probably healthy, in an effort to squeeze every last second of time out of the process.
I’ll present my findings, and a bunch of interesting articles I (re)discovered along the way in the next few weeks. In the meantime, and to help set the scene somewhat, enjoy this little gem from the man himself - Patrick Smacchia (creator of NDepend)
http://www.simple-talk.com/dotnet/.net-framework/partitioning-your-code-base-through-.net-assemblies-and-visual-studio-projects/
I’ve had to setup my dev environment on a few different machines recently. Quite a simple, but repetitive exercise, so I decided to see if I could make it completely portable. The TL;DR of it is that you can’t completely - but you can to a certain extent.
Here’s what I’ve managed to do so far:
a) File sync
I’m using SpiderOak currently. DropBox only lets you backup a single folder, and Ubuntu One’s conflict resolution leaves a lot to be desired on Windows (at the moment) - appending .u1.conflict to filenames all over the place. The SpiderOak client is not perfect either - but it seems to be a workable solution so far.
b) Dotfiles
I’ve added some of my dotfiles to their own directory (.bashrc, .bash_history, .ssh/, .gitconfig etc), and got them syncing to the “cloud”. You can then use mklink to make a Windows version of a symlink, thus:
mklink /H ..\.bashrc dotfiles\.bashrc
c) Portable apps
Most of the tools I use have a portable version (obviously with the exception of Visual Studio & Resharper), so get these sync’d up as well
- Git (make sure you set GITDIR in your environment)
- Console2 (delete the config in your %APPDATA%)
- Sublime (this is a great little text editor I’ve just discovered, so long Notepad++!)
- WinSplit Revolution
- Unlocker
d) The extras
Next thing I did was to create batch files to set your symlinks and path. The symlinks work a treat, but the ENV/PATH stuff is a bit of a pain (more on this below).
As a nice to have, there are some registry files to add stuff to your context menu as thus:
Windows Registry Editor Version 5.00 [HKEY_CLASSES_ROOT\*\shell\Open with Sublime\command] @="C:\\Users\\matt.jackson\\dev\\Sublime Text 2 Build 2139\\sublime_text.exe %1"
d) What I haven’t done yet
Git Extensions. There is a portable version I believe, but the Explorer menu is the main reason I use it. The GitExtensions project sets these via a MSI, which is less than ideal - I’m open to suggestions.
p4merge. Probably the best thing to come out of Perforce, and its free! Doesn’t appear to be portable though.
Resharper license/settings. I know settings are stored in %AppData%, so this is on my TODO list. License information is probably in the registry but to be confirmed. Work in progress.
Autorun scripts on logon. Maybe add something to my .bashrc or similar that ensures everything is set correctly. Need to think on this more.
Add directories to your user PATH permanently. I could have sworn there was a way do this via SET but I still can’t find it. For now, its a case of copy/pasting into a dialog box.
I’d love to hear about people’s experiences with this. How far have you got and have you solved anything on the TODO list above?
Sonar is a shiny dashboard for code quality that provides an integration point for various quality frameworks (FxCop, StyleCop, NCover, Gallio, Gendarme etc). Unfortunately (like most awesome tools), its native to the JVM but there are actively maintained plugins for .NET.
So here’s a quick rundown for how I got it running on my local machine:
sonar.jdbc.url: jdbc:derby://localhost:1527/sonar;create=true
sonar.jdbc.driverClassName: org.apache.derby.jdbc.ClientDriver
I’ve had to solve some interesting problems over the last few weeks, and although it doesn’t really surprise me, git has come to the rescue in every single case.
Merging two git repositories
Say you were working on a spike of some independent code in its’ own repo, and you’ve decided you want to merge it into your main repository. Easy:
http://nuclearsquid.com/writings/subtree-merging-and-you/
Triggering TeamCity builds directly from github
GitHub is awesome. You should host your code there. But triggering your local build without polling them every 30 seconds? No problem:
http://www.jaxzin.com/2011/02/teamcity-build-triggering-by-github.html
Splitting a git repository (including history)
Finally, imagine a folder that you’d love to get rid of out of your repository. Hypothetically, let’s say a folder full of documentation, specifications, Word files, Visio files and the like. Hundreds of megs and you don’t really need that shit in a codebase do you? Well, let’s split it out:
http://stackoverflow.com/questions/359424/detach-subdirectory-into-separate-git-repository
// copy your repo to a new directory
git clone --no-hardlinks ./original_repo ./new_repo
// now filter out the folder(s) you want to keep
cd new_repo/
git status
git filter-branch --subdirectory-filter ./the_folder_you_want_to_split/ HEAD
git reset --hard
rm -rf .git/refs/original/
git reflog expire --expire=now --all
git gc --aggressive --prune=now// and head back to the original repo and delete that folder
cd ../original_repo/
git filter-branch --index-filter "git rm -r -f --cached --ignore-unmatch the_folder_you_want_to_split" --prune-empty HEAD
git reset --hard
git gc --aggressive --prune=now
And one for the road, here’s a cool little site that outlines what goes on under git’s covers:
I did have a few free ebooks on the topic, I’ll see if I can dig them up - they are great reads.
Some little gems from my .gitconfig…
p4merge with git
[diff] tool = p4merge guitool = p4merge [difftool "p4merge"] path = C:/Program Files/Perforce/p4merge.exe cmd = \"C:/Program Files/Perforce/p4merge.exe\" \"$LOCAL\" \"$REMOTE\" [merge] summary = true tool = p4merge [mergetool "p4merge"] path = C:/Program Files/Perforce/p4merge.exe keepBackup = false cmd = \"c:/Program Files/Perforce/p4merge.exe\" \"$BASE\" \"$LOCAL\" \"$REMOTE\" \"$MERGED\"
pull with automatic rebase
I have just discovered the beauty of pull with rebase (single, easy to read history on master! no more merges!). However, its a bit of a pain to continually do this:
git pull --rebase origin master
So to switch on rebase by default…
git config --global branch.autosetuprebase always
Beware! This only applies to new repo’s, not existing ones. To update existing repo’s with this setting try this:
git config branch.branch-name.rebase true
eg.
git config branch.master.rebase true
(reference: git with automatic rebase)
ssh-agent on windows
Ok, this one is just stolen straight from the github site here, but it still bears mentioning anyway. Use ssh-agent to hold onto your keys instead of stupid pageant. Add this to your .bashrc and have your keys loaded the first time you launch git bash after a boot!
SSH_ENV="$HOME/.ssh/environment"
# start the ssh-agent
function start_agent {
echo "Initializing new SSH agent..."
# spawn ssh-agent
ssh-agent | sed 's/^echo/#echo/' > "$SSH_ENV"
echo succeeded
chmod 600 "$SSH_ENV"
. "$SSH_ENV" > /dev/null
ssh-add
}
# test for identities
function test_identities {
# test whether standard identities have been added to the agent already
ssh-add -l | grep "The agent has no identities" > /dev/null
if [ $? -eq 0 ]; then
ssh-add
# $SSH_AUTH_SOCK broken so we start a new proper agent
if [ $? -eq 2 ];then
start_agent
fi
fi
}
# check for running ssh-agent with proper $SSH_AGENT_PID
if [ -n "$SSH_AGENT_PID" ]; then
ps -ef | grep "$SSH_AGENT_PID" | grep ssh-agent > /dev/null
if [ $? -eq 0 ]; then
test_identities
fi
# if $SSH_AGENT_PID is not properly set, we might be able to load one from
# $SSH_ENV
else
if [ -f "$SSH_ENV" ]; then
. "$SSH_ENV" > /dev/null
fi
ps -ef | grep "$SSH_AGENT_PID" | grep -v grep | grep ssh-agent > /dev/null
if [ $? -eq 0 ]; then
test_identities
else
start_agent
fi
fi
Ok given a collection of documents like this:
{
"Name": "A",
"Price": 1.50
}
How do I perform a simple aggregation on the prices in the list? I don't want to perform any grouping, just a simple scalar result.
ie. sum, avg etc
I have tried both of the following without success:
Map only:
for doc in docs
select new { sumPrices = Sum(d => d.Price) }
and
Map:
for doc in docs
select new { price = d.Price }
Reduce:
for result in results
select new { sumPrices = Sum(result) }
Just doing some quick spikes into possibly using a messaging system to process files that are in a nicely decoupled work flow system.
What are the pro's and cons that people have found of using each of the above frameworks? What are the advantages of using these versus a hand-rolled MSMQ system with the WCF bindings and/or non-MSMQ solutions??
We have been kicking about an idea where UAT can be tested with near live data (say maximum a week old). I strongly believe that development and QA environments should be in control of their own data, but UAT (the final tier before production) represents a bit of a grey area. So my questions are:
a) is this a good idea? I think so, but have nagging doubts.
b) if so, what are some proven techniques that people have used in the past?
I want to be able to replicate this adsutil.vbs behaviour in PowerShell:
cscript adsutil.vbs set W3SVC/$(ProjectWebSiteIdentifier)/MimeMap
".pdf,application/pdf"
and I've gotten as far as getting the website object:
$website = gwmi -namespace "root\MicrosoftIISv2" -class "IISWebServerSetting"
-filter "ServerComment like '%$name%'"
if (!($website -eq $NULL)) {
#add some mimetype
}
and listing out the MimeMap collection:
([adsi]"IIS://localhost/MimeMap").MimeMap
Anyone know how to fill in the blanks so that I can add mimetypes to an exiting IIS6 website?
Is it newline? prompt? What exactly?
Trying to run powershell over plink and the command executes but plink doesn't recognise its finished and the session hangs. Most curiously though, the command executes successfully when sent through the shell (via Putty). However, when sent via plink, the same command hangs...
Any ideas?
We're evaluating FinalBuilder and are curious as to how it works under the hood. For compiling C# code, does it:
You can also specify this via the command line:
MsBuild.exe build.file /p:AllowedReferenceRelatedFileExtensions=none
You can also specify this via the command line:
MsBuild.exe build.file /p:AllowedReferenceRelatedFileExtensions=none
You can also specify this via the command line:
MsBuild.exe build.file /p:AllowedReferenceRelatedFileExtensions=none
Ok well after much frustration and research, this is the solution I've come up with...
a) Grab the COM DLL "Interop.IISOle.dll" and put it somewhere easily referenced (eg. reference the COM component "Active DS IIS Namespace Provider" in a dummy project, build and grab the DLL from the bin folder)
b)
function AddMimeType ([string] $websiteId, [string] $extension,
[string] $application)
{
[Reflection.Assembly]::LoadFile("yourpath\Interop.IISOle.dll") | Out-Null;
$directoryEntry = New-Object System
.DirectoryServices
.DirectoryEntry("IIS://localhost/W3SVC/$websiteId/root");
try {
$mimeMap = $directoryEntry.Properties["MimeMap"]
$mimeType = New-Object "IISOle.MimeMapClass";
$mimeType.Extension = $extension
$mimeType.MimeType = $application
$mimeMap.Add($mimeType)
$directoryEntry.CommitChanges()
}
finally {
if ($directoryEntry -ne $null) {
if ($directoryEntry.psbase -eq $null) {
$directoryEntry.Dispose()
} else {
$directoryEntry.psbase.Dispose()
}
}
}
}
c) Sample usage:
AddMimeType "123456" ".pdf" "application/pdf"
References: Can I setup an IIS MIME type in .NET?
Ok so I've ordered Applying Domain-Driven Design and Patterns: Using .Net, but while I wait for it to arrive I'm looking at starting to apply the techniques in my current project. I really grasp the concepts quite well now, but when I try to apply them I get caught up with the execution and end up leaking my respsonsibilities across the various projects. As such I'm looking for resources out there that can guide me in the right direction, especially sample projects with actual code that I can work against. I remember a sample site out there in the Alt.Net world that had a real working project that people could browse but can't seem to find it? Does anyone out there have that link, or any other links they could share??
Edit: I have since found this sample application from the DomainDrivenDesign.org site (although it is Java based) as well as the example outlined below.
I am still looking for the Alt.Net sample application if anyone knows where to find it?
Just interested in hearing some experiences with Electric Cloud from people who have been using it at their work environment.
As a long-time user of TeamCity, I'm particularly interested in hearing people compare/contrast with other CI solutions, like TeamCity, Hudson/Jenkins, CruiseControl, Go etc
Any using nHibernate with a Domain object & DTO object implemented from a common interface? I'm trying to separate all of my nHibernate attributes into the Domain object, leaving my DTO's and interface clean.
The problem comes with nHibernate throwing errors when it tries to associate the interfaces with the concrete classes.
NHibernate.MappingException: Association references unmapped class: IContact
I understand why its complaining about the use of the non-hibernated interface, but I'm struggling to visual a way to restructure around it. A skeleton reproduction of my code is set out as below, any ideas for how to structure my code better?
public interface ICompany
{
IList<IContact> Contacts { get; set; }
}
public class CompanyDTO : ICompany
{
private IList<IContact> contacts;
public IList<IContact> Contacts { get { return this.contacts; } set { this.contacts = value; } }
}
[ActiveRecord]
public class Company : ActiveRecordBase<Company>, ICompany
{
private IList<IContact> contacts;
[HasMany(Inverse=true, Table="Contact", ColumnKey="CompanyId")]
[ScriptIgnore]
public IList<IContact> Contacts { get { return this.contacts; } set { this.contacts = value; } }
}
Edit:
I want to have a common interface so that I can ensure they are keeping the same fields (ie. leaning on the compiler to keep them consistent). It also allows me to use the DTO's in the view part of my application, but casts them to domain objects for business and data access. Also, alex's solution does not work because ICompany's Contacts is of type IList, not IList. I would like to keep it as IContact so my DTO object has no knowledge of the Contact Domain object.
I'm looking for a lightweight, easy to setup CI server that I can run on my laptop along with Visual Studio & Resharper. I'm obviously looking at all the big names like CruiseControl, TeamCity etc etc but the biggest consideration to me is ease of setup and to a lesser extent memory footprint.
Edit: I'd also like some suggestions for other solutions outside the big 2/3...
Edit: I'm about to accept an answer if no one else has anything to add?
Given a store which is a collection of JSON documents in the (approximate) form of:
{
PeriodStart: 18/04/2011 17:10:49
PeriodEnd: 18/04/2011 17:15:54
Count: 12902
Max: 23041 Min: 0
Mean: 102.86 StdDev: 560.97
},
{
PeriodStart: 18/04/2011 17:15:49
PeriodEnd: 18/04/2011 17:20:54
Count: 10000
Max: 23041 Min: 0
Mean: 102.86 StdDev: 560.97
}... etc
If I want to query the collection for given date range (say all documents from last 24 hours), which would give me the easiest querying operations to do this?
To further elaborate on requirements:
I've decided to go with Mongo for the time being.
I found that setup/deployment was relatively easy, and the C# wrapper was adequate for what we're trying to do (and in the cases where its not we can resort to javascript queries easily).
I'm trying to create a service that executes scheduled Tasks in an asynchronous (and parallel) way using TPL.
The basic requirement is that for a bunch of different tasks, each with their own scheduled rates (some to be executed every second, others 30 seconds, other 5 mins etc) to be executed concurrently. And I'm not sure of the best way to go about this, especially considering the ConcurrentBag (which I was considering as a holder of all future tasks) contains no methods with which to select collections of tasks that need to be executed.
It also means that I can't use WaitAny or WaitAll, as these short-running tasks need to finish and requeue themselves independently.
How should I proceed with this?
Edit:
Ok basically my design is thus:
A ScheduledTask, which is a wrapper for Task with a Scheduled DateTime property. A bunch of these are stored in a ConcurrentBag
A Controller that polls the ConcurrentBag (currently just a while(true) loop, but could be a Timer or similar), removing any that are scheduled, and Start()'s them.
Each ScheduledTask holds a reference to the ConcurrentBag, and enqueues a new instance of itself when it completes, with a new ScheduledTime.
This design seems to work so far, but there is something about each Task holding a reference to the ConcurrentBag that doesn't sit well with me. Any design comments or suggestions would be appreciated.
A few points:
a) Following the principle of "Tell, don't ask", it is not the AnimalShowTimeService's reposibility to resolve the type. Push the Animal to another object to make the choice.
b) Hardcoding references to ObjectFactory inside your domain is a bad design. The purpose of a DI container is to decouple your objects, not move the coupling somewhere else (StructureMap in this case).
Edit:
With regards to a) don't solve it in a polymorphic manner. You don't need generics to share behaviour, and inheritance hierachies only increase coupling. If you really do need to go down this path, I think implementing your own Convention might be what you're looking for. Or you could name every instance of IAmimal, and resolve the service with ObjectFactory.GetInstance(animal.GetType().ToString()), but that is clearly not ideal.
I think the point is however, that you're doing this as an exercise for DI & DI containers (I think), and if you can't get your design to fit, maybe you need to scrap it and start again, rather than trying to force a square peg into a round hole.
Why can't you use WebClient, WebRequest or HttpWebRequest? They are more than adequate for HTTP calls (including all the restful verbs).
I'm getting the following error when trying to initialise the SMO objects in my application:
Microsoft.SqlServer.Management.Trace.SqlTraceException: Failed to initialize object as reader. ---> System.IO.FileNotFoundException: Could not load file or assembly 'file:///c:\Program Files\Microsoft SQL Server\100\Tools\Binn\pfclnt.dll' or one of its dependencies. The system cannot find the file specified.
This file is indeed missing from that location.
Any ideas why and where I can go about getting it?
I'm running: SqlServer 2005 ManagementStudio 9.00.4035.00 WinServer 2003 SP2
Anyone have any snippets for creating a SQL Server trace on the fly? I've found this on MSDN but it only seems to output to the file system. What about logging it to a DB table or returning it via some sort of UDF? Ideally it would be used to create a debugging tool, so it would be nice to wrap it up in something that could be turned on and off easily.
I've created a performance counter that shows a fraction of an incremented value (RawFraction type) over a base value (RawBase).
Unfortunately, when monitoring this value, it only shows the percentage when one of the counters is incremented. At all other times it it is sampled, it shows 0. Is there some way to tell the counter to hold onto the last value until the next time it needs to recalculate the fraction?
When I visit a particular site on my laptop through my tethered phone's 3G, I keep getting served a certain broken javascript file. However when I do a force refresh on the page (Ctrl+F5) the most recent copy of the file is served up correctly, so clearly the old javascript file is being cached somewhere (probably on my phone providers proxy).
How can I find out where this cached file is being served from, and somehow break the cache to force the most recently copy to to be served?
Edit: What I'm talking about is some kind of tracert on the particular JS file?
You should absolutely consider the low level controllers and scripting engine to be part of your domain model, however you should have these representated via abstractions (ie. with interfaces) so that you can properly test the rest of your domain.
I would also recommend against doing much more upfront design, and instead let your design evolve via TDD, otherwise you run the risk of trying to shoehorn an implementation in just to fit your UML diagrams...
I have a username textbox on a form, that has a few validation rules applied to it via the DataAnnotation attributes:
[Required(ErrorMessage = "FTP login is required")]
[StringLength(15, ErrorMessage = "Must be 15 characters or fewer")]
[RegularExpression(@"[a-zA-Z0-9]*", ErrorMessage = "Alpha-numeric characters only")]
public string FtpLogin { get; set; }
I also have a button next to this text box, that fires off a jQuery ajax request that checks for the existence of the username as follows:
<button onclick="check(this);return false;" id="FtpLoginCheck" name="FtpLoginCheck">Available?</button>
I'm looking for a way of tieing the two together, so that the client-side validation is performed before the call to the "check(this)" in the onclick event.
Edit: To be more clear, I need a way to inspect or trigger the client-side validation result of the textbox, when I click the unrelated button beside it.
Edit: I now have the button JS checking for $("form").validate().invalid, but not displaying the usual validation messages. Almost there
Any ideas?
Any idea how we can assert a mock object was called when it is being accessed inside Parallel.ForEach via a closure? I assume that because each invocation is on a different thread that Rhino Mocks loses track of the object?
Pseudocode:
var someStub = MockRepository.GenerateStub()
Parallel.Foreach(collectionOfInts, anInt => someStub.DoSomething(anInt))
someStub.AssertWasCalled(s => s.DoSomething, Repeat.Five.Times)
This test will return an expectation violation, expecting the stub to be called 5 times but being actually called 0 times.
Any ideas how we can tell the lambdas to keep track of the thread-local stub object?
Ok, well I'm still not quite sure what the problem is, but I've found a workaround via the TeamCity forums.
Basically you want to echo some abitrary string and pipe that output into your powershell executable, like thus:
echo 'executing powershell...' | C:\windows\system32\windowspowershell \v1.0\powershell.exe exit 1
So then your full plink command becomes:
plink.exe user@someIp -i key.ppk -P 22 -batch -v "echo 'executing powershell...' | C:\windows\system32\windowspowershell\v1.0\powershell.exe exit 1"
Nb. Plink will still pass through return codes and console output using this method.
Link to TeamCity forum:
http://youtrack.jetbrains.net/issue/TW-6021
Hope this helps
Ok well as a temporary measure, we've just abstracted the call to Parallel.ForEach away into another class...
Any idea how I can tell AutoMapper to resolve a TypeConverter constructor argument using StructureMap?
ie. We have this:
private class StringIdToContentProviderConverter : TypeConverter<string, ContentProvider> {
private readonly IContentProviderRepository _repository;
public StringIdToContentProviderConverter(IContentProviderRepository repository) {
_repository = repository;
}
public StringIdToContentProviderConverter() {
_repository = ObjectFactory.GetInstance<IContentProviderRepository>();
}
protected override ContentProvider ConvertCore(string contentProviderId) {
return _repository.Get(new Guid(contentProviderId));
}
}
And in the AutoMap registration:
Mapper.CreateMap<Guid, ContentProvider>().ConvertUsing<GuidToContentProviderConverter>();
However, I don't like the idea of hardwiring an ObjectFactory.GetInstance in my constructor for the converter. Any ideas how I can tell AutoMapper how to resolve my IContentProviderRepository?
Or ideas to other approaches for using Automapper to hydrate domain objects from viewmodel ID's using a repository?
We found David B's solution worked the best. But we adapted it to a more general solution:
list.GroupBy(item => item.SomeProperty)
.Select(group => new List<T>(group))
.ToArray();
I meant, with the cassette 3.5 fork :)
How did you get on with this?
Why on earth are you using an IOC container for unit testing?
Did you try data migrations as well as db backups? What were the pros/cons of each?
I guess my question then is, you're just using DB backups once a month and then rolling forward migrations?
Don't really have the test case requirement, our UAT is more of a staging / final sign off from the customer. Functional test cases are handled earlier in the process.
Did you ever figure out a solution to this? I'm experiencing the same problem
Not necessarily... plenty of companies talk about their technologies, it might not even be the part of their product they consider their competitive advantage
I was hoping for a quicker answer than waiting for the vendor to get back to me
If you have so many HQL queries that you have strings causing memory issues, I would hazard a guess that you're doing it wrong.
Near realtime is the gig. Single point of failure is fairly acceptable because the source data is still archived somewhere else. Define mainenance requirements?
I agree this is not ideal
Criteria's allow you to do basically anything you would ever imagine doing with T-SQL
A mature C# library would also be nice, but most NoSql stores have one these days anyway, so...
Not necessarily... I'll edit the post
I am looking to build great products using great practices, and to constantly improve my skills and broaden my experience. TDD, SOLID, Lean and XP (including continuous integration & pair programming) are especially important to me.
I enjoy working on web-scale sites and API's, with SOA, REST and message-based systems of particular interest.
Currently renovating a legacy in-house structured product management system with ASP.NET MVC via TDD, SOLID, XP and Scrum.
Delivered significant improvements in the speed and quality of Wonga's development pipeline, focusing on continuous integration, automated testing, dependency management & deployment.
Utilised agile techniques such as TDD, XP and Lean to develop distributed & service oriented systems both for 7digital and clients such as Samsung, Waterstones and RIM.
Maintained and extended the moodboard.com site and internal photographic workflow systems.
Worked on the NDTMS web application, processing large volumes of patient data.
Worked on a variety of web and desktop applications for clients such as IGT, Reliance and Extend Technologies