From 8a97b16035d8fe0a616af12306e69c3a96a86efa Mon Sep 17 00:00:00 2001 From: paulomorgado <470455+paulomorgado@users.noreply.github.com> Date: Thu, 1 Aug 2019 23:04:12 +0100 Subject: [PATCH 01/11] add analyzer/fixer for usages of Enumerable.Count() where a property of the target type with the same semantics already exists. --- ...icrosoft.CodeAnalysis.FxCopAnalyzers.sarif | 88 ++++++-- ...InsteadOfCountMethodWhenAvailable.Fixer.cs | 35 +++ .../MicrosoftNetCoreAnalyzersResources.resx | 9 + ...InsteadOfCountMethodWhenAvailable.Fixer.cs | 117 ++++++++++ ...opertyInsteadOfCountMethodWhenAvailable.cs | 207 ++++++++++++++++++ .../MicrosoftNetCoreAnalyzersResources.cs.xlf | 15 ++ .../MicrosoftNetCoreAnalyzersResources.de.xlf | 15 ++ .../MicrosoftNetCoreAnalyzersResources.es.xlf | 15 ++ .../MicrosoftNetCoreAnalyzersResources.fr.xlf | 15 ++ .../MicrosoftNetCoreAnalyzersResources.it.xlf | 15 ++ .../MicrosoftNetCoreAnalyzersResources.ja.xlf | 15 ++ .../MicrosoftNetCoreAnalyzersResources.ko.xlf | 15 ++ .../MicrosoftNetCoreAnalyzersResources.pl.xlf | 15 ++ ...crosoftNetCoreAnalyzersResources.pt-BR.xlf | 15 ++ .../MicrosoftNetCoreAnalyzersResources.ru.xlf | 15 ++ .../MicrosoftNetCoreAnalyzersResources.tr.xlf | 15 ++ ...osoftNetCoreAnalyzersResources.zh-Hans.xlf | 15 ++ ...osoftNetCoreAnalyzersResources.zh-Hant.xlf | 15 ++ .../Microsoft.NetCore.Analyzers.sarif | 88 ++++++-- ...opertyInsteadOfCountMethodWhenAvailable.cs | 112 ++++++++++ ...osoft.NetCore.VisualBasic.Analyzers.vbproj | 3 - ...InsteadOfCountMethodWhenAvailable.Fixer.vb | 42 ++++ 22 files changed, 849 insertions(+), 47 deletions(-) create mode 100644 src/Microsoft.NetCore.Analyzers/CSharp/Performance/CSharpUsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs create mode 100644 src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs create mode 100644 src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs create mode 100644 src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs create mode 100644 src/Microsoft.NetCore.Analyzers/VisualBasic/Performance/BasicUsePropertyInsteadOfCountMethodWhenAvailable.Fixer.vb diff --git a/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.sarif b/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.sarif index e7ae266bd8..c9b01a0b60 100644 --- a/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.sarif +++ b/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.sarif @@ -2128,32 +2128,16 @@ ] } }, - "CA1827": { - "id": "CA1827", - "shortDescription": "Do not use Count() or LongCount() when Any() can be used", - "fullDescription": "For non-empty collections, Count() and LongCount() enumerate the entire sequence, while Any() stops at the first item or the first item that satisfies a condition.", - "defaultLevel": "warning", - "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1827", - "properties": { - "category": "Performance", - "isEnabledByDefault": true, - "typeName": "DoNotUseCountWhenAnyCanBeUsedAnalyzer", - "languages": [ - "C#", - "Visual Basic" - ] - } - }, - "CA1828": { - "id": "CA1828", - "shortDescription": "Do not use CountAsync() or LongCountAsync() when AnyAsync() can be used", - "fullDescription": "For non-empty collections, CountAsync() and LongCountAsync() enumerate the entire sequence, while AnyAsync() stops at the first item or the first item that satisfies a condition.", + "CA1829": { + "id": "CA1829", + "shortDescription": "Use property instead of Count() when available", + "fullDescription": "Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access.", "defaultLevel": "warning", - "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1828", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1829", "properties": { "category": "Performance", "isEnabledByDefault": true, - "typeName": "DoNotUseCountWhenAnyCanBeUsedAnalyzer", + "typeName": "UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer", "languages": [ "C#", "Visual Basic" @@ -3788,6 +3772,36 @@ ] } }, + "CA1827": { + "id": "CA1827", + "shortDescription": "Do not use Count() or LongCount() when Any() can be used", + "fullDescription": "For non-empty collections, Count() and LongCount() enumerate the entire sequence, while Any() stops at the first item or the first item that satisfies a condition.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1827", + "properties": { + "category": "Performance", + "isEnabledByDefault": true, + "typeName": "CSharpDoNotUseCountWhenAnyCanBeUsedAnalyzer", + "languages": [ + "C#" + ] + } + }, + "CA1828": { + "id": "CA1828", + "shortDescription": "Do not use CountAsync() or LongCountAsync() when AnyAsync() can be used", + "fullDescription": "For non-empty collections, CountAsync() and LongCountAsync() enumerate the entire sequence, while AnyAsync() stops at the first item or the first item that satisfies a condition.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1828", + "properties": { + "category": "Performance", + "isEnabledByDefault": true, + "typeName": "CSharpDoNotUseCountWhenAnyCanBeUsedAnalyzer", + "languages": [ + "C#" + ] + } + }, "CA2010": { "id": "CA2010", "shortDescription": "Always consume the value returned by methods marked with PreserveSigAttribute", @@ -3923,6 +3937,36 @@ ] } }, + "CA1827": { + "id": "CA1827", + "shortDescription": "Do not use Count() or LongCount() when Any() can be used", + "fullDescription": "For non-empty collections, Count() and LongCount() enumerate the entire sequence, while Any() stops at the first item or the first item that satisfies a condition.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1827", + "properties": { + "category": "Performance", + "isEnabledByDefault": true, + "typeName": "BasicDoNotUseCountWhenAnyCanBeUsedAnalyzer", + "languages": [ + "Visual Basic" + ] + } + }, + "CA1828": { + "id": "CA1828", + "shortDescription": "Do not use CountAsync() or LongCountAsync() when AnyAsync() can be used", + "fullDescription": "For non-empty collections, CountAsync() and LongCountAsync() enumerate the entire sequence, while AnyAsync() stops at the first item or the first item that satisfies a condition.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1828", + "properties": { + "category": "Performance", + "isEnabledByDefault": true, + "typeName": "BasicDoNotUseCountWhenAnyCanBeUsedAnalyzer", + "languages": [ + "Visual Basic" + ] + } + }, "CA2010": { "id": "CA2010", "shortDescription": "Always consume the value returned by methods marked with PreserveSigAttribute", diff --git a/src/Microsoft.NetCore.Analyzers/CSharp/Performance/CSharpUsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs b/src/Microsoft.NetCore.Analyzers/CSharp/Performance/CSharpUsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs new file mode 100644 index 0000000000..b414cb817b --- /dev/null +++ b/src/Microsoft.NetCore.Analyzers/CSharp/Performance/CSharpUsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Composition; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.NetCore.Analyzers.Performance; + +namespace Microsoft.NetCore.CSharp.Analyzers.Performance +{ + /// + /// CA1829: Use property instead of , when available. + /// + [ExportCodeFixProvider(LanguageNames.CSharp), Shared] + public sealed class CSharpUsePropertyInsteadOfCountMethodWhenAvailableFixer : UsePropertyInsteadOfCountMethodWhenAvailableFixer + { + /// + /// Gets the expression from the specified where to replace the invocation of the + /// method with a property invocation. + /// + /// The node to get a fixer for. + /// The expression from the specified where to replace the invocation of the + /// method with a property invocation + /// if found; otherwise. + protected override SyntaxNode GetExpression(SyntaxNode node) + { + if (node is InvocationExpressionSyntax invocationExpression) + { + return ((MemberAccessExpressionSyntax)invocationExpression.Expression).Expression; + } + + return null; + } + } +} diff --git a/src/Microsoft.NetCore.Analyzers/Core/MicrosoftNetCoreAnalyzersResources.resx b/src/Microsoft.NetCore.Analyzers/Core/MicrosoftNetCoreAnalyzersResources.resx index 3777d1cbcb..c375a744d0 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/MicrosoftNetCoreAnalyzersResources.resx +++ b/src/Microsoft.NetCore.Analyzers/Core/MicrosoftNetCoreAnalyzersResources.resx @@ -1134,6 +1134,15 @@ Do not use CountAsync() or LongCountAsync() when AnyAsync() can be used + + Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. + + + Use the {0} property instead of Enumerable.Count(). + + + Use property instead of Count() when available + Set HttpOnly to true for HttpCookie diff --git a/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs b/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs new file mode 100644 index 0000000000..dc795a00e2 --- /dev/null +++ b/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Linq.Expressions; +using System.Threading; +using System.Threading.Tasks; +using Analyzer.Utilities; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CodeActions; +using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Editing; +using Microsoft.CodeAnalysis.Formatting; + +namespace Microsoft.NetCore.Analyzers.Performance + +{ + /// + /// CA1829: Use property instead of , when available. + /// Implements the + /// + public abstract class UsePropertyInsteadOfCountMethodWhenAvailableFixer : CodeFixProvider + { + /// + /// A list of diagnostic IDs that this provider can provider fixes for. + /// + /// The fixable diagnostic ids. + public override ImmutableArray FixableDiagnosticIds { get; } = ImmutableArray.Create(UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer.RuleId); + + + /// + /// Gets an optional that can fix all/multiple occurrences of diagnostics fixed by this code fix provider. + /// Return null if the provider doesn't support fix all/multiple occurrences. + /// Otherwise, you can return any of the well known fix all providers from or implement your own fix all provider. + /// + /// FixAllProvider. + public sealed override FixAllProvider GetFixAllProvider() + { + // See https://github.com/dotnet/roslyn/blob/master/docs/analyzers/FixAllProvider.md for more information on Fix All Providers + return WellKnownFixAllProviders.BatchFixer; + } + + /// + /// Computes one or more fixes for the specified . + /// + /// A containing context information about the diagnostics to fix. + /// The context must only contain diagnostics with a included in the + /// for the current provider. + /// A that represents the asynchronous operation. + public override async Task RegisterCodeFixesAsync(CodeFixContext context) + { + var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); + var node = root.FindNode(context.Span); + var propertyName = context.Diagnostics[0].Properties["PropertyName"]; + + if (node is object && propertyName is object && GetExpression(node) is SyntaxNode expression) + { + context.RegisterCodeFix( + new UsePropertyInsteadOfCountMethodWhenAvailableCodeAction(context.Document, node, expression, propertyName), + context.Diagnostics); + } + } + + /// + /// Gets the expression from the specified where to replace the invocation of the + /// method with a property invocation. + /// + /// The node to get a fixer for. + /// The expression from the specified where to replace the invocation of the + /// method with a property invocation + /// if found; otherwise. + protected abstract SyntaxNode GetExpression(SyntaxNode node); + + private class UsePropertyInsteadOfCountMethodWhenAvailableCodeAction : CodeAction + { + private readonly Document document; + private readonly SyntaxNode node; + private readonly SyntaxNode expression; + private readonly string propertyName; + + public UsePropertyInsteadOfCountMethodWhenAvailableCodeAction( + Document document, + SyntaxNode node, + SyntaxNode expression, + string propertyName) + { + this.document = document; + this.node = node; + this.expression = expression; + this.propertyName = propertyName; + } + + public override string Title { get; } = MicrosoftNetCoreAnalyzersResources.UsePropertyInsteadOfCountMethodWhenAvailableTitle; + + public override string EquivalenceKey { get; } = MicrosoftNetCoreAnalyzersResources.UsePropertyInsteadOfCountMethodWhenAvailableTitle; + + protected override async Task GetChangedDocumentAsync(CancellationToken cancellationToken) + { + var editor = await DocumentEditor.CreateAsync(this.document, cancellationToken).ConfigureAwait(false); + var generator = editor.Generator; + var replacementSyntax = generator.MemberAccessExpression(this.expression.WithoutTrailingTrivia(), this.propertyName); + + replacementSyntax = replacementSyntax + .WithAdditionalAnnotations(Formatter.Annotation) + .WithTriviaFrom(this.node); + + editor.ReplaceNode(this.node, replacementSyntax); + + return editor.GetChangedDocument(); + } + } + } +} diff --git a/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs b/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs new file mode 100644 index 0000000000..bdf10de7f4 --- /dev/null +++ b/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs @@ -0,0 +1,207 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Linq; +using Analyzer.Utilities; +using Analyzer.Utilities.Extensions; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Operations; +using Microsoft.NetCore.Analyzers; + +namespace Microsoft.NetCore.Analyzers.Performance +{ + /// + /// CA1829: Use property instead of , when available. + /// Implements the + /// + /// + /// Flags the use of on types that are know to have a property with the same semantics: + /// Length, Count. + /// + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + public sealed class UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer : DiagnosticAnalyzer + { + internal const string RuleId = "CA1829"; + private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.UsePropertyInsteadOfCountMethodWhenAvailableTitle), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); + private static readonly LocalizableString s_localizableMessage = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.UsePropertyInsteadOfCountMethodWhenAvailableMessage), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); + private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.UsePropertyInsteadOfCountMethodWhenAvailableDescription), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); + private static readonly DiagnosticDescriptor s_rule = new DiagnosticDescriptor( + RuleId, + s_localizableTitle, + s_localizableMessage, + DiagnosticCategory.Performance, + DiagnosticHelpers.DefaultDiagnosticSeverity, + isEnabledByDefault: DiagnosticHelpers.EnabledByDefaultForVsixAndNuget, + description: s_localizableDescription, +#pragma warning disable CA1308 // Normalize strings to uppercase + helpLinkUri: "https://docs.microsoft.com/visualstudio/code-quality/" + RuleId.ToLowerInvariant()); +#pragma warning restore CA1308 // Normalize strings to uppercase + + private static readonly ImmutableHashSet propertyNames = ImmutableHashSet.Create("Length", "Count"); + + /// + /// Returns a set of descriptors for the diagnostics that this analyzer is capable of producing. + /// + /// The supported diagnostics. + public override ImmutableArray SupportedDiagnostics { get; } = ImmutableArray.Create(s_rule); + + /// + /// Called once at session start to register actions in the analysis context. + /// + /// The context. + public override void Initialize(AnalysisContext context) + { + context.EnableConcurrentExecution(); + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); + + context.RegisterCompilationStartAction(OnCompilationStart); + } + + /// + /// Called on compilation start. + /// + /// The context. + private static void OnCompilationStart(CompilationStartAnalysisContext context) + { + if (WellKnownTypes.Enumerable(context.Compilation) is INamedTypeSymbol enumerableType) + { + var operationActionsHandler = context.Compilation.Language == LanguageNames.CSharp + ? (OperationActionsHandler)new CSharpOperationActionsHandler(containingSymbol: enumerableType, rule: s_rule) + : (OperationActionsHandler)new BasicOperationActionsHandler(containingSymbol: enumerableType, rule: s_rule); + + context.RegisterOperationAction( + operationActionsHandler.AnalyzeInvocationOperation, + OperationKind.Invocation); + } + } + + /// + /// Handler for operaction actions. + /// + private abstract class OperationActionsHandler + { + private readonly INamedTypeSymbol containingSymbol; + private readonly DiagnosticDescriptor rule; + + protected OperationActionsHandler(INamedTypeSymbol containingSymbol, DiagnosticDescriptor rule) + { + this.containingSymbol = containingSymbol; + this.rule = rule; + } + + internal void AnalyzeInvocationOperation(OperationAnalysisContext context) + { + var invocationOperation = (IInvocationOperation)context.Operation; + + if (GetEnumerableCountInvocationTargetType(invocationOperation, this.containingSymbol) is ITypeSymbol invocationTarget && + GetReplacementProperty(invocationTarget) is string propertyName) + { + var propertiesBuilder = ImmutableDictionary.CreateBuilder(); + propertiesBuilder.Add("PropertyName", propertyName); + + var diagnostic = Diagnostic.Create( + this.rule, + invocationOperation.Syntax.GetLocation(), + propertiesBuilder.ToImmutable(), + propertyName); + + context.ReportDiagnostic(diagnostic); + } + } + + protected abstract ITypeSymbol GetEnumerableCountInvocationTargetType(IInvocationOperation invocationOperation, INamedTypeSymbol containingSymbol); + + private static string GetReplacementProperty(ITypeSymbol invocationTarget) + { + if (invocationTarget.TypeKind == TypeKind.Array) + { + return nameof(Array.Length); + } + + foreach (var member in invocationTarget.GetMembers()) + { + if (member is IPropertySymbol property && propertyNames.Contains(property.Name)) + { + return property.Name; + } + } + + foreach (var type in invocationTarget.AllInterfaces) + { + foreach (var member in type.GetMembers()) + { + if (member is IPropertySymbol property && propertyNames.Contains(property.Name)) + { + return property.Name; + } + } + } + + return null; + } + } + + /// + /// Handler for operaction actions for C#. This class cannot be inherited. + /// Implements the + /// + /// + private sealed class CSharpOperationActionsHandler : OperationActionsHandler + { + internal CSharpOperationActionsHandler(INamedTypeSymbol containingSymbol, DiagnosticDescriptor rule) : base(containingSymbol, rule) + { + } + + protected override ITypeSymbol GetEnumerableCountInvocationTargetType(IInvocationOperation invocationOperation, INamedTypeSymbol containingSymbol) + { + var method = invocationOperation.TargetMethod; + + if (invocationOperation.Arguments.Length == 1 && + method.Name.Equals(nameof(Enumerable.Count), StringComparison.Ordinal) && + method.ContainingSymbol.Equals(containingSymbol)) + { + var targetType = invocationOperation.Arguments[0].Value is IConversionOperation convertionOperation + ? convertionOperation.Operand.Type + : invocationOperation.Arguments[0].Value.Type; + + return targetType as ITypeSymbol; + } + + return null; + } + } + + /// + /// Handler for operaction actions fro Visual Basic. This class cannot be inherited. + /// Implements the + /// + /// + private sealed class BasicOperationActionsHandler : OperationActionsHandler + { + internal BasicOperationActionsHandler(INamedTypeSymbol containingSymbol, DiagnosticDescriptor rule) : base(containingSymbol, rule) + { + } + + protected override ITypeSymbol GetEnumerableCountInvocationTargetType(IInvocationOperation invocationOperation, INamedTypeSymbol containingSymbol) + { + var method = invocationOperation.TargetMethod; + + if (invocationOperation.Arguments.Length == 0 && + method.Name.Equals(nameof(Enumerable.Count), StringComparison.Ordinal) && + method.ContainingSymbol.Equals(containingSymbol)) + { + var targetType = invocationOperation.Instance is IConversionOperation convertionOperation + ? convertionOperation.Operand.Type + : invocationOperation.Instance.Type; + + return targetType as ITypeSymbol; + } + + return null; + } + } + } +} diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.cs.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.cs.xlf index 0462ff7c96..c9da78a201 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.cs.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.cs.xlf @@ -1662,6 +1662,21 @@ Pokud je to možné, zvažte použití řízení přístupu Azure na základě role namísto sdíleného přístupového podpisu (SAS). Pokud i přesto potřebujete používat sdílený přístupový podpis, použijte při jeho vytváření zásady přístupu na úrovni kontejneru. + + Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. + Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. + + + + Use the {0} property instead of Enumerable.Count(). + Use the {0} property instead of Enumerable.Count(). + + + + Use property instead of Count() when available + Use property instead of Count() when available + + Use Rivest–Shamir–Adleman (RSA) Algorithm With Sufficient Key Size Použijte algoritmus RSA (Rivest-Shamir-Adleman) s dostatečnou velikostí klíče diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.de.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.de.xlf index 42539896f2..e58f50a9ea 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.de.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.de.xlf @@ -1662,6 +1662,21 @@ Erwägen Sie (sofern möglich) die Verwendung der rollenbasierten Zugriffssteuerung von Azure anstelle einer Shared Access Signature (SAS). Wenn Sie weiterhin eine SAS benötigen, verwenden Sie beim Erstellen einer SAS eine Zugriffsrichtlinie auf Containerebene. + + Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. + Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. + + + + Use the {0} property instead of Enumerable.Count(). + Use the {0} property instead of Enumerable.Count(). + + + + Use property instead of Count() when available + Use property instead of Count() when available + + Use Rivest–Shamir–Adleman (RSA) Algorithm With Sufficient Key Size Verwenden Sie den RSA-Algorithmus (Rivest – Shamir – Adleman) mit einer ausreichenden Schlüsselgröße. diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.es.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.es.xlf index c93fa8ae09..123574a9eb 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.es.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.es.xlf @@ -1662,6 +1662,21 @@ Considere la posibilidad de usar el control de acceso basado en rol de Azure en lugar de una firma de acceso compartido (SAS), si es posible. Si tiene que usar una firma de acceso compartido, utilice una directiva de acceso de nivel de contenedor al crear la firma. + + Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. + Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. + + + + Use the {0} property instead of Enumerable.Count(). + Use the {0} property instead of Enumerable.Count(). + + + + Use property instead of Count() when available + Use property instead of Count() when available + + Use Rivest–Shamir–Adleman (RSA) Algorithm With Sufficient Key Size Usar un algoritmo de Rivest-Shamir-Adleman (RSA) con un tamaño de clave suficiente diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.fr.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.fr.xlf index 61eb231dcf..230604fa65 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.fr.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.fr.xlf @@ -1662,6 +1662,21 @@ Si possible, utilisez la fonctionnalité RBAC (contrôle d'accès en fonction du rôle) d'Azure à la place d'une SAP (signature d'accès partagé). Si vous devez quand même utiliser une SAP, utilisez une stratégie d'accès au niveau du conteneur quand vous créez la SAP + + Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. + Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. + + + + Use the {0} property instead of Enumerable.Count(). + Use the {0} property instead of Enumerable.Count(). + + + + Use property instead of Count() when available + Use property instead of Count() when available + + Use Rivest–Shamir–Adleman (RSA) Algorithm With Sufficient Key Size Utiliser l'algorithme RSA (Rivest-Shamir-Adleman) avec une taille de clé suffisante diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.it.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.it.xlf index 0edddb1ddc..ffe754ae7f 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.it.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.it.xlf @@ -1662,6 +1662,21 @@ Se possibile, provare a usare il controllo degli accessi in base al ruolo di Azure, invece della firma di accesso condiviso. Se è necessaria una firma di accesso condiviso, usare un criterio di accesso a livello di contenitore quando si crea la firma + + Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. + Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. + + + + Use the {0} property instead of Enumerable.Count(). + Use the {0} property instead of Enumerable.Count(). + + + + Use property instead of Count() when available + Use property instead of Count() when available + + Use Rivest–Shamir–Adleman (RSA) Algorithm With Sufficient Key Size Usa l'algoritmo RSA (Rivest-Shamir-Adleman) con dimensione di chiave sufficiente diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ja.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ja.xlf index 195af8c4df..7a7a4799d3 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ja.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ja.xlf @@ -1662,6 +1662,21 @@ 可能な場合は、Shared Access Signature (SAS) の代わりに、Azure のロールベースのアクセス制御を使用することを検討してください。依然として SAS を使用する必要がある場合は、SAS の作成時にコンテナーレベルのアクセス ポリシーを使用します + + Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. + Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. + + + + Use the {0} property instead of Enumerable.Count(). + Use the {0} property instead of Enumerable.Count(). + + + + Use property instead of Count() when available + Use property instead of Count() when available + + Use Rivest–Shamir–Adleman (RSA) Algorithm With Sufficient Key Size 十分なキー サイズの Rivest–Shamir–Adleman (RSA) アルゴリズムを使用します diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ko.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ko.xlf index d502db3161..e5c05420b9 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ko.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ko.xlf @@ -1662,6 +1662,21 @@ 가능한 경우 SAS(공유 액세스 서명) 대신 Azure의 역할 기반 액세스 제어를 사용하세요. 계속 SAS를 사용해야 할 경우 SAS를 만들 때 컨테이너 수준 액세스 정책을 사용하세요. + + Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. + Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. + + + + Use the {0} property instead of Enumerable.Count(). + Use the {0} property instead of Enumerable.Count(). + + + + Use property instead of Count() when available + Use property instead of Count() when available + + Use Rivest–Shamir–Adleman (RSA) Algorithm With Sufficient Key Size 충분한 키 크기로 RSA(Rivest–Shamir–Adleman) 알고리즘 사용 diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.pl.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.pl.xlf index d4b0e232ec..13ba185429 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.pl.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.pl.xlf @@ -1662,6 +1662,21 @@ Jeśli to możliwe, rozważ użycie kontroli dostępu opartej na rolach platformy Azure zamiast sygnatury dostępu współdzielonego (SAS). Jeśli nadal chcesz używać sygnatury SAS, podczas jej tworzenia użyj zasad dostępu na poziomie kontenera + + Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. + Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. + + + + Use the {0} property instead of Enumerable.Count(). + Use the {0} property instead of Enumerable.Count(). + + + + Use property instead of Count() when available + Use property instead of Count() when available + + Use Rivest–Shamir–Adleman (RSA) Algorithm With Sufficient Key Size Użyj algorytmu Rivest-Shamir-Adleman (RSA) z wystarczającym rozmiarem klucza diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.pt-BR.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.pt-BR.xlf index fad26873b1..e245b646a1 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.pt-BR.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.pt-BR.xlf @@ -1662,6 +1662,21 @@ Se possível, considere usar o controle de acesso baseado em função do Azure em vez de uma SAS (Assinatura de Acesso Compartilhado). Se você ainda precisar usar uma SAS, use uma política de acesso de nível de contêiner ao criar uma SAS + + Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. + Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. + + + + Use the {0} property instead of Enumerable.Count(). + Use the {0} property instead of Enumerable.Count(). + + + + Use property instead of Count() when available + Use property instead of Count() when available + + Use Rivest–Shamir–Adleman (RSA) Algorithm With Sufficient Key Size Usar o Algoritmo RSA (Rivest-Shamir-Adleman) com um Tamanho de Chave Suficiente diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ru.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ru.xlf index fde0948067..f5579cc6d6 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ru.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ru.xlf @@ -1662,6 +1662,21 @@ Если возможно, попробуйте использовать управление доступом на основе ролей Azure, а не подписанный URL-адрес (SAS). Если все-таки требуется использовать SAS, при его создании примените политику доступа на уровне контейнера. + + Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. + Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. + + + + Use the {0} property instead of Enumerable.Count(). + Use the {0} property instead of Enumerable.Count(). + + + + Use property instead of Count() when available + Use property instead of Count() when available + + Use Rivest–Shamir–Adleman (RSA) Algorithm With Sufficient Key Size Использовать алгоритм шифрования RSA с достаточным размером ключа diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.tr.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.tr.xlf index 8383d239bf..a999191f74 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.tr.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.tr.xlf @@ -1662,6 +1662,21 @@ Mümkünse Paylaşılan Erişim İmzası (SAS) yerine Azure'un rol tabanlı erişim denetimini kullanmayı düşünün. Yine de SAS kullanmanız gerekiyorsa, SAS oluştururken kapsayıcı düzeyinde bir erişim ilkesi kullanın + + Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. + Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. + + + + Use the {0} property instead of Enumerable.Count(). + Use the {0} property instead of Enumerable.Count(). + + + + Use property instead of Count() when available + Use property instead of Count() when available + + Use Rivest–Shamir–Adleman (RSA) Algorithm With Sufficient Key Size Yeterli Anahtar Boyutuna Sahip Rivest–Shamir–Adleman (RSA) Algoritmasını Kullan diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hans.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hans.xlf index 4ea0ce2d1c..1fcd9df8c7 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hans.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hans.xlf @@ -1662,6 +1662,21 @@ 如果可能,请考虑使用 Azure 基于角色的访问控制,而不是共享访问签名(SAS)。如果仍需使用 SAS,请在创建 SAS 时使用容器级别访问策略 + + Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. + Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. + + + + Use the {0} property instead of Enumerable.Count(). + Use the {0} property instead of Enumerable.Count(). + + + + Use property instead of Count() when available + Use property instead of Count() when available + + Use Rivest–Shamir–Adleman (RSA) Algorithm With Sufficient Key Size 设置具有足够密钥大小的 Rivest–Shamir–Adleman (RSA)算法 diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hant.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hant.xlf index fa382c06ff..e8f88cd422 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hant.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hant.xlf @@ -1662,6 +1662,21 @@ 如果可行的話,請考慮從共用存取簽章 (SAS) 改為使用 Azure 的角色型存取控制。如果您仍需要使用 SAS,請於建立 SAS 時使用容器層級存取原則 + + Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. + Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. + + + + Use the {0} property instead of Enumerable.Count(). + Use the {0} property instead of Enumerable.Count(). + + + + Use property instead of Count() when available + Use property instead of Count() when available + + Use Rivest–Shamir–Adleman (RSA) Algorithm With Sufficient Key Size 使用有足夠金鑰大小的 Rivest–Shamir–Adleman (RSA) 加密演算法 diff --git a/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.sarif b/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.sarif index 680449a91a..348d89fac4 100644 --- a/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.sarif +++ b/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.sarif @@ -208,32 +208,16 @@ ] } }, - "CA1827": { - "id": "CA1827", - "shortDescription": "Do not use Count() or LongCount() when Any() can be used", - "fullDescription": "For non-empty collections, Count() and LongCount() enumerate the entire sequence, while Any() stops at the first item or the first item that satisfies a condition.", - "defaultLevel": "warning", - "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1827", - "properties": { - "category": "Performance", - "isEnabledByDefault": true, - "typeName": "DoNotUseCountWhenAnyCanBeUsedAnalyzer", - "languages": [ - "C#", - "Visual Basic" - ] - } - }, - "CA1828": { - "id": "CA1828", - "shortDescription": "Do not use CountAsync() or LongCountAsync() when AnyAsync() can be used", - "fullDescription": "For non-empty collections, CountAsync() and LongCountAsync() enumerate the entire sequence, while AnyAsync() stops at the first item or the first item that satisfies a condition.", + "CA1829": { + "id": "CA1829", + "shortDescription": "Use property instead of Count() when available", + "fullDescription": "Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access.", "defaultLevel": "warning", - "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1828", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1829", "properties": { "category": "Performance", "isEnabledByDefault": true, - "typeName": "DoNotUseCountWhenAnyCanBeUsedAnalyzer", + "typeName": "UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer", "languages": [ "C#", "Visual Basic" @@ -1868,6 +1852,36 @@ ] } }, + "CA1827": { + "id": "CA1827", + "shortDescription": "Do not use Count() or LongCount() when Any() can be used", + "fullDescription": "For non-empty collections, Count() and LongCount() enumerate the entire sequence, while Any() stops at the first item or the first item that satisfies a condition.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1827", + "properties": { + "category": "Performance", + "isEnabledByDefault": true, + "typeName": "CSharpDoNotUseCountWhenAnyCanBeUsedAnalyzer", + "languages": [ + "C#" + ] + } + }, + "CA1828": { + "id": "CA1828", + "shortDescription": "Do not use CountAsync() or LongCountAsync() when AnyAsync() can be used", + "fullDescription": "For non-empty collections, CountAsync() and LongCountAsync() enumerate the entire sequence, while AnyAsync() stops at the first item or the first item that satisfies a condition.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1828", + "properties": { + "category": "Performance", + "isEnabledByDefault": true, + "typeName": "CSharpDoNotUseCountWhenAnyCanBeUsedAnalyzer", + "languages": [ + "C#" + ] + } + }, "CA2010": { "id": "CA2010", "shortDescription": "Always consume the value returned by methods marked with PreserveSigAttribute", @@ -2003,6 +2017,36 @@ ] } }, + "CA1827": { + "id": "CA1827", + "shortDescription": "Do not use Count() or LongCount() when Any() can be used", + "fullDescription": "For non-empty collections, Count() and LongCount() enumerate the entire sequence, while Any() stops at the first item or the first item that satisfies a condition.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1827", + "properties": { + "category": "Performance", + "isEnabledByDefault": true, + "typeName": "BasicDoNotUseCountWhenAnyCanBeUsedAnalyzer", + "languages": [ + "Visual Basic" + ] + } + }, + "CA1828": { + "id": "CA1828", + "shortDescription": "Do not use CountAsync() or LongCountAsync() when AnyAsync() can be used", + "fullDescription": "For non-empty collections, CountAsync() and LongCountAsync() enumerate the entire sequence, while AnyAsync() stops at the first item or the first item that satisfies a condition.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1828", + "properties": { + "category": "Performance", + "isEnabledByDefault": true, + "typeName": "BasicDoNotUseCountWhenAnyCanBeUsedAnalyzer", + "languages": [ + "Visual Basic" + ] + } + }, "CA2010": { "id": "CA2010", "shortDescription": "Always consume the value returned by methods marked with PreserveSigAttribute", diff --git a/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs b/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs new file mode 100644 index 0000000000..5d28395be2 --- /dev/null +++ b/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs @@ -0,0 +1,112 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Operations; +using Xunit; +using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< + Microsoft.NetCore.Analyzers.Performance.UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer, + Microsoft.NetCore.CSharp.Analyzers.Performance.CSharpUsePropertyInsteadOfCountMethodWhenAvailableFixer>; +using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< + Microsoft.NetCore.Analyzers.Performance.UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer, + Microsoft.NetCore.VisualBasic.Analyzers.Performance.BasicUsePropertyInsteadOfCountMethodWhenAvailableFixer>; + +namespace Microsoft.NetCore.Analyzers.Performance.UnitTests +{ + public static partial class UsePropertyInsteadOfCountMethodWhenAvailableTests + { + [Theory] + [InlineData("string[]", nameof(Array.Length))] + [InlineData("System.Collections.Immutable.ImmutableArray", nameof(ImmutableArray.Length))] + [InlineData("System.Collections.Generic.List", nameof(List.Count))] + [InlineData("System.Collections.Generic.IList", nameof(IList.Count))] + [InlineData("System.Collections.Generic.ICollection", nameof(ICollection.Count))] + public static Task CSharp_Fixed(string type, string propertyName) + => VerifyCS.VerifyCodeFixAsync( + $@"using System; +using System.Linq; +public static class C +{{ + public static {type} GetData() => default; + public static int M() => GetData().Count(); +}} +", + VerifyCS.Diagnostic(UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer.RuleId) + .WithLocation(6, 30) + .WithArguments(propertyName), + $@"using System; +using System.Linq; +public static class C +{{ + public static {type} GetData() => default; + public static int M() => GetData().{propertyName}; +}} +"); + + [Theory] + [InlineData("string()", nameof(Array.Length))] + [InlineData("System.Collections.Immutable.ImmutableArray(Of Integer)", nameof(ImmutableArray.Length))] + public static Task Basic_Fixed(string type, string propertyName) + => VerifyVB.VerifyCodeFixAsync( + $@"Imports System +Imports System.Linq +Public Module M + Public Function GetData() As {type} + Return Nothing + End Function + Public Function F() As Integer + Return GetData().Count() + End Function +End Module +", + VerifyCS.Diagnostic(UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer.RuleId) + .WithLocation(8, 16) + .WithArguments(propertyName), + $@"Imports System +Imports System.Linq +Public Module M + Public Function GetData() As {type} + Return Nothing + End Function + Public Function F() As Integer + Return GetData().{propertyName} + End Function +End Module +"); + + [Theory] + [InlineData("System.Collections.Generic.IEnumerable")] + public static Task CSharp_NoDiagnostic(string type) + => VerifyCS.VerifyAnalyzerAsync( + $@"using System; +using System.Linq; +public static class C +{{ + public static {type} GetData() => default; + public static int M() => GetData().Count(); +}} +"); + + [Theory] + [InlineData("System.Collections.Generic.List(Of Integer)")] + [InlineData("System.Collections.Generic.IList(Of Integer)")] + [InlineData("System.Collections.Generic.ICollection(Of Integer)")] + [InlineData("System.Collections.Generic.IEnumerable(Of Integer)")] + public static Task Basic_NoDiagnostic(string type) + => VerifyVB.VerifyAnalyzerAsync( + $@"Imports System +Imports System.Linq +Public Module M + Public Function GetData() As {type} + Return Nothing + End Function + Public Function F() As Integer + Return GetData().Count() + End Function +End Module +"); + } +} diff --git a/src/Microsoft.NetCore.Analyzers/VisualBasic/Microsoft.NetCore.VisualBasic.Analyzers.vbproj b/src/Microsoft.NetCore.Analyzers/VisualBasic/Microsoft.NetCore.VisualBasic.Analyzers.vbproj index c1f83a2913..da939d48b3 100644 --- a/src/Microsoft.NetCore.Analyzers/VisualBasic/Microsoft.NetCore.VisualBasic.Analyzers.vbproj +++ b/src/Microsoft.NetCore.Analyzers/VisualBasic/Microsoft.NetCore.VisualBasic.Analyzers.vbproj @@ -9,7 +9,4 @@ - - - \ No newline at end of file diff --git a/src/Microsoft.NetCore.Analyzers/VisualBasic/Performance/BasicUsePropertyInsteadOfCountMethodWhenAvailable.Fixer.vb b/src/Microsoft.NetCore.Analyzers/VisualBasic/Performance/BasicUsePropertyInsteadOfCountMethodWhenAvailable.Fixer.vb new file mode 100644 index 0000000000..70f463bf5c --- /dev/null +++ b/src/Microsoft.NetCore.Analyzers/VisualBasic/Performance/BasicUsePropertyInsteadOfCountMethodWhenAvailable.Fixer.vb @@ -0,0 +1,42 @@ +' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +Imports System.Composition +Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.CodeFixes +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax +Imports Microsoft.NetCore.Analyzers.Performance + +Namespace Microsoft.NetCore.VisualBasic.Analyzers.Performance + + ''' + ''' CA1829: Use property instead of , when available. + ''' + + Public NotInheritable Class BasicUsePropertyInsteadOfCountMethodWhenAvailableFixer + Inherits UsePropertyInsteadOfCountMethodWhenAvailableFixer + + ''' + ''' Gets the expression from the specified where to replace the invocation of the + ''' method with a property invocation. + ''' + ''' The node to get a fixer for. + ''' The expression from the specified where to replace the invocation of the + ''' method with a property invocation + ''' if found; otherwise. + ''' + Protected Overrides Function GetExpression(node As SyntaxNode) As SyntaxNode + + Dim invocationExpression = TryCast(node, InvocationExpressionSyntax) + + If Not invocationExpression Is Nothing Then + + Return DirectCast(invocationExpression.Expression, MemberAccessExpressionSyntax).Expression + + End If + + Return Nothing + + End Function + End Class + +End Namespace From 65b2d795edcf1ce298a1411f9660db552f33b1ea Mon Sep 17 00:00:00 2001 From: paulomorgado <470455+paulomorgado@users.noreply.github.com> Date: Fri, 2 Aug 2019 00:05:54 +0100 Subject: [PATCH 02/11] fixed message --- .../Core/MicrosoftNetCoreAnalyzersResources.resx | 2 +- .../Core/xlf/MicrosoftNetCoreAnalyzersResources.cs.xlf | 4 ++-- .../Core/xlf/MicrosoftNetCoreAnalyzersResources.de.xlf | 4 ++-- .../Core/xlf/MicrosoftNetCoreAnalyzersResources.es.xlf | 4 ++-- .../Core/xlf/MicrosoftNetCoreAnalyzersResources.fr.xlf | 4 ++-- .../Core/xlf/MicrosoftNetCoreAnalyzersResources.it.xlf | 4 ++-- .../Core/xlf/MicrosoftNetCoreAnalyzersResources.ja.xlf | 4 ++-- .../Core/xlf/MicrosoftNetCoreAnalyzersResources.ko.xlf | 4 ++-- .../Core/xlf/MicrosoftNetCoreAnalyzersResources.pl.xlf | 4 ++-- .../Core/xlf/MicrosoftNetCoreAnalyzersResources.pt-BR.xlf | 4 ++-- .../Core/xlf/MicrosoftNetCoreAnalyzersResources.ru.xlf | 4 ++-- .../Core/xlf/MicrosoftNetCoreAnalyzersResources.tr.xlf | 4 ++-- .../Core/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hans.xlf | 4 ++-- .../Core/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hant.xlf | 4 ++-- 14 files changed, 27 insertions(+), 27 deletions(-) diff --git a/src/Microsoft.NetCore.Analyzers/Core/MicrosoftNetCoreAnalyzersResources.resx b/src/Microsoft.NetCore.Analyzers/Core/MicrosoftNetCoreAnalyzersResources.resx index c375a744d0..e3539c3241 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/MicrosoftNetCoreAnalyzersResources.resx +++ b/src/Microsoft.NetCore.Analyzers/Core/MicrosoftNetCoreAnalyzersResources.resx @@ -1138,7 +1138,7 @@ Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. - Use the {0} property instead of Enumerable.Count(). + Use the "{0}" property instead of Enumerable.Count(). Use property instead of Count() when available diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.cs.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.cs.xlf index c9da78a201..21115155d4 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.cs.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.cs.xlf @@ -1668,8 +1668,8 @@ - Use the {0} property instead of Enumerable.Count(). - Use the {0} property instead of Enumerable.Count(). + Use the "{0}" property instead of Enumerable.Count(). + Use the "{0}" property instead of Enumerable.Count(). diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.de.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.de.xlf index e58f50a9ea..6e7aa52fa8 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.de.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.de.xlf @@ -1668,8 +1668,8 @@ - Use the {0} property instead of Enumerable.Count(). - Use the {0} property instead of Enumerable.Count(). + Use the "{0}" property instead of Enumerable.Count(). + Use the "{0}" property instead of Enumerable.Count(). diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.es.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.es.xlf index 123574a9eb..912191cb9c 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.es.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.es.xlf @@ -1668,8 +1668,8 @@ - Use the {0} property instead of Enumerable.Count(). - Use the {0} property instead of Enumerable.Count(). + Use the "{0}" property instead of Enumerable.Count(). + Use the "{0}" property instead of Enumerable.Count(). diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.fr.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.fr.xlf index 230604fa65..b7c2cafbe9 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.fr.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.fr.xlf @@ -1668,8 +1668,8 @@ - Use the {0} property instead of Enumerable.Count(). - Use the {0} property instead of Enumerable.Count(). + Use the "{0}" property instead of Enumerable.Count(). + Use the "{0}" property instead of Enumerable.Count(). diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.it.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.it.xlf index ffe754ae7f..06690c9340 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.it.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.it.xlf @@ -1668,8 +1668,8 @@ - Use the {0} property instead of Enumerable.Count(). - Use the {0} property instead of Enumerable.Count(). + Use the "{0}" property instead of Enumerable.Count(). + Use the "{0}" property instead of Enumerable.Count(). diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ja.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ja.xlf index 7a7a4799d3..83e016b0be 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ja.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ja.xlf @@ -1668,8 +1668,8 @@ - Use the {0} property instead of Enumerable.Count(). - Use the {0} property instead of Enumerable.Count(). + Use the "{0}" property instead of Enumerable.Count(). + Use the "{0}" property instead of Enumerable.Count(). diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ko.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ko.xlf index e5c05420b9..06ad66b89e 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ko.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ko.xlf @@ -1668,8 +1668,8 @@ - Use the {0} property instead of Enumerable.Count(). - Use the {0} property instead of Enumerable.Count(). + Use the "{0}" property instead of Enumerable.Count(). + Use the "{0}" property instead of Enumerable.Count(). diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.pl.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.pl.xlf index 13ba185429..d9913b0d48 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.pl.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.pl.xlf @@ -1668,8 +1668,8 @@ - Use the {0} property instead of Enumerable.Count(). - Use the {0} property instead of Enumerable.Count(). + Use the "{0}" property instead of Enumerable.Count(). + Use the "{0}" property instead of Enumerable.Count(). diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.pt-BR.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.pt-BR.xlf index e245b646a1..6736e74753 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.pt-BR.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.pt-BR.xlf @@ -1668,8 +1668,8 @@ - Use the {0} property instead of Enumerable.Count(). - Use the {0} property instead of Enumerable.Count(). + Use the "{0}" property instead of Enumerable.Count(). + Use the "{0}" property instead of Enumerable.Count(). diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ru.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ru.xlf index f5579cc6d6..5ac9495984 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ru.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ru.xlf @@ -1668,8 +1668,8 @@ - Use the {0} property instead of Enumerable.Count(). - Use the {0} property instead of Enumerable.Count(). + Use the "{0}" property instead of Enumerable.Count(). + Use the "{0}" property instead of Enumerable.Count(). diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.tr.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.tr.xlf index a999191f74..c95e3582e4 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.tr.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.tr.xlf @@ -1668,8 +1668,8 @@ - Use the {0} property instead of Enumerable.Count(). - Use the {0} property instead of Enumerable.Count(). + Use the "{0}" property instead of Enumerable.Count(). + Use the "{0}" property instead of Enumerable.Count(). diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hans.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hans.xlf index 1fcd9df8c7..26d88362e7 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hans.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hans.xlf @@ -1668,8 +1668,8 @@ - Use the {0} property instead of Enumerable.Count(). - Use the {0} property instead of Enumerable.Count(). + Use the "{0}" property instead of Enumerable.Count(). + Use the "{0}" property instead of Enumerable.Count(). diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hant.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hant.xlf index e8f88cd422..501953fc5e 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hant.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hant.xlf @@ -1668,8 +1668,8 @@ - Use the {0} property instead of Enumerable.Count(). - Use the {0} property instead of Enumerable.Count(). + Use the "{0}" property instead of Enumerable.Count(). + Use the "{0}" property instead of Enumerable.Count(). From a179baaf7980d868aeeb5743482c44295114e7aa Mon Sep 17 00:00:00 2001 From: paulomorgado <470455+paulomorgado@users.noreply.github.com> Date: Mon, 5 Aug 2019 16:46:11 +0100 Subject: [PATCH 03/11] CA1829: Use property instead of Enumerable.Count{). --- .../Microsoft.CodeAnalysis.FxCopAnalyzers.md | 217 ++++++------ ...opertyInsteadOfCountMethodWhenAvailable.cs | 148 ++++++--- ...opertyInsteadOfCountMethodWhenAvailable.cs | 112 ------- ...yInsteadOfCountMethodWhenAvailableTests.cs | 312 ++++++++++++++++++ src/Utilities/Compiler/WellKnownTypes.cs | 5 + 5 files changed, 533 insertions(+), 261 deletions(-) delete mode 100644 src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs create mode 100644 src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailableTests.cs diff --git a/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.md b/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.md index 934a2a15e8..317243072b 100644 --- a/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.md +++ b/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.md @@ -88,112 +88,111 @@ Sr. No. | Rule ID | Title | Category | Enabled | CodeFix | Description | 85 | CA1826 | Do not use Enumerable methods on indexable collections. Instead use the collection directly | Performance | True | True | This collection is directly indexable. Going through LINQ here causes unnecessary allocations and CPU work. | 86 | [CA1827](https://docs.microsoft.com/visualstudio/code-quality/ca1827) | Do not use Count() or LongCount() when Any() can be used | Performance | True | True | For non-empty collections, Count() and LongCount() enumerate the entire sequence, while Any() stops at the first item or the first item that satisfies a condition. | 87 | [CA1828](https://docs.microsoft.com/visualstudio/code-quality/ca1828) | Do not use CountAsync() or LongCountAsync() when AnyAsync() can be used | Performance | True | True | For non-empty collections, CountAsync() and LongCountAsync() enumerate the entire sequence, while AnyAsync() stops at the first item or the first item that satisfies a condition. | -88 | [CA2000](https://docs.microsoft.com/visualstudio/code-quality/ca2000-dispose-objects-before-losing-scope) | Dispose objects before losing scope | Reliability | True | False | If a disposable object is not explicitly disposed before all references to it are out of scope, the object will be disposed at some indeterminate time when the garbage collector runs the finalizer of the object. Because an exceptional event might occur that will prevent the finalizer of the object from running, the object should be explicitly disposed instead. | -89 | [CA2002](https://docs.microsoft.com/visualstudio/code-quality/ca2002-do-not-lock-on-objects-with-weak-identity) | Do not lock on objects with weak identity | Reliability | True | False | An object is said to have a weak identity when it can be directly accessed across application domain boundaries. A thread that tries to acquire a lock on an object that has a weak identity can be blocked by a second thread in a different application domain that has a lock on the same object. | -90 | [CA2007](https://docs.microsoft.com/visualstudio/code-quality/ca2007-do-not-directly-await-task) | Consider calling ConfigureAwait on the awaited task | Reliability | True | True | When an asynchronous method awaits a Task directly, continuation occurs in the same thread that created the task. Consider calling Task.ConfigureAwait(Boolean) to signal your intention for continuation. Call ConfigureAwait(false) on the task to schedule continuations to the thread pool, thereby avoiding a deadlock on the UI thread. Passing false is a good option for app-independent libraries. Calling ConfigureAwait(true) on the task has the same behavior as not explicitly calling ConfigureAwait. By explicitly calling this method, you're letting readers know you intentionally want to perform the continuation on the original synchronization context. | -91 | CA2008 | Do not create tasks without passing a TaskScheduler | Reliability | True | True | Do not create tasks unless you are using one of the overloads that takes a TaskScheduler. The default is to schedule on TaskScheduler.Current, which would lead to deadlocks. Either use TaskScheduler.Default to schedule on the thread pool, or explicitly pass TaskScheduler.Current to make your intentions clear. | -92 | CA2009 | Do not call ToImmutableCollection on an ImmutableCollection value | Reliability | True | True | Do not call {0} on an {1} value | -93 | CA2010 | Always consume the value returned by methods marked with PreserveSigAttribute | Reliability | True | False | PreserveSigAttribute indicates that a method will return an HRESULT, rather than throwing an exception. Therefore, it is important to consume the HRESULT returned by the method, so that errors can be detected. Generally, this is done by calling Marshal.ThrowExceptionForHR. | -94 | [CA2100](https://docs.microsoft.com/visualstudio/code-quality/ca2100-review-sql-queries-for-security-vulnerabilities) | Review SQL queries for security vulnerabilities | Security | True | False | SQL queries that directly use user input can be vulnerable to SQL injection attacks. Review this SQL query for potential vulnerabilities, and consider using a parameterized SQL query. | -95 | [CA2101](https://docs.microsoft.com/visualstudio/code-quality/ca2101-specify-marshaling-for-p-invoke-string-arguments) | Specify marshaling for P/Invoke string arguments | Globalization | True | True | A platform invoke member allows partially trusted callers, has a string parameter, and does not explicitly marshal the string. This can cause a potential security vulnerability. | -96 | [CA2119](https://docs.microsoft.com/visualstudio/code-quality/ca2119-seal-methods-that-satisfy-private-interfaces) | Seal methods that satisfy private interfaces | Security | True | True | An inheritable public type provides an overridable method implementation of an internal (Friend in Visual Basic) interface. To fix a violation of this rule, prevent the method from being overridden outside the assembly. | -97 | [CA2153](https://docs.microsoft.com/visualstudio/code-quality/ca2153-avoid-handling-corrupted-state-exceptions) | Do Not Catch Corrupted State Exceptions | Security | True | False | Catching corrupted state exceptions could mask errors (such as access violations), resulting in inconsistent state of execution or making it easier for attackers to compromise system. Instead, catch and handle a more specific set of exception type(s) or re-throw the exception | -98 | [CA2200](https://docs.microsoft.com/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details) | Rethrow to preserve stack details. | Usage | True | False | Re-throwing caught exception changes stack information. | -99 | [CA2201](https://docs.microsoft.com/visualstudio/code-quality/ca2201-do-not-raise-reserved-exception-types) | Do not raise reserved exception types | Usage | False | False | An exception of type that is not sufficiently specific or reserved by the runtime should never be raised by user code. This makes the original error difficult to detect and debug. If this exception instance might be thrown, use a different exception type. | -100 | [CA2207](https://docs.microsoft.com/visualstudio/code-quality/ca2207-initialize-value-type-static-fields-inline) | Initialize value type static fields inline | Usage | True | True | A value type declares an explicit static constructor. To fix a violation of this rule, initialize all static data when it is declared and remove the static constructor. | -101 | [CA2208](https://docs.microsoft.com/visualstudio/code-quality/ca2208-instantiate-argument-exceptions-correctly) | Instantiate argument exceptions correctly | Usage | True | True | A call is made to the default (parameterless) constructor of an exception type that is or derives from ArgumentException, or an incorrect string argument is passed to a parameterized constructor of an exception type that is or derives from ArgumentException. | -102 | [CA2211](https://docs.microsoft.com/visualstudio/code-quality/ca2211-non-constant-fields-should-not-be-visible) | Non-constant fields should not be visible | Usage | True | False | Static fields that are neither constants nor read-only are not thread-safe. Access to such a field must be carefully controlled and requires advanced programming techniques to synchronize access to the class object. | -103 | [CA2213](https://docs.microsoft.com/visualstudio/code-quality/ca2213-disposable-fields-should-be-disposed) | Disposable fields should be disposed | Usage | True | False | A type that implements System.IDisposable declares fields that are of types that also implement IDisposable. The Dispose method of the field is not called by the Dispose method of the declaring type. To fix a violation of this rule, call Dispose on fields that are of types that implement IDisposable if you are responsible for allocating and releasing the unmanaged resources held by the field. | -104 | [CA2214](https://docs.microsoft.com/visualstudio/code-quality/ca2214-do-not-call-overridable-methods-in-constructors) | Do not call overridable methods in constructors | Usage | True | False | Virtual methods defined on the class should not be called from constructors. If a derived class has overridden the method, the derived class version will be called (before the derived class constructor is called). | -105 | [CA2216](https://docs.microsoft.com/visualstudio/code-quality/ca2216-disposable-types-should-declare-finalizer) | Disposable types should declare finalizer | Usage | True | True | A type that implements System.IDisposable and has fields that suggest the use of unmanaged resources does not implement a finalizer, as described by Object.Finalize. | -106 | [CA2217](https://docs.microsoft.com/visualstudio/code-quality/ca2217-do-not-mark-enums-with-flagsattribute) | Do not mark enums with FlagsAttribute | Usage | False | True | An externally visible enumeration is marked by using FlagsAttribute, and it has one or more values that are not powers of two or a combination of the other defined values on the enumeration. | -107 | [CA2218](https://docs.microsoft.com/visualstudio/code-quality/ca2218-override-gethashcode-on-overriding-equals) | Override GetHashCode on overriding Equals | Usage | True | True | GetHashCode returns a value, based on the current instance, that is suited for hashing algorithms and data structures such as a hash table. Two objects that are the same type and are equal must return the same hash code. | -108 | [CA2219](https://docs.microsoft.com/visualstudio/code-quality/ca2219-do-not-raise-exceptions-in-exception-clauses) | Do not raise exceptions in finally clauses | Usage | True | False | When an exception is raised in a finally clause, the new exception hides the active exception. This makes the original error difficult to detect and debug. | -109 | [CA2224](https://docs.microsoft.com/visualstudio/code-quality/ca2224-override-equals-on-overloading-operator-equals) | Override Equals on overloading operator equals | Usage | True | True | A public type implements the equality operator but does not override Object.Equals. | -110 | [CA2225](https://docs.microsoft.com/visualstudio/code-quality/ca2225-operator-overloads-have-named-alternates) | Operator overloads have named alternates | Usage | True | True | An operator overload was detected, and the expected named alternative method was not found. The named alternative member provides access to the same functionality as the operator and is provided for developers who program in languages that do not support overloaded operators. | -111 | [CA2226](https://docs.microsoft.com/visualstudio/code-quality/ca2226-operators-should-have-symmetrical-overloads) | Operators should have symmetrical overloads | Usage | True | True | A type implements the equality or inequality operator and does not implement the opposite operator. | -112 | [CA2227](https://docs.microsoft.com/visualstudio/code-quality/ca2227-collection-properties-should-be-read-only) | Collection properties should be read only | Usage | True | False | A writable collection property allows a user to replace the collection with a different collection. A read-only property stops the collection from being replaced but still allows the individual members to be set. | -113 | [CA2229](https://docs.microsoft.com/visualstudio/code-quality/ca2229-implement-serialization-constructors) | Implement serialization constructors | Usage | True | True | To fix a violation of this rule, implement the serialization constructor. For a sealed class, make the constructor private; otherwise, make it protected. | -114 | [CA2231](https://docs.microsoft.com/visualstudio/code-quality/ca2231-overload-operator-equals-on-overriding-valuetype-equals) | Overload operator equals on overriding value type Equals | Usage | True | True | In most programming languages there is no default implementation of the equality operator (==) for value types. If your programming language supports operator overloads, you should consider implementing the equality operator. Its behavior should be identical to that of Equals | -115 | [CA2234](https://docs.microsoft.com/visualstudio/code-quality/ca2234-pass-system-uri-objects-instead-of-strings) | Pass system uri objects instead of strings | Usage | True | False | A call is made to a method that has a string parameter whose name contains "uri", "URI", "urn", "URN", "url", or "URL". The declaring type of the method contains a corresponding method overload that has a System.Uri parameter. | -116 | [CA2235](https://docs.microsoft.com/visualstudio/code-quality/ca2235-mark-all-non-serializable-fields) | Mark all non-serializable fields | Usage | True | True | An instance field of a type that is not serializable is declared in a type that is serializable. | -117 | [CA2237](https://docs.microsoft.com/visualstudio/code-quality/ca2237-mark-iserializable-types-with-serializableattribute) | Mark ISerializable types with serializable | Usage | True | True | To be recognized by the common language runtime as serializable, types must be marked by using the SerializableAttribute attribute even when the type uses a custom serialization routine through implementation of the ISerializable interface. | -118 | [CA2241](https://docs.microsoft.com/visualstudio/code-quality/ca2241-provide-correct-arguments-to-formatting-methods) | Provide correct arguments to formatting methods | Usage | True | False | The format argument that is passed to System.String.Format does not contain a format item that corresponds to each object argument, or vice versa. | -119 | [CA2242](https://docs.microsoft.com/visualstudio/code-quality/ca2242-test-for-nan-correctly) | Test for NaN correctly | Usage | True | True | This expression tests a value against Single.Nan or Double.Nan. Use Single.IsNan(Single) or Double.IsNan(Double) to test the value. | -120 | [CA2243](https://docs.microsoft.com/visualstudio/code-quality/ca2243-attribute-string-literals-should-parse-correctly) | Attribute string literals should parse correctly | Usage | True | False | The string literal parameter of an attribute does not parse correctly for a URL, a GUID, or a version. | -121 | CA2244 | Do not duplicate indexed element initializations | Usage | True | False | Indexed elements in objects initializers must initialize unique elements. A duplicate index might overwrite a previous element initialization. | -122 | CA2245 | Do not assign a property to itself. | Usage | True | False | The property {0} should not be assigned to itself. | -123 | [CA2300](https://docs.microsoft.com/visualstudio/code-quality/ca2300-do-not-use-insecure-deserializer-binaryformatter) | Do not use insecure deserializer BinaryFormatter | Security | False | False | The method '{0}' is insecure when deserializing untrusted data. If you need to instead detect BinaryFormatter deserialization without a SerializationBinder set, then disable rule CA2300, and enable rules CA2301 and CA2302. | -124 | [CA2301](https://docs.microsoft.com/visualstudio/code-quality/ca2301-do-not-call-binaryformatter-deserialize-without-first-setting-binaryformatter-binder) | Do not call BinaryFormatter.Deserialize without first setting BinaryFormatter.Binder | Security | False | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | -125 | [CA2302](https://docs.microsoft.com/visualstudio/code-quality/ca2302-ensure-binaryformatter-binder-is-set-before-calling-binaryformatter-deserialize) | Ensure BinaryFormatter.Binder is set before calling BinaryFormatter.Deserialize | Security | False | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | -126 | [CA2305](https://docs.microsoft.com/visualstudio/code-quality/ca2305-do-not-use-insecure-deserializer-losformatter) | Do not use insecure deserializer LosFormatter | Security | False | False | The method '{0}' is insecure when deserializing untrusted data. | -127 | [CA2310](https://docs.microsoft.com/visualstudio/code-quality/ca2310-do-not-use-insecure-deserializer-netdatacontractserializer) | Do not use insecure deserializer NetDataContractSerializer | Security | False | False | The method '{0}' is insecure when deserializing untrusted data. If you need to instead detect NetDataContractSerializer deserialization without a SerializationBinder set, then disable rule CA2310, and enable rules CA2311 and CA2312. | -128 | [CA2311](https://docs.microsoft.com/visualstudio/code-quality/ca2311-do-not-deserialize-without-first-setting-netdatacontractserializer-binder) | Do not deserialize without first setting NetDataContractSerializer.Binder | Security | False | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | -129 | [CA2312](https://docs.microsoft.com/visualstudio/code-quality/ca2312-ensure-netdatacontractserializer-binder-is-set-before-deserializing) | Ensure NetDataContractSerializer.Binder is set before deserializing | Security | False | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | -130 | [CA2315](https://docs.microsoft.com/visualstudio/code-quality/ca2315-do-not-use-insecure-deserializer-objectstateformatter) | Do not use insecure deserializer ObjectStateFormatter | Security | False | False | The method '{0}' is insecure when deserializing untrusted data. | -131 | [CA2321](https://docs.microsoft.com/visualstudio/code-quality/ca2321) | Do not deserialize with JavaScriptSerializer using a SimpleTypeResolver | Security | False | False | The method '{0}' is insecure when deserializing untrusted data with a JavaScriptSerializer initialized with a SimpleTypeResolver. Initialize JavaScriptSerializer without a JavaScriptTypeResolver specified, or initialize with a JavaScriptTypeResolver that limits the types of objects in the deserialized object graph. | -132 | [CA2322](https://docs.microsoft.com/visualstudio/code-quality/ca2322) | Ensure JavaScriptSerializer is not initialized with SimpleTypeResolver before deserializing | Security | False | False | The method '{0}' is insecure when deserializing untrusted data with a JavaScriptSerializer initialized with a SimpleTypeResolver. Ensure that the JavaScriptSerializer is initialized without a JavaScriptTypeResolver specified, or initialized with a JavaScriptTypeResolver that limits the types of objects in the deserialized object graph. | -133 | [CA2326](https://docs.microsoft.com/visualstudio/code-quality/ca2326) | Do not use TypeNameHandling values other than None | Security | False | False | Deserializing JSON when using a TypeNameHandling value other than None can be insecure. If you need to instead detect Json.NET deserialization when a SerializationBinder isn't specified, then disable rule CA2326, and enable rules CA2327, CA2328, CA2329, and CA2330. | -134 | [CA2327](https://docs.microsoft.com/visualstudio/code-quality/ca2327) | Do not use insecure JsonSerializerSettings | Security | False | False | When deserializing untrusted input, allowing arbitrary types to be deserialized is insecure. When using JsonSerializerSettings, use TypeNameHandling.None, or for values other than None, restrict deserialized types with a SerializationBinder. | -135 | [CA2328](https://docs.microsoft.com/visualstudio/code-quality/ca2328) | Ensure that JsonSerializerSettings are secure | Security | False | False | When deserializing untrusted input, allowing arbitrary types to be deserialized is insecure. When using JsonSerializerSettings, ensure TypeNameHandling.None is specified, or for values other than None, ensure a SerializationBinder is specified to restrict deserialized types. | -136 | [CA2329](https://docs.microsoft.com/visualstudio/code-quality/ca2329) | Do not deserialize with JsonSerializer using an insecure configuration | Security | False | False | When deserializing untrusted input, allowing arbitrary types to be deserialized is insecure. When using deserializing JsonSerializer, use TypeNameHandling.None, or for values other than None, restrict deserialized types with a SerializationBinder. | -137 | [CA2330](https://docs.microsoft.com/visualstudio/code-quality/ca2330) | Ensure that JsonSerializer has a secure configuration when deserializing | Security | False | False | When deserializing untrusted input, allowing arbitrary types to be deserialized is insecure. When using deserializing JsonSerializer, use TypeNameHandling.None, or for values other than None, restrict deserialized types with a SerializationBinder. | -138 | [CA3001](https://docs.microsoft.com/visualstudio/code-quality/ca3001-review-code-for-sql-injection-vulnerabilities) | Review code for SQL injection vulnerabilities | Security | False | False | Potential SQL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -139 | [CA3002](https://docs.microsoft.com/visualstudio/code-quality/ca3002-review-code-for-xss-vulnerabilities) | Review code for XSS vulnerabilities | Security | False | False | Potential cross-site scripting (XSS) vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -140 | [CA3003](https://docs.microsoft.com/visualstudio/code-quality/ca3003-review-code-for-file-path-injection-vulnerabilities) | Review code for file path injection vulnerabilities | Security | False | False | Potential file path injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -141 | [CA3004](https://docs.microsoft.com/visualstudio/code-quality/ca3004-review-code-for-information-disclosure-vulnerabilities) | Review code for information disclosure vulnerabilities | Security | False | False | Potential information disclosure vulnerability was found where '{0}' in method '{1}' may contain unintended information from '{2}' in method '{3}'. | -142 | [CA3005](https://docs.microsoft.com/visualstudio/code-quality/ca3005-review-code-for-ldap-injection-vulnerabilities) | Review code for LDAP injection vulnerabilities | Security | False | False | Potential LDAP injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -143 | [CA3006](https://docs.microsoft.com/visualstudio/code-quality/ca3006-review-code-for-process-command-injection-vulnerabilities) | Review code for process command injection vulnerabilities | Security | False | False | Potential process command injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -144 | [CA3007](https://docs.microsoft.com/visualstudio/code-quality/ca3007-review-code-for-open-redirect-vulnerabilities) | Review code for open redirect vulnerabilities | Security | False | False | Potential open redirect vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -145 | [CA3008](https://docs.microsoft.com/visualstudio/code-quality/ca3008-review-code-for-xpath-injection-vulnerabilities) | Review code for XPath injection vulnerabilities | Security | False | False | Potential XPath injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -146 | [CA3009](https://docs.microsoft.com/visualstudio/code-quality/ca3009-review-code-for-xml-injection-vulnerabilities) | Review code for XML injection vulnerabilities | Security | False | False | Potential XML injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -147 | [CA3010](https://docs.microsoft.com/visualstudio/code-quality/ca3010-review-code-for-xaml-injection-vulnerabilities) | Review code for XAML injection vulnerabilities | Security | False | False | Potential XAML injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -148 | [CA3011](https://docs.microsoft.com/visualstudio/code-quality/ca3011-review-code-for-dll-injection-vulnerabilities) | Review code for DLL injection vulnerabilities | Security | False | False | Potential DLL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -149 | [CA3012](https://docs.microsoft.com/visualstudio/code-quality/ca3012-review-code-for-regex-injection-vulnerabilities) | Review code for regex injection vulnerabilities | Security | False | False | Potential regex injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -150 | CA3061 | Do Not Add Schema By URL | Security | True | False | This overload of XmlSchemaCollection.Add method internally enables DTD processing on the XML reader instance used, and uses UrlResolver for resolving external XML entities. The outcome is information disclosure. Content from file system or network shares for the machine processing the XML can be exposed to attacker. In addition, an attacker can use this as a DoS vector. | -151 | [CA3075](https://docs.microsoft.com/visualstudio/code-quality/ca3075-insecure-dtd-processing) | Insecure DTD processing in XML | Security | True | False | Using XmlTextReader.Load(), creating an insecure XmlReaderSettings instance when invoking XmlReader.Create(), setting the InnerXml property of the XmlDocument and enabling DTD processing using XmlUrlResolver insecurely can lead to information disclosure. Replace it with a call to the Load() method overload that takes an XmlReader instance, use XmlReader.Create() to accept XmlReaderSettings arguments or consider explicitly setting secure values. The DataViewSettingCollectionString property of DataViewManager should always be assigned from a trusted source, the DtdProcessing property should be set to false, and the XmlResolver property should be changed to XmlSecureResolver or null.  | -152 | [CA3076](https://docs.microsoft.com/visualstudio/code-quality/ca3076-insecure-xslt-script-execution) | Insecure XSLT script processing. | Security | True | False | Providing an insecure XsltSettings instance and an insecure XmlResolver instance to XslCompiledTransform.Load method is potentially unsafe as it allows processing script within XSL, which on an untrusted XSL input may lead to malicious code execution. Either replace the insecure XsltSettings argument with XsltSettings.Default or an instance that has disabled document function and script execution, or replace the XmlResolver argurment with null or an XmlSecureResolver instance. This message may be suppressed if the input is known to be from a trusted source and external resource resolution from locations that are not known in advance must be supported. | -153 | [CA3077](https://docs.microsoft.com/visualstudio/code-quality/ca3077-insecure-processing-in-api-design-xml-document-and-xml-text-reader) | Insecure Processing in API Design, XmlDocument and XmlTextReader | Security | True | False | Enabling DTD processing on all instances derived from XmlTextReader or  XmlDocument and using XmlUrlResolver for resolving external XML entities may lead to information disclosure. Ensure to set the XmlResolver property to null, create an instance of XmlSecureResolver when processing untrusted input, or use XmlReader.Create method with a secure XmlReaderSettings argument. Unless you need to enable it, ensure the DtdProcessing property is set to false.  | -154 | [CA3147](https://docs.microsoft.com/visualstudio/code-quality/ca3147-mark-verb-handlers-with-validateantiforgerytoken) | Mark Verb Handlers With Validate Antiforgery Token | Security | True | False | Missing ValidateAntiForgeryTokenAttribute on controller action {0}. | -155 | [CA5350](https://docs.microsoft.com/visualstudio/code-quality/ca5350-do-not-use-weak-cryptographic-algorithms) | Do Not Use Weak Cryptographic Algorithms | Security | True | False | Cryptographic algorithms degrade over time as attacks become for advances to attacker get access to more computation. Depending on the type and application of this cryptographic algorithm, further degradation of the cryptographic strength of it may allow attackers to read enciphered messages, tamper with enciphered  messages, forge digital signatures, tamper with hashed content, or otherwise compromise any cryptosystem based on this algorithm. Replace encryption uses with the AES algorithm (AES-256, AES-192 and AES-128 are acceptable) with a key length greater than or equal to 128 bits. Replace hashing uses with a hashing function in the SHA-2 family, such as SHA-2 512, SHA-2 384, or SHA-2 256. | -156 | [CA5351](https://docs.microsoft.com/visualstudio/code-quality/ca5351-do-not-use-broken-cryptographic-algorithms) | Do Not Use Broken Cryptographic Algorithms | Security | True | False | An attack making it computationally feasible to break this algorithm exists. This allows attackers to break the cryptographic guarantees it is designed to provide. Depending on the type and application of this cryptographic algorithm, this may allow attackers to read enciphered messages, tamper with enciphered  messages, forge digital signatures, tamper with hashed content, or otherwise compromise any cryptosystem based on this algorithm. Replace encryption uses with the AES algorithm (AES-256, AES-192 and AES-128 are acceptable) with a key length greater than or equal to 128 bits. Replace hashing uses with a hashing function in the SHA-2 family, such as SHA512, SHA384, or SHA256. Replace digital signature uses with RSA with a key length greater than or equal to 2048-bits, or ECDSA with a key length greater than or equal to 256 bits. | -157 | CA5358 | Do Not Use Unsafe Cipher Modes | Security | False | False | These modes are vulnerable to attacks. Use only approved modes (CBC, CTS). | -158 | CA5359 | Do Not Disable Certificate Validation | Security | True | False | A certificate can help authenticate the identity of the server. Clients should validate the server certificate to ensure requests are sent to the intended server. If the ServerCertificateValidationCallback always returns 'true', any certificate will pass validation. | -159 | CA5360 | Do Not Call Dangerous Methods In Deserialization | Security | True | False | Insecure Deserialization is a vulnerability which occurs when untrusted data is used to abuse the logic of an application, inflict a Denial-of-Service (DoS) attack, or even execute arbitrary code upon it being deserialized. It’s frequently possible for malicious users to abuse these deserialization features when the application is deserializing untrusted data which is under their control. Specifically, invoke dangerous methods in the process of deserialization. Successful insecure deserialization attacks could allow an attacker to carry out attacks such as DoS attacks, authentication bypasses, and remote code execution. | -160 | [CA5361](https://docs.microsoft.com/visualstudio/code-quality/ca5361) | Do Not Disable SChannel Use of Strong Crypto | Security | True | False | Starting with the .NET Framework 4.6, the System.Net.ServicePointManager and System.Net.Security.SslStream classes are recommeded to use new protocols. The old ones have protocol weaknesses and are not supported. Setting Switch.System.Net.DontEnableSchUseStrongCrypto with true will use the old weak crypto check and opt out of the protocol migration. | -161 | CA5362 | Do Not Refer Self In Serializable Class | Security | False | False | This can allow an attacker to DOS or exhaust the memory of the process. | -162 | CA5363 | Do Not Disable Request Validation | Security | True | False | Request validation is a feature in ASP.NET that examines HTTP requests and determines whether they contain potentially dangerous content. This check adds protection from markup or code in the URL query string, cookies, or posted form values that might have been added for malicious purposes. So, it is generally desirable and should be left enabled for defense in depth. | -163 | [CA5364](https://docs.microsoft.com/visualstudio/code-quality/ca5364) | Do Not Use Deprecated Security Protocols | Security | True | False | Using a deprecated security protocol rather than the system default is risky. | -164 | CA5365 | Do Not Disable HTTP Header Checking | Security | True | False | HTTP header checking enables encoding of the carriage return and newline characters, \r and \n, that are found in response headers. This encoding can help to avoid injection attacks that exploit an application that echoes untrusted data contained by the header. | -165 | CA5366 | Use XmlReader For DataSet Read Xml | Security | True | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | -166 | CA5367 | Do Not Serialize Types With Pointer Fields | Security | False | False | Pointers are not "type safe" in the sense that you cannot guarantee the correctness of the memory they point at. So, serializing types with pointer fields is dangerous, as it may allow an attacker to control the pointer. | -167 | CA5368 | Set ViewStateUserKey For Classes Derived From Page | Security | True | False | Setting the ViewStateUserKey property can help you prevent attacks on your application by allowing you to assign an identifier to the view-state variable for individual users so that they cannot use the variable to generate an attack. Otherwise, there will be cross-site request forgery vulnerabilities. | -168 | CA5369 | Use XmlReader For Deserialize | Security | True | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | -169 | CA5370 | Use XmlReader For Validating Reader | Security | True | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | -170 | CA5371 | Use XmlReader For Schema Read | Security | True | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | -171 | CA5372 | Use XmlReader For XPathDocument | Security | True | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | -172 | CA5373 | Do not use obsolete key derivation function | Security | True | False | Password-based key derivation should use PBKDF2 with SHA-2. Avoid using PasswordDeriveBytes since it generates a PBKDF1 key. Avoid using Rfc2898DeriveBytes.CryptDeriveKey since it doesn't use the iteration count or salt. | -173 | CA5374 | Do Not Use XslTransform | Security | True | False | Do not use XslTransform. It does not restrict potentially dangerous external references. | -174 | CA5375 | Do Not Use Account Shared Access Signature | Security | False | False | Shared Access Signatures(SAS) are a vital part of the security model for any application using Azure Storage, they should provide limited and safe permissions to your storage account to clients that don't have the account key. All of the operations available via a service SAS are also available via an account SAS, that is, account SAS is too powerful. So it is recommended to use Service SAS to delegate access more carefully. | -175 | CA5376 | Use SharedAccessProtocol HttpsOnly | Security | True | False | HTTPS encrypts network traffic. Use HttpsOnly, rather than HttpOrHttps, to ensure network traffic is always encrypted to help prevent disclosure of sensitive data. | -176 | CA5377 | Use Container Level Access Policy | Security | True | False | No access policy identifier is specified, making tokens non-revocable. | -177 | [CA5378](https://docs.microsoft.com/visualstudio/code-quality/ca5378) | Do not disable ServicePointManagerSecurityProtocols | Security | True | False | Do not set Switch.System.ServiceModel.DisableUsingServicePointManagerSecurityProtocols to true. Setting this switch limits Windows Communication Framework (WCF) to using Transport Layer Security (TLS) 1.0, which is insecure and obsolete. | -178 | CA5379 | Do Not Use Weak Key Derivation Function Algorithm | Security | True | False | Some implementations of the Rfc2898DeriveBytes class allow for a hash algorithm to be specified in a constructor parameter or overwritten in the HashAlgorithm property. If a hash algorithm is specified, then it should be SHA-256 or higher. | -179 | CA5380 | Do Not Add Certificates To Root Store | Security | True | False | By default, the Trusted Root Certification Authorities certificate store is configured with a set of public CAs that has met the requirements of the Microsoft Root Certificate Program. Since all trusted root CAs can issue certificates for any domain, an attacker can pick a weak or coercible CA that you install by yourself to target for an attack – and a single vulnerable, malicious or coercible CA undermines the security of the entire system. To make matters worse, these attacks can go unnoticed quite easily. | -180 | CA5381 | Ensure Certificates Are Not Added To Root Store | Security | True | False | By default, the Trusted Root Certification Authorities certificate store is configured with a set of public CAs that has met the requirements of the Microsoft Root Certificate Program. Since all trusted root CAs can issue certificates for any domain, an attacker can pick a weak or coercible CA that you install by yourself to target for an attack – and a single vulnerable, malicious or coercible CA undermines the security of the entire system. To make matters worse, these attacks can go unnoticed quite easily. | -181 | CA5382 | Use Secure Cookies In ASP.Net Core | Security | False | False | Applications available over HTTPS must use secure cookies. | -182 | CA5383 | Ensure Use Secure Cookies In ASP.Net Core | Security | False | False | Applications available over HTTPS must use secure cookies. | -183 | CA5384 | Do Not Use Digital Signature Algorithm (DSA) | Security | True | False | DSA is too weak to use. | -184 | CA5385 | Use Rivest–Shamir–Adleman (RSA) Algorithm With Sufficient Key Size | Security | True | False | Encryption algorithms are vulnerable to brute force attacks when too small a key size is used. | -185 | [CA5386](https://docs.microsoft.com/visualstudio/code-quality/ca5386) | Avoid hardcoding SecurityProtocolType value | Security | False | False | Avoid hardcoding SecurityProtocolType {0}, and instead use SecurityProtocolType.SystemDefault to allow the operating system to choose the best Transport Layer Security protocol to use. | -186 | CA5387 | Do Not Use Weak Key Derivation Function With Insufficient Iteration Count | Security | False | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | -187 | CA5388 | Ensure Sufficient Iteration Count When Using Weak Key Derivation Function | Security | False | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | -188 | CA5389 | Do Not Add Archive Item's Path To The Target File System Path | Security | True | False | When extracting files from an archive and using the archive item's path, check if the path is safe. Archive path can be relative and can lead to file system access outside of the expected file system target path, leading to malicious config changes and remote code execution via lay-and-wait technique. | -189 | CA5390 | Do Not Hard Code Encryption Key | Security | True | False | SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. | -190 | CA5392 | Use DefaultDllImportSearchPaths attribute for P/Invokes | Security | True | False | By default, P/Invokes using DllImportAttribute probe a number of directories, including the current working directory for the library to load. This can be a security issue for certain applications, leading to DLL hijacking. | -191 | CA5393 | Do not use unsafe DllImportSearchPath value | Security | True | False | There could be a malicious DLL in the default DLL search directories. Or, depending on where your application is run from, there could be a malicious DLL in the application's directory. Use a DllImportSearchPath value that specifies an explicit search path instead. The DllImportSearchPath flags that this rule looks for can be configured in .editorconfig. | -192 | CA5394 | Do not use insecure randomness | Security | False | False | {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security | -193 | CA5396 | Set HttpOnly to true for HttpCookie | Security | False | False | As a defense in depth measure, ensure security sensitive HTTP cookies are marked as HttpOnly. This indicates web browsers should disallow scripts from accessing the cookies. Injected malicious scripts are a common way of stealing cookies. | -194 | [CA5397](https://docs.microsoft.com/visualstudio/code-quality/ca5397) | Do not use deprecated SslProtocols values | Security | True | False | Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. | -195 | [CA5398](https://docs.microsoft.com/visualstudio/code-quality/ca5398) | Avoid hardcoded SslProtocols values | Security | False | False | Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. | -196 | CA9999 | Analyzer version mismatch | Reliability | True | False | Analyzers in this package require a certain minimum version of Microsoft.CodeAnalysis to execute correctly. Refer to https://docs.microsoft.com/visualstudio/code-quality/install-fxcop-analyzers#fxcopanalyzers-package-versions to install the correct analyzer version. | +88 | [CA1829](https://docs.microsoft.com/visualstudio/code-quality/ca1829) | Use property instead of Count() when available | Performance | True | True | Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. | +89 | [CA2000](https://docs.microsoft.com/visualstudio/code-quality/ca2000-dispose-objects-before-losing-scope) | Dispose objects before losing scope | Reliability | True | False | If a disposable object is not explicitly disposed before all references to it are out of scope, the object will be disposed at some indeterminate time when the garbage collector runs the finalizer of the object. Because an exceptional event might occur that will prevent the finalizer of the object from running, the object should be explicitly disposed instead. | +90 | [CA2002](https://docs.microsoft.com/visualstudio/code-quality/ca2002-do-not-lock-on-objects-with-weak-identity) | Do not lock on objects with weak identity | Reliability | True | False | An object is said to have a weak identity when it can be directly accessed across application domain boundaries. A thread that tries to acquire a lock on an object that has a weak identity can be blocked by a second thread in a different application domain that has a lock on the same object. | +91 | [CA2007](https://docs.microsoft.com/visualstudio/code-quality/ca2007-do-not-directly-await-task) | Consider calling ConfigureAwait on the awaited task | Reliability | True | True | When an asynchronous method awaits a Task directly, continuation occurs in the same thread that created the task. Consider calling Task.ConfigureAwait(Boolean) to signal your intention for continuation. Call ConfigureAwait(false) on the task to schedule continuations to the thread pool, thereby avoiding a deadlock on the UI thread. Passing false is a good option for app-independent libraries. Calling ConfigureAwait(true) on the task has the same behavior as not explicitly calling ConfigureAwait. By explicitly calling this method, you're letting readers know you intentionally want to perform the continuation on the original synchronization context. | +92 | CA2008 | Do not create tasks without passing a TaskScheduler | Reliability | True | True | Do not create tasks unless you are using one of the overloads that takes a TaskScheduler. The default is to schedule on TaskScheduler.Current, which would lead to deadlocks. Either use TaskScheduler.Default to schedule on the thread pool, or explicitly pass TaskScheduler.Current to make your intentions clear. | +93 | CA2009 | Do not call ToImmutableCollection on an ImmutableCollection value | Reliability | True | True | Do not call {0} on an {1} value | +94 | CA2010 | Always consume the value returned by methods marked with PreserveSigAttribute | Reliability | True | False | PreserveSigAttribute indicates that a method will return an HRESULT, rather than throwing an exception. Therefore, it is important to consume the HRESULT returned by the method, so that errors can be detected. Generally, this is done by calling Marshal.ThrowExceptionForHR. | +95 | [CA2100](https://docs.microsoft.com/visualstudio/code-quality/ca2100-review-sql-queries-for-security-vulnerabilities) | Review SQL queries for security vulnerabilities | Security | True | False | SQL queries that directly use user input can be vulnerable to SQL injection attacks. Review this SQL query for potential vulnerabilities, and consider using a parameterized SQL query. | +96 | [CA2101](https://docs.microsoft.com/visualstudio/code-quality/ca2101-specify-marshaling-for-p-invoke-string-arguments) | Specify marshaling for P/Invoke string arguments | Globalization | True | True | A platform invoke member allows partially trusted callers, has a string parameter, and does not explicitly marshal the string. This can cause a potential security vulnerability. | +97 | [CA2119](https://docs.microsoft.com/visualstudio/code-quality/ca2119-seal-methods-that-satisfy-private-interfaces) | Seal methods that satisfy private interfaces | Security | True | True | An inheritable public type provides an overridable method implementation of an internal (Friend in Visual Basic) interface. To fix a violation of this rule, prevent the method from being overridden outside the assembly. | +98 | [CA2153](https://docs.microsoft.com/visualstudio/code-quality/ca2153-avoid-handling-corrupted-state-exceptions) | Do Not Catch Corrupted State Exceptions | Security | True | False | Catching corrupted state exceptions could mask errors (such as access violations), resulting in inconsistent state of execution or making it easier for attackers to compromise system. Instead, catch and handle a more specific set of exception type(s) or re-throw the exception | +99 | [CA2200](https://docs.microsoft.com/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details) | Rethrow to preserve stack details. | Usage | True | False | Re-throwing caught exception changes stack information. | +100 | [CA2201](https://docs.microsoft.com/visualstudio/code-quality/ca2201-do-not-raise-reserved-exception-types) | Do not raise reserved exception types | Usage | False | False | An exception of type that is not sufficiently specific or reserved by the runtime should never be raised by user code. This makes the original error difficult to detect and debug. If this exception instance might be thrown, use a different exception type. | +101 | [CA2207](https://docs.microsoft.com/visualstudio/code-quality/ca2207-initialize-value-type-static-fields-inline) | Initialize value type static fields inline | Usage | True | True | A value type declares an explicit static constructor. To fix a violation of this rule, initialize all static data when it is declared and remove the static constructor. | +102 | [CA2208](https://docs.microsoft.com/visualstudio/code-quality/ca2208-instantiate-argument-exceptions-correctly) | Instantiate argument exceptions correctly | Usage | True | True | A call is made to the default (parameterless) constructor of an exception type that is or derives from ArgumentException, or an incorrect string argument is passed to a parameterized constructor of an exception type that is or derives from ArgumentException. | +103 | [CA2211](https://docs.microsoft.com/visualstudio/code-quality/ca2211-non-constant-fields-should-not-be-visible) | Non-constant fields should not be visible | Usage | True | False | Static fields that are neither constants nor read-only are not thread-safe. Access to such a field must be carefully controlled and requires advanced programming techniques to synchronize access to the class object. | +104 | [CA2213](https://docs.microsoft.com/visualstudio/code-quality/ca2213-disposable-fields-should-be-disposed) | Disposable fields should be disposed | Usage | True | False | A type that implements System.IDisposable declares fields that are of types that also implement IDisposable. The Dispose method of the field is not called by the Dispose method of the declaring type. To fix a violation of this rule, call Dispose on fields that are of types that implement IDisposable if you are responsible for allocating and releasing the unmanaged resources held by the field. | +105 | [CA2214](https://docs.microsoft.com/visualstudio/code-quality/ca2214-do-not-call-overridable-methods-in-constructors) | Do not call overridable methods in constructors | Usage | True | False | Virtual methods defined on the class should not be called from constructors. If a derived class has overridden the method, the derived class version will be called (before the derived class constructor is called). | +106 | [CA2216](https://docs.microsoft.com/visualstudio/code-quality/ca2216-disposable-types-should-declare-finalizer) | Disposable types should declare finalizer | Usage | True | True | A type that implements System.IDisposable and has fields that suggest the use of unmanaged resources does not implement a finalizer, as described by Object.Finalize. | +107 | [CA2217](https://docs.microsoft.com/visualstudio/code-quality/ca2217-do-not-mark-enums-with-flagsattribute) | Do not mark enums with FlagsAttribute | Usage | False | True | An externally visible enumeration is marked by using FlagsAttribute, and it has one or more values that are not powers of two or a combination of the other defined values on the enumeration. | +108 | [CA2218](https://docs.microsoft.com/visualstudio/code-quality/ca2218-override-gethashcode-on-overriding-equals) | Override GetHashCode on overriding Equals | Usage | True | True | GetHashCode returns a value, based on the current instance, that is suited for hashing algorithms and data structures such as a hash table. Two objects that are the same type and are equal must return the same hash code. | +109 | [CA2219](https://docs.microsoft.com/visualstudio/code-quality/ca2219-do-not-raise-exceptions-in-exception-clauses) | Do not raise exceptions in finally clauses | Usage | True | False | When an exception is raised in a finally clause, the new exception hides the active exception. This makes the original error difficult to detect and debug. | +110 | [CA2224](https://docs.microsoft.com/visualstudio/code-quality/ca2224-override-equals-on-overloading-operator-equals) | Override Equals on overloading operator equals | Usage | True | True | A public type implements the equality operator but does not override Object.Equals. | +111 | [CA2225](https://docs.microsoft.com/visualstudio/code-quality/ca2225-operator-overloads-have-named-alternates) | Operator overloads have named alternates | Usage | True | True | An operator overload was detected, and the expected named alternative method was not found. The named alternative member provides access to the same functionality as the operator and is provided for developers who program in languages that do not support overloaded operators. | +112 | [CA2226](https://docs.microsoft.com/visualstudio/code-quality/ca2226-operators-should-have-symmetrical-overloads) | Operators should have symmetrical overloads | Usage | True | True | A type implements the equality or inequality operator and does not implement the opposite operator. | +113 | [CA2227](https://docs.microsoft.com/visualstudio/code-quality/ca2227-collection-properties-should-be-read-only) | Collection properties should be read only | Usage | True | False | A writable collection property allows a user to replace the collection with a different collection. A read-only property stops the collection from being replaced but still allows the individual members to be set. | +114 | [CA2229](https://docs.microsoft.com/visualstudio/code-quality/ca2229-implement-serialization-constructors) | Implement serialization constructors | Usage | True | True | To fix a violation of this rule, implement the serialization constructor. For a sealed class, make the constructor private; otherwise, make it protected. | +115 | [CA2231](https://docs.microsoft.com/visualstudio/code-quality/ca2231-overload-operator-equals-on-overriding-valuetype-equals) | Overload operator equals on overriding value type Equals | Usage | True | True | In most programming languages there is no default implementation of the equality operator (==) for value types. If your programming language supports operator overloads, you should consider implementing the equality operator. Its behavior should be identical to that of Equals | +116 | [CA2234](https://docs.microsoft.com/visualstudio/code-quality/ca2234-pass-system-uri-objects-instead-of-strings) | Pass system uri objects instead of strings | Usage | True | False | A call is made to a method that has a string parameter whose name contains "uri", "URI", "urn", "URN", "url", or "URL". The declaring type of the method contains a corresponding method overload that has a System.Uri parameter. | +117 | [CA2235](https://docs.microsoft.com/visualstudio/code-quality/ca2235-mark-all-non-serializable-fields) | Mark all non-serializable fields | Usage | True | True | An instance field of a type that is not serializable is declared in a type that is serializable. | +118 | [CA2237](https://docs.microsoft.com/visualstudio/code-quality/ca2237-mark-iserializable-types-with-serializableattribute) | Mark ISerializable types with serializable | Usage | True | True | To be recognized by the common language runtime as serializable, types must be marked by using the SerializableAttribute attribute even when the type uses a custom serialization routine through implementation of the ISerializable interface. | +119 | [CA2241](https://docs.microsoft.com/visualstudio/code-quality/ca2241-provide-correct-arguments-to-formatting-methods) | Provide correct arguments to formatting methods | Usage | True | False | The format argument that is passed to System.String.Format does not contain a format item that corresponds to each object argument, or vice versa. | +120 | [CA2242](https://docs.microsoft.com/visualstudio/code-quality/ca2242-test-for-nan-correctly) | Test for NaN correctly | Usage | True | True | This expression tests a value against Single.Nan or Double.Nan. Use Single.IsNan(Single) or Double.IsNan(Double) to test the value. | +121 | [CA2243](https://docs.microsoft.com/visualstudio/code-quality/ca2243-attribute-string-literals-should-parse-correctly) | Attribute string literals should parse correctly | Usage | True | False | The string literal parameter of an attribute does not parse correctly for a URL, a GUID, or a version. | +122 | CA2244 | Do not duplicate indexed element initializations | Usage | True | False | Indexed elements in objects initializers must initialize unique elements. A duplicate index might overwrite a previous element initialization. | +123 | CA2245 | Do not assign a property to itself. | Usage | True | False | The property {0} should not be assigned to itself. | +124 | [CA2300](https://docs.microsoft.com/visualstudio/code-quality/ca2300-do-not-use-insecure-deserializer-binaryformatter) | Do not use insecure deserializer BinaryFormatter | Security | False | False | The method '{0}' is insecure when deserializing untrusted data. If you need to instead detect BinaryFormatter deserialization without a SerializationBinder set, then disable rule CA2300, and enable rules CA2301 and CA2302. | +125 | [CA2301](https://docs.microsoft.com/visualstudio/code-quality/ca2301-do-not-call-binaryformatter-deserialize-without-first-setting-binaryformatter-binder) | Do not call BinaryFormatter.Deserialize without first setting BinaryFormatter.Binder | Security | False | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | +126 | [CA2302](https://docs.microsoft.com/visualstudio/code-quality/ca2302-ensure-binaryformatter-binder-is-set-before-calling-binaryformatter-deserialize) | Ensure BinaryFormatter.Binder is set before calling BinaryFormatter.Deserialize | Security | False | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | +127 | [CA2305](https://docs.microsoft.com/visualstudio/code-quality/ca2305-do-not-use-insecure-deserializer-losformatter) | Do not use insecure deserializer LosFormatter | Security | False | False | The method '{0}' is insecure when deserializing untrusted data. | +128 | [CA2310](https://docs.microsoft.com/visualstudio/code-quality/ca2310-do-not-use-insecure-deserializer-netdatacontractserializer) | Do not use insecure deserializer NetDataContractSerializer | Security | False | False | The method '{0}' is insecure when deserializing untrusted data. If you need to instead detect NetDataContractSerializer deserialization without a SerializationBinder set, then disable rule CA2310, and enable rules CA2311 and CA2312. | +129 | [CA2311](https://docs.microsoft.com/visualstudio/code-quality/ca2311-do-not-deserialize-without-first-setting-netdatacontractserializer-binder) | Do not deserialize without first setting NetDataContractSerializer.Binder | Security | False | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | +130 | [CA2312](https://docs.microsoft.com/visualstudio/code-quality/ca2312-ensure-netdatacontractserializer-binder-is-set-before-deserializing) | Ensure NetDataContractSerializer.Binder is set before deserializing | Security | False | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | +131 | [CA2315](https://docs.microsoft.com/visualstudio/code-quality/ca2315-do-not-use-insecure-deserializer-objectstateformatter) | Do not use insecure deserializer ObjectStateFormatter | Security | False | False | The method '{0}' is insecure when deserializing untrusted data. | +132 | [CA2321](https://docs.microsoft.com/visualstudio/code-quality/ca2321) | Do not deserialize with JavaScriptSerializer using a SimpleTypeResolver | Security | False | False | The method '{0}' is insecure when deserializing untrusted data with a JavaScriptSerializer initialized with a SimpleTypeResolver. Initialize JavaScriptSerializer without a JavaScriptTypeResolver specified, or initialize with a JavaScriptTypeResolver that limits the types of objects in the deserialized object graph. | +133 | [CA2322](https://docs.microsoft.com/visualstudio/code-quality/ca2322) | Ensure JavaScriptSerializer is not initialized with SimpleTypeResolver before deserializing | Security | False | False | The method '{0}' is insecure when deserializing untrusted data with a JavaScriptSerializer initialized with a SimpleTypeResolver. Ensure that the JavaScriptSerializer is initialized without a JavaScriptTypeResolver specified, or initialized with a JavaScriptTypeResolver that limits the types of objects in the deserialized object graph. | +134 | CA2326 | Do not use TypeNameHandling values other than None | Security | False | False | Deserializing JSON when using a TypeNameHandling value other than None can be insecure. If you need to instead detect Json.NET deserialization when a SerializationBinder isn't specified, then disable rule CA2326, and enable rules CA2327, CA2328, CA2329, and CA2330. | +135 | CA2327 | Do not use insecure JsonSerializerSettings | Security | False | False | When deserializing untrusted input, allowing arbitrary types to be deserialized is insecure. When using JsonSerializerSettings, use TypeNameHandling.None, or for values other than None, restrict deserialized types with a SerializationBinder. | +136 | CA2328 | Ensure that JsonSerializerSettings are secure | Security | False | False | When deserializing untrusted input, allowing arbitrary types to be deserialized is insecure. When using JsonSerializerSettings, ensure TypeNameHandling.None is specified, or for values other than None, ensure a SerializationBinder is specified to restrict deserialized types. | +137 | CA2329 | Do not deserialize with JsonSerializer using an insecure configuration | Security | False | False | When deserializing untrusted input, allowing arbitrary types to be deserialized is insecure. When using deserializing JsonSerializer, use TypeNameHandling.None, or for values other than None, restrict deserialized types with a SerializationBinder. | +138 | CA2330 | Ensure that JsonSerializer has a secure configuration when deserializing | Security | False | False | When deserializing untrusted input, allowing arbitrary types to be deserialized is insecure. When using deserializing JsonSerializer, use TypeNameHandling.None, or for values other than None, restrict deserialized types with a SerializationBinder. | +139 | [CA3001](https://docs.microsoft.com/visualstudio/code-quality/ca3001-review-code-for-sql-injection-vulnerabilities) | Review code for SQL injection vulnerabilities | Security | False | False | Potential SQL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +140 | [CA3002](https://docs.microsoft.com/visualstudio/code-quality/ca3002-review-code-for-xss-vulnerabilities) | Review code for XSS vulnerabilities | Security | False | False | Potential cross-site scripting (XSS) vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +141 | [CA3003](https://docs.microsoft.com/visualstudio/code-quality/ca3003-review-code-for-file-path-injection-vulnerabilities) | Review code for file path injection vulnerabilities | Security | False | False | Potential file path injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +142 | [CA3004](https://docs.microsoft.com/visualstudio/code-quality/ca3004-review-code-for-information-disclosure-vulnerabilities) | Review code for information disclosure vulnerabilities | Security | False | False | Potential information disclosure vulnerability was found where '{0}' in method '{1}' may contain unintended information from '{2}' in method '{3}'. | +143 | [CA3005](https://docs.microsoft.com/visualstudio/code-quality/ca3005-review-code-for-ldap-injection-vulnerabilities) | Review code for LDAP injection vulnerabilities | Security | False | False | Potential LDAP injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +144 | [CA3006](https://docs.microsoft.com/visualstudio/code-quality/ca3006-review-code-for-process-command-injection-vulnerabilities) | Review code for process command injection vulnerabilities | Security | False | False | Potential process command injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +145 | [CA3007](https://docs.microsoft.com/visualstudio/code-quality/ca3007-review-code-for-open-redirect-vulnerabilities) | Review code for open redirect vulnerabilities | Security | False | False | Potential open redirect vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +146 | [CA3008](https://docs.microsoft.com/visualstudio/code-quality/ca3008-review-code-for-xpath-injection-vulnerabilities) | Review code for XPath injection vulnerabilities | Security | False | False | Potential XPath injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +147 | [CA3009](https://docs.microsoft.com/visualstudio/code-quality/ca3009-review-code-for-xml-injection-vulnerabilities) | Review code for XML injection vulnerabilities | Security | False | False | Potential XML injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +148 | [CA3010](https://docs.microsoft.com/visualstudio/code-quality/ca3010-review-code-for-xaml-injection-vulnerabilities) | Review code for XAML injection vulnerabilities | Security | False | False | Potential XAML injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +149 | [CA3011](https://docs.microsoft.com/visualstudio/code-quality/ca3011-review-code-for-dll-injection-vulnerabilities) | Review code for DLL injection vulnerabilities | Security | False | False | Potential DLL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +150 | [CA3012](https://docs.microsoft.com/visualstudio/code-quality/ca3012-review-code-for-regex-injection-vulnerabilities) | Review code for regex injection vulnerabilities | Security | False | False | Potential regex injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +151 | CA3061 | Do Not Add Schema By URL | Security | True | False | This overload of XmlSchemaCollection.Add method internally enables DTD processing on the XML reader instance used, and uses UrlResolver for resolving external XML entities. The outcome is information disclosure. Content from file system or network shares for the machine processing the XML can be exposed to attacker. In addition, an attacker can use this as a DoS vector. | +152 | [CA3075](https://docs.microsoft.com/visualstudio/code-quality/ca3075-insecure-dtd-processing) | Insecure DTD processing in XML | Security | True | False | Using XmlTextReader.Load(), creating an insecure XmlReaderSettings instance when invoking XmlReader.Create(), setting the InnerXml property of the XmlDocument and enabling DTD processing using XmlUrlResolver insecurely can lead to information disclosure. Replace it with a call to the Load() method overload that takes an XmlReader instance, use XmlReader.Create() to accept XmlReaderSettings arguments or consider explicitly setting secure values. The DataViewSettingCollectionString property of DataViewManager should always be assigned from a trusted source, the DtdProcessing property should be set to false, and the XmlResolver property should be changed to XmlSecureResolver or null.  | +153 | [CA3076](https://docs.microsoft.com/visualstudio/code-quality/ca3076-insecure-xslt-script-execution) | Insecure XSLT script processing. | Security | True | False | Providing an insecure XsltSettings instance and an insecure XmlResolver instance to XslCompiledTransform.Load method is potentially unsafe as it allows processing script within XSL, which on an untrusted XSL input may lead to malicious code execution. Either replace the insecure XsltSettings argument with XsltSettings.Default or an instance that has disabled document function and script execution, or replace the XmlResolver argurment with null or an XmlSecureResolver instance. This message may be suppressed if the input is known to be from a trusted source and external resource resolution from locations that are not known in advance must be supported. | +154 | [CA3077](https://docs.microsoft.com/visualstudio/code-quality/ca3077-insecure-processing-in-api-design-xml-document-and-xml-text-reader) | Insecure Processing in API Design, XmlDocument and XmlTextReader | Security | True | False | Enabling DTD processing on all instances derived from XmlTextReader or  XmlDocument and using XmlUrlResolver for resolving external XML entities may lead to information disclosure. Ensure to set the XmlResolver property to null, create an instance of XmlSecureResolver when processing untrusted input, or use XmlReader.Create method with a secure XmlReaderSettings argument. Unless you need to enable it, ensure the DtdProcessing property is set to false.  | +155 | [CA3147](https://docs.microsoft.com/visualstudio/code-quality/ca3147-mark-verb-handlers-with-validateantiforgerytoken) | Mark Verb Handlers With Validate Antiforgery Token | Security | True | False | Missing ValidateAntiForgeryTokenAttribute on controller action {0}. | +156 | [CA5350](https://docs.microsoft.com/visualstudio/code-quality/ca5350-do-not-use-weak-cryptographic-algorithms) | Do Not Use Weak Cryptographic Algorithms | Security | True | False | Cryptographic algorithms degrade over time as attacks become for advances to attacker get access to more computation. Depending on the type and application of this cryptographic algorithm, further degradation of the cryptographic strength of it may allow attackers to read enciphered messages, tamper with enciphered  messages, forge digital signatures, tamper with hashed content, or otherwise compromise any cryptosystem based on this algorithm. Replace encryption uses with the AES algorithm (AES-256, AES-192 and AES-128 are acceptable) with a key length greater than or equal to 128 bits. Replace hashing uses with a hashing function in the SHA-2 family, such as SHA-2 512, SHA-2 384, or SHA-2 256. | +157 | [CA5351](https://docs.microsoft.com/visualstudio/code-quality/ca5351-do-not-use-broken-cryptographic-algorithms) | Do Not Use Broken Cryptographic Algorithms | Security | True | False | An attack making it computationally feasible to break this algorithm exists. This allows attackers to break the cryptographic guarantees it is designed to provide. Depending on the type and application of this cryptographic algorithm, this may allow attackers to read enciphered messages, tamper with enciphered  messages, forge digital signatures, tamper with hashed content, or otherwise compromise any cryptosystem based on this algorithm. Replace encryption uses with the AES algorithm (AES-256, AES-192 and AES-128 are acceptable) with a key length greater than or equal to 128 bits. Replace hashing uses with a hashing function in the SHA-2 family, such as SHA512, SHA384, or SHA256. Replace digital signature uses with RSA with a key length greater than or equal to 2048-bits, or ECDSA with a key length greater than or equal to 256 bits. | +158 | CA5358 | Do Not Use Unsafe Cipher Modes | Security | False | False | These modes are vulnerable to attacks. Use only approved modes (CBC, CTS). | +159 | CA5359 | Do Not Disable Certificate Validation | Security | True | False | A certificate can help authenticate the identity of the server. Clients should validate the server certificate to ensure requests are sent to the intended server. If the ServerCertificateValidationCallback always returns 'true', any certificate will pass validation. | +160 | CA5360 | Do Not Call Dangerous Methods In Deserialization | Security | True | False | Insecure Deserialization is a vulnerability which occurs when untrusted data is used to abuse the logic of an application, inflict a Denial-of-Service (DoS) attack, or even execute arbitrary code upon it being deserialized. It’s frequently possible for malicious users to abuse these deserialization features when the application is deserializing untrusted data which is under their control. Specifically, invoke dangerous methods in the process of deserialization. Successful insecure deserialization attacks could allow an attacker to carry out attacks such as DoS attacks, authentication bypasses, and remote code execution. | +161 | [CA5361](https://docs.microsoft.com/visualstudio/code-quality/ca5361) | Do Not Disable SChannel Use of Strong Crypto | Security | True | False | Starting with the .NET Framework 4.6, the System.Net.ServicePointManager and System.Net.Security.SslStream classes are recommeded to use new protocols. The old ones have protocol weaknesses and are not supported. Setting Switch.System.Net.DontEnableSchUseStrongCrypto with true will use the old weak crypto check and opt out of the protocol migration. | +162 | CA5362 | Do Not Refer Self In Serializable Class | Security | False | False | This can allow an attacker to DOS or exhaust the memory of the process. | +163 | CA5363 | Do Not Disable Request Validation | Security | True | False | Request validation is a feature in ASP.NET that examines HTTP requests and determines whether they contain potentially dangerous content. This check adds protection from markup or code in the URL query string, cookies, or posted form values that might have been added for malicious purposes. So, it is generally desirable and should be left enabled for defense in depth. | +164 | [CA5364](https://docs.microsoft.com/visualstudio/code-quality/ca5364) | Do Not Use Deprecated Security Protocols | Security | True | False | Using a deprecated security protocol rather than the system default is risky. | +165 | CA5365 | Do Not Disable HTTP Header Checking | Security | True | False | HTTP header checking enables encoding of the carriage return and newline characters, \r and \n, that are found in response headers. This encoding can help to avoid injection attacks that exploit an application that echoes untrusted data contained by the header. | +166 | CA5366 | Use XmlReader For DataSet Read Xml | Security | True | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | +167 | CA5367 | Do Not Serialize Types With Pointer Fields | Security | False | False | Pointers are not "type safe" in the sense that you cannot guarantee the correctness of the memory they point at. So, serializing types with pointer fields is dangerous, as it may allow an attacker to control the pointer. | +168 | CA5368 | Set ViewStateUserKey For Classes Derived From Page | Security | True | False | Setting the ViewStateUserKey property can help you prevent attacks on your application by allowing you to assign an identifier to the view-state variable for individual users so that they cannot use the variable to generate an attack. Otherwise, there will be cross-site request forgery vulnerabilities. | +169 | CA5369 | Use XmlReader For Deserialize | Security | True | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | +170 | CA5370 | Use XmlReader For Validating Reader | Security | True | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | +171 | CA5371 | Use XmlReader For Schema Read | Security | True | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | +172 | CA5372 | Use XmlReader For XPathDocument | Security | True | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | +173 | CA5373 | Do not use obsolete key derivation function | Security | True | False | Password-based key derivation should use PBKDF2 with SHA-2. Avoid using PasswordDeriveBytes since it generates a PBKDF1 key. Avoid using Rfc2898DeriveBytes.CryptDeriveKey since it doesn't use the iteration count or salt. | +174 | CA5374 | Do Not Use XslTransform | Security | True | False | Do not use XslTransform. It does not restrict potentially dangerous external references. | +175 | CA5375 | Do Not Use Account Shared Access Signature | Security | False | False | Shared Access Signatures(SAS) are a vital part of the security model for any application using Azure Storage, they should provide limited and safe permissions to your storage account to clients that don't have the account key. All of the operations available via a service SAS are also available via an account SAS, that is, account SAS is too powerful. So it is recommended to use Service SAS to delegate access more carefully. | +176 | CA5376 | Use SharedAccessProtocol HttpsOnly | Security | True | False | HTTPS encrypts network traffic. Use HttpsOnly, rather than HttpOrHttps, to ensure network traffic is always encrypted to help prevent disclosure of sensitive data. | +177 | CA5377 | Use Container Level Access Policy | Security | True | False | No access policy identifier is specified, making tokens non-revocable. | +178 | [CA5378](https://docs.microsoft.com/visualstudio/code-quality/ca5378) | Do not disable ServicePointManagerSecurityProtocols | Security | True | False | Do not set Switch.System.ServiceModel.DisableUsingServicePointManagerSecurityProtocols to true. Setting this switch limits Windows Communication Framework (WCF) to using Transport Layer Security (TLS) 1.0, which is insecure and obsolete. | +179 | CA5379 | Do Not Use Weak Key Derivation Function Algorithm | Security | True | False | Some implementations of the Rfc2898DeriveBytes class allow for a hash algorithm to be specified in a constructor parameter or overwritten in the HashAlgorithm property. If a hash algorithm is specified, then it should be SHA-256 or higher. | +180 | CA5380 | Do Not Add Certificates To Root Store | Security | True | False | By default, the Trusted Root Certification Authorities certificate store is configured with a set of public CAs that has met the requirements of the Microsoft Root Certificate Program. Since all trusted root CAs can issue certificates for any domain, an attacker can pick a weak or coercible CA that you install by yourself to target for an attack – and a single vulnerable, malicious or coercible CA undermines the security of the entire system. To make matters worse, these attacks can go unnoticed quite easily. | +181 | CA5381 | Ensure Certificates Are Not Added To Root Store | Security | True | False | By default, the Trusted Root Certification Authorities certificate store is configured with a set of public CAs that has met the requirements of the Microsoft Root Certificate Program. Since all trusted root CAs can issue certificates for any domain, an attacker can pick a weak or coercible CA that you install by yourself to target for an attack – and a single vulnerable, malicious or coercible CA undermines the security of the entire system. To make matters worse, these attacks can go unnoticed quite easily. | +182 | CA5382 | Use Secure Cookies In ASP.Net Core | Security | False | False | Applications available over HTTPS must use secure cookies. | +183 | CA5383 | Ensure Use Secure Cookies In ASP.Net Core | Security | False | False | Applications available over HTTPS must use secure cookies. | +184 | CA5384 | Do Not Use Digital Signature Algorithm (DSA) | Security | True | False | DSA is too weak to use. | +185 | CA5385 | Use Rivest–Shamir–Adleman (RSA) Algorithm With Sufficient Key Size | Security | True | False | Encryption algorithms are vulnerable to brute force attacks when too small a key size is used. | +186 | [CA5386](https://docs.microsoft.com/visualstudio/code-quality/ca5386) | Avoid hardcoding SecurityProtocolType value | Security | False | False | Avoid hardcoding SecurityProtocolType {0}, and instead use SecurityProtocolType.SystemDefault to allow the operating system to choose the best Transport Layer Security protocol to use. | +187 | CA5387 | Do Not Use Weak Key Derivation Function With Insufficient Iteration Count | Security | False | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | +188 | CA5388 | Ensure Sufficient Iteration Count When Using Weak Key Derivation Function | Security | False | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | +189 | CA5389 | Do Not Add Archive Item's Path To The Target File System Path | Security | True | False | When extracting files from an archive and using the archive item's path, check if the path is safe. Archive path can be relative and can lead to file system access outside of the expected file system target path, leading to malicious config changes and remote code execution via lay-and-wait technique. | +190 | CA5390 | Do Not Hard Code Encryption Key | Security | True | False | SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. | +191 | CA5392 | Use DefaultDllImportSearchPaths attribute for P/Invokes | Security | True | False | By default, P/Invokes using DllImportAttribute probe a number of directories, including the current working directory for the library to load. This can be a security issue for certain applications, leading to DLL hijacking. | +192 | CA5393 | Do not use unsafe DllImportSearchPath value | Security | True | False | There could be a malicious DLL in the default DLL search directories. Or, depending on where your application is run from, there could be a malicious DLL in the application's directory. Use a DllImportSearchPath value that specifies an explicit search path instead. The DllImportSearchPath flags that this rule looks for can be configured in .editorconfig. | +193 | CA5394 | Do not use insecure randomness | Security | False | False | {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security | +194 | CA5396 | Set HttpOnly to true for HttpCookie | Security | False | False | As a defense in depth measure, ensure security sensitive HTTP cookies are marked as HttpOnly. This indicates web browsers should disallow scripts from accessing the cookies. Injected malicious scripts are a common way of stealing cookies. | +195 | CA9999 | Analyzer version mismatch | Reliability | True | False | Analyzers in this package require a certain minimum version of Microsoft.CodeAnalysis to execute correctly. Refer to https://docs.microsoft.com/visualstudio/code-quality/install-fxcop-analyzers#fxcopanalyzers-package-versions to install the correct analyzer version. | diff --git a/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs b/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs index bdf10de7f4..3193067371 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; +using System.Collections; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; @@ -25,6 +26,8 @@ namespace Microsoft.NetCore.Analyzers.Performance public sealed class UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer : DiagnosticAnalyzer { internal const string RuleId = "CA1829"; + private const string CountPropertyName = "Count"; + private const string LengthPropertyName = "Length"; private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.UsePropertyInsteadOfCountMethodWhenAvailableTitle), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); private static readonly LocalizableString s_localizableMessage = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.UsePropertyInsteadOfCountMethodWhenAvailableMessage), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.UsePropertyInsteadOfCountMethodWhenAvailableDescription), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); @@ -40,8 +43,6 @@ public sealed class UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer : Diagn helpLinkUri: "https://docs.microsoft.com/visualstudio/code-quality/" + RuleId.ToLowerInvariant()); #pragma warning restore CA1308 // Normalize strings to uppercase - private static readonly ImmutableHashSet propertyNames = ImmutableHashSet.Create("Length", "Count"); - /// /// Returns a set of descriptors for the diagnostics that this analyzer is capable of producing. /// @@ -68,9 +69,16 @@ private static void OnCompilationStart(CompilationStartAnalysisContext context) { if (WellKnownTypes.Enumerable(context.Compilation) is INamedTypeSymbol enumerableType) { + var operationActionsContext = new UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer.OperationActionsContext( + context.Compilation, + enumerableType, + WellKnownTypes.ICollection(context.Compilation)?.GetMembers(CountPropertyName).OfType().SingleOrDefault(), + WellKnownTypes.GenericICollection(context.Compilation)?.GetMembers(CountPropertyName).OfType().SingleOrDefault(), + WellKnownTypes.ImmutableArray(context.Compilation)); + var operationActionsHandler = context.Compilation.Language == LanguageNames.CSharp - ? (OperationActionsHandler)new CSharpOperationActionsHandler(containingSymbol: enumerableType, rule: s_rule) - : (OperationActionsHandler)new BasicOperationActionsHandler(containingSymbol: enumerableType, rule: s_rule); + ? (OperationActionsHandler)new CSharpOperationActionsHandler(operationActionsContext) + : (OperationActionsHandler)new BasicOperationActionsHandler(operationActionsContext); context.RegisterOperationAction( operationActionsHandler.AnalyzeInvocationOperation, @@ -78,32 +86,48 @@ private static void OnCompilationStart(CompilationStartAnalysisContext context) } } + private sealed class OperationActionsContext + { + public OperationActionsContext(Compilation compilation, INamedTypeSymbol enumerableType, IPropertySymbol collectionCountProperty, IPropertySymbol collectionOfTCountProperty, INamedTypeSymbol immutableArrayType) + { + Compilation = compilation; + EnumerableType = enumerableType; + CollectionCountProperty = collectionCountProperty; + CollectionOfTCountProperty = collectionOfTCountProperty; + ImmutableArrayType = immutableArrayType; + } + + public Compilation Compilation { get; } + public INamedTypeSymbol EnumerableType { get; } + public IPropertySymbol CollectionCountProperty { get; } + public IPropertySymbol CollectionOfTCountProperty { get; } + public INamedTypeSymbol ImmutableArrayType { get; } + } + /// /// Handler for operaction actions. /// private abstract class OperationActionsHandler { - private readonly INamedTypeSymbol containingSymbol; - private readonly DiagnosticDescriptor rule; - - protected OperationActionsHandler(INamedTypeSymbol containingSymbol, DiagnosticDescriptor rule) + protected OperationActionsHandler(OperationActionsContext context) { - this.containingSymbol = containingSymbol; - this.rule = rule; + Context = context; } + public OperationActionsContext Context { get; } + internal void AnalyzeInvocationOperation(OperationAnalysisContext context) { var invocationOperation = (IInvocationOperation)context.Operation; - if (GetEnumerableCountInvocationTargetType(invocationOperation, this.containingSymbol) is ITypeSymbol invocationTarget && + if (GetEnumerableCountInvocationTargetType(invocationOperation) is ITypeSymbol invocationTarget && GetReplacementProperty(invocationTarget) is string propertyName) { var propertiesBuilder = ImmutableDictionary.CreateBuilder(); propertiesBuilder.Add("PropertyName", propertyName); var diagnostic = Diagnostic.Create( - this.rule, + s_rule, invocationOperation.Syntax.GetLocation(), propertiesBuilder.ToImmutable(), propertyName); @@ -112,35 +136,79 @@ internal void AnalyzeInvocationOperation(OperationAnalysisContext context) } } - protected abstract ITypeSymbol GetEnumerableCountInvocationTargetType(IInvocationOperation invocationOperation, INamedTypeSymbol containingSymbol); + protected abstract ITypeSymbol GetEnumerableCountInvocationTargetType(IInvocationOperation invocationOperation); - private static string GetReplacementProperty(ITypeSymbol invocationTarget) + private string GetReplacementProperty(ITypeSymbol invocationTarget) { if (invocationTarget.TypeKind == TypeKind.Array) { - return nameof(Array.Length); + return LengthPropertyName; } - foreach (var member in invocationTarget.GetMembers()) + if (invocationTarget.OriginalDefinition is ITypeSymbol originalDefinition && + originalDefinition.MetadataName.ToString().Equals(typeof(ImmutableArray<>).Name, StringComparison.Ordinal) && + originalDefinition.ContainingNamespace.ToString().Equals(typeof(ImmutableArray<>).Namespace, StringComparison.Ordinal)) { - if (member is IPropertySymbol property && propertyNames.Contains(property.Name)) - { - return property.Name; - } + return LengthPropertyName; + } + + if (invocationTarget.FindImplementationForInterfaceMember(this.Context.CollectionCountProperty) is IPropertySymbol countProperty && + !countProperty.ExplicitInterfaceImplementations.Any()) + { + return CountPropertyName; } - foreach (var type in invocationTarget.AllInterfaces) + if (findImplementationForCollectionOfTInterfaceCountProperty(invocationTarget)) { - foreach (var member in type.GetMembers()) + return CountPropertyName; + } + + return null; + + bool findImplementationForCollectionOfTInterfaceCountProperty(ITypeSymbol invocationTarget) + { + if (isCollectionOfTInterface(invocationTarget)) { - if (member is IPropertySymbol property && propertyNames.Contains(property.Name)) + return true; + } + + if (invocationTarget.TypeKind == TypeKind.Interface) + { + if (invocationTarget.GetMembers(CountPropertyName).OfType().Any()) { - return property.Name; + return false; + } + + foreach (var @interface in invocationTarget.AllInterfaces) + { + if (@interface.OriginalDefinition is INamedTypeSymbol originalInterfaceDefinition && + isCollectionOfTInterface(originalInterfaceDefinition)) + { + return true; + } + } + } + else + { + foreach (var @interface in invocationTarget.AllInterfaces) + { + if (@interface.OriginalDefinition is INamedTypeSymbol originalInterfaceDefinition && + isCollectionOfTInterface(originalInterfaceDefinition)) + { + if (invocationTarget.FindImplementationForInterfaceMember(@interface.GetMembers(CountPropertyName)[0]) is IPropertySymbol propertyImplementation && + !propertyImplementation.ExplicitInterfaceImplementations.Any()) + { + return true; + } + } } } - } - return null; + return false; + + bool isCollectionOfTInterface(ITypeSymbol type) + => type.OriginalDefinition?.Equals(this.Context.CollectionOfTCountProperty.ContainingSymbol) ?? false; + } } } @@ -151,23 +219,23 @@ private static string GetReplacementProperty(ITypeSymbol invocationTarget) /// private sealed class CSharpOperationActionsHandler : OperationActionsHandler { - internal CSharpOperationActionsHandler(INamedTypeSymbol containingSymbol, DiagnosticDescriptor rule) : base(containingSymbol, rule) + internal CSharpOperationActionsHandler(UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer.OperationActionsContext context) + : base(context) { } - protected override ITypeSymbol GetEnumerableCountInvocationTargetType(IInvocationOperation invocationOperation, INamedTypeSymbol containingSymbol) + protected override ITypeSymbol GetEnumerableCountInvocationTargetType(IInvocationOperation invocationOperation) { var method = invocationOperation.TargetMethod; if (invocationOperation.Arguments.Length == 1 && method.Name.Equals(nameof(Enumerable.Count), StringComparison.Ordinal) && - method.ContainingSymbol.Equals(containingSymbol)) + method.ContainingSymbol.Equals(this.Context.EnumerableType) && + ((INamedTypeSymbol)(method.Parameters[0].Type)).TypeArguments[0] is ITypeSymbol methodSourceItemType) { - var targetType = invocationOperation.Arguments[0].Value is IConversionOperation convertionOperation + return invocationOperation.Arguments[0].Value is IConversionOperation convertionOperation ? convertionOperation.Operand.Type : invocationOperation.Arguments[0].Value.Type; - - return targetType as ITypeSymbol; } return null; @@ -181,23 +249,23 @@ protected override ITypeSymbol GetEnumerableCountInvocationTargetType(IInvocatio /// private sealed class BasicOperationActionsHandler : OperationActionsHandler { - internal BasicOperationActionsHandler(INamedTypeSymbol containingSymbol, DiagnosticDescriptor rule) : base(containingSymbol, rule) + internal BasicOperationActionsHandler(UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer.OperationActionsContext context) + : base(context) { } - protected override ITypeSymbol GetEnumerableCountInvocationTargetType(IInvocationOperation invocationOperation, INamedTypeSymbol containingSymbol) + protected override ITypeSymbol GetEnumerableCountInvocationTargetType(IInvocationOperation invocationOperation) { var method = invocationOperation.TargetMethod; if (invocationOperation.Arguments.Length == 0 && method.Name.Equals(nameof(Enumerable.Count), StringComparison.Ordinal) && - method.ContainingSymbol.Equals(containingSymbol)) + method.ContainingSymbol.Equals(this.Context.EnumerableType) && + ((INamedTypeSymbol)(invocationOperation.Instance.Type)).TypeArguments[0] is ITypeSymbol methodSourceItemType) { - var targetType = invocationOperation.Instance is IConversionOperation convertionOperation - ? convertionOperation.Operand.Type - : invocationOperation.Instance.Type; - - return targetType as ITypeSymbol; + return invocationOperation.Instance is IConversionOperation convertionOperation + ? convertionOperation.Operand.Type + : invocationOperation.Instance.Type; } return null; diff --git a/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs b/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs deleted file mode 100644 index 5d28395be2..0000000000 --- a/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Threading.Tasks; -using Microsoft.CodeAnalysis.Operations; -using Xunit; -using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< - Microsoft.NetCore.Analyzers.Performance.UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer, - Microsoft.NetCore.CSharp.Analyzers.Performance.CSharpUsePropertyInsteadOfCountMethodWhenAvailableFixer>; -using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< - Microsoft.NetCore.Analyzers.Performance.UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer, - Microsoft.NetCore.VisualBasic.Analyzers.Performance.BasicUsePropertyInsteadOfCountMethodWhenAvailableFixer>; - -namespace Microsoft.NetCore.Analyzers.Performance.UnitTests -{ - public static partial class UsePropertyInsteadOfCountMethodWhenAvailableTests - { - [Theory] - [InlineData("string[]", nameof(Array.Length))] - [InlineData("System.Collections.Immutable.ImmutableArray", nameof(ImmutableArray.Length))] - [InlineData("System.Collections.Generic.List", nameof(List.Count))] - [InlineData("System.Collections.Generic.IList", nameof(IList.Count))] - [InlineData("System.Collections.Generic.ICollection", nameof(ICollection.Count))] - public static Task CSharp_Fixed(string type, string propertyName) - => VerifyCS.VerifyCodeFixAsync( - $@"using System; -using System.Linq; -public static class C -{{ - public static {type} GetData() => default; - public static int M() => GetData().Count(); -}} -", - VerifyCS.Diagnostic(UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer.RuleId) - .WithLocation(6, 30) - .WithArguments(propertyName), - $@"using System; -using System.Linq; -public static class C -{{ - public static {type} GetData() => default; - public static int M() => GetData().{propertyName}; -}} -"); - - [Theory] - [InlineData("string()", nameof(Array.Length))] - [InlineData("System.Collections.Immutable.ImmutableArray(Of Integer)", nameof(ImmutableArray.Length))] - public static Task Basic_Fixed(string type, string propertyName) - => VerifyVB.VerifyCodeFixAsync( - $@"Imports System -Imports System.Linq -Public Module M - Public Function GetData() As {type} - Return Nothing - End Function - Public Function F() As Integer - Return GetData().Count() - End Function -End Module -", - VerifyCS.Diagnostic(UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer.RuleId) - .WithLocation(8, 16) - .WithArguments(propertyName), - $@"Imports System -Imports System.Linq -Public Module M - Public Function GetData() As {type} - Return Nothing - End Function - Public Function F() As Integer - Return GetData().{propertyName} - End Function -End Module -"); - - [Theory] - [InlineData("System.Collections.Generic.IEnumerable")] - public static Task CSharp_NoDiagnostic(string type) - => VerifyCS.VerifyAnalyzerAsync( - $@"using System; -using System.Linq; -public static class C -{{ - public static {type} GetData() => default; - public static int M() => GetData().Count(); -}} -"); - - [Theory] - [InlineData("System.Collections.Generic.List(Of Integer)")] - [InlineData("System.Collections.Generic.IList(Of Integer)")] - [InlineData("System.Collections.Generic.ICollection(Of Integer)")] - [InlineData("System.Collections.Generic.IEnumerable(Of Integer)")] - public static Task Basic_NoDiagnostic(string type) - => VerifyVB.VerifyAnalyzerAsync( - $@"Imports System -Imports System.Linq -Public Module M - Public Function GetData() As {type} - Return Nothing - End Function - Public Function F() As Integer - Return GetData().Count() - End Function -End Module -"); - } -} diff --git a/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailableTests.cs b/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailableTests.cs new file mode 100644 index 0000000000..31524ed4f3 --- /dev/null +++ b/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailableTests.cs @@ -0,0 +1,312 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Dynamic; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Operations; +using Xunit; +using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< + Microsoft.NetCore.Analyzers.Performance.UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer, + Microsoft.NetCore.CSharp.Analyzers.Performance.CSharpUsePropertyInsteadOfCountMethodWhenAvailableFixer>; +using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< + Microsoft.NetCore.Analyzers.Performance.UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer, + Microsoft.NetCore.VisualBasic.Analyzers.Performance.BasicUsePropertyInsteadOfCountMethodWhenAvailableFixer>; + +namespace Microsoft.NetCore.Analyzers.Performance.UnitTests +{ + public static partial class UsePropertyInsteadOfCountMethodWhenAvailableTests + { + [Theory] + [InlineData("string[]", nameof(Array.Length))] + [InlineData("System.Collections.Immutable.ImmutableArray", nameof(ImmutableArray.Length))] + [InlineData("System.Collections.Generic.List", nameof(List.Count))] + [InlineData("System.Collections.Generic.IList", nameof(IList.Count))] + [InlineData("System.Collections.Generic.ICollection", nameof(ICollection.Count))] + public static Task CSharp_Fixed(string type, string propertyName) + => VerifyCS.VerifyCodeFixAsync( + $@"using System; +using System.Linq; +public static class C +{{ + public static {type} GetData() => default; + public static int M() => GetData().Count(); +}} +", + VerifyCS.Diagnostic(UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer.RuleId) + .WithLocation(6, 30) + .WithArguments(propertyName), + $@"using System; +using System.Linq; +public static class C +{{ + public static {type} GetData() => default; + public static int M() => GetData().{propertyName}; +}} +"); + + [Theory] + [InlineData("string()", nameof(Array.Length))] + [InlineData("System.Collections.Immutable.ImmutableArray(Of Integer)", nameof(ImmutableArray.Length))] + public static Task Basic_Fixed(string type, string propertyName) + => VerifyVB.VerifyCodeFixAsync( + $@"Imports System +Imports System.Linq +Public Module M + Public Function GetData() As {type} + Return Nothing + End Function + Public Function F() As Integer + Return GetData().Count() + End Function +End Module +", + VerifyCS.Diagnostic(UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer.RuleId) + .WithLocation(8, 16) + .WithArguments(propertyName), + $@"Imports System +Imports System.Linq +Public Module M + Public Function GetData() As {type} + Return Nothing + End Function + Public Function F() As Integer + Return GetData().{propertyName} + End Function +End Module +"); + + [Theory] + [InlineData("System.Collections.Generic.IEnumerable")] + public static Task CSharp_NoDiagnostic(string type) + => VerifyCS.VerifyAnalyzerAsync( + $@"using System; +using System.Linq; +public static class C +{{ + public static {type} GetData() => default; + public static int M() => GetData().Count(); +}} +"); + + [Theory] + [InlineData("System.Collections.Generic.List(Of Integer)")] + [InlineData("System.Collections.Generic.IList(Of Integer)")] + [InlineData("System.Collections.Generic.ICollection(Of Integer)")] + [InlineData("System.Collections.Generic.IEnumerable(Of Integer)")] + public static Task Basic_NoDiagnostic(string type) + => VerifyVB.VerifyAnalyzerAsync( + $@"Imports System +Imports System.Linq +Public Module M + Public Function GetData() As {type} + Return Nothing + End Function + Public Function F() As Integer + Return GetData().Count() + End Function +End Module +"); + + [Fact] + public static Task CSharp_ICollectionOfTImplementerWithImplicitCount_Fixed() + => VerifyCS.VerifyCodeFixAsync( + $@"using System; +using System.Linq; +public class T : global::System.Collections.Generic.ICollection +{{ + public int Count => throw new NotImplementedException(); + public bool IsReadOnly => throw new NotImplementedException(); + public void Add(string item) => throw new NotImplementedException(); + public void Clear() => throw new NotImplementedException(); + public bool Contains(string item) => throw new NotImplementedException(); + public void CopyTo(string[] array, int arrayIndex) => throw new NotImplementedException(); + public global::System.Collections.Generic.IEnumerator GetEnumerator() => throw new NotImplementedException(); + public bool Remove(string item) => throw new NotImplementedException(); + global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => throw new NotImplementedException(); +}} +public static class C +{{ + public static T GetData() => default; + public static int M() => GetData().Count(); +}} +", + VerifyCS.Diagnostic(UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer.RuleId) + .WithLocation(18, 30) + .WithArguments("Count"), + $@"using System; +using System.Linq; +public class T : global::System.Collections.Generic.ICollection +{{ + public int Count => throw new NotImplementedException(); + public bool IsReadOnly => throw new NotImplementedException(); + public void Add(string item) => throw new NotImplementedException(); + public void Clear() => throw new NotImplementedException(); + public bool Contains(string item) => throw new NotImplementedException(); + public void CopyTo(string[] array, int arrayIndex) => throw new NotImplementedException(); + public global::System.Collections.Generic.IEnumerator GetEnumerator() => throw new NotImplementedException(); + public bool Remove(string item) => throw new NotImplementedException(); + global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => throw new NotImplementedException(); +}} +public static class C +{{ + public static T GetData() => default; + public static int M() => GetData().Count; +}} +"); + + [Fact] + public static Task CSharp_ICollectionImplementerWithImplicitCount_Fixed() + => VerifyCS.VerifyCodeFixAsync( + $@"using System; +using System.Linq; +public class T : + global::System.Collections.Generic.IEnumerable, + global::System.Collections.ICollection +{{ + public int Count => throw new NotImplementedException(); + bool global::System.Collections.ICollection.IsSynchronized => throw new NotImplementedException(); + object global::System.Collections.ICollection.SyncRoot => throw new NotImplementedException(); + void global::System.Collections.ICollection.CopyTo(global::System.Array array, int arrayIndex) => throw new NotImplementedException(); + public global::System.Collections.Generic.IEnumerator GetEnumerator() => throw new NotImplementedException(); + global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => throw new NotImplementedException(); +}} +public static class C +{{ + public static T GetData() => default; + public static int M() => GetData().Count(); +}} +", + VerifyCS.Diagnostic(UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer.RuleId) + .WithLocation(17, 30) + .WithArguments("Count"), + $@"using System; +using System.Linq; +public class T : + global::System.Collections.Generic.IEnumerable, + global::System.Collections.ICollection +{{ + public int Count => throw new NotImplementedException(); + bool global::System.Collections.ICollection.IsSynchronized => throw new NotImplementedException(); + object global::System.Collections.ICollection.SyncRoot => throw new NotImplementedException(); + void global::System.Collections.ICollection.CopyTo(global::System.Array array, int arrayIndex) => throw new NotImplementedException(); + public global::System.Collections.Generic.IEnumerator GetEnumerator() => throw new NotImplementedException(); + global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => throw new NotImplementedException(); +}} +public static class C +{{ + public static T GetData() => default; + public static int M() => GetData().Count; +}} +"); + + [Fact] + public static Task CSharp_ICollectionOfTImplementerWithExplicitCount_NoDiagnostic() + => VerifyCS.VerifyAnalyzerAsync( + $@"using System; +using System.Linq; +public class T : global::System.Collections.Generic.ICollection +{{ + int global::System.Collections.Generic.ICollection.Count => throw new NotImplementedException(); + bool global::System.Collections.Generic.ICollection.IsReadOnly => throw new NotImplementedException(); + void global::System.Collections.Generic.ICollection.Add(string item) => throw new NotImplementedException(); + void global::System.Collections.Generic.ICollection.Clear() => throw new NotImplementedException(); + bool global::System.Collections.Generic.ICollection.Contains(string item) => throw new NotImplementedException(); + void global::System.Collections.Generic.ICollection.CopyTo(string[] array, int arrayIndex) => throw new NotImplementedException(); + public global::System.Collections.Generic.IEnumerator GetEnumerator() => throw new NotImplementedException(); + global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => throw new NotImplementedException(); + bool global::System.Collections.Generic.ICollection.Remove(string item) => throw new NotImplementedException(); +}} +public static class C +{{ + public static T GetData() => default; + public static int M() => GetData().Count(); +}} +"); + + [Fact] + public static Task CSharp_InterfaceShadowingICollectionOfT_NoDiagnostic() + => VerifyCS.VerifyAnalyzerAsync( + @"using System; +using System.Linq; +public interface I : global::System.Collections.Generic.ICollection +{ + new int Count { get; } +} +public static class C +{ + public static I GetData() => default; + public static int M() => GetData().Count(); +} +"); + + [Fact] + public static Task CSharp_InterfaceShadowingICollection_NoDiagnostic() + => VerifyCS.VerifyAnalyzerAsync( + @"using System; +using System.Linq; +public interface I : + global::System.Collections.Generic.IEnumerable, + global::System.Collections.ICollection +{ + new int Count { get; } +} +public static class C +{ + public static I GetData() => default; + public static int M() => GetData().Count(); +} +"); + + [Fact] + public static Task CSharp_ClassShadowingICollectionOfT_NoDiagnostic() + => VerifyCS.VerifyAnalyzerAsync( + $@"using System; +using System.Linq; +public class T : global::System.Collections.Generic.ICollection +{{ + public int Count => throw new NotImplementedException(); + int global::System.Collections.Generic.ICollection.Count => throw new NotImplementedException(); + bool global::System.Collections.Generic.ICollection.IsReadOnly => throw new NotImplementedException(); + void global::System.Collections.Generic.ICollection.Add(string item) => throw new NotImplementedException(); + void global::System.Collections.Generic.ICollection.Clear() => throw new NotImplementedException(); + bool global::System.Collections.Generic.ICollection.Contains(string item) => throw new NotImplementedException(); + void global::System.Collections.Generic.ICollection.CopyTo(string[] array, int arrayIndex) => throw new NotImplementedException(); + bool global::System.Collections.Generic.ICollection.Remove(string item) => throw new NotImplementedException(); + public global::System.Collections.Generic.IEnumerator GetEnumerator() => throw new NotImplementedException(); + global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => throw new NotImplementedException(); +}} +public static class C +{{ + public static T GetData() => default; + public static int M() => GetData().Count(); +}} +"); + + [Fact] + public static Task CSharp_ClassShadowingICollection_NoDiagnostic() + => VerifyCS.VerifyAnalyzerAsync( + $@"using System; +using System.Linq; +public class T : + global::System.Collections.Generic.IEnumerable, + global::System.Collections.ICollection +{{ + public int Count => throw new NotImplementedException(); + int global::System.Collections.ICollection.Count => throw new NotImplementedException(); + bool global::System.Collections.ICollection.IsSynchronized => throw new NotImplementedException(); + object global::System.Collections.ICollection.SyncRoot => throw new NotImplementedException(); + void global::System.Collections.ICollection.CopyTo(global::System.Array array, int arrayIndex) => throw new NotImplementedException(); + public global::System.Collections.Generic.IEnumerator GetEnumerator() => throw new NotImplementedException(); + global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator() => throw new NotImplementedException(); +}} +public static class C +{{ + public static T GetData() => default; + public static int M() => GetData().Count(); +}} +"); + } +} diff --git a/src/Utilities/Compiler/WellKnownTypes.cs b/src/Utilities/Compiler/WellKnownTypes.cs index 70baf6d32f..b2a59cb92c 100644 --- a/src/Utilities/Compiler/WellKnownTypes.cs +++ b/src/Utilities/Compiler/WellKnownTypes.cs @@ -528,6 +528,11 @@ public static INamedTypeSymbol HttpVerbs(Compilation compilation) return compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemWebMvcHttpVerbs); } + public static INamedTypeSymbol ImmutableArray(Compilation compilation) + { + return compilation.GetTypeByMetadataName(typeof(System.Collections.Immutable.ImmutableArray<>).FullName); + } + public static INamedTypeSymbol IImmutableDictionary(Compilation compilation) { return compilation.GetTypeByMetadataName(typeof(System.Collections.Immutable.IImmutableDictionary<,>).FullName); From 3a6e73555deaf378c52baab6fc075255783c2f65 Mon Sep 17 00:00:00 2001 From: paulomorgado <470455+paulomorgado@users.noreply.github.com> Date: Sat, 10 Aug 2019 21:53:49 +0100 Subject: [PATCH 04/11] workaround for ImmutableArray --- ...InsteadOfCountMethodWhenAvailable.Fixer.cs | 6 - ...opertyInsteadOfCountMethodWhenAvailable.cs | 181 ++++++++++-------- ...yInsteadOfCountMethodWhenAvailableTests.cs | 23 +++ 3 files changed, 127 insertions(+), 83 deletions(-) diff --git a/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs b/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs index dc795a00e2..d6ceeb8774 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs @@ -1,18 +1,12 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; -using System.Collections; -using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; -using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; -using Analyzer.Utilities; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; -using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; diff --git a/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs b/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs index 3193067371..8744b7f84e 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs @@ -1,16 +1,12 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using System.Collections; using System.Collections.Immutable; -using System.Diagnostics; using System.Linq; using Analyzer.Utilities; -using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; -using Microsoft.NetCore.Analyzers; namespace Microsoft.NetCore.Analyzers.Performance { @@ -71,10 +67,7 @@ private static void OnCompilationStart(CompilationStartAnalysisContext context) { var operationActionsContext = new UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer.OperationActionsContext( context.Compilation, - enumerableType, - WellKnownTypes.ICollection(context.Compilation)?.GetMembers(CountPropertyName).OfType().SingleOrDefault(), - WellKnownTypes.GenericICollection(context.Compilation)?.GetMembers(CountPropertyName).OfType().SingleOrDefault(), - WellKnownTypes.ImmutableArray(context.Compilation)); + enumerableType); var operationActionsHandler = context.Compilation.Language == LanguageNames.CSharp ? (OperationActionsHandler)new CSharpOperationActionsHandler(operationActionsContext) @@ -86,22 +79,114 @@ private static void OnCompilationStart(CompilationStartAnalysisContext context) } } + private void AnalyzeInvocationOperation(OperationAnalysisContext obj) + { + throw new NotImplementedException(); + } + private sealed class OperationActionsContext { - public OperationActionsContext(Compilation compilation, INamedTypeSymbol enumerableType, IPropertySymbol collectionCountProperty, IPropertySymbol collectionOfTCountProperty, INamedTypeSymbol immutableArrayType) + private /*readonly*/ Lazy _immutableArrayType; + private readonly Lazy _iCollectionCountProperty; + private readonly Lazy _iCollectionOfType; + private readonly Lazy _iCollectionOfTCountProperty; + + public OperationActionsContext(Compilation compilation, INamedTypeSymbol enumerableType) { Compilation = compilation; EnumerableType = enumerableType; - CollectionCountProperty = collectionCountProperty; - CollectionOfTCountProperty = collectionOfTCountProperty; - ImmutableArrayType = immutableArrayType; + _immutableArrayType = new Lazy(() => Compilation.GetTypeByMetadataName("System.Collections.Immutable.ImmutableArray`1"), true); + _iCollectionCountProperty = new Lazy(() => WellKnownTypes.ICollection(Compilation)?.GetMembers(CountPropertyName).OfType().Single(), true); + _iCollectionOfType = new Lazy(() => WellKnownTypes.GenericICollection(Compilation), true); + _iCollectionOfTCountProperty = new Lazy(() => ICollectionOfTType?.GetMembers(CountPropertyName).OfType().Single(), true); + } + + internal Compilation Compilation { get; } + + internal INamedTypeSymbol EnumerableType { get; } + + internal IPropertySymbol ICollectionCountProperty => _iCollectionCountProperty.Value; + + internal IPropertySymbol ICollectionOfTCountProperty => _iCollectionOfTCountProperty.Value; + + internal INamedTypeSymbol ICollectionOfTType => _iCollectionOfType.Value; + + internal INamedTypeSymbol ImmutableArrayType => _immutableArrayType.Value; + + internal bool IsImmutableArrayType(ITypeSymbol typeSymbol) + { + if (typeSymbol is INamedTypeSymbol namedTypeSymbol && namedTypeSymbol.ConstructedFrom is INamedTypeSymbol constructedFrom) + { + if (ImmutableArrayType is null && + constructedFrom.MetadataName.ToString().Equals("ImmutableArray`1", StringComparison.Ordinal) && + constructedFrom.ContainingNamespace.ToString().Equals("System.Collections.Immutable", StringComparison.Ordinal)) + { + _immutableArrayType = new Lazy(() => constructedFrom, true); + return true; + } + + return constructedFrom.Equals(ImmutableArrayType); + } + + return false; } - public Compilation Compilation { get; } - public INamedTypeSymbol EnumerableType { get; } - public IPropertySymbol CollectionCountProperty { get; } - public IPropertySymbol CollectionOfTCountProperty { get; } - public INamedTypeSymbol ImmutableArrayType { get; } + internal bool IsICollectionImplementation(ITypeSymbol invocationTarget) + => this.ICollectionCountProperty is object && + invocationTarget.FindImplementationForInterfaceMember(this.ICollectionCountProperty) is IPropertySymbol countProperty && + !countProperty.ExplicitInterfaceImplementations.Any(); + + internal bool IsICollectionOfTImplementation(ITypeSymbol invocationTarget) + { + if (ICollectionOfTType is null) + { + return false; + } + + if (isCollectionOfTInterface(invocationTarget)) + { + return true; + } + + if (invocationTarget.TypeKind == TypeKind.Interface) + { + if (invocationTarget.GetMembers(CountPropertyName).OfType().Any()) + { + return false; + } + + foreach (var @interface in invocationTarget.AllInterfaces) + { + if (@interface.OriginalDefinition is INamedTypeSymbol originalInterfaceDefinition && + isCollectionOfTInterface(originalInterfaceDefinition)) + { + return true; + } + } + } + else + { + foreach (var @interface in invocationTarget.AllInterfaces) + { + if (@interface.OriginalDefinition is INamedTypeSymbol originalInterfaceDefinition && + isCollectionOfTInterface(originalInterfaceDefinition)) + { + if (invocationTarget.FindImplementationForInterfaceMember(@interface.GetMembers(CountPropertyName)[0]) is IPropertySymbol propertyImplementation && + !propertyImplementation.ExplicitInterfaceImplementations.Any()) + { + return true; + } + } + } + } + + return false; + + bool isCollectionOfTInterface(ITypeSymbol type) + { + return type.OriginalDefinition?.Equals(this.ICollectionOfTType) ?? false; + } + } } /// @@ -140,75 +225,17 @@ internal void AnalyzeInvocationOperation(OperationAnalysisContext context) private string GetReplacementProperty(ITypeSymbol invocationTarget) { - if (invocationTarget.TypeKind == TypeKind.Array) - { - return LengthPropertyName; - } - - if (invocationTarget.OriginalDefinition is ITypeSymbol originalDefinition && - originalDefinition.MetadataName.ToString().Equals(typeof(ImmutableArray<>).Name, StringComparison.Ordinal) && - originalDefinition.ContainingNamespace.ToString().Equals(typeof(ImmutableArray<>).Namespace, StringComparison.Ordinal)) + if ((invocationTarget.TypeKind == TypeKind.Array) || Context.IsImmutableArrayType(invocationTarget)) { return LengthPropertyName; } - if (invocationTarget.FindImplementationForInterfaceMember(this.Context.CollectionCountProperty) is IPropertySymbol countProperty && - !countProperty.ExplicitInterfaceImplementations.Any()) - { - return CountPropertyName; - } - - if (findImplementationForCollectionOfTInterfaceCountProperty(invocationTarget)) + if (Context.IsICollectionImplementation(invocationTarget) || Context.IsICollectionOfTImplementation(invocationTarget)) { return CountPropertyName; } return null; - - bool findImplementationForCollectionOfTInterfaceCountProperty(ITypeSymbol invocationTarget) - { - if (isCollectionOfTInterface(invocationTarget)) - { - return true; - } - - if (invocationTarget.TypeKind == TypeKind.Interface) - { - if (invocationTarget.GetMembers(CountPropertyName).OfType().Any()) - { - return false; - } - - foreach (var @interface in invocationTarget.AllInterfaces) - { - if (@interface.OriginalDefinition is INamedTypeSymbol originalInterfaceDefinition && - isCollectionOfTInterface(originalInterfaceDefinition)) - { - return true; - } - } - } - else - { - foreach (var @interface in invocationTarget.AllInterfaces) - { - if (@interface.OriginalDefinition is INamedTypeSymbol originalInterfaceDefinition && - isCollectionOfTInterface(originalInterfaceDefinition)) - { - if (invocationTarget.FindImplementationForInterfaceMember(@interface.GetMembers(CountPropertyName)[0]) is IPropertySymbol propertyImplementation && - !propertyImplementation.ExplicitInterfaceImplementations.Any()) - { - return true; - } - } - } - } - - return false; - - bool isCollectionOfTInterface(ITypeSymbol type) - => type.OriginalDefinition?.Equals(this.Context.CollectionOfTCountProperty.ContainingSymbol) ?? false; - } } } diff --git a/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailableTests.cs b/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailableTests.cs index 31524ed4f3..32cb97aabf 100644 --- a/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailableTests.cs +++ b/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailableTests.cs @@ -7,6 +7,7 @@ using System.Dynamic; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Operations; +using Microsoft.NetCore.Analyzers.Runtime; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.NetCore.Analyzers.Performance.UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer, @@ -19,6 +20,28 @@ namespace Microsoft.NetCore.Analyzers.Performance.UnitTests { public static partial class UsePropertyInsteadOfCountMethodWhenAvailableTests { + [Fact] + public static Task CSharp_ImmutableArray_Tests() + => VerifyCS.VerifyCodeFixAsync( + $@"using System; +using System.Linq; +public static class C +{{ + public static System.Collections.Immutable.ImmutableArray GetData() => default; + public static int M() => {{|{UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer.RuleId}:GetData().Count()|}}; + public static int N() => {{|{UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer.RuleId}:GetData().Count()|}}; +}} +", + $@"using System; +using System.Linq; +public static class C +{{ + public static System.Collections.Immutable.ImmutableArray GetData() => default; + public static int M() => GetData().Length; + public static int N() => GetData().Length; +}} +"); + [Theory] [InlineData("string[]", nameof(Array.Length))] [InlineData("System.Collections.Immutable.ImmutableArray", nameof(ImmutableArray.Length))] From e9891de1f202921acec82f175cf8af7b5a925565 Mon Sep 17 00:00:00 2001 From: paulomorgado <470455+paulomorgado@users.noreply.github.com> Date: Tue, 13 Aug 2019 16:33:38 +0100 Subject: [PATCH 05/11] workaround for ImmutableArray --- ...opertyInsteadOfCountMethodWhenAvailable.cs | 56 +++++++------------ ...yInsteadOfCountMethodWhenAvailableTests.cs | 25 ++++++++- 2 files changed, 43 insertions(+), 38 deletions(-) diff --git a/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs b/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs index 8744b7f84e..b156ab8a71 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs @@ -79,57 +79,40 @@ private static void OnCompilationStart(CompilationStartAnalysisContext context) } } - private void AnalyzeInvocationOperation(OperationAnalysisContext obj) - { - throw new NotImplementedException(); - } - private sealed class OperationActionsContext { - private /*readonly*/ Lazy _immutableArrayType; + ////private /*readonly*/ Lazy _immutableArrayType; private readonly Lazy _iCollectionCountProperty; private readonly Lazy _iCollectionOfType; - private readonly Lazy _iCollectionOfTCountProperty; public OperationActionsContext(Compilation compilation, INamedTypeSymbol enumerableType) { Compilation = compilation; EnumerableType = enumerableType; - _immutableArrayType = new Lazy(() => Compilation.GetTypeByMetadataName("System.Collections.Immutable.ImmutableArray`1"), true); + ////_immutableArrayType = new Lazy(() => Compilation.GetTypeByMetadataName("System.Collections.Immutable.ImmutableArray`1"), true); _iCollectionCountProperty = new Lazy(() => WellKnownTypes.ICollection(Compilation)?.GetMembers(CountPropertyName).OfType().Single(), true); _iCollectionOfType = new Lazy(() => WellKnownTypes.GenericICollection(Compilation), true); - _iCollectionOfTCountProperty = new Lazy(() => ICollectionOfTType?.GetMembers(CountPropertyName).OfType().Single(), true); } internal Compilation Compilation { get; } - internal INamedTypeSymbol EnumerableType { get; } - - internal IPropertySymbol ICollectionCountProperty => _iCollectionCountProperty.Value; + private INamedTypeSymbol EnumerableType { get; } - internal IPropertySymbol ICollectionOfTCountProperty => _iCollectionOfTCountProperty.Value; + private IPropertySymbol ICollectionCountProperty => _iCollectionCountProperty.Value; - internal INamedTypeSymbol ICollectionOfTType => _iCollectionOfType.Value; + private INamedTypeSymbol ICollectionOfTType => _iCollectionOfType.Value; - internal INamedTypeSymbol ImmutableArrayType => _immutableArrayType.Value; + ////internal INamedTypeSymbol ImmutableArrayType => _immutableArrayType.Value; +#pragma warning disable CA1822 internal bool IsImmutableArrayType(ITypeSymbol typeSymbol) - { - if (typeSymbol is INamedTypeSymbol namedTypeSymbol && namedTypeSymbol.ConstructedFrom is INamedTypeSymbol constructedFrom) - { - if (ImmutableArrayType is null && - constructedFrom.MetadataName.ToString().Equals("ImmutableArray`1", StringComparison.Ordinal) && - constructedFrom.ContainingNamespace.ToString().Equals("System.Collections.Immutable", StringComparison.Ordinal)) - { - _immutableArrayType = new Lazy(() => constructedFrom, true); - return true; - } - - return constructedFrom.Equals(ImmutableArrayType); - } - - return false; - } + => typeSymbol is INamedTypeSymbol namedTypeSymbol && + namedTypeSymbol.MetadataName.Equals("ImmutableArray`1", StringComparison.Ordinal) && + namedTypeSymbol.ContainingNamespace.ToDisplayString().Equals("System.Collections.Immutable", StringComparison.Ordinal) && + namedTypeSymbol.ConstructedFrom is INamedTypeSymbol constructedFrom && + constructedFrom.MetadataName.Equals("ImmutableArray`1", StringComparison.Ordinal) && + constructedFrom.ContainingNamespace.ToDisplayString().Equals("System.Collections.Immutable", StringComparison.Ordinal); +#pragma warning restore CA1822 internal bool IsICollectionImplementation(ITypeSymbol invocationTarget) => this.ICollectionCountProperty is object && @@ -183,10 +166,11 @@ internal bool IsICollectionOfTImplementation(ITypeSymbol invocationTarget) return false; bool isCollectionOfTInterface(ITypeSymbol type) - { - return type.OriginalDefinition?.Equals(this.ICollectionOfTType) ?? false; - } + => this.ICollectionOfTType.Equals(type.OriginalDefinition); } + + internal bool IsEnumerableType(ISymbol symbol) + => this.EnumerableType.Equals(symbol); } /// @@ -257,7 +241,7 @@ protected override ITypeSymbol GetEnumerableCountInvocationTargetType(IInvocatio if (invocationOperation.Arguments.Length == 1 && method.Name.Equals(nameof(Enumerable.Count), StringComparison.Ordinal) && - method.ContainingSymbol.Equals(this.Context.EnumerableType) && + this.Context.IsEnumerableType(method.ContainingSymbol) && ((INamedTypeSymbol)(method.Parameters[0].Type)).TypeArguments[0] is ITypeSymbol methodSourceItemType) { return invocationOperation.Arguments[0].Value is IConversionOperation convertionOperation @@ -287,7 +271,7 @@ protected override ITypeSymbol GetEnumerableCountInvocationTargetType(IInvocatio if (invocationOperation.Arguments.Length == 0 && method.Name.Equals(nameof(Enumerable.Count), StringComparison.Ordinal) && - method.ContainingSymbol.Equals(this.Context.EnumerableType) && + this.Context.IsEnumerableType(method.ContainingSymbol) && ((INamedTypeSymbol)(invocationOperation.Instance.Type)).TypeArguments[0] is ITypeSymbol methodSourceItemType) { return invocationOperation.Instance is IConversionOperation convertionOperation diff --git a/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailableTests.cs b/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailableTests.cs index 32cb97aabf..137b47824a 100644 --- a/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailableTests.cs +++ b/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailableTests.cs @@ -5,7 +5,9 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Dynamic; +using System.Reflection; using System.Threading.Tasks; +using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Operations; using Microsoft.NetCore.Analyzers.Runtime; using Xunit; @@ -22,7 +24,12 @@ public static partial class UsePropertyInsteadOfCountMethodWhenAvailableTests { [Fact] public static Task CSharp_ImmutableArray_Tests() - => VerifyCS.VerifyCodeFixAsync( + => new VerifyCS.Test + { + TestState = + { + Sources= + { $@"using System; using System.Linq; public static class C @@ -32,6 +39,16 @@ public static class C public static int N() => {{|{UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer.RuleId}:GetData().Count()|}}; }} ", + }, + AdditionalReferences = + { + MetadataReference.CreateFromFile(typeof(ImmutableArray<>).GetTypeInfo().Assembly.Location, default(MetadataReferenceProperties), null), + }, + }, + FixedState = + { + Sources= + { $@"using System; using System.Linq; public static class C @@ -40,7 +57,11 @@ public static class C public static int M() => GetData().Length; public static int N() => GetData().Length; }} -"); +" , + }, + }, + IncludeImmutableCollectionsReference = false, + }.RunAsync(); [Theory] [InlineData("string[]", nameof(Array.Length))] From c9835b7eed806b3c74f553613bb6639ab2fb140b Mon Sep 17 00:00:00 2001 From: paulomorgado <470455+paulomorgado@users.noreply.github.com> Date: Fri, 16 Aug 2019 12:15:25 +0100 Subject: [PATCH 06/11] fixed for conditional invocations --- ...InsteadOfCountMethodWhenAvailable.Fixer.cs | 33 +++-- ...InsteadOfCountMethodWhenAvailable.Fixer.cs | 44 +++---- ...yInsteadOfCountMethodWhenAvailableTests.cs | 118 ++++++++++++++++-- ...InsteadOfCountMethodWhenAvailable.Fixer.vb | 36 ++++-- 4 files changed, 177 insertions(+), 54 deletions(-) diff --git a/src/Microsoft.NetCore.Analyzers/CSharp/Performance/CSharpUsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs b/src/Microsoft.NetCore.Analyzers/CSharp/Performance/CSharpUsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs index b414cb817b..ef11cc2bae 100644 --- a/src/Microsoft.NetCore.Analyzers/CSharp/Performance/CSharpUsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs +++ b/src/Microsoft.NetCore.Analyzers/CSharp/Performance/CSharpUsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs @@ -15,21 +15,34 @@ namespace Microsoft.NetCore.CSharp.Analyzers.Performance public sealed class CSharpUsePropertyInsteadOfCountMethodWhenAvailableFixer : UsePropertyInsteadOfCountMethodWhenAvailableFixer { /// - /// Gets the expression from the specified where to replace the invocation of the - /// method with a property invocation. + /// Gets the expression from the specified where to replace the invocation of the + /// method with a property invocation. /// - /// The node to get a fixer for. - /// The expression from the specified where to replace the invocation of the - /// method with a property invocation - /// if found; otherwise. - protected override SyntaxNode GetExpression(SyntaxNode node) + /// The invocation node to get a fixer for. + /// The member access node for the invocation node. + /// The name node for the invocation node. + /// if a and were found; + /// otherwise. + protected override bool TryGetExpression(SyntaxNode invocationNode, out SyntaxNode memberAccessNode, out SyntaxNode nameNode) { - if (node is InvocationExpressionSyntax invocationExpression) + if (invocationNode is InvocationExpressionSyntax invocationExpression) { - return ((MemberAccessExpressionSyntax)invocationExpression.Expression).Expression; + switch (invocationExpression.Expression) + { + case MemberAccessExpressionSyntax memberAccessExpression: + memberAccessNode = invocationExpression.Expression; + nameNode = memberAccessExpression.Name; + return true; + case MemberBindingExpressionSyntax memberBindingExpression: + memberAccessNode = invocationExpression.Expression; + nameNode = memberBindingExpression.Name; + return true; + } } - return null; + memberAccessNode = default; + nameNode = default; + return false; } } } diff --git a/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs b/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs index d6ceeb8774..0f499c42c6 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs @@ -51,40 +51,44 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) var node = root.FindNode(context.Span); var propertyName = context.Diagnostics[0].Properties["PropertyName"]; - if (node is object && propertyName is object && GetExpression(node) is SyntaxNode expression) + if (node is object && propertyName is object && TryGetExpression(node, out var expressionNode, out var nameNode)) { context.RegisterCodeFix( - new UsePropertyInsteadOfCountMethodWhenAvailableCodeAction(context.Document, node, expression, propertyName), + new UsePropertyInsteadOfCountMethodWhenAvailableCodeAction(context.Document, node, expressionNode, nameNode, propertyName), context.Diagnostics); } } /// - /// Gets the expression from the specified where to replace the invocation of the - /// method with a property invocation. + /// Gets the expression from the specified where to replace the invocation of the + /// method with a property invocation. /// - /// The node to get a fixer for. - /// The expression from the specified where to replace the invocation of the - /// method with a property invocation - /// if found; otherwise. - protected abstract SyntaxNode GetExpression(SyntaxNode node); + /// The invocation node to get a fixer for. + /// The member access node for the invocation node. + /// The name node for the invocation node. + /// if a and were found; + /// otherwise. + protected abstract bool TryGetExpression(SyntaxNode invocationNode, out SyntaxNode memberAccessNode, out SyntaxNode nameNode); private class UsePropertyInsteadOfCountMethodWhenAvailableCodeAction : CodeAction { private readonly Document document; - private readonly SyntaxNode node; - private readonly SyntaxNode expression; + private readonly SyntaxNode invocationNode; + private readonly SyntaxNode memberAccessNode; + private readonly SyntaxNode nameNode; private readonly string propertyName; public UsePropertyInsteadOfCountMethodWhenAvailableCodeAction( Document document, - SyntaxNode node, - SyntaxNode expression, + SyntaxNode invocationNode, + SyntaxNode memberAccessNode, + SyntaxNode nameNode, string propertyName) { this.document = document; - this.node = node; - this.expression = expression; + this.invocationNode = invocationNode; + this.memberAccessNode = memberAccessNode; + this.nameNode = nameNode; this.propertyName = propertyName; } @@ -92,17 +96,15 @@ private class UsePropertyInsteadOfCountMethodWhenAvailableCodeAction : CodeActio public override string EquivalenceKey { get; } = MicrosoftNetCoreAnalyzersResources.UsePropertyInsteadOfCountMethodWhenAvailableTitle; - protected override async Task GetChangedDocumentAsync(CancellationToken cancellationToken) + protected sealed override async Task GetChangedDocumentAsync(CancellationToken cancellationToken) { var editor = await DocumentEditor.CreateAsync(this.document, cancellationToken).ConfigureAwait(false); var generator = editor.Generator; - var replacementSyntax = generator.MemberAccessExpression(this.expression.WithoutTrailingTrivia(), this.propertyName); - - replacementSyntax = replacementSyntax + var replacementSyntax = generator.ReplaceNode(this.memberAccessNode, this.nameNode, generator.IdentifierName(propertyName)) .WithAdditionalAnnotations(Formatter.Annotation) - .WithTriviaFrom(this.node); + .WithTriviaFrom(this.invocationNode); - editor.ReplaceNode(this.node, replacementSyntax); + editor.ReplaceNode(this.invocationNode, replacementSyntax); return editor.GetChangedDocument(); } diff --git a/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailableTests.cs b/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailableTests.cs index 137b47824a..623f9a02dc 100644 --- a/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailableTests.cs +++ b/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailableTests.cs @@ -1,15 +1,9 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; -using System.Dynamic; -using System.Reflection; using System.Threading.Tasks; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Operations; -using Microsoft.NetCore.Analyzers.Runtime; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.NetCore.Analyzers.Performance.UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer, @@ -40,10 +34,6 @@ public static class C }} ", }, - AdditionalReferences = - { - MetadataReference.CreateFromFile(typeof(ImmutableArray<>).GetTypeInfo().Assembly.Location, default(MetadataReferenceProperties), null), - }, }, FixedState = { @@ -60,7 +50,54 @@ public static class C " , }, }, - IncludeImmutableCollectionsReference = false, + IncludeImmutableCollectionsReference = true, + }.RunAsync(); + + [Fact] + public static Task Basic_ImmutableArray_Tests() + => new VerifyVB.Test + { + TestState = + { + Sources= + { + $@"Imports System +Imports System.Linq +Public Module C + Public Function GetData() As System.Collections.Immutable.ImmutableArray(Of Integer) + Return Nothing + End Function + Public Function F() As Integer + Return {{|{UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer.RuleId}:GetData().Count()|}} + End Function + Public Function G() As Integer + Return {{|{UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer.RuleId}:GetData().Count()|}} + End Function +End Module +", + }, + }, + FixedState = + { + Sources= + { + $@"Imports System +Imports System.Linq +Public Module C + Public Function GetData() As System.Collections.Immutable.ImmutableArray(Of Integer) + Return Nothing + End Function + Public Function F() As Integer + Return GetData().Length + End Function + Public Function G() As Integer + Return GetData().Length + End Function +End Module +" , + }, + }, + IncludeImmutableCollectionsReference = true, }.RunAsync(); [Theory] @@ -89,6 +126,34 @@ public static class C public static {type} GetData() => default; public static int M() => GetData().{propertyName}; }} +"); + + [Theory] + [InlineData("string[]", nameof(Array.Length))] + [InlineData("System.Collections.Immutable.ImmutableArray?", nameof(ImmutableArray.Length))] + [InlineData("System.Collections.Generic.List", nameof(List.Count))] + [InlineData("System.Collections.Generic.IList", nameof(IList.Count))] + [InlineData("System.Collections.Generic.ICollection", nameof(ICollection.Count))] + public static Task CSharp_Conditional_Fixed(string type, string propertyName) + => VerifyCS.VerifyCodeFixAsync( + $@"using System; +using System.Linq; +public static class C +{{ + public static {type} GetData() => default; + public static int? M() => GetData()?.Count(); +}} +", + VerifyCS.Diagnostic(UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer.RuleId) + .WithLocation(6, 41) + .WithArguments(propertyName), + $@"using System; +using System.Linq; +public static class C +{{ + public static {type} GetData() => default; + public static int? M() => GetData()?.{propertyName}; +}} "); [Theory] @@ -120,6 +185,37 @@ End Function Return GetData().{propertyName} End Function End Module +"); + + [Theory] + [InlineData("string()", nameof(Array.Length))] + [InlineData("System.Collections.Immutable.ImmutableArray(Of Integer)?", nameof(ImmutableArray.Length))] + public static Task Basic_Conditional_Fixed(string type, string propertyName) + => VerifyVB.VerifyCodeFixAsync( + $@"Imports System +Imports System.Linq +Public Module M + Public Function GetData() As {type} + Return Nothing + End Function + Public Function F() As Integer + Return GetData()?.Count() + End Function +End Module +", + VerifyCS.Diagnostic(UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer.RuleId) + .WithLocation(8, 26) + .WithArguments(propertyName), + $@"Imports System +Imports System.Linq +Public Module M + Public Function GetData() As {type} + Return Nothing + End Function + Public Function F() As Integer + Return GetData()?.{propertyName} + End Function +End Module "); [Theory] diff --git a/src/Microsoft.NetCore.Analyzers/VisualBasic/Performance/BasicUsePropertyInsteadOfCountMethodWhenAvailable.Fixer.vb b/src/Microsoft.NetCore.Analyzers/VisualBasic/Performance/BasicUsePropertyInsteadOfCountMethodWhenAvailable.Fixer.vb index 70f463bf5c..53d29448a0 100644 --- a/src/Microsoft.NetCore.Analyzers/VisualBasic/Performance/BasicUsePropertyInsteadOfCountMethodWhenAvailable.Fixer.vb +++ b/src/Microsoft.NetCore.Analyzers/VisualBasic/Performance/BasicUsePropertyInsteadOfCountMethodWhenAvailable.Fixer.vb @@ -16,27 +16,39 @@ Namespace Microsoft.NetCore.VisualBasic.Analyzers.Performance Inherits UsePropertyInsteadOfCountMethodWhenAvailableFixer ''' - ''' Gets the expression from the specified where to replace the invocation of the - ''' method with a property invocation. + ''' Gets the expression from the specified where to replace the invocation of the + ''' method with a property invocation. ''' - ''' The node to get a fixer for. - ''' The expression from the specified where to replace the invocation of the - ''' method with a property invocation - ''' if found; otherwise. - ''' - Protected Overrides Function GetExpression(node As SyntaxNode) As SyntaxNode + ''' The invocation node to get a fixer for. + ''' The member access node for the invocation node. + ''' The name node for the invocation node. + ''' if a and were found; + ''' otherwise. + Protected Overrides Function TryGetExpression(invocationNode As SyntaxNode, ByRef memberAccessNode As SyntaxNode, ByRef nameNode As SyntaxNode) As Boolean - Dim invocationExpression = TryCast(node, InvocationExpressionSyntax) + Dim invocationExpression = TryCast(invocationNode, InvocationExpressionSyntax) - If Not invocationExpression Is Nothing Then + If invocationExpression Is Nothing Then - Return DirectCast(invocationExpression.Expression, MemberAccessExpressionSyntax).Expression + Return False End If - Return Nothing + Dim memberAccessExpression = TryCast(invocationExpression.Expression, MemberAccessExpressionSyntax) + + If Not memberAccessExpression Is Nothing Then + + memberAccessNode = memberAccessExpression + nameNode = memberAccessExpression.Name + + Return True + + End If + + Return False End Function + End Class End Namespace From 02b30d5e00fac4ae5c5c16ec8d4cff5ed58f3ce1 Mon Sep 17 00:00:00 2001 From: paulomorgado <470455+paulomorgado@users.noreply.github.com> Date: Mon, 19 Aug 2019 20:52:48 +0100 Subject: [PATCH 07/11] Added GetVisibleTypeByMetadataName extensions to Compilation. --- ...opertyInsteadOfCountMethodWhenAvailable.cs | 16 ++--- .../Compiler/Analyzer.Utilities.projitems | 1 + .../Extensions/CompilationExtensions.cs | 66 +++++++++++++++++++ src/Utilities/Compiler/WellKnownTypeNames.cs | 11 ++++ src/Utilities/Compiler/WellKnownTypes.cs | 13 ++-- 5 files changed, 91 insertions(+), 16 deletions(-) create mode 100644 src/Utilities/Compiler/Extensions/CompilationExtensions.cs diff --git a/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs b/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs index b156ab8a71..a65c4a07df 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs @@ -81,7 +81,7 @@ private static void OnCompilationStart(CompilationStartAnalysisContext context) private sealed class OperationActionsContext { - ////private /*readonly*/ Lazy _immutableArrayType; + private readonly Lazy _immutableArrayType; private readonly Lazy _iCollectionCountProperty; private readonly Lazy _iCollectionOfType; @@ -89,7 +89,7 @@ public OperationActionsContext(Compilation compilation, INamedTypeSymbol enumera { Compilation = compilation; EnumerableType = enumerableType; - ////_immutableArrayType = new Lazy(() => Compilation.GetTypeByMetadataName("System.Collections.Immutable.ImmutableArray`1"), true); + _immutableArrayType = new Lazy(() => WellKnownTypes.ImmutableArray(Compilation), true); _iCollectionCountProperty = new Lazy(() => WellKnownTypes.ICollection(Compilation)?.GetMembers(CountPropertyName).OfType().Single(), true); _iCollectionOfType = new Lazy(() => WellKnownTypes.GenericICollection(Compilation), true); } @@ -102,17 +102,13 @@ public OperationActionsContext(Compilation compilation, INamedTypeSymbol enumera private INamedTypeSymbol ICollectionOfTType => _iCollectionOfType.Value; - ////internal INamedTypeSymbol ImmutableArrayType => _immutableArrayType.Value; + internal INamedTypeSymbol ImmutableArrayType => _immutableArrayType.Value; -#pragma warning disable CA1822 internal bool IsImmutableArrayType(ITypeSymbol typeSymbol) - => typeSymbol is INamedTypeSymbol namedTypeSymbol && - namedTypeSymbol.MetadataName.Equals("ImmutableArray`1", StringComparison.Ordinal) && - namedTypeSymbol.ContainingNamespace.ToDisplayString().Equals("System.Collections.Immutable", StringComparison.Ordinal) && + => this.ImmutableArrayType is object && + typeSymbol is INamedTypeSymbol namedTypeSymbol && namedTypeSymbol.ConstructedFrom is INamedTypeSymbol constructedFrom && - constructedFrom.MetadataName.Equals("ImmutableArray`1", StringComparison.Ordinal) && - constructedFrom.ContainingNamespace.ToDisplayString().Equals("System.Collections.Immutable", StringComparison.Ordinal); -#pragma warning restore CA1822 + constructedFrom.Equals(this.ImmutableArrayType); internal bool IsICollectionImplementation(ITypeSymbol invocationTarget) => this.ICollectionCountProperty is object && diff --git a/src/Utilities/Compiler/Analyzer.Utilities.projitems b/src/Utilities/Compiler/Analyzer.Utilities.projitems index dd5a6ca73c..85b09aeea9 100644 --- a/src/Utilities/Compiler/Analyzer.Utilities.projitems +++ b/src/Utilities/Compiler/Analyzer.Utilities.projitems @@ -31,6 +31,7 @@ + diff --git a/src/Utilities/Compiler/Extensions/CompilationExtensions.cs b/src/Utilities/Compiler/Extensions/CompilationExtensions.cs new file mode 100644 index 0000000000..7caa94b1aa --- /dev/null +++ b/src/Utilities/Compiler/Extensions/CompilationExtensions.cs @@ -0,0 +1,66 @@ +using System.Linq; +using Microsoft.CodeAnalysis; + +namespace Analyzer.Utilities.Extensions +{ + /// + /// Provides extensions to . + /// + internal static class CompilationExtensions + { + /// + /// Gets the type within the compilation's assembly using its canonical CLR metadata name. If not found, gets the first public type from all referenced assemblies. If not found, gets the first type from all referenced assemblies. + /// + /// The compilation. + /// The fully qualified metadata name. + /// A if found; otherwise. + internal static INamedTypeSymbol GetVisibleTypeByMetadataName(this Compilation compilation, string fullyQualifiedMetadataName) + { + var typeSymbol = compilation.GetTypeByMetadataName(fullyQualifiedMetadataName); + if (typeSymbol is object) + { + return typeSymbol; + } + + var segments = fullyQualifiedMetadataName.Split('.'); + + var @namespace = compilation.GlobalNamespace; + + for (var s = 0; s < segments.Length - 1; s++) + { + @namespace = @namespace.GetMembers(segments[s]).OfType().SingleOrDefault(); + + if (@namespace is null) + { + return null; + } + } + + var metadataName = segments[segments.Length - 1]; + INamedTypeSymbol publicType = null; + INamedTypeSymbol anyType = null; + + foreach (var member in @namespace.GetMembers()) + { + if (member is INamedTypeSymbol type && type.MetadataName == metadataName) + { + if (type.ContainingAssembly.Equals(compilation.Assembly)) + { + return type; + } + else if (publicType is null && type.DeclaredAccessibility == Accessibility.Public) + { + publicType = type; + break; + } + else if (anyType is null) + { + anyType = type; + } + } + } + + return publicType ?? anyType; + } + } +} diff --git a/src/Utilities/Compiler/WellKnownTypeNames.cs b/src/Utilities/Compiler/WellKnownTypeNames.cs index 70b5432304..16588216e2 100644 --- a/src/Utilities/Compiler/WellKnownTypeNames.cs +++ b/src/Utilities/Compiler/WellKnownTypeNames.cs @@ -138,6 +138,17 @@ internal static class WellKnownTypeNames public const string SystemCollectionsIList = "System.Collections.IList"; public const string SystemCollectionsGenericIList1 = "System.Collections.Generic.IList`1"; public const string SystemCollectionsSpecializedNameValueCollection = "System.Collections.Specialized.NameValueCollection"; + public const string SystemCollectionsImmutableImmutableArray = "System.Collections.Immutable.ImmutableArray`1"; + public const string SystemCollectionsImmutableImmutableList = "System.Collections.Immutable.ImmutableList`1"; + public const string SystemCollectionsImmutableImmutableHashSet = "System.Collections.Immutable.ImmutableHashSet`1"; + public const string SystemCollectionsImmutableImmutableSortedSet = "System.Collections.Immutable.ImmutableSortedSet`1"; + public const string SystemCollectionsImmutableImmutableDictionary = "System.Collections.Immutable.ImmutableDictionary`2"; + public const string SystemCollectionsImmutableImmutableSortedDictionary = "System.Collections.Immutable.ImmutableSortedDictionary`2"; + public const string SystemCollectionsImmutableIImmutableDictionary = "System.Collections.Immutable.IImmutableDictionary`2"; + public const string SystemCollectionsImmutableIImmutableList = "System.Collections.Immutable.IImmutableList`1"; + public const string SystemCollectionsImmutableIImmutableQueue = "System.Collections.Immutable.IImmutableQueue`1"; + public const string SystemCollectionsImmutableIImmutableSet = "System.Collections.Immutable.IImmutableSet`1"; + public const string SystemCollectionsImmutableIImmutableStack = "System.Collections.Immutable.IImmutableStack`1"; public const string SystemRuntimeSerializationFormattersBinaryBinaryFormatter = "System.Runtime.Serialization.Formatters.Binary.BinaryFormatter"; public const string SystemWebUILosFormatter = "System.Web.UI.LosFormatter"; public const string SystemReflectionAssemblyFullName = "System.Reflection.Assembly"; diff --git a/src/Utilities/Compiler/WellKnownTypes.cs b/src/Utilities/Compiler/WellKnownTypes.cs index b2a59cb92c..9e7890b627 100644 --- a/src/Utilities/Compiler/WellKnownTypes.cs +++ b/src/Utilities/Compiler/WellKnownTypes.cs @@ -1,5 +1,6 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; namespace Analyzer.Utilities @@ -530,32 +531,32 @@ public static INamedTypeSymbol HttpVerbs(Compilation compilation) public static INamedTypeSymbol ImmutableArray(Compilation compilation) { - return compilation.GetTypeByMetadataName(typeof(System.Collections.Immutable.ImmutableArray<>).FullName); + return compilation.GetVisibleTypeByMetadataName(WellKnownTypeNames.SystemCollectionsImmutableImmutableArray); } public static INamedTypeSymbol IImmutableDictionary(Compilation compilation) { - return compilation.GetTypeByMetadataName(typeof(System.Collections.Immutable.IImmutableDictionary<,>).FullName); + return compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemCollectionsImmutableIImmutableDictionary); } public static INamedTypeSymbol IImmutableList(Compilation compilation) { - return compilation.GetTypeByMetadataName(typeof(System.Collections.Immutable.IImmutableList<>).FullName); + return compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemCollectionsImmutableIImmutableList); } public static INamedTypeSymbol IImmutableQueue(Compilation compilation) { - return compilation.GetTypeByMetadataName(typeof(System.Collections.Immutable.IImmutableQueue<>).FullName); + return compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemCollectionsImmutableIImmutableQueue); } public static INamedTypeSymbol IImmutableSet(Compilation compilation) { - return compilation.GetTypeByMetadataName(typeof(System.Collections.Immutable.IImmutableSet<>).FullName); + return compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemCollectionsImmutableIImmutableSet); } public static INamedTypeSymbol IImmutableStack(Compilation compilation) { - return compilation.GetTypeByMetadataName(typeof(System.Collections.Immutable.IImmutableStack<>).FullName); + return compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemCollectionsImmutableIImmutableStack); } public static INamedTypeSymbol SystemIOFile(Compilation compilation) From 623ca8c433bda9d8bc5cccc635c7386dd3b55087 Mon Sep 17 00:00:00 2001 From: paulomorgado <470455+paulomorgado@users.noreply.github.com> Date: Tue, 20 Aug 2019 00:40:15 +0100 Subject: [PATCH 08/11] added property names to diagnostic title. added diagnostic property key constant. split analyzers int language-specific analyzers. --- .../Microsoft.CodeAnalysis.FxCopAnalyzers.md | 16 +- ...icrosoft.CodeAnalysis.FxCopAnalyzers.sarif | 46 +++-- ...opertyInsteadOfCountMethodWhenAvailable.cs | 54 ++++++ .../MicrosoftNetCoreAnalyzersResources.resx | 2 +- ...InsteadOfCountMethodWhenAvailable.Fixer.cs | 6 +- ...opertyInsteadOfCountMethodWhenAvailable.cs | 86 ++------- .../MicrosoftNetCoreAnalyzersResources.cs.xlf | 4 +- .../MicrosoftNetCoreAnalyzersResources.de.xlf | 4 +- .../MicrosoftNetCoreAnalyzersResources.es.xlf | 4 +- .../MicrosoftNetCoreAnalyzersResources.fr.xlf | 4 +- .../MicrosoftNetCoreAnalyzersResources.it.xlf | 4 +- .../MicrosoftNetCoreAnalyzersResources.ja.xlf | 4 +- .../MicrosoftNetCoreAnalyzersResources.ko.xlf | 4 +- .../MicrosoftNetCoreAnalyzersResources.pl.xlf | 4 +- ...crosoftNetCoreAnalyzersResources.pt-BR.xlf | 4 +- .../MicrosoftNetCoreAnalyzersResources.ru.xlf | 4 +- .../MicrosoftNetCoreAnalyzersResources.tr.xlf | 4 +- ...osoftNetCoreAnalyzersResources.zh-Hans.xlf | 4 +- ...osoftNetCoreAnalyzersResources.zh-Hant.xlf | 4 +- .../Microsoft.NetCore.Analyzers.md | 175 +++++++++--------- .../Microsoft.NetCore.Analyzers.sarif | 46 +++-- ...yInsteadOfCountMethodWhenAvailableTests.cs | 4 +- ...opertyInsteadOfCountMethodWhenAvailable.vb | 57 ++++++ 23 files changed, 316 insertions(+), 228 deletions(-) create mode 100644 src/Microsoft.NetCore.Analyzers/CSharp/Performance/CSharpUsePropertyInsteadOfCountMethodWhenAvailable.cs create mode 100644 src/Microsoft.NetCore.Analyzers/VisualBasic/Performance/BasicUsePropertyInsteadOfCountMethodWhenAvailable.vb diff --git a/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.md b/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.md index 317243072b..1d3297e105 100644 --- a/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.md +++ b/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.md @@ -88,7 +88,7 @@ Sr. No. | Rule ID | Title | Category | Enabled | CodeFix | Description | 85 | CA1826 | Do not use Enumerable methods on indexable collections. Instead use the collection directly | Performance | True | True | This collection is directly indexable. Going through LINQ here causes unnecessary allocations and CPU work. | 86 | [CA1827](https://docs.microsoft.com/visualstudio/code-quality/ca1827) | Do not use Count() or LongCount() when Any() can be used | Performance | True | True | For non-empty collections, Count() and LongCount() enumerate the entire sequence, while Any() stops at the first item or the first item that satisfies a condition. | 87 | [CA1828](https://docs.microsoft.com/visualstudio/code-quality/ca1828) | Do not use CountAsync() or LongCountAsync() when AnyAsync() can be used | Performance | True | True | For non-empty collections, CountAsync() and LongCountAsync() enumerate the entire sequence, while AnyAsync() stops at the first item or the first item that satisfies a condition. | -88 | [CA1829](https://docs.microsoft.com/visualstudio/code-quality/ca1829) | Use property instead of Count() when available | Performance | True | True | Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. | +88 | [CA1829](https://docs.microsoft.com/visualstudio/code-quality/ca1829) | Use Length/Count property instead of Count() when available | Performance | True | True | Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. | 89 | [CA2000](https://docs.microsoft.com/visualstudio/code-quality/ca2000-dispose-objects-before-losing-scope) | Dispose objects before losing scope | Reliability | True | False | If a disposable object is not explicitly disposed before all references to it are out of scope, the object will be disposed at some indeterminate time when the garbage collector runs the finalizer of the object. Because an exceptional event might occur that will prevent the finalizer of the object from running, the object should be explicitly disposed instead. | 90 | [CA2002](https://docs.microsoft.com/visualstudio/code-quality/ca2002-do-not-lock-on-objects-with-weak-identity) | Do not lock on objects with weak identity | Reliability | True | False | An object is said to have a weak identity when it can be directly accessed across application domain boundaries. A thread that tries to acquire a lock on an object that has a weak identity can be blocked by a second thread in a different application domain that has a lock on the same object. | 91 | [CA2007](https://docs.microsoft.com/visualstudio/code-quality/ca2007-do-not-directly-await-task) | Consider calling ConfigureAwait on the awaited task | Reliability | True | True | When an asynchronous method awaits a Task directly, continuation occurs in the same thread that created the task. Consider calling Task.ConfigureAwait(Boolean) to signal your intention for continuation. Call ConfigureAwait(false) on the task to schedule continuations to the thread pool, thereby avoiding a deadlock on the UI thread. Passing false is a good option for app-independent libraries. Calling ConfigureAwait(true) on the task has the same behavior as not explicitly calling ConfigureAwait. By explicitly calling this method, you're letting readers know you intentionally want to perform the continuation on the original synchronization context. | @@ -134,11 +134,11 @@ Sr. No. | Rule ID | Title | Category | Enabled | CodeFix | Description | 131 | [CA2315](https://docs.microsoft.com/visualstudio/code-quality/ca2315-do-not-use-insecure-deserializer-objectstateformatter) | Do not use insecure deserializer ObjectStateFormatter | Security | False | False | The method '{0}' is insecure when deserializing untrusted data. | 132 | [CA2321](https://docs.microsoft.com/visualstudio/code-quality/ca2321) | Do not deserialize with JavaScriptSerializer using a SimpleTypeResolver | Security | False | False | The method '{0}' is insecure when deserializing untrusted data with a JavaScriptSerializer initialized with a SimpleTypeResolver. Initialize JavaScriptSerializer without a JavaScriptTypeResolver specified, or initialize with a JavaScriptTypeResolver that limits the types of objects in the deserialized object graph. | 133 | [CA2322](https://docs.microsoft.com/visualstudio/code-quality/ca2322) | Ensure JavaScriptSerializer is not initialized with SimpleTypeResolver before deserializing | Security | False | False | The method '{0}' is insecure when deserializing untrusted data with a JavaScriptSerializer initialized with a SimpleTypeResolver. Ensure that the JavaScriptSerializer is initialized without a JavaScriptTypeResolver specified, or initialized with a JavaScriptTypeResolver that limits the types of objects in the deserialized object graph. | -134 | CA2326 | Do not use TypeNameHandling values other than None | Security | False | False | Deserializing JSON when using a TypeNameHandling value other than None can be insecure. If you need to instead detect Json.NET deserialization when a SerializationBinder isn't specified, then disable rule CA2326, and enable rules CA2327, CA2328, CA2329, and CA2330. | -135 | CA2327 | Do not use insecure JsonSerializerSettings | Security | False | False | When deserializing untrusted input, allowing arbitrary types to be deserialized is insecure. When using JsonSerializerSettings, use TypeNameHandling.None, or for values other than None, restrict deserialized types with a SerializationBinder. | -136 | CA2328 | Ensure that JsonSerializerSettings are secure | Security | False | False | When deserializing untrusted input, allowing arbitrary types to be deserialized is insecure. When using JsonSerializerSettings, ensure TypeNameHandling.None is specified, or for values other than None, ensure a SerializationBinder is specified to restrict deserialized types. | -137 | CA2329 | Do not deserialize with JsonSerializer using an insecure configuration | Security | False | False | When deserializing untrusted input, allowing arbitrary types to be deserialized is insecure. When using deserializing JsonSerializer, use TypeNameHandling.None, or for values other than None, restrict deserialized types with a SerializationBinder. | -138 | CA2330 | Ensure that JsonSerializer has a secure configuration when deserializing | Security | False | False | When deserializing untrusted input, allowing arbitrary types to be deserialized is insecure. When using deserializing JsonSerializer, use TypeNameHandling.None, or for values other than None, restrict deserialized types with a SerializationBinder. | +134 | [CA2326](https://docs.microsoft.com/visualstudio/code-quality/ca2326) | Do not use TypeNameHandling values other than None | Security | False | False | Deserializing JSON when using a TypeNameHandling value other than None can be insecure. If you need to instead detect Json.NET deserialization when a SerializationBinder isn't specified, then disable rule CA2326, and enable rules CA2327, CA2328, CA2329, and CA2330. | +135 | [CA2327](https://docs.microsoft.com/visualstudio/code-quality/ca2327) | Do not use insecure JsonSerializerSettings | Security | False | False | When deserializing untrusted input, allowing arbitrary types to be deserialized is insecure. When using JsonSerializerSettings, use TypeNameHandling.None, or for values other than None, restrict deserialized types with a SerializationBinder. | +136 | [CA2328](https://docs.microsoft.com/visualstudio/code-quality/ca2328) | Ensure that JsonSerializerSettings are secure | Security | False | False | When deserializing untrusted input, allowing arbitrary types to be deserialized is insecure. When using JsonSerializerSettings, ensure TypeNameHandling.None is specified, or for values other than None, ensure a SerializationBinder is specified to restrict deserialized types. | +137 | [CA2329](https://docs.microsoft.com/visualstudio/code-quality/ca2329) | Do not deserialize with JsonSerializer using an insecure configuration | Security | False | False | When deserializing untrusted input, allowing arbitrary types to be deserialized is insecure. When using deserializing JsonSerializer, use TypeNameHandling.None, or for values other than None, restrict deserialized types with a SerializationBinder. | +138 | [CA2330](https://docs.microsoft.com/visualstudio/code-quality/ca2330) | Ensure that JsonSerializer has a secure configuration when deserializing | Security | False | False | When deserializing untrusted input, allowing arbitrary types to be deserialized is insecure. When using deserializing JsonSerializer, use TypeNameHandling.None, or for values other than None, restrict deserialized types with a SerializationBinder. | 139 | [CA3001](https://docs.microsoft.com/visualstudio/code-quality/ca3001-review-code-for-sql-injection-vulnerabilities) | Review code for SQL injection vulnerabilities | Security | False | False | Potential SQL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | 140 | [CA3002](https://docs.microsoft.com/visualstudio/code-quality/ca3002-review-code-for-xss-vulnerabilities) | Review code for XSS vulnerabilities | Security | False | False | Potential cross-site scripting (XSS) vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | 141 | [CA3003](https://docs.microsoft.com/visualstudio/code-quality/ca3003-review-code-for-file-path-injection-vulnerabilities) | Review code for file path injection vulnerabilities | Security | False | False | Potential file path injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | @@ -195,4 +195,6 @@ Sr. No. | Rule ID | Title | Category | Enabled | CodeFix | Description | 192 | CA5393 | Do not use unsafe DllImportSearchPath value | Security | True | False | There could be a malicious DLL in the default DLL search directories. Or, depending on where your application is run from, there could be a malicious DLL in the application's directory. Use a DllImportSearchPath value that specifies an explicit search path instead. The DllImportSearchPath flags that this rule looks for can be configured in .editorconfig. | 193 | CA5394 | Do not use insecure randomness | Security | False | False | {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security | 194 | CA5396 | Set HttpOnly to true for HttpCookie | Security | False | False | As a defense in depth measure, ensure security sensitive HTTP cookies are marked as HttpOnly. This indicates web browsers should disallow scripts from accessing the cookies. Injected malicious scripts are a common way of stealing cookies. | -195 | CA9999 | Analyzer version mismatch | Reliability | True | False | Analyzers in this package require a certain minimum version of Microsoft.CodeAnalysis to execute correctly. Refer to https://docs.microsoft.com/visualstudio/code-quality/install-fxcop-analyzers#fxcopanalyzers-package-versions to install the correct analyzer version. | +195 | [CA5397](https://docs.microsoft.com/visualstudio/code-quality/ca5397) | Do not use deprecated SslProtocols values | Security | True | False | Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. | +196 | [CA5398](https://docs.microsoft.com/visualstudio/code-quality/ca5398) | Avoid hardcoded SslProtocols values | Security | False | False | Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. | +197 | CA9999 | Analyzer version mismatch | Reliability | True | False | Analyzers in this package require a certain minimum version of Microsoft.CodeAnalysis to execute correctly. Refer to https://docs.microsoft.com/visualstudio/code-quality/install-fxcop-analyzers#fxcopanalyzers-package-versions to install the correct analyzer version. | diff --git a/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.sarif b/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.sarif index c9b01a0b60..6a80facaf2 100644 --- a/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.sarif +++ b/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.sarif @@ -2128,22 +2128,6 @@ ] } }, - "CA1829": { - "id": "CA1829", - "shortDescription": "Use property instead of Count() when available", - "fullDescription": "Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access.", - "defaultLevel": "warning", - "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1829", - "properties": { - "category": "Performance", - "isEnabledByDefault": true, - "typeName": "UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer", - "languages": [ - "C#", - "Visual Basic" - ] - } - }, "CA2000": { "id": "CA2000", "shortDescription": "Dispose objects before losing scope", @@ -3802,6 +3786,21 @@ ] } }, + "CA1829": { + "id": "CA1829", + "shortDescription": "Use Length/Count property instead of Count() when available", + "fullDescription": "Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1829", + "properties": { + "category": "Performance", + "isEnabledByDefault": true, + "typeName": "CSharpUsePropertyInsteadOfCountMethodWhenAvailableAnalyzer", + "languages": [ + "C#" + ] + } + }, "CA2010": { "id": "CA2010", "shortDescription": "Always consume the value returned by methods marked with PreserveSigAttribute", @@ -3967,6 +3966,21 @@ ] } }, + "CA1829": { + "id": "CA1829", + "shortDescription": "Use Length/Count property instead of Count() when available", + "fullDescription": "Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1829", + "properties": { + "category": "Performance", + "isEnabledByDefault": true, + "typeName": "BasicUsePropertyInsteadOfCountMethodWhenAvailableAnalyzer", + "languages": [ + "Visual Basic" + ] + } + }, "CA2010": { "id": "CA2010", "shortDescription": "Always consume the value returned by methods marked with PreserveSigAttribute", diff --git a/src/Microsoft.NetCore.Analyzers/CSharp/Performance/CSharpUsePropertyInsteadOfCountMethodWhenAvailable.cs b/src/Microsoft.NetCore.Analyzers/CSharp/Performance/CSharpUsePropertyInsteadOfCountMethodWhenAvailable.cs new file mode 100644 index 0000000000..ba268835cb --- /dev/null +++ b/src/Microsoft.NetCore.Analyzers/CSharp/Performance/CSharpUsePropertyInsteadOfCountMethodWhenAvailable.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Operations; +using Microsoft.NetCore.Analyzers.Performance; + +namespace Microsoft.NetCore.CSharp.Analyzers.Performance +{ + [DiagnosticAnalyzer(LanguageNames.CSharp)] + public sealed class CSharpUsePropertyInsteadOfCountMethodWhenAvailableAnalyzer + : UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer + { + /// + /// Creates the operation actions handler. + /// + /// The context. + /// The operation actions handler. + protected override OperationActionsHandler CreateOperationActionsHandler(OperationActionsContext context) + => new CSharpOperationActionsHandler(context); + + /// + /// Handler for operaction actions for C#. This class cannot be inherited. + /// Implements the + /// + /// + private sealed class CSharpOperationActionsHandler : OperationActionsHandler + { + internal CSharpOperationActionsHandler(OperationActionsContext context) + : base(context) + { + } + + protected override ITypeSymbol GetEnumerableCountInvocationTargetType(IInvocationOperation invocationOperation) + { + var method = invocationOperation.TargetMethod; + + if (invocationOperation.Arguments.Length == 1 && + method.Name.Equals(nameof(Enumerable.Count), StringComparison.Ordinal) && + this.Context.IsEnumerableType(method.ContainingSymbol) && + ((INamedTypeSymbol)(method.Parameters[0].Type)).TypeArguments[0] is ITypeSymbol methodSourceItemType) + { + return invocationOperation.Arguments[0].Value is IConversionOperation convertionOperation + ? convertionOperation.Operand.Type + : invocationOperation.Arguments[0].Value.Type; + } + + return null; + } + } + } +} diff --git a/src/Microsoft.NetCore.Analyzers/Core/MicrosoftNetCoreAnalyzersResources.resx b/src/Microsoft.NetCore.Analyzers/Core/MicrosoftNetCoreAnalyzersResources.resx index e3539c3241..132dbfa5cc 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/MicrosoftNetCoreAnalyzersResources.resx +++ b/src/Microsoft.NetCore.Analyzers/Core/MicrosoftNetCoreAnalyzersResources.resx @@ -1141,7 +1141,7 @@ Use the "{0}" property instead of Enumerable.Count(). - Use property instead of Count() when available + Use Length/Count property instead of Count() when available Set HttpOnly to true for HttpCookie diff --git a/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs b/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs index 0f499c42c6..c08de574a3 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs @@ -49,9 +49,11 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); var node = root.FindNode(context.Span); - var propertyName = context.Diagnostics[0].Properties["PropertyName"]; - if (node is object && propertyName is object && TryGetExpression(node, out var expressionNode, out var nameNode)) + if (node is object && + context.Diagnostics[0].Properties.TryGetValue(UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer.PropertyNameKey, out var propertyName) && + propertyName is object && + TryGetExpression(node, out var expressionNode, out var nameNode)) { context.RegisterCodeFix( new UsePropertyInsteadOfCountMethodWhenAvailableCodeAction(context.Document, node, expressionNode, nameNode, propertyName), diff --git a/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs b/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs index a65c4a07df..a26f3fc693 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs @@ -19,9 +19,10 @@ namespace Microsoft.NetCore.Analyzers.Performance /// Length, Count. /// [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] - public sealed class UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer : DiagnosticAnalyzer + public abstract class UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer : DiagnosticAnalyzer { internal const string RuleId = "CA1829"; + internal const string PropertyNameKey = nameof(PropertyNameKey); private const string CountPropertyName = "Count"; private const string LengthPropertyName = "Length"; private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.UsePropertyInsteadOfCountMethodWhenAvailableTitle), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); @@ -61,7 +62,7 @@ public override void Initialize(AnalysisContext context) /// Called on compilation start. /// /// The context. - private static void OnCompilationStart(CompilationStartAnalysisContext context) + private void OnCompilationStart(CompilationStartAnalysisContext context) { if (WellKnownTypes.Enumerable(context.Compilation) is INamedTypeSymbol enumerableType) { @@ -69,17 +70,20 @@ private static void OnCompilationStart(CompilationStartAnalysisContext context) context.Compilation, enumerableType); - var operationActionsHandler = context.Compilation.Language == LanguageNames.CSharp - ? (OperationActionsHandler)new CSharpOperationActionsHandler(operationActionsContext) - : (OperationActionsHandler)new BasicOperationActionsHandler(operationActionsContext); - context.RegisterOperationAction( - operationActionsHandler.AnalyzeInvocationOperation, + CreateOperationActionsHandler(operationActionsContext).AnalyzeInvocationOperation, OperationKind.Invocation); } } - private sealed class OperationActionsContext + /// + /// Creates the operation actions handler. + /// + /// The context. + /// The operation actions handler. + protected abstract OperationActionsHandler CreateOperationActionsHandler(OperationActionsContext context); + + protected sealed class OperationActionsContext { private readonly Lazy _immutableArrayType; private readonly Lazy _iCollectionCountProperty; @@ -172,14 +176,14 @@ internal bool IsEnumerableType(ISymbol symbol) /// /// Handler for operaction actions. /// - private abstract class OperationActionsHandler + protected abstract class OperationActionsHandler { protected OperationActionsHandler(OperationActionsContext context) { Context = context; } - public OperationActionsContext Context { get; } + protected OperationActionsContext Context { get; } internal void AnalyzeInvocationOperation(OperationAnalysisContext context) { @@ -189,7 +193,7 @@ internal void AnalyzeInvocationOperation(OperationAnalysisContext context) GetReplacementProperty(invocationTarget) is string propertyName) { var propertiesBuilder = ImmutableDictionary.CreateBuilder(); - propertiesBuilder.Add("PropertyName", propertyName); + propertiesBuilder.Add(PropertyNameKey, propertyName); var diagnostic = Diagnostic.Create( s_rule, @@ -218,65 +222,5 @@ private string GetReplacementProperty(ITypeSymbol invocationTarget) return null; } } - - /// - /// Handler for operaction actions for C#. This class cannot be inherited. - /// Implements the - /// - /// - private sealed class CSharpOperationActionsHandler : OperationActionsHandler - { - internal CSharpOperationActionsHandler(UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer.OperationActionsContext context) - : base(context) - { - } - - protected override ITypeSymbol GetEnumerableCountInvocationTargetType(IInvocationOperation invocationOperation) - { - var method = invocationOperation.TargetMethod; - - if (invocationOperation.Arguments.Length == 1 && - method.Name.Equals(nameof(Enumerable.Count), StringComparison.Ordinal) && - this.Context.IsEnumerableType(method.ContainingSymbol) && - ((INamedTypeSymbol)(method.Parameters[0].Type)).TypeArguments[0] is ITypeSymbol methodSourceItemType) - { - return invocationOperation.Arguments[0].Value is IConversionOperation convertionOperation - ? convertionOperation.Operand.Type - : invocationOperation.Arguments[0].Value.Type; - } - - return null; - } - } - - /// - /// Handler for operaction actions fro Visual Basic. This class cannot be inherited. - /// Implements the - /// - /// - private sealed class BasicOperationActionsHandler : OperationActionsHandler - { - internal BasicOperationActionsHandler(UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer.OperationActionsContext context) - : base(context) - { - } - - protected override ITypeSymbol GetEnumerableCountInvocationTargetType(IInvocationOperation invocationOperation) - { - var method = invocationOperation.TargetMethod; - - if (invocationOperation.Arguments.Length == 0 && - method.Name.Equals(nameof(Enumerable.Count), StringComparison.Ordinal) && - this.Context.IsEnumerableType(method.ContainingSymbol) && - ((INamedTypeSymbol)(invocationOperation.Instance.Type)).TypeArguments[0] is ITypeSymbol methodSourceItemType) - { - return invocationOperation.Instance is IConversionOperation convertionOperation - ? convertionOperation.Operand.Type - : invocationOperation.Instance.Type; - } - - return null; - } - } } } diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.cs.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.cs.xlf index 21115155d4..7d28e19761 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.cs.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.cs.xlf @@ -1673,8 +1673,8 @@ - Use property instead of Count() when available - Use property instead of Count() when available + Use Length/Count property instead of Count() when available + Use Length/Count property instead of Count() when available diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.de.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.de.xlf index 6e7aa52fa8..86c8619ba4 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.de.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.de.xlf @@ -1673,8 +1673,8 @@ - Use property instead of Count() when available - Use property instead of Count() when available + Use Length/Count property instead of Count() when available + Use Length/Count property instead of Count() when available diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.es.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.es.xlf index 912191cb9c..131d3f46b6 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.es.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.es.xlf @@ -1673,8 +1673,8 @@ - Use property instead of Count() when available - Use property instead of Count() when available + Use Length/Count property instead of Count() when available + Use Length/Count property instead of Count() when available diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.fr.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.fr.xlf index b7c2cafbe9..d69ed3e309 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.fr.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.fr.xlf @@ -1673,8 +1673,8 @@ - Use property instead of Count() when available - Use property instead of Count() when available + Use Length/Count property instead of Count() when available + Use Length/Count property instead of Count() when available diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.it.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.it.xlf index 06690c9340..99223791d8 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.it.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.it.xlf @@ -1673,8 +1673,8 @@ - Use property instead of Count() when available - Use property instead of Count() when available + Use Length/Count property instead of Count() when available + Use Length/Count property instead of Count() when available diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ja.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ja.xlf index 83e016b0be..89160b0996 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ja.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ja.xlf @@ -1673,8 +1673,8 @@ - Use property instead of Count() when available - Use property instead of Count() when available + Use Length/Count property instead of Count() when available + Use Length/Count property instead of Count() when available diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ko.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ko.xlf index 06ad66b89e..b53fd8151b 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ko.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ko.xlf @@ -1673,8 +1673,8 @@ - Use property instead of Count() when available - Use property instead of Count() when available + Use Length/Count property instead of Count() when available + Use Length/Count property instead of Count() when available diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.pl.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.pl.xlf index d9913b0d48..499df4b5bb 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.pl.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.pl.xlf @@ -1673,8 +1673,8 @@ - Use property instead of Count() when available - Use property instead of Count() when available + Use Length/Count property instead of Count() when available + Use Length/Count property instead of Count() when available diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.pt-BR.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.pt-BR.xlf index 6736e74753..23f641199e 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.pt-BR.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.pt-BR.xlf @@ -1673,8 +1673,8 @@ - Use property instead of Count() when available - Use property instead of Count() when available + Use Length/Count property instead of Count() when available + Use Length/Count property instead of Count() when available diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ru.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ru.xlf index 5ac9495984..bf4b495468 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ru.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.ru.xlf @@ -1673,8 +1673,8 @@ - Use property instead of Count() when available - Use property instead of Count() when available + Use Length/Count property instead of Count() when available + Use Length/Count property instead of Count() when available diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.tr.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.tr.xlf index c95e3582e4..67f701cbae 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.tr.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.tr.xlf @@ -1673,8 +1673,8 @@ - Use property instead of Count() when available - Use property instead of Count() when available + Use Length/Count property instead of Count() when available + Use Length/Count property instead of Count() when available diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hans.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hans.xlf index 26d88362e7..1a6e73d33c 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hans.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hans.xlf @@ -1673,8 +1673,8 @@ - Use property instead of Count() when available - Use property instead of Count() when available + Use Length/Count property instead of Count() when available + Use Length/Count property instead of Count() when available diff --git a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hant.xlf b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hant.xlf index 501953fc5e..a2438a4b69 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hant.xlf +++ b/src/Microsoft.NetCore.Analyzers/Core/xlf/MicrosoftNetCoreAnalyzersResources.zh-Hant.xlf @@ -1673,8 +1673,8 @@ - Use property instead of Count() when available - Use property instead of Count() when available + Use Length/Count property instead of Count() when available + Use Length/Count property instead of Count() when available diff --git a/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.md b/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.md index 6d09fdc86e..73a41f9af9 100644 --- a/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.md +++ b/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.md @@ -17,90 +17,91 @@ Sr. No. | Rule ID | Title | Category | Enabled | CodeFix | Description | 14 | CA1826 | Do not use Enumerable methods on indexable collections. Instead use the collection directly | Performance | True | True | This collection is directly indexable. Going through LINQ here causes unnecessary allocations and CPU work. | 15 | [CA1827](https://docs.microsoft.com/visualstudio/code-quality/ca1827) | Do not use Count() or LongCount() when Any() can be used | Performance | True | True | For non-empty collections, Count() and LongCount() enumerate the entire sequence, while Any() stops at the first item or the first item that satisfies a condition. | 16 | [CA1828](https://docs.microsoft.com/visualstudio/code-quality/ca1828) | Do not use CountAsync() or LongCountAsync() when AnyAsync() can be used | Performance | True | True | For non-empty collections, CountAsync() and LongCountAsync() enumerate the entire sequence, while AnyAsync() stops at the first item or the first item that satisfies a condition. | -17 | [CA2000](https://docs.microsoft.com/visualstudio/code-quality/ca2000-dispose-objects-before-losing-scope) | Dispose objects before losing scope | Reliability | True | False | If a disposable object is not explicitly disposed before all references to it are out of scope, the object will be disposed at some indeterminate time when the garbage collector runs the finalizer of the object. Because an exceptional event might occur that will prevent the finalizer of the object from running, the object should be explicitly disposed instead. | -18 | [CA2002](https://docs.microsoft.com/visualstudio/code-quality/ca2002-do-not-lock-on-objects-with-weak-identity) | Do not lock on objects with weak identity | Reliability | True | False | An object is said to have a weak identity when it can be directly accessed across application domain boundaries. A thread that tries to acquire a lock on an object that has a weak identity can be blocked by a second thread in a different application domain that has a lock on the same object. | -19 | CA2008 | Do not create tasks without passing a TaskScheduler | Reliability | True | True | Do not create tasks unless you are using one of the overloads that takes a TaskScheduler. The default is to schedule on TaskScheduler.Current, which would lead to deadlocks. Either use TaskScheduler.Default to schedule on the thread pool, or explicitly pass TaskScheduler.Current to make your intentions clear. | -20 | CA2009 | Do not call ToImmutableCollection on an ImmutableCollection value | Reliability | True | True | Do not call {0} on an {1} value | -21 | CA2010 | Always consume the value returned by methods marked with PreserveSigAttribute | Reliability | True | False | PreserveSigAttribute indicates that a method will return an HRESULT, rather than throwing an exception. Therefore, it is important to consume the HRESULT returned by the method, so that errors can be detected. Generally, this is done by calling Marshal.ThrowExceptionForHR. | -22 | [CA2100](https://docs.microsoft.com/visualstudio/code-quality/ca2100-review-sql-queries-for-security-vulnerabilities) | Review SQL queries for security vulnerabilities | Security | True | False | SQL queries that directly use user input can be vulnerable to SQL injection attacks. Review this SQL query for potential vulnerabilities, and consider using a parameterized SQL query. | -23 | [CA2101](https://docs.microsoft.com/visualstudio/code-quality/ca2101-specify-marshaling-for-p-invoke-string-arguments) | Specify marshaling for P/Invoke string arguments | Globalization | True | True | A platform invoke member allows partially trusted callers, has a string parameter, and does not explicitly marshal the string. This can cause a potential security vulnerability. | -24 | [CA2201](https://docs.microsoft.com/visualstudio/code-quality/ca2201-do-not-raise-reserved-exception-types) | Do not raise reserved exception types | Usage | False | False | An exception of type that is not sufficiently specific or reserved by the runtime should never be raised by user code. This makes the original error difficult to detect and debug. If this exception instance might be thrown, use a different exception type. | -25 | [CA2207](https://docs.microsoft.com/visualstudio/code-quality/ca2207-initialize-value-type-static-fields-inline) | Initialize value type static fields inline | Usage | True | True | A value type declares an explicit static constructor. To fix a violation of this rule, initialize all static data when it is declared and remove the static constructor. | -26 | [CA2208](https://docs.microsoft.com/visualstudio/code-quality/ca2208-instantiate-argument-exceptions-correctly) | Instantiate argument exceptions correctly | Usage | True | True | A call is made to the default (parameterless) constructor of an exception type that is or derives from ArgumentException, or an incorrect string argument is passed to a parameterized constructor of an exception type that is or derives from ArgumentException. | -27 | [CA2213](https://docs.microsoft.com/visualstudio/code-quality/ca2213-disposable-fields-should-be-disposed) | Disposable fields should be disposed | Usage | True | False | A type that implements System.IDisposable declares fields that are of types that also implement IDisposable. The Dispose method of the field is not called by the Dispose method of the declaring type. To fix a violation of this rule, call Dispose on fields that are of types that implement IDisposable if you are responsible for allocating and releasing the unmanaged resources held by the field. | -28 | [CA2216](https://docs.microsoft.com/visualstudio/code-quality/ca2216-disposable-types-should-declare-finalizer) | Disposable types should declare finalizer | Usage | True | True | A type that implements System.IDisposable and has fields that suggest the use of unmanaged resources does not implement a finalizer, as described by Object.Finalize. | -29 | [CA2229](https://docs.microsoft.com/visualstudio/code-quality/ca2229-implement-serialization-constructors) | Implement serialization constructors | Usage | True | True | To fix a violation of this rule, implement the serialization constructor. For a sealed class, make the constructor private; otherwise, make it protected. | -30 | [CA2235](https://docs.microsoft.com/visualstudio/code-quality/ca2235-mark-all-non-serializable-fields) | Mark all non-serializable fields | Usage | True | True | An instance field of a type that is not serializable is declared in a type that is serializable. | -31 | [CA2237](https://docs.microsoft.com/visualstudio/code-quality/ca2237-mark-iserializable-types-with-serializableattribute) | Mark ISerializable types with serializable | Usage | True | True | To be recognized by the common language runtime as serializable, types must be marked by using the SerializableAttribute attribute even when the type uses a custom serialization routine through implementation of the ISerializable interface. | -32 | [CA2241](https://docs.microsoft.com/visualstudio/code-quality/ca2241-provide-correct-arguments-to-formatting-methods) | Provide correct arguments to formatting methods | Usage | True | False | The format argument that is passed to System.String.Format does not contain a format item that corresponds to each object argument, or vice versa. | -33 | [CA2242](https://docs.microsoft.com/visualstudio/code-quality/ca2242-test-for-nan-correctly) | Test for NaN correctly | Usage | True | True | This expression tests a value against Single.Nan or Double.Nan. Use Single.IsNan(Single) or Double.IsNan(Double) to test the value. | -34 | [CA2243](https://docs.microsoft.com/visualstudio/code-quality/ca2243-attribute-string-literals-should-parse-correctly) | Attribute string literals should parse correctly | Usage | True | False | The string literal parameter of an attribute does not parse correctly for a URL, a GUID, or a version. | -35 | [CA2300](https://docs.microsoft.com/visualstudio/code-quality/ca2300-do-not-use-insecure-deserializer-binaryformatter) | Do not use insecure deserializer BinaryFormatter | Security | False | False | The method '{0}' is insecure when deserializing untrusted data. If you need to instead detect BinaryFormatter deserialization without a SerializationBinder set, then disable rule CA2300, and enable rules CA2301 and CA2302. | -36 | [CA2301](https://docs.microsoft.com/visualstudio/code-quality/ca2301-do-not-call-binaryformatter-deserialize-without-first-setting-binaryformatter-binder) | Do not call BinaryFormatter.Deserialize without first setting BinaryFormatter.Binder | Security | False | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | -37 | [CA2302](https://docs.microsoft.com/visualstudio/code-quality/ca2302-ensure-binaryformatter-binder-is-set-before-calling-binaryformatter-deserialize) | Ensure BinaryFormatter.Binder is set before calling BinaryFormatter.Deserialize | Security | False | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | -38 | [CA2305](https://docs.microsoft.com/visualstudio/code-quality/ca2305-do-not-use-insecure-deserializer-losformatter) | Do not use insecure deserializer LosFormatter | Security | False | False | The method '{0}' is insecure when deserializing untrusted data. | -39 | [CA2310](https://docs.microsoft.com/visualstudio/code-quality/ca2310-do-not-use-insecure-deserializer-netdatacontractserializer) | Do not use insecure deserializer NetDataContractSerializer | Security | False | False | The method '{0}' is insecure when deserializing untrusted data. If you need to instead detect NetDataContractSerializer deserialization without a SerializationBinder set, then disable rule CA2310, and enable rules CA2311 and CA2312. | -40 | [CA2311](https://docs.microsoft.com/visualstudio/code-quality/ca2311-do-not-deserialize-without-first-setting-netdatacontractserializer-binder) | Do not deserialize without first setting NetDataContractSerializer.Binder | Security | False | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | -41 | [CA2312](https://docs.microsoft.com/visualstudio/code-quality/ca2312-ensure-netdatacontractserializer-binder-is-set-before-deserializing) | Ensure NetDataContractSerializer.Binder is set before deserializing | Security | False | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | -42 | [CA2315](https://docs.microsoft.com/visualstudio/code-quality/ca2315-do-not-use-insecure-deserializer-objectstateformatter) | Do not use insecure deserializer ObjectStateFormatter | Security | False | False | The method '{0}' is insecure when deserializing untrusted data. | -43 | [CA2321](https://docs.microsoft.com/visualstudio/code-quality/ca2321) | Do not deserialize with JavaScriptSerializer using a SimpleTypeResolver | Security | False | False | The method '{0}' is insecure when deserializing untrusted data with a JavaScriptSerializer initialized with a SimpleTypeResolver. Initialize JavaScriptSerializer without a JavaScriptTypeResolver specified, or initialize with a JavaScriptTypeResolver that limits the types of objects in the deserialized object graph. | -44 | [CA2322](https://docs.microsoft.com/visualstudio/code-quality/ca2322) | Ensure JavaScriptSerializer is not initialized with SimpleTypeResolver before deserializing | Security | False | False | The method '{0}' is insecure when deserializing untrusted data with a JavaScriptSerializer initialized with a SimpleTypeResolver. Ensure that the JavaScriptSerializer is initialized without a JavaScriptTypeResolver specified, or initialized with a JavaScriptTypeResolver that limits the types of objects in the deserialized object graph. | -45 | [CA2326](https://docs.microsoft.com/visualstudio/code-quality/ca2326) | Do not use TypeNameHandling values other than None | Security | False | False | Deserializing JSON when using a TypeNameHandling value other than None can be insecure. If you need to instead detect Json.NET deserialization when a SerializationBinder isn't specified, then disable rule CA2326, and enable rules CA2327, CA2328, CA2329, and CA2330. | -46 | [CA2327](https://docs.microsoft.com/visualstudio/code-quality/ca2327) | Do not use insecure JsonSerializerSettings | Security | False | False | When deserializing untrusted input, allowing arbitrary types to be deserialized is insecure. When using JsonSerializerSettings, use TypeNameHandling.None, or for values other than None, restrict deserialized types with a SerializationBinder. | -47 | [CA2328](https://docs.microsoft.com/visualstudio/code-quality/ca2328) | Ensure that JsonSerializerSettings are secure | Security | False | False | When deserializing untrusted input, allowing arbitrary types to be deserialized is insecure. When using JsonSerializerSettings, ensure TypeNameHandling.None is specified, or for values other than None, ensure a SerializationBinder is specified to restrict deserialized types. | -48 | [CA2329](https://docs.microsoft.com/visualstudio/code-quality/ca2329) | Do not deserialize with JsonSerializer using an insecure configuration | Security | False | False | When deserializing untrusted input, allowing arbitrary types to be deserialized is insecure. When using deserializing JsonSerializer, use TypeNameHandling.None, or for values other than None, restrict deserialized types with a SerializationBinder. | -49 | [CA2330](https://docs.microsoft.com/visualstudio/code-quality/ca2330) | Ensure that JsonSerializer has a secure configuration when deserializing | Security | False | False | When deserializing untrusted input, allowing arbitrary types to be deserialized is insecure. When using deserializing JsonSerializer, use TypeNameHandling.None, or for values other than None, restrict deserialized types with a SerializationBinder. | -50 | [CA3001](https://docs.microsoft.com/visualstudio/code-quality/ca3001-review-code-for-sql-injection-vulnerabilities) | Review code for SQL injection vulnerabilities | Security | False | False | Potential SQL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -51 | [CA3002](https://docs.microsoft.com/visualstudio/code-quality/ca3002-review-code-for-xss-vulnerabilities) | Review code for XSS vulnerabilities | Security | False | False | Potential cross-site scripting (XSS) vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -52 | [CA3003](https://docs.microsoft.com/visualstudio/code-quality/ca3003-review-code-for-file-path-injection-vulnerabilities) | Review code for file path injection vulnerabilities | Security | False | False | Potential file path injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -53 | [CA3004](https://docs.microsoft.com/visualstudio/code-quality/ca3004-review-code-for-information-disclosure-vulnerabilities) | Review code for information disclosure vulnerabilities | Security | False | False | Potential information disclosure vulnerability was found where '{0}' in method '{1}' may contain unintended information from '{2}' in method '{3}'. | -54 | [CA3005](https://docs.microsoft.com/visualstudio/code-quality/ca3005-review-code-for-ldap-injection-vulnerabilities) | Review code for LDAP injection vulnerabilities | Security | False | False | Potential LDAP injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -55 | [CA3006](https://docs.microsoft.com/visualstudio/code-quality/ca3006-review-code-for-process-command-injection-vulnerabilities) | Review code for process command injection vulnerabilities | Security | False | False | Potential process command injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -56 | [CA3007](https://docs.microsoft.com/visualstudio/code-quality/ca3007-review-code-for-open-redirect-vulnerabilities) | Review code for open redirect vulnerabilities | Security | False | False | Potential open redirect vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -57 | [CA3008](https://docs.microsoft.com/visualstudio/code-quality/ca3008-review-code-for-xpath-injection-vulnerabilities) | Review code for XPath injection vulnerabilities | Security | False | False | Potential XPath injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -58 | [CA3009](https://docs.microsoft.com/visualstudio/code-quality/ca3009-review-code-for-xml-injection-vulnerabilities) | Review code for XML injection vulnerabilities | Security | False | False | Potential XML injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -59 | [CA3010](https://docs.microsoft.com/visualstudio/code-quality/ca3010-review-code-for-xaml-injection-vulnerabilities) | Review code for XAML injection vulnerabilities | Security | False | False | Potential XAML injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -60 | [CA3011](https://docs.microsoft.com/visualstudio/code-quality/ca3011-review-code-for-dll-injection-vulnerabilities) | Review code for DLL injection vulnerabilities | Security | False | False | Potential DLL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -61 | [CA3012](https://docs.microsoft.com/visualstudio/code-quality/ca3012-review-code-for-regex-injection-vulnerabilities) | Review code for regex injection vulnerabilities | Security | False | False | Potential regex injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -62 | CA3061 | Do Not Add Schema By URL | Security | True | False | This overload of XmlSchemaCollection.Add method internally enables DTD processing on the XML reader instance used, and uses UrlResolver for resolving external XML entities. The outcome is information disclosure. Content from file system or network shares for the machine processing the XML can be exposed to attacker. In addition, an attacker can use this as a DoS vector. | -63 | [CA5350](https://docs.microsoft.com/visualstudio/code-quality/ca5350-do-not-use-weak-cryptographic-algorithms) | Do Not Use Weak Cryptographic Algorithms | Security | True | False | Cryptographic algorithms degrade over time as attacks become for advances to attacker get access to more computation. Depending on the type and application of this cryptographic algorithm, further degradation of the cryptographic strength of it may allow attackers to read enciphered messages, tamper with enciphered  messages, forge digital signatures, tamper with hashed content, or otherwise compromise any cryptosystem based on this algorithm. Replace encryption uses with the AES algorithm (AES-256, AES-192 and AES-128 are acceptable) with a key length greater than or equal to 128 bits. Replace hashing uses with a hashing function in the SHA-2 family, such as SHA-2 512, SHA-2 384, or SHA-2 256. | -64 | [CA5351](https://docs.microsoft.com/visualstudio/code-quality/ca5351-do-not-use-broken-cryptographic-algorithms) | Do Not Use Broken Cryptographic Algorithms | Security | True | False | An attack making it computationally feasible to break this algorithm exists. This allows attackers to break the cryptographic guarantees it is designed to provide. Depending on the type and application of this cryptographic algorithm, this may allow attackers to read enciphered messages, tamper with enciphered  messages, forge digital signatures, tamper with hashed content, or otherwise compromise any cryptosystem based on this algorithm. Replace encryption uses with the AES algorithm (AES-256, AES-192 and AES-128 are acceptable) with a key length greater than or equal to 128 bits. Replace hashing uses with a hashing function in the SHA-2 family, such as SHA512, SHA384, or SHA256. Replace digital signature uses with RSA with a key length greater than or equal to 2048-bits, or ECDSA with a key length greater than or equal to 256 bits. | -65 | CA5358 | Do Not Use Unsafe Cipher Modes | Security | False | False | These modes are vulnerable to attacks. Use only approved modes (CBC, CTS). | -66 | CA5359 | Do Not Disable Certificate Validation | Security | True | False | A certificate can help authenticate the identity of the server. Clients should validate the server certificate to ensure requests are sent to the intended server. If the ServerCertificateValidationCallback always returns 'true', any certificate will pass validation. | -67 | CA5360 | Do Not Call Dangerous Methods In Deserialization | Security | True | False | Insecure Deserialization is a vulnerability which occurs when untrusted data is used to abuse the logic of an application, inflict a Denial-of-Service (DoS) attack, or even execute arbitrary code upon it being deserialized. It’s frequently possible for malicious users to abuse these deserialization features when the application is deserializing untrusted data which is under their control. Specifically, invoke dangerous methods in the process of deserialization. Successful insecure deserialization attacks could allow an attacker to carry out attacks such as DoS attacks, authentication bypasses, and remote code execution. | -68 | [CA5361](https://docs.microsoft.com/visualstudio/code-quality/ca5361) | Do Not Disable SChannel Use of Strong Crypto | Security | True | False | Starting with the .NET Framework 4.6, the System.Net.ServicePointManager and System.Net.Security.SslStream classes are recommeded to use new protocols. The old ones have protocol weaknesses and are not supported. Setting Switch.System.Net.DontEnableSchUseStrongCrypto with true will use the old weak crypto check and opt out of the protocol migration. | -69 | CA5362 | Do Not Refer Self In Serializable Class | Security | False | False | This can allow an attacker to DOS or exhaust the memory of the process. | -70 | CA5363 | Do Not Disable Request Validation | Security | True | False | Request validation is a feature in ASP.NET that examines HTTP requests and determines whether they contain potentially dangerous content. This check adds protection from markup or code in the URL query string, cookies, or posted form values that might have been added for malicious purposes. So, it is generally desirable and should be left enabled for defense in depth. | -71 | [CA5364](https://docs.microsoft.com/visualstudio/code-quality/ca5364) | Do Not Use Deprecated Security Protocols | Security | True | False | Using a deprecated security protocol rather than the system default is risky. | -72 | CA5365 | Do Not Disable HTTP Header Checking | Security | True | False | HTTP header checking enables encoding of the carriage return and newline characters, \r and \n, that are found in response headers. This encoding can help to avoid injection attacks that exploit an application that echoes untrusted data contained by the header. | -73 | CA5366 | Use XmlReader For DataSet Read Xml | Security | True | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | -74 | CA5367 | Do Not Serialize Types With Pointer Fields | Security | False | False | Pointers are not "type safe" in the sense that you cannot guarantee the correctness of the memory they point at. So, serializing types with pointer fields is dangerous, as it may allow an attacker to control the pointer. | -75 | CA5368 | Set ViewStateUserKey For Classes Derived From Page | Security | True | False | Setting the ViewStateUserKey property can help you prevent attacks on your application by allowing you to assign an identifier to the view-state variable for individual users so that they cannot use the variable to generate an attack. Otherwise, there will be cross-site request forgery vulnerabilities. | -76 | CA5369 | Use XmlReader For Deserialize | Security | True | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | -77 | CA5370 | Use XmlReader For Validating Reader | Security | True | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | -78 | CA5371 | Use XmlReader For Schema Read | Security | True | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | -79 | CA5372 | Use XmlReader For XPathDocument | Security | True | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | -80 | CA5373 | Do not use obsolete key derivation function | Security | True | False | Password-based key derivation should use PBKDF2 with SHA-2. Avoid using PasswordDeriveBytes since it generates a PBKDF1 key. Avoid using Rfc2898DeriveBytes.CryptDeriveKey since it doesn't use the iteration count or salt. | -81 | CA5374 | Do Not Use XslTransform | Security | True | False | Do not use XslTransform. It does not restrict potentially dangerous external references. | -82 | CA5375 | Do Not Use Account Shared Access Signature | Security | False | False | Shared Access Signatures(SAS) are a vital part of the security model for any application using Azure Storage, they should provide limited and safe permissions to your storage account to clients that don't have the account key. All of the operations available via a service SAS are also available via an account SAS, that is, account SAS is too powerful. So it is recommended to use Service SAS to delegate access more carefully. | -83 | CA5376 | Use SharedAccessProtocol HttpsOnly | Security | True | False | HTTPS encrypts network traffic. Use HttpsOnly, rather than HttpOrHttps, to ensure network traffic is always encrypted to help prevent disclosure of sensitive data. | -84 | CA5377 | Use Container Level Access Policy | Security | True | False | No access policy identifier is specified, making tokens non-revocable. | -85 | [CA5378](https://docs.microsoft.com/visualstudio/code-quality/ca5378) | Do not disable ServicePointManagerSecurityProtocols | Security | True | False | Do not set Switch.System.ServiceModel.DisableUsingServicePointManagerSecurityProtocols to true. Setting this switch limits Windows Communication Framework (WCF) to using Transport Layer Security (TLS) 1.0, which is insecure and obsolete. | -86 | CA5379 | Do Not Use Weak Key Derivation Function Algorithm | Security | True | False | Some implementations of the Rfc2898DeriveBytes class allow for a hash algorithm to be specified in a constructor parameter or overwritten in the HashAlgorithm property. If a hash algorithm is specified, then it should be SHA-256 or higher. | -87 | CA5380 | Do Not Add Certificates To Root Store | Security | True | False | By default, the Trusted Root Certification Authorities certificate store is configured with a set of public CAs that has met the requirements of the Microsoft Root Certificate Program. Since all trusted root CAs can issue certificates for any domain, an attacker can pick a weak or coercible CA that you install by yourself to target for an attack – and a single vulnerable, malicious or coercible CA undermines the security of the entire system. To make matters worse, these attacks can go unnoticed quite easily. | -88 | CA5381 | Ensure Certificates Are Not Added To Root Store | Security | True | False | By default, the Trusted Root Certification Authorities certificate store is configured with a set of public CAs that has met the requirements of the Microsoft Root Certificate Program. Since all trusted root CAs can issue certificates for any domain, an attacker can pick a weak or coercible CA that you install by yourself to target for an attack – and a single vulnerable, malicious or coercible CA undermines the security of the entire system. To make matters worse, these attacks can go unnoticed quite easily. | -89 | CA5382 | Use Secure Cookies In ASP.Net Core | Security | False | False | Applications available over HTTPS must use secure cookies. | -90 | CA5383 | Ensure Use Secure Cookies In ASP.Net Core | Security | False | False | Applications available over HTTPS must use secure cookies. | -91 | CA5384 | Do Not Use Digital Signature Algorithm (DSA) | Security | True | False | DSA is too weak to use. | -92 | CA5385 | Use Rivest–Shamir–Adleman (RSA) Algorithm With Sufficient Key Size | Security | True | False | Encryption algorithms are vulnerable to brute force attacks when too small a key size is used. | -93 | [CA5386](https://docs.microsoft.com/visualstudio/code-quality/ca5386) | Avoid hardcoding SecurityProtocolType value | Security | False | False | Avoid hardcoding SecurityProtocolType {0}, and instead use SecurityProtocolType.SystemDefault to allow the operating system to choose the best Transport Layer Security protocol to use. | -94 | CA5387 | Do Not Use Weak Key Derivation Function With Insufficient Iteration Count | Security | False | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | -95 | CA5388 | Ensure Sufficient Iteration Count When Using Weak Key Derivation Function | Security | False | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | -96 | CA5389 | Do Not Add Archive Item's Path To The Target File System Path | Security | True | False | When extracting files from an archive and using the archive item's path, check if the path is safe. Archive path can be relative and can lead to file system access outside of the expected file system target path, leading to malicious config changes and remote code execution via lay-and-wait technique. | -97 | CA5390 | Do Not Hard Code Encryption Key | Security | True | False | SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. | -98 | CA5392 | Use DefaultDllImportSearchPaths attribute for P/Invokes | Security | True | False | By default, P/Invokes using DllImportAttribute probe a number of directories, including the current working directory for the library to load. This can be a security issue for certain applications, leading to DLL hijacking. | -99 | CA5393 | Do not use unsafe DllImportSearchPath value | Security | True | False | There could be a malicious DLL in the default DLL search directories. Or, depending on where your application is run from, there could be a malicious DLL in the application's directory. Use a DllImportSearchPath value that specifies an explicit search path instead. The DllImportSearchPath flags that this rule looks for can be configured in .editorconfig. | -100 | CA5394 | Do not use insecure randomness | Security | False | False | {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security | -101 | CA5396 | Set HttpOnly to true for HttpCookie | Security | False | False | As a defense in depth measure, ensure security sensitive HTTP cookies are marked as HttpOnly. This indicates web browsers should disallow scripts from accessing the cookies. Injected malicious scripts are a common way of stealing cookies. | -102 | [CA5397](https://docs.microsoft.com/visualstudio/code-quality/ca5397) | Do not use deprecated SslProtocols values | Security | True | False | Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. | -103 | [CA5398](https://docs.microsoft.com/visualstudio/code-quality/ca5398) | Avoid hardcoded SslProtocols values | Security | False | False | Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. | +17 | [CA1829](https://docs.microsoft.com/visualstudio/code-quality/ca1829) | Use Length/Count property instead of Count() when available | Performance | True | True | Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. | +18 | [CA2000](https://docs.microsoft.com/visualstudio/code-quality/ca2000-dispose-objects-before-losing-scope) | Dispose objects before losing scope | Reliability | True | False | If a disposable object is not explicitly disposed before all references to it are out of scope, the object will be disposed at some indeterminate time when the garbage collector runs the finalizer of the object. Because an exceptional event might occur that will prevent the finalizer of the object from running, the object should be explicitly disposed instead. | +19 | [CA2002](https://docs.microsoft.com/visualstudio/code-quality/ca2002-do-not-lock-on-objects-with-weak-identity) | Do not lock on objects with weak identity | Reliability | True | False | An object is said to have a weak identity when it can be directly accessed across application domain boundaries. A thread that tries to acquire a lock on an object that has a weak identity can be blocked by a second thread in a different application domain that has a lock on the same object. | +20 | CA2008 | Do not create tasks without passing a TaskScheduler | Reliability | True | True | Do not create tasks unless you are using one of the overloads that takes a TaskScheduler. The default is to schedule on TaskScheduler.Current, which would lead to deadlocks. Either use TaskScheduler.Default to schedule on the thread pool, or explicitly pass TaskScheduler.Current to make your intentions clear. | +21 | CA2009 | Do not call ToImmutableCollection on an ImmutableCollection value | Reliability | True | True | Do not call {0} on an {1} value | +22 | CA2010 | Always consume the value returned by methods marked with PreserveSigAttribute | Reliability | True | False | PreserveSigAttribute indicates that a method will return an HRESULT, rather than throwing an exception. Therefore, it is important to consume the HRESULT returned by the method, so that errors can be detected. Generally, this is done by calling Marshal.ThrowExceptionForHR. | +23 | [CA2100](https://docs.microsoft.com/visualstudio/code-quality/ca2100-review-sql-queries-for-security-vulnerabilities) | Review SQL queries for security vulnerabilities | Security | True | False | SQL queries that directly use user input can be vulnerable to SQL injection attacks. Review this SQL query for potential vulnerabilities, and consider using a parameterized SQL query. | +24 | [CA2101](https://docs.microsoft.com/visualstudio/code-quality/ca2101-specify-marshaling-for-p-invoke-string-arguments) | Specify marshaling for P/Invoke string arguments | Globalization | True | True | A platform invoke member allows partially trusted callers, has a string parameter, and does not explicitly marshal the string. This can cause a potential security vulnerability. | +25 | [CA2201](https://docs.microsoft.com/visualstudio/code-quality/ca2201-do-not-raise-reserved-exception-types) | Do not raise reserved exception types | Usage | False | False | An exception of type that is not sufficiently specific or reserved by the runtime should never be raised by user code. This makes the original error difficult to detect and debug. If this exception instance might be thrown, use a different exception type. | +26 | [CA2207](https://docs.microsoft.com/visualstudio/code-quality/ca2207-initialize-value-type-static-fields-inline) | Initialize value type static fields inline | Usage | True | True | A value type declares an explicit static constructor. To fix a violation of this rule, initialize all static data when it is declared and remove the static constructor. | +27 | [CA2208](https://docs.microsoft.com/visualstudio/code-quality/ca2208-instantiate-argument-exceptions-correctly) | Instantiate argument exceptions correctly | Usage | True | True | A call is made to the default (parameterless) constructor of an exception type that is or derives from ArgumentException, or an incorrect string argument is passed to a parameterized constructor of an exception type that is or derives from ArgumentException. | +28 | [CA2213](https://docs.microsoft.com/visualstudio/code-quality/ca2213-disposable-fields-should-be-disposed) | Disposable fields should be disposed | Usage | True | False | A type that implements System.IDisposable declares fields that are of types that also implement IDisposable. The Dispose method of the field is not called by the Dispose method of the declaring type. To fix a violation of this rule, call Dispose on fields that are of types that implement IDisposable if you are responsible for allocating and releasing the unmanaged resources held by the field. | +29 | [CA2216](https://docs.microsoft.com/visualstudio/code-quality/ca2216-disposable-types-should-declare-finalizer) | Disposable types should declare finalizer | Usage | True | True | A type that implements System.IDisposable and has fields that suggest the use of unmanaged resources does not implement a finalizer, as described by Object.Finalize. | +30 | [CA2229](https://docs.microsoft.com/visualstudio/code-quality/ca2229-implement-serialization-constructors) | Implement serialization constructors | Usage | True | True | To fix a violation of this rule, implement the serialization constructor. For a sealed class, make the constructor private; otherwise, make it protected. | +31 | [CA2235](https://docs.microsoft.com/visualstudio/code-quality/ca2235-mark-all-non-serializable-fields) | Mark all non-serializable fields | Usage | True | True | An instance field of a type that is not serializable is declared in a type that is serializable. | +32 | [CA2237](https://docs.microsoft.com/visualstudio/code-quality/ca2237-mark-iserializable-types-with-serializableattribute) | Mark ISerializable types with serializable | Usage | True | True | To be recognized by the common language runtime as serializable, types must be marked by using the SerializableAttribute attribute even when the type uses a custom serialization routine through implementation of the ISerializable interface. | +33 | [CA2241](https://docs.microsoft.com/visualstudio/code-quality/ca2241-provide-correct-arguments-to-formatting-methods) | Provide correct arguments to formatting methods | Usage | True | False | The format argument that is passed to System.String.Format does not contain a format item that corresponds to each object argument, or vice versa. | +34 | [CA2242](https://docs.microsoft.com/visualstudio/code-quality/ca2242-test-for-nan-correctly) | Test for NaN correctly | Usage | True | True | This expression tests a value against Single.Nan or Double.Nan. Use Single.IsNan(Single) or Double.IsNan(Double) to test the value. | +35 | [CA2243](https://docs.microsoft.com/visualstudio/code-quality/ca2243-attribute-string-literals-should-parse-correctly) | Attribute string literals should parse correctly | Usage | True | False | The string literal parameter of an attribute does not parse correctly for a URL, a GUID, or a version. | +36 | [CA2300](https://docs.microsoft.com/visualstudio/code-quality/ca2300-do-not-use-insecure-deserializer-binaryformatter) | Do not use insecure deserializer BinaryFormatter | Security | False | False | The method '{0}' is insecure when deserializing untrusted data. If you need to instead detect BinaryFormatter deserialization without a SerializationBinder set, then disable rule CA2300, and enable rules CA2301 and CA2302. | +37 | [CA2301](https://docs.microsoft.com/visualstudio/code-quality/ca2301-do-not-call-binaryformatter-deserialize-without-first-setting-binaryformatter-binder) | Do not call BinaryFormatter.Deserialize without first setting BinaryFormatter.Binder | Security | False | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | +38 | [CA2302](https://docs.microsoft.com/visualstudio/code-quality/ca2302-ensure-binaryformatter-binder-is-set-before-calling-binaryformatter-deserialize) | Ensure BinaryFormatter.Binder is set before calling BinaryFormatter.Deserialize | Security | False | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | +39 | [CA2305](https://docs.microsoft.com/visualstudio/code-quality/ca2305-do-not-use-insecure-deserializer-losformatter) | Do not use insecure deserializer LosFormatter | Security | False | False | The method '{0}' is insecure when deserializing untrusted data. | +40 | [CA2310](https://docs.microsoft.com/visualstudio/code-quality/ca2310-do-not-use-insecure-deserializer-netdatacontractserializer) | Do not use insecure deserializer NetDataContractSerializer | Security | False | False | The method '{0}' is insecure when deserializing untrusted data. If you need to instead detect NetDataContractSerializer deserialization without a SerializationBinder set, then disable rule CA2310, and enable rules CA2311 and CA2312. | +41 | [CA2311](https://docs.microsoft.com/visualstudio/code-quality/ca2311-do-not-deserialize-without-first-setting-netdatacontractserializer-binder) | Do not deserialize without first setting NetDataContractSerializer.Binder | Security | False | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | +42 | [CA2312](https://docs.microsoft.com/visualstudio/code-quality/ca2312-ensure-netdatacontractserializer-binder-is-set-before-deserializing) | Ensure NetDataContractSerializer.Binder is set before deserializing | Security | False | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | +43 | [CA2315](https://docs.microsoft.com/visualstudio/code-quality/ca2315-do-not-use-insecure-deserializer-objectstateformatter) | Do not use insecure deserializer ObjectStateFormatter | Security | False | False | The method '{0}' is insecure when deserializing untrusted data. | +44 | [CA2321](https://docs.microsoft.com/visualstudio/code-quality/ca2321) | Do not deserialize with JavaScriptSerializer using a SimpleTypeResolver | Security | False | False | The method '{0}' is insecure when deserializing untrusted data with a JavaScriptSerializer initialized with a SimpleTypeResolver. Initialize JavaScriptSerializer without a JavaScriptTypeResolver specified, or initialize with a JavaScriptTypeResolver that limits the types of objects in the deserialized object graph. | +45 | [CA2322](https://docs.microsoft.com/visualstudio/code-quality/ca2322) | Ensure JavaScriptSerializer is not initialized with SimpleTypeResolver before deserializing | Security | False | False | The method '{0}' is insecure when deserializing untrusted data with a JavaScriptSerializer initialized with a SimpleTypeResolver. Ensure that the JavaScriptSerializer is initialized without a JavaScriptTypeResolver specified, or initialized with a JavaScriptTypeResolver that limits the types of objects in the deserialized object graph. | +46 | [CA2326](https://docs.microsoft.com/visualstudio/code-quality/ca2326) | Do not use TypeNameHandling values other than None | Security | False | False | Deserializing JSON when using a TypeNameHandling value other than None can be insecure. If you need to instead detect Json.NET deserialization when a SerializationBinder isn't specified, then disable rule CA2326, and enable rules CA2327, CA2328, CA2329, and CA2330. | +47 | [CA2327](https://docs.microsoft.com/visualstudio/code-quality/ca2327) | Do not use insecure JsonSerializerSettings | Security | False | False | When deserializing untrusted input, allowing arbitrary types to be deserialized is insecure. When using JsonSerializerSettings, use TypeNameHandling.None, or for values other than None, restrict deserialized types with a SerializationBinder. | +48 | [CA2328](https://docs.microsoft.com/visualstudio/code-quality/ca2328) | Ensure that JsonSerializerSettings are secure | Security | False | False | When deserializing untrusted input, allowing arbitrary types to be deserialized is insecure. When using JsonSerializerSettings, ensure TypeNameHandling.None is specified, or for values other than None, ensure a SerializationBinder is specified to restrict deserialized types. | +49 | [CA2329](https://docs.microsoft.com/visualstudio/code-quality/ca2329) | Do not deserialize with JsonSerializer using an insecure configuration | Security | False | False | When deserializing untrusted input, allowing arbitrary types to be deserialized is insecure. When using deserializing JsonSerializer, use TypeNameHandling.None, or for values other than None, restrict deserialized types with a SerializationBinder. | +50 | [CA2330](https://docs.microsoft.com/visualstudio/code-quality/ca2330) | Ensure that JsonSerializer has a secure configuration when deserializing | Security | False | False | When deserializing untrusted input, allowing arbitrary types to be deserialized is insecure. When using deserializing JsonSerializer, use TypeNameHandling.None, or for values other than None, restrict deserialized types with a SerializationBinder. | +51 | [CA3001](https://docs.microsoft.com/visualstudio/code-quality/ca3001-review-code-for-sql-injection-vulnerabilities) | Review code for SQL injection vulnerabilities | Security | False | False | Potential SQL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +52 | [CA3002](https://docs.microsoft.com/visualstudio/code-quality/ca3002-review-code-for-xss-vulnerabilities) | Review code for XSS vulnerabilities | Security | False | False | Potential cross-site scripting (XSS) vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +53 | [CA3003](https://docs.microsoft.com/visualstudio/code-quality/ca3003-review-code-for-file-path-injection-vulnerabilities) | Review code for file path injection vulnerabilities | Security | False | False | Potential file path injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +54 | [CA3004](https://docs.microsoft.com/visualstudio/code-quality/ca3004-review-code-for-information-disclosure-vulnerabilities) | Review code for information disclosure vulnerabilities | Security | False | False | Potential information disclosure vulnerability was found where '{0}' in method '{1}' may contain unintended information from '{2}' in method '{3}'. | +55 | [CA3005](https://docs.microsoft.com/visualstudio/code-quality/ca3005-review-code-for-ldap-injection-vulnerabilities) | Review code for LDAP injection vulnerabilities | Security | False | False | Potential LDAP injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +56 | [CA3006](https://docs.microsoft.com/visualstudio/code-quality/ca3006-review-code-for-process-command-injection-vulnerabilities) | Review code for process command injection vulnerabilities | Security | False | False | Potential process command injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +57 | [CA3007](https://docs.microsoft.com/visualstudio/code-quality/ca3007-review-code-for-open-redirect-vulnerabilities) | Review code for open redirect vulnerabilities | Security | False | False | Potential open redirect vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +58 | [CA3008](https://docs.microsoft.com/visualstudio/code-quality/ca3008-review-code-for-xpath-injection-vulnerabilities) | Review code for XPath injection vulnerabilities | Security | False | False | Potential XPath injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +59 | [CA3009](https://docs.microsoft.com/visualstudio/code-quality/ca3009-review-code-for-xml-injection-vulnerabilities) | Review code for XML injection vulnerabilities | Security | False | False | Potential XML injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +60 | [CA3010](https://docs.microsoft.com/visualstudio/code-quality/ca3010-review-code-for-xaml-injection-vulnerabilities) | Review code for XAML injection vulnerabilities | Security | False | False | Potential XAML injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +61 | [CA3011](https://docs.microsoft.com/visualstudio/code-quality/ca3011-review-code-for-dll-injection-vulnerabilities) | Review code for DLL injection vulnerabilities | Security | False | False | Potential DLL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +62 | [CA3012](https://docs.microsoft.com/visualstudio/code-quality/ca3012-review-code-for-regex-injection-vulnerabilities) | Review code for regex injection vulnerabilities | Security | False | False | Potential regex injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | +63 | CA3061 | Do Not Add Schema By URL | Security | True | False | This overload of XmlSchemaCollection.Add method internally enables DTD processing on the XML reader instance used, and uses UrlResolver for resolving external XML entities. The outcome is information disclosure. Content from file system or network shares for the machine processing the XML can be exposed to attacker. In addition, an attacker can use this as a DoS vector. | +64 | [CA5350](https://docs.microsoft.com/visualstudio/code-quality/ca5350-do-not-use-weak-cryptographic-algorithms) | Do Not Use Weak Cryptographic Algorithms | Security | True | False | Cryptographic algorithms degrade over time as attacks become for advances to attacker get access to more computation. Depending on the type and application of this cryptographic algorithm, further degradation of the cryptographic strength of it may allow attackers to read enciphered messages, tamper with enciphered  messages, forge digital signatures, tamper with hashed content, or otherwise compromise any cryptosystem based on this algorithm. Replace encryption uses with the AES algorithm (AES-256, AES-192 and AES-128 are acceptable) with a key length greater than or equal to 128 bits. Replace hashing uses with a hashing function in the SHA-2 family, such as SHA-2 512, SHA-2 384, or SHA-2 256. | +65 | [CA5351](https://docs.microsoft.com/visualstudio/code-quality/ca5351-do-not-use-broken-cryptographic-algorithms) | Do Not Use Broken Cryptographic Algorithms | Security | True | False | An attack making it computationally feasible to break this algorithm exists. This allows attackers to break the cryptographic guarantees it is designed to provide. Depending on the type and application of this cryptographic algorithm, this may allow attackers to read enciphered messages, tamper with enciphered  messages, forge digital signatures, tamper with hashed content, or otherwise compromise any cryptosystem based on this algorithm. Replace encryption uses with the AES algorithm (AES-256, AES-192 and AES-128 are acceptable) with a key length greater than or equal to 128 bits. Replace hashing uses with a hashing function in the SHA-2 family, such as SHA512, SHA384, or SHA256. Replace digital signature uses with RSA with a key length greater than or equal to 2048-bits, or ECDSA with a key length greater than or equal to 256 bits. | +66 | CA5358 | Do Not Use Unsafe Cipher Modes | Security | False | False | These modes are vulnerable to attacks. Use only approved modes (CBC, CTS). | +67 | CA5359 | Do Not Disable Certificate Validation | Security | True | False | A certificate can help authenticate the identity of the server. Clients should validate the server certificate to ensure requests are sent to the intended server. If the ServerCertificateValidationCallback always returns 'true', any certificate will pass validation. | +68 | CA5360 | Do Not Call Dangerous Methods In Deserialization | Security | True | False | Insecure Deserialization is a vulnerability which occurs when untrusted data is used to abuse the logic of an application, inflict a Denial-of-Service (DoS) attack, or even execute arbitrary code upon it being deserialized. It’s frequently possible for malicious users to abuse these deserialization features when the application is deserializing untrusted data which is under their control. Specifically, invoke dangerous methods in the process of deserialization. Successful insecure deserialization attacks could allow an attacker to carry out attacks such as DoS attacks, authentication bypasses, and remote code execution. | +69 | [CA5361](https://docs.microsoft.com/visualstudio/code-quality/ca5361) | Do Not Disable SChannel Use of Strong Crypto | Security | True | False | Starting with the .NET Framework 4.6, the System.Net.ServicePointManager and System.Net.Security.SslStream classes are recommeded to use new protocols. The old ones have protocol weaknesses and are not supported. Setting Switch.System.Net.DontEnableSchUseStrongCrypto with true will use the old weak crypto check and opt out of the protocol migration. | +70 | CA5362 | Do Not Refer Self In Serializable Class | Security | False | False | This can allow an attacker to DOS or exhaust the memory of the process. | +71 | CA5363 | Do Not Disable Request Validation | Security | True | False | Request validation is a feature in ASP.NET that examines HTTP requests and determines whether they contain potentially dangerous content. This check adds protection from markup or code in the URL query string, cookies, or posted form values that might have been added for malicious purposes. So, it is generally desirable and should be left enabled for defense in depth. | +72 | [CA5364](https://docs.microsoft.com/visualstudio/code-quality/ca5364) | Do Not Use Deprecated Security Protocols | Security | True | False | Using a deprecated security protocol rather than the system default is risky. | +73 | CA5365 | Do Not Disable HTTP Header Checking | Security | True | False | HTTP header checking enables encoding of the carriage return and newline characters, \r and \n, that are found in response headers. This encoding can help to avoid injection attacks that exploit an application that echoes untrusted data contained by the header. | +74 | CA5366 | Use XmlReader For DataSet Read Xml | Security | True | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | +75 | CA5367 | Do Not Serialize Types With Pointer Fields | Security | False | False | Pointers are not "type safe" in the sense that you cannot guarantee the correctness of the memory they point at. So, serializing types with pointer fields is dangerous, as it may allow an attacker to control the pointer. | +76 | CA5368 | Set ViewStateUserKey For Classes Derived From Page | Security | True | False | Setting the ViewStateUserKey property can help you prevent attacks on your application by allowing you to assign an identifier to the view-state variable for individual users so that they cannot use the variable to generate an attack. Otherwise, there will be cross-site request forgery vulnerabilities. | +77 | CA5369 | Use XmlReader For Deserialize | Security | True | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | +78 | CA5370 | Use XmlReader For Validating Reader | Security | True | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | +79 | CA5371 | Use XmlReader For Schema Read | Security | True | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | +80 | CA5372 | Use XmlReader For XPathDocument | Security | True | False | Processing XML from untrusted data may load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled. | +81 | CA5373 | Do not use obsolete key derivation function | Security | True | False | Password-based key derivation should use PBKDF2 with SHA-2. Avoid using PasswordDeriveBytes since it generates a PBKDF1 key. Avoid using Rfc2898DeriveBytes.CryptDeriveKey since it doesn't use the iteration count or salt. | +82 | CA5374 | Do Not Use XslTransform | Security | True | False | Do not use XslTransform. It does not restrict potentially dangerous external references. | +83 | CA5375 | Do Not Use Account Shared Access Signature | Security | False | False | Shared Access Signatures(SAS) are a vital part of the security model for any application using Azure Storage, they should provide limited and safe permissions to your storage account to clients that don't have the account key. All of the operations available via a service SAS are also available via an account SAS, that is, account SAS is too powerful. So it is recommended to use Service SAS to delegate access more carefully. | +84 | CA5376 | Use SharedAccessProtocol HttpsOnly | Security | True | False | HTTPS encrypts network traffic. Use HttpsOnly, rather than HttpOrHttps, to ensure network traffic is always encrypted to help prevent disclosure of sensitive data. | +85 | CA5377 | Use Container Level Access Policy | Security | True | False | No access policy identifier is specified, making tokens non-revocable. | +86 | [CA5378](https://docs.microsoft.com/visualstudio/code-quality/ca5378) | Do not disable ServicePointManagerSecurityProtocols | Security | True | False | Do not set Switch.System.ServiceModel.DisableUsingServicePointManagerSecurityProtocols to true. Setting this switch limits Windows Communication Framework (WCF) to using Transport Layer Security (TLS) 1.0, which is insecure and obsolete. | +87 | CA5379 | Do Not Use Weak Key Derivation Function Algorithm | Security | True | False | Some implementations of the Rfc2898DeriveBytes class allow for a hash algorithm to be specified in a constructor parameter or overwritten in the HashAlgorithm property. If a hash algorithm is specified, then it should be SHA-256 or higher. | +88 | CA5380 | Do Not Add Certificates To Root Store | Security | True | False | By default, the Trusted Root Certification Authorities certificate store is configured with a set of public CAs that has met the requirements of the Microsoft Root Certificate Program. Since all trusted root CAs can issue certificates for any domain, an attacker can pick a weak or coercible CA that you install by yourself to target for an attack – and a single vulnerable, malicious or coercible CA undermines the security of the entire system. To make matters worse, these attacks can go unnoticed quite easily. | +89 | CA5381 | Ensure Certificates Are Not Added To Root Store | Security | True | False | By default, the Trusted Root Certification Authorities certificate store is configured with a set of public CAs that has met the requirements of the Microsoft Root Certificate Program. Since all trusted root CAs can issue certificates for any domain, an attacker can pick a weak or coercible CA that you install by yourself to target for an attack – and a single vulnerable, malicious or coercible CA undermines the security of the entire system. To make matters worse, these attacks can go unnoticed quite easily. | +90 | CA5382 | Use Secure Cookies In ASP.Net Core | Security | False | False | Applications available over HTTPS must use secure cookies. | +91 | CA5383 | Ensure Use Secure Cookies In ASP.Net Core | Security | False | False | Applications available over HTTPS must use secure cookies. | +92 | CA5384 | Do Not Use Digital Signature Algorithm (DSA) | Security | True | False | DSA is too weak to use. | +93 | CA5385 | Use Rivest–Shamir–Adleman (RSA) Algorithm With Sufficient Key Size | Security | True | False | Encryption algorithms are vulnerable to brute force attacks when too small a key size is used. | +94 | [CA5386](https://docs.microsoft.com/visualstudio/code-quality/ca5386) | Avoid hardcoding SecurityProtocolType value | Security | False | False | Avoid hardcoding SecurityProtocolType {0}, and instead use SecurityProtocolType.SystemDefault to allow the operating system to choose the best Transport Layer Security protocol to use. | +95 | CA5387 | Do Not Use Weak Key Derivation Function With Insufficient Iteration Count | Security | False | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | +96 | CA5388 | Ensure Sufficient Iteration Count When Using Weak Key Derivation Function | Security | False | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | +97 | CA5389 | Do Not Add Archive Item's Path To The Target File System Path | Security | True | False | When extracting files from an archive and using the archive item's path, check if the path is safe. Archive path can be relative and can lead to file system access outside of the expected file system target path, leading to malicious config changes and remote code execution via lay-and-wait technique. | +98 | CA5390 | Do Not Hard Code Encryption Key | Security | True | False | SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. | +99 | CA5392 | Use DefaultDllImportSearchPaths attribute for P/Invokes | Security | True | False | By default, P/Invokes using DllImportAttribute probe a number of directories, including the current working directory for the library to load. This can be a security issue for certain applications, leading to DLL hijacking. | +100 | CA5393 | Do not use unsafe DllImportSearchPath value | Security | True | False | There could be a malicious DLL in the default DLL search directories. Or, depending on where your application is run from, there could be a malicious DLL in the application's directory. Use a DllImportSearchPath value that specifies an explicit search path instead. The DllImportSearchPath flags that this rule looks for can be configured in .editorconfig. | +101 | CA5394 | Do not use insecure randomness | Security | False | False | {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security | +102 | CA5396 | Set HttpOnly to true for HttpCookie | Security | False | False | As a defense in depth measure, ensure security sensitive HTTP cookies are marked as HttpOnly. This indicates web browsers should disallow scripts from accessing the cookies. Injected malicious scripts are a common way of stealing cookies. | +103 | [CA5397](https://docs.microsoft.com/visualstudio/code-quality/ca5397) | Do not use deprecated SslProtocols values | Security | True | False | Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. | +104 | [CA5398](https://docs.microsoft.com/visualstudio/code-quality/ca5398) | Avoid hardcoded SslProtocols values | Security | False | False | Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. | diff --git a/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.sarif b/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.sarif index 348d89fac4..e4772c66ab 100644 --- a/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.sarif +++ b/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.sarif @@ -208,22 +208,6 @@ ] } }, - "CA1829": { - "id": "CA1829", - "shortDescription": "Use property instead of Count() when available", - "fullDescription": "Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access.", - "defaultLevel": "warning", - "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1829", - "properties": { - "category": "Performance", - "isEnabledByDefault": true, - "typeName": "UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer", - "languages": [ - "C#", - "Visual Basic" - ] - } - }, "CA2000": { "id": "CA2000", "shortDescription": "Dispose objects before losing scope", @@ -1882,6 +1866,21 @@ ] } }, + "CA1829": { + "id": "CA1829", + "shortDescription": "Use Length/Count property instead of Count() when available", + "fullDescription": "Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1829", + "properties": { + "category": "Performance", + "isEnabledByDefault": true, + "typeName": "CSharpUsePropertyInsteadOfCountMethodWhenAvailableAnalyzer", + "languages": [ + "C#" + ] + } + }, "CA2010": { "id": "CA2010", "shortDescription": "Always consume the value returned by methods marked with PreserveSigAttribute", @@ -2047,6 +2046,21 @@ ] } }, + "CA1829": { + "id": "CA1829", + "shortDescription": "Use Length/Count property instead of Count() when available", + "fullDescription": "Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1829", + "properties": { + "category": "Performance", + "isEnabledByDefault": true, + "typeName": "BasicUsePropertyInsteadOfCountMethodWhenAvailableAnalyzer", + "languages": [ + "Visual Basic" + ] + } + }, "CA2010": { "id": "CA2010", "shortDescription": "Always consume the value returned by methods marked with PreserveSigAttribute", diff --git a/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailableTests.cs b/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailableTests.cs index 623f9a02dc..9608eaace7 100644 --- a/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailableTests.cs +++ b/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailableTests.cs @@ -6,10 +6,10 @@ using System.Threading.Tasks; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< - Microsoft.NetCore.Analyzers.Performance.UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer, + Microsoft.NetCore.CSharp.Analyzers.Performance.CSharpUsePropertyInsteadOfCountMethodWhenAvailableAnalyzer, Microsoft.NetCore.CSharp.Analyzers.Performance.CSharpUsePropertyInsteadOfCountMethodWhenAvailableFixer>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< - Microsoft.NetCore.Analyzers.Performance.UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer, + Microsoft.NetCore.VisualBasic.Analyzers.Performance.BasicUsePropertyInsteadOfCountMethodWhenAvailableAnalyzer, Microsoft.NetCore.VisualBasic.Analyzers.Performance.BasicUsePropertyInsteadOfCountMethodWhenAvailableFixer>; namespace Microsoft.NetCore.Analyzers.Performance.UnitTests diff --git a/src/Microsoft.NetCore.Analyzers/VisualBasic/Performance/BasicUsePropertyInsteadOfCountMethodWhenAvailable.vb b/src/Microsoft.NetCore.Analyzers/VisualBasic/Performance/BasicUsePropertyInsteadOfCountMethodWhenAvailable.vb new file mode 100644 index 0000000000..518fa27037 --- /dev/null +++ b/src/Microsoft.NetCore.Analyzers/VisualBasic/Performance/BasicUsePropertyInsteadOfCountMethodWhenAvailable.vb @@ -0,0 +1,57 @@ +' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +Imports Microsoft.CodeAnalysis +Imports Microsoft.CodeAnalysis.Diagnostics +Imports Microsoft.CodeAnalysis.Operations +Imports Microsoft.NetCore.Analyzers.Performance + +Namespace Microsoft.NetCore.VisualBasic.Analyzers.Performance + + + Public NotInheritable Class BasicUsePropertyInsteadOfCountMethodWhenAvailableAnalyzer + Inherits UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer + + Protected Overrides Function CreateOperationActionsHandler(context As OperationActionsContext) As OperationActionsHandler + + Return New BasicOperationActionsHandler(context) + + End Function + + Private NotInheritable Class BasicOperationActionsHandler + Inherits OperationActionsHandler + + Public Sub New(context As OperationActionsContext) + MyBase.New(context) + End Sub + + Protected Overrides Function GetEnumerableCountInvocationTargetType(invocationOperation As IInvocationOperation) As ITypeSymbol + + Dim method = invocationOperation.TargetMethod + + If invocationOperation.Arguments.Length = 0 AndAlso + method.Name.Equals(NameOf(Enumerable.Count), StringComparison.Ordinal) AndAlso + Me.Context.IsEnumerableType(method.ContainingSymbol) Then + + Dim methodSourceItemType = TryCast(DirectCast(invocationOperation.Instance.Type, INamedTypeSymbol).TypeArguments.Item(0), ITypeSymbol) + + If Not methodSourceItemType Is Nothing Then + + Dim convertionOperation = TryCast(invocationOperation.Instance, IConversionOperation) + + Return If(Not convertionOperation Is Nothing, + convertionOperation.Operand.Type, + invocationOperation.Instance.Type) + + End If + + End If + + Return Nothing + + End Function + + End Class + + End Class + +End Namespace From aa4f8da17984acd949049e0a9f078fe82f763134 Mon Sep 17 00:00:00 2001 From: paulomorgado <470455+paulomorgado@users.noreply.github.com> Date: Wed, 28 Aug 2019 23:32:59 +0100 Subject: [PATCH 09/11] update documentation --- .../Microsoft.CodeAnalysis.FxCopAnalyzers.md | 16 ++- ...icrosoft.CodeAnalysis.FxCopAnalyzers.sarif | 128 ++++++++++-------- .../Microsoft.NetCore.Analyzers.md | 14 +- .../Microsoft.NetCore.Analyzers.sarif | 128 ++++++++++-------- 4 files changed, 153 insertions(+), 133 deletions(-) diff --git a/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.md b/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.md index 1d3297e105..c5b5ae1340 100644 --- a/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.md +++ b/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.md @@ -191,10 +191,12 @@ Sr. No. | Rule ID | Title | Category | Enabled | CodeFix | Description | 188 | CA5388 | Ensure Sufficient Iteration Count When Using Weak Key Derivation Function | Security | False | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | 189 | CA5389 | Do Not Add Archive Item's Path To The Target File System Path | Security | True | False | When extracting files from an archive and using the archive item's path, check if the path is safe. Archive path can be relative and can lead to file system access outside of the expected file system target path, leading to malicious config changes and remote code execution via lay-and-wait technique. | 190 | CA5390 | Do Not Hard Code Encryption Key | Security | True | False | SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. | -191 | CA5392 | Use DefaultDllImportSearchPaths attribute for P/Invokes | Security | True | False | By default, P/Invokes using DllImportAttribute probe a number of directories, including the current working directory for the library to load. This can be a security issue for certain applications, leading to DLL hijacking. | -192 | CA5393 | Do not use unsafe DllImportSearchPath value | Security | True | False | There could be a malicious DLL in the default DLL search directories. Or, depending on where your application is run from, there could be a malicious DLL in the application's directory. Use a DllImportSearchPath value that specifies an explicit search path instead. The DllImportSearchPath flags that this rule looks for can be configured in .editorconfig. | -193 | CA5394 | Do not use insecure randomness | Security | False | False | {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security | -194 | CA5396 | Set HttpOnly to true for HttpCookie | Security | False | False | As a defense in depth measure, ensure security sensitive HTTP cookies are marked as HttpOnly. This indicates web browsers should disallow scripts from accessing the cookies. Injected malicious scripts are a common way of stealing cookies. | -195 | [CA5397](https://docs.microsoft.com/visualstudio/code-quality/ca5397) | Do not use deprecated SslProtocols values | Security | True | False | Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. | -196 | [CA5398](https://docs.microsoft.com/visualstudio/code-quality/ca5398) | Avoid hardcoded SslProtocols values | Security | False | False | Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. | -197 | CA9999 | Analyzer version mismatch | Reliability | True | False | Analyzers in this package require a certain minimum version of Microsoft.CodeAnalysis to execute correctly. Refer to https://docs.microsoft.com/visualstudio/code-quality/install-fxcop-analyzers#fxcopanalyzers-package-versions to install the correct analyzer version. | +191 | CA5391 | Use antiforgery tokens in ASP.NET Core MVC controllers | Security | True | False | Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. | +192 | CA5392 | Use DefaultDllImportSearchPaths attribute for P/Invokes | Security | True | False | By default, P/Invokes using DllImportAttribute probe a number of directories, including the current working directory for the library to load. This can be a security issue for certain applications, leading to DLL hijacking. | +193 | CA5393 | Do not use unsafe DllImportSearchPath value | Security | True | False | There could be a malicious DLL in the default DLL search directories. Or, depending on where your application is run from, there could be a malicious DLL in the application's directory. Use a DllImportSearchPath value that specifies an explicit search path instead. The DllImportSearchPath flags that this rule looks for can be configured in .editorconfig. | +194 | CA5394 | Do not use insecure randomness | Security | False | False | {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security | +195 | CA5395 | Miss HttpVerb attribute for action methods | Security | False | False | All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost] overload of the method, which needs to be protected with the anti forgery attribute from request forgery. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data. | +196 | CA5396 | Set HttpOnly to true for HttpCookie | Security | False | False | As a defense in depth measure, ensure security sensitive HTTP cookies are marked as HttpOnly. This indicates web browsers should disallow scripts from accessing the cookies. Injected malicious scripts are a common way of stealing cookies. | +197 | [CA5397](https://docs.microsoft.com/visualstudio/code-quality/ca5397) | Do not use deprecated SslProtocols values | Security | True | False | Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. | +198 | [CA5398](https://docs.microsoft.com/visualstudio/code-quality/ca5398) | Avoid hardcoded SslProtocols values | Security | False | False | Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. | +199 | CA9999 | Analyzer version mismatch | Reliability | True | False | Analyzers in this package require a certain minimum version of Microsoft.CodeAnalysis to execute correctly. Refer to https://docs.microsoft.com/visualstudio/code-quality/install-fxcop-analyzers#fxcopanalyzers-package-versions to install the correct analyzer version. | diff --git a/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.sarif b/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.sarif index 6a80facaf2..2e4660c087 100644 --- a/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.sarif +++ b/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.sarif @@ -2128,6 +2128,38 @@ ] } }, + "CA1827": { + "id": "CA1827", + "shortDescription": "Do not use Count() or LongCount() when Any() can be used", + "fullDescription": "For non-empty collections, Count() and LongCount() enumerate the entire sequence, while Any() stops at the first item or the first item that satisfies a condition.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1827", + "properties": { + "category": "Performance", + "isEnabledByDefault": true, + "typeName": "DoNotUseCountWhenAnyCanBeUsedAnalyzer", + "languages": [ + "C#", + "Visual Basic" + ] + } + }, + "CA1828": { + "id": "CA1828", + "shortDescription": "Do not use CountAsync() or LongCountAsync() when AnyAsync() can be used", + "fullDescription": "For non-empty collections, CountAsync() and LongCountAsync() enumerate the entire sequence, while AnyAsync() stops at the first item or the first item that satisfies a condition.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1828", + "properties": { + "category": "Performance", + "isEnabledByDefault": true, + "typeName": "DoNotUseCountWhenAnyCanBeUsedAnalyzer", + "languages": [ + "C#", + "Visual Basic" + ] + } + }, "CA2000": { "id": "CA2000", "shortDescription": "Dispose objects before losing scope", @@ -3565,6 +3597,24 @@ ] } }, + "CA5391": { + "id": "CA5391", + "shortDescription": "Use antiforgery tokens in ASP.NET Core MVC controllers", + "fullDescription": "Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller.", + "defaultLevel": "warning", + "properties": { + "category": "Security", + "isEnabledByDefault": true, + "typeName": "UseAutoValidateAntiforgeryToken", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, "CA5392": { "id": "CA5392", "shortDescription": "Use DefaultDllImportSearchPaths attribute for P/Invokes", @@ -3619,6 +3669,24 @@ ] } }, + "CA5395": { + "id": "CA5395", + "shortDescription": "Miss HttpVerb attribute for action methods", + "fullDescription": "All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost] overload of the method, which needs to be protected with the anti forgery attribute from request forgery. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data.", + "defaultLevel": "warning", + "properties": { + "category": "Security", + "isEnabledByDefault": false, + "typeName": "UseAutoValidateAntiforgeryToken", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, "CA5396": { "id": "CA5396", "shortDescription": "Set HttpOnly to true for HttpCookie", @@ -3756,36 +3824,6 @@ ] } }, - "CA1827": { - "id": "CA1827", - "shortDescription": "Do not use Count() or LongCount() when Any() can be used", - "fullDescription": "For non-empty collections, Count() and LongCount() enumerate the entire sequence, while Any() stops at the first item or the first item that satisfies a condition.", - "defaultLevel": "warning", - "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1827", - "properties": { - "category": "Performance", - "isEnabledByDefault": true, - "typeName": "CSharpDoNotUseCountWhenAnyCanBeUsedAnalyzer", - "languages": [ - "C#" - ] - } - }, - "CA1828": { - "id": "CA1828", - "shortDescription": "Do not use CountAsync() or LongCountAsync() when AnyAsync() can be used", - "fullDescription": "For non-empty collections, CountAsync() and LongCountAsync() enumerate the entire sequence, while AnyAsync() stops at the first item or the first item that satisfies a condition.", - "defaultLevel": "warning", - "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1828", - "properties": { - "category": "Performance", - "isEnabledByDefault": true, - "typeName": "CSharpDoNotUseCountWhenAnyCanBeUsedAnalyzer", - "languages": [ - "C#" - ] - } - }, "CA1829": { "id": "CA1829", "shortDescription": "Use Length/Count property instead of Count() when available", @@ -3936,36 +3974,6 @@ ] } }, - "CA1827": { - "id": "CA1827", - "shortDescription": "Do not use Count() or LongCount() when Any() can be used", - "fullDescription": "For non-empty collections, Count() and LongCount() enumerate the entire sequence, while Any() stops at the first item or the first item that satisfies a condition.", - "defaultLevel": "warning", - "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1827", - "properties": { - "category": "Performance", - "isEnabledByDefault": true, - "typeName": "BasicDoNotUseCountWhenAnyCanBeUsedAnalyzer", - "languages": [ - "Visual Basic" - ] - } - }, - "CA1828": { - "id": "CA1828", - "shortDescription": "Do not use CountAsync() or LongCountAsync() when AnyAsync() can be used", - "fullDescription": "For non-empty collections, CountAsync() and LongCountAsync() enumerate the entire sequence, while AnyAsync() stops at the first item or the first item that satisfies a condition.", - "defaultLevel": "warning", - "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1828", - "properties": { - "category": "Performance", - "isEnabledByDefault": true, - "typeName": "BasicDoNotUseCountWhenAnyCanBeUsedAnalyzer", - "languages": [ - "Visual Basic" - ] - } - }, "CA1829": { "id": "CA1829", "shortDescription": "Use Length/Count property instead of Count() when available", diff --git a/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.md b/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.md index 73a41f9af9..8436688850 100644 --- a/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.md +++ b/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.md @@ -99,9 +99,11 @@ Sr. No. | Rule ID | Title | Category | Enabled | CodeFix | Description | 96 | CA5388 | Ensure Sufficient Iteration Count When Using Weak Key Derivation Function | Security | False | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | 97 | CA5389 | Do Not Add Archive Item's Path To The Target File System Path | Security | True | False | When extracting files from an archive and using the archive item's path, check if the path is safe. Archive path can be relative and can lead to file system access outside of the expected file system target path, leading to malicious config changes and remote code execution via lay-and-wait technique. | 98 | CA5390 | Do Not Hard Code Encryption Key | Security | True | False | SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. | -99 | CA5392 | Use DefaultDllImportSearchPaths attribute for P/Invokes | Security | True | False | By default, P/Invokes using DllImportAttribute probe a number of directories, including the current working directory for the library to load. This can be a security issue for certain applications, leading to DLL hijacking. | -100 | CA5393 | Do not use unsafe DllImportSearchPath value | Security | True | False | There could be a malicious DLL in the default DLL search directories. Or, depending on where your application is run from, there could be a malicious DLL in the application's directory. Use a DllImportSearchPath value that specifies an explicit search path instead. The DllImportSearchPath flags that this rule looks for can be configured in .editorconfig. | -101 | CA5394 | Do not use insecure randomness | Security | False | False | {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security | -102 | CA5396 | Set HttpOnly to true for HttpCookie | Security | False | False | As a defense in depth measure, ensure security sensitive HTTP cookies are marked as HttpOnly. This indicates web browsers should disallow scripts from accessing the cookies. Injected malicious scripts are a common way of stealing cookies. | -103 | [CA5397](https://docs.microsoft.com/visualstudio/code-quality/ca5397) | Do not use deprecated SslProtocols values | Security | True | False | Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. | -104 | [CA5398](https://docs.microsoft.com/visualstudio/code-quality/ca5398) | Avoid hardcoded SslProtocols values | Security | False | False | Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. | +99 | CA5391 | Use antiforgery tokens in ASP.NET Core MVC controllers | Security | True | False | Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. | +100 | CA5392 | Use DefaultDllImportSearchPaths attribute for P/Invokes | Security | True | False | By default, P/Invokes using DllImportAttribute probe a number of directories, including the current working directory for the library to load. This can be a security issue for certain applications, leading to DLL hijacking. | +101 | CA5393 | Do not use unsafe DllImportSearchPath value | Security | True | False | There could be a malicious DLL in the default DLL search directories. Or, depending on where your application is run from, there could be a malicious DLL in the application's directory. Use a DllImportSearchPath value that specifies an explicit search path instead. The DllImportSearchPath flags that this rule looks for can be configured in .editorconfig. | +102 | CA5394 | Do not use insecure randomness | Security | False | False | {0} is an insecure random number generator. Use cryptographically secure random number generators when randomness is required for security | +103 | CA5395 | Miss HttpVerb attribute for action methods | Security | False | False | All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost] overload of the method, which needs to be protected with the anti forgery attribute from request forgery. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data. | +104 | CA5396 | Set HttpOnly to true for HttpCookie | Security | False | False | As a defense in depth measure, ensure security sensitive HTTP cookies are marked as HttpOnly. This indicates web browsers should disallow scripts from accessing the cookies. Injected malicious scripts are a common way of stealing cookies. | +105 | [CA5397](https://docs.microsoft.com/visualstudio/code-quality/ca5397) | Do not use deprecated SslProtocols values | Security | True | False | Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. | +106 | [CA5398](https://docs.microsoft.com/visualstudio/code-quality/ca5398) | Avoid hardcoded SslProtocols values | Security | False | False | Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. | diff --git a/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.sarif b/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.sarif index e4772c66ab..430d81e12d 100644 --- a/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.sarif +++ b/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.sarif @@ -208,6 +208,38 @@ ] } }, + "CA1827": { + "id": "CA1827", + "shortDescription": "Do not use Count() or LongCount() when Any() can be used", + "fullDescription": "For non-empty collections, Count() and LongCount() enumerate the entire sequence, while Any() stops at the first item or the first item that satisfies a condition.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1827", + "properties": { + "category": "Performance", + "isEnabledByDefault": true, + "typeName": "DoNotUseCountWhenAnyCanBeUsedAnalyzer", + "languages": [ + "C#", + "Visual Basic" + ] + } + }, + "CA1828": { + "id": "CA1828", + "shortDescription": "Do not use CountAsync() or LongCountAsync() when AnyAsync() can be used", + "fullDescription": "For non-empty collections, CountAsync() and LongCountAsync() enumerate the entire sequence, while AnyAsync() stops at the first item or the first item that satisfies a condition.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1828", + "properties": { + "category": "Performance", + "isEnabledByDefault": true, + "typeName": "DoNotUseCountWhenAnyCanBeUsedAnalyzer", + "languages": [ + "C#", + "Visual Basic" + ] + } + }, "CA2000": { "id": "CA2000", "shortDescription": "Dispose objects before losing scope", @@ -1645,6 +1677,24 @@ ] } }, + "CA5391": { + "id": "CA5391", + "shortDescription": "Use antiforgery tokens in ASP.NET Core MVC controllers", + "fullDescription": "Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller.", + "defaultLevel": "warning", + "properties": { + "category": "Security", + "isEnabledByDefault": true, + "typeName": "UseAutoValidateAntiforgeryToken", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, "CA5392": { "id": "CA5392", "shortDescription": "Use DefaultDllImportSearchPaths attribute for P/Invokes", @@ -1699,6 +1749,24 @@ ] } }, + "CA5395": { + "id": "CA5395", + "shortDescription": "Miss HttpVerb attribute for action methods", + "fullDescription": "All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost] overload of the method, which needs to be protected with the anti forgery attribute from request forgery. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data.", + "defaultLevel": "warning", + "properties": { + "category": "Security", + "isEnabledByDefault": false, + "typeName": "UseAutoValidateAntiforgeryToken", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, "CA5396": { "id": "CA5396", "shortDescription": "Set HttpOnly to true for HttpCookie", @@ -1836,36 +1904,6 @@ ] } }, - "CA1827": { - "id": "CA1827", - "shortDescription": "Do not use Count() or LongCount() when Any() can be used", - "fullDescription": "For non-empty collections, Count() and LongCount() enumerate the entire sequence, while Any() stops at the first item or the first item that satisfies a condition.", - "defaultLevel": "warning", - "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1827", - "properties": { - "category": "Performance", - "isEnabledByDefault": true, - "typeName": "CSharpDoNotUseCountWhenAnyCanBeUsedAnalyzer", - "languages": [ - "C#" - ] - } - }, - "CA1828": { - "id": "CA1828", - "shortDescription": "Do not use CountAsync() or LongCountAsync() when AnyAsync() can be used", - "fullDescription": "For non-empty collections, CountAsync() and LongCountAsync() enumerate the entire sequence, while AnyAsync() stops at the first item or the first item that satisfies a condition.", - "defaultLevel": "warning", - "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1828", - "properties": { - "category": "Performance", - "isEnabledByDefault": true, - "typeName": "CSharpDoNotUseCountWhenAnyCanBeUsedAnalyzer", - "languages": [ - "C#" - ] - } - }, "CA1829": { "id": "CA1829", "shortDescription": "Use Length/Count property instead of Count() when available", @@ -2016,36 +2054,6 @@ ] } }, - "CA1827": { - "id": "CA1827", - "shortDescription": "Do not use Count() or LongCount() when Any() can be used", - "fullDescription": "For non-empty collections, Count() and LongCount() enumerate the entire sequence, while Any() stops at the first item or the first item that satisfies a condition.", - "defaultLevel": "warning", - "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1827", - "properties": { - "category": "Performance", - "isEnabledByDefault": true, - "typeName": "BasicDoNotUseCountWhenAnyCanBeUsedAnalyzer", - "languages": [ - "Visual Basic" - ] - } - }, - "CA1828": { - "id": "CA1828", - "shortDescription": "Do not use CountAsync() or LongCountAsync() when AnyAsync() can be used", - "fullDescription": "For non-empty collections, CountAsync() and LongCountAsync() enumerate the entire sequence, while AnyAsync() stops at the first item or the first item that satisfies a condition.", - "defaultLevel": "warning", - "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1828", - "properties": { - "category": "Performance", - "isEnabledByDefault": true, - "typeName": "BasicDoNotUseCountWhenAnyCanBeUsedAnalyzer", - "languages": [ - "Visual Basic" - ] - } - }, "CA1829": { "id": "CA1829", "shortDescription": "Use Length/Count property instead of Count() when available", From 490072391da1fee9823ac861f180f1696601f0da Mon Sep 17 00:00:00 2001 From: paulomorgado <470455+paulomorgado@users.noreply.github.com> Date: Mon, 9 Sep 2019 15:56:42 +0100 Subject: [PATCH 10/11] changed resolution of ICollection.Count from LINQ to foreach. simplified detection of Enumerable.Count() invoction. split VB test for clarity --- ...InsteadOfCountMethodWhenAvailable.Fixer.cs | 4 +- ...opertyInsteadOfCountMethodWhenAvailable.cs | 12 ++- ...InsteadOfCountMethodWhenAvailable.Fixer.cs | 42 ++++---- ...opertyInsteadOfCountMethodWhenAvailable.cs | 98 ++++++++++++++++++- ...yInsteadOfCountMethodWhenAvailableTests.cs | 19 +++- ...InsteadOfCountMethodWhenAvailable.Fixer.vb | 4 +- ...opertyInsteadOfCountMethodWhenAvailable.vb | 41 ++++++-- 7 files changed, 183 insertions(+), 37 deletions(-) diff --git a/src/Microsoft.NetCore.Analyzers/CSharp/Performance/CSharpUsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs b/src/Microsoft.NetCore.Analyzers/CSharp/Performance/CSharpUsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs index ef11cc2bae..99bf9b2f2a 100644 --- a/src/Microsoft.NetCore.Analyzers/CSharp/Performance/CSharpUsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs +++ b/src/Microsoft.NetCore.Analyzers/CSharp/Performance/CSharpUsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs @@ -9,8 +9,10 @@ namespace Microsoft.NetCore.CSharp.Analyzers.Performance { /// - /// CA1829: Use property instead of , when available. + /// CA1829: C# implementation of use property instead of , when available. + /// Implements the /// + /// [ExportCodeFixProvider(LanguageNames.CSharp), Shared] public sealed class CSharpUsePropertyInsteadOfCountMethodWhenAvailableFixer : UsePropertyInsteadOfCountMethodWhenAvailableFixer { diff --git a/src/Microsoft.NetCore.Analyzers/CSharp/Performance/CSharpUsePropertyInsteadOfCountMethodWhenAvailable.cs b/src/Microsoft.NetCore.Analyzers/CSharp/Performance/CSharpUsePropertyInsteadOfCountMethodWhenAvailable.cs index ba268835cb..f33002576d 100644 --- a/src/Microsoft.NetCore.Analyzers/CSharp/Performance/CSharpUsePropertyInsteadOfCountMethodWhenAvailable.cs +++ b/src/Microsoft.NetCore.Analyzers/CSharp/Performance/CSharpUsePropertyInsteadOfCountMethodWhenAvailable.cs @@ -9,6 +9,15 @@ namespace Microsoft.NetCore.CSharp.Analyzers.Performance { + /// + /// CA1829: C# implementation of use property instead of , when available. + /// Implements the + /// + /// + /// Flags the use of on types that are know to have a property with the same semantics: + /// Length, Count. + /// + /// [DiagnosticAnalyzer(LanguageNames.CSharp)] public sealed class CSharpUsePropertyInsteadOfCountMethodWhenAvailableAnalyzer : UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer @@ -39,8 +48,7 @@ protected override ITypeSymbol GetEnumerableCountInvocationTargetType(IInvocatio if (invocationOperation.Arguments.Length == 1 && method.Name.Equals(nameof(Enumerable.Count), StringComparison.Ordinal) && - this.Context.IsEnumerableType(method.ContainingSymbol) && - ((INamedTypeSymbol)(method.Parameters[0].Type)).TypeArguments[0] is ITypeSymbol methodSourceItemType) + this.Context.IsEnumerableType(method.ContainingSymbol)) { return invocationOperation.Arguments[0].Value is IConversionOperation convertionOperation ? convertionOperation.Operand.Type diff --git a/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs b/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs index c08de574a3..121f92316e 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs @@ -11,11 +11,10 @@ using Microsoft.CodeAnalysis.Formatting; namespace Microsoft.NetCore.Analyzers.Performance - { /// /// CA1829: Use property instead of , when available. - /// Implements the + /// Implements the /// public abstract class UsePropertyInsteadOfCountMethodWhenAvailableFixer : CodeFixProvider { @@ -72,13 +71,19 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) /// otherwise. protected abstract bool TryGetExpression(SyntaxNode invocationNode, out SyntaxNode memberAccessNode, out SyntaxNode nameNode); - private class UsePropertyInsteadOfCountMethodWhenAvailableCodeAction : CodeAction + /// + /// Implements the for replacing the use of + /// for the use of a property of the receiving type. + /// This class cannot be inherited. + /// + /// + private sealed class UsePropertyInsteadOfCountMethodWhenAvailableCodeAction : CodeAction { - private readonly Document document; - private readonly SyntaxNode invocationNode; - private readonly SyntaxNode memberAccessNode; - private readonly SyntaxNode nameNode; - private readonly string propertyName; + private readonly Document _document; + private readonly SyntaxNode _invocationNode; + private readonly SyntaxNode _memberAccessNode; + private readonly SyntaxNode _nameNode; + private readonly string _propertyName; public UsePropertyInsteadOfCountMethodWhenAvailableCodeAction( Document document, @@ -87,26 +92,29 @@ private class UsePropertyInsteadOfCountMethodWhenAvailableCodeAction : CodeActio SyntaxNode nameNode, string propertyName) { - this.document = document; - this.invocationNode = invocationNode; - this.memberAccessNode = memberAccessNode; - this.nameNode = nameNode; - this.propertyName = propertyName; + this._document = document; + this._invocationNode = invocationNode; + this._memberAccessNode = memberAccessNode; + this._nameNode = nameNode; + this._propertyName = propertyName; } + /// public override string Title { get; } = MicrosoftNetCoreAnalyzersResources.UsePropertyInsteadOfCountMethodWhenAvailableTitle; + /// public override string EquivalenceKey { get; } = MicrosoftNetCoreAnalyzersResources.UsePropertyInsteadOfCountMethodWhenAvailableTitle; + /// protected sealed override async Task GetChangedDocumentAsync(CancellationToken cancellationToken) { - var editor = await DocumentEditor.CreateAsync(this.document, cancellationToken).ConfigureAwait(false); + var editor = await DocumentEditor.CreateAsync(this._document, cancellationToken).ConfigureAwait(false); var generator = editor.Generator; - var replacementSyntax = generator.ReplaceNode(this.memberAccessNode, this.nameNode, generator.IdentifierName(propertyName)) + var replacementSyntax = generator.ReplaceNode(this._memberAccessNode, this._nameNode, generator.IdentifierName(_propertyName)) .WithAdditionalAnnotations(Formatter.Annotation) - .WithTriviaFrom(this.invocationNode); + .WithTriviaFrom(this._invocationNode); - editor.ReplaceNode(this.invocationNode, replacementSyntax); + editor.ReplaceNode(this._invocationNode, replacementSyntax); return editor.GetChangedDocument(); } diff --git a/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs b/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs index a26f3fc693..b7954427a2 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs @@ -12,13 +12,12 @@ namespace Microsoft.NetCore.Analyzers.Performance { /// /// CA1829: Use property instead of , when available. - /// Implements the + /// Implements the /// /// /// Flags the use of on types that are know to have a property with the same semantics: /// Length, Count. /// - [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public abstract class UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer : DiagnosticAnalyzer { internal const string RuleId = "CA1829"; @@ -66,7 +65,7 @@ private void OnCompilationStart(CompilationStartAnalysisContext context) { if (WellKnownTypes.Enumerable(context.Compilation) is INamedTypeSymbol enumerableType) { - var operationActionsContext = new UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer.OperationActionsContext( + var operationActionsContext = new OperationActionsContext( context.Compilation, enumerableType); @@ -83,42 +82,110 @@ private void OnCompilationStart(CompilationStartAnalysisContext context) /// The operation actions handler. protected abstract OperationActionsHandler CreateOperationActionsHandler(OperationActionsContext context); + /// + /// Holds the and helper methods. + /// protected sealed class OperationActionsContext { private readonly Lazy _immutableArrayType; private readonly Lazy _iCollectionCountProperty; private readonly Lazy _iCollectionOfType; + /// + /// Initializes a new instance of the class. + /// + /// The compilation. + /// Type of the enumerable. public OperationActionsContext(Compilation compilation, INamedTypeSymbol enumerableType) { Compilation = compilation; EnumerableType = enumerableType; _immutableArrayType = new Lazy(() => WellKnownTypes.ImmutableArray(Compilation), true); - _iCollectionCountProperty = new Lazy(() => WellKnownTypes.ICollection(Compilation)?.GetMembers(CountPropertyName).OfType().Single(), true); + _iCollectionCountProperty = new Lazy(ResolveICollectionCountProperty, true); _iCollectionOfType = new Lazy(() => WellKnownTypes.GenericICollection(Compilation), true); } + /// + /// Gets the . + /// + /// The . internal Compilation Compilation { get; } private INamedTypeSymbol EnumerableType { get; } + /// + /// Gets the property. + /// + /// The property. private IPropertySymbol ICollectionCountProperty => _iCollectionCountProperty.Value; + /// + /// Gets the type of the type. + /// + /// The type. private INamedTypeSymbol ICollectionOfTType => _iCollectionOfType.Value; + /// + /// Gets the type of the type. + /// + /// The type. internal INamedTypeSymbol ImmutableArrayType => _immutableArrayType.Value; + /// + /// Gets the type of the property, if one and only one exists. + /// + /// The property. + private IPropertySymbol ResolveICollectionCountProperty() + { + IPropertySymbol countProperty = null; + + if (WellKnownTypes.ICollection(Compilation) is INamedTypeSymbol iCollectionType) + { + foreach (var member in iCollectionType.GetMembers()) + { + if (member is IPropertySymbol property && property.Name.Equals(CountPropertyName, StringComparison.Ordinal)) + { + if (countProperty is null) + { + countProperty = property; + } + else + { + return null; + } + } + } + } + + return countProperty; + } + + /// + /// Determines whether the specified type symbol is the immutable array generic type. + /// + /// The type symbol. + /// if the specified type symbol is the immutable array generic type; otherwise, . internal bool IsImmutableArrayType(ITypeSymbol typeSymbol) => this.ImmutableArrayType is object && typeSymbol is INamedTypeSymbol namedTypeSymbol && namedTypeSymbol.ConstructedFrom is INamedTypeSymbol constructedFrom && constructedFrom.Equals(this.ImmutableArrayType); + /// + /// Determines whether the specified invocation target implements . + /// + /// The invocation target. + /// if the specified invocation target implements ; otherwise, . internal bool IsICollectionImplementation(ITypeSymbol invocationTarget) => this.ICollectionCountProperty is object && invocationTarget.FindImplementationForInterfaceMember(this.ICollectionCountProperty) is IPropertySymbol countProperty && !countProperty.ExplicitInterfaceImplementations.Any(); + /// + /// Determines whether the specified invocation target implements System.Collections.Generic.ICollection{TSource}. + /// + /// The invocation target. + /// if the specified invocation target implements System.Collections.Generic.ICollection{TSource}; otherwise, . internal bool IsICollectionOfTImplementation(ITypeSymbol invocationTarget) { if (ICollectionOfTType is null) @@ -169,6 +236,11 @@ bool isCollectionOfTInterface(ITypeSymbol type) => this.ICollectionOfTType.Equals(type.OriginalDefinition); } + /// + /// Determines whether [is enumerable type] [the specified symbol]. + /// + /// The symbol. + /// if [is enumerable type] [the specified symbol]; otherwise, . internal bool IsEnumerableType(ISymbol symbol) => this.EnumerableType.Equals(symbol); } @@ -178,11 +250,19 @@ internal bool IsEnumerableType(ISymbol symbol) /// protected abstract class OperationActionsHandler { + /// + /// Initializes a new instance of the class. + /// + /// The context. protected OperationActionsHandler(OperationActionsContext context) { Context = context; } + /// + /// Gets the context. + /// + /// The context. protected OperationActionsContext Context { get; } internal void AnalyzeInvocationOperation(OperationAnalysisContext context) @@ -205,8 +285,18 @@ internal void AnalyzeInvocationOperation(OperationAnalysisContext context) } } + /// + /// Gets the type of the receiver of the . + /// + /// The invocation operation. + /// The of the receiver of the extension method. protected abstract ITypeSymbol GetEnumerableCountInvocationTargetType(IInvocationOperation invocationOperation); + /// + /// Gets the replacement property. + /// + /// The invocation target. + /// The name of the replacement property. private string GetReplacementProperty(ITypeSymbol invocationTarget) { if ((invocationTarget.TypeKind == TypeKind.Array) || Context.IsImmutableArrayType(invocationTarget)) diff --git a/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailableTests.cs b/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailableTests.cs index 9608eaace7..7bbc902109 100644 --- a/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailableTests.cs +++ b/src/Microsoft.NetCore.Analyzers/UnitTests/Performance/UsePropertyInsteadOfCountMethodWhenAvailableTests.cs @@ -229,14 +229,29 @@ public static class C public static {type} GetData() => default; public static int M() => GetData().Count(); }} +"); + + [Theory] + [InlineData("System.Collections.Generic.IEnumerable(Of Integer)")] + public static Task Basic_NoDiagnostic(string type) + => VerifyVB.VerifyAnalyzerAsync( + $@"Imports System +Imports System.Linq +Public Module M + Public Function GetData() As {type} + Return Nothing + End Function + Public Function F() As Integer + Return GetData().Count() + End Function +End Module "); [Theory] [InlineData("System.Collections.Generic.List(Of Integer)")] [InlineData("System.Collections.Generic.IList(Of Integer)")] [InlineData("System.Collections.Generic.ICollection(Of Integer)")] - [InlineData("System.Collections.Generic.IEnumerable(Of Integer)")] - public static Task Basic_NoDiagnostic(string type) + public static Task Basic_PropertyInvocationWithParenthesis_NoDiagnostic(string type) => VerifyVB.VerifyAnalyzerAsync( $@"Imports System Imports System.Linq diff --git a/src/Microsoft.NetCore.Analyzers/VisualBasic/Performance/BasicUsePropertyInsteadOfCountMethodWhenAvailable.Fixer.vb b/src/Microsoft.NetCore.Analyzers/VisualBasic/Performance/BasicUsePropertyInsteadOfCountMethodWhenAvailable.Fixer.vb index 53d29448a0..5cca85be15 100644 --- a/src/Microsoft.NetCore.Analyzers/VisualBasic/Performance/BasicUsePropertyInsteadOfCountMethodWhenAvailable.Fixer.vb +++ b/src/Microsoft.NetCore.Analyzers/VisualBasic/Performance/BasicUsePropertyInsteadOfCountMethodWhenAvailable.Fixer.vb @@ -9,8 +9,10 @@ Imports Microsoft.NetCore.Analyzers.Performance Namespace Microsoft.NetCore.VisualBasic.Analyzers.Performance ''' - ''' CA1829: Use property instead of , when available. + ''' CA1829: C# implementation Of use Property instead Of , When available. + ''' Implements the ''' + ''' Public NotInheritable Class BasicUsePropertyInsteadOfCountMethodWhenAvailableFixer Inherits UsePropertyInsteadOfCountMethodWhenAvailableFixer diff --git a/src/Microsoft.NetCore.Analyzers/VisualBasic/Performance/BasicUsePropertyInsteadOfCountMethodWhenAvailable.vb b/src/Microsoft.NetCore.Analyzers/VisualBasic/Performance/BasicUsePropertyInsteadOfCountMethodWhenAvailable.vb index 518fa27037..a37fcab8a0 100644 --- a/src/Microsoft.NetCore.Analyzers/VisualBasic/Performance/BasicUsePropertyInsteadOfCountMethodWhenAvailable.vb +++ b/src/Microsoft.NetCore.Analyzers/VisualBasic/Performance/BasicUsePropertyInsteadOfCountMethodWhenAvailable.vb @@ -7,23 +7,50 @@ Imports Microsoft.NetCore.Analyzers.Performance Namespace Microsoft.NetCore.VisualBasic.Analyzers.Performance + ''' + ''' CA1829: Visual Basic implementation Of use Property instead Of , When available. + ''' + ''' + ''' Flags the use of on types that are know to have a property with the same semantics: + ''' Length, Count. + ''' + ''' Public NotInheritable Class BasicUsePropertyInsteadOfCountMethodWhenAvailableAnalyzer Inherits UsePropertyInsteadOfCountMethodWhenAvailableAnalyzer + ''' + ''' Creates the operation actions handler. + ''' + ''' The context. + ''' The operation actions handler. Protected Overrides Function CreateOperationActionsHandler(context As OperationActionsContext) As OperationActionsHandler Return New BasicOperationActionsHandler(context) End Function + ''' + ''' Handler for operaction actions for Visual Basic. This class cannot be inherited. + ''' Implements the + ''' + ''' Private NotInheritable Class BasicOperationActionsHandler Inherits OperationActionsHandler + ''' + ''' Initializes a new instance of the class. + ''' + ''' The context. Public Sub New(context As OperationActionsContext) MyBase.New(context) End Sub + ''' + ''' Gets the type of the receiver of the . + ''' + ''' The invocation operation. + ''' The of the receiver of the extension method. Protected Overrides Function GetEnumerableCountInvocationTargetType(invocationOperation As IInvocationOperation) As ITypeSymbol Dim method = invocationOperation.TargetMethod @@ -32,24 +59,18 @@ Namespace Microsoft.NetCore.VisualBasic.Analyzers.Performance method.Name.Equals(NameOf(Enumerable.Count), StringComparison.Ordinal) AndAlso Me.Context.IsEnumerableType(method.ContainingSymbol) Then - Dim methodSourceItemType = TryCast(DirectCast(invocationOperation.Instance.Type, INamedTypeSymbol).TypeArguments.Item(0), ITypeSymbol) + Dim convertionOperation = TryCast(invocationOperation.Instance, IConversionOperation) - If Not methodSourceItemType Is Nothing Then + Return If(Not convertionOperation Is Nothing, + convertionOperation.Operand.Type, + invocationOperation.Instance.Type) - Dim convertionOperation = TryCast(invocationOperation.Instance, IConversionOperation) - - Return If(Not convertionOperation Is Nothing, - convertionOperation.Operand.Type, - invocationOperation.Instance.Type) - - End If End If Return Nothing End Function - End Class End Class From b7a564858676707561362e467f255ee6eff66fca Mon Sep 17 00:00:00 2001 From: paulomorgado <470455+paulomorgado@users.noreply.github.com> Date: Mon, 9 Sep 2019 16:12:07 +0100 Subject: [PATCH 11/11] updated documentation --- .../Microsoft.CodeAnalysis.FxCopAnalyzers.md | 16 +++++++++------- .../Microsoft.NetCore.Analyzers.md | 14 ++++++++------ 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.md b/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.md index a5e2281de4..19b444865c 100644 --- a/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.md +++ b/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.md @@ -92,7 +92,7 @@ Sr. No. | Rule ID | Title | Category | Enabled | CodeFix | Description | 89 | [CA2000](https://docs.microsoft.com/visualstudio/code-quality/ca2000-dispose-objects-before-losing-scope) | Dispose objects before losing scope | Reliability | True | False | If a disposable object is not explicitly disposed before all references to it are out of scope, the object will be disposed at some indeterminate time when the garbage collector runs the finalizer of the object. Because an exceptional event might occur that will prevent the finalizer of the object from running, the object should be explicitly disposed instead. | 90 | [CA2002](https://docs.microsoft.com/visualstudio/code-quality/ca2002-do-not-lock-on-objects-with-weak-identity) | Do not lock on objects with weak identity | Reliability | True | False | An object is said to have a weak identity when it can be directly accessed across application domain boundaries. A thread that tries to acquire a lock on an object that has a weak identity can be blocked by a second thread in a different application domain that has a lock on the same object. | 91 | [CA2007](https://docs.microsoft.com/visualstudio/code-quality/ca2007-do-not-directly-await-task) | Consider calling ConfigureAwait on the awaited task | Reliability | True | True | When an asynchronous method awaits a Task directly, continuation occurs in the same thread that created the task. Consider calling Task.ConfigureAwait(Boolean) to signal your intention for continuation. Call ConfigureAwait(false) on the task to schedule continuations to the thread pool, thereby avoiding a deadlock on the UI thread. Passing false is a good option for app-independent libraries. Calling ConfigureAwait(true) on the task has the same behavior as not explicitly calling ConfigureAwait. By explicitly calling this method, you're letting readers know you intentionally want to perform the continuation on the original synchronization context. | -92 | CA2008 | Do not create tasks without passing a TaskScheduler | Reliability | True | True | Do not create tasks unless you are using one of the overloads that takes a TaskScheduler. The default is to schedule on TaskScheduler.Current, which would lead to deadlocks. Either use TaskScheduler.Default to schedule on the thread pool, or explicitly pass TaskScheduler.Current to make your intentions clear. | +92 | CA2008 | Do not create tasks without passing a TaskScheduler | Reliability | True | False | Do not create tasks unless you are using one of the overloads that takes a TaskScheduler. The default is to schedule on TaskScheduler.Current, which would lead to deadlocks. Either use TaskScheduler.Default to schedule on the thread pool, or explicitly pass TaskScheduler.Current to make your intentions clear. | 93 | CA2009 | Do not call ToImmutableCollection on an ImmutableCollection value | Reliability | True | True | Do not call {0} on an {1} value | 94 | CA2010 | Always consume the value returned by methods marked with PreserveSigAttribute | Reliability | True | False | PreserveSigAttribute indicates that a method will return an HRESULT, rather than throwing an exception. Therefore, it is important to consume the HRESULT returned by the method, so that errors can be detected. Generally, this is done by calling Marshal.ThrowExceptionForHR. | 95 | [CA2100](https://docs.microsoft.com/visualstudio/code-quality/ca2100-review-sql-queries-for-security-vulnerabilities) | Review SQL queries for security vulnerabilities | Security | True | False | SQL queries that directly use user input can be vulnerable to SQL injection attacks. Review this SQL query for potential vulnerabilities, and consider using a parameterized SQL query. | @@ -101,12 +101,12 @@ Sr. No. | Rule ID | Title | Category | Enabled | CodeFix | Description | 98 | [CA2153](https://docs.microsoft.com/visualstudio/code-quality/ca2153-avoid-handling-corrupted-state-exceptions) | Do Not Catch Corrupted State Exceptions | Security | True | False | Catching corrupted state exceptions could mask errors (such as access violations), resulting in inconsistent state of execution or making it easier for attackers to compromise system. Instead, catch and handle a more specific set of exception type(s) or re-throw the exception | 99 | [CA2200](https://docs.microsoft.com/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details) | Rethrow to preserve stack details. | Usage | True | False | Re-throwing caught exception changes stack information. | 100 | [CA2201](https://docs.microsoft.com/visualstudio/code-quality/ca2201-do-not-raise-reserved-exception-types) | Do not raise reserved exception types | Usage | False | False | An exception of type that is not sufficiently specific or reserved by the runtime should never be raised by user code. This makes the original error difficult to detect and debug. If this exception instance might be thrown, use a different exception type. | -101 | [CA2207](https://docs.microsoft.com/visualstudio/code-quality/ca2207-initialize-value-type-static-fields-inline) | Initialize value type static fields inline | Usage | True | True | A value type declares an explicit static constructor. To fix a violation of this rule, initialize all static data when it is declared and remove the static constructor. | -102 | [CA2208](https://docs.microsoft.com/visualstudio/code-quality/ca2208-instantiate-argument-exceptions-correctly) | Instantiate argument exceptions correctly | Usage | True | True | A call is made to the default (parameterless) constructor of an exception type that is or derives from ArgumentException, or an incorrect string argument is passed to a parameterized constructor of an exception type that is or derives from ArgumentException. | +101 | [CA2207](https://docs.microsoft.com/visualstudio/code-quality/ca2207-initialize-value-type-static-fields-inline) | Initialize value type static fields inline | Usage | True | False | A value type declares an explicit static constructor. To fix a violation of this rule, initialize all static data when it is declared and remove the static constructor. | +102 | [CA2208](https://docs.microsoft.com/visualstudio/code-quality/ca2208-instantiate-argument-exceptions-correctly) | Instantiate argument exceptions correctly | Usage | True | False | A call is made to the default (parameterless) constructor of an exception type that is or derives from ArgumentException, or an incorrect string argument is passed to a parameterized constructor of an exception type that is or derives from ArgumentException. | 103 | [CA2211](https://docs.microsoft.com/visualstudio/code-quality/ca2211-non-constant-fields-should-not-be-visible) | Non-constant fields should not be visible | Usage | True | False | Static fields that are neither constants nor read-only are not thread-safe. Access to such a field must be carefully controlled and requires advanced programming techniques to synchronize access to the class object. | 104 | [CA2213](https://docs.microsoft.com/visualstudio/code-quality/ca2213-disposable-fields-should-be-disposed) | Disposable fields should be disposed | Usage | True | False | A type that implements System.IDisposable declares fields that are of types that also implement IDisposable. The Dispose method of the field is not called by the Dispose method of the declaring type. To fix a violation of this rule, call Dispose on fields that are of types that implement IDisposable if you are responsible for allocating and releasing the unmanaged resources held by the field. | 105 | [CA2214](https://docs.microsoft.com/visualstudio/code-quality/ca2214-do-not-call-overridable-methods-in-constructors) | Do not call overridable methods in constructors | Usage | True | False | Virtual methods defined on the class should not be called from constructors. If a derived class has overridden the method, the derived class version will be called (before the derived class constructor is called). | -106 | [CA2216](https://docs.microsoft.com/visualstudio/code-quality/ca2216-disposable-types-should-declare-finalizer) | Disposable types should declare finalizer | Usage | True | True | A type that implements System.IDisposable and has fields that suggest the use of unmanaged resources does not implement a finalizer, as described by Object.Finalize. | +106 | [CA2216](https://docs.microsoft.com/visualstudio/code-quality/ca2216-disposable-types-should-declare-finalizer) | Disposable types should declare finalizer | Usage | True | False | A type that implements System.IDisposable and has fields that suggest the use of unmanaged resources does not implement a finalizer, as described by Object.Finalize. | 107 | [CA2217](https://docs.microsoft.com/visualstudio/code-quality/ca2217-do-not-mark-enums-with-flagsattribute) | Do not mark enums with FlagsAttribute | Usage | False | True | An externally visible enumeration is marked by using FlagsAttribute, and it has one or more values that are not powers of two or a combination of the other defined values on the enumeration. | 108 | [CA2218](https://docs.microsoft.com/visualstudio/code-quality/ca2218-override-gethashcode-on-overriding-equals) | Override GetHashCode on overriding Equals | Usage | True | True | GetHashCode returns a value, based on the current instance, that is suited for hashing algorithms and data structures such as a hash table. Two objects that are the same type and are equal must return the same hash code. | 109 | [CA2219](https://docs.microsoft.com/visualstudio/code-quality/ca2219-do-not-raise-exceptions-in-exception-clauses) | Do not raise exceptions in finally clauses | Usage | True | False | When an exception is raised in a finally clause, the new exception hides the active exception. This makes the original error difficult to detect and debug. | @@ -189,8 +189,8 @@ Sr. No. | Rule ID | Title | Category | Enabled | CodeFix | Description | 186 | [CA5386](https://docs.microsoft.com/visualstudio/code-quality/ca5386) | Avoid hardcoding SecurityProtocolType value | Security | False | False | Avoid hardcoding SecurityProtocolType {0}, and instead use SecurityProtocolType.SystemDefault to allow the operating system to choose the best Transport Layer Security protocol to use. | 187 | CA5387 | Do Not Use Weak Key Derivation Function With Insufficient Iteration Count | Security | False | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | 188 | CA5388 | Ensure Sufficient Iteration Count When Using Weak Key Derivation Function | Security | False | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | -189 | CA5389 | Do Not Add Archive Item's Path To The Target File System Path | Security | True | False | When extracting files from an archive and using the archive item's path, check if the path is safe. Archive path can be relative and can lead to file system access outside of the expected file system target path, leading to malicious config changes and remote code execution via lay-and-wait technique. | -190 | CA5390 | Do Not Hard Code Encryption Key | Security | True | False | SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. | +189 | CA5389 | Do Not Add Archive Item's Path To The Target File System Path | Security | False | False | When extracting files from an archive and using the archive item's path, check if the path is safe. Archive path can be relative and can lead to file system access outside of the expected file system target path, leading to malicious config changes and remote code execution via lay-and-wait technique. | +190 | CA5390 | Do Not Hard Code Encryption Key | Security | False | False | SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. | 191 | CA5391 | Use antiforgery tokens in ASP.NET Core MVC controllers | Security | True | False | Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. | 192 | CA5392 | Use DefaultDllImportSearchPaths attribute for P/Invokes | Security | True | False | By default, P/Invokes using DllImportAttribute probe a number of directories, including the current working directory for the library to load. This can be a security issue for certain applications, leading to DLL hijacking. | 193 | CA5393 | Do not use unsafe DllImportSearchPath value | Security | True | False | There could be a malicious DLL in the default DLL search directories. Or, depending on where your application is run from, there could be a malicious DLL in the application's directory. Use a DllImportSearchPath value that specifies an explicit search path instead. The DllImportSearchPath flags that this rule looks for can be configured in .editorconfig. | @@ -199,4 +199,6 @@ Sr. No. | Rule ID | Title | Category | Enabled | CodeFix | Description | 196 | CA5396 | Set HttpOnly to true for HttpCookie | Security | False | False | As a defense in depth measure, ensure security sensitive HTTP cookies are marked as HttpOnly. This indicates web browsers should disallow scripts from accessing the cookies. Injected malicious scripts are a common way of stealing cookies. | 197 | [CA5397](https://docs.microsoft.com/visualstudio/code-quality/ca5397) | Do not use deprecated SslProtocols values | Security | True | False | Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. | 198 | [CA5398](https://docs.microsoft.com/visualstudio/code-quality/ca5398) | Avoid hardcoded SslProtocols values | Security | False | False | Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. | -199 | CA9999 | Analyzer version mismatch | Reliability | True | False | Analyzers in this package require a certain minimum version of Microsoft.CodeAnalysis to execute correctly. Refer to https://docs.microsoft.com/visualstudio/code-quality/install-fxcop-analyzers#fxcopanalyzers-package-versions to install the correct analyzer version. | +199 | CA5399 | Definitely disable HttpClient certificate revocation list check | Security | False | False | Using HttpClient without providing a platform specific handler (WinHttpHandler or CurlHandler or HttpClientHandler) where the CheckCertificateRevocationList property is set to true, will allow revoked certificates to be accepted by the HttpClient as valid. | +200 | CA5400 | Ensure HttpClient certificate revocation list check is not disabled | Security | False | False | Using HttpClient without providing a platform specific handler (WinHttpHandler or CurlHandler or HttpClientHandler) where the CheckCertificateRevocationList property is set to true, will allow revoked certificates to be accepted by the HttpClient as valid. | +201 | CA9999 | Analyzer version mismatch | Reliability | True | False | Analyzers in this package require a certain minimum version of Microsoft.CodeAnalysis to execute correctly. Refer to https://docs.microsoft.com/visualstudio/code-quality/install-fxcop-analyzers#fxcopanalyzers-package-versions to install the correct analyzer version. | diff --git a/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.md b/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.md index 3e17c6e63f..2a423ea253 100644 --- a/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.md +++ b/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.md @@ -20,16 +20,16 @@ Sr. No. | Rule ID | Title | Category | Enabled | CodeFix | Description | 17 | [CA1829](https://docs.microsoft.com/visualstudio/code-quality/ca1829) | Use Length/Count property instead of Count() when available | Performance | True | True | Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. | 18 | [CA2000](https://docs.microsoft.com/visualstudio/code-quality/ca2000-dispose-objects-before-losing-scope) | Dispose objects before losing scope | Reliability | True | False | If a disposable object is not explicitly disposed before all references to it are out of scope, the object will be disposed at some indeterminate time when the garbage collector runs the finalizer of the object. Because an exceptional event might occur that will prevent the finalizer of the object from running, the object should be explicitly disposed instead. | 19 | [CA2002](https://docs.microsoft.com/visualstudio/code-quality/ca2002-do-not-lock-on-objects-with-weak-identity) | Do not lock on objects with weak identity | Reliability | True | False | An object is said to have a weak identity when it can be directly accessed across application domain boundaries. A thread that tries to acquire a lock on an object that has a weak identity can be blocked by a second thread in a different application domain that has a lock on the same object. | -20 | CA2008 | Do not create tasks without passing a TaskScheduler | Reliability | True | True | Do not create tasks unless you are using one of the overloads that takes a TaskScheduler. The default is to schedule on TaskScheduler.Current, which would lead to deadlocks. Either use TaskScheduler.Default to schedule on the thread pool, or explicitly pass TaskScheduler.Current to make your intentions clear. | +20 | CA2008 | Do not create tasks without passing a TaskScheduler | Reliability | True | False | Do not create tasks unless you are using one of the overloads that takes a TaskScheduler. The default is to schedule on TaskScheduler.Current, which would lead to deadlocks. Either use TaskScheduler.Default to schedule on the thread pool, or explicitly pass TaskScheduler.Current to make your intentions clear. | 21 | CA2009 | Do not call ToImmutableCollection on an ImmutableCollection value | Reliability | True | True | Do not call {0} on an {1} value | 22 | CA2010 | Always consume the value returned by methods marked with PreserveSigAttribute | Reliability | True | False | PreserveSigAttribute indicates that a method will return an HRESULT, rather than throwing an exception. Therefore, it is important to consume the HRESULT returned by the method, so that errors can be detected. Generally, this is done by calling Marshal.ThrowExceptionForHR. | 23 | [CA2100](https://docs.microsoft.com/visualstudio/code-quality/ca2100-review-sql-queries-for-security-vulnerabilities) | Review SQL queries for security vulnerabilities | Security | True | False | SQL queries that directly use user input can be vulnerable to SQL injection attacks. Review this SQL query for potential vulnerabilities, and consider using a parameterized SQL query. | 24 | [CA2101](https://docs.microsoft.com/visualstudio/code-quality/ca2101-specify-marshaling-for-p-invoke-string-arguments) | Specify marshaling for P/Invoke string arguments | Globalization | True | True | A platform invoke member allows partially trusted callers, has a string parameter, and does not explicitly marshal the string. This can cause a potential security vulnerability. | 25 | [CA2201](https://docs.microsoft.com/visualstudio/code-quality/ca2201-do-not-raise-reserved-exception-types) | Do not raise reserved exception types | Usage | False | False | An exception of type that is not sufficiently specific or reserved by the runtime should never be raised by user code. This makes the original error difficult to detect and debug. If this exception instance might be thrown, use a different exception type. | -26 | [CA2207](https://docs.microsoft.com/visualstudio/code-quality/ca2207-initialize-value-type-static-fields-inline) | Initialize value type static fields inline | Usage | True | True | A value type declares an explicit static constructor. To fix a violation of this rule, initialize all static data when it is declared and remove the static constructor. | -27 | [CA2208](https://docs.microsoft.com/visualstudio/code-quality/ca2208-instantiate-argument-exceptions-correctly) | Instantiate argument exceptions correctly | Usage | True | True | A call is made to the default (parameterless) constructor of an exception type that is or derives from ArgumentException, or an incorrect string argument is passed to a parameterized constructor of an exception type that is or derives from ArgumentException. | +26 | [CA2207](https://docs.microsoft.com/visualstudio/code-quality/ca2207-initialize-value-type-static-fields-inline) | Initialize value type static fields inline | Usage | True | False | A value type declares an explicit static constructor. To fix a violation of this rule, initialize all static data when it is declared and remove the static constructor. | +27 | [CA2208](https://docs.microsoft.com/visualstudio/code-quality/ca2208-instantiate-argument-exceptions-correctly) | Instantiate argument exceptions correctly | Usage | True | False | A call is made to the default (parameterless) constructor of an exception type that is or derives from ArgumentException, or an incorrect string argument is passed to a parameterized constructor of an exception type that is or derives from ArgumentException. | 28 | [CA2213](https://docs.microsoft.com/visualstudio/code-quality/ca2213-disposable-fields-should-be-disposed) | Disposable fields should be disposed | Usage | True | False | A type that implements System.IDisposable declares fields that are of types that also implement IDisposable. The Dispose method of the field is not called by the Dispose method of the declaring type. To fix a violation of this rule, call Dispose on fields that are of types that implement IDisposable if you are responsible for allocating and releasing the unmanaged resources held by the field. | -29 | [CA2216](https://docs.microsoft.com/visualstudio/code-quality/ca2216-disposable-types-should-declare-finalizer) | Disposable types should declare finalizer | Usage | True | True | A type that implements System.IDisposable and has fields that suggest the use of unmanaged resources does not implement a finalizer, as described by Object.Finalize. | +29 | [CA2216](https://docs.microsoft.com/visualstudio/code-quality/ca2216-disposable-types-should-declare-finalizer) | Disposable types should declare finalizer | Usage | True | False | A type that implements System.IDisposable and has fields that suggest the use of unmanaged resources does not implement a finalizer, as described by Object.Finalize. | 30 | [CA2229](https://docs.microsoft.com/visualstudio/code-quality/ca2229-implement-serialization-constructors) | Implement serialization constructors | Usage | True | True | To fix a violation of this rule, implement the serialization constructor. For a sealed class, make the constructor private; otherwise, make it protected. | 31 | [CA2235](https://docs.microsoft.com/visualstudio/code-quality/ca2235-mark-all-non-serializable-fields) | Mark all non-serializable fields | Usage | True | True | An instance field of a type that is not serializable is declared in a type that is serializable. | 32 | [CA2237](https://docs.microsoft.com/visualstudio/code-quality/ca2237-mark-iserializable-types-with-serializableattribute) | Mark ISerializable types with serializable | Usage | True | True | To be recognized by the common language runtime as serializable, types must be marked by using the SerializableAttribute attribute even when the type uses a custom serialization routine through implementation of the ISerializable interface. | @@ -97,8 +97,8 @@ Sr. No. | Rule ID | Title | Category | Enabled | CodeFix | Description | 94 | [CA5386](https://docs.microsoft.com/visualstudio/code-quality/ca5386) | Avoid hardcoding SecurityProtocolType value | Security | False | False | Avoid hardcoding SecurityProtocolType {0}, and instead use SecurityProtocolType.SystemDefault to allow the operating system to choose the best Transport Layer Security protocol to use. | 95 | CA5387 | Do Not Use Weak Key Derivation Function With Insufficient Iteration Count | Security | False | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | 96 | CA5388 | Ensure Sufficient Iteration Count When Using Weak Key Derivation Function | Security | False | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | -97 | CA5389 | Do Not Add Archive Item's Path To The Target File System Path | Security | True | False | When extracting files from an archive and using the archive item's path, check if the path is safe. Archive path can be relative and can lead to file system access outside of the expected file system target path, leading to malicious config changes and remote code execution via lay-and-wait technique. | -98 | CA5390 | Do Not Hard Code Encryption Key | Security | True | False | SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. | +97 | CA5389 | Do Not Add Archive Item's Path To The Target File System Path | Security | False | False | When extracting files from an archive and using the archive item's path, check if the path is safe. Archive path can be relative and can lead to file system access outside of the expected file system target path, leading to malicious config changes and remote code execution via lay-and-wait technique. | +98 | CA5390 | Do Not Hard Code Encryption Key | Security | False | False | SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hardcoded value. | 99 | CA5391 | Use antiforgery tokens in ASP.NET Core MVC controllers | Security | True | False | Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token may be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller. | 100 | CA5392 | Use DefaultDllImportSearchPaths attribute for P/Invokes | Security | True | False | By default, P/Invokes using DllImportAttribute probe a number of directories, including the current working directory for the library to load. This can be a security issue for certain applications, leading to DLL hijacking. | 101 | CA5393 | Do not use unsafe DllImportSearchPath value | Security | True | False | There could be a malicious DLL in the default DLL search directories. Or, depending on where your application is run from, there could be a malicious DLL in the application's directory. Use a DllImportSearchPath value that specifies an explicit search path instead. The DllImportSearchPath flags that this rule looks for can be configured in .editorconfig. | @@ -107,3 +107,5 @@ Sr. No. | Rule ID | Title | Category | Enabled | CodeFix | Description | 104 | CA5396 | Set HttpOnly to true for HttpCookie | Security | False | False | As a defense in depth measure, ensure security sensitive HTTP cookies are marked as HttpOnly. This indicates web browsers should disallow scripts from accessing the cookies. Injected malicious scripts are a common way of stealing cookies. | 105 | [CA5397](https://docs.microsoft.com/visualstudio/code-quality/ca5397) | Do not use deprecated SslProtocols values | Security | True | False | Older protocol versions of Transport Layer Security (TLS) are less secure than TLS 1.2 and TLS 1.3, and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk. | 106 | [CA5398](https://docs.microsoft.com/visualstudio/code-quality/ca5398) | Avoid hardcoded SslProtocols values | Security | False | False | Current Transport Layer Security protocol versions may become deprecated if vulnerabilities are found. Avoid hardcoding SslProtocols values to keep your application secure. Use 'None' to let the Operating System choose a version. | +107 | CA5399 | Definitely disable HttpClient certificate revocation list check | Security | False | False | Using HttpClient without providing a platform specific handler (WinHttpHandler or CurlHandler or HttpClientHandler) where the CheckCertificateRevocationList property is set to true, will allow revoked certificates to be accepted by the HttpClient as valid. | +108 | CA5400 | Ensure HttpClient certificate revocation list check is not disabled | Security | False | False | Using HttpClient without providing a platform specific handler (WinHttpHandler or CurlHandler or HttpClientHandler) where the CheckCertificateRevocationList property is set to true, will allow revoked certificates to be accepted by the HttpClient as valid. |