### BenchmarkDotNet Setup and Benchmarks in C# Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S6617.html Defines parameters, global setup, and benchmark methods for comparing HashSet and List performance. ```csharp [Params(10000)] public int SampleSize; [Params(1000)] public int Iterations; private static HashSet hashSet; private static List list; [GlobalSetup] public void Setup() { hashSet = new HashSet(Enumerable.Range(0, SampleSize)); list = Enumerable.Range(0, SampleSize).ToList(); } [Benchmark] public void HashSet_Any() => CheckAny(hashSet, SampleSize / 2); [Benchmark] public void HashSet_Contains() => CheckContains(hashSet, SampleSize / 2); [Benchmark] public void List_Any() => CheckAny(list, SampleSize / 2); [Benchmark] public void List_Contains() => CheckContains(list, SampleSize / 2); ``` -------------------------------- ### Global Setup for Logging Benchmarks Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S2629.html Initializes loggers for various .NET logging frameworks. This setup is required before running the benchmarks. ```csharp using Microsoft.Extensions.Logging; using ILogger = Microsoft.Extensions.Logging.ILogger; [Params(10000)] public int Iterations; private ILogger ms_logger; private Castle.Core.Logging.ILogger cc_logger; private log4net.ILog l4n_logger; private Serilog.ILogger se_logger; private NLog.ILogger nl_logger; [GlobalSetup] public void GlobalSetup() { ms_logger = new LoggerFactory().CreateLogger(); cc_logger = new Castle.Core.Logging.NullLogFactory().Create("Castle.Core.Logging"); l4n_logger = log4net.LogManager.GetLogger(typeof(LoggingTemplates)); se_logger = Serilog.Log.Logger; nl_logger = NLog.LogManager.GetLogger("NLog"); } ``` -------------------------------- ### Benchmark setup for string comparison methods Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S6610.html This code sets up a benchmark to compare the performance of string vs. char overloads for StartsWith and EndsWith. It uses BenchmarkDotNet and generates a list of GUIDs for testing. ```csharp private List data; [Params(1_000_000)] public int N { get; set; } [GlobalSetup] public void Setup() => data = Enumerable.Range(0, N).Select(_ => Guid.NewGuid().ToString()).ToList(); [Benchmark] public void StartsWith_String() { _ = data.Where(guid => guid.StartsWith("d")).ToList(); } [Benchmark] public void StartsWith_Char() { _ = data.Where(guid => guid.StartsWith('d')).ToList(); } [Benchmark] public void EndsWith_String() { _ = data.Where(guid => guid.EndsWith("d")).ToList(); } [Benchmark] public void EndsWith_Char() { _ = data.Where(guid => guid.EndsWith('d')).ToList(); } ``` -------------------------------- ### Build and Install Plugin with Maven Source: https://github.com/sonarsource/sonar-dotnet/blob/master/docs/contributing-plugin.md Build the plugin and run unit tests using Maven. This command also installs the plugin locally. ```bash mvn clean install ``` -------------------------------- ### BenchmarkDotNet Setup and Benchmarks in VB.NET Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/vbnet/S6617.html Defines parameters, setup, and benchmark methods for comparing collection performance. Use this for performance testing of .NET collections. ```vb.net Imports System.Collections.Generic Imports System.Linq Imports BenchmarkDotNet.Attributes Public Class CollectionBenchmarks _ Public Property SampleSize As Integer _ Public Property Iterations As Integer Private Shared hashSet As HashSet(Of Integer) Private Shared list As List(Of Integer) Public Sub Setup() hashSet = New HashSet(Of Integer)(Enumerable.Range(0, SampleSize)) list = Enumerable.Range(0, SampleSize).ToList() End Sub Public Sub HashSet_Any() => CheckAny(hashSet, SampleSize / 2) Public Sub HashSet_Contains() => CheckContains(hashSet, SampleSize / 2) Public Sub List_Any() => CheckAny(list, SampleSize / 2) Public Sub List_Contains() => CheckContains(list, SampleSize / 2) Private Sub CheckAny(values As IEnumerable(Of Integer), target As Integer) For i As Integer = 0 To Iterations - 1 _ = values.Any(Function(x) x = target) ' Enumerable.Any Next End Sub Private Sub CheckContains(values As ICollection(Of Integer), target As Integer) For i As Integer = 0 To Iterations - 1 _ = values.Contains(target) ' ICollection(T).Contains Next End Sub End Class ``` -------------------------------- ### BenchmarkDotNet setup for C# indexing performance Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S6608.html This setup code is used with BenchmarkDotNet to measure the performance difference between Enumerable methods and direct indexing in C#. ```csharp private List data; private Random random; [Params(1_000_000)] public int SampleSize; [Params(1_000)] public int LoopSize; [GlobalSetup] public void Setup() { random = new Random(42); var bytes = new byte[SampleSize]; random.NextBytes(bytes); data = bytes.ToList(); } ``` -------------------------------- ### Benchmark Setup and Methods Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/vbnet/S6602.html This C# code sets up benchmarks for collection types using BenchmarkDotNet. It includes delegate caching, global setup for data initialization, and benchmark methods for List, ImmutableList, and arrays. ```csharp // Explicitly cache the delegates to avoid allocations inside the benchmark. private readonly static Func ConditionFunc = static x => x == 1; private readonly static Predicate ConditionPredicate = static x => x == 1; private List list; private ImmutableList immutableList; private int\[\] array; public const int N = 10\_000; \[GlobalSetup\] public void GlobalSetup() { list = Enumerable.Range(0, N).Select(x => N - x).ToList(); immutableList = ImmutableList.CreateRange(list); array = list.ToArray(); } \[BenchmarkCategory("List"), Benchmark(Baseline = true)\] public int ListFirstOrDefault() => list.FirstOrDefault(ConditionFunc); \[BenchmarkCategory("List"), Benchmark\] public int ListFind() => list.Find(ConditionPredicate); \[BenchmarkCategory("ImmutableList"), Benchmark(Baseline = true)\] public int ImmutableListFirstOrDefault() => immutableList.FirstOrDefault(ConditionFunc); \[BenchmarkCategory("ImmutableList"), Benchmark\] public int ImmutableListFind() => immutableList.Find(ConditionPredicate); \[BenchmarkCategory("Array"), Benchmark(Baseline = true)\] public int ArrayFirstOrDefault() => array.FirstOrDefault(ConditionFunc); \[BenchmarkCategory("Array"), Benchmark\] public int ArrayFind() => Array.Find(array, ConditionPredicate); ``` -------------------------------- ### Avoid Parameterless Guid Instantiation in VB.NET Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/vbnet/S4581.html This noncompliant code example shows the ambiguous use of parameterless Guid instantiation. Use explicit methods like Guid.Empty or Guid.NewGuid() for clarity. ```vbnet Public Sub Foo() Dim G1 As New Guid ' Noncompliant - what's the intent? Dim G2 As Guid = Nothing ' Noncompliant End Sub ``` -------------------------------- ### Benchmark Setup for LINQ Sorting Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S3169.html This C# code defines the Person class and the BenchmarkDotNet setup for comparing the performance of different LINQ sorting methods. It includes global setup for data generation and individual benchmarks for various sorting scenarios. ```csharp public class Person { public string Name { get; set; } public int Age { get; set; } public int Size { get; set; } } private Random random = new Random(1); private Consumer consumer = new Consumer(); private Person[] array; [Params(100_000)] public int N { get; set; } [GlobalSetup] public void GlobalSetup() { array = Enumerable.Range(0, N).Select(x => new Person { Name = Path.GetRandomFileName(), Age = random.Next(0, 100), Size = random.Next(0, 200) }).ToArray(); } [Benchmark(Baseline = true)] public void OrderByAge() => array.OrderBy(x => x.Age).Consume(consumer); [Benchmark] public void OrderByAgeOrderBySize() => array.OrderBy(x => x.Age).OrderBy(x => x.Size).Consume(consumer); [Benchmark] public void OrderByAgeThenBySize() => array.OrderBy(x => x.Age).ThenBy(x => x.Size).Consume(consumer); ``` -------------------------------- ### Compliant Guid Instantiation Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S4581.html Use `Guid.Empty` for an empty GUID, `Guid.NewGuid()` for a random GUID, or `new Guid(bytes)` for a GUID initialized with specific bytes. ```csharp public void Foo(byte[] bytes) { var g1 = Guid.Empty; var g2 = Guid.NewGuid(); var g3 = new Guid(bytes); } ``` -------------------------------- ### Use Explicit Guid Initialization in VB.NET Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/vbnet/S4581.html This compliant solution demonstrates the correct ways to initialize a Guid. It shows using Guid.Empty, Guid.NewGuid(), and a constructor with byte array parameters. ```vbnet Public Sub Foo(Bytes As Byte()) Dim G1 As Guid = Guid.Empty Dim G2 As Guid = Guid.NewGuid() Dim G3 As Guid = New Guid(Bytes) End Sub ``` -------------------------------- ### Noncompliant Guid Instantiation Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S4581.html Avoid using parameterless `new Guid()` or `default(Guid)` as the intent is unclear. Use `Guid.Empty`, `Guid.NewGuid()`, or `new Guid(bytes)` instead. ```csharp public void Foo() { var g1 = new Guid(); // Noncompliant - what's the intent? Guid g2 = new(); // Noncompliant var g3 = default(Guid); // Noncompliant Guid g4 = default; // Noncompliant } ``` -------------------------------- ### Compliant File Header Example Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S1451.html This is an example of a compliant file header that includes copyright and license information, followed by an empty line before the namespace declaration. ```csharp /* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2013 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * SonarQube is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ ``` -------------------------------- ### BenchmarkDotNet Setup and Benchmarks in C# Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/vbnet/S6608.html This C# code sets up a benchmark scenario using BenchmarkDotNet to compare the performance of Enumerable methods (ElementAt, First, Last) against direct indexing for a List. It includes global setup and individual benchmark methods for each access pattern. ```csharp private List data; private Random random; [Params(1_000_000)] public int SampleSize; [Params(1_000)] public int LoopSize; [GlobalSetup] public void Setup() { random = new Random(42); var bytes = new byte[SampleSize]; random.NextBytes(bytes); data = bytes.ToList(); } [Benchmark] public int ElementAt() { int result = default; for (var i = 0; i < LoopSize; i++) { result = data.ElementAt(i); } return result; } [Benchmark] public int Index() { int result = default; for (var i = 0; i < LoopSize; i++) { result = data[i]; } return result; } [Benchmark] public int First() { int result = default; for (var i = 0; i < LoopSize; i++) { result = data.First(); } return result; } [Benchmark] public int First_Index() { int result = default; for (var i = 0; i < LoopSize; i++) { result = data[0]; } return result; } [Benchmark] public int Last() { int result = default; for (var i = 0; i < LoopSize; i++) { result = data.Last(); } return result; } [Benchmark] public int Last_Index() { int result = default; for (var i = 0; i < LoopSize; i++) { result = data[data.Count - 1]; } return result; } ``` -------------------------------- ### Compliant VB.NET code examples for handling credentials Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/vbnet/S2068.html These examples show secure ways to handle credentials in VB.NET. They utilize methods like retrieving encrypted passwords or using string formatting with secure values. The last example shows a compliant URI with identical username and password, and a compliant constant for a password property. ```vbnet Dim username As String = "admin" Dim password As String = GetEncryptedPassword() Dim usernamePassword As String = String.Format("user={0}&password={1}", GetEncryptedUsername(), GetEncryptedPassword()) Dim url As String = $"scheme://{username}:{password}@domain.com" Dim url2 As String= "http://guest:guest@domain.com" ' Compliant Const Password_Property As String = "custom.password" ' Compliant ``` -------------------------------- ### Compliant C# Solution Example Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S2325.html This example demonstrates the compliant solution where the non-static members that don't access instance data are correctly marked as static. ```csharp public class Utilities { public static int MagicNum { get { return 42; } } private static string magicWord = "please"; public static string MagicWord { get { return magicWord; } set { magicWord = value; } } public static int Sum(int a, int b) { return a + b; } } ``` -------------------------------- ### Compliant C# Code Example with Property Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S2357.html This example demonstrates a compliant solution using a public property with a getter to encapsulate the field. ```csharp public class Foo { public int MagicNumber { get { return 42; } } } ``` -------------------------------- ### Compliant AssemblyVersion Example Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S3904.html This compliant example demonstrates the correct usage by including both AssemblyTitle and AssemblyVersion attributes. Specifying the version ensures unique identification and prevents dependency issues. ```csharp using System.Reflection; [assembly: AssemblyTitle("MyAssembly")] [assembly: AssemblyVersion("42.1.125.0")] namespace MyLibrary { // ... } ``` -------------------------------- ### String Interpolation Example Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S3457.html This example demonstrates the use of string interpolation, which is recommended for its compile-time validation and improved readability compared to String.Format. ```csharp string str = $"Hello {firstName} {lastName}!"; ``` -------------------------------- ### Noncompliant code example with unused usings Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S1128.html This example demonstrates a C# file with several 'using' directives that are not utilized by the code. These include System.Collections.Generic, MyApp.Helpers, and MyCustomNamespace. ```csharp using System.IO; using System.Linq; using System.Collections.Generic; // Noncompliant - no types are used from this namespace using MyApp.Helpers; // Noncompliant - FileHelper is in the same namespace using MyCustomNamespace; // Noncompliant - no types are used from this namespace namespace MyApp.Helpers { public class FileHelper { public static string ReadFirstLine(string filePath) => File.ReadAllLines(filePath).First(); } } ``` -------------------------------- ### VB.NET Compliant File Header Example Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/vbnet/S1451.html This example shows a compliant header for a VB.NET file, including copyright, license, and contact information, followed by a namespace declaration. ```vbnet Copyright (c) SonarSource. All Rights Reserved. Licensed under the LGPL License. See License.txt in the project root for license information. namespace Foo { } ``` ```vbnet /* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2013 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * SonarQube is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ ``` -------------------------------- ### BenchmarkDotNet Setup for Max Method vs. Max Property Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/vbnet/S6609.html This C# code snippet demonstrates the setup for a BenchmarkDotNet test comparing the performance of the `Enumerable.Max()` extension method against the `SortedSet.Max` property. It initializes a SortedSet with a specified number of unique strings. ```csharp private SortedSet data; [Params(1_000)] public int Iterations; [GlobalSetup] public void Setup() => data = new SortedSet(Enumerable.Range(0, Iterations).Select(x => Guid.NewGuid().ToString())); ``` -------------------------------- ### Compliant VB.NET Code Example using With Statement Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/vbnet/S2375.html This example demonstrates the compliant solution using the 'With' statement for cleaner and more readable access to object members. ```vb.net Module Module1 Dim product = New With {.Name = "paperclips", .RetailPrice = 1.2, .WholesalePrice = 0.6, .A = 0, .B = 0, .C = 0} Sub Main() With product .Name = "" .RetailPrice = 0 .WholesalePrice = 0 .A = 0 .B = 0 .C = 0 End With End Sub End Module ``` -------------------------------- ### Compliant Code Example Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S125.html This is a compliant solution where commented-out code has been removed. ```csharp void Method(string s) { // Do something... } ``` -------------------------------- ### Compliant VB.NET Code: Guid as Primary Key Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/vbnet/S3363.html This example shows a compliant VB.NET class using Guid as the primary key, which is a safer alternative to temporal types. ```vbnet Public Class Account Public Property Id As Guid Public Property Name As String Public Property Surname As String End Class ``` -------------------------------- ### Noncompliant Method: Public 'Get' Method Returning a Value Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S4049.html This method violates the rule because it starts with 'Get', takes no parameters, and returns a string value. It should be refactored into a property. ```csharp using System; namespace MyLibrary { public class Foo { private string name; public string GetName() // Noncompliant { return name; } } } ``` -------------------------------- ### Compliant C# Code Example Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S3902.html This code uses `typeof(Example).Assembly` to get the assembly of the current type, which is a fast property access. This is the preferred method for performance-sensitive scenarios. ```csharp public class Example { public static void Main() { Assembly assem = typeof(Example).Assembly; // Here we use the type of the current class Console.WriteLine("Assembly name: {0}", assem.FullName); } } ``` -------------------------------- ### Benchmark Setup for ConcurrentDictionary Capture vs. Lambda Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S6612.html This C# code sets up a benchmark to compare the performance of `ConcurrentDictionary.GetOrAdd` when using lambda capture versus when avoiding it. It includes global setup for initializing the dictionary and data. ```csharp private ConcurrentDictionary dict; private List data; [Params(1_000_000)] public int N { get; set; } [GlobalSetup] public void Setup() { dict = new ConcurrentDictionary(); data = Enumerable.Range(0, N).OrderBy(_ => Guid.NewGuid()).ToList(); } ``` -------------------------------- ### Compliant solution for credentials Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S2068.html This example demonstrates compliant code by retrieving credentials securely. Use methods like GetEncryptedPassword() or environment variables instead of hard-coding. ```csharp string username = "admin"; string password = GetEncryptedPassword(); string usernamePassword = string.Format("user={0}&password={1}", GetEncryptedUsername(), GetEncryptedPassword()); string url = $"scheme://{username}:{password}@domain.com"; ``` ```csharp string url2 = "http://guest:guest@domain.com"; // Compliant ``` ```csharp const string Password_Property = "custom.password"; // Compliant ``` -------------------------------- ### Compliant C# Class with Guid Primary Key Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S3363.html This example demonstrates a compliant C# class using 'Guid Id' as the primary key, which avoids potential duplicate key issues. ```csharp internal class Account { public Guid Id { get; set; } public string Name { get; set; } public string Surname { get; set; } } ``` -------------------------------- ### Compliant VB.NET AssemblyVersion Example Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/vbnet/S3904.html This code example shows the compliant solution by including the AssemblyVersion attribute with a specific version number. This ensures unique identification and avoids dependency conflicts. ```vbnet Imports System.Reflection Namespace MyLibrary ' ... End Namespace ``` -------------------------------- ### Compliant C# Class with [Key] Guid Primary Key Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S3363.html This example shows a compliant C# class using the [Key] attribute with a 'Guid PersonIdentifier' as the primary key, adhering to best practices. ```csharp internal class Person { \[Key] public Guid PersonIdentifier { get; set; } public string Name { get; set; } public string Surname { get; set; } } ``` -------------------------------- ### BenchmarkDotNet Setup and Benchmarks in C# Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S6605.html This code sets up a BenchmarkDotNet benchmark suite. It includes delegate caching, collection initialization, and benchmark methods for List, ImmutableList, and arrays using Any() and Exists(). ```csharp // Explicitly cache the delegates to avoid allocations inside the benchmark. private readonly static Func ConditionFunc = static x => x == -1 * Math.Abs(x); private readonly static Predicate ConditionPredicate = static x => x == -1 * Math.Abs(x); private List list; private ImmutableList immutableList; private int[] array; [Params(1000)] public int N { get; set; } [GlobalSetup] public void GlobalSetup() { list = Enumerable.Range(0, N).Select(x => N - x).ToList(); immutableList = ImmutableList.CreateRange(list); array = list.ToArray(); } [BenchmarkCategory("List"), Benchmark] public bool ListAny() => list.Any(ConditionFunc); [BenchmarkCategory("List"), Benchmark(Baseline = true)] public bool ListExists() => list.Exists(ConditionPredicate); [BenchmarkCategory("ImmutableList"), Benchmark(Baseline = true)] public bool ImmutableListAny() => immutableList.Any(ConditionFunc); [BenchmarkCategory("ImmutableList"), Benchmark] public bool ImmutableListExists() => immutableList.Exists(ConditionPredicate); [BenchmarkCategory("Array"), Benchmark(Baseline = true)] public bool ArrayAny() => array.Any(ConditionFunc); [BenchmarkCategory("Array"), Benchmark] public bool ArrayExists() => Array.Exists(array, ConditionPredicate); ``` -------------------------------- ### Compliant VB.NET Code: Guid with [Key] Attribute Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/vbnet/S3363.html This example shows a compliant VB.NET class using Guid as the primary key, marked with the [Key] attribute, which avoids the risks associated with temporal types. ```vbnet Public Class Person Public Property PersonIdentifier As Guid Public Property Name As String Public Property Surname As String End Class ``` -------------------------------- ### BenchmarkDotNet Setup and Delegates Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S6603.html Defines delegates for performance comparisons and sets up various collection types for benchmarking. Caches delegates to avoid allocations. ```csharp private readonly static Func ConditionFunc = static x => x == Math.Abs(x); private readonly static Predicate ConditionPredicate = static x => x == Math.Abs(x); private List list; private ImmutableList immutableList; private ImmutableList.Builder immutableListBuilder; private int[] array; [Params(100000)] public int N { get; set; } [GlobalSetup] public void GlobalSetup() { list = Enumerable.Range(0, N).Select(x => N - x).ToList(); immutableList = ImmutableList.CreateRange(list); immutableListBuilder = ImmutableList.CreateBuilder(); immutableListBuilder.AddRange(list); array = list.ToArray(); } ``` -------------------------------- ### Noncompliant local variable naming Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/vbnet/S117.html This example shows a local variable 'Foo' that does not comply with the default camel casing convention, starting with an uppercase letter. ```vbnet Module Module1 Sub Main() Dim Foo = 0 ' Noncompliant End Sub End Module ``` -------------------------------- ### Benchmark Setup and Delegates Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/vbnet/S6605.html Defines delegates and initializes collections for benchmarking. Caches delegates to avoid allocations within the benchmark. ```csharp private readonly static Func ConditionFunc = static x => x == -1 * Math.Abs(x); private readonly static Predicate ConditionPredicate = static x => x == -1 * Math.Abs(x); private List list; private ImmutableList immutableList; private int[] array; [Params(1000)] public int N { get; set; } [GlobalSetup] public void GlobalSetup() { list = Enumerable.Range(0, N).Select(x => N - x).ToList(); immutableList = ImmutableList.CreateRange(list); array = list.ToArray(); } ``` -------------------------------- ### Compliant local variable naming Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/vbnet/S117.html This example demonstrates a compliant local variable 'foo' that follows the default camel casing convention, starting with a lowercase letter. ```vbnet Module Module1 Sub Main() Dim foo = 0 ' Compliant End Sub End Module ``` -------------------------------- ### Benchmark Setup and Delegates Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S6602.html Defines delegates and initializes collections for benchmarking. Caches delegates to avoid allocations within benchmark methods. ```csharp private readonly static Func ConditionFunc = static x => x == 1; private readonly static Predicate ConditionPredicate = static x => x == 1; private List list; private ImmutableList immutableList; private int[] array; public const int N = 10_000; [GlobalSetup] public void GlobalSetup() { list = Enumerable.Range(0, N).Select(x => N - x).ToList(); immutableList = ImmutableList.CreateRange(list); array = list.ToArray(); } ``` -------------------------------- ### Noncompliant Naming Convention - VB.NET Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/vbnet/S2348.html This example shows a VB.NET event named 'fooEvent' which violates the default Pascal casing convention because it starts with a lowercase letter. The regular expression used is `^([A-Z]{1,3}[a-z0-9]+)*([A-Z]{2})?$`. Ensure all identifiers start with an uppercase letter unless they are short abbreviations. ```vbnet Class Foo Event fooEvent() ' Noncompliant End Class ``` -------------------------------- ### AnalysisContext Registration Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/src/SonarAnalyzer.ShimLayer.Lightup/CSharp8.md Methods for registering symbol start actions in analysis contexts. ```APIDOC ## AnalysisContext Registration ### Description Methods to register actions that start analysis for symbols. ### Methods - `virtual void RegisterSymbolStartAction(Action action, SymbolKind symbolKind)` (Applies to `AnalysisContext` and `CompilationStartAnalysisContext`) ``` -------------------------------- ### Compliant solution with necessary usings Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S1128.html This is the corrected version of the previous example, where only the essential 'using' directives (System.IO and System.Linq) are retained, as they are the only ones actually used by the code. ```csharp using System.IO; using System.Linq; namespace MyApp.Helpers { public class FileHelper { public static string ReadFirstLine(string filePath) => File.ReadAllLines(filePath).First(); } } ``` -------------------------------- ### VB.NET: Compliant Property Access Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/vbnet/S4275.html This compliant VB.NET code example shows a property where both the 'Get' and 'Set' procedures correctly access and update the corresponding private field. This adheres to encapsulation principles. ```vbnet Public Class Sample Private _x As Integer Private _y As Integer Public Property Y As Integer Get Return _y End Get Set(value As Integer) _y = value End Set End Property End Class ``` -------------------------------- ### BenchmarkDotNet Benchmark Setup Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S3260.html This code sets up a BenchmarkDotNet benchmark to compare the performance of unsealed and sealed classes. It includes parameters, benchmark methods, and class definitions for comparison. ```csharp [Params(1_000_000)] public int Iterations { get; set; } private readonly UnsealedClass unsealedType = new UnsealedClass(); private readonly SealedClass sealedType = new SealedClass(); [Benchmark(Baseline = true)] public void UnsealedType() { for (int i = 0; i < Iterations; i++) { unsealedType.DoNothing(); } } [Benchmark] public void SealedType() { for (int i = 0; i < Iterations; i++) { sealedType.DoNothing(); } } private class BaseType { public virtual void DoNothing() { } } private class UnsealedClass : BaseType { public override void DoNothing() { } } private sealed class SealedClass : BaseType { public override void DoNothing() { } } ``` -------------------------------- ### Noncompliant: Action Route Overrides Controller Route Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S6931.html This example shows how an action-level route starting with '/' ignores the controller's route template. This behavior can be confusing as it maps the action to the application root. ```csharp [Route("[controller]")] // This route is ignored public class HomeController : Controller { [HttpGet("/Index1")] // This action is mapped to the root of the web application public ActionResult Index1() => View(); [Route("/Index2")] // The same applies here public ActionResult Index2() => View(); } ``` -------------------------------- ### Compliant VB.NET Generic Type Parameter Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/vbnet/S119.html This example demonstrates a compliant VB.NET generic type parameter that adheres to the recommended naming convention. Generic type parameters should start with 'T' and use Pascal casing. ```vbnet Public Class Foo(Of TKey) ' Compliant End Class ``` -------------------------------- ### Unit Test Setup with VerifierBuilder Source: https://github.com/sonarsource/sonar-dotnet/blob/master/docs/contributing-analyzer.md Demonstrates how to set up a unit test for a C# analyzer using the VerifierBuilder. Ensure the analyzer and test case files are correctly referenced. ```csharp public class MyAnalyzerTest { private readonly VerifierBuilder verifier = new VerifierBuilder(); [TestMethod] public void MyAnalyzer_CSharp10() { verifier .AddPaths("MyAnalyzer.CSharp10.cs") // searched in analyzers\tests\SonarAnalyzer.Test\TestCases\ .AddReferences(MetadataReferenceFacade.SystemData); .WithOptions(ParseOptionsHelper.FromCSharp10) .Verify(); } } ``` -------------------------------- ### Noncompliant VB.NET Generic Type Parameter Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/vbnet/S119.html This example shows a noncompliant VB.NET generic type parameter that does not follow the recommended naming convention. Ensure generic type parameters start with 'T' and follow Pascal casing. ```vbnet Public Class Foo(Of tkey) ' Noncompliant End Class ``` -------------------------------- ### ASP.NET MVC Action Route Ignored Due to Absolute Path Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/vbnet/S6931.html Controller-level routes are ignored when actions define absolute routes starting with '/'. This example demonstrates how 'Index1' and 'Index2' are mapped to the root instead of being relative to the controller. ```vbnet ' This route is ignored for the routing of Index1 and Index2 Public Class HomeController Inherits Controller ' This action is mapped to the root of the web application Public Function Index1() As ActionResult Return View() End Function ' The same applies here Public Function Index2() As ActionResult Return View() End Function End Class ``` -------------------------------- ### Build SonarAnalyzer with .NET CLI Source: https://github.com/sonarsource/sonar-dotnet/blob/master/docs/contributing-plugin.md Use the .NET CLI to build the SonarAnalyzer solution. Ensure you have the .NET SDK installed. ```bash dotnet build .\analyzers\SonarAnalyzer.sln ``` -------------------------------- ### Noncompliant Generic Type Parameter Naming in VB.NET Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/vbnet/S2373.html This example shows a noncompliant generic type parameter name that does not follow the recommended naming conventions. Ensure generic type parameters start with 'T' and follow Pascal casing. ```vbnet Public Class Foo(Of t) ' Noncompliant End Class ``` -------------------------------- ### VB.NET: Noncompliant Property Access Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/vbnet/S4275.html This noncompliant code example demonstrates a VB.NET property where the 'Get' procedure returns the wrong field and the 'Set' procedure updates the wrong field. Ensure property procedures access the field with the corresponding name. ```vbnet Public Class Sample Private _x As Integer Private _y As Integer Public Property Y As Integer Get Return _x ' Noncompliant: field '_y' is not used in the return value End Get Set(value As Integer) _x = value ' Noncompliant: field '_y' is not updated End Set End Property End Class ``` -------------------------------- ### Telemetry Data Example 1 Source: https://github.com/sonarsource/sonar-dotnet/blob/master/sonar-dotnet-core/src/test/resources/TelemetrySensorTest/Readme.md Content of the first telemetry.pb file, including project path, target frameworks, and language version. ```protobuf projectFullPath: A.csproj targetFramework: TFM1 targetFramework: TFM2 languageVersion: CS12 ``` -------------------------------- ### SCrypt Password Hashing Example Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S5344.html Demonstrates password hashing using SCrypt from Bouncy Castle. Ensure sufficient cost factors (N, r, p) are used for security. ```csharp using Org.BouncyCastle.Crypto.Generators; string password = Request.Query["password"]; byte[] salt = RandomNumberGenerator.GetBytes(128 / 8); // divide by 8 to convert bits to bytes string hashed = Convert.ToBase64String(SCrypt.Generate(Encoding.Unicode.GetBytes(password), salt, 1<<12, 8, 1, 32)); // Noncompliant ``` -------------------------------- ### Benchmark setup for Any() vs Count() Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S1155.html This code snippet is used for benchmarking the performance difference between using Any() and Count() for checking collection emptiness. It requires BenchmarkDotNet to run. ```csharp private IEnumerable collection; public const int N = 10_000; [GlobalSetup] public void GlobalSetup() { collection = Enumerable.Range(0, N).Select(x => N - x); } [Benchmark(Baseline = true)] public bool Count() => collection.Count() > 0; [Benchmark] public bool Any() => collection.Any(); ``` -------------------------------- ### Compliant Windows Forms Entry Point with STAThread Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S4210.html This example demonstrates the correct way to define a Windows Forms application entry point by including the STAThreadAttribute. This ensures proper threading model for Windows Forms. ```csharp using System; using System.Windows.Forms; namespace MyLibrary { public class MyForm: Form { public MyForm() { this.Text = "Hello World!"; } [STAThread] public static void Main() { var form = new MyForm(); Application.Run(form); } } } ``` -------------------------------- ### Telemetry Data Example 2 Source: https://github.com/sonarsource/sonar-dotnet/blob/master/sonar-dotnet-core/src/test/resources/TelemetrySensorTest/Readme.md Content of the second telemetry.pb file, showcasing multiple target frameworks for a single project. ```protobuf projectFullPath: B.csproj targetFramework: TFM1 targetFramework: TFM2 targetFramework: TFM3 languageVersion: CS12 ``` -------------------------------- ### Noncompliant C# Code Example Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S2357.html This example shows a public field, which violates the rule. Fields should be private and accessed through properties. ```csharp public class Foo { public int MagicNumber = 42; } ``` -------------------------------- ### Compliant C# URI Handling with System.Uri Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S4005.html This example demonstrates the compliant solution by using System.Uri objects for URI parameters. This ensures proper parsing and encoding, enhancing security. ```csharp using System; namespace MyLibrary { public class Foo { public void FetchResource(string uriString) { } public void FetchResource(Uri uri) { } public string ReadResource(string uriString, string name, bool isLocal) { } public string ReadResource(Uri uri, string name, bool isIsLocal) { } public void Main() { FetchResource(new Uri("http://www.mysite.com")); ReadResource(new Uri("http://www.mysite.com"), "foo-resource", true); } } } ``` -------------------------------- ### VB.NET Compliant Regular Expression Examples Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/vbnet/S5856.html This example shows the corrected VB.NET regular expression patterns that avoid runtime exceptions. ```vbnet Sub Regexes(Input As String) Dim Rx As New Regex("\\\[A-Z\\\]") Dim Match = Regex.Match(Input, "\\\[A-Z\\\]") Dim NegativeLookahead As New Regex("a(?!b)") Dim NegativeLookbehind As New Regex("(? x > 5).Select(x => x * x); ``` ```csharp var isEqual = "this string".Equals("other string"); ``` -------------------------------- ### Noncompliant C# Code Example Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S2325.html This example shows non-compliant code where properties and a method that do not access instance data are not marked as static. ```csharp public class Utilities { public int MagicNum // Noncompliant - only returns a constant value { get { return 42; } } private static string magicWord = "please"; public string MagicWord // Noncompliant - only accesses a static field { get { return magicWord; } set { magicWord = value; } } public int Sum(int a, int b) // Noncompliant - doesn't access instance data, only the method parameters { return a + b; } } ``` -------------------------------- ### Avoid Thread.Sleep in Moq Setups Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/vbnet/S2925.html Introducing Thread.Sleep within a Moq setup can lead to non-compliant behavior. Consider using ReturnsAsync for delays. ```vbnet Public Sub UserService_Test() Dim UserService As New Mock(Of UserService) Dim Expected As New User UserService.Setup(Function(X) X.GetUserById(42)).Returns( Function() Threading.Thread.Sleep(500) ' Noncompliant Return Task.FromResult(Expected) End Function) ' assertions... End Sub ``` -------------------------------- ### Use `Dim foo = {"foo", "bar"}` for array declaration Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/vbnet/S2429.html This compliant code example demonstrates the preferred syntax for declaring and initializing an array. It is more compact and readable than the older method. ```vbnet Module Module1 Sub Main() Dim foo = {"foo", "bar"} ' Compliant End Sub End Module ``` -------------------------------- ### Compliant C# Logging Solution Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S6664.html This example shows a compliant solution by reducing the number of 'Information' logs within the loop, ensuring the threshold is not exceeded. It retains necessary logs for debugging. ```csharp void MyMethod(List items) { logger.Debug("The operation started"); foreach(var item in items) { logger.Information($"Evaluating {item.Name}"); var result = Evaluate(item); if (item.Name is string.Empty) { logger.Error("Invalid item name"); } logger.Information($"End item evaluation with result: {result}"); } logger.Debug("The operation ended"); } ``` -------------------------------- ### Avoid Redundant `goto` and `continue` Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S3626.html Noncompliant code example demonstrating the use of `goto` and `continue` in a way that makes the code harder to follow. These should be refactored for better readability. ```csharp void Foo() { goto A; // Noncompliant A: while (condition1) { if (condition2) { continue; // Noncompliant } else { DoTheThing(); } } return; // Noncompliant; this is a void method } ``` -------------------------------- ### Avoid Thread.Sleep in Moq Setups Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S2925.html Introducing `Thread.Sleep` within a `Moq` setup can lead to non-compliant behavior. Consider using `ReturnsAsync` for delayed responses. ```csharp using Moq; using System.Threading.Tasks; // ... public class UserService {} public class User {} [TestMethod] public void UserService_Test() { var userService = new Mock(); var expected = new User(); userService .Setup(m => m.GetUserById(42)) .Returns(() => { Thread.Sleep(500); // Noncompliant return Task.FromResult(expected); }); // assertions... } ``` -------------------------------- ### Benchmark Setup for LINQ Order Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S6607.html This code sets up the data and parameters for benchmarking the performance difference between calling OrderBy then Where versus Where then OrderBy. It uses BenchmarkDotNet. ```csharp private IList data; private static readonly Random Random = new Random(); [Params(1_000_000)] public int NumberOfEntries; [GlobalSetup] public void Setup() => data = Enumerable.Range(0, NumberOfEntries).Select(x => Random.Next(0, NumberOfEntries)).ToList(); ``` -------------------------------- ### Class Member Ordering Example Source: https://github.com/sonarsource/sonar-dotnet/blob/master/docs/coding-style.md Demonstrates the recommended ordering of class members: constants, enums, fields, abstract members, properties, constructors, and methods. Accessibility levels should also be ordered from public to private within each category. ```csharp public int PublicMethod() => 42; int CallerOne() => Leaf(); int CallerTwo() => Leaf() + PublicMethod(); int Leaf() => 42; ``` -------------------------------- ### Noncompliant Code Example: Shadowing Fields Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/vbnet/S2387.html This example demonstrates a noncompliant scenario where child class fields shadow parent class fields with the same name. ```vbnet Public Class Fruit Protected Ripe As Season Protected Flesh As Color ' ... End Class Public Class Raspberry Inherits Fruit Private Ripe As Boolean ' Noncompliant Private Shared FLESH As Color ' Noncompliant ' ... End Class ``` -------------------------------- ### Use TLS 1.2 and TLS 1.3 (Compliant) Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/vbnet/S4423.html This code example demonstrates the compliant configuration of ServicePointManager.SecurityProtocol to use TLS 1.2 and TLS 1.3. These are the recommended strong and secure protocols. ```vbnet Imports System.Net Imports System.Security.Authentication Public Sub Encrypt() ServicePointManager.SecurityProtocol = \ SecurityProtocolType.Tls12 \ Or SecurityProtocolType.Tls13 End Sub ``` -------------------------------- ### Noncompliant Code Example with TODO Tag Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/vbnet/S1135.html This VB.NET example shows a function with an unattended TODO comment. Such tags can be overlooked, leading to incomplete code. ```vbnet Sub DoSomething() ' TODO End Sub ``` -------------------------------- ### Noncompliant Code Example: Variable Shadowing Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S1117.html This example demonstrates variable shadowing where local variables 'myField' and 'MyProperty' have the same names as class members. This is noncompliant. ```csharp class Foo { public int myField; public int MyProperty { get; set; } public void DoSomething() { int myField = 0; // Noncompliant int MyProperty = 0; // Noncompliant } } ``` -------------------------------- ### VB.NET Noncompliant Regular Expression Examples Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/vbnet/S5856.html These examples demonstrate common VB.NET regular expression patterns that will cause runtime exceptions due to incorrect syntax. ```vbnet Sub Regexes(Input As String) Dim Rx As New Regex("\\\[A") ' Noncompliant: unmatched "\\\[" Dim Match = Regex.Match(Input, "\\\[A") ' Noncompliant Dim NegativeLookahead As New Regex("a(?!b)", RegexOptions.NonBacktracking) ' Noncompliant: negative lookahead without backtracking Dim NegativeLookbehind As New Regex("(? Public Class FooBar Inherits IFooBar End Class ``` -------------------------------- ### Compliant Logging Example with Dedicated Overloads Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S6668.html This compliant solution demonstrates the correct way to log exceptions and event IDs by using the dedicated overloads provided by logging frameworks. ```csharp try { } catch (Exception ex) { logger.LogDebug(eventId, ex, "An exception occured."); ``` -------------------------------- ### Compliant C# Code Example Source: https://github.com/sonarsource/sonar-dotnet/blob/master/analyzers/rspec/cs/S3459.html This code shows how to correctly initialize fields and auto-properties. Explicit initialization prevents them from holding default values and ensures predictable behavior. ```csharp class MyClass { private int field = 1; private int Property { get; set; } = 42; public void Print() { field++; Console.WriteLine(field); Console.WriteLine(Property); } } ```