Adding FxCop rules to Sonarqube

In my posts about custom FxCop rules I mention creating rules for FxCop. In this post I’ll explain how to add the created rules to Sonarqube.

First of all, the assembly needs to be put on the server somewhere. The location doesn’t really matter too much, as long as it’s accessible for Sonarqube. In my case I just dropped it into the default FxCop Rules folder, which is located by default in C:\Program Files (x86)\Microsoft FxCop 10.0\Rules.

After that, Sonarqube needs to be told about the rules as well. The XML is actually fairly similar to the XML file we create for the FxCop rules in the first place.

<?xml version="1.0" encoding="utf-8" ?>
<rules>
    <rule key="Classname">
        <name><![CDATA[Name for the rule]]></name>
        <configKey><![CDATA[Classname@Location\Of\Assembly\Assemblyname.dll]]></configKey>
        <description><![CDATA[Rule description]]></description>
    </rule>
</rules>

So, to take the example of the GetItemUsingID rule, the XML could look something like this:

<?xml version="1.0" encoding="utf-8" ?>
<rules>
    <rule key="GetItemUsingID">
        <name><![CDATA[Enforce calling the GetItem method using an ID]]></name>
        <configKey><![CDATA[GetItemUsingID@$(FxCopDir)\Rules\Sitecore.FxCop.dll]]></configKey>
        <description><!CDATA[Use GUIDS where possible instead of path / name. This will improve performance as well as prevent code breaking if content is renamed or moved in the content tree.]]></description>
    </rule>
</rules>

When the XML has been created it has to be put in the FxCop custom rules field in Sonarqube. You can get to this by going to Sonarqube -> Settings -> Configuration -> .NET FxCop:
Sonarqube configuration settings

Before the rules can be used Sonarqube does have to be restarted. Then we can go into Sonarqube -> Settings -> Quality Profiles. Select the active code profile, and go to the inactive FxCop rules. Select the newly added rules to be active, and we’re all done.

I guess this would also be a good time to mention the source code of the 11 rules I initially created is available on Bitbucket and Sitecore’s marketplace, so feel free to create a fork and add your own rules!

If you just want to use the rules, that’s possible as well, just go to the download page on Bitbucket and download the zipfile. The zipfile contains a dll of the initial release at the moment, although I hope to steadily add new rules to the project.

Advertisements