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.
The solution has two projects. The “server” project is ASP.NET Core and the “core” project is just .NET Core
I might as well be ambitious, so I’ve added several analysis packages and I’ll worry about the consequences later.
Full solution analysis can be enabled in Visual Studio under Options. This is to see all errors going on.
As the code exists, it’s getting hit with 418 warnings right off the bat.
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.")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "CA1707:Identifiers should not contain underscores", Justification = "My naming convention is purposeful.")]
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.
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:Element must begin with upper-case letter", Justification = "Lot of places to fix this.")]
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.