Friday, April 24, 2015

Updating a Web.config or App.config file using MSBuild

Normally, if you want to update your Web.config file or App.config file with specific settings, you will normally use a Config Transformation.

However, the problem with Config Transformations is that they require a separate file for EACH environment you want to deploy.  Therefore, you can easily see the number of Config Transformation files growing as you add more environments for development and testing.

So, what is the solution?

Well, in the past, you could update these files using an XmlTask such as the one found in MSBuild Extension Pack.

However, with the release of MSBuild v. 4.0, this is no longer needed with the inclusion of the XmlPoke Task.

In order to update your target Config file with the appropriate values, you simply provide the following:
  1. The path to your Config file
  2. The XPath that you want to update
  3. The new value for the specified element or attribute

Therefore, you can update an appSetting in your Web.config file using MSBuild in the following manner:

<Project ToolsVersion="12.0" DefaultTargets="UpdateWebConfig" InitialTargets="UpdateWebConfig" xmlns="">

    <Target Name="UpdateWebConfig">






        <XmlPoke XmlInputPath="$(WebConfigFile)" Query="$(AppSettingPath)" Value="$(AppSettingNewValue)" />



If you are interested in updating multiple AppSettings in batch, you can do something like the following:

<Target Name="UpdateWebConfigAppSettings">
    <AppSettingKey Include="Key1">
    <AppSettingKey Include="Key2">
    <AppSettingKey Include="Key3">
    <AppSettingKey Include="Key4">
    <AppSettingKey Include="Key5">
  <XmlPoke XmlInputPath="C:\Code\Web.config" Query="/configuration/appSettings/add[@key='@(AppSettingKey)']/@value" Value="%(AppSettingKey.Value)" />

If you want to integrate with a Continuous Integration Build Server such as Jetbrains TeamCity, you simply have to ensure that you pass these properties into your MSBuild script by using System Properties (ex: system.Value1)


That is all there is to it!! Easy as pie!!

No comments:

Post a Comment