The tool :
So everyone knows wonderful tool from Microsoft, named StyleCop. StyleCop is a tool that runs against C# code (not against IL assemblies – already build code) and based on rules saved either per machine, or per project (we will show us how to save them per project) gives you feedback , if you violated some of these rules. StyleCop started on codeplex (MS take on similar portal like github) and currently moved to GitHub – https://github.com/StyleCop. If you see closely, on GitHub we have two projects :
- https://github.com/StyleCop/StyleCop – StyleCop as such and
- https://github.com/StyleCop/StyleCop.ReSharper – plugin for ReSharper tool
We will go down the free path and take a look at first option. There are two plugins I will speak about today :
- StyleCop Visual Studio extension – https://visualstudiogallery.msdn.microsoft.com/5441d959-387f-4cb2-a8c0-9998dd1fa49f – extension for your Visual Studio 2010 – 2017
- StyleCop.MSBuild NuGet package – https://www.nuget.org/packages/StyleCop.MSBuild – NuGet package that will deliver the same results but on the command line at build time.
(please note that in StyleCop repo there is a note about recommendation to use Roslyn based StyleCop from https://github.com/DotNetAnalyzers/StyleCopAnalyzers repo)
So, you can add NuGet StyleCop.MSBuild package and now running msbuild from command line will trigger analysis. Which is what we want on CI server, but not for builds from Visual Studio. You can try to run build from VS and see what happens.
How to turn off StyleCop.MSBuild for VS builds :
After some search on the interwebz I found out, that there is a property StyleCopEnabled in StyleCop.MSBuild.Targets that is set to true if nothing is specified, which we need to set to false as default. So you need to edit your .csproj (or any other .proj file) and insert
in some PropertyGroup.
This will enable you to do following thing :
- run msbuild to trigger just plain old build
- run msbuild /p:StyleCopEnabled=true to pass parameter to msbuild that will do the analysis after the build.
If you guess that the first will be “used” when building from VS and second to get analysis on your CI server, you are right 🙂
And if you questioned yourself, “why not to pass /p:StyleCopEnabled=false” from VS build, then AFAIK from VS also in 2017 we cant just pass parameters to msbuild. Shame, I know.