No one likes their code to be changed

I consider myself really really lucky to be in the business of writing software. The reason being, this is the only creative thing I do in a day. When I am done coding a module, I am like, look at this thing, its my work :). ( It might not follow all the SOLID principles, but… well.. what the heck!). And I bet every programmer on this planet has some kind of love with the code they have written in an editor. When someone comes along and without taking your “feelings” into consideration just tears apart the code to “refactor” it, or may be remove extra white spaces for performance reasons!, you can be certain that the person is going to get pissed off at this. Be it your best friend, girl friend whatever, if you think a piece of code is not written with good standards, it is wise to explain why its not good to have it like this, and then delegate that person to refactor or take it up yourself in a friendly way.

Taking someone’s code, refactoring it and checking in with an email saying that your code was not good enough so I refactored it, will only suck all the spirit out of that person and you would be basically named as a dick in the team.

Happy Refactoring!


So you want to use Continuous Integration!

Alright, this would be among the better decisions you would have taken in your project. Good for ya. Well… what next? This is what happened to me lately. Whenever a new thing comes in town, like a pragmatic programmer I do not get on the “Wow this is awesome” wagon until I have done some homework over it. So for Continuous Integration (hereafter mentioned as CI), I looked around the cloud and found several options. One option that is obvious was CruiseControl. It has been used for quite some time in the developer community both .NET and in Java (and others may be). Not sure if it is just me on this, but I found configuring and getting in running for my project became a project in itself. I was basically sitting in front of my laptop trying to get my local svn server, CruiseControl  and few other bells and whistles that come with it to try talk to each other. Not straightforward.

Now you can certainly argue like, Ohhh commmmon man, you are a developer and nothing is straight forward anyways, CruiseControl is configurable in just a snap by editing xml files here and there, starting the service etc. But really I feel things like CI, Source Control which are used to enhance the efficiency of a team, should not become a management task in itself. It should just be easy to setup and get going. And so there is a relatively new kid in town Hudson. It is written in Java by Kohsuke Kawaguchi of Sun. I believe its only his brain into this tool and that makes it consistent throughout. I am mainly .NET guy and needed to get my C# projects into hudson. So here is what I had to do to get Hudson talk to my other companions on my laptop –:

  1. If you are completely Java agnostic, and happen to have no trace of Java on your machine, you would have to download Java atleast version 1.5. Get it from here, http://java.com/en/
  2. Download the latest and greatest hudson.war file from http://hudson-ci.org/latest/hudson.war.
  3. Place the downloaded hudson.war file at some sensible place, well I have it here C:\Hudson.
  4. Open a command prompt and get to folder location which has the hudson.war file. Issue the following command, java –jar hudson.war .
  5. Once hudson is started, visit http://localhost:8080/ on your browser and voila, you should have a wonderful Hudson dashboard smiling at you.

Now to configure my .NET project,

  1. Click ManageHudson in the left navigation links on the Dashboard. Click Manage Plugins (3rd link for the lazy ones, man I am spoiling you). Click the Available tab, Select the MSBuild Plugin and click Install and the very bottom of the page.
  2. Hudson would download everything you ask for and the automatic updates right off the web interface, so no need to upgrade manually.
  3. The MSBuild plugin is basically used to well, build your .NET projects using msbuild.exe. Configure this plugin with your msbuild settings. For really basic settings, Click Manage Hudson again. Click Configure System, navigate to MSBuild Builder section, name it something like MSBuild .NET 3.5 (can be anything really) and the path to the msbuild.exe. Typically the path would be C:\Windows\Microsoft.NET\Framework\v3.5\MSBuild.exe. Hit Save the very bottom of the page.
  4. Now go to the home page, click New Job. Give some Job name. Select “Build a free-style software project” which makes it all configurable.
  5. Since I use Subversion, in the Source Code Management section, I selected Subversion, and gave the repo url as my local repository path(svn://localhost/myproject/trunk/ConsoleApplication8). Local module directory can be set to a period “.”, so that Hudson copies the code files directly into its workspace.
  6. In Build section, click Add Build Step. You should see the Msbuild name you gave in the MSBuild plugin setup. Select that, for the MsBuild file, give the name of your solution like so, ConsoleApplication8.sln. You could give any additional command like arguments to MSBuild if needed for your project.
  7. Hit Save. On the Home Page you would see a link to your project. Click that, you should see a Build Now link in the left navigation links. This would build your project. Wohoooo!!

This is just a basic setting I did in Hudson and got myself CI’ed with Hudson. There are several options to choose from if you know what you are doing of course. I am still overhauling this tool and no doubt it sounds promising. Here are few wonderful links for much deeper help,

http://blog.bobcravens.com/2010/03/01/GettingStartedWithCIUsingHudsonForYourNETProjects.aspx

http://redsolo.blogspot.com/2008/04/guide-to-building-net-projects-using.html

Happy Integrating.


Generic WPF Dispatcher

Howdy! In a medium to large WPF application, it is fairly common required to do some background stuff and update the UI asynchronously. You could use the BackgroundWorker class to do this, you could use the Dispatcher object to do this too. Most of the people know how to use the Dispatcher and for those who do not, this link will surely help http://msdn.microsoft.com/en-us/magazine/cc163328.aspx.

Rather than peppering the Dispatcher code all over the application, it would be nice to have it in a single place. This can be achieved using extension methods on the Dispatcher class. Below is some code which can be used as is to make your Dispatcher generic enough to do most of the stuff.

internal static class TDFDispatcher
{
internal static void Dispatch(this Dispatcher source,Nullable<DispatcherPriority> priority,Action invokedDelegate)
{
if (invokedDelegate != null)
{
if (!source.CheckAccess())
{
source.Invoke(priority.HasValue ? priority.Value : DispatcherPriority.Normal, invokedDelegate);
}
else
{
invokedDelegate();
}
}
}

internal static void Dispatch<T>(this Dispatcher source, Nullable<DispatcherPriority> priority, Action<T> invokedDelegate,T arg)
{
if (invokedDelegate != null)
{
if (!source.CheckAccess())
{
source.Invoke(priority.HasValue ? priority.Value : DispatcherPriority.Normal, invokedDelegate,arg);
}
else
{
invokedDelegate(arg);
}
}
}

internal static TResult Dispatch<T,TResult>(this Dispatcher source, Nullable<DispatcherPriority> priority, Func<T,TResult> invokedDelegate, T arg)
{
TResult result = default(TResult);
if (invokedDelegate != null)
{
if (!source.CheckAccess())
{
result = (TResult)source.Invoke(priority.HasValue ? priority.Value : DispatcherPriority.Normal, invokedDelegate, arg);
}
else
{
result = invokedDelegate(arg);
}
}
return result;
}


You can certainly come up with even more permutations and combinations to enhance this class.



Happy Programming!


Creating instance of a type outside the current AppDomain

Howdy Ho! So I am came across a conundrum lately in my project where I had to create instances of a type via reflection. The scenario is, there is a Sample.dll which has a type defined in it MyType. The Sample.dll refers several other 3rd party dll’s like SomeOther1.dll and SomeCrap.dll. I have an executing assembly MyExecutingAssembly.exe residing in folder MyExecutingAssembly. The Sample.dll and its referenced files are located somewhere else in a folder called Sample.

Like a normal stupid developer, I wrote the following code to create the instance in MyExecutingAssembly.exe.

Assembly assembly = Assembly.LoadFrom(C:\Sample\Sample.dll);
Type appType = assembly.GetType(MyType);
object objClassInstance = Activator.CreateInstance(appType);

Boom! Error message for the 3rd line was something like, “Could not find assembly SomeCrap.dll, The assembly used while compiling might be different than that used while loading from …”. Blistering Barnacles, thundering typhoons… Now some straight talk,

The type MyType, resides in the Sample.dll, this dll references 2 other dlls, when the runtime tries so, it searches for the files in the folder where the MyExecutingAssembly.exe resides. This is so because the AppDomain in which we are trying to create the instance has the base directory path of the MyExecutingAssembly. Phew! Hope you get the issue here. There are several ways to tackle this,



Method 1



Create an appdomain, set its base directory to the folder where the Sample.dll and its referenced files reside. But this is some serious implication. Since we are in a separate AppDomain, we are creating the instance in a completely impenetrable environment. This asks for .NET remoting to communicate with the instance. The code would look as below,



Assembly assembly = Assembly.LoadFrom(@"C:\Sample\Sample.dll");
AppDomainSetup setup = new AppDomainSetup();
setup.ApplicationBase = @"C:\Sample\";
AppDomain appDomain = AppDomain.CreateDomain("AppHostDomain", null, setup);
object obj = appDomain.CreateInstanceFromAndUnwrap(@"C:\Sample\Sample.dll", "SampleProxy");

Observe that the type I am creating is not the actual MyType but a class called SampleProxy which inherits from MarshalByRefObject. I create instance of the MyType inside this class. Sigh! It seems you did not like this. More information on Suzanne’s blog here.

Method 2 



Recursively check references of all the assemblies and load all of them manually in the current AppDomain. This a bit lengthy process, but, well, it works. Here is the code,



Assembly assembly = Assembly.LoadFrom(@"C:\Sample\Sample.dll");
AssemblyName[] arr = assembly.GetReferencedAssemblies();
LoadAssembly(arr);


private void LoadAssembly(AssemblyName[] arr)
{
Assembly[] loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
List<string> names = new List<string>();
foreach (Assembly assem in loadedAssemblies)
{
names.Add(assem.FullName);
}

foreach (AssemblyName aname in arr)
{
if (!names.Contains(aname.FullName))
{
try
{
Assembly loadedAssembly = Assembly.LoadFrom(@"C:\Sample\" + aname.Name + ".dll");
AssemblyName[] referencedAssemblies = loadedAssembly.GetReferencedAssemblies();
LoadAssembly(referencedAssemblies);
}
catch (Exception ex)
{
continue;
}
}
}
}

Tedious eh.

Method 3



Use the AppDomain’s AssemblyResolve event. Basically, whenever you are trying to load assemblies in an AppDomain, if a particular assembly is that the runtime is trying to load fails for some reason, this event is fired. We can tap into this event and load the right assembly instead. Here is the code in short,



Assembly assembly = Assembly.LoadFrom(@"C:\Sample\Sample.dll");
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
object obj = Activator.CreateInstanceFrom(@"C:\Sample\Sample.dll", "MyType");

Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
string path = @"C:\Sample\Sample.dll";
string test = path.Substring(0,path.LastIndexOf(@"\"));
string[] arr = args.Name.Split(',');
string assemblyName = args.Name.Substring(0, args.Name.IndexOf(",")) + ".dll";
string newPath = System.IO.Path.Combine(test, assemblyName);
return Assembly.LoadFrom(newPath);
}


Well, a little better I guess. More information on this here.

Happy Programming!


Coding to the specs or “Spec”ing to the Code!

Its March. You need to deliver a fuckin awesome all-knowing, all-seeing application to your super ambitious client. The client has found you good enough to do this work for him. All is well, your manager is happy to take on this project, things move on. Oh but, did I mention that the delivery needs to be in 2nd week of May. Blistering Barnacles!!!!! Thundering Typhoooons, Maniacs, Ectoplasmsss…

In such cases, Agile, Waterfall, and other superman techniques are thrown out of the window, aren’t they? I do not give a crocodile’s ass for the manager or his boss or his boss. I am talking to the developer. Mate, the worst thing you could do in such case is to hastily start coding and get ready to deliver it and impress your boss, and may be get a free coupon to McDonald’s I(Not sure where I am going with this, but stay with me.) Although this is the thing you would be asked to do by your bosses. No specifications (specs), no clear requirements, no beer, just start the damn coding phase. A not so warm welcome to Outsourcing.

You the developer, do not have much control on these happenings. But there is one thing which can save your soul and make you a better human being. Write your own specifications. They can be rudimentary, as long as you know what you are writing in it, the purpose is served. Your specs can be just simple English statements like -

- Get all folders in the directory for given path.

- If folder with name Sucker exists, fork new thread.

- New thread will run background.

….

Your code then should follow this spec, and let me tell you, that really works. Jumping right into the editor might have worked for you before, but you can consider it as a coincidence. Writing such specs before coding might not get you the free coupon, but surely it will improve your code and make you feel better! Please do not go to your boss and explain him how important specs are for this project, let me say he is too smart to understand these things.

This is how I work and I can tell from my experience (its not that long experience really), I feel really good about massaging my fingers with some nice specs before slapping the keyboard with my crappy code.

Happy Programming!