Using Custom Web.config Transformations in MSBUILD
Join the DZone community and get the full member experience.Join For Free
web.config transformations have been around for a while now, and a lot of developers use them in their staple day-to-day environment deployment strategies – hell, scott hanselman was spouting about them way back in the beginning on 2010 with his “ web deployment made awesome: if you’re using xcopy, you’re doing it wrong ” post. as usual though, one size does not fit all – and in the case of continuous integration fans out there that may have specific build-configuration-based build and deployment scenarios (such as myself), there is the need to have finer grained control over the web.config transformation process. if this sounds like you, then this post is aimed to deliver.
what a second… what the hell are “web.config transforms”?
asp.net has had a few features that that been around for what seems like forever when it comes to abstracting away or alternating between different configuration data for your website (i’m talking about configsource functionality mostly). the features were very minimal and usually created a less-than-ideal solution for developers working on big websites in multiple environments. with the advent of visual studio 2010 microsoft kindly helped us all out by taking note that “ hey maybe not all websites are being built for a single server with a single configuration ”… smart guys . they created web.config transformations to help deal with this problem and jokes aside, the feature is actually pretty cool and allows you to write a base web.config file as you normally would and then transform it for each of your environments.
your base web.config:
<?xml version="1.0"?> <configuration> <appsettings> <add key="exampleapplicationsetting" value="value being replaced by transform"/> </appsettings> <connectionstrings> <add name="myconnectionstring" connectionstring="..." providername="system.data.sqlclient" /> </connectionstrings> <system.web> <customerrors mode="off"/> <compilation debug="true"> </compilation> </system.web> </configuration>
your web.config transform (note the change to my connection string, my custom errors and my compilation mode):
<?xml version="1.0"?> <configuration xmlns:xdt="http://schemas.microsoft.com/xml-document-transform"> <appsettings> <add key="exampleapplicationsetting" xdt:transform="setattributes(value)" xdt:locator="condition(@key='exampleapplicationsetting')" value="the new value to replace after transform"/> </appsettings> <connectionstrings> <add name="mysolutiondatabase" xdt:transform="replace" xdt:locator="condition(@name='mysolutiondatabase')" connectionstring="... my new connection string ..." providername="system.data.sqlclient" /> </connectionstrings> <system.web> <customerrors xdt:transform="replace" mode="remoteonly" /> <compilation xdt:transform="setattributes(debug)" debug="false" /> </system.web> </configuration>
if this is the first you’ve heard of web.config transforms and the syntax in my example above isn’t the clearest it could be, you’ll find the msdn page on the transformation syntax a valuable read.
so what is wrong with the default usage?
“so what?” you say, “ i use them every day, and they work fine” . the main problem i have with the “out of the box solution” is as follows;
the default usage creates a new config transform for each build configuration of the website they sit inside .
when using visual studio and you right click your web.config and
add config transformations
you will end up with the following
this is a major problem for me, as nearly all the places i have worked that use continuous delivery or continuous integration with asp.net websites have used solution configurations for switching between different build environments, not project configurations.
your website should really only have two build configurations that you use for compilation:
your different environments may be:
- internal staging
- quality assurance
- external staging
but all of the above environments will either be compiled in debug mode or release mode, so confusing build configurations with environmental configurations feels to me like you are introducing some serious “ code smell ” into your build setup.
for some environments you may want to use the same web.config transform
another issue i have with this setup is that it assumes that you have a different transformation for each of your build configurations. what if you use the same environment configurations for a number of your build configurations? your production-staging environment should probably be the same as your production environment for example – i don't begin to know your requirements, but i do know that mine are not as rigid as this.
for some environments you may want to use multiple tiers of web.config transformations applied over the top of each other
another case where the default usage may not tick all your boxes is
when it comes to tiering multiple configurations transformations
together. having the ability to apply transformations in
is a very powerful potential usage of transformations.
so where does this leave us?
for me, this put me in the position of wanting badly to find a solution that could give me this level of granularity while still using the transformation tools built into visual studio and all the nice convention based functionality that comes with their usage. up until this point i have been a big fan of abstracting my configs based on environment using something similar to below and swapping the “\live\” string at build time:
<configuration> <appsettings configsource ="configs\live\appsettings.config" /> </configuration>
the major problem with using this technique is that you end up risking having some configurations that are missing certain appsettings keys and a couple of other annoying niggling issues that you usually only become aware of at the time of deployment (this is a big no-no when using continuous integration as the main point of using it is that it removes a lot of the risks of deploying – and this very issue creates risk). so i was very eager to find a solution that uses config transforms.
“… msbuild is a hell of a drug…”
i am a big fan of msbuild when writing build scripts, if for no other reason than the fact that microsoft’s web deployment projects are basically msbuild scripts that integrate well within the visual studio ide.
why does this matter? because i am about to show you a way to use
msbuild to apply web.config transformations step-by-step, allowing you
to apply them with as much fine granularity as you like…
omfg wtg bbq r u seriuzz!
short answer: yes
the short version
applying configuration transformations using msbuild is quite easy, all you need is the to have visual studio 2010 installed on the machine running your build (in my case this is usually my teamcity server).
the bare minimum example for applying a transform is shown below ( do not use this until you have read the rest of this post and become aware of “the bug”) :
<usingtask taskname="transformxml" assemblyfile="$(msbuildextensionspath)\microsoft\visualstudio\v10.0\web\microsoft.web.publishing.tasks.dll"/> <target name="transformwebconfig"> <transformxml source="c:\code\myproject\web.config" transform="c:\code\myproject\transformfile.config" destination="c:\code\myproject\web.config" stacktrace="true" /> </target>
my above example kind of explains itself, however just to clarify what this does:
- imports the assembly found at $(msbuildextensionspath)\microsoft\visualstudio\v10.0\web\microsoft.web.publishing.tasks.dll and gives it the task name transformxml .
- defines a new target named transformwebconfig (so that you can call this from somewhere else in your msbuild/web deployment project file, such as in your afterbuild section).
inside our newly created target, we call
and pass it the following parameters
- our source web.config is located at c:\code\myproject\web.config
- our transformation file is located at c:\code\myproject\transformfile.config
- the end resulting web.config file should be saved to c:\code\myproject\web.config
turn on stacktrace so that in my build log i can review any
issues with the transformation such as rules that couldn’t be applied
etc (good to have on for review).
pretty cool eh?
with the above snippet you can apply as many different transforms as you like in your build scripts by using the command in different ways – even to put into action more advanced configurations such as applying tiered transformations.
thar be dragons! – use this instead
there is a known issue with the above msbuild task though in that it does not close the source web.config file successfully during the application of the transformation causing it to error when reading and writing to the same web.config. this is very annoying as it causes your build to fail if you use my example above directly , because msbuild will try and write over the original web.config while it still has it open. to overcome this, i add a simple second step to my build task that copies the web.config to a temporary location and then deletes the file after the transform has taken place.
<usingtask taskname="transformxml" assemblyfile="$(msbuildextensionspath)\microsoft\visualstudio\v10.0\web\microsoft.web.publishing.tasks.dll"/> <target name="transformwebconfig"> <itemgroup> <originalwebconfig include="c:\code\myproject\web.config"/> <tempwebconfig include="c:\code\myproject\tempweb.config"/> </itemgroup> <copy sourcefiles="@(originalwebconfig)" destinationfiles="@(tempwebconfig)" /> <transformxml source="c:\code\myproject\tempweb.config" transform="c:\code\myproject\transformfile.config" destination="c:\code\myproject\web.config" stacktrace="true" /> <delete files="@(tempwebconfig)" /> </target>
more advanced techniques
as i mentioned earlier in this post, i usually prefer to use a more dynamic solution configuration based switching in my continuous delivery setups for deployment, and therefore want to be able to have my transforms applied depending on the solution configuration being fired, to allow for more flexibility.
my usual website project setup includes a folder called deployment that sits in the root of the site. in this folder i include any assets that are used as part of my deployment . this includes things like a command-line sftp client, a web.config checker and any configuration files that are used in my build. i usually have a post build step that deletes this folder so that you don’t find things such as sftp hashes or alternate environment database connection strings finding their way onto your web host’s servers – i highly recommend you follow a similar procedure.
for my example below i base all the properties i send the transformxml build task shown above on the build configuration parameters and the file paths being used at build time. i also refer to the transform files i have in my \deployment\ folder shown above.
my example below, does the following:
- defines a property named webconfigreplacement and defines it depending on the solution build configuration being used. if building a staging deployment use the staging transform file, if a production deployment use the production config transform file.
- copy the web.config file to a temporary location inside my \ deployment\ folder
- runs the config transform defined in step 1 to the temporary web.config created in step 2 and save it over the top of my web applications web.config
- delete the temporary web.config inside my \deployment\ folder.
<!-- setup the transformation file to use --> <propertygroup condition="'$(configuration)|$(platform)' == 'deploy - staging|anycpu'"> <webconfigreplacement>staging</webconfigreplacement> </propertygroup> <propertygroup condition="'$(configuration)|$(platform)' == 'deploy - production|anycpu'"> <webconfigreplacement>production</webconfigreplacement> </propertygroup> <usingtask taskname="transformxml" assemblyfile="$(msbuildextensionspath)\microsoft\visualstudio\v10.0\web\microsoft.web.publishing.tasks.dll"/> <propertygroup> <transforminputfile>$(outputpath)\deployment\web.temp.config</transforminputfile> <transformfile>$(outputpath)\deployment\web.$(webconfigreplacement).config</transformfile> <transformoutputfile>$(outputpath)\web.config</transformoutputfile> <stacktraceenabled>false</stacktraceenabled> </propertygroup> <itemgroup> <originalwebconfig include="$(outputpath)\web.config"/> <tempwebconfig include="$(outputpath)\deployment\web.temp.config"/> </itemgroup> <target name="transformwebconfig" condition="'$(configuration)|$(platform)' == 'deploy - production|anycpu' or '$(configuration)|$(platform)' == 'deploy - staging|anycpu'"> <!-- copy our web.config into a temp folder as the 'transformxml' task has a file lock bug --> <copy sourcefiles="@(originalwebconfig)" destinationfiles="@(tempwebconfig)" /> <transformxml source="$(transforminputfile)" transform="$(transformfile)" destination="$(transformoutputfile)" stacktrace="$(stacktraceenabled)" /> <delete files="@(tempwebconfig)"/> </target>
hopefully this has given you food-for-thought and got your continuous integration juices flowing. web.config transformations are a very cool feature, so you shouldn’t have to go without just because you are a fan of continuous integration – time to come play with all the other kids…
Published at DZone with permission of Douglas Rathbone, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.