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