Search code examples
visual-studioconfigapp-configslowcheetahxdt-transform

Transform app.config entries only if a flag in app.debug.config is true


I would like to perform an xdt:Transform when in Debug configuration but only if the value of an entry in app.debug.config is a certain value, lets say true to keep it simple. For example:

App.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <appSettings> 
    <add key="Value.First" value="foo" />
    <add key="Value.Second" value="foo" />
    <add key="Value.Third" value="foo" />
  </appSettings>
</configuration>

App.Debug.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <appSettings>
    <!--Convenient flag to indicate if transform should happen-->
    <add key="Perform.Transform.If.True" value="true" xdt:Transform="Insert" />

    <!--Should only happen if the above is true-->
    <add key="Value.First" value="bar" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" />
    <add key="Value.Second" value="bar" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" />
    <add key="Value.Third" value="bar" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" />
  </appSettings>
</configuration>

I would like all of the Value.* entries in app.config to be transformed only if the key Perform.Transform.If.True is set to true. If it is false nothing should happen. The reason being that sometimes during testing we would like to quickly turn things on and off which are controlled by the config files.

I have seen the options for Locator for things like Match, Conditional, XPath, etc. but none seem to allow for a condition from another entry. Can that be done with slowcheetah/xdt transforms?


Solution

  • Well, found a round-about way using XPath:

     <add
        key="Value.First" 
        value="bar" 
        xdt:Transform="Replace"
        xdt:Locator="XPath(//appSettings/add[@key='Perform.Transform.If.True' and translate(@value, 'ERTU', 'ertu')='true']/../add[@key='Value.First'])" 
    />
    

    If the flag is not true it will fail to resolve the path. The translate makes it case-insensitive.

    Failing to resolve (is false) leads to compile warnings which is annoying but since this is a debug tool we can live with that.