Using Sonar Cloud on .NET Core with Travis

Note to self since I just spent a frustratingly long time on this. In order to analyse your .NET Core project with Sonar on Linux (using Travis in my case since it's an open source project), the following is required:

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

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

- 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. Only the MSBuild scanner is supported.
  • The MSBuild scanner currently 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 are generated from NUnit tests via the "--logger:trx" parameter passed to dotnet run.
  • The property sonar.login needs to be passed 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 only on the last step.

Photo by Shane Colella on Unsplash