Friday, November 11, 2016

Running Web.Config Transforms on Build

Web application deployment typically involves transforming the build depending on the build target.  Typically Visual Studio only runs the standard transforms on publish of the web application (publish profiles).  This can be confusing and frustrating as many expect a different behavior.  It seems intuitive that transforms would be ran on build. 

The following is a simple recipe you can follow to ensure that MS Build will run the correct build target transforms on build.  In the steps below you'll notice it is suggested that the Web.Config in the project directory be removed from source control.  This is because each time you change configuration and build, the web config will be updated.   

  1. In Visual Studio, from the Build menu, open Configuration Manager.  At this point you can add build targets for each one of your environments.



Do what make sense, but a typical set of build targets may look something like this :
  • Debug
  • Staging
  • Pre-Production
  • Release

  1. In your Visual Studio Project, add a folder called Config 
    1. Copy your current Web.Config and its children Web.Debug.config & Web.Release.Config into the new Config folder.  Delete the old files and remove them from source control.
    2. Add a new file Web.($BuildTarget).config named to match your additional build targets by copying one of the existing transforms.


  1. Add a pre-build step in Visual Studio under Project > Properties > Build Events where project folder refers to the name of your project folder where the original web configs existed.
    1. xcopy "$(ProjectDir)Config\*.*" "$(SolutionDir)\ProjectFolder" /Y
  2. Unload your Visual Studio Project and edit the .csproj files xml.
    1. Add an AfterBuild target to the very bottom of the file right before the closing </Project> tag

<Target Name="AfterBuild" Condition="'$(PublishProfileName)' == '' And '$(WebPublishProfileFile)' == ''"> 
    <TransformXml Source="Web.config" Transform="Web.$(Configuration).config" Destination="Web.config" />
</Target>

Now each time a build is triggered, the web-config will be properly transformed.