Conditionally excluding projects from analysis not working with dotnet build

We are trying to conditionally exclude projects from analysis as we don’t want to analyze common projects in are part of multiple solutions. We could easily achieve conditional analysis by following article Advanced SonarQube Scanner for MSBuild configuration. Please refer Explicitly associating an MSBuild project with a SonarQube project section in above mentioned article.
Conditional analysis is working fine with msbuild.exe but not working with dotnet.exe. We think this is happening because ImportBefore targets are not getting loaded in case of dotnet.exe.
Following are the steps we have performed.

  • Saved targets file with content given below at C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Microsoft.Common.targets\ImportBefore

      <Project xmlns="">
      <PropertyGroup Condition=" $(SQProjectKey) != '' AND $(SonarQubeExclude) == '' ">		
      	<SonarQubeExclude Condition=" $(SQProjectKey) != $(TargetSQProjectKey) " >true</SonarQubeExclude>
  • Added following in csproj file.
    <PropertyGroup><TargetSQProjectKey>Key1</TargetSQProjectKey> </PropertyGroup>

  • Start analysis by running following
    SonarScanner.MSBuild.exe begin /k:"Key1"

  • Run the build.
    dotnet msbuild my.sln -property:SQProjectKey=Key1

  • End analysis
    SonarScanner.MSBuild.exe end

Please note conditional analysis works as expected if we change command used in Run the build to msbuild.exe my.sln /p:SQProjectKey=Key1

How do we solve this problem? We don’t want to use msbuild.exe .net core projects.

That’s almost certainly the case. You’ve installed your target file under the instance of MSBuild installed with VS i.e. in a per-instance location.

The dotnet SDK will have installed its own copy of MSBuild in another location, and it will be searching there for the ImportBefore directory.

A better solution would be to place your targets file in a per-user location e.g. %LocalAppData%\Microsoft\MSBuild\Current\Microsoft.Common.targets\ImportBefore for MSBuild v16+. That location will be checked by all instances of MSBuild 16+, whether you trigger the build using msbuild.exe or dotnet.

Thank you. We will test this out. Feel free to close the issue.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.