1. Skip to navigation
  2. Skip to content

Fun With MsBuild

Lately I’ve been automating a client’s build process using MsBuild. Their original scripts were written using NAnt, and just consisted of the fundamentals of compile, docs, code analysis, etc… This is a .Net project as I’m sure you’ve guessed. Although I’ve played around with MsBuild in the past, this is the first time I’ve completely automated a build system and integrated it into a Continuous Integration process. It’s been a fun project, but there are some real gotchas when working with MsBuild, and the availability of good documentation out there is pretty slim. This means a lot of trial and error, with lots of tasks thrown in for good measure.

One thing that got me early on is the fact that ItemGroup gets evaluated at the time the file is read not when the property is referenced. For instance, let’s say we have a Target that looks something like the following:



    



    

This Target simply copies files from a source location to a release location. This works fine if at the time the script is run (at the start, when the script is first evaluated) files exist in the directory structure specified. But lets say instead that our Target looked something like:



    



    
    
    
    

The above code will not work, because at the the time the script is evaluated the OutputFiles do not exist since they are created by the MsBuild task. This seems like a bug to me, but apparently this is by design. Often people not realizing this problem will experience a situation where it works intermittently because in some cases they may be re-running the task and the files are still there from a prior run.

To get around this problem we use the CreateItem task. CreateItem allows us to Create an ItemGroup on the fly as part of our Target process. For instance, using the CreateItem task we can rewrite the above so that it actually works consistently.



    
    
    
    
    
        
    
    

Problem solved! Working with MsBuild is a lot of fun; it is a very flexible environment, but as you can tell there are some things to be watchful about.