Search code examples
c#sonarqubevisual-studio-2019sonarlintmicrosoft.codeanalysis

Merge SonarAnalyzer.CSharp and the Microsoft.CodeAnalysis rulesets


We run a SonarQube in our company. We also installed the SonarLint for Visual Studio 2019 extension.

If I now connect a solution to the SonarQube, a file named "{MySolution}csharp.ruleset" is created. Inside are 5 nodes: "Managed Binary Analysis", "Microsoft.CodeAnalysis.CSharp", "Microsoft.CodeAnalysis.CSharp.Features", "Microsoft.CodeAnalysis.Features" and finally "SonarAnalyser.CSharp".

The project now is analysed using all of these rulesets. When I change one of these rules it is changed in my file, but not on the SonarQube server. When I change something on the SonarQube and "reload" the rules from there, the standard settings for the first 4 nodes are resetted and the now set rules inside SonarQube are inside the SonarAnalyzer.CSharp.

My question is: "How can I change some of these Microsoft rules and tell SonarQube to use these rules company wide and not only until I reload the rules from SonarQube? Is it maybe possible to set these rules as SonarAnalyzer rules (merge them) or can we set these rules parted from the normal analyzing? Or, what would make the most sense, can we say SonarQube to just actualize the SonarAnalyzer.CSharp ruleset and don't touch the other ones?"


Solution

  • If I now connect a solution to the SonarQube, a file named "{MySolution}csharp.ruleset" is created. Inside are 5 nodes: "Managed Binary Analysis",...

    I'm guessing you're opening the ruleset file in VS and using the VS editor. If you open the generated ruleset file with a text editor you'll see it only contains one "node" for the SonarAnalyzer rules.

    The VS editor is showing the other four "nodes" for built-in rules that are enabled by default. When you change any of the default settings, VS is saving those changes to ruleset file generated by SonarLint.

    You can achieve what you want as follows:

    1. add a new ruleset file imports the SonarLint-generated file e.g.
    <?xml version="1.0" encoding="utf-8"?>
    <RuleSet Name="Corporate ruleset" ToolsVersion="17.0">
      <!-- Assumes this file is in the same folder as the solution file -->
      <Include Path=".sonarlint\sonarlint-visualstudiocsharp.ruleset" Action="Default" />
    </RuleSet>
    
    1. change your MSBuild projects so that the CodeAnalysisRuleSet property points to this new ruleset file rather than the SonarLint-generated ruleset.

    Now, when you edit the settings for the non-Sonar rules in the VS editor, the changes will be saved to your new ruleset file.

    To change the Sonar rules settings, you would modify your Quality Profile in SonarQube, and tell SonarLint to regenerate it's ruleset file.

    FYI this wiki page describes what changes SonarLint for Visual Studio is making to your projects, and how you can customise them.