Setting Up SonarLint/SonarAnalyzer.CSharp in .Net Core

Hi all,

This is the current set that we have.

  1. We have a .Net Core 2.2 solution with 7 projects
  2. I am using the SonarLint extension and also downloaded the SonarAnalyzer.Csharp package for all projects from Nuget Package.
  3. I added the ruleset in the solution folder

In the Ruleset, I’m not able to add the SonarAnalyzer.Csharp analyzer in the file. I found a way to reference the projects to use that ruleset(The idea is to have all projects refer to one ruleset). Did I miss some steps? I’m able to do this on .Net Framework projects.

Hi.

You don’t need to install both the SonarLint vsix and the NuGet packages - they are different ways of packaging the same rules (although the vsix does provide some additional functionality). The Microsoft docs explain the differences between packaging rules in vsixes and NuGets.

The UX for rulesets in Visual Studio is different for .NET Core projects (i.e. SDK-style projects) e.g. you can’t configure rulesets through the project properties page.

However, you can manually edit the project files to reference the ruleset file e.g.
<CodeAnalysisRuleSet>..\..\MyRuleset.ruleset</CodeAnalysisRuleSet>
The ruleset will then appear in the Solution Explorer and you should then be able to edit it in the UI.

If you want to reference the same ruleset from every project you could use create a Directory.Build.props file instead of adding the ruleset property to every project.

What do I need to add in the props file?

Just the ruleset property e.g.

<Project>
 <PropertyGroup>
   <CodeAnalysisRuleSet>$(MSBuildThisFileDirectory)MyRuleset.ruleset</CodeAnalysisRuleSet>
 </PropertyGroup>
</Project>

My project isn’t referencing the props file for some reason

Below is my props file. Ruleset and props file is in the solutions folder

<Project>
 <PropertyGroup>
   <CodeAnalysisRuleSet>$(MSBuildProjectFullPath)ruleset.ruleset</CodeAnalysisRuleSet>
 </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="SonarAnalyzer.CSharp" Version="7.15.0.8572">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
    </PackageReference>
  </ItemGroup>
</Project>

Try MSBuildThisFileDirectory instead of MSBuildProjectFullPath - you want the path to be relative to the Directory.Build.props file, not the project file.

That did not work. I ended up settling on the first recommended option where for each csproj file, I’m updating it to reference the ruleset.