Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Target BeforeBuild doesn't work in csproj

I'm trying to use the target event "BeforeBuild" in .csproj (vs2017), but it's not working. Someone would know what is wrong:

<Project DefaultTargets="BeforeBuild" Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>

  <Target Name="BeforeBuild">
    <Message Text="Test123"></Message>
  </Target>
</Project>

The expected result is a message: Test123 on output.

[]s

like image 667
Glauber Gasparotto Avatar asked Jun 20 '17 03:06

Glauber Gasparotto


2 Answers

BeforeBuild dosen't working in csproj

That because Before/AfterTarget in csproj gets overridden by SDKs target file.

if you're using the new Sdk attribute on the Project element, it's not possible to put a target definition after the default .targets import. This can lead to targets that people put in their project files unexpectedly not running, with no indication why unless you examine the log file and see the message that the target has been overridden.

dsplaisted have filed Microsoft/msbuild#1680 for this issue. As a workaround, you can do the following:

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.1</TargetFramework>
    <PreBuildEvent />

  </PropertyGroup>
  <Import Project="Sdk.props" Sdk="Microsoft.NET.Sdk" />
  <Import Project="Sdk.targets" Sdk="Microsoft.NET.Sdk" />

  <Target Name="BeforeBuild">
    <Message Text="Test123"></Message>
  </Target>

Or:

  <Target Name="test" BeforeTargets="Build">
    <Message Text="Test123" />
  </Target>
like image 161
Leo Liu-MSFT Avatar answered Oct 24 '22 04:10

Leo Liu-MSFT


From the official docs:

Warning

Be sure to use different names than the predefined targets listed in the table in the previous section (for example, we named the custom build target here CustomAfterBuild, not AfterBuild), since those predefined targets are overridden by the SDK import which also defines them. You don't see the import of the target file that overrides those targets, but it is implicitly added to the end of the project file when you use the Sdk attribute method of referencing an SDK.

like image 1
Emmanuel Avatar answered Oct 24 '22 05:10

Emmanuel