Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude Generated Code from C# SONAR Analysis

Tags:

c#

sonarqube

So in VS2013 we have an option of "Suppress Results from generated Code(Managed only)"

Do we have a similar option when performing analysis via SONAR ?

The below code reports violations when the above option is unchecked but I don't see any option in SONAR to make use of the above option. I did try the Sonar.dotnet.excludeGeneratedCode = true option, but doesn't seem to make any difference.

    public IEnumerable<string> YieldTest()
    {
        foreach(var num in Enumerable.Range(100, 100))
            yield return string.Format("{0}", num);
    }
like image 290
PankajH Avatar asked Oct 30 '22 20:10

PankajH


1 Answers

The MSBuild SonarQube Runner (at least in versions 1.0 and 1.0.1) always forces the "Suppress Results from generated Code(Managed only)" flag to be checked when FxCop is launched during the build. See SonarQube.Integration.targets#L342

You can verify this behavior in your build logs, by looking at the command launched during the RunCodeAnalysis: phase:

RunCodeAnalysis:
  Running Code Analysis...
  C:\Program Files (x86)\Microsoft Visual Studio 14.0\Team Tools\Static Analysis Tools\FxCop\FxCopCmd.exe 
  /outputCulture:1033
  /out:"bin\Debug\ConsoleApplication1.exe.CodeAnalysisLog.xml" /file:"bin\Debug\ConsoleApplication1.exe" /ruleSet:"=C:\Users\dinesh\Desktop\tmp\ConsoleApplication1\.sonarqube\conf\\SonarQubeFxCop-cs.ruleset"
  [... references ...]
  /rulesetdirectory:"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Team Tools\Static Analysis Tools\\Rule Sets"
  /rule:"-C:\Program Files (x86)\Microsoft Visual Studio 14.0\Team Tools\Static Analysis Tools\FxCop\\Rules"
  /searchgac /ignoreinvalidtargets /forceoutput /successfile **/ignoregeneratedcode** /saveMessagesToReport:Active /timeout:120 /reportMissingIndirectAssemblies

You should see the /ignoregeneratedcode being passed to FxCopCmd.exe.

Now, only FxCop rules will be suppressed by this flag. StyleCop and ReSharper rules for example will not understand this flag and will still report on that method.

FYI, it seems that FxCop excludes this method because of the presence of the yield statement: The C# compiler generates quite complex IL code in the assembly for this statement. FxCop analyzes assemblies (and not the source code), which is why it has to treat the yield statement as generated code.

So, in SonarQube, you should not see an issue for CA1305, regardless of whether or not you checked the "Suppress Results from generated Code(Managed only)" on your project.

like image 60
Dinesh Bolkensteyn Avatar answered Nov 13 '22 19:11

Dinesh Bolkensteyn