With the new Visual Studio 2017 out you might have been busy upgrading your .NET Core solutions to the new format and accidentally found out that StyleCop Analyzers stopped working? Automated upgrade will just upgrade projects, however will not adjust Visual Studio 2017 StyleCop Analyzers settings. Therefore, I’ve updated my template’s source code and added this quick guide.
First, you need to upgrade or install StyleCop Analyzers nuget package (as of now the current version is 1.1.0-beta004). Command to get the latest pre-release version:
Install-Package StyleCop.Analyzers -Pre
.NET Core compatibility. In Visual Studio 2017 StyleCop Analyzers work much better compared to Visual Studio 2015, since you get real-time warnings/errors highlight, fix suggestions that work really well together with ReSharper.
I have following settings on:
- Make warnings to be treated as errors (disabled by default).
- Suppress 1701;1702;1705 warnings (enabled by default).
To enable a ruleset that we previously had in “_stylecop” folder in the solution folder, you need to manually edit project file and add following.
<PropertyGroup> <CodeAnalysisRuleSet>$(SolutionDir)\_stylecop\StyleCopeRules.ruleset</CodeAnalysisRuleSet> </PropertyGroup> <ItemGroup> <AdditionalFiles Include="$(SolutionDir)\_stylecop\stylecop.json" Link="stylecop.json" /> </ItemGroup>
This specifies what ruleset to use, and adds a link to StyleCope Analyzers settings file for additional settings. “stylecop.json” could be linked manually using Visual Studio’s UI as well, however applying this change to multiple project files might be easier to copy-paste the code snippet.
In my test solution I have .NET Core application and a library to show how rulesets are shared between projects. My folders and files structure is displayed in the screenshot below.
Important. After quick research I was unable to find how to enable spelling dictionary in StyleCop Analyzers in VS2017, hence “CustomDictionary.xml” file is just a placeholder for now. I will update the post once I find this.
You can easily test if StyleCop Analyzers work by removing method documentation comments and adding extra space after curly braces, and you will see errors highlighted in red right away! See screenshot below.
All in all, just a few small changes and we have StyleCop Analyzers working again in Visual Studio 2017 projects again. Happy coding!
All source code can found on my GitHub.
A previous blog post about Visual Studio 2015 is here.
Seems like Visual Studio 2017 versions prior VS 2017 Preview 2 (15.3.0-pre.2.0+26606.0) may not pick up StyleCop.Analyzers ruleset during development and wrongly highlight code in red but would work just fine during the build.
As Sam mentioned in the comment you need to set an absolute path to the ruleset file to make StyleCop.Analyzers work. As in the code snippet above, you could use $(SolutionDir) macro to achieve this. More macros on MSDN.