.NET · C# · Visual Studio

app.config Transform for non-Web Project (web.config style)

web.config style Transform is very useful. Unfortunately, it’s only available for web project. Here’s how to make it available for non-web project.

1. Unload your project
2. Edit your project file
3. Edit your config entries – note the DependentUpon tag

  <ItemGroup>
    <Content Include="app.config" />
    <Content Include="app.Debug.config">
      <DependentUpon>app.config</DependentUpon>
    </Content>
    <Content Include="app.Test.config">
      <DependentUpon>app.config</DependentUpon>
    </Content>
    <Content Include="app.Release.config">
      <DependentUpon>app.config</DependentUpon>
    </Content>
  </ItemGroup>

4. Add transform task at the bottom of file

<Project>
  ...
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.Tasks.dll" />
  <Target Name="AfterCompile" Condition="exists('app.$(Configuration).config')">
    <!-- Generate transformed app config in the intermediate directory -->
    <TransformXml Source="app.config" Destination="$(IntermediateOutputPath)$(TargetFileName).config" Transform="app.$(Configuration).config" />
    <!-- Force build process to use the transformed configuration file from now on. -->
    <ItemGroup>
      <AppConfigWithTargetPath Remove="app.config" />
      <AppConfigWithTargetPath Include="$(IntermediateOutputPath)$(TargetFileName).config">
        <TargetPath>$(TargetFileName).config</TargetPath>
      </AppConfigWithTargetPath>
    </ItemGroup>
  </Target>
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>

5. Reload your project

Cheers, Sy

Advertisements

3 thoughts on “app.config Transform for non-Web Project (web.config style)

  1. I get the error Error Namespace prefix ‘xdt’ is not defined. My project is a Windows Service. Any advice??

    1. Hi teleco, looks like you’re missing xmlns:xdt=”http://schemas.microsoft.com/XML-Document-Transform” in your configuration tag. Sy

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s