Web.config Transformation Syntax for Web Application Project Deployment

Other Versions
 

Updated: May 2011

Web.config files typically include settings that have to be different depending on which environment the application is running in. For example, you might have to change a database connection string or disable debugging when you deploy a Web.config file. For Web application projects, ASP.NET provides tools that automate the process of changing (transforming) Web.config files when they are deployed. For each environment that you want to deploy to, you create a transform file that specifies only the differences between the original Web.config file and the deployed Web.config file for that environment.

A transform file is an XML file that specifies how the Web.config file should be changed when it is deployed. Transformation actions are specified by using XML attributes that are defined in the XML-Document-Transform namespace, which is mapped to the xdt prefix. The XML-Document-Transform namespace defines two attributes: Locator and Transform. The Locator attribute specifies the Web.config element or set of elements that you want to change in some way. The Transformattribute specifies what you want to do to the elements that the Locator attribute finds.

The following example shows the contents of a transform file that changes a connection string and replaces the customErrors element:

 
 
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<connectionStrings>
<add name="MyDB"
connectionString="value for the deployed Web.config file"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>
<system.web>
<customErrors defaultRedirect="GenericError.htm"
mode="RemoteOnly" xdt:Transform="Replace">
<error statusCode="500" redirect="InternalError.htm"/>
</customErrors>
</system.web>
</configuration>

The root element of a transform file must specify the XML-Document-Transform namespace in its opening tag, as shown in the preceding example. The Locator and Transform elements themselves are not reproduced in the deployed Web.config file.

This following sections provide reference information about the syntax to use in transform files.

Locator Attribute Syntax

 

Each of the following sections explains the syntax for one Locator attribute.

Condition

Specifies an XPath expression that is appended to the current element's XPath expression. Elements that match the combined XPath expression are selected.

Syntax

 
 
Locator="Condition(XPath expression)"

Example

The following example shows how to select connection string elements whose name attribute value is oldname or a providerName attribute whose value is oldprovider. In the deployed Web.config file, the selected elements are replaced with the element that is specified in the transform file.

 
 
<configuration xmlns:xdt="...">
<connectionStrings>
<add name="AWLT" connectionString="newstring"
providerName="newprovider"
xdt:Transform="Replace"
xdt:Locator="Condition(@name='oldname'
or @providerName='oldprovider')" />
</connectionStrings>
</configuration>

The effective XPath expression that is applied to the development Web.config file as a result of the specified Condition expression is the following:

configuration/connectionStrings/add[@name='AWLT' or @providerName='System.Data.SqlClient']

This expression is a result of combining the implicit XPath condition for the current element (configuration/connectionStrings) with the expression that is specified explicitly.

Match

Selects the element or elements that have a matching value for the specified attribute or attributes. If multiple attribute names are specified, only elements that match all the specified attributes are selected.

Syntax

 
 
Locator="Match(comma-delimited list of one or more attribute names)"

Example

The following example shows how to select the connection string add element that has AWLT in the name attribute in the development Web.config file. In the deployed Web.config file, the selected element is replaced with the add element that is specified in the transform file.

 
 
<configuration xmlns:xdt="...">
<connectionStrings>
<add name="AWLT" connectionString="newstring"
providerName="newprovider"
xdt:Transform="Replace"
xdt:Locator="Match(name)" />
</connectionStrings>
</configuration>

XPath

Specifies an absolute XPath expression that is applied to the development Web.config file. (Unlike Condition, the expression that you specify is not appended to the implicit XPath expression that corresponds to the current element.)

Syntax

 
 
Locator="XPath(XPath expression)"

Example

The following example shows how to select the same elements that are selected by the preceding example for the Condition keyword.

 
 
<configuration xmlns:xdt="...">
<connectionStrings>
<add name="AWLT" connectionString="newstring"
providerName="newprovider"
xdt:Transform="Replace"
xdt:Locator="XPath(configuration/connectionStrings[@name='AWLT'
or @providerName='System.Data.SqlClient'])" />
</connectionStrings>
</configuration>

Transform Attribute Syntax

 

Each of the following sections explains the syntax for one Transform attribute.

Replace

Replaces the selected element with the element that is specified in the transform file. If more than one element is selected, only the first selected element is replaced. For an example of how to use the Replace keyword, see the examples for the Locator attributes.

Syntax

 
 
Transform="Replace"

Insert

Adds the element that is defined in the transform file as a sibling to the selected element or elements. The new element is added at the end of any collection.

Syntax

 
 
Transform="Insert"

Example

The following example shows how to select all the connection strings in the development Web.config file. In the deployed Web.config file, the specified connection string is added to the end of the collection.

 
 
<configuration xmlns:xdt="...">
<connectionStrings>
<add name="AWLT" connectionString="newstring"
providerName="newprovider"
xdt:Transform="Insert" />
</connectionStrings>
</configuration>

InsertBefore

Inserts the element that is defined in the transform XML directly before the element that is selected by the specified XPath expression. The XPath expression must be an absolute expression, because it is applied to the development Web.config file as a whole; it is not appended only to the current element's implicit XPath expression.

Syntax

 
 
Transform="InsertBefore(XPath expression)"

Example

The following example shows how to select the deny element that denies access to all users, and then inserts an allow element before it that grants access to administrators.

 
 
<configuration xmlns:xdt="...">
<authorization>
<allow roles="Admins"
xdt:Transform="InsertBefore(/configuration/system.web/authorization/deny[@users='*'])" />
</authorization>
</configuration>

InsertAfter

Inserts the element that is defined in the transform XML directly after the element that is selected by the specified XPath expression. The XPath expression must be an absolute expression, because it is applied to the development Web.config file as a whole; it is not appended to the current element's implicit XPath expression.

Syntax

 
 
Transform="InsertAfter(XPath expression)"

Example

The following example shows how to select the allow element that grants access to administrators, and inserts a deny element after it that denies access to a specified user.

 
 
<configuration xmlns:xdt="...">
<authorization>
<deny users="UserName"
xdt:Transform="InsertAfter
(/configuration/system.web/authorization/allow[@roles='Admins'])" />
</authorization>
</configuration>

Remove

Removes the selected element. If multiple elements are selected, removes the first element.

Syntax

 
 
Transform="Remove"

Example

The following example shows how to select all the connection string add elements in the development Web.config file. In the deployed Web.config file, only the first connection string element is removed.

 
 
<configuration xmlns:xdt="...">
<connectionStrings>
<add xdt:Transform="Remove" />
</connectionStrings>
</configuration>

RemoveAll

Removes the selected element or elements.

Syntax

 
 
Transform="RemoveAll"

Example

The following example shows how to select all the connection strings in the development Web.config file. In the deployed Web.config file, all the elements are removed.

 
 
<configuration xmlns:xdt="...">
<connectionStrings>
<add xdt:Transform="RemoveAll" />
</connectionStrings>
</configuration>

RemoveAttributes

Removes specified attributes from the selected elements.

Syntax

 
 
Transform="RemoveAttributes(comma-delimited list of one or more attribute names)"

Example

The following example shows how to select all the compilation elements in the development Web.config file. (Because there can be only one compilation element in the configuration file, you do not have to specify a Locator attribute.) In the deployed Web.config file, the debug and batchattributes are removed from the compilation element.

 
 
<configuration xmlns:xdt="...">
<compilation
xdt:Transform="RemoveAttributes(debug,batch)">
</compilation>
</configuration>

SetAttributes

Sets attributes for selected elements to the specified values. The Replace transform attribute replaces an entire element including all of its attributes. In contrast, the SetAttributes attribute enables you to leave the element as it is but change selected attributes. If you do not specify which attributes to change, all of the attributes that are present in the element in the transform file are changed.

The SetAttributes transform affects all selected elements. This is different from the Replacetransform attribute, which affects only the first selected element if multiple elements are selected.

Syntax

 
 
Transform="SetAttributes(comma-delimited list of one or more attribute names)"

Example

The following example shows how to select all the compilation elements in the development Web.config file. (Because there can be only one compilation element in the configuration file, you do not have to specify a Locator attribute.) In the deployed Web.config file, the value of the compilation element's batch attribute is set to false.

 
 
<configuration xmlns:xdt="...">
<compilation
batch="false"
xdt:Transform="SetAttributes(batch)">
</compilation>
</configuration>

Omitting Locator Attributes

 

Locator attributes are optional. If you do not specify a Locator attribute, the element to be changed is specified implicitly by the element that the Transform attribute is specified for. In the following example, the entire system.web element is replaced, because no Locator attribute is specified to indicate otherwise.

 
 
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<system.web xdt:Transform="Replace">
<customErrors defaultRedirect="GenericError.htm"
mode="RemoteOnly">
<error statusCode="500" redirect="InternalError.htm"/>
</customErrors>
</system.web>
</configuration>

Using Transform and Locator Attributes on Separate Elements

 

A Transform attribute does not have to be set in the same element as a Locator element. You can specify a Locator element on a parent element in order to select elements whose child elements you want to work with. You can then specify a Transform attribute in a child element in order to apply a change to the children.

The following example shows how to use the Locator attribute to select location elements for the specified path. However, only elements that are children of the selected location elements are transformed.

 
 
<configuration xmlns:xdt="...">
<location path="C:\MySite\Admin" xdt:Locator="Match(path)">
<system.web>
<pages viewStateEncryptionMode="Always"
xdt:Transform="SetAttributes(viewStateEncryptionMode)" />
</system.web>
</location>
</configuration>

If you specify a Locator attribute but you do not specify a Transform attribute in the same element or in a child element, no changes are made.

Note

A Transform attribute on a parent element can affect child elements even if no Transform is specified for them. For example, if you put the attribute xdt:Transform="Replace" in the system.web element, all the elements that are children of the system.web element are replaced with the content from the transform file.

Change History

 
 

Date

History

Reason

May 2011

Corrected the explanation of how the Replace transform works.

Customer feedback.

Community Additions

 

Config file is a big mistake

It not so easy to implement......i hope microsoft will make better approach than this

This system is way more complicated than it needs to be...

Simplicity is elegant. This is way over engineered. Unless the purpose was to support the new and growing profession of configuration engineer. 
7/25/2014

You guys need to simply this.

Have you guys took a look at rails framework. It automatically sets up debug, QA and dev environments.

Depending on which DB you are using you need to find the config file and set the server credentials.

This article puts me to sleep.

6/18/2014

is there a way to add a comment?

Is there a way to add a comment to a customized web.config?

Example:
In web.prod.config:
<!--

 Web.Config for the PRODUCTION server 

-->

in web.QA.config:
<!--

Web.Config for the Q.A. server 

-->

Thanks,
Marcelo

8/9/2012

Is there way to do "InsertAtTop", basically the "Insert" add the node at the end, is there a way to

Is there way to do "InsertAtTop", basically the "Insert" add the node at the end, is there a way to add it as the first node?

InsertBefore isn't useful, as we may not know what's the current first node in source xml.

5/30/2012

Web.Config transforms with new line symbol

Exists:

<applicationSettings>
     <ADM.Web.Admin.ADMSettings>
          <settingname="ApplicationWebAddress"serializeAs="String">
              <value>http://localhost:8929</value>
          </setting>
     </ADM.Web.Admin.ADMSettings>
</applicationSettings>

Do transform:

<settingname="ApplicationWebAddress"serializeAs="String"xdt:Transform="Replace"xdt:Locator="Match(name)">
     <value>http://live.site.com</value>
</setting>

Get a config with new line character:

<settingname="ApplicationWebAddress"serializeAs="String">
     <value>http://live.site.com
     </value>
</setting>

Anyone knows how to solve this issue?

12/4/2011

Not all web.config elements have the "file" attribute

@Artem,

While it is true you can use the file attribute for appSettings instead, it is not true that you can use it for all elements. For instance, we write a log of WCF applications. The system.service.model element does not have a file attribute, and we must provide overrides to have diffent endpoints, bindings, etc. for different environment configurations.

The article is about how to write transforms. Using <appSettings> as an example is just an easy pedagogical technique, since everyone is so familiar with that element.

11/27/2011

Preserve <CRLF> from the transform file?

We use <CRLF> between attributes for readablility, and to make file compares between existing and generated .config files easier to compare.

It seems that the transform tool ignores, somewhat randomly, our <CRLF> characters between attributes. Is there a way to preserve them?

Or is there a way (particularly in a continuous build/deploy environment) to apply the formatting rules in Visual Studio for XML files to the generated output?

11/27/2011

Managing elements with a different namespace

In case you would like to change some element values (in my case of the Microsoft.Unity framework) within the web.config that have a different schema (not part of the orginal Web.Config schema) then you need to do the following:

1) Add the (new) schema in question to the <configuration> element. For example:

<


configurationxmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform" xmlns:u="http://schemas.microsoft.com/practices/2010/unity">

2) In case you need to set an attribute on the alias tag within Unity, then use the following

<

u:unity>

<u:alias    alias="yourAliasGoesHere" 
                type="yourTypeGoesHere"
                xdt:Transform="SetAttributes"
                xdt:Locator="Match(alias)"/>

</u:unity>

10/18/2011

RE: Build with TFS

Good stuff, THANK YOU, tlingenf !!

To use the web.config transformations you need to use a compatable web project and have it properly configured for each of your build configurations. For more information see: http://msdn.microsoft.com/en-us/library/dd483479.aspx

You can use TFS to build your web projects and it too can perform the web.config transformations. To do this you can include the following MSBuild command-line parameters /p:CreatePackageOnPublish=true /p:DeployOnBuild=True. If you are using TFS 2008 place each parameter on a separate line in the TFSBuild.rsp file. On build, you will get a new folder for your project package under the drop folder's _PublishedWebsites folder that contains your web deployment configuration package with the transformed web.config.

6/30/2011

Transformation Test Tool

I have created a tool to debug and test web.config transformation. It is found here: http://webconfigtransformationtester.apphb.com/
3/20/2011

How to simply generate the Transformed Config

For testing your transformation or for a low-key transformation (avoiding a full publish of the project) you can add this custom task in your *.csproj

<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.Tasks.dll" />

<Target Name="Transform">

<MakeDir Directories="obj\$(Configuration)" Condition="!Exists('obj\$(Configuration)')" />

<TransformXml Source="Web.Config" Transform="Web.$(Configuration).config" Destination="obj\$(Configuration)\Web.config" StackTrace="true" />

</Target>

Afterwards you can generate the transformation using :

call "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcvarsall.bat"

"msbuild" "D:\Solutions\Web.csproj" /m /t:Transform /p:Configuration=QA

Regards,

Jan Hebnes

3/18/2011

XML Formatting may affect some application settings of type String

The "Replace" and "Insert" transform can append linebreaks within an element value. For instance, if you have an application setting that contains a root filepath and use the replace transform in the web config transform it may insert a linebreak after your string value placing the closing </value> tag on the next line. This linebreak will carry over into your application setting if it is of type String.

e.g.

<setting name="VersionDate" serializeAs="String">
    <value>14th September 2010
    </value>

</setting>

3/14/2011

"file" attribute of appSettings node

All of this makes very little sense because you can achieve more by using the "file" attribute of the appSettings node of web.config. This allows you to completely hide from employees (developers and QA, for example) really sensitive company information such as payment gateway account login, production SMTP credentials, production db connection strings, etc. There is nothing more dangerous than an angry developer whom you just fired :) Find and read the documentation of the appSettings, pay attention to its "file" attribute.
 
 

Web.config Transformation Syntax for Web Application Project Deployment的更多相关文章

  1. 转:Transform Web.Config when Deploying a Web Application Project

    Introduction One of the really cool features that are integrated with Visual Studio 2010 is Web.Conf ...

  2. 使用Web.Config Transformation配置灵活的配置文件

    发布Asp.net程序的时候,开发环境和发布环境的Web.Config往往不同,比如connectionstring等.如果常常有发布的需求,就需要常常修改web.config文件,这往往是一件非常麻 ...

  3. Web.Config Transformation配置灵活的配置文件

    使用Web.Config Transformation配置灵活的配置文件 发布Asp.net程序的时候,开发环境和发布环境的Web.Config往往不同,比如connectionstring等.如果常 ...

  4. 10 Things ASP.NET Developers Should Know About Web.config Inheritance and Overrides(转)

    10 Things ASP.NET Developers Should Know About Web.config Inheritance and Overrides Wednesday, Janua ...

  5. 关于Web.config的debug和release.config文件

    使用Web.Config Transformation配置灵活的配置文件 发布Asp.net程序的时候,开发环境和发布环境的Web.Config往往不同,比如connectionstring等.如果常 ...

  6. 微软ASP.NET网站部署指南(3):使用Web.Config文件的Transformations

    1. 综述 大多数程序里都会在Web.config里设置參数,而且在部署的时候须要更改. 每次都手工更改这些配置非常乏味,也easy出错. 该章节将会告诉你假设通过自己主动化更新Web.config文 ...

  7. web.config 配置

    一.认识Web.config文件   Web.config 文件是一个xml文本文件,它用来储存 asp.NET Web 应用程序的配置信息(如最常用的设置asp.NET Web 应用程序的身份验证方 ...

  8. ASP.NET,web.config 中SessionState的配置

    web Form 网页是基于HTTP的,它们没有状态, 这意味着它们不知道所有的请求是否来自同一台客户端计算机,网页是受到了破坏,以及是否得到了刷新,这样就可能造成信息的丢失. 于是, 状态管理就成了 ...

  9. 在VisualStudio 2012中通过SmallSharp压缩js及修改web.config

    在项目中加入一个targets文件,取名my.build.targets 在targets文件中加入内容: <?xml version="1.0" encoding=&quo ...

随机推荐

  1. android如何快速查看APK包名和activity

    一.通过ADB命令 1.dos进入 2.输入adb shell登录 3.输入dumpsys package | grep eggs(过滤相关包名) 二.通过日志查看包名() 1.连接设备 2.cmd命 ...

  2. Android Studio 打包时 Signature Version 选择V1还是V2 ?

    只勾选V2会导致 7.0 以下的安卓机出现 INSTALL_PARSE_FAILED_NO_CERTIFICATES 的问题 ,推荐全选. 解决方案一v1和v2的签名使用1)只勾选v1签名并不会影响什 ...

  3. 17.嵌入ace插件

    我们想 在problem-detail上具体显示代码 建一个component 叫 editor 将ace集成上去,算是他的画布吧. 支持各种语言 可以reset  提交写好的代码到server端编译 ...

  4. 学习JS的心路历程-函式(一)

    前几天有间单提到该如何声明函式及在Hositing中会发生什么事,但是函式的奥妙不仅于此. 身为一个使用JS的工程师,我们一定要熟悉函式到比恋人还熟! 这几天将会把函式逐一扒开跟各位一起探讨其中的奥妙 ...

  5. @Component单例与并发(未解决)

    今天用websocket记录连接的个数: 模拟少量请求到服务器端的websocket,@Component默认是单例的,让其注解到MyWebSocket类上: 每次请求过来都是相同的MyWebSock ...

  6. 2017面向对象程序设计(Java) 第4周学习指导及要求(2017.9.14-2017.9.18)

    学习目标 深入理解程序设计中算法与程序的关系: 深入理解java程序设计中类与对象的关系: 理解OO程序设计的第一个特征:封装: 需要掌握基本使用方法的预定义类有:Math类.String类.Arra ...

  7. Linux命令_2

    P42 远程管理 命令 目标 关机/重启 shutdown 查看或配置网卡信息 ifconfig ping 远程登录和复制文件 ssh scp 01.关机/重启 命令: shutdown  选项  时 ...

  8. 1.3.3、CDH 搭建Hadoop在安装之前(端口---CDH组件使用的端口)

    列出的所有端口都是TCP. 在下表中,每个端口的“ 访问要求”列通常是“内部”或“外部”.在此上下文中,“内部”表示端口仅用于组件之间的通信; “外部”表示该端口可用于内部或外部通信. Compone ...

  9. 预览InputFile

    [预览InputFile] 通过input的files属性,可以取到选择的File对象,通过FileReader可以将File对象读取出来. <body> <input type=& ...

  10. sql数据库之多库查询

    连接到数据库服务器gwsps07上,打开查询分析器,如何获取gwrenshi数据库中的数据? 查询语句如下: select * from GWRENSHI.CGC.dbo.PERempms(serve ...