Visual Studio Extension Development | Code Analyzer - A Complete Guide
Isn't it really cool if we could customize the Intellisense/Analyzer rule so that we can add our own analyzer rules and code fixes for the same? Yes, its possible with the help of Visual Studio Extension development toolkit. Lets walk through the steps involved for creating your own code analyzer with code fixes as visual studio extension project and then let us see the analyzer in action.
Installing Necessary Toolset for Visual Studio Extension Development
First step is to install the necessary tool set from the Visual Studio Installer. For this demo I am using Visual Studio 2022. Launch the Visual Studio Installer from the programs and Select the Visual Studio Extension Development from other Toolsets if not already checked as shown in the figure below and click on Modify
Creating New Analyzer Project with Code Fix in Visual Studio
Once its successfully installed and updated, Project templates would be available from the Extension. Create a new project with the "Analyzer with Code Fix" Template as shown in the figure below:
Give a suitable name for the analyzer project, I have given the name as "MyFirstAnalyzer". Once the project is created it will create a set of projects as shown in the figure below:
As shown in the figure around five projects are created out of which First one "MyFirstAnalyzer" is used to add custom analyzer rule, second one "MyFirstAnalyzer.CodeFixes" is used to add the code fixes for the rules described in the first project, rest of them are mainly used for packaging and testing the analyzer code.
Our Analyzer in Action
Lets us try to test our analyzer, For this set the Startup Project as "MyFirstAnalyzer.Vsix" and click on Execute from the Visual Studio. This would launch a new instance of the Visual Studio with our extension pre-installed. We can verify our extension is installed from Extensions->Manage Extensions from the newly created visual studio instance as shown in the figure below:
Lets us try to create a new Console Application in the new instance of the Visual Studio to test out our Analyzer, Write some sample code, After some time you will observe squiggly line in the code. This is coming from "MyFirstAnalyzer" project if we try to hover our the code we can see the warning from our Analyzer as shown in the figure below:
If you click on the light bulb you will observe the suggested fix for the warning which is coming from the "MyFirstAnalyzer.CodeFixes" project as shown in the below figure:
Comments
Post a Comment