Beruflich Dokumente
Kultur Dokumente
NET users
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 and 2015
7. Additional Configurations
8. Appendix 1: Upgrading from v0.9 of the SonarQube MSBuild Runner
9. Appendix 2: Configuring the MSBuild SonarQube Runner
10. Appendix 3: Advanced MSBuild SonarQube Runner configuration
11. Conclusion
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 Serv er.
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
Prerequisites
At the time of this writing, the current version of SonarQube, v5.1, had the following requirements.
Java
A Java runtime is required for SonarQube to run. Supported JVMs:
Java (Oracle JRE 7 or greater or OpenJDK 7 or greater).
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
Hardware
At least 1GB RAM
Disk space requirements vary dependent upon the size and number of projects you wish to analyze using SonarQube. As a point
of reference, Nemo, the public instance of SonarQube, currently analyzes over 15 million lines of source code, which includes
four 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 hard
drive you have at your disposal for best results.
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
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.
>> 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
Copy sonarqube-5.1.zip and j re-8u45-w indow s-xXX.exe to your Team Foundation Server.
Install Jav a SE Runtime Env ironment on the destination server.
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
10
11
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 file.
This file is located in the conf folder located under the SonarQube installation folder. Example: C:\SonarQube\SonarQube5.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.
12
>>NOTE >> Before proceeding with the below configuration steps make sure you have configured SonarQube to use SQL
Server database instead of embedded database.
Search for and locate the entry for sonar.j dbc.username.
Uncomment (i.e. delete the leading #) the two sonar.j dbc settings circled in the screenshot above and replace sonar in
each setting with the database login name and password, respectively.
13
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:
sqlserv er://.\SQLExpress/Sonar;SelectMethod=Cursor
14
>> NOTE >> The jdbc driver installed with SonarQube requires the SQL Server Browser to be running. Check that it is running
using the Services Console.
Save and close the file.
5. OPTIONAL - Connect w ith integrated authenticaton on Window s
>> 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 Serv er connection string to use integrated security.
15
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
16
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 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.
17
>> 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.
18
19
%PATH%
Add the directory containing the MSBuild SonarQube Runner executable to the
%PATH%
command line:
20
21
MSBuild.SonarQube.Runner.exe
%PATH% .
MSBuild.SonarQube.Runner.exe begin /key:{SonarQube project key} /name:{SQ project name} /version:{SQ project version}
msbuild
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 an
internal or external command,operable program or batch file."
3. Run the MSBuild.SonarQube.Runner.exe end phase
MSBuild.SonarQube.Runner.exe end
22
Installing the TFS 2013 Object Model on a TFS 2015 Build Agent
Installing Visual Studio 2013 will install the necessary assemblies on the build agent. Alternatively, Microsoft provide a separate
installer for the object model that can be downloaded and installed as follows:
Browse to the Visual Studio Gallery
Search for "Team Foundation Server Object Model"
Choose the appropriate version of the 2013 object model for the updates you have applied to your TFS installation
Download and run the installer
Analyzing code stored in Visual Studio Online ("VSO") requires a TFS 2013 build agent
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 known
issue that is being tracked here [http://jira.sonarsource.com/browse/SONARMSBRU-73].
23
Analyze .NET Projects From Team Foundation Server 2013 and 2015
24
Analyze .NET Projects From Team Foundation Server 2013 and 2015
25
Analyze .NET Projects From Team Foundation Server 2013 and 2015
26
Analyze .NET Projects From Team Foundation Server 2013 and 2015
27
Analyze .NET Projects From Team Foundation Server 2013 and 2015
28
Analyze .NET Projects From Team Foundation Server 2013 and 2015
29
Analyze .NET Projects From Team Foundation Server 2013 and 2015
30
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).
31
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 the
general-purpose "Command Line" task to call MSBuild.SonarQube.Runner.exe (i.e. to do the same job as the "Pre-Build script"/"PostBuild 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 here
Install the MSBuild.SonarQube.Runner on the build agent
Create a new build definition that includes the MSBuild and (optionally) Visual Studio Test steps
Add Command Line build step before the MSBuild step and after the Visual Studio Test step
In the pre-build command line:
set the Tool field to point to the MSBuild.SonarQube.Runner.exe
supply 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 file 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.exe
set 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 so
you 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.
Analyze .NET Projects From Team Foundation Server 2013 and 2015
32
Additional Configurations
Running SonarQube as a Service on Windows
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
Additional Configurations
33
<SonarQube_Install_Directory>\bin\windows-x86-64\StartNTService.bat
5. Validate
From Services Console make sure the service is running correctly.
Additional Configurations
34
>> 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 Serv ice name to use if given on the General tab
Additional Configurations
35
Validate that the inter-service dependency has been added successfully by navigating to the SonarQube serv ice and check
the Dependencies tab.
Preparations
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.
Additional Configurations
36
Additional Configurations
37
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 database
you will be create.
3. Check authentication
Click on the Security node.
Since, by default, SonarQube utilizes SQL Authentication we need to ensure that Server Authentication is set to SQL Serv er
and Window s Authentication mode as shown in the screenshot below.
Additional Configurations
38
Walkthrough
1. Create database for use by SonarQube
Within SSMS right-click on the Databases node (just under the Server\Instance node).
Select New Database
Additional Configurations
39
Additional Configurations
40
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.
Additional Configurations
41
Additional Configurations
42
In the User Mapping node, ensure the SonarUser has been mapped to the Sonar database and check the db_ow ner
database role membership
Additional Configurations
43
Additional Configurations
44
Additional Configurations
45
Additional Configurations
46
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.
See Security section on the SonarQube site for more information.
Additional Configurations
47
%PATH% .
48
Contents
Supplying additional analysis settings
Classifying projects as test projects
Excluding artefacts from analysis
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.
<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.
49
50
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>
<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 set
conditionally at build time.
<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:
<ItemGroup>
<Compile Include="MyFile.cs">
<!-- Exclude the file from analysis -->
<SonarQubeExclude>true</SonarQubeExclude>
</Compile>
</ItemGroup>
51
Two possible methods of handling this scenario using a small amount of customisation and configuration are shown below. Both
methods conditionally set the SonarQubeExclude property based on additional data supplied during the build phase.
<PropertyGroup>
<TargetSQProjectKey>example.sqproject2</TargetSQProjectKey>
</PropertyGroup>
import the custom targets file using one of the standard MSBuild mechanisms e.g. either explicitly import it into the relevant
projects, or drop it in a location in which it will be automatically imported such as %ProgramFiles(x86)%\MSBuild*[MSBuild
version]*\Microsoft.Common.Targets\ImportBefore\.
at build time, pass the relevant SonarQube project key to MSBuild.
52
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:
This would have the desired effect of ensuring MSBuild project X is only analysed once.
c:\Web\ProjectA
c:\Web\ProjectB
c:\Framework\ProjectC
c:\Framework\ProjectD
c:\Framework\ProjectX
The following custom targets file selects the projects to analyse based on the file path:
REM Only analyse the web projects, regardless of which projects are included in the solution
REM Note: the backslash in the supplied path is escaped
msbuild Solution1.sln /p:SQPathFilter=c:\\web
REM Only analyse the framework projects
msbuild Solution2.sln /p:SQPathFilter=c:\\framework
53
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 Microsoft Visual Studio ALM Rangers
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
- Special thanks to: Colin Dembovsky
Conclusion
54