Building your c# Solution with MSBuild, the easy way

Everything in this post should be obvious to any c# developer, but sadly for whatever reason, people just don’t seem to know these things.

The key to improving your knowledge, and to prevent asking stupid questions on sites like StackOverflow, is this. The first thing you should do after installing Visual Studio 2012, is install the documentation. The full documentation. It’s not part of the download, but if you search around, you can find a free ISO available from Microsoft, which installs all the documentation. I’m not providing a link to it. Instead I’ll quote the wise words of Raymond Chen, who tells us time and time again: Don’t be helpless.

Again, my source archive file, is a working example of everything explained here.

First of all (after closing Visual Studio), before I build anything from the command-line, I like to clean my projects, removing all intermediate and compiled files. That is, delete all bin and obj directories and so on. If you’re already saying “I can’t do that. My projects won’t build if I delete the bin directories, because it will lose references” then I must inform you that you don’t know how to set up your solutions properly. Everything in the bin directories should be generated, and that may often mean adding directories especially for your references.

After cleaning my projects, I go one step further, and terminate any existing MSBuild instances. You can do that by using a little program from SysInternals, but I prefer to call my own little utility from my batch files, so here is the source code for it:

How to kill processes with c#

  1. using System;
  2. using System.Diagnostics;
  3. using System.Threading.Tasks;
  5. namespace KillProcesses
  6. {
  7.     /// <summary>I wrote this because my Visual Studio 2012 installation has a habit of leaving
  8.     /// orphaned MSBuild processes around with file locks, and then it fails to build.</summary>
  9.     /// <remarks>Generally, this does not solve the problem, and VS needs a restart anyway, but
  10.     /// it is useful to run from a build script before cleanup, after closing Visual Studio.</remarks>
  11.     class Program
  12.     {
  13.         static void Main()
  14.         {
  15.             var args = Environment.GetCommandLineArgs();
  17.             if (args.Length != 2)
  18.                 ShowUsage();
  20.             var processes = Process.GetProcessesByName(args[1]);
  22.             if (processes.Length > 0)
  23.             {
  24.                 Parallel.ForEach(processes, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, p =>
  25.                 {
  26.                     try
  27.                     {
  28.                         p.Kill();
  29.                         Console.WriteLine(“Successfully killed process ‘{0}’ with PID {1}”, p.ProcessName, p.Id);
  30.                     }
  31.                     catch (Exception ex)
  32.                     {
  33.                         Console.WriteLine(“Unable to kill process ‘{0}’ with PID {1}. {2}”, p.ProcessName, p.Id, ex.Message);
  34.                     }
  35.                 });
  36.             }
  37.             else
  38.             {
  39.                 Console.WriteLine(“No processes named ‘{0}’ were found.”, args[1]);
  40.             }
  41.         }
  43.         private static void ShowUsage()
  44.         {
  45.             Console.WriteLine(“KillProcesses [ProcessName]”);
  46.             Console.WriteLine(“Kill processes by name.”);
  47.             Environment.Exit(0);
  48.         }
  49.     }
  50. }

That is, the command in my cleanup batch file is simply:

KillProcesses MSBuild

Obviously some common sense is assumed here. You don’t want to go and run that command while other builds are in progress, since it will speedily kill them all simultaneously in parallel.

Then, it’s just a matter of building the solution. And here’s the key: Every solution file is a valid MSBuild project. You don’t need to build your script by hand – just set up your solution properly in the IDE, making sure it can build in both Debug and Release configurations, and you’re good to go.

Further, it’s not at all difficult to get the environment right to be able to call your relevant dev tools. Every version of Visual Studio for as far back as I can remember has set everything up for you. To see how, look no further than the “Visual Studio Command Prompt” shortcut it creates for you in the Start menu. (There is always an environment variable that points to the current dev tools directory, and a batch file relevant to your environment. In my case that is %VS110COMNTOOLS% and the 32bit batch file.)

Thus my build batch file, in the same directory as my solution file, contains just this:

CALL “%VS110COMNTOOLS%\vsvars32.bat”
msbuild RomyView.sln /t:Rebuild /m /nologo /v:m /p:Configuration=Release

To clarify my arrogant opinion that everything in the bin directory should be generated, i.e. It’s not a place to put DLLs that you reference. This may seem like an odd statement – it is after all the lazy way that many a .Net developer works. To my mind, the most sensible approach to references is to place them in a project directory such that the path is relative to your project. This way, new developers joining your organization don’t have to fight for hours, or maybe days, with source control, before their solutions can even build. And you don’t find yourself in a situation years down the line with mysterious DLLs whose purpose nobody remembers in your bin directory, tied to a particular framework version, and without which your software falls over crying for mommy.


About Jerome

I am a senior C# developer in Johannesburg, South Africa. I am also a recovering addict, who spent nearly eight years using methamphetamine. I write on my recovery blog about my lessons learned and sometimes give advice to others who have made similar mistakes, often from my viewpoint as an atheist, and I also write some C# programming articles on my programming blog.
This entry was posted in Programming and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s