Monday, October 15, 2012

Install and configure Sonar on Windows 7 for .NET projects

It has been a very long time since I post anything. I apologize for this. I will definitely try to do this more often.
Recently, I have been managing and analyzing code quality metrics using Sonar with C# plugins for .NET projects Sonar, as described on their website, is a quality management platform, dedicated to continuously analyze and measure technical quality from project portfolio to method.  It is extensible and configurable for multiple programming languages.  It provides a report friendly accessible web user interface to manage project analysis results that contain detailed information for code coverage, complexity, coupling, duplication, rules violations for coding standards, etc.  It is definitely a good option to consider for code analysis management.
Even though it’s very easy to follow the steps explained on their site, I have prepared this detailed post on how to install and configure Sonar on Windows 7 OS.  there are a few things to consider for minimizing the effort and prevent troubleshooting too much while installing and configuring Sonar. The main purpose of this post is to get hands on experience with Sonar and have it running in 10 minutes… of course after the pre-requisites are installedJ.
Let’s get down to business with my sample solution named JobSeekerWeb:

1. Software used
2. Considerations
  • Run command prompt (cmd) as Administrator.
  • Sonar uses port 9000 by default; it could be configure to use other available port.  In my example, I configured port 9090 (shown after). Check port availability by running netstat –a in a command prompt.
  • If you’re running 32 bit version of Java JDK, you must also run 32 bit version of Sonar as well (shown after).  Check your current Java JDK version by running java –version in a command prompt.
3. Installation
  1. Make sure to have Java JDK installed. Its default path for 32 bit version is C:\Program Files (x86)\Java\jdk1.6.0_29
  2. Unzip sonar-3.2.zip file. I used this path C:\Sonar
  3. Unzip sonar-runner-2.0.zip file. I used the Sonar's folder C:\Sonar\Sonar-runner-2.0
  4. Unzip the CSharpPluginsEcosystem-1.4.zip file into your Sonar’s plugins folder C:\Sonar\extensions\plugins
  5. Install FxCop 1.36. Its default installation folder is C:\Program Files (x86)\Microsoft FxCop 1.36
  6. Install Gallio. Its default installation folder is C:\Program Files\Gallio
  7. Install OpenCover to gather coverage statistics for your app. Its default installation folder is C:\Program Files (x86)\OpenCover
4. Configuration

Note: .properties files can be edited by any text editor like Notepad or Notepad++. I prefer to use Notepad++, it helps to read these files better.
  1. Edit Sonar configuration file (sonar.properties).  Path C:\Sonar\conf
    Remove
    the # sign of the following line and assign port number. I used port 9090 (view image).

  2. Edit sonar-runner configuration file (sonar-runner.properties).  Path C:\Sonar\sonar-runner-2.0\conf
    Remove
    the # sign of the following two lines and assign host and port configured in sonar.properties.  The same for the encoding at the end (view image).
  3. Add or Edit two new environment variables %JAVA_HOME% and %SONAR_RUNNER_HOME%.  Also Edit %PATH% variable to add Sonar-Runner path (view image).

    To open the environment variables dialog box:
    Right click > Computer > click Properties > click Advanced system settings > tap Advance > click button Environment Variables

    Note
    : Notice that I’m using the same paths previously highlighted above.
  4. Create a file: sonar-project.properties and configure it (view image).  Save this file in the same folder of your solution (.sln file).  The path for my sample solution is C:\Workspaces\JobSeekerWeb





    Text of above screen shot:

    # Project identification 
    sonar.projectKey=JS:JobSeekerWeb
    sonar.projectVersion=1.0
    sonar.projectName=Job Seeker Web
      
    # Info required for Sonar 
    sonar.sources=. 
    sonar.language=cs 
      
    #Core C# Settings 
    sonar.dotnet.visualstudio.solution.file=JobSeekerWeb.sln 
    sonar.dotnet.4.0.sdk.directory=C:/WIndows/Microsoft.NET/Framework/v4.0.30319
    sonar.dotnet.version=4.0
    sonar.donet.visualstudio.testProjectPattern=*UnitTests*;*test*;*Test*
    sonar.fxcop.installDirectory=C:/Program Files (x86)/Microsoft FxCop 1.36
    sonar.gallio.installDirectory=C:/Program Files/Gallio
    sonar.opencover.installDirectory=C:/Program Files (x86)/OpenCover
    sonar.gallio.coverage.tool=OpenCover
    sonar.gallio.runner=IsolatedProcess
    sonar.gallio.timeoutMinutes=60
    sonar.fxcop.assemblyDependencyDirectories=c:/Program Files (x86)/Microsoft ASP.NET/ASP.NET MVC 3/Assemblies,C:/Program Files (x86)/Microsoft Visual Studio 10.0/Common7/IDE/PublicAssemblies,c:/Program Files (x86)/Microsoft ASP.NET/ASP.NET Web Pages/v1.0/Assemblies

    # Exclusions Settings
    sonar.skippedModules=UnitTests


    Note: Notice that I’m using the same paths previously highlighted above.
5. Running Sonar and Getting Analysis Reports
  1. Find 32 bit version of Sonar.  Path C:\Sonar\bin\windows-x86-32and start Sonar Service by opening a command prompt and running StartSonar (view image).  You should get an output like the image below.

    Note
    : It could also be install as a service by running InstallNTService and then StartNTService.  If it doesn’t work just configure the service manually by changing the default user to Network Service.
  2. My Sonar's page is http://localhost:9090 as configured previously in the sonar.properties file.
  3. Execute Sonar-Runner against the sample solution.  Start up command prompt from where the solution (.sln) and sonar-project.properties files are located and start sonar-runner (view image).  After it finishes refresh the Sonar 's page (previous step).  You should see the project analysis result listed.



    Note
    : It could take a couple of minutes. All depends on the size of the solution, number of projects, tests to run, etc.
  4. View dashboard with Sonar Code Analysis project output.  Click on project name “Job Seeker Web” which was previously assigned in the sonar-project.properties file on line sonar.projectName=Job Seeker Web
  5. Login to Sonar by clicking Log in link on the top right of the page. The default user and password is admin as left in the sonar.properties file.  Once loged in you have other options to configured and extend.
6. Summary
We have successfully installed and configured Sonar and Sonar-Runner on Windows 7 OS for C# solution with its default configuration and embedded database.  
 
Here are some features I would recommend you try:
1.   Configure another database, such as Oracle, SQL Server, MySQL, etc. to store analysis output.
2.   Access Sonar service remotely other than localhost.  The sonar-runner needs to be local, but not the service. 
3.   Modify rules template for FxCop.
4.   Configure Gallio differently than default.
5.   Switch coverage engine, try NCover for example.
6.   Activate Sonar’s support for integration tests feature.
7.   Configure Sonar to be part of your deployment.
If you want more information and details about Sonar follow the link: http://docs.codehaus.org/display/SONAR/Documentation.
Thanks for reading, I really hope you find this helpful.

23 comments:

  1. Its as if you read my thoughts! You appear to understand a great deal relating to this, as if you authored it inside it or something like that. I believe you could use a couple of photos they are driving the content home a little, but apart from that, this really is great blog. An excellent read. I'll certainly return.

    ReplyDelete
  2. What timing! Two days before I try to get sonar running on a Windows 7 install (with Jenkins)! How did you know I was about to do this?!

    Thanks!

    ReplyDelete
  3. Thank your for the feedback. I'm glad is useful for you guys.

    ReplyDelete
  4. I had some trouble getting code coverage results into sonar when the sonar-runner was run from Jenkins. When run manually, I got the results, but Jenkins results would not show up. The sonar-runner would report that no assembly was found after the unit tests were run.

    To solve this, I made the jenkins service run under a user account, rather than local system.

    ReplyDelete
    Replies
    1. I am looking for some informatin on integrating sonar with Visual Studio 2012, any inputs will be of great help.

      Thanks

      Delete
  5. I WAS FORGETING THE STEP ABOUT THE JAVA ENVIROMENT VARIABLE, THANKS VERY MUCH!!

    ReplyDelete
  6. Hi,

    I have placed the sonar-project.properties in the .sln folder,but still on running sonar runner it shows sonnar runner needs projectKey,projectVersion,projectName. Could you please help me?

    ReplyDelete
  7. Hi,
    could you provide me some explanation about: fxcop, opencover, gallio and what is their purpose to be used in sonar???
    I'm new in this product and I didn't found a good explanation about it, it will be better to hear from expert.

    ReplyDelete
  8. Excellent! it was very helpful, thanks for sharing your knowledge.

    ReplyDelete
  9. Hi, I do all steps needed, but after running the command sonar-runner, i do refresh to the web page (http://localhost:9090) but nothing happened :(
    Any help please?

    Is it required to install visual studio in the same environment.???

    ReplyDelete
  10. Hello Friends ..

    I commented'm starting to implement sonar in projects.NET, I'm in the process of testing, and I find this error when running sonar-runner.

    Very interesting this blog .. Keep well!

    Greetings from Argentina.

    error Screen:

    http://subefotos.com/ver/?3568ae97b156771ccbba57f2e35a2994o.png

    ReplyDelete
  11. I did as it is but I wasnt able execute c# sharp projects.I could execute only java projects please help me.

    ReplyDelete
  12. Hello!
    Can you help me? I try analise with SonarQube my ASP.NET Web Site project. And when i started sonar-runner i get exception:
    ERROR: Error during Sonar runner execution
    org.sonar.runner.impl.RunnerException: Unable to execute Sonar
    at org.sonar.runner.impl.BatchLauncher$1.delegateExecution(BatchLauncher
    .java:91)
    at org.sonar.runner.impl.BatchLauncher$1.run(BatchLauncher.java:75)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.sonar.runner.impl.BatchLauncher.doExecute(BatchLauncher.java:69)
    at org.sonar.runner.impl.BatchLauncher.execute(BatchLauncher.java:50)
    at org.sonar.runner.api.EmbeddedRunner.doExecute(EmbeddedRunner.java:102
    )
    at org.sonar.runner.api.Runner.execute(Runner.java:90)
    at org.sonar.runner.Main.executeTask(Main.java:70)
    at org.sonar.runner.Main.execute(Main.java:59)
    at org.sonar.runner.Main.main(Main.java:41)
    Caused by: java.lang.IllegalStateException: You must define the following mandat
    ory properties for 'Unknown': sonar.projectKey, sonar.projectName, sonar.project
    Version, sonar.sources

    What i'm doing wrong?

    ReplyDelete
    Replies
    1. Search for sonar-properties file and how to configure it.

      Delete
  13. Hi,
    I used Sonar 3.6 instead of Sonar 3.2 and remaining i followed same as per this article but i could not get the project name in the projects lists.

    ReplyDelete
  14. hi,,
    please help me, igot this error:


    INFO: ------------------------------------------------------------------------
    INFO: EXECUTION FAILURE
    INFO: ------------------------------------------------------------------------
    Total time: 6.214s
    Final Memory: 19M/362M
    INFO: ------------------------------------------------------------------------
    ERROR: Error during Sonar runner execution
    ERROR: Unable to execute Sonar
    ERROR: Caused by: java.io.IOException: Cannot run program "C:\Windows\System32\W
    indowsMicrosoft.NETFrameworkv4.0.30319\MSBuild.exe": CreateProcess error=2, The
    system cannot find the file specified
    ERROR: Caused by: Cannot run program "C:\Windows\System32\WindowsMicrosoft.NETFr
    ameworkv4.0.30319\MSBuild.exe": CreateProcess error=2, The system cannot find th
    e file specified
    ERROR: Caused by: CreateProcess error=2, The system cannot find the file specifi
    ed
    ERROR:
    ERROR: To see the full stack trace of the errors, re-run SonarQube Runner with t
    he -e switch.
    ERROR: Re-run SonarQube Runner using the -X switch to enable full debug logging.

    ReplyDelete
  15. Hi ..
    Thank you so much .. that's a very good tuto !
    For me I have a java/jee project How to do it ?

    ReplyDelete
  16. Hi..
    I used SonarQube 4.3 and SonarQube Runner 2.4. The Quality Profiles when I navigate to localhost:9000 (thats where I configured it to be) shows only Java profile. How do I add C# profile to analyse .Net projects / solutions? Any help to configure it is appreciated. Thanks.

    ReplyDelete
  17. When I see reports on sonar server, it shows 0 lines of code?
    Please help, I've followed all the steps. I am using Windows 7 -64 bit OS

    ReplyDelete
    Replies
    1. Please check the versions being run and your configuration #Core C# Settings mentioned above. I used the same environment for the example.

      Delete
    2. Thank you Alexandro for quick response and the helpful article.
      I just started all oever again with latest versions and it worked

      Delete
  18. I'm using SonarQube 5.3 and Sonar Runner on TeamCity for C# project, how can i do so that Code coverage show content on Coverage tab

    ReplyDelete