Posts Tagged With SonarQube - Musing, Rants & Jumbled Thoughts

Header Photo Credit: Lorenzo Cafaro (Creative Commons Zero License)

Well, it seems the perceived success of my SonarQube ReSharper plugin was it's own downfall. Less than 30 days after it's official release, that plugin, as it exists today, is now officially deprecated. The SonarSource team has taken it upon themselves to completely rewrite ReSharper integration with the next release of what is currently called the ".net ecosystem" plugins (coming this month) and I am bowing out of developing for SonarQube.

And as I was writing this post, I received an email from SonarSource with this:

I didn't want to touch your repository at the time I started this work, because I would indeed have needed to discuss this with you first, and I was under some time pressure.

You also correctly identified that this implies that your plugin is de facto end of lifed.

I am going to have to ask for the removal of the repository, and to prefix your Jira component name by "(Deprecated)".

This will remove any possible confusion between your plugin and the library.

Seems they are more than happy to run me out of town, but want me to hang my own eviction notice -- perhaps as some sort of extra humiliation?

Unfortunately, it is unlikely I can even use the new plugin, as it will not support reuseReport mode. Additionally, SonarSource's stated (and restated) goal is to eventually drop support for ReSharper and all third-party tools, so this is a temporary solution.

While I am in a "wait and see" mode right now to determine if I will even continue utilizing SonarQube at all once these changes go live with v4.2, I will not be providing additional support or fixes for the current sonar-dotnet-resharper plugin.

This makes me very sad -- and angry. But I guess I should have seen this coming, considering just getting the ReSharper plugin approved was like pulling teeth, and then my NUnit integration plugin was killed. Shame on me for not seeing this coming. Or maybe my Java skills are just that bad.

So, that's all for my involvement with the SonarQube ReSharper integration. I appreciate those who helped while it lasted, and hope those of you who are using it are able to continue with the new version.

If you want the details, just take a look at the last two weeks on the SonarQube dev mailing list. There are too many threads to list here.

Personally, I have two other side projects currently active. I'm helping out with the That Conference organization team and I'm working with a couple of friends to write an Azure Cloud plugin for TeamCity.



As of SonarQube v4.0, the server natively supports HTTPS access. The official configuration instructions, however, are not really clear for people who 1) aren't familiar with Java and 2) are running on a Windows server. So in this post, I'm documenting the steps I followed to get SonarQube server up and running with an SSL cert purchased from a signing authority.

Step 1: Create a PKCS#12 Cert File

If you already have a version of your cert that ends with .p12 or .pfx, you can skip this step. Otherwise, you likely have a .cert, .cer or .crt file. You'll need to convert it to PKCS#12 format using the instructions I've provided in a separate post: Converting a SSL Certificate to PKCS#12 Format on Windows

Step 2: Configure SonarQube

Copy the .pfx file you created in Step 1 to the /conf folder of your SonarQube install location. Then open the sonar.properties file in that same folder.

In the "Web" section of the sonar.properties file, you'll need to change the properties as follows:

  • sonar.web.https.port=443
    • This will enable HTTPS access on the port you provide (443 is the standard HTTPS port). If you want to force HTTPS access only, you should also set sonar.web.port=-1 to turn off HTTP access.
  • sonar.web.https.keyPass=changeit (where changeit is the password you provided during the Export Wizard in Step 1)
  • sonar.web.https.keystoreFile=C:/Path/To/Your/SonarQube/conf/exportedCert.pfx
    • Enter the correct path to the .pfx file (hit, Shift-Right-Click the file and choose "Copy as path". Make sure to use forward slashes in your path here, not the standard Windows back-slashes.
  • sonar.web.https.keystoreType=PKCS12

Now, restart your SonarQube server.

If there were issues loading your cert, such as a bad password, you may see entries like this in the /log/sonar log file:

Step 3: Change your default URL

Go to the Settings page for your SonarQube server and in the General section, change the URL to use https://hostname.in.your.cert.file/. This will ensure links generated by the system (such as in emails) point to the https link. Make sure the hostname you use matches your cert!

Enjoy!



If you use TeamCity for your builds and to run your SonarQube analysis, you can add a tab to the TeamCity build results page that includes your SonarQube results.

Here's what the end result will look like. Note the "SonarQube" tab next to the Artifacts tab, which includes a report showing new (by default) issues added in this build.

I'm using TeamCity 8.1 and SonarQube 4.1, but older versions of both should be able to use these same steps with little or no changes. I'm analyzing a C# project using the sonar-runner utility, but if you're using Java, you should be able to follow along too.

Setting this up is actually really easy!

In SonarQube, add the Issues Report plugin. The easiest way to do this is by clicking "Install" on it's entry in the Update Center and restarting the SonarQube service.

Then, on your TeamCity server, modify your Sonar Runner build step to include -Dsonar.issuesReport.html.enable=true

This will cause the Sonar Runner to output an html report into the .sonar/issues-report folder after the SonarQube analysis is completed. The next step is exposing that report in a custom tab, which the TeamCity folks have made very easy. If you're using a version of TeamCity older than 8.1, you'll want to follow that link for alternate instructions.

Now, setup the project artifacts path to include the .sonar\\issues-report folder, like this:

Then, go into the project-level settings (not the build-level settings) and click the "Report Tabs" option. You'll use the Create new report tab button to add a "SonarQube" tab and use the issues-report.html file from artifact you just created as the Start Page (issues-report.zip!issues-report.html if you put it in a zip, like I showed above):

Run a build, and you've got your tab! If you don't see the tab, double-check the artifacts path in the Reports Tab settings.



UPDATE 2/1/2014: After I wrote this initial posting, the team at SonarSource who oversee SonarQube and the .NET plugins replied to me saying they have changed their mind on the need for this plugin, and on Unit Test reporting in general. Going forward, SonarQube will not be reporting unit test results, focusing only on coverage details. As such, this plugin is effectively dead. I do not plan on continuing any work on it at this time.

I've made some decent progress with a new SonarQube plugin, intended to be part of the community "C# Ecosystem" plugin package, which I'm calling the "sonar.dotnet.tests" plugin. The intent of this plugin is to support direct parsing of unit testing/coverage tools' reports instead of relying on Gallio, as the current ecosystem plugins do. The first (and currently only) supported framework is NUnit, allowing you to directly import NUnit test results into SonarQube without going through Gallio (see SONARDOTNT-372).

I posted this email to the SonarQube developers mailing list, but thought I'd also post the information here, so that it's easier to find via search engines and so that people can leave comments without having to subscribe to the mailing list.

If you're interested in taking a look at my work in-progress, you can find my code in the "dotnet-tests-plugin" branch of my GitHub clone of the dotnet repository. Note: I have multiple branches in my repo, so make sure you're looking at the "dotnet-tests-plugin" branch. There is not currently a publicly hosted build of the plugin, so if you want to try it out, you'll need to build it (and the other dotnet plugins in the same repo) yourself.

Some general notes:

  • There is one known open issue: It currently is unable to associate test results to the appropriate classes when the tests are defined in a base class of the test fixture.
  • The plugin utilizes the default SonarQube unit test widget (no need for the separate widget used in the gallio plugin)
  • The plugin is using the org.sonar.api.test classes (TestCase, TestPlan, etc), which required changing the sonar API version to v3.5 (from 3.0). Since 3.7 is the LTS version, I think this should not create too many complaints.
  • I have only implemented the nunit support so far, but it should be pretty straight forward to migrate the mbunit (gallio) parsing logic from the existing gallio plugin, as well as almost all of the coverage report parsing code.
  • The plugin supports only reuseReport and skip modes.

Implementation details:

  • This branch also includes Peter Steven's Pull request for SONARDOTNT-382, which is required for the NUnit support to work.
  • As part of this implementation, I made some changes to the base dotnet plugins:
    • Added a property (sonar.csharp.squid.includeTestSources) to include Test projects when performing squid parsing for c# projects (building out the AST). (Default is false to mirror prior behavior). This allows consumers to lookup file resources for types/members in test classes. This also required changes to the CSharpSquidSensor so that it will run for test projects and be able to lookup files in the test sources tree but not to include the Test files when saving measures, complexity, issues, etc.
    • CSharpResourcesBridge now also indexes methods using their parameter signatures (ex: My.Namespace.MyClass#MethodName(bool, int)) as a second index. This allows callers to lookup methods based on their usages without having to know the line number they are defined at.
      • The current indexing implementation includes the line number in the index key and the doc for DotNetResourceBridge currently says this: /!\\ Do not use for the moment! For the moment, method key ends with ':XXXX', where 'XXXX' is the line number, so this API does not work. TODO: Need to work on that.
      • As such, the changes I made to include a secondary index for methods could be removed and made the primary index instead. This would remove the need for the custom SourceMethod class as well, but would break anyone who has implemented against the current line number based signature. I would appreciate feedback on whether this should be a second index or the primary index.
    • Similar changes would likely be required in the VB.NET plugin, which I don't have access to, so haven't tested/reviewed.
  • New unit test result parsers (such as MSTest and MBUnit/gallio) would need to extend o.s.p.dotnet.tests.parser.DotNetTestResultParser and be added to DotNetTestsSensor.getParsers() at the line that currently says "//TODO: add other parsers here". I would eventually like to refactor this to use dependency injection to discover the parsers, but haven't gotten there yet.

Usage:

For the NUnit parsing, the following properties need to be defined in the project.properties file (or equivalent) :

#
# global flags to enable/disable all parsing. Integration tests have a separate flag.
#
sonar.dotnet.tests.mode=reuseReport
sonar.dotnet.tests.it.mode=skip

#
# each parser will have it's own pair of report path keys (unit and integration):
#
sonar.dotnet.tests.nunit.reports.path=$(SolutionDir)/TestResult*.xml
#sonar.dotnet.tests.nunit.it.reports.path=$(SolutionDir)/AggregateResults.xml

#
# The NUnit parser requires the new c# squid property to be set to true
#
sonar.csharp.squid.includeTestSources=True

As I mentioned, I will be setting this aside for several months as I will be spending my "side project time" working with the That Conference organizers team for That Conference 2014. I would appreciate anyone who could review things as they currently stand and provide any feedback, particularly from the current dotnet plugin maintainers and SourceSource crew.



Update 2014-02-06: The SonarQube .NET ReSharper plugin has been released. See my release announcement.

For those of you following along with the SonarQube ReSharper plugin, here's an update on where things currently stand.

JetBrains released version 8.1 of the ReSharper commandline tools back in early December, so I consider version 1.0 of the plugin to have been "released" around that time... and there are a handful of folks out there using it! However, I was unsuccessful in getting the necessary votes on the SonarQube developers mailing list to get the plugin published to the official Update Center, which would make it uber simple for others to install and use the plugin. I must say, I was quite disappointed that I only managed one "+1" vote of the required three. (For the uninitiated, the rules for getting a plugin officially released require three "+1", or "yes" votes and no "-1" or "no" votes from the existing developers group.) As discussed on the dev mailing list, there's not much incentive for the developers on the list, who are, by definition, Java developers, to try, test and therefore vote on plugins for .NET (or other languages), thus making the bar very high for new developers to make the cut. Generally, the call for a vote stays open for under a week -- in my case, it was open for more than a month before I threw in the towel.

Since then, however, someone else reported an issue with the rule keys used by the plugin (which map directly to the ReSharper rule keys) that cause the Issues Report plugin to fail.

Additionally, several users have asked for the ability to provide a ReSharper dotSettings file while running analysis directly in the plugin.

And I've had a few people contact me to say they'd like to submit pull requests for features they'd like to see as well.

So, I'm planning to work on version 1.1 over the next month or so to fix the rule key issue and add a few of the user-requested features (especially if pull requests are submitted). And at that point, re-try to get the plugin officially hosted in the Update Center. I am putting a somewhat hard limit on a month to get this wrapped up, as my "volunteer" time will be shifting to support That Conference 2014, likely up until the actual conference, Aug 11-13th.



Update 2014-02-06: The SonarQube .NET ReSharper plugin has been released. See my release announcement. Since my last post announcing my SonarQube plugin, it has been accepted into the SonarQube Community plugins, including hosting of documentation, issue tracking, and builds on the SonarSource servers, and moving the code into the SonarCommunity GitHub repository, with a path for eventual inclusion in the SonarQube Update Center for easy distribution to users.

Before I open the gates and push a formal release to the public, I'd like to get some beta testers to use the plugin and work out any rough edges. If you're using SonarQube for your .Net-based projects, I'd love to have you as an early adopter and get your feedback.

Overview



The basic idea is this: The good folks at JetBrains have released a commandline-based tool (called "InspectCode") allowing users to run ReSharper code analysis outside of Visual Studio and generate an XML-based file listing the various issues it detected in your codebase. Oh, and it's free!

I felt this lined up very well with SonarQube, and wrote a SonarQube plugin to (optionally) execute the ReSharper analysis and consume the results, publishing them into SonarQube as Issues, allowing users to take advantage of the management, planning, reporting, etc, features of SonarQube to manage their code quality and technical debt.

What You Can Expect To See

Something like this in Visual Studio: Violation in Visual Studio

Will turn into this in SonarQube: Violation in SonarQube

How To Get Started



For this beta, I'm assuming you're already a SonarQube user and have successfully configured analysis for your .Net solutions. If that's not the case, take a look at my post on setting up SonarQube analysis for C# projects.

The official documentation for installing this plugin can be found on the SonarQube Wiki page for this plugin, which I'm still building out, and will change over time to reflect the current state of things. For now, here's the process:

Download resharper EAP and run a local analysis First, make sure the InspectCode tool is working for you. Download the ReSharper Command Line Tools (they come as a .zip file) and extract them into the folder of your choosing. For the purpose of this posting, I'm assuming you used C:\jetbrains-commandline-tools\.

Open a command prompt and run inspectcode.exe /help. You should see a usage statements printed to the console.

Now change into the folder with your VS Solution file and run the command c:\jetbrains-commandline-tools\inspectcode.exe /output=resharper-results.xml YourSolutionFile.sln

Warning: This may take a very long time to run, possibly a couple hours for very large projects. I would suggest starting with a small project and maybe grabbing some lunch.

One this completes, you should have a resharper-results.xml file in your solution folder, which will look a little like this:

<?xml version="1.0" encoding="utf-8"?>
<!-- Generated by InspectCode 8.0.0.0 -->
<Report ToolsVersion="8.0">
    <Information>
        <Solution>Example.sln</Solution>
        <InspectionScope>
            <Element>Solution</Element>
        </InspectionScope>
    </Information>
    <IssueTypes>
        <IssueType Id="CSharpWarnings::CS0162" Category="Compiler Warnings" Description="CS0162:Code is unreachable" Severity="WARNING" />
        <IssueType Id="CanBeReplacedWithTryCastAndCheckForNull" Category="Potential Code Quality Issues" Description="Type check and direct cast can be replaced with try cast and check for null" Severity="SUGGESTION" />
        <IssueType Id="ClassNeverInstantiated.Global" Category="Potential Code Quality Issues" Description="Class is never instantiated: Non-private accessibility" Severity="SUGGESTION" />
        <!-- ... -->
    </IssueTypes>
    <Issues>
        <Project Name="Example.Application">
            <Issue TypeId="RedundantUsingDirective" File="Example.Application\\Program.cs" Offset="910-943" Line="22" Message="Using directive is not required by the code and can be safely removed" />
            <Issue TypeId="RedundantUsingDirective" File="Example.Application\\Program.cs" Offset="945-963" Line="23" Message="Using directive is not required by the code and can be safely removed" />
            <!-- ... -->
        </Project>
        <Project Name="Example.Core">
            <Issue TypeId="RedundantUsingDirective" File="Example.Core\\IMoney.cs" Offset="895-908" Line="21" Message="Using directive is not required by the code and can be safely removed" />
            <Issue TypeId="RedundantUsingDirective" File="Example.Core\\IMoney.cs" Offset="910-943" Line="22" Message="Using directive is not required by the code and can be safely removed" />
            <!-- ... -->
        </Project>
    </Issues>
</Report>

If that all works, then you're ready to start using the plugin.

  • Download the sonar-dotnet-resharper-plugin from the build server and place it in your SONARQUBE_SERVER_HOME/extensions/plugins folder.
  • Restart your SonarQube service
  • Login to the SonarQube server with an admin account and head over to the Quality Profiles page and select the profile used by your .Net project (this may be the "Sonar way" profile, or one you've created on your own).
  • In the search fields, set the Repository to ReSharper and the Activation to Any and click "Search". You should be presented with a list of approx 650 rules supported by ReSharper's tool. In the upper right corner of the results list is a Bulk Change option. Choose Activate all. This will (immediately) activate all of the ReSharper rules for this profile.
SonarQube Quality Profile Bulk Change
  • Modify your sonar-project.properties file to include the following:
    # ReSharper settings
    sonar.resharper.mode=reuseReport  #leave blank (run ReSharper during sonar analysis), 'skip' to deactive, or 'reuseReport' (recommended) and provide a previously generated results file
    sonar.resharper.report.path=$(SolutionDir)/resharper-results.xml
    #sonar.resharper.installDirectory=c:/jetbrains-commandline-tools  #only needed if running during sonar analysis
    #sonar.resharper.timeoutMinutes=10 #optional, and only if running during sonar analysis
  • Execute sonar-runner and get yourself a cup of coffee. For really big projects this could take half and hour or more.
  • Bask in the glory of your new ReSharper-based Issues in the SonarQube web UI.

A Note About Rule Severity



ReSharper users a four-tier severity (plus a "Do Not Show" option), while SonarQube uses a five-tier system. I have mapped the ReSharper values like this:

ReSharper SonarQube
Error Blocker
Warning Critical
- Major
Suggestion Minor
Hint Info
Do Not Show Info

While some of the ReSharper rules are marked as Do Not Show by default, the plugin maps them to Info so that you can modify their visibility via the Quality Profile. If you want them to not show, disable the rules in the Quality Profile. You can, of course, change any of these levels for any rule using the Quality Profile, and I fully expect most people will want to downgrade a lot of the Critical rules to Major and a lot of Info to be turned off.

Reuse Report vs Run During Analysis



The ReSharper analysis can be very time consuming for large solutions with many projects, sometime taking multiple hours to run if the cache has to be rebuilt, so I would suggest users favor the reuseReport mode when possible. This reduces the number of times the analysis is executed, since running it during the sonar-runner will analyze each project separately, adding significant analysis time, even with heavy caching in the ReSharper tool.

To use the reuseReport option you'll need to use the inspectcode.exe utility to analyze your solution before executing sonar-runner. There are several command line options for the tool, but at minimum, you’ll need this:

inspectcode.exe -o=resharper-results.xml YourSolutionName.sln

Where -o=resharper-results.xml will write the results into the file name you provide. Note: by default (without the -o argument), inspectcode will write the file to the temp directory. You’ll need this file to provide to the plugin.

Analysis times

The amount of time required to run the inspectcode analyzer and import the results into SonarQube can vary based on several factors. Here is some representative data to give you some guidance on how long it will take, based on two actual projects I'm analyzing.

Small Project Larger Project
Lines of Code 27,515 593,979
VS Projects in Solution 10 39
Standalone InspectCode 4min 1hr 24min
Sonar-Runner (ReuseReport) 2min 35min
Sonar-Runner (embedded InspectCode) 11min 2hr 58min

All cases had an existing ReSharper cache. Excludes unsupported project types, such as WiX (installer) projects. Includes only the .NET ReSharper plugin and the base C# plugins (ie: does not include FxCop, Gallio/Unit Tests, etc). Timings are based on running within a TeamCity CI build on a decently powerful server. Obviously, your times will vary and these represent only a guidepost for how much variation can happen between runs.

Known Issues / Limitations



The ReSharper command line tools are fairly new and still have a few kinks to work out. I would suggest always using the newest possible version, including new EAP builds of 8.1 while it is still in development.

Inconsistent results from inspectcode

From one run to the next, you may get a different list of rule violations from ReSharper, even without code changes. This means you will have violations come and go in SonarQube without the underlying issue actually being addressed. In my tests, for a large project like the Windows Azure .net library, I saw a 4% difference (~430 rules delta on ~12,000 total)

See RSRP-390005 - inspectcode provides inconsistent results

Data quality issues in available rules

With the 8.1 EAP builds, JetBrains has added a commandline switch to inspectcode to dump the list of possible issuetypes that could be reported. There are a couple of data issues in that output, which I have worked around in the plugin:

See RSRP-390380 - inspectcode /dumpIssuesTypes includes duplicate entries for "StructuralSearch" and RSRP-390375 - IssueType "InvocationIsSkipped" has undocumented "INFO" severity

"Sonar.UnknownIssueType" Violation

SonarQube requires that the rule database be populated up front, at server start. ReSharper provides a list of possible violation types for their tool via the /dumpIssuesTypes argument, and I've populated the SonarQube rule repository using these values. However, as new versions come out, or you add your own ReSharper plugins to generate new IssueTypes, it’s possible that you will have violations in your code that the plugin did not know about when the server started, so cannot import into SonarQube appropriately. When the plugin comes across one of these, it will write a log statement (to the runner’s log) and generate a "Sonar.UnknownIssueType" violation with instructions on how to add the rule information to the 'ReSharper custom rules' property in the Settings UI. After adding that setting and restarting SonarQube, future analysis runs will support those IssueTypes.

unknown violation setting

Other File Types

While the ReSharper tools support the full .Net stack, including .xaml and other file types, The sonar-dotnet API does not currently support more than one language (C# or VB.net) for a given project. For .xaml and other files, the plugin attempts to report the violation against the file, but they may end up attached to the project instead. In either case, the source code for the .xaml or other unsupported file type will not be imported into SonarQube.

Future plans and release timeline



There are a handful of things I want to see before I release version 1.0, which will go out in the Update Center for general public consumption:

  • ReSharper 8.1 released. I feel like the 8.0 release of the command line tools just isn't viable for use with SonarQube, primarily due to the inconsistent results from one run to the next. This also ensures any breaking changes they make before 8.1 ships are caught and addressed in the plugin. JetBrains has not publicly stated when they thing 8.1 will be released.
  • A handful of early adopters are using the plugin and providing feedback (and are happy with it).
  • I've addressed any high-value tickets in JIRA. I'm using the NETRESHARPER-1.0 release to track things targeted for the public release.

Other features I'm hoping to include, but are not guaranteed:

  • additional configuration settings to modify the inspectcode arguments when running directly. For example: ability to set the cache folder path, disable solution-wide analysis, use of a R# settings file, etc.
  • utilize and document ReSharper plugins in the inspectcode analysis. This is a core feature we're looking to utilize at work to make the dev-time experience match the CI server analysis for company coding standards enforcement. This may "just work", but is dependent on JetBrains releasing the 8.1 SDK nuget packages, which will be "later this autumn".

Disclaimers



I am not associated with JetBrains in any way, aside from being a big fan of many of their products. I have, however, received free licenses to JetBrains products (ReSharper and dotPeek) over the years via raffles over the years at the Chicago Alt.Net Users Group, which is sponsored by JetBrains.



Update 2014-02-06: The SonarQube .NET ReSharper plugin has been released. See my release announcement.

Update - I've moved my plugin into the "SonarQube Forge" and hosting the source, etc, under the SonarCommunity plugins. The information on this page is now stale. See my post SonarQube .Net ReSharper Beta Release for updated information.


I've created a fork of the SonarQube .Net ecosystem plugin's GitHub repository with the purpose of adding a new plugin to support the free JetBrains ReSharper command line code inspection tool. I have full intention of submitting this back to the main SonarQube dotnot plugin repository once it's stabilized, under SONARDOTNT-348.

The fork can be found at https://github.com/johnmwright/sonar-dotnet(no longer hosted here), if you want to try it yourself. I provide no warranty, no guarantee and limited support (I'm just one guy, doing this in 30-minute chucks on my train ride to/from work). I'm using the LGPL v3 license for this code, same as the .Net ecosystem plugins, so the code is open for anyone -- thus the use of GitHub. You are free to modify it yourself, in accordance with the license, and I will accept pull request, should you wish to provide them.

Currently, this plugin only support reusing an existing report, although I will be adding support to run the analysis directly in the next month or so.

Installation Instructions:

Install .NET plugins 2.2-SNAPSHOT

This plugin requires you use the "2.2-SNAPSHOT" builds of the C#/.NET plugins for SonarQube. While you can build these from within my fork, since I'm not actively integrating upstream changes, I suggest you don't use these and pull from the official sources. I will provide some support for the ReSharper plugin, but for the rest of the .NET Ecosystem plugins you should go through the upstream maintainers.

Install ReSharper Command Line Tools and Analyze

To use the new sonar-dotnet-resharper-plugin, you'll need to download the ReSharper command line tools from JetBrains and use the inspectcode.exe utility to analyse your solution. There are several command line options for the tool, but at minimum, you'll need this:

    inspectcode.exe -o=resharper-results.xml YourSolutionName.sln

Where -o=resharper-results.xml will write the results into the file name you provide. Note: by default (without the -o argument), inspectcode will write the file to the temp directory. You'll need this file to provide to my SonarQube plugin.

You can also optionally provide the name of a single project in the solution to limit the analysis to just that project.

Install My Plugin

Install the sonar-dotnet-resharper-plugin into your SonarQube server's \extensions\plugins folder and restart the SonarQube server. In the server's log file, you should see lines like this:

    2013.09.12 22:22:08 INFO  org.sonar.INFO  Register rules [resharper-cs/cs]...
    2013.09.12 22:22:09 INFO  org.sonar.INFO  Register rules [resharper-cs/cs] done: 718 ms
    2013.09.12 22:22:09 INFO  org.sonar.INFO  Register rules [resharper-vbnet/vbnet]...
    2013.09.12 22:22:09 INFO  org.sonar.INFO  Register rules [resharper-vbnet/vbnet] done: 313 ms

Now, add the following to your sonar-project.properties file(s):

    #ReSharper
    sonar.resharper.mode=reuseReport
    sonar.resharper.reports.path=resharper-results.xml

Where the value of sonar.resharper.reports.path is the path to the ReSharper results file relative to each project file. This has the current limitation (same as the FxCop and other sonar-dotnet plugins) of requiring the same relative path be used for all projects. As such, if your filesystem layout has project files at different depths relative to the results file, you will have to copy the results file to each project's folder so that the relative path works.

Right now, for sonar.resharper.mode it only supports reuseReport. In the (near) future I will add the ability to directly run project-level ReSharper analysis instead of reusing a report, which will work much better for people that have differing depth project files.

Modify Your Project's Quality Profile

If you install the sonar-dotnet-resharper-plugin on a clean system where you have not modified the "Sonar way" Quality Profile, then all of the new ReSharper-based rules will be included and enabled immediately. However, if you have modified that profile or have your own custom profile(s), you will need to enable the ReSharper rules for that profile. To do this, go into the SonarQube web UI, click the "Quality Profiles" link in the header bar, and choose the profile you wish to include ReSharper results.

In the filter boxes, choose "ReSharper" in the Repository field and "Any" from the Activation field and submit. I expect you'll see a list of approx 240 rules, all disabled. In the upper right corner of the results list is a "Bulk Change" option. Choose "Activate all". This will (immediately) activate all of the ReSharper rules for this profile.

A Note About Rule Severity

ReSharper users a four-tier severity, while SonarQube uses a five-tier system. I have mapped the ReSharper values like this:

ReSharper SonarQube
Error Blocker
Warning Critical
Major
Suggestion Minor
Hint Info

Note that there is no mapping to the SonarQube 'Major' category, but this is the fall-back/default value SonarUses for a rule, so if you see any (or all) of the ReSharper rules in this tier, please let me know -- there was likely an error importing the rules into your SonarQube installation.

You can, of course, change these levels for any rule using the Quality Profile, and I fully expect most people will want to downgrade a lot of the 'Critical' rules to 'Major'.

Run the sonar-runner!

Now run sonar-runner on your SonarQube project. You should now see your new ReSharper violations in the SonarQube web reports.

Current limitations

SonarQube requires that the rule database be populated up front, at server start. However, ReSharper does not (yet) publish a list of possible violation types for their tool, so the rules in the plugin are only those which I've come across so far in my own C# projects. This means that it's possible, likely even, that you will have violations in your code that the plugin does not know about, so cannot import into SonarQube appropriately. When the plugin comes across one of these, it will write a log statement (to the runner's log). In a future release, it log more information on how to 1) submit that rule back to me for inclusion in a future plugin build and 2) add it to a local supplement file for inclusion in your local rules. For now, if you hit this, you can email me with the block of your ReSharper results block and I'll update the plugin. Also, I have an open request with JetBrains to provide a mechanism to get the full list of violations up front so that this issue will be less likely going forward.

The sonar-dotnet API does not currently work for .xaml files, so any violations in .xaml files are not reported in SonarQube.



NOTE: This post was last updated for SonarQube v4 in Dec 2013. The support for .NET has changed quite a bit since then, so this guide is probably not going to be very useful anymore. Sorry.

In an effort to better understand some of the problematic areas of the C# codebase I work on, I recently setup an instance of the SonarQube code analysis platform. SonarQube is originally written for Java analysis and later added C# support. This posting walks you through my experience attempting to setup, configure and run the analysis.

Note: SonarQube changed it's name from "Sonar" in mid-2013, so older references to this posting may use the old name.

I periodically update this post to reflect changes with newer versions of the tools. Most recent update was 12/18/2013 based on a fresh install of SonarQube v4.0.

I've also written a SonarQube plugin to use ReSharper as a source for quality metrics. Once you have your SonarQube instance up and running for your .NET project, see my post SonarQube .Net ReSharper Beta Release for details on importing ReSharper results into SonarQube.

SonarQube Overview:

So why did I even do this? Once up and running, SonarQube provides some useful metrics for pointing out hotspots in your code that may be making it more difficult to maintain and extend your functionality. Through the web interface, you can drill-down on any of the metrics to the module, class, and method level, including full source code. Some of the metrics provided for each C# project include (screenshots are from the "nemo" demo site mentioned below, my own project, or other sources):

  • General analysis
    • Uses several rule-based static analysis tools
    • Details and statistics, with drill-downs, on rule violations
  • Comments:
    • Percentage of code commented
    • Percentage of public APIs that are (un)documented
  • Duplication:
    • Percentage of code that is duplicated
    • Counts by duplicated lines of code, blocks, files
  • Unit tests:
  • Counts:
    • Lines of code
    • Count of files
    • Count of classes
    • Count of methods

In addition, it will track changes over time, so you can see where issues are increasing/decreasing in your code.

SonarQube is open sourced under the LGPL and free to use, however some of the plugins used to perform the analysis are only commercially available, and in some cases come with steep licensing fees. For this blog, I focus on only freely available (ie: no fees) aspects of the product. Each of the tools I used are also freely available (FxCop, StyleCop, Gendarme, Gallio, OpenCover, MySQL -- all have licenses that allow no-fee usage for most people).

There is a demo site provided by one of the commercial plugin providers to demo the system (including their not-free SQALE plugin) which shows analysis for several open-source Java projects and can give you a feel for the UI and the data that can be provided. Beware -- this includes data from some of the commercial plugins, so don't expect to see everything on that site after following this posting.

You can also reference the [official installation notes])http://docs.codehaus.org/display/SONAR/Setup+and+Upgrade).

General SonarQube Technical Architecture:

Generally, there is a "runner" that consumes the source code and analyzes it via plugins. This information is published to the SonarQube database directly. Before each run, the runner makes a call to the server to download configuration settings stored there, and mashes those with configuration settings stored in a local config file, as well as a project-specific config file.

The SonarQube (web) server pulls the results from the database and provides a UI for reviewing and managing them, as well as a UI for managing configuration settings, user authentication, etc. The server also has it's own config file where you define database settings, user authentication settings, etc.

Step 1: Prerequisites and Assumptions:

This posting assumes you have a working Debug build of your codebase that compiles with no errors and generates .pdb files. You need access to the source code and the output, as they exists at the completion of your build. In my case, I have a CI server (TeamCity for my playground site -- free for small/mid-scale configurations, and Jenkins for our production BI build servers) running and just added another build step at the end to kick-off the SonarQube analysis from the command line.

For many of the plugins (such as FxCop and Gendarme), you'll need to install the .NET Reference Assemblies, which are part of the Win7 SDK for versions of .NET 1.0 through 4.0 and the Win8 SDK for .NET version 4.5. Note that the FxCop installer is included (exclusively) with the Win SDK. Also note that a full Win7 SDK install is several Gigs in size and will take some time to download, so plan accordingly. You only need to install the Reference Assemblies (under the .NET Development header in the installer) which ends up being about 151MB to download and 505MB to install if you use the web-based installer I linked to above.

If you have any Silverlight components in your build, you will need to install the Silverlight SDK for the version of Silverlight you are targeting.

Install the Java JDK Yes, the JDK. It's big and ugly, I know. You're a .Net dev, I know. Do it anyway. Set the JAVA_HOME environment variable to point to the JDK root folder. This should be the “jre” folder – for example, on my machine the value is set like this: JAVA_HOME=C:\\Program Files\\Java\\jre7 Note: You don’t need to install the Source Code component from the installer, which will save you about 500MB of disk space.

If you’re using Gallio for running your unit tests, you’ll also need to make sure .NET2.0 is installed. For newer versions of Windows (Win8 and Win Server 2012), this requires going into “Turn on Windows Features” settings and adding the “.NET Framework 3.5 Features” feature (note: in WinServer 2012, this is part of the Application Server role).

Step 2: The SonarQube Server

Download the SonarQube server. At the time of this (revised) posting, it was version 4.0.

This will give you a .zip file. Decompress it into the location you want; I used C:/sonar-server

For the initial configuration/setup, I'd suggest running it at the command line until you know you have it fully configured. To do that, open a command window and run bin\\windows-x86-64\\StartSonar.bat (or -x86-32 for 32-bit machines) This will run in your current window (no real output, but the command blocks) until you hit Cntl-Z or Cntl-Break. You'll see it pulling down additional packages as needed, such as JRuby, but eventually you'll see something like this, which means it's working:

For SonarQube 3.7:

jvm 1 | 2012-04-27 08:45:44.254:INFO::Started SelectChannelConnector@0.0.0.0:9000

For SonarQube 4.0:

jvm 1    | 2013.12.18 21:04:17 INFO  Web server is started

Once you get things working, I'd suggest installing it as a Windows service. To do this, first register Sonar as a service using the provided script: bin\\windows-x86-64\\InstallNTService.bat (There's an UnInstallNTService.bat script too). Then, start the service from the Windows Services control panel, or using the provided StartNTService.bat script. Personally, I would suggest just configuring it to be Automatic so it will survive reboots, etc.

With my SonarQube install on Windows Server, running the service failed initially, so I used the logs/sonar.log file to troubleshoot and found this error:

Encountered an error running main: java.lang.IllegalStateException: Unable to create file in temporary directory, please check existence of it and permissions: C:\Windows\system32\config\systemprofile\AppData\Local\Temp\

Initially, I just took the lazy route and configured the service to run under my user account instead of a system account, so didn't really "fix" that issue. Update: In a later installs, I had to create the “Temp” folder in the systemprofile\AppData\Local folder and provide security rights to the LOCAL SERVICE user.

The server has a sonar.properties config file that drives some of it's functionality, including which database to use. You can find it in the \conf folder. The only change I made to this file was the port used for web connections (default is 9000 – I changed to 80), and the database (see Step 3) -- but if you want to use the built-in Derby database, no changes are needed.

Step 2a: Verify and Change Password

At this point, you should be able to access the SonarQube server at http://localhost:9000 (or whatever port you set in the sonar.properties file). The default username/password is admin/admin. I would highly recommend changing the admin password at this time. Passwords are changed via the user profile page.

Step 3: The Database

SonarQube server comes with a build-in Derby database. While it is quick to install and easy (and pre-configured), I would suggest moving away from it almost immediately. I had MAJOR performance problems using it. For instance, for my solution of about 400K lines of code (50+ Visual Studio projects), when using the Derby database, it took about 2 hours to perform the analysis, 5 hours if the runner was on a different host. During that time, the server CPU would be pegged at 100% for 5 - 15 minutes per project as the runner reported it's results. Once I moved to a MySQL database, it takes about 20 minutes total.

So, I would suggest downloading and installing the free MySQL Community Edition from Oracle. At the time of this (revised) writing, it was at version 5.6.13.

Once installed, you'll need to create the SonarQube database instance. This is pretty straightforward, but SonarQube provides a script to make it even that much easier. For v3.7, from the SonarQube installation folder, the script is in extras/database/mysql/create_database.sql. It's no longer included in the v4.0 release, but you can find it on the SonarQube GitHub repository. The command to execute the query is at the top of the file. This will generate the SonarQube database instance, as well as grant access from localhost and remotely. The SonarQube schema is created the first time you run the server.

You'll need to configure the SonarQube server to use this db. This is as easy as changing a couple of lines in the sonar.properties config file. Chances are, the lines you want are already in the file (commented out), as samples are there for MySQL, PostgreSQL, Oracle and MS SqlServer. (Note: MS SqlServer is not officially supported, although people on the web have posted ways to get it working. I did not venture down this path).

Update: While getting SonarQube up and running in our production environment, the person doing the work was able to get up and running with MS SqlServer and provided me with this feedback. Note, he was using v.2.13.1, which is newer than what I was using at the time:

I followed the link you had on your page (http://www.sezok.de/sonar/sonar.html) but differed in the following ways:

  • The database must be setup with Case Sensitive and Accent Sensitive rules, so I created the database with collate option SQL_Latin1_General_CP1_CS_AS
  • The jdbc drivers that come bundled with 2.13.1 actually work, and the ones listed in the above link don’t.

For me, I commented out the Derby/H2 lines and used these for my MySQL instance:

#----- MySQL 5.x/6.x
# Comment the embedded database and uncomment the following properties to use MySQL.
# The validation query is optional.
sonar.jdbc.url: jdbc:mysql://localhost:3306/sonar?useUnicode=true&amp;characterEncoding=utf8&amp;rewriteBatchedStatements=true

# Optional properties
#sonar.jdbc.driverClassName: com.mysql.jdbc.Driver
#sonar.jdbc.validationQuery: select 1

Restart the SonarQube server, if it's running.

I should note that there isn't a quick-and-easy way to migrate from the Derby db to another, so expect any data collected in Derby will be lost when you move. I found this page where someone found a way, if you really must try.

Note: at one point, I was getting a com.mysql.jdbc.PacketTooBigException error, so I followed the suggestions here and ran the sql command: SET GLOBAL max_allowed_packet = 1024*1024*14;

Step 3a: Verify and Change password, again

At this point, the SonarQube server should be up and running again, albeit with no data. I would suggest verifying you can reach the server at http://localhost:9000 (or whatever port you used in the sonar.properties file). The user accounts will have reset with the database change, so again I would highly recommend changing the admin password at this time!

Step 4: The Runner

SonarQube was build for Java, so the docs almost all assume you're using Maven. You may be able to get this working with nAnt, but there's an easier route. A small, java-based runner has been created that can be kicked-off from the command line. This is what I used from within my TeamCity and Jenkins builds. There’s also a Jenkins plugin that looks promising, but I haven’t used it.

To use this runner, you will need to do a few things:

  1. Download the runner. At this (revised) writing, the version was 2.3. This will come as a Zip file. Decompress it in an appropriate location. For me, I put it in C:/sonar-runner/
  2. Test that it works. Open a command line to the sonar-runner/bin folder and run sonar-runner -h. This will either show you the usage statement (if things are working fine), or blow up. If it blows up, check you'reJAVA_HOME is set correctly to point at the jre folder.
  3. Once it works, set another environment var: SONAR_RUNNER_HOME to the root installation folder for sonar-runner. (for example: C:/sonar-runner/) This is used when you want to run the sonar runner from a folder other than the /bin folder. (ie: when you run sonar-runner from your source folder).
  4. Change the conf/sonar-runner.properties file. This has general configuration items used by the runner, some of which can be overridden in the project's config file (we'll get to that later). At a minimum, you'll need to set the sonar.host.url to point to where you have your sonar server running, and the database config. For the db, just copy/paste the lines from the sonar.properties file you created in Step 2. Again, example values are provided in the file (commented out) which will likely work just fine. Don't forget to comment out the Derby lines if they exist.

Step 5: The C# Plugins

You'll need to install the "C# Plugins Ecosystem" (ie: The plugins to analyze C# code). Login to the SonarQube website as an Admin user and click the "Settings" link in the upper right-hand corner, then click "Update Center" in the left-hand navigation pane. You should see an "Available Plugins" tab, under which you will find all of the officially supported plugins. Search down the list to find "C#" under the Additional Languages section and click on the "C#" link. You should now see an "Install" button -- click it!

Under the hood, this is installing each of the C# plugins .jar files into the /extensions/plugins folder of your SonarQube server installation folder. You will need to restart the SonarQube service after you place the files for them to be available.

The plugins consist of the following: (as of this writing, which uses v2.1 of the plugins)

  • sonar-dotnet-plugin - .NET Core (support for the .NET-based languages - general API used by other plugins -- required)
  • sonar-csharp-plugin - C# Core (support for parsing C# language -- required)
  • sonar-dotnet-fxcop-plugin - FxCop support (general analysis)
  • sonar-csharp-stylecop-plugin - StyleCop support (formatting analysis)
  • sonar-dotnet-gendarme-plugin - Gendarme support (general analysis)
  • sonar-dotnet-gallio-plugin - Gallio support (unit testing / coverage)
  • sonar-dotnet-ndeps-plugin - NDeps (assembly dependency parsing) (new in v1.3)

Note: If you use VB.NET, there is a separate plugin entry for that, which will reuse several of these plugins.

If you're going to use FxCop, you'll need to install FxCop 10 (the FxCop installer is installed as part of the Win7 SDK install).

If you're going to use StyleCop, you can either use a bundled version included with SonarQube, or install your own.

If you're going to use Gendarme, you can either use a bundled version or install your own.

If you're going to use Gallio, you'll need to install it as well as OpenCover (or you can use NCover, if you have a license). When installing OpenCover, I suggest using the Advanced mode and setting it to install for all users. Also note: Gallio does not support NUnit v2.5.4 or higher, so you’ll either need to update the Gallio plugin or jump to NUnit 2.6 (or other supported version).

Step 6: The sonar-project.properties File

Each Solution will need to have it's own sonar-project.properties file. This file will need to exist in the folder from which you execute the sonar-runner. To make this easy, I would suggest putting the file in the same folder as your .sln file.

The file will have a few sections, which I will describe here.

Important Note: Any folder names in the config file will need to either escape the backslash with another backslash (\\) or use a forward slash (/). I've chosen the latter.

Project Identification:

This section will provide the project key used by the SonarQube server to group analysis results over time, as well as provide a useful name in the UI, etc. This should be unique across projects. The project version can be used to track different branches, etc.

# Project identification
sonar.projectKey=Jwright:DemoApp
sonar.projectVersion=trunk
sonar.projectName=DemoApplication

Then, describe the source code layout. The "sources" field points to the top-level folder where the source code exists. If you're .sln and .csproj files have relative paths internally, then this should be the top-level folder. Assuming you don't have any strange layouts, this will likely be the same folder as your .sln file (which is likely where your .properties file exists), so can just be ".". Additionally, you need to denote that the language is C# using the "cs" value.

# Info required for Sonar 
sonar.sources=.
sonar.language=cs 

C#-specific settings:

Here, you'll need to provide information about where the .sln file is located and where key libraries are located, and which version of .Net you're using.

#Core C# Settings
sonar.dotnet.visualstudio.solution.file=DemoApp.sln
sonar.silverlight.4.mscorlib.location=C:/Program Files (x86)/Reference Assemblies/Microsoft/Framework/Silverlight/v4.0
sonar.dotnet.excludeGeneratedCode=true
sonar.dotnet.4.0.sdk.directory=C:/Windows/Microsoft.NET/Framework/v4.0.30319
sonar.dotnet.version=4.0 

# To prevent any issues while analyzing multiple solutions containing projects with similar keys
# Will be set by default to safe starting at version 2.2: http://jira.codehaus.org/browse/SONARDOTNT-339
sonar.dotnet.key.generation.strategy=safe

Plug-in Specific Sections:

For each plugin, there is a "mode" setting. If blank, then the plugin will run. If you want to skip/not run a plugin, set the mode to "skip".

For Gallio, you can stipulate if you want to use OpenCover (free) or NCover (not free). You can also stipulate the runner mode. I had trouble using anything other than "Local". You will also need to stipulate the naming pattern (regular expressions, I believe) for the Visual Studio projects that include unit tests. You can have multiple patterns, separated by semicolons.

#Gendarme
sonar.gendarme.mode=

# Gallio / Unit Tests
sonar.gallio.mode=
sonar.gallio.coverage.tool=OpenCover
sonar.gallio.runner=Local
sonar.dotnet.visualstudio.testProjectPattern=*UnitTest*;Testing*
sonar.opencover.installDirectory=C:/Program Files (x86)/OpenCover/ 

# FXCop 
sonar.fxcop.mode=skip 

# StyleCop 
sonar.stylecop.mode=

# NDeps
sonar.ndeps.mode=

Step 7: Running an Analysis

From the folder with the sonar-project.properties file, run the command $SONAR_RUNNER_HOME/bin/sonar-runner

You'll see the runner start up, listing some details like the working folder, etc, then it will kick off the source code parsing, then the plugins (such as running the unit tests). If there are any errors, a Java exception will be thrown. Sometimes these contain enough details to troubleshoot, sometimes not, so you may need to run with the -X command line argument to get additional details when errors occur.

One error I run into frequently is UTF-8 Byte Order Mark causing the source file parsing to fail. You will see this in two ways: the files will not end up in the SonarQube web UI and something like the following will show in the runner log:

  07:42:56.938 ERROR - Unable to parse source file : C:\\Users\\...\\CodeFile.cs
  07:42:56.969 ERROR - Source Snippet:
  ---------------
    --> n++using System;
      2 using System.Collections.Generic;
      3 using System.Diagnostics;
      4 using System.IO;
      5 using System.IO.Pipes;
      6 using System
  ---------------

You can fix this by setting the encoding in your sonar-project.properties or the sonar-runner.properties file:

   #----- Default source code encoding
   sonar.sourceEncoding=UTF-8

After a successful run of the analysis, you can see the results in the SonarQube server webpage. Unless you have changed the port in the sonar.properties file, this will be at http://localhost:9000/

The homepage will have a link for each project (the value provided as sonar.projectName), which will take you to the project overview. Clicking on any of the links on the overview page will take you to the drill-down data for that metric.

References:

I used this page to start my journey, in addition to the SonarQube project docs: http://www.ifunky.net/Blog/post/Install-and-Configure-Sonar-on-Windows-2008.aspx

The C# Plugins page: http://docs.codehaus.org/display/SONAR/C-Sharp+Plugins+Ecosystem

The Sonar installation page: http://docs.codehaus.org/display/SONAR/Install+Sonar

Update: The Sonar Source page, complete with mailing lists, issue trackers, etc. http://www.sonarsource.org/support/support

Hope this helps!