Using Sonar Cloud on .NET Core with Travis

Note to self since I spent a frustratingly long time on this. To analyse your .NET Core project with Sonar on Linux (using Travis in my case since it’s an open source project), you need the following:

  • Have a machine with Mono and .NET Core installed
  • Download the MSBuild Sonar Analyzer and ensure that the scripts are executable
  • Execute it with the right amount of parameters

For reference, some build steps out of a Travis YAML file I’ve been working for NGenerics :

Bash
1
2
3
4
5
- mono ../tools/sonar/SonarQube.Scanner.MSBuild.exe begin /n:NGenerics /k:ngenerics-github /d:sonar.login=${SONAR_TOKEN} /d:sonar.host.url="https://sonarcloud.io" /d:sonar.cs.vstest.reportsPaths="*/TestResults/.trx" /v:"2.0"
- dotnet build
- dotnet test NGenerics.Tests --logger:trx
- dotnet test NGenerics.Examples --logger:trx
- mono ../tools/sonar/SonarQube.Scanner.MSBuild.exe end /d:sonar.login=${SONAR_TOKEN}

Notes:

  • The CLI scanner does not work for C# code at the time of writing. The MSBuild scanner works.
  • The MSBuild scanner requires Mono as the SonarQube team is still in the progress of migrating some dependencies.
  • ${SONAR_TOKEN} is an environment variable injected by Travis that contains an authentication token. The VSTest reports come from NUnit tests via the “–logger:trx” parameter passed to dotnet run.
  • You need to pass the property sonar.login to the “end” step of the MSBuild scanner since that information is not persisted to disk when running “begin”.

Hope this saves someone some time - the feedback cycle is incredibly long as the Sonar scan tends to break on the last step.

Photo by Shane Colella on Unsplash