torsdag 26 november 2009

app.config transformation with the new MsBuild task XslTransformation in .NET4

I want to have different connection strings, server paths, etc. in my app.config files for different build configurations. MS have solved this in a nice way inVS2010 Web Deployment with web.config transformations but that's regretfully not available in my non web projects.

I'm trying to accomplish something similar to my app.config files by including xslt files in my projects and then have MsBuild execute transformations at build time. I just found that in version 4 of the Microsoft.Build.Tasks (Microsoft.Build.Tasks.v4.0.dll) there is a new task called XslTransformation which is cool, as we no longer have to write our own custom task for this!

By using a simple xsl file with the following contents I can replace a named connection string (Test) with a new one. This is very similar to the behaviour of the web.config transformations though the XDT syntax is a bit simpler.

<?xml version="1.0" encoding="utf-8"?>

<xsl:stylesheet version="1.0" xmlns:xsl="" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
<xsl:output method="xml" indent="yes"/>

<!-- Default template -->
<xsl:template match="@* node()">
<xsl:apply-templates select="@* node()"/>

<!-- Connection string replacement template -->
<xsl:template match="/configuration/connectionStrings/add[@name='Test']">
<add name="Test" connectionString="NewValue" providerName="System.Data.EntityClient" />

2 kommentarer:

  1. Thank you for this! I implemented your idea in my own solution and it works like a charm.

    I blogged about my solution which is very close to yours. Hope you don't mind.

    Mikael Lundin

  2. Mikael, I'm glad I could help!