3

I'm attempting to create an Analyzer for Roslyn that will prevent the use of Asserts within a given namespace (to ensure that the project design standard is maintained).

I've been able to get to the point where I can verify if this is an assert, but I am unsure how get the namespace from the context.

public override void Initialize(AnalysisContext context)
{
    context.RegisterSyntaxNodeAction(AnalyzeMethod, SyntaxKind.InvocationExpression);
}

private static void AnalyzeMethod(SyntaxNodeAnalysisContext context)
{
    var expression = (InvocationExpressionSyntax)context.Node;

    var memberAccessExpression = expression.Expression as MemberAccessExpressionSyntax;

    if (memberAccessExpression == null) return;

    var memberSymbol = ModelExtensions.GetSymbolInfo(context.SemanticModel, memberAccessExpression).Symbol as IMethodSymbol;

    if (!memberSymbol?.ToString().Contains("Assert") ?? true) return;

    //Check if we're inside the Page Namespace.


    //This is an Assert, lets fail it.
    var diagnostic = Diagnostic.Create(Rule, memberAccessExpression.GetLocation(), memberAccessExpression.Name);

    context.ReportDiagnostic(diagnostic);
}

When inspecting the context object itself, I can see a ContainingSymbol object, that contains a ContainingNamespace property, but when I try to code against this, I don't appear to be able to access it.

ContainingNamespace

Whats the easiest method of getting the class namespace? i.e. I want the namespace of the class the Assert is in, not the namespace of the assert.

As a bonus question - Is there any decent documentation on any of this?

2 Answers 2

2

ContainingSymbol returns the base ISymbol interface, which can represent any symbol.

To access more-specific properties, you need to cast it to a more-specific interface, such as IMethodSymbol.

Sign up to request clarification or add additional context in comments.

2 Comments

So part of the issue is that I can't even see the containingsymbol property on the context. How do I get to it?
1

Make sure you have pulled down the latest packages via NuGet.

However I don't understand why you are able to see it at runtime using the debugger but unable to code against it.

3 Comments

This was the winner. Seems strange that you can see it at runtime, but need the updated packages to be able to see it.
@ObsidianPhoenix: If you're running in VS, you're using the latest packages at runtime regardless, due to VS bindingRedirects.
@SLaks Thanks. So what happens if I code for the latest version and someone tries to use the package on an older VS2015 Update? Is it likely to break?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.