Wednesday, June 10, 2015

Configure StyleCop with MSBuild to treat Warnings as Errors

We can easily configure StyleCop with MSBuild to make warnings appear as errors with the help of StyleCop.MSBuild NuGet package.

First go to Package Manager Console and install it with following command.

Install-Package StyleCop.MSBuild
Then unload your project and open the project file to modify it.

Now you have to add "StyleCopTreatErrorsAsWarnings" property inside "PropertyGroup" tag as below.
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
  <ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them.  For more information, see The missing file is {0}.</ErrorText>
<Error Condition="!Exists('..\packages\StyleCop.MSBuild.\build\StyleCop.MSBuild.Targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\StyleCop.MSBuild.\build\StyleCop.MSBuild.Targets'))" />
Almost done, but sometimes auto generated files gives errors when we build the project, to overcome that we need to modify "Settings.StyleCop" file.

Go to project folder and inside that you can find folder called "packages". It contains StyleCop files and inside "tools" folder you can find that setting file. You can open it with a test editor.

Now you can add new value to GeneratedFileFilters as bellow to ignore those generated files.
<Parser ParserId="StyleCop.CSharp.CsParser">
 <CollectionProperty Name="GeneratedFileFilters">
Now reload your project and try to build your project. You will be able to see that all the warnings appear as errors.


Post a Comment