Search code examples
visual-studio.net-4.0app-configslowcheetahweb-config-transform

App.Config Transformation for projects which are not Web Projects in Visual Studio?


For Visual Studio 2010 Web based application we have Config Transformation features by which we can maintain multiple configuration files for different environments. But the same feature is not available for App.Config files for Windows Services/WinForms or Console Application.

There is a workaround available as suggested here: Applying XDT magic to App.Config.

However it is not straightforward and requires a number of steps. Is there an easier way to achieve the same for app.config files?


Solution

  • This works now with the Visual Studio AddIn treated in this article: SlowCheetah - Web.config Transformation Syntax now generalized for any XML configuration file.

    You can right-click on your web.config and click "Add Config Transforms." When you do this, you'll get a web.debug.config and a web.release.config. You can make a web.whatever.config if you like, as long as the name lines up with a configuration profile. These files are just the changes you want made, not a complete copy of your web.config.

    You might think you'd want to use XSLT to transform a web.config, but while they feels intuitively right it's actually very verbose.

    Here's two transforms, one using XSLT and the same one using the XML Document Transform syntax/namespace. As with all things there's multiple ways in XSLT to do this, but you get the general idea. XSLT is a generalized tree transformation language, while this deployment one is optimized for a specific subset of common scenarios. But, the cool part is that each XDT transform is a .NET plugin, so you can make your own.

    <?xml version="1.0" ?>
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:template match="@*|node()">
      <xsl:copy>           
        <xsl:apply-templates select="@*|node()"/>
      </xsl:copy>
    </xsl:template>
    <xsl:template match="/configuration/appSettings">
      <xsl:copy>
        <xsl:apply-templates select="node()|@*"/>
        <xsl:element name="add">
          <xsl:attribute name="key">NewSetting</xsl:attribute>
          <xsl:attribute name="value">New Setting Value</xsl:attribute>
        </xsl:element>
      </xsl:copy>
    </xsl:template>
    </xsl:stylesheet>
    

    Or the same thing via the deployment transform:

    <configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
       <appSettings>
          <add name="NewSetting" value="New Setting Value" xdt:Transform="Insert"/>
       </appSettings>
    </configuration>