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] 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