How do I test my config transforms?

  • Page Owner: Not Set
  • Last Reviewed: 2021-04-16

While Visual Studio has some support for testing Web.config transforms, sometimes I need to be able to run arbitrary config transforms against a file. How can I do this?


Answer

First, locate the Microsoft.Web.XmlTransform.dll DLL on your harddrive. I believe it's in a Visual Studio install folder. If you have multiple, use the latest version. Copy that file somewhere you can reference it easily.

Then create this script somewhere you can reference it easily:

    Param(
        [string] $xml,
        [string] $xdt
    )

    Add-Type -LiteralPath "C:\path\to\Microsoft.Web.XmlTransform.dll"

    $fullXml = Resolve-Path $xml
    $fullXdt = Resolve-Path $xdt

    $xmldoc = New-Object Microsoft.Web.XmlTransform.XmlTransformableDocument;
    $xmldoc.PreserveWhitespace = $true
    $xmldoc.Load($fullXml);

    $transf = New-Object Microsoft.Web.XmlTransform.XmlTransformation($fullXdt);
    if ($transf.Apply($xmldoc) -eq $false)
    {
        throw "Transformation failed."
    }
    $xmldoc.Save($fullXml);

NOTE: You need to find update the Add-Type -LiteralPath "C:\path\to\Microsoft.Web.XmlTransform.dll" with the correct path.

Once it's setup, you can invoke the command like this: c:\path\to\transform.ps1 Web.config Web.Integration.config. This will transform the Web.config file with the Web.Integration.config file, and save the resulting file back to Web.config. In git, this makes it pretty easy to see what transforms are actually applied.

For a DXP and DXP-like environments, you can then run the script multiple times (once for each environment) to get to the final Production config:

c:\path\to\transform.ps1 .\Web.config .\Web.Integration.config
c:\path\to\transform.ps1 .\Web.config .\Web.Preproduction.config
c:\path\to\transform.ps1 .\Web.config .\Web.Production.config

Additional Posts

Use Visual Studio's Compare tool

In your CSProj file add the IsTransformFile property to your webconfig content include line. Note this does require a DependentUpon element.

<Content Include="Web.Integration.config">
  <DependentUpon>Web.config</DependentUpon>
  <IsTransformFile>True</IsTransformFile>
</Content>

When you right click on the transform, a new item will appear, Preview Transform