Search code examples
msbuildcsprojmsbuild-task

Multiple UsingTask in csprojfile


I have two files that I want to configure by environment: App.config and ApplicationInsights.config. I have created the files App.Debug.config and ApplicationINsights.Debug.config and added the following tasks to the csproj file:

<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Web\Microsoft.Web.Publishing.Tasks.dll" />
<Target Name="AfterCompile" Condition="exists('app.$(Configuration).config')">
  <TransformXml Source="app.config" Destination="$(IntermediateOutputPath)$(TargetFileName).config" Transform="app.$(Configuration).config" />
  <ItemGroup>
    <AppConfigWithTargetPath Remove="app.config" />
    <AppConfigWithTargetPath Include="$(IntermediateOutputPath)$(TargetFileName).config">
      <TargetPath>$(TargetFileName).config</TargetPath>
    </AppConfigWithTargetPath>
  </ItemGroup>
</Target>
<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Web\Microsoft.Web.Publishing.Tasks.dll" />
<Target Name="AfterCompile" Condition="exists('ApplicationInsights.$(Configuration).config')">
  <Message Text="Transforming app insights config file to $(OutputPath)\ApplicationInsights.config" Importance="high" />
  <TransformXml Source="ApplicationInsights.config" Transform="ApplicationInsights.$(Configuration).config" Destination="$(OutputPath)\ApplicationInsights.config" />
</Target>

Both tasks work when they are the only task in the file, but when both are included only the second transform is executed. I have tried giving the tasks different Names, but to no avail. What can I do to get both tasks to run?


Solution

  • You have to give the two tasks different Names and then hook into the existing AfterCompile target:

    <Target Name="SomeUniqueName1" AfterTargets="AfterCompile" …>
      …
    </Target>
    <Target Name="SomeUniqueName2" AfterTargets="AfterCompile" …>
      …
    </Target>
    

    The <UsingTask> only needs to be there once to define the imported TransformXml task.