Friday, March 25, 2011

A craftsman knows his tools

Those who have worked with me for any length of time will know that I’m always looking for ways to improve my ability as a programmer. It may be in researching the latest available tool libraries (my current new favourite is StoryQ, which is great for developing BDD-style tests, and NSubstitute, which is as easy to use as Moq, but without those annoying calls to .Object), or how to write better, more reliable, build scripts. Either way, learning new skills and refining existing skills is an essential part of any craft (I’m deliberately steering clear of the ongoing “software development isn’t a craft”/“oh yes it is argument – this still applies to trades and scientific disciplines).

This week I have been focusing on knowing my tools, and being a developer who works with Microsoft technologies, those tools inevitably centre around Visual Studio. One way to increase your productivity is to reduce the time you spend doing pointless activities, or rather, when faced with two ways of achieving something, to choose the quicker way. The most obvious form for a programmer is to learn to let go of the mouse; a little strange maybe, especially in an operating system that defines itself around the use of the mouse, but it really does act as a great big brake on your productivity. When I first started playing guitar, it would take me several seconds to visualise the necessary finger patterns in my head, and then position my fingers on the fret board. Now after much practising, I can see an F# minor chord written down and play it without having to even think about it.

The first step was to get rid of all the toolbars and icons. If there are no icons on screen, there’s not much point using the mouse to click them! The commands are still all there, and they can be accessed via the menu bar if I get really stuck. As a bonus, suddenly I have much more viewable area to concentrate on what really matters – the code.

So my first shortcut to learn was how to stop a debug session. I knew F5 to launch the debugger, but I always clicked on the Stop icon to stop it; well, it turns out that Shift-F5 was my new best friend. So far, so easy, and not too much time saved.

The next useful one was the Surround-with snippet; this is part of the excellent Resharper which really takes the heavy lifting out of Windows programming). I was working with code which was throwing exceptions, and there was no exception handler. Before, I would have used the mouse to click just above the offending line of code, then typed in the standard try/catch blocks, then selected the offending line of code and cut’n’paste it into the try {} block, then clicked into the catch {} and add the exception handling. That’s a lot of pointless mouse and keyboard work. Now, using the keyboard, I would select the line of text (Shift-End to select to the end of the line), then Ctrl-K,S to bring up the Surround-with snippets, then type try and press Enter to surround my code with a try/catch block and automatically position the cursor in the catch {} block ready to select my exception type. Intellisense camel-case matching helped, so I only had to type in CE to match the ConstraintException I was trying to catch, hit Enter, and job done.

There are only so many hours in the day - reclaim yours by learning how to use the tools you have to get more done in less time.

Thursday, March 24, 2011

Synchronicity Part 2

Last year, it was Flash crashing Safari while I was trying to read an article about the problems with Flash. This time, it’s Google Chrome crashing while I’m trying to read about why the newly-released Firefox 4 is the new hotness.


Coincidence or conspiracy?

Tuesday, March 22, 2011

Unity and log4net

In my current project at TouchStar, I’ve had the opportunity to play with Unity, Microsoft’s Inversion-of-Control container. Previously I’ve used StructureMap, which is very popular, but I wanted to broaden my experience of different containers, and given that my project involved a WPF client, Unity seemed to be a good choice.

One of the first problems was how to configure log4net using Unity. Usually, log4net is called from within a class thusly:

   1: public class MyClassWithLogger()
   2: {
   3:     private static readonly ILog Logger = LogManager.GetLogger(typeof(this));
   5:     public void DoAction()
   6:     {
   7:         Logger.Debug("Hello world");
   8:         DoSomeOtherAction();
   9:     }
  11:     private void DoSomeOtherAction()
  12:     {
  13:         Logger.Debug("Still here");
  14:     }
  15: }

Which, depending on how you’ve configured your appenders, would produce an output something like this:

   1: MyClassWithLogger [DEBUG] - Hello world
   2: MyClassWithLogger [DEBUG] - Still here

So far, so vanilla, and the sort of code that anyone whose used log4net will have written thousands of times; but what happens if we want to apply good SOLID design principles and inject the log4net dependency into the class, rather than have the class create the instance itself. I prefer constructor injection for this, as it makes it very explicit what the dependencies are, and you can’t accidentally forget to set one without getting a compile-time error. The class would then become:

   1: public class MyClassWithLoggerDependency()
   2: {
   3:     private static readonly ILog Logger;
   5:     public MyClassWithLoggerDependency(ILog logger)
   6:     {
   7:         Logger = logger;
   8:     }
  10:     public void DoAction()
  11:     {
  12:         Logger.Debug("Hello world");
  13:         DoSomeOtherAction();
  14:     }
  16:     private void DoSomeOtherAction()
  17:     {
  18:         Logger.Debug("Still here");
  19:     }
  20: }

We’re now ready to apply some IoC magic with Unity to create the instance of ILog that our class will use. Since log4net uses its own factory class to instantiate itself, we have to jump through a hoop or two to get Unity to set things up properly:

   1: public class Program
   2: {
   3:     public static void Main(string[] args)
   4:     {
   5:         var container = new UnityContainer()
   6:             .Register<ILog>(new InjectionFactory(x => LogManager.GetLogger(typeof(this))));
   7:             .Register<MyClassWithLoggerDependency>()
   9:         var myClass = new container.Resolve<MyClassWithLoggerDependency>();
  10:         myClass.DoStuff();
  11:     }
  12: }

Which produces an output like this:

   1: Program [DEBUG] - Hello world
   2: Program [DEBUG] - Still here

See the problem? Now the logger is using the context of the code where Unity was configured to log from, rather than the context that the logger is being called from. I’ve seen plenty of questions asked about this, but it was only today that I stumbled upon the answer to this problem, hidden in a discussion on the Unity forums. A developer named Marco posted his solution, which was to create two extensions – the first being a BuildTracking extension, and the second being a LogCreation extension. The build tracking extension keeps tabs on what types are being built up, and then calls out to the log creation extension to create the logger component in the context of the class which is asking for it. Another developer, Scott, then posted his amendments that took care of some breaking API changes from the earlier version of Unity that Marco was using, together with an enhancement to improve detection of the calling class name when log4net is not being used with dependency injection.

My small contribution to the discussion was to provide the actual implementation code, which is as follows:

   1: public class Program
   2: {
   3:     public static void Main(string[] args)
   4:     {
   5:         var container = new UnityContainer()
   6:             .AddNewExtension<BuildTracking>()
   7:             .AddNewExtension<LogCreation>()
   8:             .Register<MyClassWithLoggerDependency>()
  10:         var myClass = new container.Resolve<MyClassWithLoggerDependency>();
  11:         myClass.DoStuff();
  12:     }
  13: }
Now that in my eyes is a much tidier piece of code. Gone is the explicit registration of the ILog type with its rather ungainly use of the InjectionFactory to create the appropriate implementation, and instead we have the two new extensions registered.

This is a great little bit of code, and big thanks go to Marco and Scott for sharing their contributions with us. I’m sure that many other developers will find this useful.

Monday, March 21, 2011

Watching Ideas Take Flight

In my last entry, I mentioned an idea I’d had before on how to make it easier to package .NET applications when run as part of an automated build. It solved a problem for me, and I thought it worth sharing, firstly as an aide mémoire for myself, and secondly because it seems the sort of thing that other people would find useful.

Rob Reynolds came across my post, and he obviously found it useful. In fact, he liked it so much that he has put together a NuGet package to make the set-up of _PublishedApplications even easier, together with a demo of how easy it is to use.

Demo of _PublishedApplications at work

I’m thrilled to see this getting out there – a big thanks to Rob for really getting this off the ground, as well as giving it more exposure.

Thursday, March 10, 2011

Publishing .NET Applications

This is a problem I came across in my previous job at Fairfax Digital, when setting up automated builds; now that I am working at TouchStar, I’m facing the same problem, but couldn’t remember what I did the first time round.

The problem is this: when building ASP.NET web applications using TFS or some other continuous integration solution (I’m using UppercuT at TouchStar), the MSBuild engine very conveniently creates a _PublishedWebsites folder in your output folder, and then creates a subfolder in that folder for each website that you are creating. So far, so good. However, when building executable applications, such as console apps, WPF applications or Windows services (and I’m building all three at TouchStar) then it just throws everything into one directory, and leaves it to you to pick out the bits you need. “If only you could export your build results to a _PublishedApplications folder!”, I hear you cry.

Well, that’s essentially my solution. I took a copy of the Microsoft.WebApplication.targets file that is referenced in the ASP.NET project file, renamed it to Microsoft.Application.targets and saved it to C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\Applications. I then tweaked it, renaming variables and such to match the type of content, and removing any references to /bin folders. I then reference the new file in the Visual Studio project file by adding the following line:

  <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\Applications\Microsoft.Application.targets" />

And voila! I now have one folder per application in the _PublishedApplications folder when run as part of an automated build. If I build from within Visual Studio, outputs are still sent to their usual location (e.g. /bin/Debug/). I’ve included a link to the file below.

[Download Microsoft.Application.targets]