This article gives a short introduction to the MSBuild tool.
Thanks to Joe Wass for correcting my bad english :o

MSBuild Basics

.NET 2.0 introduced a new tool called MSBuild. MSBuild is primarily used to build .NET applications, but can be used for other types of applications as well. From Windows Vista, MSBuild is distributed with Windows itself, making it a strong platform for implementing scripted application on non-developer PCs as well.

Before .NET 2.0, application were built by one or more of these strategies:

  • Using the build menu from inside Visual Studio
  • Using the devenv.exe process from the command line with some extra parameters
  • Using a third-party tool like NAnt (which MSBuild is based on)

The drawback with the first two strategies was that it was hard to script. The drawback with the third solution was that two build environments had to be held in sync and maintained. .NET 2.0 Visual Studio projects are now implemented in the MSBuild language, but MSBuild has no dependencies on Visual Studio itself. MSBuild can in theory be implemented in files with any extension but a number of formats seem to be the supported standard from Microsoft: csproj, vbproj, vcproj, vjsproj, proj, .targets. The first four are different types of project files for Visual Studio, while the last two are new extensions which are either written by hand or with a tool knowing the MSBuild syntax. A few tools exist for this purpose. My personal opinion is that building in xml editor in Visual Studio is quite good for this purpose. A repeating question among MSBuild developers is if you should extend the files generated by visual studio with new stuff or whether you should write your own containing your home-made MSBuild scripts. My personal opinion is to let Visual Studio generate its own projects (example: csproj files) and create your home-made scripts in a .proj file with the same name as the project. I usually start the .proj file by implementing the three targets: Clean, Build and Rebuild, which basically just calls the similar targets in the .csproj file. This way you avoid updating an auto-generated file which you don’t have control over.

An MSBuild file is implemented in XML. The root element of an MSBuild XML file will always be a project containing target elements. It is possible to run multiple targets in a MSBuild file. When the MSBuild script is started from the command line, it takes a build file as parameter as well as the names of the targets, which should be executed.

A target is implemented as a sequential list of tasks. The tasks are executed in the order in which they are specified beneath the target element. Both targets and tasks can be dependant on each other.

This is an example of a very simple build file to build a .NET project:

<?xml version="1.0" encoding="utf-8" ?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Target Name="Build">
    <Message Text="Building msbuildintro" />
    <MSBuild Projects="msbuildintro.csproj" Targets="Build" />
  </Target>
</Project>

The example defines a project with the MSBuild namespace. Using the namespace helps you develop the build file in Visual Studio using Intellisense. The build file contains a single target named Build. This target contains two tasks: Message and MSBuild. Message outputs a message to the console and is used primarily for debug purposes. MSBuild runs a configurable number of targets on another build file. Because the .csproj file is also implemented in MSBuild we are able to call targets in the build file from the example build file. In this case we call the target Build in the .csproj file. All projects generated by Visual Studio automatically implements the Clean, Build and Rebuild targets. These targets are actually executed when you select the similar commands in the Build menu from within Visual Studio.

Properties

To be able to parameterise a build script, MSBuild has implemented properties. A property is a simple key/value type, which can be used from multiple locations in the scripts. Let’s look at an example using properties:

<?xml version="1.0" encoding="utf-8" ?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <MyReleaseOutput>.\release</MyReleaseOutput>
  </PropertyGroup>
  <Target Name="Build">
    <Message Text="Building msbuildintro" />
    <MSBuild Projects="msbuildintro.csproj" Targets="Build" />
  </Target>
  <Target Name="Release" DependsOnTargets="Build">
    <MakeDir Directories="$(MyReleaseOutput)" />
    <Copy SourceFiles=".\bin\debug\msbuildintro.exe" DestinationFolder="$(MyReleaseOutput)"  />
  </Target>
</Project>

The example defines a property defined in a property group. Properties can be defined both outside and inside scope of a target. When a property is defined like in this example, the value of the property is assigned before executing the actual targets. In the example I define a property called MyReleaseOutput and add the value .\release. In this example I have added two targets as well: Build and Release. The Build target is similar to the one specified in the previous example, while the Release target is new. The Release target introduces a new attribute called DependsOnTargets, which is the way to define dependencies between targets in MSBuild. In this case we tell MSBuild to run the Build target before running the Release targets. If you run the Build target manually before running the Release target, the Build target is run only once.

The release target introduces two new tasks as well: MakeDir which (well you guessed it) creates a new directory and Copy, which copies on or more files from A to B. MakeDir contains a single attribute, defining the path of the new directory.
In this example that path is the value of the MyReleaseOutput property. Notice the use of the $(propertyname) syntax here. $() is used to reference properties in MSBuild. The copy task in our example points out a single file and the destination folder where this file should be copied to, when executing the Release target. The $(MyReleaseOutput) used is again replaced by the value of this property.

Items

The example above copied a single file from one directory to another. This can certainly be useful in many situations but sometimes this is simply not flexible enough. This is were items comes in. An item gives the possibility of creating dynamic lists of, for instance, file names. Let’s start by looking at an example:

<?xml version="1.0" encoding="utf-8" ?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <MyReleaseOutput>.\release</MyReleaseOutput>
  </PropertyGroup>
  <ItemGroup>
    <MyReleaseFiles Include=".\bin\debug\*.*" />
  </ItemGroup>
  <Target Name="Build">
    <Message Text="Building msbuildintro" />
    <MSBuild Projects="msbuildintro.csproj" Targets="Build" />
  </Target>
  <Target Name="Release" DependsOnTargets="Build">
    <MakeDir Directories="$(MyReleaseOutput)" />
    <Copy SourceFiles="@(MyReleaseFiles)" DestinationFolder="$(MyReleaseOutput)"  />
  </Target>
</Project>

We start by defining an ItemGroup outer scope of a target. This means that the content is calculated before actually running any targets. In this example I define an ItemGroup containing a single item called MyReleaseFiles. The item contains a single attribute called Include, which acts as a filter for the generated file list: in this case, all files beneath the bin\debug directory. I use this item in the copy task beneath the Release target to indicate which files should be copied when doing a release.

The Include filter decides which file to include. We also have the possibility to specify an Exclude filter. The following example shows how:

<?xml version="1.0" encoding="utf-8" ?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <MyReleaseOutput>.\release</MyReleaseOutput>
  </PropertyGroup>
  <ItemGroup>
    <MyReleaseFiles Include=".\bin\debug\*.*" Exclude=".\bin\debug\*vshost.exe" />
  </ItemGroup>
  <Target Name="Build">
    <Message Text="Building msbuildintro" />
    <MSBuild Projects="msbuildintro.csproj" Targets="Build" />
  </Target>
  <Target Name="Release" DependsOnTargets="Build">
    <MakeDir Directories="$(MyReleaseOutput)" />
    <Copy SourceFiles="@(MyReleaseFiles)" DestinationFolder="$(MyReleaseOutput)"  />
  </Target>
</Project>

I added an Exlude attribute to my MyReleaseFiles item. The exclude in this examples excludes all files beneath the bin\debug directory which end in vshost.exe. An item containing both Include and Exclude will be generated by taking all the files specified in the Include and subtracting the files specified in the Exlude.

The last two examples of using items are actually not that useful because the content for the MyReleaseFiles item is generated before running the actual targets. On a new checkout or after a clean, no files exist in the bin\debug directory meaning that the generated file list will therefore be completely empty. Bummer! Let us fix the example. We define a new item inside the scope of a target instead:

<?xml version="1.0" encoding="utf-8" ?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <MyReleaseOutput>.\release</MyReleaseOutput>
  </PropertyGroup>
  <Target Name="Build">
    <Message Text="Building msbuildintro" />
    <MSBuild Projects="msbuildintro.csproj" Targets="Build" />
  </Target>
  <Target Name="Release" DependsOnTargets="Build">
    <MakeDir Directories="$(MyReleaseOutput)" />
    <CreateItem Include=".\bin\debug\*.*" Exclude=".\bin\debug\*vshost.exe">
      <Output TaskParameter="Include" ItemName="MyReleaseFiles"/>
    </CreateItem>
    <Copy SourceFiles="@(MyReleaseFiles)" DestinationFolder="$(MyReleaseOutput)"  />
  </Target>
</Project>

I moved the MyReleaseOutput item inside the Release target. This is done using the CreateItem task. The CreateItem task creates a new item on the fly which means that the content is generated at the point in time when the CreateItem task is executed. Notice that the CreateItem task contains an Output element. The Output element is used in a lot of different places in MSBuild where a target is able to output some data. In this case is use the ItemName attribute to define the name from the previous example.

Anyone still reading? If you have read this far, you derserve a little prize:

dilbert2002444471010.gif

Conditions

Besides the CreateItem task in a previous example, our build scripts have been very static until now. This can be sufficient for a lot of projects but sometimes you need slightly more flexible build scripts. A feature for fulfilling this in MSBuild is called Conditions. A condition in MSBuild is not that different to a condition in other software languages. It is a possibile, for instance, to make more flexible structures to avoid running targets and/or tasks when certain conditions are met. You can define conditions on all targets and almost all tasks. Lets check out another example:

<?xml version="1.0" encoding="utf-8" ?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <MyReleaseOutput>.\release</MyReleaseOutput>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
  </PropertyGroup>
  <Target Name="Build">
    <Message Text="Building msbuildintro $(Configuration)" />
    <MSBuild Projects="msbuildintro.csproj" Targets="Build" />
  </Target>
  <Target Name="Release" DependsOnTargets="Build" Condition="$(Configuration) == 'Release'">
    <MakeDir Directories="$(MyReleaseOutput)" />
    <CreateItem Include=".\bin\$(Configuration)\*.*" Exclude=".\bin\$(Configuration)\*vshost.exe">
      <Output TaskParameter="Include" ItemName="MyReleaseFiles" />
    </CreateItem>
    <Copy SourceFiles="@(MyReleaseFiles)" DestinationFolder="$(MyReleaseOutput)" />
  </Target>
</Project>

I added a lot of new stuff here. But of course you are already quite an MSBuild expert, so I think you will manage. First of all, I have added a new property named Configuration. This property contains a condition attribute, which determines the value of the property at runtime. If the Configuration property has not been set upfront, the value of the attribute is set to Debug. Properties can be set upfront by using a special syntax on the command line:

Msbuild.exe build.proj /p:Configuration=Debug /t:release

More new stuff. I changed all references to the debug, with the value of the new Configuration property. This means that I am now able to run the script in both Debug and Release mode.

The last new addition is the condition attribute on the release target. This condition examines if the value of the Configuration property is Release and only allows execution of the Release target if this condition is true.

Frequently Used Tasks

CallTarget – Executes another target inside the current build file. Used where a target needs to call another target at a specific place inside the target itself. If the target were just dependant on the other target being executed, we would use the DependsOnTargets attribute instead.

Copy – We already saw this task in action. Copies one or more files from A to B.

CreateItem – Create dynamic items.

CreateProperty – Create dynamic properties.

Delete – Deletes on or more files.

Exec – Executes an external process. This is typically used to executed external tools, which did not implement MSBuild targets themself.

MakeDir – Creates one or more directories.

Message – Outputs a message to the console.

MSBuild – Executes one or more targets in an external MSBuild file.

RemoveDir – Removes one or more directories.

And there are a lot more.

Custom MSBuild Tasks

It is possible to write your own MSBuild tasks. This can be extremely useful if you want to integrate some of your own tools with MSBuild or if you need to do stuff which is not yet supported by MSBuild. The following example shows how to write a simple addition task:

using System;
using Microsoft.Build.Utilities;
using Microsoft.Build.Framework;
namespace MyTasks
{
  public class AddTask : Task
  {
    private int number1;
    [Required]
    public int Number1
    {
      get { return number1; }
      set { number1 = value; }
    }
    private int number2;
    [Required]
    public int Number2
    {
      get { return number2; }
      set { number2 = value; }
    }
    private int sum;
    [Output]
    public int Sum
    {
      get { return sum; }
      set { sum = value; }
    }
    public override bool Execute()
    {
      try
      {
        sum = number1 + number2;
      }
      catch (ArithmeticException e)
      {
        Console.WriteLine("Error occured during addition: {0}", e.Message);
        return false;
      }
      return true;
    }
  }
}

I start by defining the AddTask class which extends the Task class from the MSBuild API. By extending this task, I don’t need to worry about implementing conditions etc.
I defined two properties which act as input variables to the addition task: Number1 and Number2. Both properties are marked with the Required attribute which tells the script to fail if they are not specified. An output property is added as well. The value of this property will be available within the build script. Let’s see how to use this new and fancy task:

<?xml version="1.0" encoding="utf-8" ?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <UsingTask TaskName="MyTasks.AddTask" AssemblyFile=".\AddTask.dll"/>
  <Target Name="Addition">
    <AddTask Number1="10" Number2="12">
      <Output TaskParameter="Sum" PropertyName="CalculatedSum" />
    </AddTask>
    <Message Text="10 + 12 = $(CalculatedSum)" />
  </Target>
</Project>

TODO: Describe inline tasks (http://msdn.microsoft.com/en-us/library/dd722601.aspx).

Because my AddTask in an external task not built into the MSBuild framework, I use the UsingTask element to reference it. The name of the task as well as the assembly name is specified.

The Addition target uses the AddTask with the two Number properties as attributes. The Output element copies the result of the task to a property called CalculatedSum. This property is accessible in the Message task for output on the console.

You just implemented your first custom MSBuild task. Pretty easy, right?

Generic Targets

Once in a while a question pops up in different forums: How do I parameterize a common part of my script, making it possible to use it from different targets? This is a great question. We don’t want to have the same lines of code spread around our build script, making it longer than necessary and complex to maintain. MSBuild provides the CallTarget task, which executes another target inside the current build file. Unfortunately there is no way to parameterize the CallTarget task, making it unusable for anything other than simple situations where needed tasks are 100% identical.

Let’s look at and example where we have two targets with some identical tasks:

<?xml version="1.0" encoding="utf-8" ?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Target Name="Target1">
    <Message Text="Hello World from Target1" />
  </Target>
  <Target Name="Target2">
    <Message Text="Hello World from Target2" />
  </Target>
</Project>

In the example we define two targets: Target1 and Target2. You will probably notice that the targets look very similar. The only difference is the text inside the Message task. This is a simple example of the problem and of course changing the text in both message tasks would be fairly simple. But you probably understand the problem here: It would be nice to refactor the targets (let’s call it “Extract Target”), so that the Hello World text will only be specified once. First of all we need to move the common tasks to a new target:

<Target Name="PrintMessage">
  <Message Text="Hello World from X" />
</Target>

Note that the replaced part of the Text with the X. Now we need to call this target, making sure that X will be replaced with the correct string. For this purpose we use another task called MSBuild. The MSBuild task was originally produced to be able to call targets inside other MSBuild scripts. The great thing about the MSBuild task is that it has the capability to receive properties. In order to call our PrintMessage target and print the correct string, we parameterize the target like this:

<?xml version="1.0" encoding="utf-8" ?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Target Name="Target1">
    <MSBuild Projects="$(MSBuildProjectFile)" Targets="PrintMessage" Properties="Caller=Target1"/>
  </Target>
  <Target Name="Target2">
    <MSBuild Projects="$(MSBuildProjectFile)" Targets="PrintMessage" Properties="Caller=Target2"/>
  </Target>
  <Target Name="PrintMessage">
    <Message Text="Hello World from $(Caller)" />
  </Target>
</Project>

We use the MSBuild tasks in both Target1 and Target2. The $(MSBuildProjectFile) is a built-in property in MSBuild, which returns the filename of the current build file. What we do here is that we call the PrintMessage task on this. The properties attribute specify a single property named Caller. Multiple properties can be specified inside this attribute by separating them with a semicolon. In the PrintMessage task we simply print the message with the Caller property specified inside the Text attribute.

Property functions

TODO

Links

The MSBuild documentation is actually quite good and a must for all serious MSBuild developers:http://msdn2.microsoft.com/en-us/library/wea2sca5(VS.80).aspx

A lot of different tools for handling MSBuild files exist. I haven’t been able to find a tool that makes it possible to run build scripts from within Visual Studio. You could start by installing the MSBuildShellExtension tool from: MSBuildShellExtension.

Besides the build in tasks in MSBuild, there is a great community project, implementing a lot of nice tasks not implemented by Microsoft. Targets for search and replace, zipping, sending out mails, modifying subversion etc., can be found here: http://msbuildtasks.tigris.org/

Share this post:

Share to Google Plus

It’s been 7 months since the last post in my YSlow series. So why did I stop blogging about performance optimization? Well actually there are two answers to that question. First on is my passion for unit-testing which I started blogging about at pretty much that time. Secondly I have to admit, that I didn’t know what to write about YSlow rule #13 – Remove Duplicate Scripts.

So what’s the problem with including the same JavaScript twice (or more)? When the browser reaches a script import it makes a HTTP request for that script. Not all browsers are smart enough to catch this mistake. Even with modern and fast internet connections, making a lot of requests, slow down the experience of your website. If you have your caching strategy under control the duplicate request shouldn’t be much of a problem but if not, the remote request is actually made multiple times. I typically see two different patterns when people by accident include the same script twice.

Pattern 1: Including scripts i both layout/master page and partial views

Partial views in ASP.NET MVC are a great way to extract common reusable controls into a single file. A partial view has the possibility to load external JavaScript files as well. A common mistake by web developers, is to include a reference to the same script in both the layout/master page-file as well as a partial view. I haven’t really found a great solution to catch this mistake, other than running YSlow on your page. If you read this and know a solution to this problem, please let me know in the comments.

Pattern 2: Including both minified and unminified version of a script

I’ve seen multiple websites doing something like this:


<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

You typically see this pattern from webdev-cowboys needing to track down some bug in the JavaScript by adding the unminified version of jQuery to be able to debug it. When the bug is fixed, they forget to remove the newly added reference. The mistake won’t show itself in the browser, because the last imported script override the first. I was a bit disapointed by the new bundling support in ASP.NET MVC 4 when I found out, that the bundler always adds the minified version if available. Making it chose the full version in Debug configuration and the minified version in Release configuration would have been the optimal choice for me.

I’m working to catch this bug in my upcoming website validator HippoValidator.com.

Share this post:

Share to Google Plus

I sometimes find myself doing extension methods for the HtmlHelper class in ASP.NET MVC. I like HtmlHelper but don’t really dig when the methods generate HTML. This is what partial views are for, right? I usually add small utility methods related to a single view on the view model, but when dealing with shared methods, the HtmlHelper seems like the best choice.

Extension methods in general are pretty easy to unit-test, due to the fact that they are just static methods. But extension methods on HtmlHelper have all kinds of information available through the “this HtmlHelper”-parameter, which can make these methods extremely hard to test. This is the helper method I use to create a new instance of the HtmlHelper class:

public HtmlHelper<T> CreateHtmlHelper<T>(ViewDataDictionary viewData)
{
    var cc = new Mock<ControllerContext>(
        new Mock<HttpContextBase>().Object,
        new RouteData(),
        new Mock<ControllerBase>().Object);

    var mockViewContext = new Mock<ViewContext>(
        cc.Object,
        new Mock<IView>().Object,
        viewData,
        new TempDataDictionary(),
        TextWriter.Null);

    var mockViewDataContainer = new Mock<IViewDataContainer>();

    mockViewDataContainer.Setup(v => v.ViewData).Returns(viewData);

    return new HtmlHelper<T>(
        mockViewContext.Object, mockViewDataContainer.Object);
}

The method uses Moq to create mock objects for various ASP.NET MVC classes, but can easily be ported to Rhino Mocks or other mocking frameworks. Testing extension methods on HtmlHelper is now piece of pie. In the following example I test an imaginary extension method named SplitModel using the CreateHtmlHelper-method:

[Test]
public void CanSplitString()
{
    // Arrange
    var htmlHelper =
        CreateHtmlHelper<string>(
            new ViewDataDictionary("Hello World"));

    // Act
    string[] result = htmlHelper.SplitModel();

    // Assert
    Assert.That(result.Length, Is.EqualTo(2));
}

Share this post:

Share to Google Plus

This is the second and last part of my blog post titled 10 Tips to Optimize Your Time. If you haven’t read part 1, go ahead!

Only plan one visit every weekend if possible

We have a large family.  Both my wife and I are children of divorced parents and therefore have four sets of parents/grandparents.  The thing is, those grandparents want to see their grandson (and us) ALL the time.  Keeping grandparents in restraints has been a major issue for us.  We try to see family on the weekends and always only plan one of the days.  This gives us the other day to concentrate on our son and when he’s tucked in, coding time starts!

Pay someone to do tedious work

This is something that I’m not good at, but I keep trying to find new ways of outsourcing all of those tedious tasks.  Why not pay someone to clean your house?  Don’t wash the car yourself.  The car wash is a great alternative and you can catch up on your e-mail or Twitter while the old, dusty car gets a makeover.  Admittedly, we (maybe it’s I) drink a lot of soda.  Nothing sucks more than putting all of those empty cans in the can recycler.  I’m planning to make a deal with one of the kids on the street, that he will get the bottle deposit if he comes by and empties my shed for empty bottles and cans once in a while.  The point here is that people in the IT business make enough money to pay someone to do all of those tasks that you don’t like.  Just do it!

Buy work you can’t do yourself

It’s amazing what people do for money nowadays.  Before having my son, I would gladly sit down and scan hundreds of old photos, which takes a long time.  These days, I just send them for scanning in Morocco.  Yes this isn’t free, but doing manual work like that is time consuming and boring.  Last year, I started experimenting with buying help on fiverr.com.  The first couple of months weren’t a great success, but after spending a few more fiverrs, I ended up knowing some pretty talented people, willing to do stuff for $5.  I use fiverr for proof reading, graphics, copy-paste work and other tasks, which I can’t do myself or that I don’t bother to learn.

Don’t do stuff which never leaves your machine

Doing websites or code in general, which only lives on your machine, is fun if you want to learn something.  Doing stuff that other people see either through a website or GitHub is more fun.  I never write code that doesn’t end up on the internet somehow.  I have a principle that everything I do should be monetizable somehow.  I always have ads on my blogs and try monetizing everything from .NET assemblies to Chrome plugins.  I don’t even earn 1 % of my day-job paycheck each month, but the feeling of earning enough to cover your expenses on fiverr and hosting is enough to drive me. The point here is, that doing personal stuff quickly becomes a time consumer, cause you don’t get any feedback and you could have used your time on something else.

Buy gifts for your wife/girlfriend

If your better half doesn’t work in IT, he/she probably doesn’t understand that your job can also be your hobby.  My wife has become very understanding over the years.  A technique you can use, if you aren’t as lucky as me, is to buy time consuming gifts for the other part.  The Sex and the City boxset is a great example of how to make your wife happy for several hours.  Do not, and I must stress, DO NOT give her the impression that you want to see the damn thing with her though :) Make sure to spend time with your other half, but make an arrangement for one or two nights a week, where you can get into the zone without being interrupted.

Happy coding!

Share this post:

Share to Google Plus

A couple of people have asked me how I find time to do all of my hobby projects while having a house, a wife, a son, family and friends all at the same time.  The answers I gave inspired me to write this blog post.  While I’m extremely bad at focusing on a single coding projects, I’ve done a lot to optimize the time I actually have for all my experimental coding.  This the the following blog post is an attempt to explain some of the things I do to find some extra hours.

Minimize the time you talk on the phone

Face it!  Nobody needs to talk to their mom every day.  My wife thinks she does, but when I overhear their conversations, it’s always superficial small talk.  I talk to my parents once a week on a fixed time.  Agreeing on the time of the call makes it possible to plan your night and not feel frustrated when your mom calls you while you’re “in the zone” to tell you about her yoga progress.  Also, turning on the phone’s silent option keeps you from talking to sales people and other annoying disturbances.  If you’re the type of person who needs to talk to your friends all the time, meet up with them once in a while instead of calling them each night.  I chat a lot with my more neardy friends, which works great because I can code on my other screen in my dual screen setup while chatting on the other.

No weekly scheduled events

I never accept weekly scheduled events.  When someone asks me if I want to play badminton with them every Tuesday and Thursday night, I simply say no.  Playing once in a while is fun and you should definitely do it.  However, promising your time two nights a week is a major timer spender. The point here is only do it if you’re really into it!

Don’t watch live TV

A couple of years ago I watched a lot of live TV.  A LOT!  My wife and I watched everything from the news to programs titled, “100 Greatest Hollywood Screw-Ups”.  After we had our son, we canceled the cable TV and now only have something like 2 watchable channels.  This is probably the best decision we’ve made in years.  We still watch movies and shows, but always on DVD or web content.  This means that we can sit down and watch five episodes of a show in one night without being bothered by commercials and other time consuming stuff.

Optimize your shopping

When we lived in an apartment in the city 4 years ago, we discussed what we would have for dinner every day and went to the food store to buy it.  Doing weekly meal planning, gave us something like an hour extra everyday but on Monday when we do all of our shopping for the week.  Shopping for the week doesn’t take much longer than shopping for 1 or 2 days.  Also, I buy must of my stuff online from hardware to clothes.

Do stuff with your kids

I’ve heard a lot of people with kids complaining about too few hours to code.  These people typically wait to do stuff like cleaning and shopping until the kids are asleep and for that reason, they don’t starts coding until 10 in the evening.  While we love to spend time with our son, we also treasure the time when he is tucked in.  People are too afraid to admit this, but we all need time for ourselves.  We do a lot of stuff at home with our son and he also joins one of use shopping each week.  He loves it!

In the next post I reveal the final 5 tips to optimize your time.

Share this post:

Share to Google Plus

I don’t think I ever got to announcing NuGetFeed.org. NuGet Feed is a great extension to NuGet, which most .NET developers should know by now.  With NuGetFeed.org you will be able to follow your favorite NuGet package releases with a RSS reader of your choice.  Also, you will find a couple of plugins at the main NuGetFeed.org site.  One is for Google Chrome, which decorates the NuGet.org site with RSS links (it should really have been there from the beginning).  Another plugin is for Visual Studio, which lets you export all of your referenced NuGet packages to NuGetFeed.org.

I wanted to tell you the story behind NuGetFeed.org, because it has been an interesting experience for me.  About four months ago, I spoke with two of my co-workers, Jesper and Christian, about the lack of possibilities of getting notified, when someone releases a new version of their NuGet package.  You have to manually open the NuGet Package Manager and search for updates, which I don’t do that often.  I must have done a good job convincing them, because we quickly agreed to do something about the problem.  We could have joined the NuGet team, made pull requests or similar, but we decided to try another approach.

While Jesper started working on the graphics for the NuGetFeed.org website, Christian looked into doing the actual RSS feeds through the NuGet API.  I decided to use my existing knowledge about developing extensions for Google Chrome to make a kick-ass chrome plugin with links to NuGetFeed.org (pretty much a greasemonkey script) that would enhance visitors’ experience at the NuGet.org site.  Also, one of the initial ideas was to develop an add-in for Visual Studio, making it possible to export all of a project’s references to NuGetFeed.org.

We chose ASP.NET MVC for developing the website and Twitter Bootstrap for most of the UI.  Both frameworks totally kicks ass and allowed us to develop something that looks pretty nice, in only a short period of time.  For hosting, we decided to go with AppHarbor, the Danish start-up which makes Azure look like mainframe-programming.  AppHarbor supports Git, which is our preferred VCS at the moment.  Also, a single instance at AppHarbor is provided free of charge, as well as free MongoDB hosting at MongoHQ.

After a week or so, the main service and plugins started to take shape.  Remember, this was done in out spare time.  I ended up using too much time on the Visual Studio add-in and, honestly, I was very disappointed with how difficult it was.  There’s a new and shiny Visual Studio SDK using MEF, but I couldn’t find documentation on the extension points we needed for our add-in.  Therefore, I ended up developing a VSPackage, which is the old way of doing things.  The whole thing felt a lot like coding COM, which I’d forgot all about years ago.  I think the reason for the lack of great add-ins for Visual Studio is caused by old API’s which are difficult to develop against.  I really hope that Microsoft will improve the SDK over time, letting me port my nasty VSPackage to something sweeter.

Anyway, a week or so after the first night of coding, the first version of both the main site and the Chrome plugin were finished. We went live and got a few visits per day.  A couple of days after, the Visual Studio add-in went live on the Visual Studio Gallery and visits suddenly went through the roof.  I was amazed to see the impact in Analytics the day after the Visual Studio add-in release. People must be using the gallery after all.  Also, all new add-ins were published to the MSDN News Twitter account, which have almost 6,000 followers now.

A few days later, we were lucky enough to get mentioned on Chris Alcock’s blog The Morning Brew (TMB).  For those of you who don’t know TMB, it’s a great developer blog with a daily post summarizing yesterday’s most important news.  Again, we reached an all time record on the visit count on NuGetFeed.org.

NuGetFeed.org has been running for almost 6 months now and I’m happy to see that someone is using our service every day.

Share this post:

Share to Google Plus

Let’s face it, it doesn’t make sense to keep and maintain unit tests not executed on a continuous basis. In my previous post, I looked at a unit test framework for JavaScript called QUnit. While commonly used unit test runners like NUnit, JUnit and MSTest have great support on TeamCity, there is no build-in support for executing QUnit tests (yet). During my recent adventures with QUnit, I wanted to be able to execute my new and shiny QUnit-tests on TeamCity. It turned out that it was almost as easy as integrating the supported framework.

Red Badger implemented a nice NuGet package called QUnitTeamCityDriver. The package consists of two JavaScript-files: QUnitTeamCityDriver.js and QUnitTeamCityDriver.phantom.js. The first file contains logic to output results from running the QUnit tests to a format understandable by TeamCity. This file should be referenced just after the reference to QUnit.js in your tests. The second file is used on TeamCity to integrate with PhantomJS. PhantomJS is a windowless browser with a nice JavaScript API to control it all.

Before we dig into the configuration on TeamCity, we need to specify a HTML-container referencing all the js-files containing unit-tests. This is probably the biggest flaw right now because ReSharper does a nice job avoiding this container. What you need is a HTML-file looking that looks like this:

<!DOCTYPE html>
<html>
 <head>
 <title>JavaScript Tests</title>
 <link rel="stylesheet" href="qunit.css" />
 <script type="text/javascript" src="jquery-1.7.1.js"></script>
 <script type="text/javascript" src="qunit.js"></script>
 <script type="text/javascript" src="QUnitTeamCityDriver.js"></script>
</head>
 <body>
 <h1 id="qunit-header">QUnit example</h1>
 <h2 id="qunit-banner"></h2>
 <div id="qunit-testrunner-toolbar"></div>
 <h2 id="qunit-userAgent"></h2>
 <ol id="qunit-tests"></ol>
 <div id="qunit-fixture">test markup, will be hidden</div>
 <script type="text/javascript" src="tests.js"></script>
</body>
</html>

The file contains some basic HTML elements and references to jQuery, QUnit and QUnitTeamCityDriver. At the bottom, I reference the tests.js-file which I implemented in my previous blog post. So what’s the main problem with this file? Each time a new js-file containing test are added to our project, we need to manually add a reference to this file at the bottom. I haven’t found a nicer solution to this problem, so until a better approach emerges, I’ll continue using this file.

In order to get the tests running on TeamCity, you need to download and extract PhantomJS on TeamCity. Unfortunately, PhantomJS doesn’t come as a NuGet package, which is why you need to do this manually. Place PhantomJS in a folder like c:\phantomjs. Add a new build step just after you run your unit tests called, “Run JS tests”, or another name of your choice. Your settings should look like this:

In the text area to the right of “Command parameters”, I reference two files. The first file is the QUnitTeamCityDriver.phantom.js-file which came with the QUnitTeamCityDriver NuGet-package. The second is a reference to the html-file created previously in this blog post. Save the build-step and Run the build. If everything looks green, you will be able to see the QUnit-tests alongside your NUnit-tests in the “Test” tab under each build. Simple and nicely integrated!

Share this post:

Share to Google Plus

One of the areas that I never really dug into is unit testing JavaScript code. I have a background as a backend developer and for me, NUnit has been sufficient for years. During the last couple of years, I started implementing a few websites and also switched my working place from Trifork to eBay so I could expand my web knowledge. The switch opened up an entire new world for me, the world of JavaScript. I had previously written some JavaScript before starting at eBay, but I never really had the time to sit down and fully understand the language. Therefore, I never really used the full potential of JavaScript, but I still wrote a lot of the application on the server (in c#). That’s why I decided to look at unit-testing JavaScript.

Some developers argue that JavaScript shouldn’t be unit-tested because it is part of the UI. These people typically use something like Selenium to test the client, but in my experience, Selenium tests are like integration-tests: hard to write and maintain. C’mon guys, this is one of the reasons why we write unit-tests of the server, to be able to test single units and ease the debugging process when bugs are introduced. Unit-testing the UI becomes essential in today’s thick HTML5 applications.

For my JavaScript unit test experiment, I needed a framework and while there are a lot to choose from, I wanted to try out QUnit. QUnit is from the guys who brought you jQuery and is actually used to test jQuery itself. I simply can’t say it enough, but I LOVE jQuery. For this one reason I decided to try and see if I would love QUnit as well.

QUnit turned out to be pretty straight forward. Let’s look at a simple test. Save the following JavaScript to a file called tests.js (or a name of your choice):

test("Can Add Two Strings", function () {
  // Arrange
  var str1 = "Hello";
  var str2 = "World";

  // Act
  var result = str1 + " " + str2;

  // Assert
  equal(result, "Hello World");
});

Admittedly, this is probably not the best test, but it illustrates the basic features of QUnit. Every test is specified by calling a test-method from QUnit with a name of the test and a callback containing the actual test. Like NUnit, the asserts are specified by calling methods. equal matches the Assert.AreEqual method in NUnit and there are similar methods like ok for IsTrue and so on. I really like the simple yet strong-type way of writing the test method. No method name prefixes. No attributes. Also, the QUnit guys choose the correct order of the parameters for the equal method. In NUnit, the expected value goes first, which always confused me.

Unit tests exist to be run. So, what do we do to execute the test above? QUnit supplies us with a style sheet and some JavaScript files, which makes the execution pretty straightforward. An even better solution is to use the QUnit-runner in ReSharper (ReSharper 6.x only, sorry Stone Age dudes). In order for ReSharper to know that the tests.js file contains test-methods, you need to add a script reference on the top of the js-file:

/// <reference path="CodeUnderTest.js"/>

The CodeUnderTest.js-filename tells ReSharper that the file contains unit-tests. The file-path is there for information only and should not exist on the file system. In order to get IntelliSense while writing your tests, it’s a good idea to add a reference to the qunit.js-file as well. This reference is not mandatory though, because ReSharper comes bundled with its own version of QUnit. Well now for the good part: Look Ma, my QUnit test is runnable through ReSharper:

Working with QUnit has been like a dream come true. I wouldn’t have guessed that testing JavaScript could be that easy. There’s no excuse not to start implementing unit-tests of JavaScript!

Share this post:

Share to Google Plus

During the last 6 years, I’ve preached unit testing to my colleagues and people attending my test-driven development courses. The set of tools I’ve used for this purpose have been stable, for the most part. This blog post is an attempt to create a snapshot of the tools and frameworks I’m using right now.

Unit-Test Framework and Runner

NUnit has been my preferred tool to execute tests. I did some fooling around with MSTest a couple of years ago, but unlike NUnit, you need to install Visual Studio on the build server to run the tests. The syntax is strange and the test runner for Visual studio sucks. I also looked at xUnit.net which is cool, but the limited support for ReSharper at the time kept me from switching. Let’s admit it: NUnit is the defacto standard these days. The support and community around NUnit is so great, that I will probably not switch anytime soon. I really hope that NUnit looks into the cool things happening in xUnit.net. I also hope that build servers, Visual Studio extensions and other tools integrating unit test frameworks will do a better job of integrating xUnit.net.

Mocking Framework

Rhino Mocks has been my favorite mocking framework for years. I tried Moq two years ago, but quickly switched back to Rhino Mocks due to the strange errors I was receiving from Moq. Last year, I tried Moq again and liked it so much that this is now my favorite mocking framework. I also tried FakeItEasy, but I didn’t really think that it brought anything new to the table.

Buildserver

You might be thinking something like, “Whuuut? Why does the unit-test freak suddenly mention anything about build servers, in the middle of a blog post about unit-testing tools?” Well, without a build server to execute all of your unit-tests, you probably shouldn’t write them in the first place. The build server is a perfect place for conducting regression testing. I typically run all of my unit-tests before committing code, letting the build server run the heavy database-dependent integration-tests. During the last 10 years as a professional software developer, I’ve tried practically all major build servers from homemade bat-scripts over CruiseControl and CruiseControl.NET to TeamCity. TeamCity is my current favorite, with great support for .NET/C#.

Helpers

Also, last year I started using AutoFixture, which is a cool library used to automate the creation of test values. I blogged about AutoFixture a couple of times.

Shouldly is a nice set of extension methods for NUnit if you do not like the Assert.* syntax. I previously blogged about Shouldly as well.

Any opinions on missing frameworks?

Share this post:

Share to Google Plus

I found myself repeatable adding the same Live Template to R# over and over again: The unit-test template. This template adds a method with a method name starting with Can as well as the arrange/act/assert comments, which I’m pretty much in love with. Each time I re-install my old machine or simply get a new one, this is the first template I import. The other day I wanted to share this template with my team-members, but wanted to do something else than just exporting the template and sharing it by mail. It turns out that R# have a great feature to share stuff between team members. I already use this to share R# settings, as well as StyleCop settings (which is available as a R# plugin). The sharing feature also supports live templates, which I was not aware of.

To share your live templates with your team members, navigate to the Templates Explorer in the ReSharper menu inside Visual Studio. On my machine, the This computer layer was selected as shown here:

Select the test-template and export it by clicking the Export-icon. Change the layer to Solution ‘Your SLN’ team-shared and import the file. Close Visual Studio to make sure that the DotSettings file is updated. If not already added, add the file named <your sln>.DotSettings to source control and the live template is shared with your team members, the next time they get that file. Simple and neat, right?

Share this post:

Share to Google Plus