Using open source released by "roslyn" to read code file and generate new code files

Where to begin?

in my current solution, I have models like this:

public class MyAwesomeModel { .... } 

I want to take the roslyn code project to parse the source files and iterate over the syntax trees to generate new code files. Take these source files and add them to the C # project file to import into my solution again in visual studio.

Where to begin. Cloning roslyn and just write a console application that links to all roslyn and starts digging into roslyn to find out how, or are there any blogs, documentatino that shows something like this.

+7
c # roslyn
source share
1 answer

It was easy to do.

Create a console application and link:

  <package id="Microsoft.CodeAnalysis.CSharp" version="0.6.4033103-beta" targetFramework="net45" /> 

and here is the program that visited all the properties in the source code:

  class ModelCollector : CSharpSyntaxWalker { public readonly Dictionary<string, List<string>> models = new Dictionary<string, List<string>>(); public override void VisitPropertyDeclaration(PropertyDeclarationSyntax node) { var classnode = node.Parent as ClassDeclarationSyntax; if (!models.ContainsKey(classnode.Identifier.ValueText)) models.Add(classnode.Identifier.ValueText, new List<string>()); models[classnode.Identifier.ValueText].Add(node.Identifier.ValueText); } } class Program { static void Main(string[] args) { var code = @" using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace HelloWorld { public class MyAwesomeModel { public string MyProperty {get;set;} public int MyProperty1 {get;set;} } }"; var tree = CSharpSyntaxTree.ParseText(code); var root = (CompilationUnitSyntax)tree.GetRoot(); var modelCollector = new ModelCollector(); modelCollector.Visit(root); Console.WriteLine(JsonConvert.SerializeObject(modelCollector.models)); } } 
+3
source share

All Articles