6using System.Collections.Immutable;
11 [DiagnosticAnalyzer(LanguageNames.CSharp)]
15 private static readonly DiagnosticDescriptor usesAddMethodsOnContextRule =
16 new DiagnosticDescriptor(
17 Constants.AnalyzerIdentifiers.BusinessRuleContextUsage,
18 BusinessRuleDoesNotUseAddMethodsOnContextAnalyzerConstants.Title,
19 BusinessRuleDoesNotUseAddMethodsOnContextAnalyzerConstants.Message,
20 Constants.Categories.Usage, DiagnosticSeverity.Warning,
true,
21 helpLinkUri: HelpUrlBuilder.Build(
25 ImmutableArray.Create(usesAddMethodsOnContextRule);
29 context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
30 context.EnableConcurrentExecution();
31 context.RegisterSyntaxNodeAction(AnalyzeMethodDeclaration, SyntaxKind.MethodDeclaration);
34 private static void AnalyzeMethodDeclaration(SyntaxNodeAnalysisContext context)
36 var methodNode = (MethodDeclarationSyntax)context.Node;
38 if (!methodNode.ContainsDiagnostics)
40 var methodSymbol = context.SemanticModel.GetDeclaredSymbol(methodNode);
41 var typeSymbol = methodSymbol.ContainingType;
43 if (typeSymbol.IsBusinessRule() &&
44 (methodSymbol.Name ==
"Execute" || methodSymbol.Name ==
"ExecuteAsync") &&
45 methodSymbol.Parameters.Length > 0)
47 var contextParameter = methodSymbol.Parameters[0];
48 var wasAddMethodCalled =
49 methodNode.DescendantNodes(_ =>
true).OfType<InvocationExpressionSyntax>()
52 return context.SemanticModel.GetSymbolInfo(invocation.Expression).Symbol is IMethodSymbol invocationSymbol &&
53 invocationSymbol.Name.StartsWith(
"Add") && Equals(invocationSymbol.ContainingType, contextParameter.Type);
56 if (!wasAddMethodCalled)
58 context.ReportDiagnostic(Diagnostic.Create(
59 usesAddMethodsOnContextRule, contextParameter.Locations[0]));
override ImmutableArray< DiagnosticDescriptor > SupportedDiagnostics
override void Initialize(AnalysisContext context)