Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call my script before all the builds for only once in a multi-targeting project

I would like to run my powershell script for only one time before the build process. In my mind this should be easily done, simply calling the script before the PreBuildEvent would be OK. Well, it does work for normal projects.

However, for multi-targeting projects,the script would be called multiple times before each build for all the targeting framework.

Here is my project file, in which I target at 3 frameworks:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFrameworks>net40;net45;netstandard1.4</TargetFrameworks>
    <AssemblyName>abc</AssemblyName>
    <Version>1.0.0</Version>
  </PropertyGroup>
  <ItemGroup Condition=" '$(TargetFramework)' == 'net40' ">
    <Reference Include="System" />
    <Reference Include="Microsoft.CSharp" />
  </ItemGroup>
  <ItemGroup Condition=" '$(TargetFramework)' == 'net45' ">
    <Reference Include="System" />
    <Reference Include="Microsoft.CSharp" />
  </ItemGroup>
  <Target Name="PreBuild" BeforeTargets="PreBuildEvent">
    <Exec Command="PowerShell -ExecutionPolicy Unrestricted -File script.ps1/>
  </Target>
</Project>

And when I build the project, the PreBuild target was called 3 times.

So far, I have tried:

1) At first, I guessed that the builds was going in a sequence, so I added a condition to my target:

  <Target Name="PreBuild" BeforeTargets="PreBuildEvent" Condition=" '$(TargetFramework)' == 'net40' ">
    <Exec Command="PowerShell -ExecutionPolicy Unrestricted -File script.ps1/>
  </Target>

, which did not work. It turned out that mutli-target builds were going concurrently. Sometimes, net40's build would be later, so my script was not running before all the builds.

2) And then I tried to use environment variables to do the synchronization, but it did not work out, either. It seemed the builds didn’t share the environment variables.

3) At last, I turned to other MSBuild targets to replace the PreBuildEvent, but I have found no proper one.

So how do I call my scripts before all the builds and for only once in a multi-targeting project. Please help me.

like image 630
Jaren Duan Avatar asked Apr 28 '18 01:04

Jaren Duan


1 Answers

You can hook in your target into the multi-targeting msbuild target that will call the TargetFramework-specific builds like this:

  <PropertyGroup>
    <TargetFrameworks>netstandard2.0;netstandard1.4</TargetFrameworks>
  </PropertyGroup>

  <Target Name="OuterPreBuild" BeforeTargets="DispatchToInnerBuilds">
    <Message Importance="high" Text="Outer before build" />
  </Target>

</Project>

In this case BeforeTargets="Build" Condition="'$(IsCrossTargetingBuild)' == 'true'" will not work because the multi-targeting Build target depends on the "inner projects" being built already.

like image 171
Martin Ullrich Avatar answered Oct 17 '22 08:10

Martin Ullrich