Adding static analysis to an existing C# project.

I have an existing project on GitHub that is a MSSQL Exporter for Prometheus. Today I want to add .NET static analysis packages to improve code quality on this existing project.

I'm going to start with the .NET Analyzers and then add on others as appropriate.

Existing project structure

The solution has two projects. The "server" project is ASP.NET Core and the "core" project is just .NET Core

Solution Explorer

Adding Analyzers

I might as well be ambitious, so I've added several analysis packages and I'll worry about the consequences later.

  • Microsoft.CodeQuality.Analyzers
  • Microsoft.NetCore.Analyzers
  • SecurityCodeScan
  • StyleCop.Analyzers

Installed Packages

Full Solution Analysis

Full solution analysis can be enabled in Visual Studio under Options. This is to see all errors going on.

Full Solution Analysis

Error Codes

As the code exists, it's getting hit with 418 warnings right off the bat.

Error Codes

One fix at a time

SA1200

Using directive must appear within a namespace declaration

I don't like this one, so I'm just going to suppress it by adding the follow to a file named "GlobalSuppression.cs".

[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.OrderingRules", "SA1200:Using directives must be placed correctly", Justification = "I don't like this.")]

SA1208

Reorder Redirects

CA1707

Name Underscores

[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "CA1707:Identifiers should not contain underscores", Justification = "My naming convention is purposeful.")]

SA1300

It's not wrong. I should have used proper namespace casing. Another on the suppression list. I'm not nearly as concerned about naming conventions as I am code quality.

Naming convention

[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:Element must begin with upper-case letter", Justification = "Lot of places to fix this.")]

Error Codes summary

I took the liberty of skipping ahead and not going error by error, which would be tedious.

The VAST majority of my issues were with naming conventions, mostly by StyleCop "SA" prefix. As it turns out, it seems that I sometimes default to pseudo-C++ naming conventions in some ways which is a problem.

What I didn't find was obvious security flaws. If this were a large code-base, fixing a lot of formatting issues might have been a pain.