private static void MethodDeclarationAnalyzer(SyntaxNodeAnalysisContext context) { var method = (MethodDeclarationSyntax)context.Node; var allAttributes = method.AttributeLists; var checkedTypes = new List <ITypeSymbol>(); foreach (var attrib in allAttributes) { var info = RedundantAnalyzer.GetAttributeParameterType(context, attrib); if (info == null) { continue; } bool exists = false; foreach (var addedAttrib in checkedTypes) { if (addedAttrib.Name.Equals(info.Name)) { exists = true; break; } } if (!exists) { checkedTypes.Add(info); continue; } Diagnostic diagnostic = Diagnostic.Create(Rule, attrib.GetLocation(), info.Name); context.ReportDiagnostic(diagnostic); } }
private static void CheckExceptionHandling(AttributeInfo throwExceptionAttrib, SyntaxNodeAnalysisContext context) { if (!throwExceptionAttrib.AttributeData.ConstructorArguments.Any()) { return; } var attributeArgument = throwExceptionAttrib.AttributeData.ConstructorArguments.First().Value.ToString(); MethodDeclarationSyntax callerMethod = context.Node.Parent.FirstAncestorOrSelf <MethodDeclarationSyntax>(); ClassDeclarationSyntax callerClass = context.Node.Parent.FirstAncestorOrSelf <ClassDeclarationSyntax>(); if (callerMethod == null || callerClass == null) { return; } var callerClassAndMethodsAttributes = callerMethod.AttributeLists .Union(callerClass.AttributeLists) .ToList(); var detectedAttributes = from attributeList in callerClassAndMethodsAttributes let info = RedundantAnalyzer.GetAttributeParameterType(context, attributeList) where info != null && info.ToString().Equals(attributeArgument) select attributeList; if (detectedAttributes.Any()) { return; } // Checking try catch block foreach (var g in context.Node.Parent.AncestorsAndSelf().OfType <TryStatementSyntax>()) { foreach (var f in g.Catches) { if (f.Declaration == null) { return; } foreach (var k in f.Declaration.DescendantNodes().OfType <IdentifierNameSyntax>()) { var typeInfo = context.SemanticModel.GetTypeInfo(k); if (typeInfo.Type == null) { continue; } if (typeInfo.Type.ToString().Equals(typeof(Exception).FullName) || typeInfo.Type.ToString().Equals(attributeArgument)) { return; } } } } //////////////////////////////////////////////////////// Rule = new DiagnosticDescriptor(DiagnosticId, Title, FormattedMessage, Category, (Microsoft.CodeAnalysis.DiagnosticSeverity)throwExceptionAttrib.Severity, isEnabledByDefault: true, description: Description); Diagnostic diagnostic = Diagnostic.Create(Rule, context.Node.GetLocation(), attributeArgument); context.ReportDiagnostic(diagnostic); }