Saturday, January 5, 2013

Build on Save and Notify using Powershell

I'm a big fan of dnrTV, a video how-to for various technologies and techniques in software development. The last few shows featured Jean Paul Boodhoo doing a Software Craftsmanship BootCamp. One of the things JP did was to setup Rake tasks, one of which was to compile a solution on save and report build failures using Growl For Windows. That looked really interesting and useful for my particular situation.

At my job, we have separated our application into many .NET solutions and projects with dependencies on each other. Although we have one overarching solution that encompasses all of the projects, most of us spend a majority of our time in the web and tasks solutions. Most of the time, changing code inside of these solutions doesn't affect other solutions. On those occasions that is does, we have run into broken builds and other issues that we don't immediately pick up on. I wanted to try and find a better way to solve this problem.

I want to learn more about it Powershell. People that I respect in the software craftsmanship industry have extolled Powershell's virtues. I wanted to learn more about it, but I needed something to code up in it - this was my chance! If JP can do it using Rake, why can't I do this in Powershell?

I remembered that there was a FileSystemWatcher class in .NET and I figured that there was some implementation of this class in Powershell. Luckily, there was such an example script on Technet (thanks to Grant Ward for sharing it!) to start with. Through some trial and error and a lot of separate searches for different pieces of code, I think I've come up with a good start (see the Gist below).

The script was built for c# projects but you could easily change that. Any time a .cs file is changed, MSBuild compiles our master solution. The only time the automated build doesn't run is if a git operation is underway changing files. If any of you run SVN or Mercurial and want to add conditions for them, I'd be much appreciative! I found that if I didn't have this code in, the build would continuously fail until the git operation was complete. I also discovered that FileSystemWatcher has a habit of running twice for a single save of a file. I added code so that a build would happen if a different file was changed or some time had elapsed between the last save. That seemed to fix the problem.

Here are the steps to run it:
  • Install Growl For Windows
  • Change the items in the squiggly brackets to fit your situation
  • You can run the script from the command line or by making a shortcut like this:

    %SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe c:\{path to script}\BuildNotify.ps1
My preferred method is make a shortcut, but I also run the shortcut in Task Scheduler when I log in. I hope this works for you - let me know how you do with it!