Tag Archives: NuGet

Applying configuration transforms outside Visual Studio

Recently I was putting a NuGet package together and one of the things the package needs to do is change the configuration file when added to a project.

NuGet 2.7 and forward supports the use of XDT transformation files in the form of .install.xdt and .uninstall.xdt that run during package install and uninstall respectively.

However, all the files that are part of a NuGet package composition are usually outside projects in Visual Studio, so I needed a way to test that these transformations actually worked on a live config file.

To achieve this I wrote a PowerShell script that references the Microsoft.Web.XmlTransform.dll assembly that executes the transformation, applies the transformation and writes to an out.xml file in the same location as the script. The path to the XmlTransform dll is hardcoded into the script, but it is the path on a default installation of Visual Studio 2015.


param
(
[parameter(Mandatory=$true)]
[string]
$Xml,
[parameter(Mandatory=$true)]
[string]
$Xdt
)
if (!(Test-Path -path $Xml -PathType Leaf))
{
throw "XML File not found. $Xml"
}
if (!(Test-Path -path $Xdt -PathType Leaf))
{
throw "XDT File not found. $Xdt"
}
Add-Type -LiteralPath "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\spzpqgng.yjx\Microsoft.Web.XmlTransform.dll"
$xmldoc = New-Object Microsoft.Web.XmlTransform.XmlTransformableDocument
$xmldoc.PreserveWhitespace = $true
$xmldoc.Load($Xml)
$transf = New-Object Microsoft.Web.XmlTransform.XmlTransformation($xdt)
if ($transf.Apply($xmldoc) -eq $false)
{
throw "Transformation failed."
}
$xmldoc.Save("$PSScriptRoot\out.xml")