Cookie Consent by Free Privacy Policy Generator ๐Ÿ“Œ How to write a Roslyn Analyzer

๐Ÿ  Team IT Security News

TSecurity.de ist eine Online-Plattform, die sich auf die Bereitstellung von Informationen,alle 15 Minuten neuste Nachrichten, Bildungsressourcen und Dienstleistungen rund um das Thema IT-Sicherheit spezialisiert hat.
Ob es sich um aktuelle Nachrichten, Fachartikel, Blogbeitrรคge, Webinare, Tutorials, oder Tipps & Tricks handelt, TSecurity.de bietet seinen Nutzern einen umfassenden รœberblick รผber die wichtigsten Aspekte der IT-Sicherheit in einer sich stรคndig verรคndernden digitalen Welt.

16.12.2023 - TIP: Wer den Cookie Consent Banner akzeptiert, kann z.B. von Englisch nach Deutsch รผbersetzen, erst Englisch auswรคhlen dann wieder Deutsch!

Google Android Playstore Download Button fรผr Team IT Security



๐Ÿ“š How to write a Roslyn Analyzer


๐Ÿ’ก Newskategorie: Programmierung
๐Ÿ”— Quelle: devblogs.microsoft.com

Roslyn analyzers inspect your code for style, quality, maintainability, design and other issues. Because they are powered by the .NET Compiler Platform, they can produce warnings in your code as you type even before youโ€™ve finished the line. In other words, you donโ€™t have to build your code to find out that you made a mistake. Analyzers can also surface an automatic code fix through the Visual Studio light bulb prompt that allows you to clean up your code immediately. With live, project-based code analyzers in Visual Studio, API authors can ship domain-specific code analysis as part of their NuGet packages.

You donโ€™t have to be a professional API author to write an analyzer. In this post, Iโ€™ll show you how to write your very first analyzer.

Getting started

In order to create a Roslyn Analyzer project, you need to install the .NET Compiler Platform SDK via the Visual Studio Installer. There are two different ways to find the .NET Compiler Platform SDK in the Visual Studio Installer:

Install using the Visual Studio Installer โ€“ Workloads view:

  1. Run the Visual Studio Installer and select Modify.
    Visual Studio Installer
  2. Check the Visual Studio extension development workload.
    Visual Studio Extension Development Workload

Install using the Visual Studio Installer โ€“ Individual components tab:

  1. Run the Visual Studio Installer and select Modify.
  2. Select the Individual components tab.
  3. Check the box for .NET Compiler Platform SDK.
    Visual Studio Individual Components

Writing an analyzer

Letโ€™s begin by creating a syntax tree analyzer. This analyzer generates a syntax warning for any statement that is not enclosed in a block that has curly braces { and }. For example, the following code generates a warning for both the if-statement and the System.Console.WriteLine invocation statement, but the while statement is not flagged:

Brace Analyzer Diagnostic

  1. Open Visual Studio.
  2. On the Create a new project dialog search VSIX and select Analyzer with Code Fix (.NET Standard) in C# and click Next.
    Create New Project Dialog
  3. Name your project BraceAnalyzer and click OK. The solution should contain 3 projects: BraceAnalyzer, BraceAnalyzer.Test, BraceAnalyzer.Vsix.
    Analyzer Solution Layout
    • BraceAnalyzer: This is the core analyzer project that contains the default analyzer implementation that reports a diagnostic for all type names that contain any lowercase letter.
    • BraceAnalyzer.Test: This is a unit test project that lets you make sure your analyzer is producing the right diagnostics and fixes.
    • BraceAnalyzer. Vsix: The VSIX project bundles the analyzer into an extension package (.vsix file). This is the startup project in the solution.
  4. In the Solution Explorer, open Resources.resx in the BraceAnalyzer project. This displays the resource editor.
  5. Replace the existing resource string values for AnalyzerDescription, AnalyzerMessageFormat, and AnalyzerTitle with the following strings:
    • Change AnalyzerDescription to Enclose statement with curly braces.
    • Change AnalyzerMessageFormat to `{` brace expected.
    • Change AnalyzerTitle to Enclose statement with curly braces.


    Resources Resx

  6. Within the BraceAnalyzerAnalyzer.cs file, replace the Initialize method implementation with the following code:
  7. public override void Initialize(AnalysisContext context)
    {
        context.RegisterSyntaxTreeAction(syntaxTreeContext =>
        {
            // Iterate through all statements in the tree
            var root = syntaxTreeContext.Tree.GetRoot(syntaxTreeContext.CancellationToken);
            foreach (var statement in root.DescendantNodes().OfType<StatementSyntax>())
            {
                // Skip analyzing block statements 
                if (statement is BlockSyntax)
                {
                    continue;
                }
    
                // Report issues for all statements that are nested within a statement
                // but not a block statement
                if (statement.Parent is StatementSyntax && !(statement.Parent is BlockSyntax))
                {
                    var diagnostic = Diagnostic.Create(Rule, statement.GetFirstToken().GetLocation());
                    syntaxTreeContext.ReportDiagnostic(diagnostic);
                }
            }
        });
    }

  8. Check your progress by pressing F5 to run your analyzer. Make sure that the BraceAnalyzer.Vsix project is the startup project before pressing F5. Running the VSIX project loads an experimental instance of Visual Studio, which lets Visual Studio keep track of a separate set of Visual Studio extensions.
  9. In the Visual Studio instance, create a new C# class library with the following code to verify that the analyzer diagnostic is neither reported for the method block nor the while statement, but is reported for the if statement and System.Console.WriteLine invocation statement:
    Brace Analyzer Diagnostic
  10. Now, add curly braces around the System.Console.WriteLine invocation statement and verify that the only single warning is now reported for the if statement:
    Brace Diagnostic For If Statement

Writing a code fix

An analyzer can provide one or more code fixes. A code fix defines an edit that addresses the reported issue. For the analyzer that you created, you can provide a code fix that encloses a statement with a curly brace.

  1. Open the BraceAnalyzerCodeFixProvider.cs file. This code fix is already wired up to the Diagnostic ID produced by your diagnostic analyzer, but it doesnโ€™t yet implement the right code transform.
  2. Change the title string to โ€œAdd braceโ€:
  3. private const string title = "Add brace";

  4. Change the following line to register a code fix. Your fix will create a new document that results from adding braces.
  5. context.RegisterCodeFix(
            CodeAction.Create(
                title: title,
                createChangedDocument: c => AddBracesAsync(context.Document, diagnostic, root),
                equivalenceKey: title),
            diagnostic);

  6. Youโ€™ll notice red squiggles in the code you just added on the AddBracesAsync symbol. Add a declaration for AddBracesAsync by replacing the MakeUpperCaseAsync method with the following code:
  7. Task<Document> AddBracesAsync(Document document, Diagnostic diagnostic, SyntaxNode root)
            {
                var statement = root.FindNode(diagnostic.Location.SourceSpan).FirstAncestorOrSelf<StatementSyntax>();
                var newRoot = root.ReplaceNode(statement, SyntaxFactory.Block(statement));
                return Task.FromResult(document.WithSyntaxRoot(newRoot));
            }

  8. Press F5 to run the analyzer project in a second instance of Visual Studio. Place your cursor on the diagnostic and press (Ctrl+.) to trigger the Quick Actions and Refactorings menu. Notice your code fix to add a brace!
    Image brace analyzer code fix2

Conclusion

Congratulations! Youโ€™ve created your first Roslyn analyzer that performs on-the-fly code analysis to detect an issue and provides a code fix to correct it. Now that youโ€™re familiar with the .NET Compiler Platform SDK (Roslyn APIs), writing your next analyzer will be a breeze.

The post How to write a Roslyn Analyzer appeared first on .NET Blog.

...



๐Ÿ“Œ How to write a Roslyn Analyzer


๐Ÿ“ˆ 51.79 Punkte

๐Ÿ“Œ Write Better Code Faster with Roslyn Analyzers


๐Ÿ“ˆ 38.9 Punkte

๐Ÿ“Œ Mono 5.0 mit Roslyn-C#-Compiler und Concurrent Garbage Collection erschienen


๐Ÿ“ˆ 30.65 Punkte

๐Ÿ“Œ Roslyn Analyzers


๐Ÿ“ˆ 30.65 Punkte

๐Ÿ“Œ Mindestens zwei Tote durch Hurrikan Roslyn in Mexiko


๐Ÿ“ˆ 30.65 Punkte

๐Ÿ“Œ GitHub - astrelsky/Ghidra-Cpp-Class-Analyzer: Ghidra C++ Class and Run Time Type Information Analyzer


๐Ÿ“ˆ 25.77 Punkte

๐Ÿ“Œ Webshell-Analyzer - Web Shell Scanner And Analyzer


๐Ÿ“ˆ 25.77 Punkte

๐Ÿ“Œ How To Install Wireshark Network Analyzer In Ubuntu โ€“ A Best Network Traffic Analyzer For Linux


๐Ÿ“ˆ 25.77 Punkte

๐Ÿ“Œ CVE-2022-32575 | Intel Trace Analyzer and Collector prior 2021.5 out-of-bounds write (intel-sa-00733)


๐Ÿ“ˆ 21.14 Punkte

๐Ÿ“Œ CVE-2023-7243 | CISA Ethercat Zeek Plugin Datagram Analyzer out-of-bounds write (icsa-24-051-02)


๐Ÿ“ˆ 21.14 Punkte

๐Ÿ“Œ Btrfs vs write caching firmware bugs (tl;dr some hard drives with buggy firmware can corrupt your data if you don't disable write caching)


๐Ÿ“ˆ 16.52 Punkte

๐Ÿ“Œ Looking at my schoolโ€™s digital technology assessment outline. Iโ€™m not gonna write a short report ima write a novel.


๐Ÿ“ˆ 16.52 Punkte

๐Ÿ“Œ CVE-2020-14125 | Xiaomi Redmi Note 9T/Redmi Note 11 read/write out-of-bounds write


๐Ÿ“ˆ 16.52 Punkte

๐Ÿ“Œ CVE-2023-28445 | Deno 1.32.0 Asynchronous Operation read/write out-of-bounds write (GHSA-c25x-cm9x-qqgx)


๐Ÿ“ˆ 16.52 Punkte

๐Ÿ“Œ CodeSOD: Write, Write Again


๐Ÿ“ˆ 16.52 Punkte

๐Ÿ“Œ Use VSCode to write Terraform? AWS AI can now help you write your code!


๐Ÿ“ˆ 16.52 Punkte

๐Ÿ“Œ Bugtraq: ManageEngine Eventlog Analyzer v4-v10 Privilege Esacalation


๐Ÿ“ˆ 12.88 Punkte

๐Ÿ“Œ Log Analyzer 3.6.0 - Cross Site Scripting Vulnerability


๐Ÿ“ˆ 12.88 Punkte

๐Ÿ“Œ ME Firewall Analyzer v7.2 - Cross Site Vulnerabilities


๐Ÿ“ˆ 12.88 Punkte

๐Ÿ“Œ ME Firewall Analyzer v7.1 - Multiple Web Vulnerabilities


๐Ÿ“ˆ 12.88 Punkte

๐Ÿ“Œ ManageEngine Eventlog Analyzer 10 Privilege Escalation


๐Ÿ“ˆ 12.88 Punkte

๐Ÿ“Œ [webapps] - ManageEngine EventLog Analyzer 4.0 - 10 - Privilege Escalation


๐Ÿ“ˆ 12.88 Punkte

๐Ÿ“Œ Bugtraq: ManageEngine Eventlog Analyzer Privilege Escalation v10.8


๐Ÿ“ˆ 12.88 Punkte

๐Ÿ“Œ ManageEngine EventLog Analyzer 10.8 Privilege Escalation


๐Ÿ“ˆ 12.88 Punkte

๐Ÿ“Œ [webapps] - ManageEngine Firewall Analyzer 8.5 - Multiple Vulnerabilities


๐Ÿ“ˆ 12.88 Punkte

๐Ÿ“Œ ManageEngine Firewall Analyzer 8.5 SQL Injection


๐Ÿ“ˆ 12.88 Punkte

๐Ÿ“Œ ManageEngine Firewall Analyzer 8.5 SP-5.0 Cross Site Scripting


๐Ÿ“ˆ 12.88 Punkte

๐Ÿ“Œ Erste Extension fรผr Microsoft Edge im Store entdeckt - Page Analyzer


๐Ÿ“ˆ 12.88 Punkte

๐Ÿ“Œ Erste Extension fรผr Microsoft Edge im Store entdeckt - Page Analyzer


๐Ÿ“ˆ 12.88 Punkte

๐Ÿ“Œ CeBIT: HPI stellt โ€žS-Bahn Analyzerโ€œ auf Basis von Twitter-Auswertung vor


๐Ÿ“ˆ 12.88 Punkte

๐Ÿ“Œ Manage Engine EventLog Analyzer 11.0 Build 11000 Cross Site Scripting


๐Ÿ“ˆ 12.88 Punkte

๐Ÿ“Œ GSX Analyzer 10.12 / 11 Backdoor Account


๐Ÿ“ˆ 12.88 Punkte

๐Ÿ“Œ [webapps] - GSX Analyzer 10.12 and 11 - Main.swf Hardcoded Superadmin Credentials


๐Ÿ“ˆ 12.88 Punkte

๐Ÿ“Œ Bugtraq: Nagios Network Analyzer v2.2.1 Multiple CSRF


๐Ÿ“ˆ 12.88 Punkte

๐Ÿ“Œ Nagios Network Analyzer 2.2.1 Cross Site Request Forgery


๐Ÿ“ˆ 12.88 Punkte











matomo