0

I've been experimenting with Roslyn for 2-3 days now and am unable to figure a couple of things out.

I want to extract attribute details of all the methods that have atleast one corresponding attribute. Moreover, I want to seggregate the attributes based on their Identifiers.

My use case is the extract some key details from some unit tests written in C# file. As the data is sensitive, below is a demo input string:

public async Task NotIncludeMethod()
{
  //Some Method Body
}

/// <summary>
/// Comment 1.
/// Comment 2.
/// </summary>
[Fact]
[Trait("Resource", "abc")]
[Trait("Method", "xyz")]
[Trait("FullMethod", "abcxyz")]
public async Task MethodOne()
{
  //Some Method Body
}

[Theory]
[Trait("FullMethod", "pqr")]
[InlineData("some text")]
public async Task MethodTwo()
{
  //Some Method Body
}

Following is the syntax tree from the real code to provide the correct representation.

enter image description here

I want to grab all the attributes and seggregate the data based on their identifier. For example, whether it's a Fact or Theory, If the attribute is a Trait, grab the key value pair seperately. Also I want to grab the text from summary portion if it exists. The following is its syntax tree:

enter image description here

I've written this code till now but am not able to proceed further..

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;

var projectPath = @"filepath";
var project = File.ReadAllText(projectPath);

var tree = CSharpSyntaxTree.ParseText(project);
var root = tree.GetRoot();

var testList = root.DescendantNodes().OfType<MethodDeclarationSyntax>().Where(method => method.AttributeLists.Count() > 0).ToList();

foreach (var test in testList)
{

    var ft = test.AttributeLists.First().DescendantNodes().OfType<AttributeSyntax>().Single();

    var trivia = test.AttributeLists.First().OpenBracketToken.GetAllTrivia();

}

Do tell if I can provide more information.. Thanks!

0 Answers0