Where do I start?
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 go over the syntax trees to generate new code files. Take those source files and add them to a c# project file to import in my solution again in visual studio.
Where do I start. Cloning roslyn and just write a console app that reference all of roslyn and start digging into roslyn to find out how, or is there any blogs,documentatino that shows something like this.
It was somewhat easy to do.
Create a console app and add reference to Microsoft.CodeAnalysis.CSharp in your project.
Here is the program that visited all properties in a source text:
using System;
using System.Collections.Generic;
using System.Text.Json;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
class ModelCollector : CSharpSyntaxWalker
{
public Dictionary<string, List<string>> Models { get; } = 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()
{
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(JsonSerializer.Serialize(modelCollector.Models));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With