Monday, October 5, 2015

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
1
2
3
4
5
6
7
8
9
10
11
12
<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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<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

No comments:

Find a cool free stuff everyday

Giveaway of the Day

Hiren Bharadwa's Posts

DotNetJalps