Search code examples
c#.netmsbuildslowcheetahxdt-transform

Transform app.config for 3 different environment


I need to be able to transform my app.config file using msbuild. I can transform the file if it is called app.DEBUG.config or app.Release.config, but I cannot if I add one called app.PROD.config.

Using regular XDT transforms msbuild recognizes different web.config files if I select a different PublishProfile

 msbuild path.to.project.csproj Configuration=Release PublishProfile=DEV

Apparently app.config does not work with this same setup. I can always create a specific build configuration for a DEV.config setup but it seems useless to have a separate build confirm for one app. A hacky way to do so is to just copy the correct app.config per environment POST-BUILD.

I've attempted to use the SlowCheetah plugin, but this only seems to transform the default DEBUG and RELEASE config files, which is not appropriate since I have more than two environments. If I indeed am using this wrong, please let me know what parameter I should pass at to msbuild to choose my app.DEV.config.

The expected result would be that msbuild would transform the app.config according to the transform that is customized called app.DEV.config or the one customized for app.PROD.config. I would expect that there is a parameter that I can pass to msbuild that would allow me to use the Release configuration but a transform with a different name per environment.


Solution

  • This is what I use for this scenario:

    <?xml version="1.0" encoding="utf-8"?>
    <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    
      <!-- This target will run right before you run your app in Visual Studio -->
      <Target Name="UpdateWebConfigBeforeRun" BeforeTargets="Build">
        <Message Text="Configuration: $(Configuration) update from web.template.$(Configuration).config"/>
        <TransformXml Source="web.template.config"
                  Transform="web.template.$(Configuration).config"
                  Destination="web.config" />
        </Target>
    
      <!-- Exclude the config template files from the created package -->
      <Target Name="ExcludeCustomConfigTransformFiles" BeforeTargets="ExcludeFilesFromPackage">
        <ItemGroup>
          <ExcludeFromPackageFiles Include="web.template.config;web.template.*.config"/>
        </ItemGroup>
        <Message Text="ExcludeFromPackageFiles: @(ExcludeFromPackageFiles)" Importance="high"/>
      </Target>
    </Project>
    

    I have the following setup:

    web.template.config
        - web.template.debug.config
        - web.template.production.config
        - web.template.release.config etc
    

    Should work cross pc without the need for extra plugins etc. In your scenario, you need to edit the contents to say app. instead of web.