ASP.NET Core MVC 2.0 Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it...

  1. Let's download the SDK and extend the compiler, installing the VS extension, .NET Compiler Platform SDK, by going through the Tools | Extensions and Updates menu, searching for Roslyn SDK:
  1. We can now download the .NET Compiler Platform SDK templates as a .vsix file, which gives us all the available project templates to create an analyzer:
  1. We can now use the template projects in New Project | Visual C# | Extensibility | Stand-Alone Code Analysis Tool.
  1. Let's open a new console application for an Extensibility project:

This console application will access the Roslyn API, with which we will be able to use the Syntax Tree API.

  1. Let's now create a SyntaxTree, which is simply a class represented by a tree structure of elements using the SyntaxTree type:

This type has a method named ParseText, which will parse a string where a class is written:

  1. Let's write this piece of code:

The GetRoot method will give us the root of the tree.

  1. Using Ctrl + F5, we see the result.
  2. Now, thanks to the SyntaxFactory type, let's create the same class by creating a SyntaxTree with the Syntax API:
  1. With the SyntaxFactory.ClassDeclaration method, we create the class name:
  1. The WithMembers method allows us to create members of this class:
  1. Now we create a method named Bar with void as the return type.
  2. The WithBody method and its SyntaxFactory.Block parameter help us to add an empty block to the Bar method:
  1. The NormalizeWithespace method will add indentation and spaces to make this class more readable:
  1. Let's press Ctrl + F5 to see the result of our code, putting the variable representing the Syntax Tree as the parameter of Console.WriteLine: