1
votes

We are planning on making a c# script to automate the copying of rewrite rules from one web.config to another. We have multiple web.config's for each customer, and we have some general rewrite rules that sometimes need to be changed. The general rewrite rules have a unique prefix that identifies them as a general rule (and not customer-specific).

We're wondering if it's possible to copy rules from one web.config to another with C#. Just reading the rewrite url/match url from one config to write it to the other may not always do the job; it amy happen that we sometimes need to add conditions as well, for example.

Are there any ways to do this? We would like to automate it as much as possible. I am not the best at c#, but I would imagine it might be possible to read the entire rule off one file and paste it in the other? Or might it be better to just parse both the web.config files via XMLReader and then copy the rules over?

1
Is this a 'build-time' change? Why not use config transformations?Davin Tryon
No - this is post-deployment, and for the matter, the webapplication running on the websites is coded in ColdFusion 10 - so we are not using Visual Studio anyways to create this application.Deniz Zoeteman
Consider XML/Config includes.Aron
If you aren't that great at C# and the app is a coldfusion one wouldn't it be simpler for you to read the xml in your native language? The web.config is just an XML file so you can read it as such.rtpHarry
I would assume that c# can do what I want a lot better than ColdFusion can. And I am not that bad at c# that I can't code in it; I'm just unfamiliar with anything regarding XML or the ServerManager class in c#.Deniz Zoeteman

1 Answers

0
votes

I was able to figure it out myself, by using XML instead of the ServerManager class. This does pretty much what I want.

XmlDocument doc1 = new XmlDocument();
doc1.Load(@"web.new.config");

XmlDocument doc2 = new XmlDocument();
doc2.Load(@"web.config");

XmlNode rules = doc2.SelectSingleNode("/configuration/system.webServer/rewrite/rules");
XmlNodeList baserules = doc2.SelectNodes("/configuration/system.webServer/rewrite/rules/rule[contains(@name, 'GenericPrefix')]");

XmlNodeList ruleList = doc1.SelectNodes("/configuration/system.webServer/rewrite/rules/rule[contains(@name, 'GenericPrefix')]");

foreach(XmlNode baseruleOld in baserules)
{
    baseruleOld.ParentNode.RemoveChild(baseruleOld);
}

foreach(XmlNode rule in ruleList)
{
    XmlNode tocopynode = doc2.ImportNode(rule, true);
    rules.AppendChild(tocopynode);
}

doc2.Save("web.config");