SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube...

54

Transcript of SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube...

Page 1: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,
Page 2: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

1. Introduction2. The MIT License3. Prequisites4. Installation and Configuration5. Analyze .NET Projects From The Command Line6. Analyze .NET Projects From Team Foundation Server 2013 and 20157. Additional Configurations8. Appendix 1: Upgrading from v0.9 of the SonarQube MSBuild Runner9. Appendix 2: Configuring the MSBuild SonarQube Runner

10. Appendix 3: Advanced MSBuild SonarQube Runner configuration11. Conclusion

Table of Contents

SonarQube Setup Guide for .NET users

2

Page 3: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

“SonarSource products generate process-level benefits, such as decreasing software development risk, raising software quality andimproving team productivity” .

This guide aims to provide insightful and practical guidance around install ing and configuring the SonarQube™ (previously known as“Sonar”) platform for the analysis of C# and VB.NET projects.

Technical Debt has many causes: business pressures to release early with uncompleted features, software architecture does not allowfor adaptation to changing business needs, inadequate testing and documentation, isolation of changes requiring future merging ofthe changes, and lack of scheduling for refactoring. Paying down on the debt is the only debt reduction strategy.

As we continue ongoing development, the cost of paying down on the technical debt will increase, as does the cost of fixing a buglater in the development cycle. In theory, paying down technical debt is easy if you simply complete the uncompleted work. However,knowing what technical debt exists or what to track can be challenging. Enter SonarQube and Team Foundation Serv er.

SonarQube is an open source platform providing continuous inspection of your code quality. Through integration with TeamFoundation Server and SonarQube you will be empowered to continuously inspect the technical debt, manage the debt, and paydown on the debt.

The following are the details of getting the analysis of a .NET project in place either integrated in an existing deployment of TeamFoundation Server or in a standalone command line way using the MSBuild SonarQube Runner.

>> NOTE >> For more information on SonarQube, please refer to Technical Debt and Evaluate your technical debt with Sonar.

Introduction

SonarQube Setup Guide for .NET users

3Introduction

Page 4: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

Copyright (c) 2015 SonarSource SA and Microsoft Corporation

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation fi les (the"Software"), to deal in the Software without restriction, including without l imitation the rights to use, copy, modify, merge, publish,distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject tothe following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOTLIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. INNO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THESOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

The MIT License (MIT)

SonarQube Setup Guide for .NET users

4The MIT License

Page 5: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

At the time of this writing, the current version of SonarQube, v5.1, had the following requirements.

A Java runtime is required for SonarQube to run. Supported JVMs:

Java (Oracle JRE 7 or greater or OpenJDK 7 or greater).

Regardless of which database solution you choose, it must be set to UTF-8, language set to English, and collation to CS (casesensitive) and AS (accent sensitive).

Figure – Database prerequisites

For the best SonarQube experience ensure to enable JavaScript in your web browser. Supported web browsers:

Prerequisites

Java

Database

Web Browser

SonarQube Setup Guide for .NET users

5Prequisites

Page 6: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

Figure – Web browser prerequisites

At least 1GB RAMDisk space requirements vary dependent upon the size and number of projects you wish to analyze using SonarQube. As a pointof reference, Nemo, the public instance of SonarQube, currently analyzes over 15 mill ion lines of source code, which includesfour years of history. Nemo is currently using about 10GB of disk space.SonarQube relies on intensive hard drive I/O for indexing purposes. You should install SonarQube on the most performant harddrive you have at your disposal for best results.

SonarQube assumes that all of the source fi les have the same fi le encoding. Currently, the MSBuild SonarQube Runner expect this tobe UTF-8. Non-compliance will result in incorrect analysis and display when viewed in the SonarQube portal (for example whendril l ing down to view the source associated with an issue).

>> NOTE >> For the most up to date information on SonarQube requirements, check out the requirements.

Hardware

File Encoding

SonarQube Setup Guide for .NET users

6Prequisites

Page 7: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

All TFS Services, SQL Server and SonarQube, including Sonar Runner and Build Controller) hosted on a single computer.Suitable for research, dogfooding and demonstration of entire end-to-end workflow on one machine.

>> NOTE >> In this guide, we will demonstrate the installation and configurations using Brian Keller's VM, with all componentsinstalled on one box.

TFS Services and SQL Server are hosted on a single computer and SonarQube (all components) on a separate machine.Suitable for evaluation in production or near-production environments.

Refer to System requirements for Team Foundation Server and the TFS Planning, Disaster Avoidance and Recovery, and TFS onAzure IaaS Guide for information on hardware and capacity planning recommendations for your Team Foundation Serverenvironment.

While preparing a Virtual Machine that will host SonarQube database, portal and/or Runner workloads take into account the followingguidance:

For production servers it is recommended to use Fixed Sized disks (instead of dynamic ones); you must estimate accordingly to setapart the right amount of disk space as required.For production servers it is recommended NOT to use dynamic assigned memory as this may decrease overall performance in aproduction setup; a realistic estimate should be made, monitor and adjusted accordingly.Follow SQL Server best practices while setting the SonarQube database, especially in respect of tempdb as per the usageexpected by SonarQube:

Prefer fast disk for tempdb fi le storage.Distribute storage in equally sized data fi les (starting at 1/2 fi le per physical processor and up to 8 fi les).Monitor and size tempdb fi le storage accordingly.Plan for a big size of tempdb; approximately 10-12 times SonarQube database size.

Prefer usage of Windows Server 64 bits, preferably Windows Server 2012 R2.Java JRE (or Java SDK) that supports Server mode and configure SonarQube to support it: editing sonar.properties fi le forsonar.web.javaOpts=-serv er and uncommenting the line by removing the # at the start of the line. More details on Install ingthe Web Server Tuning the Web ServerPrefer to configure Sonar Portal as Windows Service. More details on how to achieve this on Running SonarQube as aService on Windows

Configure rules for opening ports used by SonarQube, with the Windows firewall and Azure endpoints, if applicable.You may use general guidance for Performance Tuning Windows Server in your particular environment/scenario. Please refer toPerformance Tuning Guidelines for Windows Server 2012 R2.Review and plan for best practices for Physical Servers hosting Hyper-V roles:

Avoid Overloading the ServerEnsure High-Speed Access to StorageInstall Multiple Network Interface CardsConfigure Antivirus Software to Bypass Hyper-V Processes and DirectoriesAvoid Storing System Files on Drives Used for Hyper-V StorageMonitor Performance to Optimize and Manage Server Loading

Installation and Configuration

Installation Topologies

Minimum Deployment

Medium Deployment

Recommended platform configurations

Running SonarQube on Hyper-V and Azure IaaS

SonarQube Setup Guide for .NET users

7Installation and Configuration

Page 8: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

1. Download

Download SonarQube 5.1 from the SonarQube downloads.

As mentioned in the Prerequisites section, a Java virtual machine (JVM) is required.If the installed JVM meets the version requirements l isted, you can skip this section. Otherwise, follow the steps below toinstall Java.Download Java SE Runtime Environment and make sure you select the one corresponding to your current operation system.

Setup SonarQube Server

SonarQube Setup Guide for .NET users

8Installation and Configuration

Page 9: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

>> NOTE >> SonarQube does not require the full Java JDK (Java SE Development Kit) to run- you only need the JRE (JavaSE Runtime Environment).

2. Install

Copy sonarqube-5.1.zip and j re-8u45-windows-xXX.exe to your Team Foundation Server.Install Jav a SE Runtime Env ironment on the destination server.

SonarQube Setup Guide for .NET users

9Installation and Configuration

Page 10: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

3. Extract

>> NOTE >> Before install ing and configuring SonarQube install and configure SQL Server according to the instructions in thesection Additional Configurations.

Right-click on sonarqube-5.1.zip, select Properties and then click on the Unblock button

SonarQube Setup Guide for .NET users

10Installation and Configuration

Page 11: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

Unzip SonarQube-x.x.zip on to a drive, for example use C:\SonarQube\SonarQube-5.1.

At this point, the installation is complete. Yes, it is that easy.

SonarQube Setup Guide for .NET users

11Installation and Configuration

Page 12: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

Proceed to the next section to complete the configuration of SonarQube.4. Configure SonarQube

>> NOTE >> This walkthrough assumes the use of the BK VM. If, for example, you are using SQLExpress instead, you haveto update the connection string. Example:

sonar.jdbc.url=jdbc:jtds:sqlserver://localhost/Sonar;instance=SQLEXPRESS;SelectMethod=Cursor

Alternatively if you are also looking for integrated security you can consider:

sonar.jdbc.url=jdbc:jtds:sqlserver://localhost:1433/sonar;instance=SQLEXPRESS;integratedSecurity=true;authenticationScheme=JavaKerberos

Basic configuration of SonarQube consists of making a few updates to the sonar.properties fi le.

This fi le is located in the conf folder located under the SonarQube installation folder. Example: C:\SonarQube\SonarQube-5.1\conf.You may not want to do this step if you prefer to go with the default SonarQube port 9000, if available.In the extracted folder navigate to Conf folder, edit sonar.properties fi le to change the default web port or you may needavailable port. By default SonarQube uses port 9000.Make sure to assign an available port for SonarQube, you may need to use the netstat command to check the currently in useports.For the purpose of this walkthrough, we assume port 9000 for the FabrikamFiber demo web site.

Search for the # Web Serv er section.Uncomment #sonar.web.port and change the port number to any available port, for example 9090

SonarQube Setup Guide for .NET users

12Installation and Configuration

Page 13: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

>>NOTE >> Before proceeding with the below configuration steps make sure you have configured SonarQube to use SQLServer database instead of embedded database.

Search for and locate the entry for sonar.jdbc.username.

Uncomment (i.e. delete the leading ‘#’) the two sonar.jdbc settings circled in the screenshot above and replace sonar ineach setting with the database login name and password, respectively.

SonarQube Setup Guide for .NET users

13Installation and Configuration

Page 14: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

Search for and locate the entry for sonar.jdbc.url. There are several copies of this setting based on database type. Make sureyou select the entry for Microsoft SQL Server.

Uncomment (i.e. delete the leading ‘#’) the sonar.jdbc.url setting circled in the screenshot above and replace the connectionstring to match the server\instance and database name for your machine. Example:sqlserv er://.\SQLExpress/Sonar;SelectMethod=Cursor

SonarQube Setup Guide for .NET users

14Installation and Configuration

Page 15: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

>> NOTE >> The jdbc driver installed with SonarQube requires the SQL Server Browser to be running. Check that it is runningusing the Services Console.

Save and close the fi le.

5. OPTIONAL - Connect with integrated authenticaton on Windows

>> NOTE >> We tested this configuration in an environment that has no security add-ons. If this does not work in yourenvironment, you need to troubleshoot with your IT departments.

Please refer to Building the Connection URL for additional details on how to build SQL Server connection string for JDBC.Edit sonar.properties.Change the SQL Serv er connection string to use integrated security.

# Only the distributed jTDS driver is supported. sonar.jdbc.url=jdbc:jtds:sqlserver://localhost;databaseName=sonar;integratedSecurity=true;”

- If you are using Sonar-runner for analysis, edit **sonar-runner.properties** and add the same configuration.

#----- Microsoft SQLServer sonar.jdbc.url=jdbc:jtds:sqlserver://localhost;databaseName=sonar;integratedSecurity=true;”

1. Download and install latest SonarQube C# plugin

Download the latest sonar-csharp-plugin-X.Y.jar. At the time of writing, all versions of the C# plugin are available from the C#Plugin page, on the SonarQube site.Use version 4.1 or higher of the plugin.Locate the directory into which the SonarQube was installed e.g. C:\SonarQube\SonarQube-5.1\. This directory will have anextensions\plugins\ subdirectory.Copy sonar-csharp-plugin-X.Y.jar to this directory from the downloaded package above.Right-click the sonar sonar-csharp-plugin-X.Y.jar and select properties.Click the Unblock button to ensure the fi le is unblocked.

2. Run

Open Command Prompt and change directory ( cd ) to the extracted folder.

SonarQube Setup Guide for .NET users

15Installation and Configuration

Page 16: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

Example:

cd C:\SonarQube\SonarQube-5.1\bin\windows-x86-64

>> NOTE >> You need to run the fi le corresponding to your operating system.

Run StartSonar.bat>> NOTE>> If you are prompted with a Windows Security Alert asking for network access, click on the Allow access button

Browse SonarQube web portal using http://YOUR_SERVER_NAME:SONAR_PORT. Example: http://v salm:9090

SonarQube Setup Guide for .NET users

16Installation and Configuration

Page 17: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

You should see the default SonarQube web page as shown above. If not, re-validate settings as shown in the previoussections.If the web server does not start, consult the logs in C:\SonarQube\SonarQube-5.1\logs to determine possible issues.

3. Verify the installed SonarQube C# plugin v ersion

Login to SonarQube using admin credentials.

If this is the first time you are using SonarQube, the default admin credentials are:

- Username: admin

- Password: admin

If you log in using the default credentials, it is recommended that you change the password.

Verify that the C# X.Y plugin has been correctly deployed, Navigate to Settings >System > Update Center.

SonarQube Setup Guide for .NET users

17Installation and Configuration

Page 18: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

>> NOTE >> The screenshot above is based version 3.5. You should see version 4.1 or later.

>> NOTE >> Please refer to section Additional Configurations for more details on how-to configure additional SonarQubeconfigurations that are required for enterprise level deployment.

You should install it on any machine that will launch SonarQube analysis (example: development machine and build agent).In case of install ing MSBuild SonarQube Runner on a development machine or build agent, you need to make sure that Java SERuntime Environment installed on that machine.Java SE Runtime Environment installation is not required if Visual Studio 2015 with Android tooling/Cross platform tools areinstalled since JDK is being installed part of Visual Studio installation.

Extract

Download the latest MSBuild SonarQube Runner from the SonarQube downloads.Right-click on the downloaded .zip fi le and click on the Unblock button.

Setup of the MSBuild SonarQube Runner on the Build Agent Machine

SonarQube Setup Guide for .NET users

18Installation and Configuration

Page 19: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

Unzip MSBuild.SonarQube.Runner-[v ersion] on to a drive. Example: C:\SonarQube\binConfigure

Edit C:\SonarQube\bin\SonarQube.Analysis.xml by specifying the following parameters to run against the SonarQubeServer we set up earlier.If you are running SonarQube 5.1.x or less, uncomment and set the following properties:

sonar.jdbc.url

sonar.jdbc.username

sonar.jdbc.password

SonarQube Setup Guide for .NET users

19Installation and Configuration

Page 20: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

OPTIONAL - Update the %PATH% env ironment v ariable

Add the directory containing the MSBuild SonarQube Runner executable to the %PATH% if you intend to use it from thecommand line:

Settings File Permissions

SonarQube Setup Guide for .NET users

20Installation and Configuration

Page 21: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

Storing passwords in clear text in unsecured settings fi les is not recommended.Restrict access to the C:\SonarQube\bin\SonarQube.Analysis.xml fi le by setting appropriate fi le permissions.

SonarQube Setup Guide for .NET users

21Installation and Configuration

Page 22: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

The following assumes that MSBuild.SonarQube.Runner.exe has been added to the %PATH% . If that is not your case, simply specify theabsolute path to it in both the begin and end phase commands.

1. Run the MSBuild.SonarQube.Runner.exe begin phase

MSBuild.SonarQube.Runner.exe begin /key:{SonarQube project key} /name:{SQ project name} /version:{SQ project version}

The begin phase takes four arguments:

begin/key:{the project key of the SonarQube project to which the build relates}/name:{the project name of the SonarQube project}/version:{the project v ersion of the SonarQube project}

The aliases /k:, /n: and /v: can also be used.

>>NOTE >> If any of the arguments contain spaces then that argument needs to be surrounded by double-quotes e.g./name:”My Project Name”.

See Configuring the MSBuild SonarQube Runner below for more information on passing additional settings.

2. Launch your normal project build

Basic example:

msbuild

Example, with nuget:

nuget restore msbuild

>>NOTE >> make sure to run MSBuild.SonarQube.Runner in a "MSBuild console", or a "VS Developer Command Prompt"otherwise you will not be able to access MSBuild command and you may get an error similar to "'msbuild' is not recognized as aninternal or external command,operable program or batch fi le."

3. Run the MSBuild.SonarQube.Runner.exe end phase

MSBuild.SonarQube.Runner.exe end

Analyze .NET Projects From The Command Line

SonarQube Setup Guide for .NET users

22Analyze .NET Projects From The Command Line

Page 23: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

The build system in Team Foundation Server 2013 ("TFS 2013") is based on Windows Workflow. Builds are defined and customisedusing XAML. TFS 2015 introduced a new build system but also supports the legacy "XAML build" system from TFS 2013.

This document describes how to set up to configure a XAML build in TFS 2013 or TFS 2015 to include code analysis. It also gives anoutline of how to set up analysis using the new build system.

SonarQube uses Projects to organize analysis results by logical application, where an application can consist of a number of modules(assemblies). It is not currently possible to upload partial analysis results for a SonarQube Project. For example, if SonarQube projectX consists of assemblies A, B and C, it is not possible to build, analyze and upload data for A and B, and later to build, analyze andupload data for C.

This means that a Build Definition must build and analyze all of the assemblies that are in that SonarQube Project.

The settings required to configure a XAML build to perform code analysis are the same for TFS 2013 and TFS 2015. However, if youare using the TFS 2015 XAML build agent then there are additional considerations:

when analysing data stored in an on-premise TFS installation, the build agent must also have the TFS 2013 Object Modelinstalleda TFS 2015 build agent cannot currently be used to analyse code stored in Visual Studio Online ("VSO"). See the following sub-sections for more information.

Install ing Visual Studio 2013 will install the necessary assemblies on the build agent. Alternatively, Microsoft provide a separateinstaller for the object model that can be downloaded and installed as follows:

Browse to the Visual Studio GallerySearch for "Team Foundation Server Object Model"Choose the appropriate version of the 2013 object model for the updates you have applied to your TFS installationDownload and run the installer

If you are analysing code stored in VSO using a XAML build then at present you must use TFS 2013 build agent. This is a knownissue that is being tracked here [http://j ira.sonarsource.com/browse/SONARMSBRU-73].

>> NOTE >> Assumptions:

One of the standard Team Build workflow templates for TFS2013 (GitTemplate.12.xaml or TfvcTemplate.12.xaml) and that thestandard Microsoft build targets are used. Users who have customized either the build targets or workflow templates may need tomodify the following steps to take account of their customizations.You have permissions to create or modify a Build Definition. If you do not, contact your Team Foundation Service administrator.

Analyze .Net Projects From Team Foundation Server 2013 and2015

Overview

Mapping Build Definitions to SonarQube projects

Analyzing projects in XAML Builds in TFS 2013 and TFS 2015

Additional considerations when using a TFS 2015 XAML build agent

Installing the TFS 2013 Object Model on a TFS 2015 Build Agent

Analyzing code stored in Visual Studio Online ("VSO") requires a TFS 2013 build agent

Updating an existing XAML build definition

SonarQube Setup Guide for .NET users

23Analyze .NET Projects From Team Foundation Server 2013 and 2015

Page 24: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

Edit build definition

Open the Team Explorer in Visual Studio.Check that you are connected to the correct Team Foundation Server.

Click on the Builds tab.The displayed Builds page will show information about recent builds and any build definitions that exist.Right-click on the build definition you want to modify and select Edit Build Definition…This will display the Build Definition in a document window.

SonarQube Setup Guide for .NET users

24Analyze .NET Projects From Team Foundation Server 2013 and 2015

Page 25: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

Edit adv anced build settings

Click on the Process section, then, within the 2. Build section, expand the 5. Adv anced section.This will display the advanced build settings.

SonarQube Setup Guide for .NET users

25Analyze .NET Projects From Team Foundation Server 2013 and 2015

Page 26: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

Set the following properties in the Advanced section:

Set the Pre-build script path to the full path to MSBuild.SonarQube.Runner.exe.Set the Pre-build script arguments to contain the following four arguments:

begin/key:{the project key of the SonarQube project to which the build definition relates}/name:{the project name of the SonarQube project}/version:{the project v ersion of the SonarQube project}

The aliases /k:, /n: and /v: can also be used.

>>NOTE >> If any of the arguments contain spaces then that argument needs to be surrounded by double-quotes e.g./name:”My Project Name”.

Click on the expander for the 2. Adv anced section under 3. Test to display the advanced test settings.

Set the Post-test script path to the full path to MSBuild.SonarQube.Runner.exe

>> NOTE >> The pre and post script paths refer to the same executable.

Set the Post-test script arguments to contain the following argument:

endOPTIONAL - Configure code cov erage

Carry out the following actions if you want to collect code coverage data for tests:

Click on the expander 3. TestSelect the 1. Automated tests l ineClick on the ell ipsis to bring up the Automated Tests dialogue.

SonarQube Setup Guide for .NET users

26Analyze .NET Projects From Team Foundation Server 2013 and 2015

Page 27: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

Click on Edit to bring up the Add/Edit Test Run dialogSelect Enable Code Cov erage from Options drop-down.

SonarQube Setup Guide for .NET users

27Analyze .NET Projects From Team Foundation Server 2013 and 2015

Page 28: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

Click OK to close the dialogs.

>>WARNING >> It is possible to dril l down through the 1. Automated tests sections to locate a drop-down for Type of runsettings in which one of the options is CodeCov erageEnabled. However, at the time of writing choosingCodeCov erageEnabled from the drop-down does not generate coverage results, due to a bug. See TFS 2013 - No CodeCoverage Results on StackOverflow for more info.

Validate and sav e build settings

The following screenshot shows how the build definition should look at this point.

SonarQube Setup Guide for .NET users

28Analyze .NET Projects From Team Foundation Server 2013 and 2015

Page 29: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

Sav e the build definition.

>>NOTE >> Assumptions

If you have not already created a SonarQube Project with Project Key specified in the Build Definition, a new SonarQube Projectwill be created automatically, when analysis results are uploaded to SonarQube.In this case, the initial analysis will use the default SonarQube Quality Profile.If you want the initial analysis to be performed using a different Quality Profile, you will need to create and configure theSonarQube project before running the first analysis.See the SonarQube documentation on Provisioning Projects for more information.

Test the build

Right-click on the build definition in the Team Explorer window.Select Queue new build… from the menu.

Test the modified build definition

SonarQube Setup Guide for .NET users

29Analyze .NET Projects From Team Foundation Server 2013 and 2015

Page 30: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

A dialogue box will appear presenting various build options.Click on Queue to accept the default options and start the build.

>> NOTE >> The build may take some time to complete, depending on the complexity of your application.

When the build is complete, the build summary Page will indicate whether the build was successfully or not.

If the build completed successfully there will be a section entitled SonarQube Analysis Summary.

SonarQube Setup Guide for .NET users

30Analyze .NET Projects From Team Foundation Server 2013 and 2015

Page 31: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

The section contains a l ink to the SonarQube portal for relevant SonarQube Project.

Try modifying the build definition to remove the SonarQube.MSBuild.Runner.exe entries in the pre- and post- script sections. If thebuild completes successfully, then the errors are related to analysis.

Most analysis-related configuration or execution errors will cause the build to fail and will be appear on the Build Summary.Additional information can be found by viewing the logs or diagnostic information (i.e. by clicking on View Log, or Diagnostics at thetop of the Build Summary page).

Troubleshooting

Build did not complete successfully and build summary contains one or more errors.

Analyzing projects using the new TFS 2015 build system

SonarQube Setup Guide for .NET users

31Analyze .NET Projects From Team Foundation Server 2013 and 2015

Page 32: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

The intention is to provide custom tasks to make the process of performing SonarQube analysis in the TFS build system straightfoward.The proposed custom build tasks will also make it possible to run SonarQube analysis on hosted build agents.

However, it is currently possible to perform SonarQube analysis in the new build system on an on-premise build agent by using thegeneral-purpose "Command Line" task to call MSBuild.SonarQube.Runner.exe (i.e. to do the same job as the "Pre-Build script"/"Post-Build script" steps in a XAML build). The following steps provide an outline of how to set this up:

Create an on-premise VSO 2015 build agent using the instructions hereInstall the MSBuild.SonarQube.Runner on the build agentCreate a new build definition that includes the MSBuild and (optionally) Visual Studio Test stepsAdd Command Line build step before the MSBuild step and after the Visual Studio Test stepIn the pre-build command line:

set the Tool field to point to the MSBuild.SonarQube.Runner.exesupply the necessary arguments in the Arguments field e.g. begin /key:my.project /name:"My Project" /version:1.0*supply the the SonarQube server URL and credentials either in the Arguments field or in a settings fi le e.g./d:sonar.host.url=http://mySonarQube:9000

In the post-build command:

set the Tool field to point to the MSBuild.SonarQube.Runner.exeset the Arguments field to end

Save the build definition

By default a new build definition will run both debug and release builds. SonarQube can only analyse one type of build at a time soyou will need to pick one or the other (Variables tab, BuildConfiguration property).

The following screenshot gives an example of how the build definition would look.

SonarQube Setup Guide for .NET users

32Analyze .NET Projects From Team Foundation Server 2013 and 2015

Page 33: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

1. Uninstall

To uninstall the NT services, run the following batch fi le using Run As Administrator.

Example:

<SonarQube_Install_Directory>\bin\windows-x86-64\UninstallNTService.bat

2. Install

To install the NT services, run the following batch fi le using Run As Administrator.

Example:

<SonarQube_Install_Directory>\bin\windows-x86-64\InstallNTService.bat

3. Serv ice Account

Remove the local system account usage and replace it with an administrative account.

Additional Configurations

Running SonarQube as a Service on Windows

SonarQube Setup Guide for .NET users

33Additional Configurations

Page 34: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

4. Start serv ice

Make sure you have closed all running non-service instances of SonarQube Serv er.

To start the service use the Services Console or run the following batch fi le using Run As Administrator.

Example:

<SonarQube_Install_Directory>\bin\windows-x86-64\StartNTService.bat

5. Validate

From Services Console make sure the service is running correctly.

SonarQube Setup Guide for .NET users

34Additional Configurations

Page 35: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

Validate that you are able to browse SonarQube portal.6. Inter-serv ice dependency

If SonarQube serv er is installed on the same machine as SQL Server with the SonarQube database, you need to make surethat SQL Server is started before the SonarQube service. In addition, the default jdbc driver install with SonarQube requiresthe SQL Brower Service to be running.Assuming you’re using the default SQL Server instance MSSQLSERVER, open the command prompt in administrative modeand run the following command to ensure both the SQL Server and SQL Browser Service are started before the SonarQubeservice.

Example: sc config SonarQube depend=MSSQLSERVER/SQLBrowser

>> NOTE >> If you are using a named SQL instance, you can check the name of the service by locating it in the ServicesConsole and viewing its properties. The Serv ice name to use if given on the General tab

SonarQube Setup Guide for .NET users

35Additional Configurations

Page 36: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

Validate that the inter-service dependency has been added successfully by navigating to the SonarQube serv ice and checkthe Dependencies tab.

>> NOTE >> For the purposes of this section, we will assume that you have already installed supported version of Microsoft SQL Server(SQL Server 2012) as part of Team Foundation Server installation.

As mentioned in the database requirements above, SQL Server must be set to UTF-8 and the language set to English. Thecollation must be set to case-sensitiv e (CS) and accent-sensitiv e (AS).To enable TCP connection for SQL, you must open the SQL Server Configuration Manager and enable TCP/IP within SQLServer Network Configuration and set it to use static port 1433.Once a database has been created, you must create a new database user with permissions to create, update, and delete objectswithin this database.

Before you get to the task of creating a new database for SonarQube, you need to complete a few preparations.

1. Launch SSMS

Launch SQL Serv er Management Studio (SSMS).Connect to the SQL Server instance on which you plan to create the database.

Example: .\\SQLExpress

2. Check collation

Right-click on the database serv er node and select Properties.

Configure SonarQube to use Microsoft SQL Database

Preparations

SonarQube Setup Guide for .NET users

36Additional Configurations

Page 37: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

This will display the Server Properties dialog.Click on the General node and make a note of the current Server Collation setting.For example, in the screenshot below, the collation setting is currently set to SQL_Latin1_General_CP1_CI_AS.

SonarQube Setup Guide for .NET users

37Additional Configurations

Page 38: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

You need the collation to be both case sensitiv e (CS) and accent sensitiv e (AS).If either is different, you will need to be sure to select the case-sensitive version when you set the collation for the databaseyou will be create.

3. Check authentication

Click on the Security node.Since, by default, SonarQube util izes SQL Authentication we need to ensure that Server Authentication is set to SQL Serv erand Windows Authentication mode as shown in the screenshot below.

SonarQube Setup Guide for .NET users

38Additional Configurations

Page 39: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

1. Create database for use by SonarQube

Within SSMS right-click on the Databases node (just under the Server\Instance node).Select New Database…

Walkthrough

SonarQube Setup Guide for .NET users

39Additional Configurations

Page 40: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

In the General node, set the Database Name to Sonar.

SonarQube Setup Guide for .NET users

40Additional Configurations

Page 41: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

In the Options node, click on the Collation drop-down list and look for the case-sensitiv e (CS) and accent-sensitiv e (AS)variant of the server collation you made note of above.

Click OK to create the initial database.2. Create database user for SonarQube

Within SSMS right-click on the SecurityLogins node (just under the Server\Instance node).Select

SonarQube Setup Guide for .NET users

41Additional Configurations

Page 42: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

Select the General node.Set the Login Name – e.g. SonarUserSelect SQL Server Authentication and provide a Password.Uncheck Enforce password expiration.Set the Default Database to the Sonar database you created.Set the Default Language to English

SonarQube Setup Guide for .NET users

42Additional Configurations

Page 43: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

In the User Mapping node, ensure the SonarUser has been mapped to the Sonar database and check the db_ownerdatabase role membership

SonarQube Setup Guide for .NET users

43Additional Configurations

Page 44: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

Click OK to complete the new user setup.3. Test connection

Launch Visual Studio and select Tools, Connect to Database...

SonarQube Setup Guide for .NET users

44Additional Configurations

Page 45: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

Select Microsoft SQL Serv er as the Data Source.

On the Add Connection dialog.

Set the Server Name to your SQL Server instance (e.g. .\SQLExpress)Select Use SQL Server Authentication and provide the User Name and Password you created.Enter the name of the database you created, for example Sonar.

SonarQube Setup Guide for .NET users

45Additional Configurations

Page 46: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

Click on Test Connection.You should see the following dialog.

By default, the SonarQube portal allows anonymous access, although SonarQube does provide a complete authentication and

Secure the SonarQube Portal

SonarQube Setup Guide for .NET users

46Additional Configurations

Page 47: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

authorization mechanism to manage security. As users of the portal wil l be able to view the analyzed source code, it is recommendedthat the anonymous access to the site not be permitted.

See Security section on the SonarQube site for more information.

SonarQube Setup Guide for .NET users

47Additional Configurations

Page 48: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

The integration pieces changed significantly from the v0.9 preview version. The main changes in the v1.0 release are as follows:

1. Added support for all of the scenarios supported by the Visual Studio Bootstrapper plugin so that the Visual Studio Bootstrapperplugin could be deprecated, and

2. Simplified the installation process.

The v0.9 release of the SonarQube MSBuild Runner did not support a number of analysis plugins (e.g. the VB.Net plugin, Resharperand StyleCop) because it did not provide any way to pass additional settings to those plugins. In version 1.0, global settings can bespecified in the new SonarQube.Analysis.xml fi le or passed on the command line. Settings specific to a particular MSBuild projectcan be specified in the MSBuild project fi le.

The v0.9 release required the user to manually set up and configure the sonar-runner. This is no longer required in v1.0 (although it issti l l necessary for Java to be pre-installed on the machine). Previously the user had to manually install theSonarQube.Integration.ImportBefore.targets fi le. This fi le is now automatically installed to the appropriate per-user location forMSBuild v4.0, v12.0 and v14.0.

A number of bugs were fixed and a series of improvements made to simplify running an analysis from the command line as well asthrough Team Build. Finally, the name of the exe changed from SonarQube.MSBuild.Runner.exe in the preview toMSBuild.SonarQube.Runner.exe in version 1.0 to comply with the plugin naming convention used by SonarSource.

Perform the following steps to upgrade from version 0.9 of the SonarQube MSBuild Runner:

1. Install the new version of the C# plugin on the SonarQube server as described above.2. Install the new version of the MSBuild.SonarQube.Runner on the agent machine as described above.3. (Optional) Migrate any additional settings from the old sonar-runner.properties fi le to the SonarQube.Analysis.xml fi le.

If you had added any additional settings in the sonar-runner.properties fi le then these settings will need to be moved to thenew SonarQube.Analysis.xml fi le.

4. Delete SonarQube.Integration.ImportBefore.targets from%ProgramFiles(x86)%\MSBuild\12.0\Microsoft.Common.Targets\ImportBefore.

5. Upgrade any existing build definitions.The name of the executable in the Pre-build script path and the Post-test script path fields should be changed fromSonarQube.MSBuild.Runner.exe to MSBuild.SonarQube.Runner.exe.Add begin to the Pre-build script argumentsAdd end to the Post-test script arguments.

It is not necessary to uninstall the manually-installed version of the sonar-runner that was required by the v0.9 version. However, if youdo wish to do so then perform the following steps:

1. Delete the sonar-runner fi les from disc.2. Remove the sonar-runner bin directory from the %PATH% .3. Delete the SONAR_RUNNER_HOME environment variable.4. Delete the SONAR_RUNNER_OPTS enviornment variable.5. Restart the TFS Build Service.

If you have amended the environment variables then you will need to restart the Build Service so it uses the modified set ofvariables.

Appendix 1: Upgrading from v0.9 of the SonarQube MSBuildRunner

Overview of the differences between v0.9 and v1.0

Required upgrade steps

Optional upgrade steps - remove the sonar-runner

SonarQube Setup Guide for .NET users

48Appendix 1: Upgrading from v0.9 of the SonarQube MSBuild Runner

Page 49: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

# Appendix 2: Configuring the MSBuild SonarQube Runner

Supplying additional analysis settingsClassifying projects as test projectsExcluding artefacts from analysis

The analysis process can be configured by passing additional analysis settings to the MSBuild SonarQube Runner. Global settings caneither be passed on the command line or in a settings fi le. Project-level settings can be set in the MSBuild project fi le.

Individual global settings can be supplied on the command using the /d switch:

MSBuild.SonarQube.Runner.exe /v:1.0 /n:"My project" /k:my.project /d:sonar.host.url=http://myServer:9001

Additional settings can also be supplied in a settings fi le. The location of the settings fi le can be specified on the command line usingthe /s switch:

MSBuild.SonarQube.Runner.exe /v:1.0 /n:"My project" /k:my.project /s:C:\SharedSettings\SonarQube.Analysis.xml

If the /s command-line switch is not supplied then the MSBuild SonarQube Runner will look for a default settings fi le calledSonarQube.Analysis.xml in the same directory as the MSBuild.SonarQube.Runner executable fi le. The default settings fi le shippedwith the MSBuild SonarQube Runner contains placeholders for the most commonly-required settings and can be used as a templatefor custom settings fi les.

Non-global (i.e. settings specific to a particular MSBuild project) can be specified in the MSBuild project fi le for the project. Forexample, the MSBuild.SonarQube.Integration.targets fi le sets the sonar.stylecop.projectFilePath property as follows:

<ItemGroup> <SonarQubeSetting Include="sonar.stylecop.projectFilePath"> <Value>$(MSBuildProjectFullPath)</Value> </SonarQubeSetting></ItemGroup>

It should only be necessary to use this mechanism in cases were a plugin requires different values for each project that is beinganalysed, as is the case with the StyleCop plugin.

If the same setting is supplied in multiple places then the value that is used is determined using the following order of precedence(highest to lowest):

- command line settings specified using /d- settings in a SonarQube.Analysis.xml file (either the default settings file or one specified using the */s* command-line switch)- settings specified in an MSBuild project file- settings fetched from the SonarQube server

Contents

Supplying additional analysis settings

Passing additional global settings on the command line

Passing additional global settings in a settings file

Passing additional non-global settings in a project file

Order of precedence of analysis settings

SonarQube Setup Guide for .NET users

49Appendix 2: Configuring the MSBuild SonarQube Runner

Page 50: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

See http://docs.sonarqube.org/x/CoBh for details on how to import Code Coverage reports into SonarQube.

See http://docs.sonarqube.org/x/DIBh for details on how to import Unit Test Execution reports into SonarQube.

See http://docs.sonarqube.org/x/lwAW for details on how to import ReSharper Command Line Tools reports into SonarQube.

SonarQube analyses test projects and product projects differently so it is important that projects are correctly classified as being eithertest or product projects.

The MSBuild SonarQube Runner will automatically recognise MSTest unit test projects as being test projects (because of thepresence of a well-known guid in the project fi le).

Other test projects are recognised by applying a regular expression to the full path of the project fi le. The regular expression canconfigured in the SonarQube portal on the settings page for the C# plugin:

Figure – MSBuild settings tab of the C# plugin

The regular expression uses .Net regular expression syntax.

In version 1.0.1 onwards, the default regular expression treats projects that contain the word "test" in the project fi le name as testprojects (in version 1.0, projects that contained "test" anywhere in the path were treated as test projects, but user feedback indicated

Importing Code Coverage reports

Importing Unit Test Execution reports

Importing ReSharper Command Line Tools reports

Classifying projects as test projects

SonarQube Setup Guide for .NET users

50Appendix 2: Configuring the MSBuild SonarQube Runner

Page 51: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

that this regular expression was not specific enough and incorrectly classified to many projects).

Finally, it is possible to manually classify a project by setting the MSBuild property SonarQubeTestProject, e.g.

<PropertyGroup> <!-- Mark the project as being a test project --> <SonarQubeTestProject>true</SonarQubeTestProject></PropertyGroup>

Certain types of project wil l automatically be excluded from analysis. For example, Microsoft Fakes generates additional projectsduring build. These auto-generated projects will not be analysed.

Individual projects can be excluded from analysis by setting the MSBuild property SonarQubeExclude to true as follows:

<PropertyGroup> <!-- Exclude the project from analysis --> <SonarQubeExclude>true</SonarQubeExclude></PropertyGroup>

See Appendix 3: Advanced MSBuild SonarQube Runner configuration for more information on how SonarQubeExclude can be setconditionally at build time.

Files that are generated by custom tools within Visual Studio are automatically excluded from analysis, such as the xxx.Designer.csfi le generated from a .resx fi le:

<Compile Include="Resources.Designer.cs"> <AutoGen>True</AutoGen> <DesignTime>True</DesignTime> <DependentUpon>Resources.resx</DependentUpon></Compile>

These fi les are excluded because they are marked as generated by Visual Studio. It is possible to manually exclude a specific fi lefrom analysis by setting the MSBuild metadata item SonarQubeExclude to true as follows:

<ItemGroup> <Compile Include="MyFile.cs"> <!-- Exclude the file from analysis --> <SonarQubeExclude>true</SonarQubeExclude> </Compile></ItemGroup>

Excluding artefacts from analysis

Excluding projects from analysis

Excluding individual files from analysis

SonarQube Setup Guide for .NET users

51Appendix 2: Configuring the MSBuild SonarQube Runner

Page 52: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

This appendix contains additional information on how the MSBuild SonarQube Runner can be configured to work effectively in morecomplex real-world scenarios.

Setting SonarQubeExclude at project level is a simple way to ensure that a project is always included or excluded. However, becauseSonarQubeExclude is an MSBuild property it can be set conditionally l ike any other MSBuild property. This allows considerableflexibil ity in deciding whether a project should be excluded or not which can be useful in a number of scenarios.

The following examples show how standard MSBuild features can be used to customise the projects that are analysed.

For example, the same MSBuild project may be included in multiple different solutions. In this situation it is generally desirable thatthe MSBuild project should only be analysed once e.g.

Solution1 contains projects 'A', 'B' and 'X'. All of the projects should be analysed as part of SonarQube project 'example.sqproject1'

Solution2 contains projects 'C', 'D' and 'X'. Only projects 'C' and 'D' should be analysed as part of SonarQube project 'example.sqproject2'

Two possible methods of handling this scenario using a small amount of customisation and configuration are shown below. Bothmethods conditionally set the SonarQubeExclude property based on additional data supplied during the build phase.

One approach is to add a property to the MSBuild project to specify which SonarQube project it belongs to, and to create a customtargets fi le that fi lters out projects that do not match the project key that is supplied at build time.

The detailed steps are as follows:

add a property to MSBuild project X specifying the SonarQube project key to which the MSBuild project belongs:

<PropertyGroup> <TargetSQProjectKey>example.sqproject2</TargetSQProjectKey></PropertyGroup>

create a targets fi le with the following content:

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0"> <!-- This target customises the SonarQube MSBuild runner targets to limit the project that are analysed. Only projects with matching SonarQube project keys will be analysed. --> <PropertyGroup Condition=" $(SQProjectKey) != '' AND $(SonarQubeExclude) == '' "> <!-- If the current project specifies a target SQ project then exclude unless the project keys match. --> <SonarQubeExclude Condition="$(TargetSQProjectKey) != '' AND $(SQProjectKey) != $(TargetSQProjectKey) " >true</SonarQubeExclude> </PropertyGroup></Project>

import the custom targets fi le using one of the standard MSBuild mechanisms e.g. either explicitly import it into the relevantprojects, or drop it in a location in which it wil l be automatically imported such as %ProgramFiles(x86)%\MSBuild*[MSBuildversion]*\Microsoft.Common.Targets\ImportBefore\.

at build time, pass the relevant SonarQube project key to MSBuild.

Appendix 3: Advanced MSBuild SonarQube Runner configuration

Conditionally excluding projects from analysis

Explicitly associating an MSBuild project with a SonarQube project

SonarQube Setup Guide for .NET users

52Appendix 3: Advanced MSBuild SonarQube Runner configuration

Page 53: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

For a TeamBuild XAML build, this would be done by editing the build definition and setting the "MSBuild arguments"appropriately e.g. /p:SQProjectKey=example.sqproject1.On the command line this could done as follows:

msbuild Solution1.sln /p:SQProjectKey=example.sqproject1

msbuild Solution2.sln /p:SQProjectKey=example.sqproject2

This would have the desired effect of ensuring MSBuild project X is only analysed once.

Depending on the layout of the projects on disk, it might be possible to specify the projects to analyse based on the fi le paths.

For example, suppose the projects above are laid out on disk as follows:

c:\Web\ProjectAc:\Web\ProjectBc:\Framework\ProjectCc:\Framework\ProjectDc:\Framework\ProjectX

The following custom targets fi le selects the projects to analyse based on the fi le path:

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0"> <!-- This target customises the SonarQube MSBuild runner targets to limit the projects that are analysed. Projects whose full path and file name do not match the specified filter will be marked as "excluded". The regular expression uses the normal .NET regular expression syntax. --> <PropertyGroup Condition=" $(SonarQubeExclude) == '' AND $(SQPathFilter) != '' "> <MatchesSQPathFilter Condition="$([System.Text.RegularExpressions.Regex]::IsMatch($(MSBuildProjectFullPath), $(SQPathFilter), System.Text.RegularExpressions.RegexOptions.IgnoreCase)) " <SonarQubeExclude Condition="$(MatchesSQPathFilter) != 'true' " >true</SonarQubeExclude> </PropertyGroup></Project>

This targets fi le would allow the projects to be fi ltered as follows:

REM Only analyse the web projects, regardless of which projects are included in the solutionREM Note: the backslash in the supplied path is escapedmsbuild Solution1.sln /p:SQPathFilter=c:\\web

REM Only analyse the framework projectsmsbuild Solution2.sln /p:SQPathFilter=c:\\framework

Excluding projects based on the file path

SonarQube Setup Guide for .NET users

53Appendix 3: Advanced MSBuild SonarQube Runner configuration

Page 54: SonarQube Setup Guide for .NET usersdocshare04.docshare.tips/files/30042/300426480.pdf · SonarQube Setup Guide for .NET users Prequisites 6 All TFS Services, SQL Server and SonarQube,

During our adventure of setting up SonarQube with an existing deployment of Team Foundation Server, we introduced you toTechnical Debt; we gave you the prerequisites and installation configurations, and covered the topologies. We hope we haveachieved our goals for the guidance, get you up and running quickly with SonarQube and Team Foundation Server so you can startyour analysis of your technical debt and begin your debt reduction strategy.

Sincerely

The Microsoft Visual Studio ALM Rangers

The Visual Studio ALM Rangers includes members from the Visual Studio Product group, Microsoft Services, Microsoft Most ValuableProfessionals (MVP) and Visual Studio Community Leads. Their mission is to provide out-of-band solutions to missing features andguidance. A growing Rangers Index is available online.

HomeSolutionsMembership

- Contributors: Anil Chandra Lingam, Baruch Frei, Brian Blackman, Cesar Solis Brito, Clementino de Mendonca, Darren Rich, DuncanPocklington, Hosam Kamel, Jean-Marc Prieur, Jeff Bramwell, Marcelo Silva, Mathew Aniyan, Michael Wiley

- Special thanks to: Colin Dembovsky

Conclusion

SonarQube Setup Guide for .NET users

54Conclusion