Automating Code Reviews with a Roslyn-Based VB.NET Analyzer Code reviews are essential for maintaining software quality, enforcing team standards, and catching bugs early. However, manual reviews are time-consuming and often prone to human oversight. By leveraging the .NET Compiler Platform (“Roslyn”), development teams can automate these checks directly inside the IDE and CI/CD pipelines. While C# dominates the Roslyn ecosystem, the framework provides identical, robust support for VB.NET.
This article explores how to build and deploy a custom Roslyn-based analyzer to automate VB.NET code reviews. Why Use Roslyn for VB.NET Automation?
Traditional static analysis tools often rely on regular expressions or basic text parsing, which fail to understand code context. Roslyn fundamentally changed this by exposing the actual compiler APIs to developers.
Roslyn offers deep code insight through two primary engines:
Syntax Trees: Represent the source code’s structural, hierarchical grammar.
Semantic Models: Provide deep type resolution, symbol info, and data-flow insights.
By using these engines, a Roslyn analyzer understands exactly what the VB.NET code is doing, allowing it to flag complex architectural violations, security flaws, or style deviations without false positives. Key Use Cases for VB.NET Analyzers
Custom analyzers excel at catching language-specific anti-patterns and enforcing organizational rules:
Enforcing Legacy Modernization: Flagging obsolete VB.NET functions (e.g., On Error GoTo, MsgBox, or Left()) and suggesting modern .NET equivalents like Try…Catch, MessageBox.Show, or String.Substring.
Strict Naming Conventions: Ensuring interfaces start with “I”, classes follow PascalCase, and private fields use camelCase with underscores.
Resource Management: Warning developers when an IDisposable object is instantiated without a Using block.
Null-Safety Checks: Catching potential NullReferenceException risks when dealing with object properties. Step-by-Step: Building a VB.NET Analyzer 1. Set Up the Environment
To get started, install the .NET Compiler Platform SDK via the Visual Studio Installer. Create a new project using the Analyzer with Code Fix (.NET Standard) template. Ensure you select Visual Basic as the language. The template generates three core projects: The Analyzer: Contains the logic to inspect code.
The Code Fix: Provides automated “quick-fix” suggestions to the user.
The Unit Tests: Validates analyzer behavior using mock code snippets. 2. Define the Diagnostic Rules
Every analyzer relies on a DiagnosticDescriptor. This object defines the metadata for the code violation, including a unique ID, title, message format, category, and severity level (e.g., Hidden, Info, Warning, Error).
Public Shared ReadOnly Rule As New DiagnosticDescriptor( “VB0001”, “Avoid Legacy Error Handling”, “Use ‘Try…Catch’ instead of ‘On Error’”, “Design”, DiagnosticSeverity.Warning, isEnabledByDefault:=True) Use code with caution. 3. Analyze the Syntax
The core of the analyzer overrides the Initialize method to register actions. To catch legacy error handling, you register a syntax node action targeting SyntaxKind.OnErrorGoToStatement.
Public Overrides Sub Initialize(context As AnalysisContext) context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None) context.EnableConcurrentExecution() ‘ Register an action to look for On Error statements context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.OnErrorGoToStatement) End Sub Private Sub AnalyzeNode(context As SyntaxNodeAnalysisContext) Dim onErrorStatement = Cast(context.Node, OnErrorStatementSyntax) ’ Report the issue at the specific location of the code violation Dim diagnostic = Diagnostic.Create(Rule, onErrorStatement.GetLocation()) context.ReportDiagnostic(diagnostic) End Sub Use code with caution. Integrating into the Code Review Pipeline
Building the analyzer is only half the battle; it must be integrated into the team’s daily workflow to automate the review process. IDE Integration via NuGet
Pack the analyzer project into a NuGet package. When teams add this package to their VB.NET projects, the analyzer runs live in Visual Studio as developers type. Violations appear instantly in the Error List and light up with squiggly underlines under the offending code. CI/CD Gatekeeping
To completely automate the code review process, integrate the analyzer into your build pipeline (Azure DevOps, GitHub Actions, or Jenkins).
By using the .dotnet build command with the treat warnings as errors flag (/warnaserror or in the .vbproj file), the build will fail if a developer attempts to commit code that violates the analyzer’s rules. This acts as an automated first-line reviewer, ensuring that only compliant code ever reaches human reviewers. Conclusion
Automating code reviews with a Roslyn-based VB.NET analyzer shifts quality control to the earliest stages of development. By replacing manual checklist audits with instantaneous, compiler-driven feedback, teams save hours of manual review time, eliminate legacy anti-patterns, and maintain a highly disciplined codebase.
If you want to expand this draft into a complete technical guide, tell me:
The specific VB.NET anti-pattern or rule you want to target (e.g., enforcing Option Strict On, naming conventions).
The target audience level (e.g., beginners to Roslyn, advanced DevOps engineers).
If you need a corresponding Code Fix provider example written out in VB.NET.
Leave a Reply