当前位置: 首页>>代码示例>>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;未经允许,请勿转载。