當前位置: 首頁>>代碼示例>>C#>>正文


C# CodeAnalysis.DiagnosticDescriptor類代碼示例

本文整理匯總了C#中Microsoft.CodeAnalysis.DiagnosticDescriptor的典型用法代碼示例。如果您正苦於以下問題:C# DiagnosticDescriptor類的具體用法?C# DiagnosticDescriptor怎麽用?C# DiagnosticDescriptor使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


DiagnosticDescriptor類屬於Microsoft.CodeAnalysis命名空間,在下文中一共展示了DiagnosticDescriptor類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: CreateDiagnostic

 public static Diagnostic CreateDiagnostic(
     this ISymbol symbol,
     DiagnosticDescriptor rule,
     params object[] args)
 {
     return symbol.Locations.CreateDiagnostic(rule, args);
 }
開發者ID:Anniepoh,項目名稱:roslyn-analyzers,代碼行數:7,代碼來源:DiagnosticExtensions.cs

示例2: AnalyzeFormatInvocation

 public static void AnalyzeFormatInvocation(SyntaxNodeAnalysisContext context, string methodName, string methodOverloadSignature, string methodWithArraySignature, DiagnosticDescriptor rule)
 {
     if (context.IsGenerated()) return;
     var invocationExpression = (InvocationExpressionSyntax)context.Node;
     var memberExpresion = invocationExpression.Expression as MemberAccessExpressionSyntax;
     if (memberExpresion?.Name?.ToString() != methodName) return;
     var memberSymbol = context.SemanticModel.GetSymbolInfo(memberExpresion).Symbol;
     if (memberSymbol == null) return;
     if (!memberSymbol.ToString().StartsWith(methodOverloadSignature)) return;
     var argumentList = invocationExpression.ArgumentList as ArgumentListSyntax;
     if (argumentList?.Arguments.Count < 2) return;
     if (!argumentList.Arguments[0]?.Expression?.IsKind(SyntaxKind.StringLiteralExpression) ?? false) return;
     if (memberSymbol.ToString() == methodWithArraySignature && argumentList.Arguments.Skip(1).Any(a => context.SemanticModel.GetTypeInfo(a.Expression).Type.TypeKind == TypeKind.Array)) return;
     var formatLiteral = (LiteralExpressionSyntax)argumentList.Arguments[0].Expression;
     var format = (string)context.SemanticModel.GetConstantValue(formatLiteral).Value;
     var formatArgs = Enumerable.Range(1, argumentList.Arguments.Count - 1).Select(i => new object()).ToArray();
     try
     {
         string.Format(format, formatArgs);
     }
     catch (FormatException)
     {
         return;
     }
     var diag = Diagnostic.Create(rule, invocationExpression.GetLocation());
     context.ReportDiagnostic(diag);
 }
開發者ID:haroldhues,項目名稱:code-cracker,代碼行數:27,代碼來源:StringFormatAnalyzer.cs

示例3: SimpleDiagnostic

            private SimpleDiagnostic(
                DiagnosticDescriptor descriptor,
                DiagnosticSeverity severity,
                int warningLevel,
                Location location,
                IEnumerable<Location> additionalLocations,
                object[] messageArgs,
                ImmutableDictionary<string, string> properties,
                bool isSuppressed)
            {
                if ((warningLevel == 0 && severity != DiagnosticSeverity.Error) ||
                    (warningLevel != 0 && severity == DiagnosticSeverity.Error))
                {
                    throw new ArgumentException(nameof(warningLevel));
                }

                if (descriptor == null)
                {
                    throw new ArgumentNullException(nameof(descriptor));
                }

                _descriptor = descriptor;
                _severity = severity;
                _warningLevel = warningLevel;
                _location = location ?? Location.None;
                _additionalLocations = additionalLocations?.ToImmutableArray() ?? SpecializedCollections.EmptyReadOnlyList<Location>();
                _messageArgs = messageArgs ?? Array.Empty<object>();
                _properties = properties ?? ImmutableDictionary<string, string>.Empty;
                _isSuppressed = isSuppressed;
            }
開發者ID:XieShuquan,項目名稱:roslyn,代碼行數:30,代碼來源:Diagnostic_SimpleDiagnostic.cs

示例4: ReportLSPViolatingExceptionIfThrown

 public static void ReportLSPViolatingExceptionIfThrown(SyntaxNodeAnalysisContext context,
                                                        INamedTypeSymbol exceptionType,
                                                        DiagnosticDescriptor rule)
 {
     var throwStatement = context.Node as ThrowStatementSyntax;
     throwStatement.Expression.DescendantNodesAndTokens()
                   .Where(t => t.IsKind(SyntaxKind.IdentifierName) || t.IsKind(SyntaxKind.IdentifierToken))
                   .TryFirst()
                   .Match()
                   .Some().Where(t => t.IsNode).Do(t =>
                   {
                       var identifier = t.AsNode() as IdentifierNameSyntax;
                       var identifierType = context.SemanticModel.GetSymbolInfo(identifier);
                       if (identifierType.Symbol.Equals(exceptionType))
                       {
                           context.ReportDiagnostic(Diagnostic.Create(rule, identifier.GetLocation()));
                       }
                   })
                   .Some().Do(t =>
                   {
                       var identifier = t.Parent as IdentifierNameSyntax;
                       var identiferType = context.SemanticModel.GetTypeInfo(identifier).Type;
                       if (identiferType.Equals(exceptionType))
                       {
                           context.ReportDiagnostic(Diagnostic.Create(rule, identifier.GetLocation()));
                       }
                   })
                   .None().Do(() => { })
                   .Exec();
 }
開發者ID:DavidArno,項目名稱:Arnolyzer,代碼行數:30,代碼來源:LSPViolatingExceptionReporter.cs

示例5: DiagnosticItem

 public DiagnosticItem(AnalyzerItem analyzerItem, DiagnosticDescriptor descriptor, ReportDiagnostic effectiveSeverity)
     : base(string.Format("{0}: {1}", descriptor.Id, descriptor.Title))
 {
     _analyzerItem = analyzerItem;
     _descriptor = descriptor;
     _effectiveSeverity = effectiveSeverity;
 }
開發者ID:elemk0vv,項目名稱:roslyn-1,代碼行數:7,代碼來源:DiagnosticItem.cs

示例6: GenerateDescriptorText

        private static string GenerateDescriptorText(DiagnosticDescriptor descriptor)
        {
            StringBuilder builder = new StringBuilder();

            builder.Append($"### {descriptor.Id}: {descriptor.Title} ###");

            if (!string.IsNullOrWhiteSpace(descriptor.Description.ToString()))
            {
                builder
                    .AppendLine()
                    .AppendLine()
                    .Append(descriptor.Description.ToString());
            }

            builder
                .AppendLine()
                .AppendLine()
                .AppendLine($"Category: {descriptor.Category}")
                .AppendLine()
                .Append($"Severity: {descriptor.DefaultSeverity}");

            if (!string.IsNullOrWhiteSpace(descriptor.HelpLinkUri))
            {
                builder
                    .AppendLine()
                    .AppendLine()
                    .Append($"Help: [{descriptor.HelpLinkUri}]({descriptor.HelpLinkUri})");
            }

            return builder.ToString();
        }
開發者ID:Anniepoh,項目名稱:roslyn-analyzers,代碼行數:31,代碼來源:Program.cs

示例7: TestCodeFix

        protected void TestCodeFix(Document document, TextSpan span, string expected, DiagnosticDescriptor descriptor)
        {
            var codeFixes = GetCodeFixes(document, span, descriptor);
            Assert.That(codeFixes.Length, Is.EqualTo(1));

            Verify.CodeAction(codeFixes[0], document, expected);
        }
開發者ID:sangelov,項目名稱:RoslynNUnitLight,代碼行數:7,代碼來源:CodeFixTestFixture.cs

示例8: ToDiagnostics

        public static Diagnostic ToDiagnostics(this RazorError error, string filePath)
        {
            if (error == null)
            {
                throw new ArgumentNullException(nameof(error));
            }

            if (filePath == null)
            {
                throw new ArgumentNullException(nameof(filePath));
            }

            var descriptor = new DiagnosticDescriptor(
                id: "Razor",
                title: "Razor parsing error",
                messageFormat: error.Message.Replace("{", "{{").Replace("}", "}}"),
                category: "Razor.Parser",
                defaultSeverity: DiagnosticSeverity.Error,
                isEnabledByDefault: true);

            var location = error.Location;
            if (location.Equals(SourceLocation.Undefined))
            {
                location = SourceLocation.Zero;
            }
            var length = Math.Max(0, error.Length);

            var textSpan = new TextSpan(location.AbsoluteIndex, length);
            var linePositionStart = new LinePosition(location.LineIndex, location.CharacterIndex);
            var linePositionEnd = new LinePosition(location.LineIndex, location.CharacterIndex + length);
            var linePositionSpan = new LinePositionSpan(linePositionStart, linePositionEnd);
            return Diagnostic.Create(descriptor, Location.Create(filePath, textSpan, linePositionSpan));
        }
開發者ID:huoxudong125,項目名稱:Mvc,代碼行數:33,代碼來源:RazorErrorExtensions.cs

示例9: SimpleDiagnostic

            private SimpleDiagnostic(
                DiagnosticDescriptor descriptor,
                DiagnosticSeverity severity,
                int warningLevel,
                Location location,
                IEnumerable<Location> additionalLocations,
                object[] messageArgs)
            {
                if ((warningLevel == 0 && severity != DiagnosticSeverity.Error) ||
                    (warningLevel != 0 && severity == DiagnosticSeverity.Error))
                {
                    throw new ArgumentException(nameof(warningLevel));
                }

                if(descriptor == null)
                {
                    throw new ArgumentNullException(nameof(descriptor));
                }

                _descriptor = descriptor;
                _severity = severity;
                _warningLevel = warningLevel;
                _location = location ?? Location.None;
                _additionalLocations = additionalLocations == null ? SpecializedCollections.EmptyReadOnlyList<Location>() : additionalLocations.ToImmutableArray();
                _messageArgs = messageArgs ?? SpecializedCollections.EmptyArray<object>();
            }
開發者ID:elemk0vv,項目名稱:roslyn-1,代碼行數:26,代碼來源:Diagnostic_SimpleDiagnostic.cs

示例10: GetDescriptionAsRawHtml

        /// <summary>
        /// Returns the description as HTML
        /// </summary>
        /// <returns>Note: the description should be returned as the HTML that should be rendered i.e. there is no need enclose it in a CDATA section</returns>
        private static string GetDescriptionAsRawHtml(DiagnosticDescriptor diagnostic)
        {
            StringBuilder sb = new StringBuilder();
            bool hasDescription = false;

            string details = diagnostic.Description.ToString(CultureInfo.CurrentCulture);
            if (!String.IsNullOrWhiteSpace(details))
            {
                sb.AppendLine("<p>" + details + "</p>");
                hasDescription = true;
            }

            if (!String.IsNullOrWhiteSpace(diagnostic.HelpLinkUri))
            {
                sb.AppendLine("<h2>" + UIResources.RuleGen_MoreDetailsTitle + "</h2>");
                sb.AppendLine(String.Format(UIResources.RuleGen_ForMoreDetailsLink, diagnostic.HelpLinkUri));
                hasDescription = true;
            }

            if (!hasDescription)
            {
                return UIResources.RuleGen_NoDescription;
            }

            return sb.ToString();
        }
開發者ID:SonarSource-VisualStudio,項目名稱:sonarqube-roslyn-sdk,代碼行數:30,代碼來源:RuleGenerator.cs

示例11: DiagnosticResult

 public DiagnosticResult(DiagnosticDescriptor descriptor)
     : this()
 {
     this.Id = descriptor.Id;
     this.Severity = descriptor.DefaultSeverity;
     this.MessageFormat = descriptor.MessageFormat;
 }
開發者ID:Romanx,項目名稱:StyleCopAnalyzers,代碼行數:7,代碼來源:DiagnosticResult.cs

示例12: BeforeCompile

        public void BeforeCompile(IBeforeCompileContext context)
        {
            string keyPath = Environment.GetEnvironmentVariable("NUGET_BUILD_KEY_PATH");
            string delaySignString = Environment.GetEnvironmentVariable("NUGET_BUILD_DELAY_SIGN");

            if (!string.IsNullOrEmpty(keyPath))
            {
                FileInfo keyFile = new FileInfo(keyPath);

                if (keyFile.Exists)
                {
                    bool delaySign = delaySignString != null && StringComparer.OrdinalIgnoreCase.Equals("true", delaySignString);

                    // Console.WriteLine("Signing assembly with: {0} Delay sign: {1}", keyFile.FullName, delaySign ? "true" : "false");

                    var parms = new CspParameters();
                    parms.KeyNumber = 2;

                    var provider = new RSACryptoServiceProvider(parms);
                    byte[] array = provider.ExportCspBlob(!provider.PublicOnly);

                    var strongNameProvider = new DesktopStrongNameProvider();


                    var options = context.Compilation.Options.WithStrongNameProvider(strongNameProvider)
                                                                   .WithCryptoKeyFile(keyFile.FullName)
                                                                   .WithDelaySign(delaySign);

                    // Enfore viral strong naming
                    var specificDiagnosticOptions = new Dictionary<string, ReportDiagnostic>(options.SpecificDiagnosticOptions);
                    specificDiagnosticOptions["CS8002"] = ReportDiagnostic.Error;
                    options = options.WithSpecificDiagnosticOptions(specificDiagnosticOptions);

                    context.Compilation = context.Compilation.WithOptions(options);
                }
                else
                {
                    // The key was not found. Throw a compile error.
                    var descriptor = new DiagnosticDescriptor(
                    id: "SN1001",
                    title: "Missing key file",
                    messageFormat: "Key file '{0}' could not be found",
                    category: "CA1001: \"StrongNaming\"",
                    defaultSeverity: DiagnosticSeverity.Error,
                    isEnabledByDefault: true);

                    // TODO: what should this reference for the location?
                    var textSpan = new TextSpan();
                    var position = new LinePosition(0, 0);
                    var span = new LinePositionSpan(position, position);

                    var location = Location.Create(context.ProjectContext.ProjectFilePath, textSpan, span);

                    var diagnsotic = Diagnostic.Create(descriptor, location, keyPath);

                    context.Diagnostics.Add(diagnsotic);
                }
            }
        }
開發者ID:cinecove,項目名稱:NuGet.Versioning,代碼行數:59,代碼來源:StrongNamingModule.cs

示例13: Start

 public LockChecks Start(SyntaxNodeAnalysisContext AnalysisContext,DiagnosticDescriptor rule)
 {
     this.analysisContext = AnalysisContext;
     this.usingStatement = (UsingStatementSyntax)analysisContext.Node;
     this.rule = rule;
     reportedIssue = false;
     return this;
 }
開發者ID:peterstevens130561,項目名稱:sonarlint-vs,代碼行數:8,代碼來源:LockChecks.cs

示例14: TestCodeFix

        protected new void TestCodeFix(string markupCode, string expected, DiagnosticDescriptor descriptor)
        {
            Document document;
            TextSpan span;
            TestHelpers.TryGetDocumentAndSpanFromMarkup(markupCode, LanguageName, References.Default, out document, out span);

            TestCodeFix(document, span, expected, descriptor);
        }
開發者ID:jwendl,項目名稱:CoreFxAnalyzers,代碼行數:8,代碼來源:ImmutableCodeFixTestFixture.cs

示例15: DiagnosticItem

 public DiagnosticItem(AnalyzerItem analyzerItem, DiagnosticDescriptor descriptor, ReportDiagnostic effectiveSeverity, IContextMenuController contextMenuController)
     : base(string.Format("{0}: {1}", descriptor.Id, descriptor.Title))
 {
     _analyzerItem = analyzerItem;
     _descriptor = descriptor;
     _effectiveSeverity = effectiveSeverity;
     _contextMenuController = contextMenuController;
 }
開發者ID:nemec,項目名稱:roslyn,代碼行數:8,代碼來源:DiagnosticItem.cs


注:本文中的Microsoft.CodeAnalysis.DiagnosticDescriptor類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。