SonarScanner for .NET & SonarCloud (2024)

In version 5.0 of the SonarScanner, we changed the name of the SonarScanner for MSBuild to SonarScanner for .NET.

The documentation is updated with the new name and we will call the scanner SonarScanner for .NET moving forward.

The SonarScanner for .NET is the recommended way to launch an analysis for projects using themsbuildordotnetbuild tools. It is the result of acollaboration between SonarSource and Microsoft.

SonarScanner for .NET is distributed as a standalone command-line executable, as an extension forAzure DevOps, and as a plugin forJenkins.

It supports .NET Core on every platform (Windows, macOS, Linux).

Prerequisites

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

Standalone executable

  • Expand the downloaded file into the directory of your choice. We'll refer to it as$install_directoryin the following steps.
    • On Windows, you might need to unblock the ZIP file first (right-clickFile > 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 SonarCloud 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:
<SonarQubeAnalysisProperties xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.sonarsource.com/msbuild/integration/2015/1"> <Property Name="sonar.host.url">https://sonarcloud.io</Property> <Property Name="sonar.token">[my-user-token]</Property></SonarQubeAnalysisProperties>
  • Add$install_directoryto your PATH environment variable.

.NET Core Global Tool

dotnet tool install --global dotnet-sonarscanner --version x.x.x

The--versionargument is optional. If it is omitted, the latest version will be installed. A complete list of releases is available on theNuGet page

.NET Core Global Tool is available from .NET Core 3.1+.

Use

You can invoke the Scanner using arguments with both dash (-) or forward-slash (/) separators. For example:

SonarScanner.MSBuild.exe begin /k:"project-key" or

SonarScanner.MSBuild.exe begin -k:"project-key"

There are two versions of the SonarScanner for .NET. In the following commands, you need to pass anauthentication tokenusing thesonar.tokenproperty.

"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:

SonarScanner.MSBuild.exe begin /k:"project-key" /o:"<organization>" /d:sonar.token="<token>"MSBuild.exe <path to solution.sln> /t:RebuildSonarScanner.MSBuild.exe end /d:sonar.token="<token>"

Note: On macOS or Linux, you can also usemono <path to SonarScanner.MSBuild.exe>.

.NET Core and .NET Core Global Tool invocation

The second version is based on .NET Core which has a very similar usage:

dotnet <path to SonarScanner.MSBuild.dll> begin /k:"project-key" /o:"<organization>" /d:sonar.token="<token>"dotnet build <path to solution.sln> --no-incrementaldotnet <path to SonarScanner.MSBuild.dll> end /d:sonar.token="<token>" 

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:

dotnet tool install --global dotnet-sonarscannerdotnet sonarscanner begin /k:"project-key" /o:"<organization>" /d:sonar.token="<token>"dotnet build <path to solution.sln> --no-incrementaldotnet sonarscanner end /d:sonar.token="<token>"

In summary, the invocation of the SonarScanner for .NET will depend on the scanner flavor:

Scanner FlavorInvocation
.NET Core Global Tooldotnet sonarscanner beginetc.
.NET Core 3.1+dotnet <path to SonarScanner.MSBuild.dll>etc.
.NET Framework 4.6.2+SonarScanner.MSBuild.exe beginetc.

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

Begin

Thebeginstep is executed when you add thebegincommand-line argument. It hooks into the build pipeline, downloads SonarCloud 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 SonarCloud.
  • /n:<project name>
    • [optional] Specifies the name of the analyzed project in SonarCloud.
    • Adding this argument will overwrite the project name in SonarCloud if it already exists.
  • /v:<version>
    • [recommended] Specifies the version of your project.
  • /o:<organization>
    • [required] Specifies the name of the target organization in SonarCloud.
  • /d:sonar.token=<token> or <username>
    • [recommended] Specifies the authentication token or username used to authenticate with to SonarCloud.
    • 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:<analysis-parameter>=<value>
    • [optional] Specifies an additional SonarCloud analysis parameter.
    • You can add this argument multiple times.

For detailed information about all available parameters, seeAnalysis Parameters.

The "begin" step will modify your build like this:

  • the activeCodeAnalysisRuleSetwill be updated to match the SonarCloud quality profile
  • WarningsAsErrorswill be turned off

If your build process cannot tolerate these changes we recommend creating a second build job for SonarCloud analysis.

Build

Between thebeginandendsteps, 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 SonarCloud Quality Profile are run during the build, and it is expected that analyzing with SonarCloud 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 theMSBuild/dotnetbuild hooks, collects the analysis data generated by the build, the test results, and the code coverage, and then uploads everything to SonarCloud. There are only two additional arguments that are allowed for the end step.

End step command line parameters:

  • /d:sonar.token=<token> or /d:sonar.token=<username>
    • This argument is required if it was added to the begin step.

Known limitations

  • MSBuild versions older than 15 are not supported.
  • 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.trxfiles in anyTestResultsfolder located under$Build.SourcesDirectory.
  • If no .trx files are found there, then a fallback search is performed under$Agent.TempDirectory.

Once the.trxfiles have been found, their.coveragecounterparts are retrieved and converted to.coveragexmlfiles for upload to SonarCloud.

As stated above, this will work only with the .NET Framework version of the scanner.

SeeTest Coveragefor more information.

Excluding projects from analysis

Some project types, such asMicrosoft Fakes, are automatically excluded from the analysis. To manually exclude a different type of project from the analysis, place the following in its.xxprojfile.

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

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 2017 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:

MSBuild.exe /t:Rebuild /p:TargetFramework=net35

If you do not want to switch your production build to MSBuild 16, you can set up a separate build dedicated to the SonarCloud analysis.

Detection of test projects

You can read a full description of that subject on our wikihere.

Per-project analysis parameters

Some analysis parameters can be set for a single MSBuild project by adding them to its.csprojfile.

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

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 supported by the available language plugins unless explicitly excluded.

If you have anesprojproject type, make sure to useMicrosoft.VisualStudio.JavaScript.SDKversion 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 listed in the.csprojor.vbprojproject file. Usually, 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.

More specifically, any files included by an element of one of theItemTypesinthis listwill be analyzed automatically. For example, the following line in your.csprojor.vbprojfile:

<Content Include="foo\bar\*.js" />

will enable the analysis of all JS files in the directoryfoo\barbecauseContentis one of theItemTypeswhose includes are automatically analyzed.

You can also addItemTypesto the default list by followingthese directions.

You can check which files the scanner will analyze by looking in the file .sonarqube\out\sonar-project.properties after MSBuild has finished.

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:

SONAR_SCANNER_OPTS = "-Dhttp.proxyHost=yourProxyHost -Dhttp.proxyPort=yourProxyPort"

WhereyourProxyHostandyourProxyPortare 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, andNO_PROXYare all supported. You can find more detailshere.

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.

We don't uninstall the globalImportBeforetargets 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 thesonar-dotnet analyzer will be executed along with your build task.

To avoid that, you can disable the targets file by adding a build parameter:

msbuild /p:SonarQubeTargetsImported=truedotnet build -p:SonarQubeTargetsImported=true
SonarScanner for .NET & SonarCloud (2024)

FAQs

What is the use of SonarScanner in dotnet? ›

The SonarScanner for . NET is the recommended way to launch a SonarQube or SonarCloud analysis for Clean Code projects/solutions using MSBuild or dotnet command as a build tool.

What is the difference between SonarQube and SonarScanner? ›

Sonarqube provides the intelligence to execute a scan. SonarScanner is the scanner developed in-house by Sonar Source the organisation that developed SonarQube too.

What is the difference between SonarQube and SonarCloud? ›

SonarCloud is free for open-source projects and is offered as a paid subscription for private projects, priced per lines of code. SonarQube is a self-managed open-source platform that helps developers create code devoid of quality and vulnerability issues.

What is SonarScanner used for? ›

The SonarScanner is the scanner to use when there is no specific scanner for your build system.

Why is SonarCloud used? ›

As a core element of our Sonar solution , SonarCloud completes the analysis loop to help you deliver clean code that meets high-quality standards. SonarCloud uses state-of-the-art techniques in static code analysis to find problems and potential problems in the code that you and your team write.

How to configure SonarQube for .net project? ›

How to Configure SonarQube?
  1. Step 1: Prerequisites. ...
  2. Step 2: SonarQube Server Installation. ...
  3. Step 3: The C# Plugins Installation in SonarQube. ...
  4. Step 4: SonarQube Runner Installation. ...
  5. Step 5: How to Run SonarQube Runner. ...
  6. Step 6: Viewing the Code Quality Analysis Results in SonarQube.

What are the disadvantages of SonarCloud? ›

Some of the limitations of SonarCloud are :
  • It does not support branch analysis (analysis of non-pull request branches other than the main branch).
  • It does not support multiple projects bound to a single repository (the monorepo strategy).
Jul 25, 2023

Is SonarCloud expensive? ›

SonarCloud Pricing

You pay upfront for a maximum number of private lines of code to be analyzed in your organization. SonarCloud pricing starts at €11/month for a maximum analysis of 100,000 LOC and can extend to €5,250/month for a maximum analysis of 20M LOC.

How do I analyze a project in SonarCloud? ›

If your project is eligible, SonarCloud will automatically trigger the first analysis. On this first analysis, the system will analyze the main branch of the project and the five most recently active pull requests. All you have to do is wait for the analysis to finish.

How to run a SonarScanner? ›

Running SonarScanner CLI from the zip file
  1. Expand the downloaded file into the directory of your choice. ...
  2. Add the <INSTALL_DIRECTORY>/bin directory to your path.
  3. Verify your installation by opening a new shell and executing the command sonar-scanner -h , or sonar-scanner.bat -h on Windows.

Does SonarQube support C#? ›

Sonar empowers developers to write Clean C# Code

As a developer, your priority is making sure the C# code you write today is readable, high quality and secure. The SonarQube user interface highlights the health of your New Code (changed or added) so you'll clearly know when your code is solid.

How to use SonarCloud? ›

SonarCloud HowTo
  1. Select your project name and click “Set Up” button.
  2. This is the screen when you first enter the newly added project, copy the organization and project key for later use.
  3. Create your own sonar token. ...
  4. Select Security tab. ...
  5. Copy the token.

What is the use of Sonar plugin? ›

Sonar Plugin API

The sonar-plugin-api is a Java API that is used to develop plugins. The API used to be part of SonarQube and released with it, but it is a separate component since v9. 5, with its own releases. You can find it here: sonar-plugin-api .

What is the use of SonarQube server? ›

SonarQube is a self-managed, automatic code review tool that systematically helps you deliver Clean Code. As a core element of our Sonar solution , SonarQube integrates into your existing workflow and detects issues in your code to help you perform continuous code inspections of your projects.

How do I start SonarScanner? ›

To run SonarScanner from the zip file, follow these steps:
  1. Expand the downloaded file into the directory of your choice. ...
  2. Add the <INSTALL_DIRECTORY>/bin directory to your path.
  3. Verify your installation by opening a new shell and executing the command sonar-scanner -h ( sonar-scanner.bat -h on Windows).

Top Articles
Latest Posts
Article information

Author: Dean Jakubowski Ret

Last Updated:

Views: 6656

Rating: 5 / 5 (50 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Dean Jakubowski Ret

Birthday: 1996-05-10

Address: Apt. 425 4346 Santiago Islands, Shariside, AK 38830-1874

Phone: +96313309894162

Job: Legacy Sales Designer

Hobby: Baseball, Wood carving, Candle making, Jigsaw puzzles, Lacemaking, Parkour, Drawing

Introduction: My name is Dean Jakubowski Ret, I am a enthusiastic, friendly, homely, handsome, zealous, brainy, elegant person who loves writing and wants to share my knowledge and understanding with you.