5
votes

I am trying to configure transformation rules for a web.config to create or update a connection string. The rules are simple:

  1. If a connection string with a given name ("MyDatabase") is present, it should not be touched.

  2. If there is no connection string with a given name, it should be inserted.

But I can't figure out if this is possible. If I just specify "add" element in my web.config.transform, it inserts connectionString element even if there is already one with such name. But if I specify xdt:Transform="Replace", then it will be replaced. I've found a good article on the subject, and it lists scenarios Replace,Insert,Delete. But I need "InsertIfNotExists".

Help is appreciated.

2

2 Answers

3
votes

The blog Custom web.config transforms and merges describes extensions Merge and MergeBefore transforms that would insert an element if it's missing but leave the element alone if it's already present.

To use a custom transform, you have to import the relevant namespace in your transformation XML:

<xdt:Import assembly="AppHarbor.TransformTester"
    namespace="AppHarbor.TransformTester.Transforms"/>
0
votes

An alternative solution, if you wish to update an element in the web.config via a config transform and the element is not present, you can simply add an empty element in web.config and configure your web.Release.config like so:

web.config:

<system.web>
<httpModules>
</httpModules>
...

web.Release.config:

<system.web>
<httpModules>
  <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" xdt:Transform="Insert" />
  <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" xdt:Transform="Insert" />
</httpModules>
...

This way, you can merge your new properties into the web config upon deployment!