If you are using Visual Studio 2010 then you may already be familiar with the Web.config transformations that are now available. What you might not know is that you can use that same technology to transform config files outside of the build process. You will need Visual Studio 2010 installed on the machine where you perform these transformations. It is very easy to perform these transformation as well. Let’s say that we start with the app.config file shown below.
04 | < add name = "Default" connectionstring = "Data Source=localhost;Initial Catalog=Sample01;Integrated Security=True;" > |
05 | </ add ></ clear ></ connectionstrings > |
08 | < add key = "contactEmail" value = "contact@demo.example.com" > |
10 | </ add ></ add ></ appsettings > |
Then we create another file, transform.xml, which contains our transformations. That file is shown below.
04 | < add name = "Default" connectionstring = "Data Source=NOT-localhost;Initial Catalog=Sample01;Integrated Security=True;" xdt:locator = "Match(name)" xdt:transform = "Replace" > |
05 | </ add ></ clear ></ connectionstrings > |
08 | < add key = "contactEmail" value = "contact@example.com" xdt:locator = "Match(key)" xdt:transform = "Replace" > |
09 | < add key = "siteUrl" value = "http://example.com" xdt:locator = "Match(key)" xdt:transform = "Replace" > |
10 | </ add ></ add ></ appsettings > |
Then we can easily execute the transformations by using MSBuild. So I created a file named trans.proj and it is shown below.
2 | < usingtask taskname = "TransformXml" assemblyfile = "$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.Tasks.dll" > |
5 | < transformxml source = "app.config" transform = "Transform.xml" destination = "app.prod.config" > |
6 | </ transformxml ></ target > |
This MSBuild file uses the TransformXml task which is shipped with Visual Studio 2010. We specify the source file, transform file and the destination. Pretty straight forward.
In order to execute this I open a Visual Studio 2010 command prompt, browse to the directory containing both files, and enter the following command
1 | msbuild trans.proj /t:Demo |
Once you do this then you will find the file app.prod.config with the following contents.
04 | < add name = "Default" connectionstring = "Data Source=NOT-localhost;Initial Catalog=Sample01;Integrated Security=True;" > |
05 | </ add ></ clear ></ connectionstrings > |
08 | < add key = "contactEmail" value = "contact@example.com" > |
10 | </ add ></ add ></ appsettings > |
Sayed Ibrahim Hashimi
Comments are closed.