04 Oct 2012

MSBuild: add git commit hash to AssemblyInfo

The goal is to automatically generate the AssemblyInfo.cs file every time I build my project. I also want to add the current git commit hash as the last part of the assembly version number.

If you spend some time googling around, you’ll find that there are various ways to accomplish this. This is how I do it, step by step:

Install MSBuild Community Tasks

Using nuget this is extremely simple. Open the nuget console and type:

Install-Package MSBuildTasks

Edit your project file and add a new target

<PropertyGroup>
    <Major>1</Major>
    <Minor>0</Minor>
    <Build>0</Build>
    <Revision>0</Revision>
</PropertyGroup>

<Target Name="Version">
    <GitVersion LocalPath="$(MSBuildProjectDirectory)">
        <Output TaskParameter="CommitHash" PropertyName="Revision" />
    </GitVersion>
    <AssemblyInfo
        CodeLanguage="CS"
        OutputFile="Properties\AssemblyInfo.cs"
        AssemblyTitle="YourAssmblyName"
        AssemblyDescription="Description"
        AssemblyCompany=""
        AssemblyProduct="Productname"
        AssemblyCopyright="Copyright"
        ComVisible="false"
        CLSCompliant="true"
        AssemblyInformationalVersion="$(Major).$(Minor).$(Build).$(Revision)"
        AssemblyVersion="$(Major).$(Minor).$(Build)"
        AssemblyFileVersion="$(Major).$(Minor).$(Build)" />
</Target>

Update the main Project tag to execute the new Version target before Build.

<Project ToolsVersion="4.0" DefaultTargets="Version;Build"
    xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

Note that the $(Revision) property, which holds the git commit hash value, is not included in the regular AssemblyVersion or AssemblyFileVersion attributes. The reason is because .NET expects here a number (UInt16) and if we put here a hash it will fail to compile. We use instead the attribute AssemblyInformationalVersion which allows us to put anything we want.

Display the full version in your application

Having access to the exact commit your application is running is invaluable. I display the full version including the commit hash on the About form of my applications. Also, it’s included in the automatic error reports.

Application.ProductVersion.ToString();