Publishing .NET Core code analysis to SonarCloud from Azure build pipeline
Image from Pexels

Publishing .NET Core code analysis to SonarCloud from Azure build pipeline

How to get your code analysis in SonarCloud directly from Azure DevOps build pipeline

Code analysis is and important part of application development. It can point to a potential bottle necks or code cluttering during the development process. Therefore it is important to have some kind of code analysis of application you are working on.

SonarCloud is a great place to have your code annualized. It provides great and simple UI where you can find all the metrics and performances of the code in your solution. If you are using Azure DevOps for your project release deployments, it is quite easy to configure SonarCloud as a part of your build pipeline and that way you get your code analysis automated along with your build process.

Note

For OpenSource and public projects SonarCloud is free, but if you want to run analysis on your private repositories, you can upgrade your account to paid for a decent price https://sonarcloud.io/about/pricing

Setting up SonarCloud project

Sonar cloud project analysis is pretty simple. Once you create your account at sonarcloud.io, you need to create new project analysis. The wizard lets you pick your repository from GitHub or any other Git repository (Azure DevOps or BitBucket) but I prefer to do this manually.

Sonar Cloud

For project key, using auto generated GUID is just fine. You can either do it from Visual Studio > Tools > Create GUID or use guidgenerator.com. As I mentioned, public, open source project can be analyzed for free, but your analysis are available to publish as your repository is. For analyzing private repositories, you need to switch to paid plan. For the complicity, I will just do everything with my public sample project I have on Azure DevOps using free plan on SonarCloud.

New Guid

Project name is the friendly name of the project you are going to use to navigate though your dashboard. This is all you need to start with analyzing your code. Now we are going to see how to automate code analysis result publishing to SonarClud from Azure Build pipeline and automate analysis reporting directly from the pipeline.

Setting up the build pipeline for ASP.NET Core

Azure DevOps has already predefined build pipeline for ASP.NET Core project, so to have your basic build pipeline is quite simple. Once you start the new Build pipeline in Azure DevOps portal and you are done with repository selection, all you need is to pick ASP.NET Core pipeline template and Azure DevOps will add all the basic steps for building and testing ASP.NET Core project. Most of the time as soon as the pipeline definition is created you can start using it.

Note

I am still not used to Azure DevOps YAML syntax, so I am using classic UI for pipeline definition. Make sure you switch to classic mode on initial build pipeline screen "Use the classic editor to create a pipeline without YAML"

Core Build Pipeline

Before you start modifying default ASP.NET Core build pipeline, make sure you install SonarCloud extension from the Azure DevOps marketplace (https://marketplace.visualstudio.com/items?itemName=SonarSource.sonarcloud). Once you have this extension installed you will have SonarCloud tasks available to add to your pipeline.

Before we start adding SonarCloud tasks to our build pipeline, we need to generate SonarCloud token which we'll use to register connection in our Azure DevOps. Navigate to security section in SoanrCloud dashboard, or just navigate to https://sonarcloud.io/account/security/ and generate your token which you will later use to connect your Azure DevOps to SonarCloud.

Token

There are several SonarCloud tasks we need to add to the pipeline in order to collect code analyses and upload them to SonarCloud. You need to add the following tasks the pipeline in the exact sequence as in this sample pipeline

Pipeline Sonar Tasks

You can see that our first task is alerting that we need to update settings. This is because we did not connect to the SonarCloud from Azure DevOps just yet. Now that generated token plays essential role. We'll use it to define connection to our SonarCloud dashboard from the Azure DevOps. In pipeline task Prepare analysis on SonarCloud configure SonarCloud Service Endpoint property and use previously generated token from SonarCloud website security section. If everything is fine, you will have option to pick your organization which you defined when registering account on SonarCloud.

Azure Connection

Once this step is done, you will have you SonarAccount linked to your Azure DevOps account and you will be able to just pick the connection next time you define a new build definition.

Unfortunately, although it is not mentioned in the documentation online you need an additional step in order to prepare your test results for uploading to SonarCloud.

Piepeline

Note

Make sure that you PowerShell task Working Directory property is set to $(Agent.TempDirectory) value in order to pick up test results. I have execute the build definition on "Hosted Windows 2019 with VS2019" build agent and I am not sure it will work properly on any other type of the build agent in Azure DevOps. If you have tried using any other agent, please share your experience

The following is the PowerShell script which will prepare the unit test result for SonarCloud analysis report publish step.

Get-ChildItem -Recurse -Filter "*.coverage" | % {
$outfile = "$([System.IO.Path]::GetFileNameWithoutExtension($_.FullName)).coveragexml"
$output = [System.IO.Path]::Combine([System.IO.Path]::GetDirectoryName($_.FullName), $outfile)
"Analyse '$($_.Name)' with output '$outfile'..."
. $env:USERPROFILE\.nuget\packages\microsoft.codecoverage\16.6.1\build
etstandard1.0\CodeCoverage\CodeCoverage.exe analyze /output:$output $_.FullName
}
"Done"
    

In order for the script above to execute successfully, you need to reference Microsoft.CodeCoverage NuGet package. When building the project, package will be restored to the current user folder under .nuget folder along with CodeCoverage.exe tool which PowerShell scripts uses to convert .coverage files to xml format file.

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>

    <IsPackable>false</IsPackable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="AutoFixture" Version="4.11.0" />
    <PackageReference Include="Microsoft.CodeCoverage" Version="16.6.1" />
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.5.0" />
    <PackageReference Include="Moq" Version="4.14.1" />
    <PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
    <PackageReference Include="xunit" Version="2.4.0" />
    <PackageReference Include="xunit.runner.visualstudio" Version="2.4.0" />
    <PackageReference Include="coverlet.collector" Version="1.2.0" />
  </ItemGroup>

</Project>

    

Make sure that the package version in .csproj and in path in PowerShell script match. Otherwise the script will fail as it will not be able to find CodeCoverage.exe file.

You are all good t go and once you run your build definition and the build process is finished successfully, you will see your SonarCloud project result in the dashboard with all the metrics SonarCloud collects.

Sonar Alaysis 

Disclaimer

Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.


About the author

DEJAN STOJANOVIC

Dejan is a passionate Software Architect/Developer. He is highly experienced in .NET programming platform including ASP.NET MVC and WebApi. He likes working on new technologies and exciting challenging projects

CONNECT WITH DEJAN  Loginlinkedin Logintwitter Logingoogleplus Logingoogleplus

JavaScript

read more

SQL/T-SQL

read more

Umbraco CMS

read more

PowerShell

read more

Comments for this article