42

有谁知道是否有办法“转换”值的特定部分而不是替换整个值或属性?

例如,我有几个 appSettings 条目,它们为不同的 Web 服务指定了 Urls。这些条目在开发环境中与生产环境略有不同。有些比其他的不那么微不足道

<!-- DEV ENTRY -->
<appSettings>
 <add key="serviceName1_WebsService_Url" value="http://wsServiceName1.dev.domain.com/v1.2.3.4/entryPoint.asmx" />
 <add key="serviceName2_WebsService_Url" value="http://ma1-lab.lab1.domain.com/v1.2.3.4/entryPoint.asmx" />
</appSettings>

<!-- PROD ENTRY -->
<appSettings>
 <add key="serviceName1_WebsService_Url" value="http://wsServiceName1.prod.domain.com/v1.2.3.4/entryPoint.asmx" />
 <add key="serviceName2_WebsService_Url" value="http://ws.ServiceName2.domain.com/v1.2.3.4/entryPoint.asmx" />
</appSettings>

请注意,在第一个条目中,唯一的区别是“.dev”与“.prod”。在第二个条目上,子域不同:“ma1-lab.lab1”来自“ws.ServiceName2”

到目前为止,我知道我可以在 Web.Release.Config 中做这样的事情:

<add xdt:Locator="Match(key)" xdt:Transform="SetAttributes(value)" key="serviceName1_WebsService_Url" value="http://wsServiceName1.prod.domain.com/v1.2.3.4/entryPoint.asmx" />
<add xdt:Locator="Match(key)" xdt:Transform="SetAttributes(value)" key="serviceName2_WebsService_Url" value="http://ws.ServiceName2.domain.com/v1.2.3.4/entryPoint.asmx" />

但是,每次更新该 web 服务的版本时,我都必须更新 Web.Release.Config,这违背了简化 web.config 更新的目的。

我知道我也可以将该 URL 拆分为不同的部分并独立更新它们,但我宁愿将它全部集中在一个键中。

我查看了可用的 web.config 转换,但似乎没有什么适合我想要完成的任务。

这些是我用作参考的网站:

Vishal Joshi 的博客MSDN 帮助Channel9 视频

任何帮助将非常感激!

-D

4

2 回答 2

69

As a matter of fact you can do this, but it is not as easy as you might think. You can create your own config transformation. I have just written a very detailed blog post at http://sedodream.com/2010/09/09/ExtendingXMLWebconfigConfigTransformation.aspx regarding this. But here are the hightlights:

  • Create Class Library project
  • Reference Web.Publishing.Tasks.dll (under %Program Files (x86)%MSBuild\Microsoft\VisualStudio\v10.0\Web folder)
  • Extend Microsoft.Web.Publishing.Tasks.Transform class
  • Implement the Apply() method
  • Place the assembly in a well known location
  • Use xdt:Import to make the new transform available
  • Use transform

Here is the class I created to do this replace

namespace CustomTransformType
{
    using System;
    using System.Text.RegularExpressions;
    using System.Xml;
    using Microsoft.Web.Publishing.Tasks;

    public class AttributeRegexReplace : Transform
    {
        private string pattern;
        private string replacement;
        private string attributeName;

        protected string AttributeName
        {
            get
            {
                if (this.attributeName == null)
                {
                    this.attributeName = this.GetArgumentValue("Attribute");
                }
                return this.attributeName;
            }
        }
        protected string Pattern
        {
            get
            {
                if (this.pattern == null)
                {
                    this.pattern = this.GetArgumentValue("Pattern");
                }

                return pattern;
            }
        }

        protected string Replacement
        {
            get
            {
                if (this.replacement == null)
                {
                    this.replacement = this.GetArgumentValue("Replacement");
                }

                return replacement;
            }
        }

        protected string GetArgumentValue(string name)
        {
            // this extracts a value from the arguments provided
            if (string.IsNullOrWhiteSpace(name)) 
            { throw new ArgumentNullException("name"); }

            string result = null;
            if (this.Arguments != null && this.Arguments.Count > 0)
            {
                foreach (string arg in this.Arguments)
                {
                    if (!string.IsNullOrWhiteSpace(arg))
                    {
                        string trimmedArg = arg.Trim();
                        if (trimmedArg.ToUpperInvariant().StartsWith(name.ToUpperInvariant()))
                        {
                            int start = arg.IndexOf('\'');
                            int last = arg.LastIndexOf('\'');
                            if (start <= 0 || last <= 0 || last <= 0)
                            {
                                throw new ArgumentException("Expected two ['] characters");
                            }

                            string value = trimmedArg.Substring(start, last - start);
                            if (value != null)
                            {
                                // remove any leading or trailing '
                                value = value.Trim().TrimStart('\'').TrimStart('\'');
                            }
                            result = value;
                        }
                    }
                }
            }
            return result;
        }

        protected override void Apply()
        {
            foreach (XmlAttribute att in this.TargetNode.Attributes)
            {
                if (string.Compare(att.Name, this.AttributeName, StringComparison.InvariantCultureIgnoreCase) == 0)
                {
                    // get current value, perform the Regex
                    att.Value = Regex.Replace(att.Value, this.Pattern, this.Replacement);
                }
            }
        }
    }
}

Here is web.config

<?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="one" value="one"/>
    <add key="two" value="partial-replace-here-end"/>
    <add key="three" value="three here"/>
  </appSettings>
</configuration>

Here is my config transform file

<?xml version="1.0"?>

<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">

  <xdt:Import path="C:\Program Files (x86)\MSBuild\Custom\CustomTransformType.dll"
              namespace="CustomTransformType" />

  <appSettings>
    <add key="one" value="one-replaced" 
         xdt:Transform="Replace" 
         xdt:Locator="Match(key)" />
    <add key="two" value="two-replaced" 
         xdt:Transform="AttributeRegexReplace(Attribute='value', Pattern='here',Replacement='REPLACED')" 
         xdt:Locator="Match(key)"/>
  </appSettings>
</configuration>

Here is the result after transformation

<?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="one" value="one-replaced"/>
    <add key="two" value="partial-replace-REPLACED-end"/>
    <add key="three" value="three here"/>
  </appSettings>
</configuration>
于 2010-09-09T06:05:47.697 回答
3

Just as an update, if you're using Visual Studio 2013, you should reference %Program Files (x86)%MSBuild\Microsoft\VisualStudio\v12.0\Web\Microsoft.Web.XmlTransform.dll instead.

于 2014-09-30T15:18:30.737 回答