Created
April 5, 2014 13:32
-
-
Save pksorensen/9992006 to your computer and use it in GitHub Desktop.
My first go with roslyn, parsing properties out of classes that has class names ending with model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.CodeAnalysis; | |
using Microsoft.CodeAnalysis.CSharp; | |
using Microsoft.CodeAnalysis.CSharp.Syntax; | |
using Newtonsoft.Json; | |
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace ConsoleApplication10 | |
{ | |
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 (!classnode.Identifier.ValueText.EndsWith("Model")) | |
return; | |
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;} | |
} | |
public class MyAwesomeClassThatIsNotAmodel | |
{ | |
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)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment