我正在尝试使用Teamcity服务器上的MSBUILD更改web.config中的connectionString。以前我在调用它的目标中使用了该属性:
<PropertyGroup>
<UpdateWebConfigCode>
<![CDATA[
public static void ScriptMain()
{
XmlDocument wcXml = new XmlDocument();
wcXml.Load(@"TCM.MVC.UI\Web.config");
XmlElement root = wcXml.DocumentElement;
XmlNodeList connList = root.SelectNodes("//connectionStrings/add");
XmlElement elem;
foreach (XmlNode node in connList)
{
elem = (XmlElement)node;
switch (elem.GetAttribute("name"))
{
case "TCMBaseConnectionString":
elem.SetAttribute("connectionString", "Data Source=server-name;Initial Catalog=TCMCentral;User ID=user;Password=something");
break;
}
}
wcXml.Save(@"TCM.MVC.UI\Web.config");
}
]]>
</UpdateWebConfigCode>
然后我会在目标中调用它:
<Target Name="UpdateWebConfig">
<Script Language="C#" Code="$(UpdateWebConfigCode)" Imports="System.Xml" />
</Target>
但是这仍然会引发错误。我意识到这可能有点过时但找不到任何替代它....任何建议?
答案 0 :(得分:5)
我最终使用了MSBuildCommunityTasks XmlUpdate属性。以下是我的目标:
<Target Name="UpdateWebConfig">
<XmlUpdate XmlFileName="C:\TCM.NET\Current\TCM.MVC.UI\web.config" XPath="configuration/connectionStrings/add[@name='TCMBaseConnectionString']/@connectionString" Value="Data Source=server-name;Initial Catalog=TCMCentral;User ID=user;Password=something" />
</Target>
这对我很有用。
答案 1 :(得分:3)
我使用自定义任务执行此操作,该任务与您的代码完全相同,但MSBuidl变为:
<UpdateConnectionString ConfigFile ="path\to\web.config"
ConnectionStringName="MyConnectionStringName"
ConnectionString="connection-string-here"/>
此类任务的代码是
public class UpdateConnectionString : Task
{
[Required]
public string ConfigFile { get; set; }
[Required]
public string ConnectionStringName { get; set; }
[Required]
public string ConnectionString { get; set; }
public override bool Execute()
{
try
{
var fi = new FileInfo(ConfigFile);
if(!fi.Exists)
{
Log.LogError("File {0} does not exist");
return false;
}
fi.IsReadOnly = false;
XDocument doc = XDocument.Load(ConfigFile);
var confignode = doc.Descendants("configuration").Single();
var connectionStrings = confignode.Descendants("connectionStrings").SingleOrDefault();
if(connectionStrings == null)
{
connectionStrings = new XElement("connectionStrings");
confignode.Add(connectionStrings);
}
var connectionElement = connectionStrings.Descendants("add").SingleOrDefault(
e => e.Attribute("name") != null &&
string.Compare(e.Attribute("name").Value, ConnectionStringName,
StringComparison.OrdinalIgnoreCase) == 0);
if (connectionElement == null)
{
connectionElement = new XElement("add", new XAttribute("name", ConnectionStringName));
connectionStrings.Add(connectionElement);
}
connectionElement.SetAttributeValue("connectionString", ConnectionString);
doc.Save(ConfigFile);
}
catch (Exception ex)
{
Log.LogErrorFromException(ex, true);
return false;
}
return true;
}
}
请注意,如果连接字符串不存在,此代码也会添加连接字符串,这可能比您现在需要的更复杂。