Using web.config transform to conditionally update an element

transformation, web-config

Solution

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"/>

Problem

I am trying to configure transformation rules for a web.config to create or update a connection string. The rules are simple: If a connection string with a given name ("MyDatabase") is present, it should not be touched. 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.

Original source