Book Image

Instant StyleCop Code Analysis How-to

By : Franck Leveque
Book Image

Instant StyleCop Code Analysis How-to

By: Franck Leveque

Overview of this book

In medium-sized and big projects, coding conventions are defined in order to improve readability and maintainability for all the developers of the team. Stylecop analyzes your code and detects coding rule violations during all the phases of your project lifecycle. Instant StyleCop Code Analysis How-to allows you to take advantage of the features of Stylecop by guiding you through how to configure it, how to integrate it in your project environment, and finally how to personalize it in order to fit your needs. Instant StyleCop Code Analysis How-to teaches you how to configure and integrate Stylecop in your programming environment. The book will do this by showing you how to configure Stylecop on the developers IDE to the continuous integration server. You will also learn how to customize Stylecop to fit your coding style by creating new rules as well as learning how to personalize your headers file. You will also see how to embed it in your own tools, using as an example the creation of a real time analysis add-on for Monodevelop. With Instant StyleCop Code Analysis How-to, you will have an overview of all the required steps to successfully integrate your programming team and enforce your own coding rules.
Table of Contents (7 chapters)

Integrating StyleCop analysis results in Jenkins/Hudson (Intermediate)


In this recipe we will see how to build and display StyleCop errors in Jenkins/Hudson jobs. To do so, we will need to see how to configure the Jenkins job with a full analysis of the C# files in order to display the technical debt of the project. As we want it to diminish, we will also set in the job an automatic recording of the last number of violations. Finally, we will return an error if we add any violations when compared to the previous build.

Getting ready

For this recipe, you will need to have:

  • StyleCop 4.7 installed with the option MSBuild integration checked

  • A Subversion server

  • A working Jenkins server including:

    • The MSBuild plug in for Jenkins

    • The Violation plug in for Jenkins

  • A C# project followed in a subversion repository.

How to do it...

  1. The first step is to build a working build script for your project. All solutions have their advantages and drawbacks. I will use MSBuild in this recipe. The only difference here will be that I won't separate files on a project basis but take the "whole" solution:

    <?xml version="1.0" encoding="utf-8" ?>
    <Project DefaultTargets="StyleCop" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
      <UsingTask TaskName="StyleCopTask" AssemblyFile="$(MSBuildExtensionsPath)\..\StyleCop 4.7\StyleCop.dll" />
      <PropertyGroup>
        <!-- Set a default value of 1000000 as maximum Stylecop violations found -->
        <StyleCopMaxViolationCount>1000000</StyleCopMaxViolationCount>
      </PropertyGroup>
      <Target Name="StyleCop">
    
        <!-- Get last violation count from file if exists -->
        <ReadLinesFromFile Condition="Exists('violationCount.txt')" File="violationCount.txt">
          <Output TaskParameter="Lines" PropertyName="StyleCopMaxViolationCount" />
        </ReadLinesFromFile>
    
        <!-- Create a collection of files to scan -->
        <CreateItem Include=".\**\*.cs">
          <Output TaskParameter="Include" ItemName="StyleCopFiles" />
        </CreateItem>
    
        <!-- Launch Stylecop task itself -->
        <StyleCopTask
          ProjectFullPath="$(MSBuildProjectFile)"
          SourceFiles="@(StyleCopFiles)"
          ForceFullAnalysis="true"
          TreatErrorsAsWarnings="true"
          OutputFile="StyleCopReport.xml"
          CacheResults="true"
          OverrideSettingsFile= "StylecopCustomRule\Settings.Stylecop"
          MaxViolationCount="$(StyleCopMaxViolationCount)">
    
          <!-- Set the returned number of violation -->
          <Output TaskParameter="ViolationCount" PropertyName="StyleCopViolationCount" />
        </StyleCopTask>
    
        <!-- Write number of violation founds in last build -->
        <WriteLinesToFile File="violationCount.txt" Lines="$(StyleCopViolationCount)" Overwrite="true" />
      </Target>
    </Project>
  2. After that, we prepare the files that will be scanned by the StyleCop engine and we launch the StyleCop task on it. We redirect the current number of violations to the StyleCopViolationCount property.

  3. Finally, we write the result in the violationsCount.txt file to find out the level of technical debt remaining. This is done with the WriteLinesToFile element.

  4. Now that we have our build script for our job, let's see how to use it with Jenkins. First, we have to create the Jenkins job itself. We will create a Build a free-style software project. After that, we have to set how the subversion repository will be accessed, as shown in the following screenshot:

    We also set it to check for changes on the subversion repository every 15 minutes.

    Then, we have to launch our MSBuild script using the MSBuild task. The task is quite simple to configure and lets you fill in three fields:

    • MSBuild Version: You need to select one of the MSBuild versions you configured in Jenkins (Jenkins | Manage Jenkins | Configure System)

    • MSBuild Build File: Here we will provide the Stylecop.proj file we previously made

    • Command Line Arguments: In our case, we don't have any to provide, but it might be useful when you have multiple targets in your MSBuild file

  5. Finally we have to configure the display of StyleCop errors. This were we will use the violation plugin of Jenkins. It permits the display of multiple quality tools' results on the same graphic. In order to make it work, you have to provide an XML file containing the violations.

    As you can see in the preceding screenshot, Jenkins is again quite simple to configure. After providing the XML filename for StyleCop, you have to fix thresholds to build health and the maximum number of violations you want to display in the detail screen of each file in violation.

How it works...

In the first part of the How to do it… section, we presented a build script. Let's explain what it does:

First, as we don't use the premade MSBuild integration, we have to declare in which assembly the StyleCop task is defined and how we will call it. This is achieved through the use of the UsingTask element.

Then we try to retrieve the previous count of violations and set the maximum number of violations that are acceptable at this stage of our project. This is the role of the ReadLinesFromFile element, which reads the content of a file. As we added a condition to ascertain the existence of the violationsCount.txt file, it will only be executed if the file exists. We redirect the output to the property StyleCopMaxViolationCount.

After that we have configured the Jenkins job to follow our project with StyleCop. We have configured some strict rules to ensure nobody will add new violations over time, and with the violation plugin and the way we addressed StyleCop, we are able to follow the technical debt of the project regarding StyleCop violations in the Violations page.

A summary of each file is also present and if we click on one of them, we will be able to follow the violations of the file.

Tip

How to address multiple projects with their own StyleCop settings

As far as I know, this is the limit of the MSBuild StyleCop task. When I need to address multiple projects with their own settings, I generally switch to StyleCopCmd using NAnt or a simple batch script and process the stylecop-report.violations.xml file with an XSLT to get the number of violations.