SonarScanner for .NET
Beginning with the Sonar Scanner for .NET v8, the way the sonar.projectBaseDir
property is automatically detected has changed which has an impact on the files that are analyzed and how relative properties, such as sonar.exclusions
and sonar.test.exclusions
, are resolved.
To customize the behavior, you can set the sonar.projectBaseDir
property to point to a directory that contains all the source code you want to analyze. The path may be relative (to the directory from which the analysis was started) or absolute.
The SonarScanner for .NET is the recommended way to launch an analysis for projects built using MSBuild
or dotnet
. It is the result of a collaboration between SonarSource and Microsoft.
The SonarScanner for .NET is distributed as a .NET Core Global Tool, in the Sonar extension for Azure DevOps, and in the Sonar extension for Jenkins.
It supports .NET Core on every platform (Windows, macOS, Linux).
Prerequisites
- SonarQube 10.4 requires the SonarScanner for .NET 5.14+.
- From version 7.0, Java is no longer required because the scanner will download it automatically.
- If internet access is limited in your configuration, skip the JRE provisioning and use the Java version installed locally.
- If you are running a previous version of the scanner you will need at least the minimal version of Java supported by your SonarQube server.
- The SDK corresponding to your build system:
- If you are using the .NET Framework version of the scanner you will need .NET Framework v4.6.2 or above. For commercial versions of SonarQube to benefit from security analysis you will need .NET Framework v4.7.2 or above
- If you are using the .NET version of the scanner or the .NET Core Global Tool you will need .NET Core SDK 3.1 or above
- The minimum supported version for SonarQube is now 8.9. We recommend that you upgrade to the 9.9 LTA (or newer) because support for older versions will end in January 2025.
- The scanner will fail to start if an older version of SonarQube is detected.
The flavor used to compile the Scanner for .NET (either .NET Framework, .NET Core or .NET) is independent of the .NET version the project you want to analyze has been built with. Concretely, you can analyze .NET Core code with the .NET Framework version of the Scanner. It's only relevant depending on your OS, and on the versions of .NET SDKs that are installed on your build machine.
Installation
.NET Core global tool
The --version
argument is optional. If it is omitted the latest version will be installed. The full list of releases is available on the NuGet page.
.NET Core Global Tool is available from .NET Core 3.1+.
Standalone executable
- Expand the downloaded file into the directory of your choice. We'll refer to it as
<INSTALL_DIRECTORY>
in the next steps.- On Windows, you might need to unblock the ZIP file first (right-click file > Properties > Unblock).
- On Linux/OSX you may need to set execute permissions on the files in
<INSTALL_DIRECTORY>/sonar-scanner-(version)/bin
.
- Uncomment, and update the global settings to point to your SonarQube server by editing
<INSTALL_DIRECTORY>/SonarQube.Analysis.xml
. Values set in this file will be applied to all analyses of all projects unless overwritten locally.
Consider setting file system permissions to restrict access to this file.
- Add
<INSTALL_DIRECTORY>
to yourPATH
environment variable.
If your SonarQube server is secured
If your SonarQube server is configured with HTTPS and a self-signed certificate then you must add the self-signed certificate to the trusted CA certificates of the SonarScanner. In addition, if mutual TLS is used then you must define the access to the client certificate at the SonarScanner level.
See Managing the TLS certificates on the client side.
Use
You can invoke the Scanner using arguments with both dash (-
) or forward-slash (/
) separators. Either of the following will work:
SonarScanner.MSBuild.exe begin /k:"project-key"
SonarScanner.MSBuild.exe begin -k:"project-key"
There are two versions of the SonarScanner for .NET. In the following commands, you need to pass an authentication token using the sonar.token
property. In addition, the default URL points to a SonarCloud path therefore, you must also direct the invocation to your /d:sonar.host.url
.
Any project file accepted by MSBuild.exe or dotnet can be used, for example .sln
, .proj
, .csproj
, or .vbproj
.
"Classic" .NET framework invocation
The first version is based on the "classic" .NET Framework. To use it, execute the following commands from the root folder of your project:
.NET Core and .NET Core global tool invocation
The second version is based on .NET Core which has a very similar usage:
The .NET Core version can also be used as a .NET Core Global Tool. After installing the Scanner as a global tool as described above it can be invoked as follows:
In summary, the invocation of the SonarScanner for .NET will depend on the scanner flavor you want to use:
Scanner Flavor | Invocation |
---|---|
.NET Core Global Tool | dotnet sonarscanner begin etc. |
.NET Core 3.1+ | dotnet <path to SonarScanner.MSBuild.dll> etc. |
.NET Framework 4.6.2+ | SonarScanner.MSBuild.exe begin etc. |
Notes:
- The .NET Core version of the scanner does not support TFS XAML builds and automatic finding/conversion of Code Coverage files. Apart from that, all versions of the Scanner have the same capabilities and command line arguments.
Analysis steps
The construction of your pipeline will be slightly different according to your DevOps platform integration. Please see the appropriate pages for your platform:
See the GitHub integration page.
See the Bitbucket Cloud integration page.
See the GitLab integration page.
See the Azure DevOps integration page.
Begin
The begin step is executed when you add the begin
command line argument. It hooks into the build pipeline, downloads SonarQube quality profiles and settings, and prepares your project for analysis.
Begin step command line parameters
/k:<project-key>
- [required] Specifies the key of the analyzed project in SonarQube
/n:<project name>
- [optional] Specifies the name of the analyzed project in SonarQube.
- Adding this argument will overwrite the project name in SonarQube if it already exists.
/v:<version>
- [recommended] Specifies the version of your project.
/d:sonar.token=<token>
- [recommended] Requires version 5.13+. Use
sonar.login
for earlier versions. - Specifies the authentication token used to authenticate with SonarQube. If this argument is added to the Begin step, it must also be added to the End step.
- [recommended] Requires version 5.13+. Use
/d:sonar.clientcert.path=<ClientCertificatePath>
- [optional] Specifies the path to a client certificate used to access SonarQube in case mutual TLS is used. The certificate must be password protected.
/d:sonar.clientcert.password=<ClientCertificatePassword>
- [optional] Specifies the password for the client certificate used to access SonarQube in case mutual TLS is used. If this argument is added to the Begin step, it must also be added to the End step.
/d:sonar.verbose=true
- [optional] Sets the logging verbosity to detailed. Add this argument before sending logs for troubleshooting.
/d:sonar.dotnet.excludeTestProjects=true
- [optional] Excludes Test Projects from analysis. Add this argument to improve build performance when issues should not be detected in Test Projects.
/d:sonar.http.timeout
- [optional] Specifies the time in seconds to wait before the HTTP requests time out.
/d:<analysis-parameter>=<value>
- [optional] Specifies an additional SonarQube analysis parameter, you can add this argument multiple times. Please note that the
sonar.sources
andsonar.tests
parameters are not supported.
- [optional] Specifies an additional SonarQube analysis parameter, you can add this argument multiple times. Please note that the
/s:<custom.analysis.xml>
- [optional] Overrides the
$install_directory/SonarQube.Analysis.xml
. You need to give the absolute path to the file.
- [optional] Overrides the
/d:sonar.plugin.cache.directory=<path_to_directory>
- [optional] Requires version 5.15+. Overrides the path where the scanner downloads its plugins. Plugins that are already present will not be downloaded again, unless newer versions are available.
- You can provide a relative or an absolute path.
- Defaults to the machine's temporary files directory.
/d:sonar.scanner.scanAll
- [optional] Enables and Disables the analysis of multiple file types. See the Multi-language support article for the full details. Unless manually excluded, the files linked by the
.csproj
project file will be analyzed even if the value is false. - Defaults to true.
- [optional] Enables and Disables the analysis of multiple file types. See the Multi-language support article for the full details. Unless manually excluded, the files linked by the
For detailed information about all available parameters, see the Analysis parameters page.
The "begin" step will modify your build like this:
- the active
CodeAnalysisRuleSet
will be updated to match the SonarQube quality profile WarningsAsErrors
will be turned off
If your build process cannot tolerate these changes we recommend creating a second build job for SonarQube analysis.
Build
Between the begin
and end
steps, you need to build your project, execute tests, and generate code coverage data. This part is specific to your needs and it is not detailed here. See .NET test coverage for more information.
The rules configured in your SonarQube Quality Profile are run during the build, and it is expected that analyzing with SonarQube can increase build duration from 4 to 8 times. The impact on duration will vary by project and by what rules are enabled; some rules are simple to execute and others take additional time to have the impact and precision expected of them.
End
The end step is executed when you add the "end" command line argument. It cleans the MSBuild/dotnet
build hooks, collects the analysis data generated by the build, the test results, and the code coverage, and then uploads everything to SonarQube. There are only two additional arguments that are allowed for the end step.
End step command line parameters
/d:sonar.token=<token>
- This argument is required if it was added to the begin step.
/d:sonar.clientcert.password=<ClientCertificatePassword>
- This argument is required if it was added to the begin step. Specifies the password for the client certificate used to access SonarQube in case mutual TLS is used.
Known limitations
- MSBuild versions 14 and older are not supported. MSBuild 15 is deprecated and support will be removed in a future version. We recommend using MSBuild 16 as a minimal version.
- Web Application projects are supported. Legacy Web Site projects are not.
- Projects targeting multiple frameworks and using preprocessor directives could have slightly inaccurate metrics (lines of code, complexity, etc.) because the metrics are calculated only from the first of the built targets.
Code coverage
In an Azure DevOps / TFS environment, test files are automatically retrieved as follows:
- A search is done for .trx files in any
TestResults
folder located under$Build.SourcesDirectory
. - If no .trx files are found there, then a fallback search is performed under
$Agent.TempDirectory
.
Once the .trx files have been found, their .coverage counterparts are retrieved and converted to .coveragexml files for upload to SonarCloud.
As stated above, this will work only with the .NET Framework version of the scanner.
See .NET test coverage for more information.
Excluding projects from analysis
Some project types, such as Microsoft Fakes, are automatically excluded from analysis. To manually exclude a different type of project from the analysis, place the following in its .xxproj file.
Advanced topics
Analyzing MSBuild 12, 14, and 15 projects with MSBuild 16
The Sonar Scanner for .NET requires your project to be built with MSBuild 16. We recommend installing Visual Studio 2022 or later on the analysis machine in order to benefit from the integration and features provided with the Visual Studio ecosystem (VSTest, MSTest unit tests, etc.).
Projects targeting older versions of the .NET Framework can be built using MSBuild 16 by setting the "TargetFrameworkVersion" MSBuild property as documented by Microsoft:
For example, if you want to build a .NET 3.5 project, but you are using a newer MSBuild version:
If you do not want to switch your production build to MSBuild 16, you can set up a separate build dedicated to the SonarQube analysis.
Detection of test projects
You can read a full description of that subject on our wiki here.
Per-project analysis parameters
Some analysis parameters can be set for a single MSBuild project by adding them to its .csproj file.
Analyzing languages other than C# and VB
For newer SDK-style projects used by .NET Core, .NET 5, and later, the SonarScanner for .NET will analyze all file types that are supported by the project type (for example, esproj
), MSBuild, and the available language plugins unless explicitly excluded. As described in the Multi-language article below, some file types are automatically included in the SonarScanner for .NET v8.0 and newer.
If you have an esproj
project type, make sure to use Microsoft.VisualStudio.JavaScript.SDK version 0.5.74-alpha or later to ensure the SonarScanner for .NET recognizes the esproj contents for scanning.
For older-style projects, the scanner will only analyze files that are listed in the .csproj
or .vbproj
project file. Normally this means that only C# and VB files will be analyzed. To enable the analysis of other types of files, include them in the project file.
Even if you disable multi-file analysis (see below), any files included by an element of the ItemTypes
in this list will be analyzed automatically. For example, the following line in your .csproj or .vbproj file will enable the analysis of all JavaScript files in the directory foo\bar because the content is one of the ItemTypes
that are automatically analyzed.
Additionally, <Compilation Remove=”FileName.ext”/>
and <None Remove=”FileName.ext”/>
attributes in .NET project files (either .csproj or .vbproj) work differently depending on the file type and if the sonar.scanner.scanAll property
(the multi-language analysis feature) is enabled or not.
- C# and VB.NET files will not be analyzed since they are not part of the compilation, and therefore the Roslyn analyzers will not run on them.
- When the multi-language analysis feature is enabled, additional language file types (such as JavaScript, TypeScript, SQL, etc.) are added to the scope and will be analyzed. To ignore specific language file types, we recommend that you use the
sonar.exclusions
property. See the Multi-language analysis article (below) for a list of file types automatically picked up by the scanner.
You can also add ItemTypes
to the default list by following these directions.
You can check which files the scanner will analyze by looking in the file .sonarqube\out\sonar-project.properties after MSBuild has finished.
File type extensions can be manually excluded from the analysis using sonar.exclusions
. See the File exclusion and inclusion article on the Analysis scope page for more details.
Using SonarScanner for .NET with a proxy
On build machines that connect to the Internet through a proxy server you might experience difficulties connecting to SonarQube. To instruct the Java VM to use specific proxy settings use the following value:
Where yourProxyHost and yourProxyPort are the hostname and the port of your proxy server. There are additional proxy settings for HTTPS, authentication and exclusions that could be passed to the Java VM. For more information, see the following article: https://docs.oracle.com/javase/8/docs/technotes/guides/net/proxies.html.
You also need to set the appropriate proxy environment variables used by .NET. HTTP_PROXY
, HTTPS_PROXY
, ALL_PROXY
, and NO_PROXY
are all supported. You can find more details here.
Multi-language analysis
The SonarScanner for .NET v8.0 automatically analyzes these languages using the sonar.scanner.scanAll
parameter. These file types are automatically picked up by the scanner:
- CSS (.css,.less,.scss,.sass)
- HTML (.html,.xhtml,.cshtml,.vbhtml,.aspx,.ascx,.rhtml,.erb,.shtm, .shtml,.cmp,.twig)
- Javascript (.js,.jsx,.cjs,.mjs,.vue). See the JavaScript/TypeScript test coverage page for details to adjust your setup.
- JSON (.json)
- PLSQL (.sql,.pks,.pkb)
- SQL (.tsql)
- TypeScript (.ts,.tsx,.cts,.mts). See the JavaScript/TypeScript test coverage page for details to adjust your setup.
- YAML (.yaml,.yml)
File type extensions can be found and configured in the SonarQube UI; see the Setting the scope by file type article for more details. Additionally, file types can be manually excluded from the analysis using sonar.exclusions
. See the Wildcard patterns article on the Analysis scope page for a list of patterns and examples.
Unless manually excluded, the files linked by the .csproj
project file will be analyzed even if the value is false.
Multi-Language analysis is enabled by default. If this was not intended and you have issues such as hitting your LOC limit or analyzing unwanted files, you can set /d:sonar.scanner.scanAll=false
in the Begin step to turn off multi-language analysis.
Known issues
I have multiple builds in the same pipeline, each of them getting analyzed even if the Run Code Analysis has already been executed:
The scanner doesn't uninstall the global ImportBefore
targets to support concurrent analyses on the same machine. The main effect is that if you build a solution where a .sonarqube folder is located nearby, then the sonar-dotnet
analyzer will be executed along with your build task.
To avoid that, you can disable the targets file by adding a build parameter:
Excluding files in certain directories
It is known that the SonarScanner for .NET can’t filter the excluded files/folders from the analysis, which happens during the build. The sonar.exclusions
property is only used to filter issues sent to SonarQube during the end step.
As a workaround, you can try to add an .editorconfig
file in your Migrations
folder to override the severity of the Sonar rules:
Unfortunately, you may have to manually do this for every rule.
Was this page helpful?