Roslyn diagnostic analyzer diagnostics not reflected in Visual Studio instance

I am trying to detect passing a model as a parameter to a function in a controller for an MVC application. I wrote some code for the Roslyn diagnostic analyzer. The logic of the code works great as the breakpoints hit the target. But the diagnostic result from the point of view of warning is not reflected in the opened instance of the visual studio.

This is a code snippet of my diagnostic analyzer:

public override void Initialize(AnalysisContext context)
{
    // TODO: Consider registering other actions that act on syntax instead of or in addition to symbols
    context.RegisterSyntaxNodeAction(AnalyzeSymbol, SyntaxKind.MethodDeclaration);
}

private async static void AnalyzeSymbol(SyntaxNodeAnalysisContext context)
{
    var method = (MethodDeclarationSyntax)context.Node;

    ParameterListSyntax ParamList = method.ParameterList;
    int flag = 0;
    string ParamName = null;

    foreach (ParameterSyntax Param in ParamList.Parameters)
    {
        if (Param.Type.ToString().Contains("Model"))
        {
            ParamName = Param.Type.ToString();
            flag = 1;
            break;
        }
    }

    if (flag == 0)
        return;

    string solutionPath = @"C:\Users\Administrator\Documents\Visual Studio 2015\Projects\WebApplication6\WebApplication6.sln";
    var workspace = MSBuildWorkspace.Create();                                                       
    var solution = await workspace.OpenSolutionAsync(solutionPath);

    foreach (var project in solution.Projects)
    {
        foreach (var document in project.Documents)
        {
            CancellationToken source = default(CancellationToken);

            SyntaxNode root = await document.GetSyntaxRootAsync(source);

            var classDeclarations = root.DescendantNodes().Where(n => n.IsKind(SyntaxKind.ClassDeclaration));
            flag = 0;

            foreach (ClassDeclarationSyntax cls in classDeclarations)
            {
                if (cls.Identifier.Text.ToString() == ParamName)
                {

                        var diagnostic = Diagnostic.Create(Rule, method.GetLocation());
                        context.ReportDiagnostic(diagnostic);
                }
            }
        }
    }
}

      

+3


source to share


1 answer


It looks like you are looking at the classes incorrectly. You must work with context and you must not open a new solution. The context contains all the necessary information about the open solution.



0


source







All Articles