Professional Documents
Culture Documents
SonarQube Setup Guide For Net Users V 1 1 0
SonarQube Setup Guide For Net Users V 1 1 0
Table of Contents
1. Introduction
2. The MIT License
3. Prequisites
4. Installation and Configuration
5. Analyze .NET Projects From The Command Line
6. Analyze .NET Projects From Team Foundation Server 2013
7. Additional Configurations
8. Appendix 1: Upgrading from v0.9 of the SonarQube MSBuild Runner
9. Appendix 2: Configuring the MSBuild SonarQube Runner
10. Conclusion
2
SonarQube Setup Guide for .NET users
Introduction
“SonarSource products generate process-level benefits, such as decreasing software development risk,
raising software quality and improving team productivity” .
This guide aims to provide insightful and practical guidance around installing 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 allow for adaptation to changing business needs, inadequate testing and
documentation, isolation of changes requiring future merging of the 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 bug later 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 Server.
SonarQube is an open source platform providing continuous inspection of your code quality. Through
integration with Team Foundation Server and SonarQube you will be empowered to continuously inspect
the technical debt, manage the debt, and pay down 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 Team Foundation 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 3
SonarQube Setup Guide for .NET users
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction, including
without limitation 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 to the 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 NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO 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 THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Prerequisites
At the time of this writing, the current version of SonarQube, v5.1, had the following requirements.
Java
Database
Regardless of which database solution you choose, it must be set to UTF-8, language set to English, and
collation to CS (case sensitive) and AS (accent sensitive).
Web Browser
For the best SonarQube experience ensure to enable JavaScript in your web browser. Supported web
browsers:
Prequisites 5
SonarQube Setup Guide for .NET users
Hardware
File Encoding
SonarQube assumes that all of the source files have the same file encoding. Currently, the MSBuild
SonarQube Runner expect this to be UTF-8. Non-compliance will result in incorrect analysis and display
when viewed in the SonarQube portal (for example when drilling down to view the source associated with
an issue).
>> NOTE >> For the most up to date information on SonarQube requirements, check out the
requirements.
Prequisites 6
SonarQube Setup Guide for .NET users
Installation Topologies
Minimum Deployment
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 components installed on one box.
Medium Deployment
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 on Azure IaaS Guide for information on hardware and capacity planning
recommendations for your Team Foundation Server environment.
While preparing a Virtual Machine that will host SonarQube database, portal and/or Runner workloads
take into account the following guidance:
For production servers it is recommended to use Fixed Sized disks (instead of dynamic ones); you
must estimate accordingly to set apart 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 a production 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 usage expected by SonarQube:
Prefer fast disk for tempdb file storage.
Distribute storage in equally sized data files (starting at 1/2 file per physical processor and up to 8
files).
1. Download
>> NOTE >> SonarQube does not require the full Java JDK (Java SE Development Kit) to run-
you only need the JRE (Java SE Runtime Environment).
2. Install
3. Extract
>> NOTE >> Before installing and configuring SonarQube install and configure SQL Server according
to the instructions in the section Additional Configurations.
Right-click on sonarqube-5.1.zip, select Properties and then click on the Unblock button
>> NOTE >> This walkthrough assumes the use of the BK VM. If, for example, you are using
SQLExpress instead, you have to 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;authe
Basic configuration of SonarQube consists of making a few updates to the sonar.properties file.
This file 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 file to change the default
web port or you may need available 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 use ports.
For the purpose of this walkthrough, we assume port 9000 for the FabrikamFiber demo web site.
>>NOTE >> Before proceeding with the below configuration steps make sure you have
configured SonarQube to use SQL Server database instead of embedded database.
Uncomment (i.e. delete the leading ‘#’) the two sonar.jdbc settings circled in the screenshot
above and replace sonar in each setting with the database login name and password,
respectively.
Search for and locate the entry for sonar.jdbc.url. There are several copies of this setting based
on database type. Make sure you 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 connection string to match the server\instance and database name for your
machine. Example: sqlserver://.\SQLExpress/Sonar;SelectMethod=Cursor
>> NOTE >> The jdbc driver installed with SonarQube requires the SQL Server Browser to be
running. Check that it is running using the Services Console.
>> NOTE >> We tested this configuration in an environment that has no security add-ons. If this does
not work in your environment, 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 Server connection string to use integrated security.
- If you are using Sonar-runner for analysis, edit **sonar-runner.properties** and add the same configuration.
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 an extensions\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 file is unblocked.
2. Run
Example:
cd C:\SonarQube\SonarQube-5.1\bin\windows-x86-64
>> NOTE >> You need to run the file 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
You should see the default SonarQube web page as shown above. If not, re-validate settings as
shown in the previous sections.
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 version
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.
>> 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 SonarQube configurations 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 installing MSBuild SonarQube Runner on a development machine or build agent, you need
to make sure that Java SE Runtime Environment installed on that machine.
Java SE Runtime Environment installation is not required if Visual Studio 2015 with Android
tooling/Cross platform tools are installed 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 file and click on the Unblock button.
sonar.jdbc.url
sonar.jdbc.username
sonar.jdbc.password
Add the directory containing the MSBuild SonarQube Runner executable to the %PATH% if you
intend to use it from the command line:
The following assumes that MSBuild.SonarQube.Runner.exe has been added to the %PATH% . If that is not your
case, simply specify the absolute path to it in both the begin and end phase commands.
MSBuild.SonarQube.Runner.exe begin /key:{SonarQube project key} /name:{SQ project name} /version:{SQ project vers
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 version of the SonarQube project}
>>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.
Basic example:
msbuild
nuget restore
msbuild
may get an error similar to "'msbuild' is not recognized as an internal or external command,operable
program or batch file."
MSBuild.SonarQube.Runner.exe end
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 project X 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 and upload data for C.
This means that a Build Definition must build and analyze all of the assemblies that are in that SonarQube
Project.
One of the standard Team Build workflow templates for TFS2013 (GitTemplate.12.xaml or
TfvcTemplate.12.xaml) and that the standard Microsoft build targets are used. Users who have
customized either the build targets or workflow templates may need to modify 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.
Click on the Process section, then, within the 2. Build section, expand the 5. Advanced section.
This will display the advanced build settings.
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 version of the SonarQube project}
>>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. Advanced section under 3. Test to display the advanced
test settings.
>> NOTE >> The pre and post script paths refer to the same executable.
end
Carry out the following actions if you want to collect code coverage data for tests:
>>WARNING >> It is possible to drill down through the 1. Automated tests sections to
locate a drop-down for Type of run settings in which one of the options is
CodeCoverageEnabled. However, at the time of writing choosing CodeCoverageEnabled
from the drop-down does not generate coverage results, due to a bug. See TFS 2013 - No
Code Coverage Results on StackOverflow for more info.
The following screenshot shows how the build definition should look at this point.
If you have not already created a SonarQube Project with Project Key specified in the Build Definition,
a new SonarQube Project will 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 the SonarQube project before running the first analysis.
See the SonarQube documentation on Provisioning Projects for more information.
>> 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.
The section contains a link to the SonarQube portal for relevant SonarQube Project.
Troubleshooting
Build did not complete successfully and build summary contains one
or more errors.
Try modifying the build definition to remove the SonarQube.MSBuild.Runner.exe entries in the pre- and
post- script sections. If the build 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 the top of the Build Summary page).
Additional Configurations
1. Uninstall
To uninstall the NT services, run the following batch file 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 file using Run As Administrator.
Example:
<SonarQube_Install_Directory>\bin\windows-x86-64\InstallNTService.bat
3. Service Account
Remove the local system account usage and replace it with an administrative account.
Additional Configurations 35
SonarQube Setup Guide for .NET users
4. Start service
Make sure you have closed all running non-service instances of SonarQube Server.
To start the service use the Services Console or run the following batch file using Run As
Administrator.
Example:
<SonarQube_Install_Directory>\bin\windows-x86-64\StartNTService.bat
Additional Configurations 36
SonarQube Setup Guide for .NET users
5. Validate
If SonarQube server is installed on the same machine as SQL Server with the SonarQube
database, you need to make sure that SQL Server is started before the SonarQube service. In
addition, the default jdbc driver install with SonarQube requires the SQL Brower Service to be
running.
Assuming you’re using the default SQL Server instance MSSQLSERVER, open the command
prompt in administrative mode and run the following command to ensure both the SQL Server
and SQL Browser Service are started before the SonarQube service.
Additional Configurations 37
SonarQube Setup Guide for .NET users
>> NOTE >> If you are using a named SQL instance, you can check the name of the service by
locating it in the Services Console and viewing its properties. The Service name to use if given
on the General tab
Validate that the inter-service dependency has been added successfully by navigating to the
SonarQube service and check the Dependencies tab.
Additional Configurations 38
SonarQube Setup Guide for .NET users
>> 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. The collation must be set to case-sensitive (CS) and accent-sensitive
(AS).
To enable TCP connection for SQL, you must open the SQL Server Configuration Manager and
enable TCP/IP within SQL Server 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 objects within this database.
Preparations
Before you get to the task of creating a new database for SonarQube, you need to complete a few
preparations.
1. Launch SSMS
Example: .\\SQLExpress
2. Check collation
Additional Configurations 39
SonarQube Setup Guide for .NET users
Additional Configurations 40
SonarQube Setup Guide for .NET users
You need the collation to be both case sensitive (CS) and accent sensitive (AS).
If either is different, you will need to be sure to select the case-sensitive version when you set the
collation for the database you will be create.
3. Check authentication
Additional Configurations 41
SonarQube Setup Guide for .NET users
Walkthrough
Within SSMS right-click on the Databases node (just under the Server\Instance node).
Select New Database…
Additional Configurations 42
SonarQube Setup Guide for .NET users
Additional Configurations 43
SonarQube Setup Guide for .NET users
In the Options node, click on the Collation drop-down list and look for the case-sensitive (CS)
and accent-sensitive (AS) variant of the server collation you made note of above.
Additional Configurations 44
SonarQube Setup Guide for .NET users
Within SSMS right-click on the SecurityLogins node (just under the Server\Instance node).
Select
Additional Configurations 45
SonarQube Setup Guide for .NET users
Additional Configurations 46
SonarQube Setup Guide for .NET users
In the User Mapping node, ensure the SonarUser has been mapped to the Sonar database and
check the db_owner database role membership
Additional Configurations 47
SonarQube Setup Guide for .NET users
Additional Configurations 48
SonarQube Setup Guide for .NET users
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.
Additional Configurations 49
SonarQube Setup Guide for .NET users
Enter the name of the database you created, for example Sonar.
Additional Configurations 50
SonarQube Setup Guide for .NET users
By default, the SonarQube portal allows anonymous access, although SonarQube does provide a
complete authentication and authorization mechanism to manage security. As users of the portal will be
able to view the analyzed source code, it is recommended that the anonymous access to the site not be
permitted.
Additional Configurations 51
SonarQube Setup Guide for .NET users
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 Bootstrapper plugin 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, Resharper and StyleCop) because it did not provide any way to pass additional settings to
those plugins. In version 1.0, global settings can be specified in the new SonarQube.Analysis.xml file or
passed on the command line. Settings specific to a particular MSBuild project can be specified in the
MSBuild project file.
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 is still necessary for Java to be pre-installed on the machine). Previously the
user had to manually install the SonarQube.Integration.ImportBefore.targets file. This file is now
automatically installed to the appropriate per-user location for MSBuild 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 as through Team Build. Finally, the name of the exe changed from
SonarQube.MSBuild.Runner.exe in the preview to MSBuild.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 file to the
SonarQube.Analysis.xml file.
If you had added any additional settings in the sonar-runner.properties file then these settings
will need to be moved to the new SonarQube.Analysis.xml file.
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 from SonarQube.MSBuild.Runner.exe to MSBuild.SonarQube.Runner.exe.
Add begin to the Pre-build script arguments
Add 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 you do wish to do so then perform the following steps:
Contents
The analysis process can be configured by passing additional analysis settings to the MSBuild SonarQube
Runner. Global settings can either be passed on the command line or in a settings file. Project-level
settings can be set in the MSBuild project file.
Individual global settings can be supplied on the command using the /d switch:
Additional settings can also be supplied in a settings file. The location of the settings file can be specified
on the command line using the /s switch:
If the /s command-line switch is not supplied then the MSBuild SonarQube Runner will look for a default
settings file called SonarQube.Analysis.xml in the same directory as the MSBuild.SonarQube.Runner
executable file. The default settings file shipped with the MSBuild SonarQube Runner contains
placeholders for the most commonly-required settings and can be used as a template for custom settings
files.
Non-global (i.e. settings specific to a particular MSBuild project) can be specified in the MSBuild project file
for the project. For example, the MSBuild.SonarQube.Integration.targets file sets the
sonar.stylecop.projectFilePath property as follows:
xml
<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 being analysed, 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):
SonarQube analyses test projects and product projects differently so it is important that projects are
correctly classified as being either test or product projects.
The MSBuild SonarQube Runner will automatically recognise MSTest unit test projects as being test
projects (because of the presence of a well-known guid in the project file).
Other test projects are recognised by applying a regular expression to the full path of the project file. The
regular expression can configured in the SonarQube portal on the settings page for the C# plugin:
Finally, it is possible to manually classify a project by setting the MSBuild property SonarQubeTestProject,
e.g.
xml
<PropertyGroup>
<!-- Mark the project as being a test project -->
<SonarQubeTestProject>true</SonarQubeTestProject>
</PropertyGroup>
Certain types of project will automatically be excluded from analysis. For example, Microsoft Fakes
generates additional projects during 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>
Files that are generated by custom tools within Visual Studio are automatically excluded from analysis,
such as the xxx.Designer.cs file generated from a .resx file:
xml
<Compile Include="Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
These files are excluded because they are marked as generated by Visual Studio. It is possible to
manually exclude a specific file from analysis by setting the MSBuild metadata item SonarQubeExclude to
true as follows:
xml
<ItemGroup>
<Compile Include="MyFile.cs">
<!-- Exclude the file from analysis -->
<SonarQubeExclude>true</SonarQubeExclude>
</Compile>
</ItemGroup>
Conclusion
During our adventure of setting up SonarQube with an existing deployment of Team Foundation Server,
we introduced you to Technical Debt; we gave you the prerequisites and installation configurations, and
covered the topologies. We hope we have achieved our goals for the guidance, get you up and running
quickly with SonarQube and Team Foundation Server so you can start your analysis of your technical debt
and begin your debt reduction strategy.
Sincerely
The Visual Studio ALM Rangers includes members from the Visual Studio Product group, Microsoft
Services, Microsoft Most Valuable Professionals (MVP) and Visual Studio Community Leads. Their
mission is to provide out-of-band solutions to missing features and guidance. A growing Rangers Index is
available online.
Home
Solutions
Membership
- Contributors: Anil Chandra Lingam, Baruch Frei, Brian Blackman, Cesar Solis Brito, Clementino de
Mendonca, Darren Rich, Duncan Pocklington, Hosam Kamel, Jean-Marc Prieur, Jeff Bramwell, Marcelo
Silva, Mathew Aniyan, Michael Wiley
Conclusion 58