19 March 2014

Visual Studio Web.config Transforms on build

Web.config Transforms

Requires Visual Studio Pro or better.

Normally web.config transforms only happen on Publish, not build. To do config transforms on build:

  1. In configuration manager add a build for the project for each config e.g. Release, Debug, Debug.[developer initials]
  2. Copy web.config to web.Base.config (this will become the basis for the transform)
  3. Unload WebProject (right click) and edit project file: 
  4. Edit web.config includers for each file like:<Content Include="Web.config" />
    <Content Include="Web.Base.Debug.config">
    <DependentUpon>Web.Base.config</DependentUpon></Content>[other configs here] 
  5. Above <Target Name="BeforeBuild"> add:<UsingTask taskname="TransformXml" assemblyfile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.Tasks.dll" />or<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\v10.0\Web\Microsoft.Web.Publishing.Tasks.dll" />Depending on your install location
  6. Add lines to edit file properties and carry out transform:<Target Name="BeforeBuild"><Exec Command="ATTRIB -R "$(SolutionDir)$(SolutionName).Website\web.config"" /><TransformXml Source="Web.Base.config" Transform="Web.Base.$(Configuration).config" Destination="Web.config" StackTrace="true" /></Target>
An alternative approach is to use the web.config as the 'base' BUT you will need to be sure to amend/remove the results of other transforms e.g. changing a debug transform result back to a release setting: the web.config may get transformed as debug then checked in as is. The advantage to using the web.config as the 'base' is that both VS, other developers and Nuget expect to use that and will modify it e.g. when un/installing packages.

No comments:

Post a Comment