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.
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?
