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.
Table of Contents:
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.
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:
- Create SonarQube Project
- Generate Token
- 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.
Add the name and key. Click on Set Up once done.
Select Locally as the option for analysis.
Further Reading => Explore the Simple Ways of Using SonarLint for Java
#2) Generate Token
Click on 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.
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
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>”
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
Step #3: Collect analysis data generated by build and upload to SonarQube
SonarScanner.MSBuild.exe end /d:sonar.login=”<Generated Token>”
Look at the SonarQube Dashboard for the 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
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 Other CI at the bottom.
Click on Generate. Click on Continue on the next screen.
Select .NET and .NET Framework as a build tool.
Run the 3 steps provided and you should see the analysis results in the 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:
- Create a SonarQube Project and generate a token
- Add dependencies to the package.json
- 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
- 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:
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.
Add the name and key. Click on Set Up once done.
Select the option to analyze locally
Generate a token, save the same, and click on Continue.
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.
Sample Node.js project
I have a sample node.js project with a .js and a .html file to be analyzed.
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:
{ &quot;name&quot;: &quot;npmexample&quot;, &quot;version&quot;: &quot;1.0.0&quot;, &quot;description&quot;: &quot;NPM Example&quot;, &quot;main&quot;: &quot;index.js&quot;, &quot;scripts&quot;: { &quot;sonar&quot;: &quot;node_modules\\sonar-scanner\\bin\\sonar-scanner.bat&quot;, &quot;test&quot;: &quot;echo Error: no test specified&quot; }, &quot;author&quot;: &quot;&quot;, &quot;license&quot;: &quot;ISC&quot;, &quot;dependencies&quot;: { &quot;sonar-scanner&quot;: &quot;^3.1.0&quot;, &quot;express&quot;: &quot;^4.18.1&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.
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 sonarOnce the analysis is done by the scanner go to the SonarQube project to look at the 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.
- Gradle Version 8.0.2
- SonarQube plugin for Gradle 4.0.0.2929
- JDK 17
- JFrog Artifactory GRADLE remote repository to download dependencies
Create SonarQube Project
To create a project in SonarQube as an admin user, on the right side click on Create Project -> Manually.
Add the name and key. Click on Set Up once done.
Select the option to analyze locally.
Click on Generate Token. Copy and save the same. This will be used in the gradle.properties file.
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.
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.
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.
buildscript { repositories { jcenter{ url 'https://vniranjan251203.jfrog.io/artifactory/niranjan-gradle-virtual' credentials { username = &quot;${artifactory_user}&quot; password = &quot;${artifactory_password}&quot; } } } dependencies { //Check for the latest version here: http://plugins.gradle.org/plugin/com.jfrog.artifactory classpath &quot;org.jfrog.buildinfo:build-info-extractor-gradle:4+&quot; } } plugins { id &quot;org.sonarqube&quot; version &quot;4.0.0.2929&quot; } allprojects { apply plugin: &quot;com.jfrog.artifactory&quot; apply plugin: 'maven-publish' apply plugin: 'java' } version = '0.9.0-SNAPSHOT' sonarqube { properties { property &quot;sonar.projectKey&quot;, &quot;GSQ&quot; property 'sonar.projectName', 'Gradle_SonarQube' property 'sonar.java.source', 'app' property 'encoding', 'UTF-8' property 'charSet', 'UTF-8' } } artifactory { contextUrl = &quot;${artifactory_contextUrl}&quot; //The base Artifactory URL if not overridden by the publisher/resolver publish { repository { repoKey = 'gradle-dev-local' username = &quot;${artifactory_user}&quot; password = &quot;${artifactory_password}&quot; maven = true } } resolve { repository { repoKey = 'niranjan-gradle-virtual' username = &quot;${artifactory_user}&quot; password = &quot;${artifactory_password}&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
Results are displayed in the SonarQube dashboard of the project.
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!