Using Web.Config transforms in your own application

A few months ago I thought it would be great if I could leverage the XML
Document Transforms found in Visual Studio publishing/packaging pipeline
in one of my own applications. I was specifically looking for the
ability to use the same Transform engine in my own project in a
redistributable way. I didn't find anything then, but am happy to report
that Microsoft have released the XML Document Transform AKA
XDT engine on NuGet. They have also released the source code on Codeplex found here.

Here's how you get started using this in your own application:

  1. At the time of writing, the package is PreRelease and can be
    installed via NuGet using the command below:

    Install-Package Microsoft.Web.Xdt -Pre

  2. You can now access the Microsoft.Web.XmlTransform namespace.
    Below is some sample code to get you started:

    var sourceConfigFile = "web.config";
    var transfromFile = "web.release.config";
    
    
    // Create a new Transformable Document from a source configuration file.
    using (var sourceConfig = new Microsoft.Web.XmlTransform.XmlTransformableDocument())
    {
        sourceConfig.Load(sourceConfigFile);
    
    
    
    using (var transformation = new Microsoft.Web.XmlTransform.XmlTransformation(transfromFile))
    {
        if (transformation.Apply(sourceConfig))
        {
            // Transformation applied successfully to sourceConfig.
        }
        else
        {
            // Transform did not apply successfully
        }
    }
    
    }
  3. It couldn't be much easier!

  4. Check out the Source Code to this which has been released on
    CodePlex - https://xdt.codeplex.com/

  5. It has been released under the Apache 2.0 license, meaning you can
    redistribute it in your own apps!

Integration with NuGet

Probably the best news from this announcement is that NuGet will get
support XDT web.config transforms. As a package author, you will be able
to perform config transforms when installing and uninstalling your
package.

  1. Simply include two new files into your package
    1. web.config.install.xdt
    2. web.config.uninstall.xdt

The official announcement can be found
here.