SonarQube Code Quality Check for .NET, Node.js and Gradle

By Sruthy

By Sruthy

Sruthy, with her 10+ years of experience, is a dynamic professional who seamlessly blends her creative soul with technical prowess. With a Technical Degree in Graphics Design and Communications and a Bachelor’s Degree in Electronics and Communication, she brings a unique combination of artistic flair…

Learn about our editorial policies.
Updated December 25, 2023

This comprehensive tutorial explains how to use SonarQube for .NET, Node.js, and Gradle programming languages with simple examples:

SonarQube as all are aware is a static code analysis tool that helps developers to analyze their code on a continuous basis and provides reports on issues like Bugs, Vulnerabilities, Code Smells, and Security.

SonarQube reduces complexity and increases the productivity of the developers by helping them to spend less time changing the code. SonarQube helps the developers detect errors early on in the life cycle and fix the issues before they can be deployed to the production environment.

So tools like SonarQube also help leads in the review of the code written by developers so as to deliver quality code to the production environment.

SonarQube for .NET, Node.js and Gradle

SonarQube For .NET, Node.Js And Gradle

SonarQube is truly a very important aspect of the development process from a code quality point of view which helps developers to enhance their coding skills.

In this article, we will look at how SonarQube can be used with the below programming languages.

logos

Analyze Code Quality

.NET Project

In this section, to get started, we will look at how to analyze the code quality of a Console and ASP.NET Core web application.

Sonar Scanner for .NET is the recommended way to do the analysis for .NET projects that are built using msbuild or dotnet utility. Download SonarScanner for .net and .NET Framework 4.6+. Add the Sonar Scanner folder to the PATH env variable.

For this analysis, I am using projects created using Visual Studio 2022 Community edition and .NET framework 6.0 which is built using msbuild utility.

Here are the steps for the analysis of the .NET project:

  1. Create SonarQube Project
  2. Generate Token
  3. Analysis of the C# console application and ASP .NET Web Application

#1) Create SonarQube Project

To create a project in SonarQube as an admin user, on the right side click on Create Project -> Manually.

Create Projects Manually

Add the name and key. Click on Set Up once done.

Create project

Select Locally as the option for analysis.

Select Locally

Further Reading => Explore the Simple Ways of Using SonarLint for Java

#2) Generate Token

Click on Generate Token.

Generate Token

Save the Token for future use. Click on Continue on the token screen.

Select .NET as a development platform and .NET Framework as the build tool.

.NET Framework

Code Analysis of the .NET project is very simple and you need to follow the 3 steps shown above.

#3) Analysis of C# Console program

Analysis of C# Console program

Sample C# console program

using System;
using System.IO;
using System.Text;

class WeekDay
{
    // Main Method
    static void Main(string[] args)
    {
        int weekday;

        //input the week day number between 0 to 6
        Console.Write("Enter weekday number (0-6): ");
        weekday = Convert.ToInt32(Console.ReadLine());

        switch (weekday)
        {
            case 0:
                Console.WriteLine("It is a SUNDAY");
                break;
            case 1:
                Console.WriteLine("It is a MONDAY");
                break;
            case 2:
                Console.WriteLine("It is a TUESDAY");
                break;
            case 3:
                Console.WriteLine("It is a WEDNESDAY");
                break;
            case 4:
                Console.WriteLine("It is a THURSDAY");
                break;
            case 5:
                Console.WriteLine("It is a FRIDAY");
                break;
            case 6:
                Console.WriteLine("It is a SATURDAY");
                break;

            //if no  value is matched
            default:
                Console.WriteLine("You have entered a wrong input ...");
                break;
        }

                Console.ReadLine();
    }
}

As per the steps for analysis to follow let’s look at executing each one of them.

Step #1: Prepare the project for analysis

Run the below command at the root of your .NET solution

SonarScanner.MSBuild.exe begin /k:”DSP” /d:sonar.host.url=”http://<Server>:9000″ /d:sonar.login=”Generated Token>”

SonarScanner.MSBuild.exe

Step #2: Build your project

MsBuild utility comes with Visual Studio 2022 and the path for the different editions is as below:

  • C:\Program Files\Microsoft Visual Studio\2022\Enterprise\MSBuild\Current\Bin
  • C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Current\Bin

I am using the Community edition so I have added the 2nd folder locations to the PATH env variable. Run the below command.

MsBuild.exe /t:Rebuild

Run Command

Step #3: Collect analysis data generated by build and upload to SonarQube

SonarScanner.MSBuild.exe end /d:sonar.login=”<Generated Token>”

Collect and Upload

Look at the SonarQube Dashboard for the analysis report.

Analysis Report

As the issues shown are fixed you will see no issues listed by running the 3 steps again.

Analysis of ASP.NET Core Web App

Analysis of ASP.NET Core Web App

To perform the code analysis I repeat the 3 steps as shown above.

Back in the SonarQube project, click on the link to set up analysis in your favorite CI

click on the link set up analysis

Click on Other CI at the bottom.

Click on Other CI

Generate a Project Token

Click on Generate. Click on Continue on the next screen.

Select .NET and .NET Framework as a build tool.

Run Analysis on your Project

Run the 3 steps provided and you should see the analysis results in the SonarQube project dashboard.

SonarQube project dashboard

Once you follow the guidelines for Code Smell issues reported and resolve the same, the issue will be clear.

Suggested Read => Custom .NET Development Companies

Node.js Project

In this section, we will look at how to analyze the code quality of a node.js project. I am analyzing the project on Windows. Here are the steps for the analysis:

  1. Create a SonarQube Project and generate a token
  2. Add dependencies to the package.json
  3. Analyze the node.js project

Here are the prerequisites along with the SonarQube server available:

  • Node.js v16.13.1 to build server-side applications using JavaScript: Download and install
  • NPM (Node Package Manager) which is the package manager for Node.js modules has to be installed and is included in the Node.js installation
  • Add node and npm command line tools to the PATH environment variable. In my computer, Node.js is installed in E:\nodejs

Edit Environment Variable

  • Npm registry: I am using JFrog Artifactory NPM remote or virtual repository to look at and download packages. Use the below command to set the same and follow the instructions in Artifactory to set up authentication as well.

npm config set registry https://vniranjan251203.jfrog.io/artifactory/api/npm/niranjan-npm-virtual/

My .npmrc file in C:\users\<Username> looks as below:

Npm registry

If you do not have JFrog Artifactory, you can use the npm public registry and set the same as shown.

npm config set registry https://registry.npmjs.org/

Create SonarQube Project

To create a project in SonarQube as an admin user, on the right side click on Create Project -> Manually.

Create Projects Manually

Add the name and key. Click on Set Up once done.

Create Projects Manually

Select the option to analyze locally

Node.js Analyse Locally

Generate a token, save the same, and click on Continue.

Node.js Generate Token

Select the options shown. Run the sonar scanner using the instructions provided or else add the scanner property to your project property file and use the sonar-scanner command in the package.json file.

Node.js Run Analysis

Sample Node.js project

I have a sample node.js project with a .js and a .html file to be analyzed.

Sample Node.js project

Package.json file – add dependency package

To run the analysis of a node.js application add the following dependency to the file:

“sonar-scanner”: “^3.1.0”,

Add the following to the script to run the sonar scanner from the command.

“scripts”: {
“sonar”: “node_modules\\sonar-scanner\\bin\\sonar-scanner.bat”,

My package.json file is shown below:

{
  &amp;quot;name&amp;quot;: &amp;quot;npmexample&amp;quot;,
  &amp;quot;version&amp;quot;: &amp;quot;1.0.0&amp;quot;,
  &amp;quot;description&amp;quot;: &amp;quot;NPM Example&amp;quot;,
  &amp;quot;main&amp;quot;: &amp;quot;index.js&amp;quot;,
  &amp;quot;scripts&amp;quot;: {
    &amp;quot;sonar&amp;quot;:  &amp;quot;node_modules\\sonar-scanner\\bin\\sonar-scanner.bat&amp;quot;,
    &amp;quot;test&amp;quot;: &amp;quot;echo Error: no test specified&amp;quot;
     },
  &amp;quot;author&amp;quot;: &amp;quot;&amp;quot;,
  &amp;quot;license&amp;quot;: &amp;quot;ISC&amp;quot;,
  &amp;quot;dependencies&amp;quot;: {
    &amp;quot;sonar-scanner&amp;quot;: &amp;quot;^3.1.0&amp;quot;,
    &amp;quot;express&amp;quot;: &amp;quot;^4.18.1&amp;quot;
  }
}

Sonar-project.properties file

Create a sonar-project.properties file in the root of your node.js application.

Further Reading => SonarQube for Java – Complete Guide

Enter the details as shown. The sonar.login property will have a Token as the value which was generated during project creation.

Sonar-project.properties file

Install the dependency and run the scanner using the command as shown below from the root of the Node.js project.

npm i sonar-scanner
npm run sonar

Install and Run the Project

Once the analysis is done by the scanner go to the SonarQube project to look at the report.

Node.js Project Report

So you can see 2 Bugs and 2 Code Smell issues reported. Once the issue is fixed the results will show as all clear.

Recommended Read => How To Setup The Node.Js Testing Framework

Gradle Java Project

In this section, we will look at running SonarQube analysis as part of the Gradle Build to find out code quality issues. Here are the steps for analysis :

  • Create a SonarQube project and generate a token
  • Setup the gradle.properties and build.gradle files
  • Analyze the Gradle project

I am using the following software and its versions as prerequisites along with a SonarQube server.

Create SonarQube Project

To create a project in SonarQube as an admin user, on the right side click on Create Project -> Manually.

Create Projects Manually

Add the name and key. Click on Set Up once done.

Gradle Create a Project

Select the option to analyze locally.

Gradle Analysis

Click on Generate Token. Copy and save the same. This will be used in the gradle.properties file.

Gradle Analyse Project

Click on Continue after the token is generated.

Use the instructions provided to run the sonar-scanner by running the command shown or else proceed to the next step to set up the gradle.properties and build.gradle file.

Gradle Run Analysis on your Project

Sample Gradle Java Project

Sample Gradle Java Project

Setup gradle.properties file

Add the SonarQube URL and Token properties.

The location of gradle.properties file in Windows will be @ c:\users\<username>\.gradle folder

The location of gradle.properties file in Linux will be @ ~/.gradle folder

systemProp.sonar.host.url=http://<Server>:9000
systemProp.sonar.login=<token>

My gradle.properties file in Windows.

gradle.properties file

The systemProp.sonar.login property will have the Token as the value that was generated during project creation.

Next, enable the SonarQube plugin in the project’s build.gradle file.

plugins {
   id “org.sonarqube” version “4.0.0.2929”
}

Also, add the below SonarQube properties in the build.gradle file

property “sonar.projectKey”, “<Sonar-ProjectKey>”
property ‘sonar.projectName’, ‘<Sonar-ProjectName>’
property ‘sonar.java.source’, ‘app’
property ‘encoding’, ‘UTF-8’
property ‘charSet’, ‘UTF-8’

My Sample build.gradle file with the plugin info (added after the dependencies block) and SonarQube properties added is in GREEN.

Sample build.gradle


buildscript {
    repositories {
        jcenter{
		url 'https://vniranjan251203.jfrog.io/artifactory/niranjan-gradle-virtual'
                credentials {
                username = &amp;quot;${artifactory_user}&amp;quot;
                password = &amp;quot;${artifactory_password}&amp;quot;
		                 }
                         }
                                     }
    dependencies {
        //Check for the latest version here: http://plugins.gradle.org/plugin/com.jfrog.artifactory
        classpath &amp;quot;org.jfrog.buildinfo:build-info-extractor-gradle:4+&amp;quot;
                                         }
} 

plugins {
  id &amp;quot;org.sonarqube&amp;quot; version &amp;quot;4.0.0.2929&amp;quot;
}
allprojects {
    apply plugin: &amp;quot;com.jfrog.artifactory&amp;quot;
    apply plugin: 'maven-publish'
    apply plugin: 'java'
}

version =  '0.9.0-SNAPSHOT'

sonarqube {
    properties {
        property &amp;quot;sonar.projectKey&amp;quot;, &amp;quot;GSQ&amp;quot;
        property 'sonar.projectName', 'Gradle_SonarQube'
        property 'sonar.java.source', 'app'
        property 'encoding', 'UTF-8'
        property 'charSet', 'UTF-8'

    }
}
artifactory {
    contextUrl = &amp;quot;${artifactory_contextUrl}&amp;quot;   //The base Artifactory URL if not overridden by the publisher/resolver
    publish {
        repository {
            repoKey = 'gradle-dev-local'
            username = &amp;quot;${artifactory_user}&amp;quot;
            password = &amp;quot;${artifactory_password}&amp;quot;
            maven = true

        }
    }
    resolve {
        repository {
            repoKey = 'niranjan-gradle-virtual'
            username = &amp;quot;${artifactory_user}&amp;quot;
            password = &amp;quot;${artifactory_password}&amp;quot;
            maven = true
        }
    }
}

The repositories section above can use the below in case you do not have artifactory for dependencies.

repositories {
          jcenter()
      }

Now run the analysis using the below command and post the execution go to your SonarQube project to look at the results.

gradle sonar –refresh-dependencies –info

Run the Analysis

Results are displayed in the SonarQube dashboard of the project.

Gradle SonarQube project dashboard

As you can see there are 2 code smell issues. The Java files to be fixed are in the app folder of the Gradle project. Once the above issues are fixed the code smell section will be all clear.

Further Reading => How to use Gradle to Create a Project

Conclusion

In this article, we have seen how SonarQube can be used for .NET, node.js framework, and Gradle to find bugs, code smells, or vulnerabilities. Details on the classification of these 3 types of issues can be found here.

The SonarQube analysis results helps the developer to improve his coding skills and is a very important tool to be used as part of the shift left approach where testing is performed early in the development life cycle.

Was this helpful?

Thanks for your feedback!