diff --git a/eng/Analyzers_ShippingRules.ruleset b/eng/Analyzers_ShippingRules.ruleset index 43d6b6bc69..29e1004c0b 100644 --- a/eng/Analyzers_ShippingRules.ruleset +++ b/eng/Analyzers_ShippingRules.ruleset @@ -26,12 +26,6 @@ - - - - - - diff --git a/eng/GenerateAnalyzerNuspec.targets b/eng/GenerateAnalyzerNuspec.targets index 48d978a75b..6933cff176 100644 --- a/eng/GenerateAnalyzerNuspec.targets +++ b/eng/GenerateAnalyzerNuspec.targets @@ -32,6 +32,7 @@ <_GeneratedGlobalAnalyzerConfigsDir>$(IntermediateOutputPath)GlobalAnalyzerConfigs false true + true true true true @@ -47,6 +48,13 @@ + + DisableNETAnalyzersForNuGetPackage.props + + + + + $(IntermediateOutputPath)Build $(NuspecPackageId).targets @@ -75,7 +83,7 @@ - + diff --git a/src/Microsoft.CodeAnalysis.AnalyzerUtilities/PublicAPI.Unshipped.txt b/src/Microsoft.CodeAnalysis.AnalyzerUtilities/PublicAPI.Unshipped.txt index eda14fd834..76eb65371c 100644 --- a/src/Microsoft.CodeAnalysis.AnalyzerUtilities/PublicAPI.Unshipped.txt +++ b/src/Microsoft.CodeAnalysis.AnalyzerUtilities/PublicAPI.Unshipped.txt @@ -9,7 +9,7 @@ Microsoft.CodeAnalysis.CodeMetrics.CodeAnalysisMetricData.MaintainabilityIndex.g Microsoft.CodeAnalysis.CodeMetrics.CodeAnalysisMetricData.SourceLines.get -> long Microsoft.CodeAnalysis.CodeMetrics.CodeAnalysisMetricData.Symbol.get -> Microsoft.CodeAnalysis.ISymbol! Microsoft.CodeAnalysis.FlowAnalysis.BranchWithInfo -Microsoft.CodeAnalysis.FlowAnalysis.BranchWithInfo.BranchValueOpt.get -> Microsoft.CodeAnalysis.IOperation? +Microsoft.CodeAnalysis.FlowAnalysis.BranchWithInfo.BranchValue.get -> Microsoft.CodeAnalysis.IOperation? Microsoft.CodeAnalysis.FlowAnalysis.BranchWithInfo.ControlFlowConditionKind.get -> Microsoft.CodeAnalysis.FlowAnalysis.ControlFlowConditionKind Microsoft.CodeAnalysis.FlowAnalysis.BranchWithInfo.Destination.get -> Microsoft.CodeAnalysis.FlowAnalysis.BasicBlock! Microsoft.CodeAnalysis.FlowAnalysis.BranchWithInfo.EnteringRegions.get -> System.Collections.Immutable.ImmutableArray @@ -31,19 +31,19 @@ Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractBlockAnalysisResult.BasicBl Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractDataFlowAnalysisContext.AbstractDataFlowAnalysisContext(Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractValueDomain! valueDomain, Analyzer.Utilities.WellKnownTypeProvider! wellKnownTypeProvider, Microsoft.CodeAnalysis.FlowAnalysis.ControlFlowGraph! controlFlowGraph, Microsoft.CodeAnalysis.ISymbol! owningSymbol, Microsoft.CodeAnalysis.Diagnostics.AnalyzerOptions! analyzerOptions, Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.InterproceduralAnalysisConfiguration interproceduralAnalysisConfig, bool pessimisticAnalysis, bool predicateAnalysis, bool exceptionPathsAnalysis, Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DataFlowAnalysisResult? copyAnalysisResult, Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis.PointsToAnalysisResult? pointsToAnalysisResult, Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DataFlowAnalysisResult? valueContentAnalysisResult, System.Func! tryGetOrComputeAnalysisResult, Microsoft.CodeAnalysis.FlowAnalysis.ControlFlowGraph? parentControlFlowGraph, Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.InterproceduralAnalysisData? interproceduralAnalysisData, Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.InterproceduralAnalysisPredicate? interproceduralAnalysisPredicate) -> void Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractDataFlowAnalysisContext.AnalyzerOptions.get -> Microsoft.CodeAnalysis.Diagnostics.AnalyzerOptions! Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractDataFlowAnalysisContext.ControlFlowGraph.get -> Microsoft.CodeAnalysis.FlowAnalysis.ControlFlowGraph! -Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractDataFlowAnalysisContext.CopyAnalysisResultOpt.get -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DataFlowAnalysisResult? +Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractDataFlowAnalysisContext.CopyAnalysisResult.get -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DataFlowAnalysisResult? Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractDataFlowAnalysisContext.ExceptionPathsAnalysis.get -> bool Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractDataFlowAnalysisContext.GetAnonymousFunctionControlFlowGraph(Microsoft.CodeAnalysis.FlowAnalysis.IFlowAnonymousFunctionOperation! lambda) -> Microsoft.CodeAnalysis.FlowAnalysis.ControlFlowGraph? Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractDataFlowAnalysisContext.GetLocalFunctionControlFlowGraph(Microsoft.CodeAnalysis.IMethodSymbol! localFunction) -> Microsoft.CodeAnalysis.FlowAnalysis.ControlFlowGraph? Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractDataFlowAnalysisContext.TryGetOrComputeAnalysisResult.get -> System.Func! Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractDataFlowAnalysisContext.InterproceduralAnalysisConfiguration.get -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.InterproceduralAnalysisConfiguration -Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractDataFlowAnalysisContext.InterproceduralAnalysisDataOpt.get -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.InterproceduralAnalysisData? -Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractDataFlowAnalysisContext.InterproceduralAnalysisPredicateOpt.get -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.InterproceduralAnalysisPredicate? +Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractDataFlowAnalysisContext.InterproceduralAnalysisData.get -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.InterproceduralAnalysisData? +Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractDataFlowAnalysisContext.InterproceduralAnalysisPredicate.get -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.InterproceduralAnalysisPredicate? Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractDataFlowAnalysisContext.OwningSymbol.get -> Microsoft.CodeAnalysis.ISymbol! -Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractDataFlowAnalysisContext.ParentControlFlowGraphOpt.get -> Microsoft.CodeAnalysis.FlowAnalysis.ControlFlowGraph? +Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractDataFlowAnalysisContext.ParentControlFlowGraph.get -> Microsoft.CodeAnalysis.FlowAnalysis.ControlFlowGraph? Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractDataFlowAnalysisContext.PessimisticAnalysis.get -> bool -Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractDataFlowAnalysisContext.PointsToAnalysisResultOpt.get -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis.PointsToAnalysisResult? -Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractDataFlowAnalysisContext.ValueContentAnalysisResultOpt.get -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DataFlowAnalysisResult? +Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractDataFlowAnalysisContext.PointsToAnalysisResult.get -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis.PointsToAnalysisResult? +Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractDataFlowAnalysisContext.ValueContentAnalysisResult.get -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DataFlowAnalysisResult? Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractDataFlowAnalysisContext.PredicateAnalysis.get -> bool Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractDataFlowAnalysisContext.ValueDomain.get -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractValueDomain! Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractDataFlowAnalysisContext.WellKnownTypeProvider.get -> Analyzer.Utilities.WellKnownTypeProvider! @@ -54,16 +54,16 @@ Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractDomain.Equals(T value1, Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractIndex Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractIndex.AbstractIndex() -> void Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractLocation -Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractLocation.AnalysisEntityOpt.get -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity? -Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractLocation.CaptureIdOpt.get -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.InterproceduralCaptureId? +Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractLocation.AnalysisEntity.get -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity? +Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractLocation.CaptureId.get -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.InterproceduralCaptureId? Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractLocation.CreationCallStack.get -> System.Collections.Immutable.ImmutableStack! -Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractLocation.CreationOpt.get -> Microsoft.CodeAnalysis.IOperation? +Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractLocation.Creation.get -> Microsoft.CodeAnalysis.IOperation? Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractLocation.GetTopOfCreationCallStackOrCreation() -> Microsoft.CodeAnalysis.IOperation? Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractLocation.IsAnalysisEntityDefaultLocation.get -> bool Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractLocation.IsNoLocation.get -> bool Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractLocation.IsNull.get -> bool -Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractLocation.LocationTypeOpt.get -> Microsoft.CodeAnalysis.ITypeSymbol? -Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractLocation.SymbolOpt.get -> Microsoft.CodeAnalysis.ISymbol? +Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractLocation.LocationType.get -> Microsoft.CodeAnalysis.ITypeSymbol? +Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractLocation.Symbol.get -> Microsoft.CodeAnalysis.ISymbol? Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractLocation.TryGetNodeToReportDiagnostic(Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis.PointsToAnalysisResult? pointsToAnalysisResult) -> Microsoft.CodeAnalysis.SyntaxNode? ~Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractLocationDataFlowOperationVisitor Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractLocationDataFlowOperationVisitor.AbstractLocationDataFlowOperationVisitor(TAnalysisContext! analysisContext) -> void @@ -74,7 +74,7 @@ Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractLocationDataFlowOperationVi Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractValueDomain Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractValueDomain.AbstractValueDomain() -> void Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity -Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity.CaptureIdOpt.get -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.InterproceduralCaptureId? +Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity.CaptureId.get -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.InterproceduralCaptureId? Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity.EqualsIgnoringInstanceLocation(Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity? other) -> bool Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity.EqualsIgnoringInstanceLocationId.get -> int Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity.HasAncestor(Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity! ancestor) -> bool @@ -82,12 +82,12 @@ Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity.HasConstantValue.get Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity.HasUnknownInstanceLocation.get -> bool Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity.Indices.get -> System.Collections.Immutable.ImmutableArray Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity.InstanceLocation.get -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis.PointsToAbstractValue! -Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity.InstanceReferenceOperationSyntaxOpt.get -> Microsoft.CodeAnalysis.SyntaxNode? +Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity.InstanceReferenceOperationSyntax.get -> Microsoft.CodeAnalysis.SyntaxNode? Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity.IsChildOrInstanceMember.get -> bool Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity.IsLValueFlowCaptureEntity.get -> bool Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity.IsThisOrMeInstance.get -> bool -Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity.ParentOpt.get -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity? -Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity.SymbolOpt.get -> Microsoft.CodeAnalysis.ISymbol? +Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity.Parent.get -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity? +Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity.Symbol.get -> Microsoft.CodeAnalysis.ISymbol? Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity.Type.get -> Microsoft.CodeAnalysis.ITypeSymbol! Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity.WithMergedInstanceLocation(Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity! analysisEntityToMerge) -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity! Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntityBasedPredicateAnalysisData @@ -127,7 +127,7 @@ Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntityFactory.TryGetForInte Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntityMapAbstractDomain Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntityMapAbstractDomain.AnalysisEntityMapAbstractDomain(Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractValueDomain! valueDomain, Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis.PointsToAnalysisResult? pointsToAnalysisResult) -> void Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ArgumentInfo -Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ArgumentInfo.AnalysisEntityOpt.get -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity? +Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ArgumentInfo.AnalysisEntity.get -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity? Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ArgumentInfo.ArgumentInfo(Microsoft.CodeAnalysis.IOperation! operation, Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity? analysisEntity, Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis.PointsToAbstractValue! instanceLocation, TAbstractAnalysisValue value) -> void Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ArgumentInfo.InstanceLocation.get -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis.PointsToAbstractValue! Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ArgumentInfo.Operation.get -> Microsoft.CodeAnalysis.IOperation! @@ -159,11 +159,11 @@ Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DataFlowAnalysis.ControlFlowGraph.get -> Microsoft.CodeAnalysis.FlowAnalysis.ControlFlowGraph! Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DataFlowAnalysisResult.DataFlowAnalysisResult(Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DataFlowAnalysisResult! other) -> void Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DataFlowAnalysisResult.EntryBlockOutput.get -> TBlockAnalysisResult! -Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DataFlowAnalysisResult.ExceptionPathsExitBlockOutputOpt.get -> TBlockAnalysisResult? +Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DataFlowAnalysisResult.ExceptionPathsExitBlockOutput.get -> TBlockAnalysisResult? Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DataFlowAnalysisResult.ExitBlockOutput.get -> TBlockAnalysisResult! Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DataFlowAnalysisResult.GetPredicateKind(Microsoft.CodeAnalysis.IOperation! operation) -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PredicateValueKind -Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DataFlowAnalysisResult.MergedStateForUnhandledThrowOperationsOpt.get -> TBlockAnalysisResult? -Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DataFlowAnalysisResult.ReturnValueAndPredicateKindOpt.get -> (TAbstractAnalysisValue Value, Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PredicateValueKind PredicateValueKind)? +Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DataFlowAnalysisResult.MergedStateForUnhandledThrowOperations.get -> TBlockAnalysisResult? +Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DataFlowAnalysisResult.ReturnValueAndPredicateKind.get -> (TAbstractAnalysisValue Value, Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PredicateValueKind PredicateValueKind)? Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DataFlowAnalysisResult.this[Microsoft.CodeAnalysis.FlowAnalysis.BasicBlock! block].get -> TBlockAnalysisResult! Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DataFlowAnalysisResult.this[Microsoft.CodeAnalysis.IOperation! operation].get -> TAbstractAnalysisValue Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DataFlowAnalysisResult.this[Microsoft.CodeAnalysis.OperationKind operationKind, Microsoft.CodeAnalysis.SyntaxNode! syntax].get -> TAbstractAnalysisValue @@ -266,10 +266,10 @@ Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.IDataFlowAnalysisContext.GetAnonymo Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.IDataFlowAnalysisContext.GetLocalFunctionControlFlowGraph(Microsoft.CodeAnalysis.IMethodSymbol! localFunction) -> Microsoft.CodeAnalysis.FlowAnalysis.ControlFlowGraph? Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.IDataFlowAnalysisContext.OwningSymbol.get -> Microsoft.CodeAnalysis.ISymbol! Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.IDataFlowAnalysisResult -Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.IDataFlowAnalysisResult.AnalysisDataForUnhandledThrowOperationsOpt.get -> object? +Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.IDataFlowAnalysisResult.AnalysisDataForUnhandledThrowOperations.get -> object? Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.IDataFlowAnalysisResult.ControlFlowGraph.get -> Microsoft.CodeAnalysis.FlowAnalysis.ControlFlowGraph! -Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.IDataFlowAnalysisResult.ReturnValueAndPredicateKindOpt.get -> (TAbstractAnalysisValue Value, Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PredicateValueKind PredicateValueKind)? -Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.IDataFlowAnalysisResult.TaskWrappedValuesMapOpt.get -> object? +Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.IDataFlowAnalysisResult.ReturnValueAndPredicateKind.get -> (TAbstractAnalysisValue Value, Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PredicateValueKind PredicateValueKind)? +Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.IDataFlowAnalysisResult.TaskWrappedValuesMap.get -> object? Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.InterproceduralAnalysisConfiguration Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.InterproceduralAnalysisConfiguration.Equals(Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.InterproceduralAnalysisConfiguration other) -> bool Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.InterproceduralAnalysisConfiguration.InterproceduralAnalysisKind.get -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.InterproceduralAnalysisKind @@ -286,9 +286,9 @@ Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.InterproceduralAnalysisData.GetInterproceduralControlFlowGraph.get -> System.Func! Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.InterproceduralAnalysisData.InitialAnalysisData.get -> TAnalysisData Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.InterproceduralAnalysisData.InterproceduralAnalysisData(TAnalysisData initialAnalysisData, (Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity?, Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis.PointsToAbstractValue!)? invocationInstance, (Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity!, Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis.PointsToAbstractValue!)? thisOrMeInstanceForCaller, System.Collections.Immutable.ImmutableDictionary!>! argumentValuesMap, System.Collections.Immutable.ImmutableDictionary! capturedVariablesMap, System.Collections.Immutable.ImmutableDictionary! addressSharedEntities, System.Collections.Immutable.ImmutableStack! callStack, System.Collections.Immutable.ImmutableHashSet! methodsBeingAnalyzed, System.Func! getCachedAbstractValueFromCaller, System.Func! getInterproceduralControlFlowGraph, System.Func! getAnalysisEntityForFlowCapture, System.Func?>! getInterproceduralCallStackForOwningSymbol) -> void -Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.InterproceduralAnalysisData.InvocationInstanceOpt.get -> (Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity? InstanceOpt, Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis.PointsToAbstractValue! PointsToValue)? +Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.InterproceduralAnalysisData.InvocationInstance.get -> (Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity? Instance, Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis.PointsToAbstractValue! PointsToValue)? Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.InterproceduralAnalysisData.MethodsBeingAnalyzed.get -> System.Collections.Immutable.ImmutableHashSet! -Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.InterproceduralAnalysisData.ThisOrMeInstanceForCallerOpt.get -> (Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity! Instance, Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis.PointsToAbstractValue! PointsToValue)? +Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.InterproceduralAnalysisData.ThisOrMeInstanceForCaller.get -> (Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity! Instance, Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis.PointsToAbstractValue! PointsToValue)? Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.InterproceduralAnalysisKind Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.InterproceduralAnalysisKind.ContextSensitive = 1 -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.InterproceduralAnalysisKind Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.InterproceduralAnalysisKind.None = 0 -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.InterproceduralAnalysisKind @@ -461,7 +461,7 @@ override Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractLocationDataFlowOp override Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntityBasedPredicateAnalysisData.Dispose(bool disposing) -> void override Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntityDataFlowOperationVisitor.ComputeAnalysisValueForReferenceOperation(Microsoft.CodeAnalysis.IOperation! operation, TAbstractAnalysisValue defaultValue) -> TAbstractAnalysisValue override Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntityDataFlowOperationVisitor.EscapeValueForParameterOnExit(Microsoft.CodeAnalysis.IParameterSymbol! parameter, Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity! analysisEntity) -> void -override Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntityDataFlowOperationVisitor.GetInitialInterproceduralAnalysisData(Microsoft.CodeAnalysis.IMethodSymbol! invokedMethod, (Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity? InstanceOpt, Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis.PointsToAbstractValue! PointsToValue)? invocationInstance, (Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity! Instance, Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis.PointsToAbstractValue! PointsToValue)? thisOrMeInstanceForCaller, System.Collections.Immutable.ImmutableDictionary!>! argumentValuesMap, System.Collections.Generic.IDictionary? pointsToValues, System.Collections.Generic.IDictionary? copyValues, System.Collections.Generic.IDictionary? valueContentValues, bool isLambdaOrLocalFunction, bool hasParameterWithDelegateType) -> TAnalysisData! +override Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntityDataFlowOperationVisitor.GetInitialInterproceduralAnalysisData(Microsoft.CodeAnalysis.IMethodSymbol! invokedMethod, (Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity? Instance, Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis.PointsToAbstractValue! PointsToValue)? invocationInstance, (Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity! Instance, Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis.PointsToAbstractValue! PointsToValue)? thisOrMeInstanceForCaller, System.Collections.Immutable.ImmutableDictionary!>! argumentValuesMap, System.Collections.Generic.IDictionary? pointsToValues, System.Collections.Generic.IDictionary? copyValues, System.Collections.Generic.IDictionary? valueContentValues, bool isLambdaOrLocalFunction, bool hasParameterWithDelegateType) -> TAnalysisData! override Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntityDataFlowOperationVisitor.GetMergedAnalysisDataForPossibleThrowingOperation(TAnalysisData? existingData, Microsoft.CodeAnalysis.IOperation! operation) -> TAnalysisData! override Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntityDataFlowOperationVisitor.GetMergedDataForUnhandledThrowOperations() -> TAnalysisData? override Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntityDataFlowOperationVisitor.ProcessOutOfScopeLocalsAndFlowCaptures(System.Collections.Generic.IEnumerable! locals, System.Collections.Generic.IEnumerable! flowCaptures) -> void @@ -692,7 +692,7 @@ virtual Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DataFlowOperationVisitor.GetAbstractDefaultValueForCatchVariable(Microsoft.CodeAnalysis.Operations.ICatchClauseOperation! catchClause) -> TAbstractAnalysisValue virtual Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DataFlowOperationVisitor.GetAssignedValueForPattern(Microsoft.CodeAnalysis.Operations.IIsPatternOperation! operation, TAbstractAnalysisValue operandValue) -> TAbstractAnalysisValue virtual Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DataFlowOperationVisitor.GetCopyAbstractValue(Microsoft.CodeAnalysis.IOperation! operation) -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.CopyAnalysis.CopyAbstractValue! -virtual Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DataFlowOperationVisitor.GetInitialInterproceduralAnalysisData(Microsoft.CodeAnalysis.IMethodSymbol! invokedMethod, (Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity? InstanceOpt, Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis.PointsToAbstractValue! PointsToValue)? invocationInstance, (Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity! Instance, Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis.PointsToAbstractValue! PointsToValue)? thisOrMeInstanceForCaller, System.Collections.Immutable.ImmutableDictionary!>! argumentValuesMap, System.Collections.Generic.IDictionary? pointsToValues, System.Collections.Generic.IDictionary? copyValues, System.Collections.Generic.IDictionary? valueContentValues, bool isLambdaOrLocalFunction, bool hasParameterWithDelegateType) -> TAnalysisData! +virtual Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DataFlowOperationVisitor.GetInitialInterproceduralAnalysisData(Microsoft.CodeAnalysis.IMethodSymbol! invokedMethod, (Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity? Instance, Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis.PointsToAbstractValue! PointsToValue)? invocationInstance, (Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity! Instance, Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis.PointsToAbstractValue! PointsToValue)? thisOrMeInstanceForCaller, System.Collections.Immutable.ImmutableDictionary!>! argumentValuesMap, System.Collections.Generic.IDictionary? pointsToValues, System.Collections.Generic.IDictionary? copyValues, System.Collections.Generic.IDictionary? valueContentValues, bool isLambdaOrLocalFunction, bool hasParameterWithDelegateType) -> TAnalysisData! virtual Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DataFlowOperationVisitor.GetMergedAnalysisDataForPossibleThrowingOperation(TAnalysisData? existingData, Microsoft.CodeAnalysis.IOperation! operation) -> TAnalysisData! virtual Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DataFlowOperationVisitor.GetMergedDataForUnhandledThrowOperations() -> TAnalysisData? virtual Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DataFlowOperationVisitor.GetPointsToAbstractValue(Microsoft.CodeAnalysis.IOperation! operation) -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis.PointsToAbstractValue! diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Microsoft.CodeAnalysis.Analyzers.md b/src/Microsoft.CodeAnalysis.Analyzers/Microsoft.CodeAnalysis.Analyzers.md index a201f0cef9..6dfa152a0c 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Microsoft.CodeAnalysis.Analyzers.md +++ b/src/Microsoft.CodeAnalysis.Analyzers/Microsoft.CodeAnalysis.Analyzers.md @@ -1,45 +1,548 @@ +# Microsoft.CodeAnalysis.Analyzers + +## RS1001: Missing diagnostic analyzer attribute + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisCorrectness| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Non-abstract sub-types of DiagnosticAnalyzer should be marked with DiagnosticAnalyzerAttribute(s). The argument to this attribute(s), if any, determine the supported languages for the analyzer. Analyzer types without this attribute will be ignored by the analysis engine. + +## RS1002: Missing kind argument when registering an analyzer action + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisCorrectness| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +You must specify at least one syntax, symbol or operation kind when registering a syntax, symbol, or operation analyzer action respectively. Otherwise, the registered action will never be invoked during analysis. + +## RS1003: Unsupported SymbolKind argument when registering a symbol analyzer action + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisCorrectness| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +SymbolKind '{0}' is not supported for symbol analyzer actions + +## RS1004: Recommend adding language support to diagnostic analyzer + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisCorrectness| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Diagnostic analyzer is marked as supporting only one language, but the analyzer assembly doesn't seem to refer to any language specific CodeAnalysis assemblies, and so is likely to work for more than one language. Consider adding an additional language argument to DiagnosticAnalyzerAttribute. + +## RS1005: ReportDiagnostic invoked with an unsupported DiagnosticDescriptor + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisCorrectness| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +ReportDiagnostic should only be invoked with supported DiagnosticDescriptors that are returned from DiagnosticAnalyzer.SupportedDiagnostics property. Otherwise, the reported diagnostic will be filtered out by the analysis engine. + +## RS1006: Invalid type argument for DiagnosticAnalyzer's Register method + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisCorrectness| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +DiagnosticAnalyzer's language-specific Register methods, such as RegisterSyntaxNodeAction, RegisterCodeBlockStartAction and RegisterCodeBlockEndAction, expect a language-specific 'SyntaxKind' type argument for it's 'TLanguageKindEnumName' type parameter. Otherwise, the registered analyzer action can never be invoked during analysis. + +## RS1007: Provide localizable arguments to diagnostic descriptor constructor + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisLocalization| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +If your diagnostic analyzer and it's reported diagnostics need to be localizable, then the supported DiagnosticDescriptors used for constructing the diagnostics must also be localizable. If so, then localizable argument(s) must be provided for parameter 'title' (and optionally 'description') to the diagnostic descriptor constructor to ensure that the descriptor is localizable. + +## RS1008: Avoid storing per-compilation data into the fields of a diagnostic analyzer + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisPerformance| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Instance of a diagnostic analyzer might outlive the lifetime of compilation. Hence, storing per-compilation data, such as symbols, into the fields of a diagnostic analyzer might cause stale compilations to stay alive and cause memory leaks. Instead, you should store this data on a separate type instantiated in a compilation start action, registered using 'AnalysisContext.RegisterCompilationStartAction' API. An instance of this type will be created per-compilation and it won't outlive compilation's lifetime, hence avoiding memory leaks. + +## RS1009: Only internal implementations of this interface are allowed + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisCompatibility| +|Enabled|True| +|Severity|Error| +|CodeFix|False| + +### Rule description + +The author of this interface did not intend to have third party implementations of this interface and reserves the right to change it. Implementing this interface could therefore result in a source or binary compatibility issue with a future version of this interface. + +## RS1010: Create code actions should have a unique EquivalenceKey for FixAll occurrences support + +|Item|Value| +|-|-| +|Category|Correctness| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A CodeFixProvider that intends to support fix all occurrences must classify the registered code actions into equivalence classes by assigning it an explicit, non-null equivalence key which is unique for each kind of code action created by this fixer. This enables the FixAllProvider to fix all diagnostics in the required scope by applying code actions from this fixer that are in the equivalence class of the trigger code action. + +## RS1011: Use code actions that have a unique EquivalenceKey for FixAll occurrences support + +|Item|Value| +|-|-| +|Category|Correctness| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A CodeFixProvider that intends to support fix all occurrences must classify the registered code actions into equivalence classes by assigning it an explicit, non-null equivalence key which is unique for each kind of code action created by this fixer. This enables the FixAllProvider to fix all diagnostics in the required scope by applying code actions from this fixer that are in the equivalence class of the trigger code action. + +## RS1012: Start action has no registered actions + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisPerformance| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +An analyzer start action enables performing stateful analysis over a given code unit, such as a code block, compilation, etc. Careful design is necessary to achieve efficient analyzer execution without memory leaks. Use the following guidelines for writing such analyzers:
1. Define a new scope for the registered start action, possibly with a private nested type for analyzing each code unit.
2. If required, define and initialize state in the start action.
3. Register at least one non-end action that refers to this state in the start action. If no such action is necessary, consider replacing the start action with a non-start action. For example, a CodeBlockStartAction with no registered actions or only a registered CodeBlockEndAction should be replaced with a CodeBlockAction.
4. If required, register an end action to report diagnostics based on the final state. + +## RS1013: Start action has no registered non-end actions + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisPerformance| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +An analyzer start action enables performing stateful analysis over a given code unit, such as a code block, compilation, etc. Careful design is necessary to achieve efficient analyzer execution without memory leaks. Use the following guidelines for writing such analyzers:
1. Define a new scope for the registered start action, possibly with a private nested type for analyzing each code unit.
2. If required, define and initialize state in the start action.
3. Register at least one non-end action that refers to this state in the start action. If no such action is necessary, consider replacing the start action with a non-start action. For example, a CodeBlockStartAction with no registered actions or only a registered CodeBlockEndAction should be replaced with a CodeBlockAction.
4. If required, register an end action to report diagnostics based on the final state. + +## RS1014: Do not ignore values returned by methods on immutable objects. + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisCorrectness| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Many objects exposed by Roslyn are immutable. The return value from a method invocation on these objects should not be ignored. + +## RS1015: Provide non-null 'helpLinkUri' value to diagnostic descriptor constructor + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisDocumentation| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The 'helpLinkUri' value is used to show information when this diagnostic in the error list. Every analyzer should have a helpLinkUri specified which points to a help page that does not change over time. + +## RS1016: Code fix providers should provide FixAll support + +|Item|Value| +|-|-| +|Category|Correctness| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +A CodeFixProvider should provide FixAll support to enable users to fix multiple instances of the underlying diagnostic with a single code fix. See documenation at https://github.com/dotnet/roslyn/blob/master/docs/analyzers/FixAllProvider.md for further details. + +## RS1017: DiagnosticId for analyzers must be a non-null constant + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisDesign| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +DiagnosticId for analyzers must be a non-null constant. + +## RS1018: DiagnosticId for analyzers must be in specified format + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisDesign| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +DiagnosticId for analyzers must be in specified format. + +## RS1019: DiagnosticId must be unique across analyzers + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisDesign| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +DiagnosticId must be unique across analyzers. + +## RS1020: Category for analyzers must be from the specified values + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisDesign| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Category for analyzers must be from the specified values. + +## RS1021: Invalid entry in analyzer category and diagnostic ID range specification file + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisDesign| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Invalid entry in analyzer category and diagnostic ID range specification file. + +## RS1022: Do not use types from Workspaces assembly in an analyzer + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisCorrectness| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Diagnostic analyzer types should not use types from Workspaces assemblies. Workspaces assemblies are only available when the analyzer executes in Visual Studio IDE live analysis, but are not available during command line build. Referencing types from Workspaces assemblies will lead to runtime exception during analyzer execution in command line build. + +## [RS1023](https://go.microsoft.com/fwlink/?linkid=874285): Upgrade MSBuildWorkspace + +|Item|Value| +|-|-| +|Category|Library| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +MSBuildWorkspace has moved to the Microsoft.CodeAnalysis.Workspaces.MSBuild NuGet package and there are breaking API changes. + +## RS1024: Compare symbols correctly + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisCorrectness| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Symbols should be compared for equality, not identity. + +## RS1025: Configure generated code analysis + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisCorrectness| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Configure generated code analysis + +## RS1026: Enable concurrent execution + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisCorrectness| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Enable concurrent execution + +## RS1027: Types marked with DiagnosticAnalyzerAttribute(s) should inherit from DiagnosticAnalyzer + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisCorrectness| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Inherit type '{0}' from DiagnosticAnalyzer or remove the DiagnosticAnalyzerAttribute(s) + +## RS1028: Provide non-null 'customTags' value to diagnostic descriptor constructor + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisDocumentation| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The 'customTags' value is used as a way to enable specific actions and filters on diagnostic descriptors based on the specific values of the tags. Every Roslyn analyzer should have at least one tag from the 'WellKnownDiagnosticTags' class. + +## RS1029: Do not use reserved diagnostic IDs + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisDesign| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +DiagnosticId for analyzers should not use reserved IDs. + +## RS1030: Do not invoke Compilation.GetSemanticModel() method within a diagnostic analyzer + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisCorrectness| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +'GetSemanticModel' is an expensive method to invoke within a diagnostic analyzer because it creates a completely new semantic model, which does not share compilation data with the compiler or other analyzers. This incurs an additional performance cost during semantic analysis. Instead, consider registering a different analyzer action which allows used of a shared 'SemanticModel', such as 'RegisterOperationAction', 'RegisterSyntaxNodeAction', or 'RegisterSemanticModelAction'. + +## RS1031: Define diagnostic title correctly + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisDesign| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +The diagnostic title should not contain a period or any line return character + +## RS1032: Define diagnostic message correctly + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisDesign| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +The diagnostic message should not contain any line return character and should either be a single sentence without a trailing period or a multi-sentences with a trailing period + +## RS1033: Define diagnostic description correctly + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisDesign| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +The diagnostic description should be one or multiple sentences ending with a punctuation sign + +## [RS2000](https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md): Add analyzer diagnostic IDs to analyzer release. + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisReleaseTracking| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +All supported analyzer diagnostic IDs should be part of an analyzer release. + +## [RS2001](https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md): Ensure up-to-date entry for analyzer diagnostic IDs are added to analyzer release. + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisReleaseTracking| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Ensure up-to-date entry for analyzer diagnostic IDs are added to analyzer release. + +## [RS2002](https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md): Do not add removed analyzer diagnostic IDs to unshipped analyzer release. + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisReleaseTracking| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Entries for analyzer diagnostic IDs that are no longer reported and never shipped can be removed from unshipped analyzer release. + +## [RS2003](https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md): Shipped diagnostic IDs that are no longer reported should have an entry in the 'Removed Rules' table in unshipped file. + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisReleaseTracking| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Shipped diagnostic IDs that are no longer reported should have an entry in the 'Removed Rules' table in unshipped file. + +## [RS2004](https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md): Diagnostic IDs marked as removed in analyzer release file should not be reported by analyzers. + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisReleaseTracking| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Diagnostic IDs marked as removed in analyzer release file should not be reported by analyzers. + +## [RS2005](https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md): Remove duplicate entries for diagnostic ID in the same analyzer release. + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisReleaseTracking| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Remove duplicate entries for diagnostic ID in the same analyzer release. + +## [RS2006](https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md): Remove duplicate entries for diagnostic ID between analyzer releases. + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisReleaseTracking| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Remove duplicate entries for diagnostic ID between analyzer releases. + +## [RS2007](https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md): Invalid entry in analyzer release file. + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisReleaseTracking| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Invalid entry in analyzer release file. + +## [RS2008](https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md): Enable analyzer release tracking + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisReleaseTracking| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Enabling release tracking for analyzer packages helps in tracking and documenting the analyzer diagnostics that ship and/or change with each analyzer release. See details at https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md. -Rule ID | Title | Category | Enabled | Severity | CodeFix | Description | ---------|-------|----------|---------|----------|---------|--------------------------------------------------------------------------------------------------------------| -RS1001 | Missing diagnostic analyzer attribute. | MicrosoftCodeAnalysisCorrectness | True | Warning | True | Non-abstract sub-types of DiagnosticAnalyzer should be marked with DiagnosticAnalyzerAttribute(s). The argument to this attribute(s), if any, determine the supported languages for the analyzer. Analyzer types without this attribute will be ignored by the analysis engine. | -RS1002 | Missing kind argument when registering an analyzer action. | MicrosoftCodeAnalysisCorrectness | True | Warning | False | You must specify at least one syntax, symbol or operation kind when registering a syntax, symbol, or operation analyzer action respectively. Otherwise, the registered action will never be invoked during analysis. | -RS1003 | Unsupported SymbolKind argument when registering a symbol analyzer action. | MicrosoftCodeAnalysisCorrectness | True | Warning | False | SymbolKind '{0}' is not supported for symbol analyzer actions. | -RS1004 | Recommend adding language support to diagnostic analyzer. | MicrosoftCodeAnalysisCorrectness | True | Warning | False | Diagnostic analyzer is marked as supporting only one language, but the analyzer assembly doesn't seem to refer to any language specific CodeAnalysis assemblies, and so is likely to work for more than one language. Consider adding an additional language argument to DiagnosticAnalyzerAttribute. | -RS1005 | ReportDiagnostic invoked with an unsupported DiagnosticDescriptor. | MicrosoftCodeAnalysisCorrectness | True | Warning | False | ReportDiagnostic should only be invoked with supported DiagnosticDescriptors that are returned from DiagnosticAnalyzer.SupportedDiagnostics property. Otherwise, the reported diagnostic will be filtered out by the analysis engine. | -RS1006 | Invalid type argument for DiagnosticAnalyzer's Register method. | MicrosoftCodeAnalysisCorrectness | True | Warning | False | DiagnosticAnalyzer's language-specific Register methods, such as RegisterSyntaxNodeAction, RegisterCodeBlockStartAction and RegisterCodeBlockEndAction, expect a language-specific 'SyntaxKind' type argument for it's 'TLanguageKindEnumName' type parameter. Otherwise, the registered analyzer action can never be invoked during analysis. | -RS1007 | Provide localizable arguments to diagnostic descriptor constructor. | MicrosoftCodeAnalysisLocalization | False | Warning | False | If your diagnostic analyzer and it's reported diagnostics need to be localizable, then the supported DiagnosticDescriptors used for constructing the diagnostics must also be localizable. If so, then localizable argument(s) must be provided for parameter 'title' (and optionally 'description') to the diagnostic descriptor constructor to ensure that the descriptor is localizable. | -RS1008 | Avoid storing per-compilation data into the fields of a diagnostic analyzer. | MicrosoftCodeAnalysisPerformance | True | Warning | False | Instance of a diagnostic analyzer might outlive the lifetime of compilation. Hence, storing per-compilation data, such as symbols, into the fields of a diagnostic analyzer might cause stale compilations to stay alive and cause memory leaks. Instead, you should store this data on a separate type instantiated in a compilation start action, registered using 'AnalysisContext.RegisterCompilationStartAction' API. An instance of this type will be created per-compilation and it won't outlive compilation's lifetime, hence avoiding memory leaks. | -RS1009 | Only internal implementations of this interface are allowed. | MicrosoftCodeAnalysisCompatibility | True | Error | False | The author of this interface did not intend to have third party implementations of this interface and reserves the right to change it. Implementing this interface could therefore result in a source or binary compatibility issue with a future version of this interface. | -RS1010 | Create code actions should have a unique EquivalenceKey for FixAll occurrences support. | Correctness | True | Warning | False | A CodeFixProvider that intends to support fix all occurrences must classify the registered code actions into equivalence classes by assigning it an explicit, non-null equivalence key which is unique for each kind of code action created by this fixer. This enables the FixAllProvider to fix all diagnostics in the required scope by applying code actions from this fixer that are in the equivalence class of the trigger code action. | -RS1011 | Use code actions that have a unique EquivalenceKey for FixAll occurrences support. | Correctness | True | Warning | False | A CodeFixProvider that intends to support fix all occurrences must classify the registered code actions into equivalence classes by assigning it an explicit, non-null equivalence key which is unique for each kind of code action created by this fixer. This enables the FixAllProvider to fix all diagnostics in the required scope by applying code actions from this fixer that are in the equivalence class of the trigger code action. | -RS1012 | Start action has no registered actions. | MicrosoftCodeAnalysisPerformance | True | Warning | False | An analyzer start action enables performing stateful analysis over a given code unit, such as a code block, compilation, etc. Careful design is necessary to achieve efficient analyzer execution without memory leaks. Use the following guidelines for writing such analyzers:
1. Define a new scope for the registered start action, possibly with a private nested type for analyzing each code unit.
2. If required, define and initialize state in the start action.
3. Register at least one non-end action that refers to this state in the start action. If no such action is necessary, consider replacing the start action with a non-start action. For example, a CodeBlockStartAction with no registered actions or only a registered CodeBlockEndAction should be replaced with a CodeBlockAction.
4. If required, register an end action to report diagnostics based on the final state.
| -RS1013 | Start action has no registered non-end actions. | MicrosoftCodeAnalysisPerformance | True | Warning | False | An analyzer start action enables performing stateful analysis over a given code unit, such as a code block, compilation, etc. Careful design is necessary to achieve efficient analyzer execution without memory leaks. Use the following guidelines for writing such analyzers:
1. Define a new scope for the registered start action, possibly with a private nested type for analyzing each code unit.
2. If required, define and initialize state in the start action.
3. Register at least one non-end action that refers to this state in the start action. If no such action is necessary, consider replacing the start action with a non-start action. For example, a CodeBlockStartAction with no registered actions or only a registered CodeBlockEndAction should be replaced with a CodeBlockAction.
4. If required, register an end action to report diagnostics based on the final state.
| -RS1014 | Do not ignore values returned by methods on immutable objects. | MicrosoftCodeAnalysisCorrectness | True | Warning | False | Many objects exposed by Roslyn are immutable. The return value from a method invocation on these objects should not be ignored. | -RS1015 | Provide non-null 'helpLinkUri' value to diagnostic descriptor constructor. | MicrosoftCodeAnalysisDocumentation | False | Warning | False | The 'helpLinkUri' value is used to show information when this diagnostic in the error list. Every analyzer should have a helpLinkUri specified which points to a help page that does not change over time. | -RS1016 | Code fix providers should provide FixAll support. | Correctness | True | Warning | True | A CodeFixProvider should provide FixAll support to enable users to fix multiple instances of the underlying diagnostic with a single code fix. See documenation at https://github.com/dotnet/roslyn/blob/master/docs/analyzers/FixAllProvider.md for further details. | -RS1017 | DiagnosticId for analyzers must be a non-null constant. | MicrosoftCodeAnalysisDesign | True | Warning | False | DiagnosticId for analyzers must be a non-null constant. | -RS1018 | DiagnosticId for analyzers must be in specified format. | MicrosoftCodeAnalysisDesign | True | Warning | False | DiagnosticId for analyzers must be in specified format. | -RS1019 | DiagnosticId must be unique across analyzers. | MicrosoftCodeAnalysisDesign | True | Warning | False | DiagnosticId must be unique across analyzers. | -RS1020 | Category for analyzers must be from the specified values. | MicrosoftCodeAnalysisDesign | False | Warning | False | Category for analyzers must be from the specified values. | -RS1021 | Invalid entry in analyzer category and diagnostic ID range specification file. | MicrosoftCodeAnalysisDesign | True | Warning | False | Invalid entry in analyzer category and diagnostic ID range specification file. | -RS1022 | Do not use types from Workspaces assembly in an analyzer | MicrosoftCodeAnalysisCorrectness | True | Warning | False | Diagnostic analyzer types should not use types from Workspaces assemblies. Workspaces assemblies are only available when the analyzer executes in Visual Studio IDE live analysis, but are not available during command line build. Referencing types from Workspaces assemblies will lead to runtime exception during analyzer execution in command line build. | -[RS1023](https://go.microsoft.com/fwlink/?linkid=874285) | Upgrade MSBuildWorkspace | Library | True | Warning | False | MSBuildWorkspace has moved to the Microsoft.CodeAnalysis.Workspaces.MSBuild NuGet package and there are breaking API changes. | -RS1024 | Compare symbols correctly | MicrosoftCodeAnalysisCorrectness | True | Warning | True | Symbols should be compared for equality, not identity. | -RS1025 | Configure generated code analysis | MicrosoftCodeAnalysisCorrectness | True | Warning | True | Configure generated code analysis | -RS1026 | Enable concurrent execution | MicrosoftCodeAnalysisCorrectness | True | Warning | True | Enable concurrent execution | -RS1027 | Types marked with DiagnosticAnalyzerAttribute(s) should inherit from DiagnosticAnalyzer. | MicrosoftCodeAnalysisCorrectness | True | Warning | False | Inherit type '{0}' from DiagnosticAnalyzer or remove the DiagnosticAnalyzerAttribute(s). | -RS1028 | Provide non-null 'customTags' value to diagnostic descriptor constructor. | MicrosoftCodeAnalysisDocumentation | False | Warning | False | The 'customTags' value is used as a way to enable specific actions and filters on diagnostic descriptors based on the specific values of the tags. Every Roslyn analyzer should have at least one tag from the 'WellKnownDiagnosticTags' class. | -RS1029 | Do not use reserved diagnostic IDs. | MicrosoftCodeAnalysisDesign | True | Warning | False | DiagnosticId for analyzers should not use reserved IDs. | -RS1030 | Do not invoke Compilation.GetSemanticModel() method within a diagnostic analyzer | MicrosoftCodeAnalysisCorrectness | True | Warning | False | 'GetSemanticModel' is an expensive method to invoke within a diagnostic analyzer because it creates a completely new semantic model, which does not share compilation data with the compiler or other analyzers. This incurs an additional performance cost during semantic analysis. Instead, consider registering a different analyzer action which allows used of a shared 'SemanticModel', such as 'RegisterOperationAction', 'RegisterSyntaxNodeAction', or 'RegisterSemanticModelAction'. | -RS1031 | Define diagnostic title correctly | MicrosoftCodeAnalysisDesign | False | Warning | False | The diagnostic title should not contain a period or any line return character | -RS1032 | Define diagnostic message correctly | MicrosoftCodeAnalysisDesign | False | Warning | False | The diagnostic message should not contain any line return character and should either be a single sentence without a trailing period or a multi-sentences with a trailing period. | -RS1033 | Define diagnostic description correctly | MicrosoftCodeAnalysisDesign | False | Warning | False | The diagnostic description should be one or multiple sentences ending with a punctuation sign. | -[RS2000](https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md) | Add analyzer diagnostic IDs to analyzer release. | MicrosoftCodeAnalysisReleaseTracking | True | Warning | True | All supported analyzer diagnostic IDs should be part of an analyzer release. | -[RS2001](https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md) | Ensure up-to-date entry for analyzer diagnostic IDs are added to analyzer release. | MicrosoftCodeAnalysisReleaseTracking | True | Warning | True | Ensure up-to-date entry for analyzer diagnostic IDs are added to analyzer release. | -[RS2002](https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md) | Do not add removed analyzer diagnostic IDs to unshipped analyzer release. | MicrosoftCodeAnalysisReleaseTracking | True | Warning | False | Entries for analyzer diagnostic IDs that are no longer reported and never shipped can be removed from unshipped analyzer release. | -[RS2003](https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md) | Shipped diagnostic IDs that are no longer reported should have an entry in the 'Removed Rules' table in unshipped file. | MicrosoftCodeAnalysisReleaseTracking | True | Warning | False | Shipped diagnostic IDs that are no longer reported should have an entry in the 'Removed Rules' table in unshipped file. | -[RS2004](https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md) | Diagnostic IDs marked as removed in analyzer release file should not be reported by analyzers. | MicrosoftCodeAnalysisReleaseTracking | True | Warning | False | Diagnostic IDs marked as removed in analyzer release file should not be reported by analyzers. | -[RS2005](https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md) | Remove duplicate entries for diagnostic ID in the same analyzer release. | MicrosoftCodeAnalysisReleaseTracking | True | Warning | False | Remove duplicate entries for diagnostic ID in the same analyzer release. | -[RS2006](https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md) | Remove duplicate entries for diagnostic ID between analyzer releases. | MicrosoftCodeAnalysisReleaseTracking | True | Warning | False | Remove duplicate entries for diagnostic ID between analyzer releases. | -[RS2007](https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md) | Invalid entry in analyzer release file. | MicrosoftCodeAnalysisReleaseTracking | True | Warning | False | Invalid entry in analyzer release file. | -[RS2008](https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md) | Enable analyzer release tracking | MicrosoftCodeAnalysisReleaseTracking | True | Warning | True | Enabling release tracking for analyzer packages helps in tracking and documenting the analyzer diagnostics that ship and/or change with each analyzer release. See details at https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md. | diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Microsoft.CodeAnalysis.Analyzers.sarif b/src/Microsoft.CodeAnalysis.Analyzers/Microsoft.CodeAnalysis.Analyzers.sarif index efaeefe074..bddd1c18e6 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Microsoft.CodeAnalysis.Analyzers.sarif +++ b/src/Microsoft.CodeAnalysis.Analyzers/Microsoft.CodeAnalysis.Analyzers.sarif @@ -11,7 +11,7 @@ "rules": { "RS1001": { "id": "RS1001", - "shortDescription": "Missing diagnostic analyzer attribute.", + "shortDescription": "Missing diagnostic analyzer attribute", "fullDescription": "Non-abstract sub-types of DiagnosticAnalyzer should be marked with DiagnosticAnalyzerAttribute(s). The argument to this attribute(s), if any, determine the supported languages for the analyzer. Analyzer types without this attribute will be ignored by the analysis engine.", "defaultLevel": "warning", "properties": { @@ -29,7 +29,7 @@ }, "RS1004": { "id": "RS1004", - "shortDescription": "Recommend adding language support to diagnostic analyzer.", + "shortDescription": "Recommend adding language support to diagnostic analyzer", "fullDescription": "Diagnostic analyzer is marked as supporting only one language, but the analyzer assembly doesn't seem to refer to any language specific CodeAnalysis assemblies, and so is likely to work for more than one language. Consider adding an additional language argument to DiagnosticAnalyzerAttribute.", "defaultLevel": "warning", "properties": { @@ -47,7 +47,7 @@ }, "RS1007": { "id": "RS1007", - "shortDescription": "Provide localizable arguments to diagnostic descriptor constructor.", + "shortDescription": "Provide localizable arguments to diagnostic descriptor constructor", "fullDescription": "If your diagnostic analyzer and it's reported diagnostics need to be localizable, then the supported DiagnosticDescriptors used for constructing the diagnostics must also be localizable. If so, then localizable argument(s) must be provided for parameter 'title' (and optionally 'description') to the diagnostic descriptor constructor to ensure that the descriptor is localizable.", "defaultLevel": "warning", "properties": { @@ -65,7 +65,7 @@ }, "RS1009": { "id": "RS1009", - "shortDescription": "Only internal implementations of this interface are allowed.", + "shortDescription": "Only internal implementations of this interface are allowed", "fullDescription": "The author of this interface did not intend to have third party implementations of this interface and reserves the right to change it. Implementing this interface could therefore result in a source or binary compatibility issue with a future version of this interface.", "defaultLevel": "error", "properties": { @@ -80,7 +80,7 @@ }, "RS1010": { "id": "RS1010", - "shortDescription": "Create code actions should have a unique EquivalenceKey for FixAll occurrences support.", + "shortDescription": "Create code actions should have a unique EquivalenceKey for FixAll occurrences support", "fullDescription": "A CodeFixProvider that intends to support fix all occurrences must classify the registered code actions into equivalence classes by assigning it an explicit, non-null equivalence key which is unique for each kind of code action created by this fixer. This enables the FixAllProvider to fix all diagnostics in the required scope by applying code actions from this fixer that are in the equivalence class of the trigger code action.", "defaultLevel": "warning", "properties": { @@ -98,7 +98,7 @@ }, "RS1011": { "id": "RS1011", - "shortDescription": "Use code actions that have a unique EquivalenceKey for FixAll occurrences support.", + "shortDescription": "Use code actions that have a unique EquivalenceKey for FixAll occurrences support", "fullDescription": "A CodeFixProvider that intends to support fix all occurrences must classify the registered code actions into equivalence classes by assigning it an explicit, non-null equivalence key which is unique for each kind of code action created by this fixer. This enables the FixAllProvider to fix all diagnostics in the required scope by applying code actions from this fixer that are in the equivalence class of the trigger code action.", "defaultLevel": "warning", "properties": { @@ -116,7 +116,7 @@ }, "RS1015": { "id": "RS1015", - "shortDescription": "Provide non-null 'helpLinkUri' value to diagnostic descriptor constructor.", + "shortDescription": "Provide non-null 'helpLinkUri' value to diagnostic descriptor constructor", "fullDescription": "The 'helpLinkUri' value is used to show information when this diagnostic in the error list. Every analyzer should have a helpLinkUri specified which points to a help page that does not change over time.", "defaultLevel": "warning", "properties": { @@ -134,7 +134,7 @@ }, "RS1016": { "id": "RS1016", - "shortDescription": "Code fix providers should provide FixAll support.", + "shortDescription": "Code fix providers should provide FixAll support", "fullDescription": "A CodeFixProvider should provide FixAll support to enable users to fix multiple instances of the underlying diagnostic with a single code fix. See documenation at https://github.com/dotnet/roslyn/blob/master/docs/analyzers/FixAllProvider.md for further details.", "defaultLevel": "warning", "properties": { @@ -152,7 +152,7 @@ }, "RS1017": { "id": "RS1017", - "shortDescription": "DiagnosticId for analyzers must be a non-null constant.", + "shortDescription": "DiagnosticId for analyzers must be a non-null constant", "fullDescription": "DiagnosticId for analyzers must be a non-null constant.", "defaultLevel": "warning", "properties": { @@ -170,7 +170,7 @@ }, "RS1018": { "id": "RS1018", - "shortDescription": "DiagnosticId for analyzers must be in specified format.", + "shortDescription": "DiagnosticId for analyzers must be in specified format", "fullDescription": "DiagnosticId for analyzers must be in specified format.", "defaultLevel": "warning", "properties": { @@ -188,7 +188,7 @@ }, "RS1019": { "id": "RS1019", - "shortDescription": "DiagnosticId must be unique across analyzers.", + "shortDescription": "DiagnosticId must be unique across analyzers", "fullDescription": "DiagnosticId must be unique across analyzers.", "defaultLevel": "warning", "properties": { @@ -206,7 +206,7 @@ }, "RS1020": { "id": "RS1020", - "shortDescription": "Category for analyzers must be from the specified values.", + "shortDescription": "Category for analyzers must be from the specified values", "fullDescription": "Category for analyzers must be from the specified values.", "defaultLevel": "warning", "properties": { @@ -224,7 +224,7 @@ }, "RS1021": { "id": "RS1021", - "shortDescription": "Invalid entry in analyzer category and diagnostic ID range specification file.", + "shortDescription": "Invalid entry in analyzer category and diagnostic ID range specification file", "fullDescription": "Invalid entry in analyzer category and diagnostic ID range specification file.", "defaultLevel": "warning", "properties": { @@ -296,8 +296,8 @@ }, "RS1027": { "id": "RS1027", - "shortDescription": "Types marked with DiagnosticAnalyzerAttribute(s) should inherit from DiagnosticAnalyzer.", - "fullDescription": "Inherit type '{0}' from DiagnosticAnalyzer or remove the DiagnosticAnalyzerAttribute(s).", + "shortDescription": "Types marked with DiagnosticAnalyzerAttribute(s) should inherit from DiagnosticAnalyzer", + "fullDescription": "Inherit type '{0}' from DiagnosticAnalyzer or remove the DiagnosticAnalyzerAttribute(s)", "defaultLevel": "warning", "properties": { "category": "MicrosoftCodeAnalysisCorrectness", @@ -314,7 +314,7 @@ }, "RS1028": { "id": "RS1028", - "shortDescription": "Provide non-null 'customTags' value to diagnostic descriptor constructor.", + "shortDescription": "Provide non-null 'customTags' value to diagnostic descriptor constructor", "fullDescription": "The 'customTags' value is used as a way to enable specific actions and filters on diagnostic descriptors based on the specific values of the tags. Every Roslyn analyzer should have at least one tag from the 'WellKnownDiagnosticTags' class.", "defaultLevel": "warning", "properties": { @@ -332,7 +332,7 @@ }, "RS1029": { "id": "RS1029", - "shortDescription": "Do not use reserved diagnostic IDs.", + "shortDescription": "Do not use reserved diagnostic IDs", "fullDescription": "DiagnosticId for analyzers should not use reserved IDs.", "defaultLevel": "warning", "properties": { @@ -373,7 +373,7 @@ "defaultLevel": "warning", "properties": { "category": "MicrosoftCodeAnalysisDesign", - "isEnabledByDefault": false, + "isEnabledByDefault": true, "typeName": "DiagnosticDescriptorCreationAnalyzer", "languages": [ "C#", @@ -387,11 +387,11 @@ "RS1032": { "id": "RS1032", "shortDescription": "Define diagnostic message correctly", - "fullDescription": "The diagnostic message should not contain any line return character and should either be a single sentence without a trailing period or a multi-sentences with a trailing period.", + "fullDescription": "The diagnostic message should not contain any line return character and should either be a single sentence without a trailing period or a multi-sentences with a trailing period", "defaultLevel": "warning", "properties": { "category": "MicrosoftCodeAnalysisDesign", - "isEnabledByDefault": false, + "isEnabledByDefault": true, "typeName": "DiagnosticDescriptorCreationAnalyzer", "languages": [ "C#", @@ -405,11 +405,11 @@ "RS1033": { "id": "RS1033", "shortDescription": "Define diagnostic description correctly", - "fullDescription": "The diagnostic description should be one or multiple sentences ending with a punctuation sign.", + "fullDescription": "The diagnostic description should be one or multiple sentences ending with a punctuation sign", "defaultLevel": "warning", "properties": { "category": "MicrosoftCodeAnalysisDesign", - "isEnabledByDefault": false, + "isEnabledByDefault": true, "typeName": "DiagnosticDescriptorCreationAnalyzer", "languages": [ "C#", @@ -602,7 +602,7 @@ "rules": { "RS1002": { "id": "RS1002", - "shortDescription": "Missing kind argument when registering an analyzer action.", + "shortDescription": "Missing kind argument when registering an analyzer action", "fullDescription": "You must specify at least one syntax, symbol or operation kind when registering a syntax, symbol, or operation analyzer action respectively. Otherwise, the registered action will never be invoked during analysis.", "defaultLevel": "warning", "properties": { @@ -619,8 +619,8 @@ }, "RS1003": { "id": "RS1003", - "shortDescription": "Unsupported SymbolKind argument when registering a symbol analyzer action.", - "fullDescription": "SymbolKind '{0}' is not supported for symbol analyzer actions.", + "shortDescription": "Unsupported SymbolKind argument when registering a symbol analyzer action", + "fullDescription": "SymbolKind '{0}' is not supported for symbol analyzer actions", "defaultLevel": "warning", "properties": { "category": "MicrosoftCodeAnalysisCorrectness", @@ -636,7 +636,7 @@ }, "RS1005": { "id": "RS1005", - "shortDescription": "ReportDiagnostic invoked with an unsupported DiagnosticDescriptor.", + "shortDescription": "ReportDiagnostic invoked with an unsupported DiagnosticDescriptor", "fullDescription": "ReportDiagnostic should only be invoked with supported DiagnosticDescriptors that are returned from DiagnosticAnalyzer.SupportedDiagnostics property. Otherwise, the reported diagnostic will be filtered out by the analysis engine.", "defaultLevel": "warning", "properties": { @@ -653,7 +653,7 @@ }, "RS1006": { "id": "RS1006", - "shortDescription": "Invalid type argument for DiagnosticAnalyzer's Register method.", + "shortDescription": "Invalid type argument for DiagnosticAnalyzer's Register method", "fullDescription": "DiagnosticAnalyzer's language-specific Register methods, such as RegisterSyntaxNodeAction, RegisterCodeBlockStartAction and RegisterCodeBlockEndAction, expect a language-specific 'SyntaxKind' type argument for it's 'TLanguageKindEnumName' type parameter. Otherwise, the registered analyzer action can never be invoked during analysis.", "defaultLevel": "warning", "properties": { @@ -670,7 +670,7 @@ }, "RS1008": { "id": "RS1008", - "shortDescription": "Avoid storing per-compilation data into the fields of a diagnostic analyzer.", + "shortDescription": "Avoid storing per-compilation data into the fields of a diagnostic analyzer", "fullDescription": "Instance of a diagnostic analyzer might outlive the lifetime of compilation. Hence, storing per-compilation data, such as symbols, into the fields of a diagnostic analyzer might cause stale compilations to stay alive and cause memory leaks. Instead, you should store this data on a separate type instantiated in a compilation start action, registered using 'AnalysisContext.RegisterCompilationStartAction' API. An instance of this type will be created per-compilation and it won't outlive compilation's lifetime, hence avoiding memory leaks.", "defaultLevel": "warning", "properties": { @@ -687,8 +687,8 @@ }, "RS1012": { "id": "RS1012", - "shortDescription": "Start action has no registered actions.", - "fullDescription": "An analyzer start action enables performing stateful analysis over a given code unit, such as a code block, compilation, etc. Careful design is necessary to achieve efficient analyzer execution without memory leaks. Use the following guidelines for writing such analyzers:\u000d\u000a1. Define a new scope for the registered start action, possibly with a private nested type for analyzing each code unit.\u000d\u000a2. If required, define and initialize state in the start action.\u000d\u000a3. Register at least one non-end action that refers to this state in the start action. If no such action is necessary, consider replacing the start action with a non-start action. For example, a CodeBlockStartAction with no registered actions or only a registered CodeBlockEndAction should be replaced with a CodeBlockAction.\u000d\u000a4. If required, register an end action to report diagnostics based on the final state.\u000d\u000a", + "shortDescription": "Start action has no registered actions", + "fullDescription": "An analyzer start action enables performing stateful analysis over a given code unit, such as a code block, compilation, etc. Careful design is necessary to achieve efficient analyzer execution without memory leaks. Use the following guidelines for writing such analyzers:\u000d\u000a1. Define a new scope for the registered start action, possibly with a private nested type for analyzing each code unit.\u000d\u000a2. If required, define and initialize state in the start action.\u000d\u000a3. Register at least one non-end action that refers to this state in the start action. If no such action is necessary, consider replacing the start action with a non-start action. For example, a CodeBlockStartAction with no registered actions or only a registered CodeBlockEndAction should be replaced with a CodeBlockAction.\u000d\u000a4. If required, register an end action to report diagnostics based on the final state.", "defaultLevel": "warning", "properties": { "category": "MicrosoftCodeAnalysisPerformance", @@ -704,8 +704,8 @@ }, "RS1013": { "id": "RS1013", - "shortDescription": "Start action has no registered non-end actions.", - "fullDescription": "An analyzer start action enables performing stateful analysis over a given code unit, such as a code block, compilation, etc. Careful design is necessary to achieve efficient analyzer execution without memory leaks. Use the following guidelines for writing such analyzers:\u000d\u000a1. Define a new scope for the registered start action, possibly with a private nested type for analyzing each code unit.\u000d\u000a2. If required, define and initialize state in the start action.\u000d\u000a3. Register at least one non-end action that refers to this state in the start action. If no such action is necessary, consider replacing the start action with a non-start action. For example, a CodeBlockStartAction with no registered actions or only a registered CodeBlockEndAction should be replaced with a CodeBlockAction.\u000d\u000a4. If required, register an end action to report diagnostics based on the final state.\u000d\u000a", + "shortDescription": "Start action has no registered non-end actions", + "fullDescription": "An analyzer start action enables performing stateful analysis over a given code unit, such as a code block, compilation, etc. Careful design is necessary to achieve efficient analyzer execution without memory leaks. Use the following guidelines for writing such analyzers:\u000d\u000a1. Define a new scope for the registered start action, possibly with a private nested type for analyzing each code unit.\u000d\u000a2. If required, define and initialize state in the start action.\u000d\u000a3. Register at least one non-end action that refers to this state in the start action. If no such action is necessary, consider replacing the start action with a non-start action. For example, a CodeBlockStartAction with no registered actions or only a registered CodeBlockEndAction should be replaced with a CodeBlockAction.\u000d\u000a4. If required, register an end action to report diagnostics based on the final state.", "defaultLevel": "warning", "properties": { "category": "MicrosoftCodeAnalysisPerformance", @@ -782,7 +782,7 @@ "rules": { "RS1002": { "id": "RS1002", - "shortDescription": "Missing kind argument when registering an analyzer action.", + "shortDescription": "Missing kind argument when registering an analyzer action", "fullDescription": "You must specify at least one syntax, symbol or operation kind when registering a syntax, symbol, or operation analyzer action respectively. Otherwise, the registered action will never be invoked during analysis.", "defaultLevel": "warning", "properties": { @@ -799,8 +799,8 @@ }, "RS1003": { "id": "RS1003", - "shortDescription": "Unsupported SymbolKind argument when registering a symbol analyzer action.", - "fullDescription": "SymbolKind '{0}' is not supported for symbol analyzer actions.", + "shortDescription": "Unsupported SymbolKind argument when registering a symbol analyzer action", + "fullDescription": "SymbolKind '{0}' is not supported for symbol analyzer actions", "defaultLevel": "warning", "properties": { "category": "MicrosoftCodeAnalysisCorrectness", @@ -816,7 +816,7 @@ }, "RS1005": { "id": "RS1005", - "shortDescription": "ReportDiagnostic invoked with an unsupported DiagnosticDescriptor.", + "shortDescription": "ReportDiagnostic invoked with an unsupported DiagnosticDescriptor", "fullDescription": "ReportDiagnostic should only be invoked with supported DiagnosticDescriptors that are returned from DiagnosticAnalyzer.SupportedDiagnostics property. Otherwise, the reported diagnostic will be filtered out by the analysis engine.", "defaultLevel": "warning", "properties": { @@ -833,7 +833,7 @@ }, "RS1006": { "id": "RS1006", - "shortDescription": "Invalid type argument for DiagnosticAnalyzer's Register method.", + "shortDescription": "Invalid type argument for DiagnosticAnalyzer's Register method", "fullDescription": "DiagnosticAnalyzer's language-specific Register methods, such as RegisterSyntaxNodeAction, RegisterCodeBlockStartAction and RegisterCodeBlockEndAction, expect a language-specific 'SyntaxKind' type argument for it's 'TLanguageKindEnumName' type parameter. Otherwise, the registered analyzer action can never be invoked during analysis.", "defaultLevel": "warning", "properties": { @@ -850,7 +850,7 @@ }, "RS1008": { "id": "RS1008", - "shortDescription": "Avoid storing per-compilation data into the fields of a diagnostic analyzer.", + "shortDescription": "Avoid storing per-compilation data into the fields of a diagnostic analyzer", "fullDescription": "Instance of a diagnostic analyzer might outlive the lifetime of compilation. Hence, storing per-compilation data, such as symbols, into the fields of a diagnostic analyzer might cause stale compilations to stay alive and cause memory leaks. Instead, you should store this data on a separate type instantiated in a compilation start action, registered using 'AnalysisContext.RegisterCompilationStartAction' API. An instance of this type will be created per-compilation and it won't outlive compilation's lifetime, hence avoiding memory leaks.", "defaultLevel": "warning", "properties": { @@ -867,8 +867,8 @@ }, "RS1012": { "id": "RS1012", - "shortDescription": "Start action has no registered actions.", - "fullDescription": "An analyzer start action enables performing stateful analysis over a given code unit, such as a code block, compilation, etc. Careful design is necessary to achieve efficient analyzer execution without memory leaks. Use the following guidelines for writing such analyzers:\u000d\u000a1. Define a new scope for the registered start action, possibly with a private nested type for analyzing each code unit.\u000d\u000a2. If required, define and initialize state in the start action.\u000d\u000a3. Register at least one non-end action that refers to this state in the start action. If no such action is necessary, consider replacing the start action with a non-start action. For example, a CodeBlockStartAction with no registered actions or only a registered CodeBlockEndAction should be replaced with a CodeBlockAction.\u000d\u000a4. If required, register an end action to report diagnostics based on the final state.\u000d\u000a", + "shortDescription": "Start action has no registered actions", + "fullDescription": "An analyzer start action enables performing stateful analysis over a given code unit, such as a code block, compilation, etc. Careful design is necessary to achieve efficient analyzer execution without memory leaks. Use the following guidelines for writing such analyzers:\u000d\u000a1. Define a new scope for the registered start action, possibly with a private nested type for analyzing each code unit.\u000d\u000a2. If required, define and initialize state in the start action.\u000d\u000a3. Register at least one non-end action that refers to this state in the start action. If no such action is necessary, consider replacing the start action with a non-start action. For example, a CodeBlockStartAction with no registered actions or only a registered CodeBlockEndAction should be replaced with a CodeBlockAction.\u000d\u000a4. If required, register an end action to report diagnostics based on the final state.", "defaultLevel": "warning", "properties": { "category": "MicrosoftCodeAnalysisPerformance", @@ -884,8 +884,8 @@ }, "RS1013": { "id": "RS1013", - "shortDescription": "Start action has no registered non-end actions.", - "fullDescription": "An analyzer start action enables performing stateful analysis over a given code unit, such as a code block, compilation, etc. Careful design is necessary to achieve efficient analyzer execution without memory leaks. Use the following guidelines for writing such analyzers:\u000d\u000a1. Define a new scope for the registered start action, possibly with a private nested type for analyzing each code unit.\u000d\u000a2. If required, define and initialize state in the start action.\u000d\u000a3. Register at least one non-end action that refers to this state in the start action. If no such action is necessary, consider replacing the start action with a non-start action. For example, a CodeBlockStartAction with no registered actions or only a registered CodeBlockEndAction should be replaced with a CodeBlockAction.\u000d\u000a4. If required, register an end action to report diagnostics based on the final state.\u000d\u000a", + "shortDescription": "Start action has no registered non-end actions", + "fullDescription": "An analyzer start action enables performing stateful analysis over a given code unit, such as a code block, compilation, etc. Careful design is necessary to achieve efficient analyzer execution without memory leaks. Use the following guidelines for writing such analyzers:\u000d\u000a1. Define a new scope for the registered start action, possibly with a private nested type for analyzing each code unit.\u000d\u000a2. If required, define and initialize state in the start action.\u000d\u000a3. Register at least one non-end action that refers to this state in the start action. If no such action is necessary, consider replacing the start action with a non-start action. For example, a CodeBlockStartAction with no registered actions or only a registered CodeBlockEndAction should be replaced with a CodeBlockAction.\u000d\u000a4. If required, register an end action to report diagnostics based on the final state.", "defaultLevel": "warning", "properties": { "category": "MicrosoftCodeAnalysisPerformance", diff --git a/src/Microsoft.CodeAnalysis.BannedApiAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers.md b/src/Microsoft.CodeAnalysis.BannedApiAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers.md index b50769d18c..4b180449a1 100644 --- a/src/Microsoft.CodeAnalysis.BannedApiAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers.md +++ b/src/Microsoft.CodeAnalysis.BannedApiAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers.md @@ -1,6 +1,41 @@ +# Microsoft.CodeAnalysis.BannedApiAnalyzers + +## [RS0030](https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.BannedApiAnalyzers/BannedApiAnalyzers.Help.md): Do not used banned APIs + +|Item|Value| +|-|-| +|Category|ApiDesign| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The symbol has been marked as banned in this project, and an alternate should be used instead. + +## [RS0031](https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.BannedApiAnalyzers/BannedApiAnalyzers.Help.md): The list of banned symbols contains a duplicate + +|Item|Value| +|-|-| +|Category|ApiDesign| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The list of banned symbols contains a duplicate. + +## RS0035: External access to internal symbols outside the restricted namespace(s) is prohibited + +|Item|Value| +|-|-| +|Category|ApiDesign| +|Enabled|True| +|Severity|Error| +|CodeFix|False| + +### Rule description + +RestrictedInternalsVisibleToAttribute enables a restricted version of InternalsVisibleToAttribute that limits access to internal symbols to those within specified namespaces. Each referencing assembly can only access internal symbols defined in the restricted namespaces that the referenced assembly allows. -Rule ID | Title | Category | Enabled | Severity | CodeFix | Description | ---------|-------|----------|---------|----------|---------|--------------------------------------------------------------------------------------------------------------| -[RS0030](https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.BannedApiAnalyzers/BannedApiAnalyzers.Help.md) | Do not used banned APIs | ApiDesign | True | Warning | False | The symbol has been marked as banned in this project, and an alternate should be used instead. | -[RS0031](https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.BannedApiAnalyzers/BannedApiAnalyzers.Help.md) | The list of banned symbols contains a duplicate | ApiDesign | True | Warning | False | The list of banned symbols contains a duplicate. | -RS0035 | External access to internal symbols outside the restricted namespace(s) is prohibited | ApiDesign | True | Error | False | RestrictedInternalsVisibleToAttribute enables a restricted version of InternalsVisibleToAttribute that limits access to internal symbols to those within specified namespaces. Each referencing assembly can only access internal symbols defined in the restricted namespaces that the referenced assembly allows. | diff --git a/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.md b/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.md index d4f06704b7..c8283356a3 100644 --- a/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.md +++ b/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.md @@ -1,243 +1,3213 @@ +# Microsoft.CodeAnalysis.FxCopAnalyzers + +## [CA1000](https://docs.microsoft.com/visualstudio/code-quality/ca1000): Do not declare static members on generic types + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +When a static member of a generic type is called, the type argument must be specified for the type. When a generic instance member that does not support inference is called, the type argument must be specified for the member. In these two cases, the syntax for specifying the type argument is different and easily confused. + +## [CA1001](https://docs.microsoft.com/visualstudio/code-quality/ca1001): Types that own disposable fields should be disposable + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +A class declares and implements an instance field that is a System.IDisposable type, and the class does not implement IDisposable. A class that declares an IDisposable field indirectly owns an unmanaged resource and should implement the IDisposable interface. + +## [CA1002](https://docs.microsoft.com/visualstudio/code-quality/ca1002): Do not expose generic lists + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +System.Collections.Generic.List is a generic collection that's designed for performance and not inheritance. List does not contain virtual members that make it easier to change the behavior of an inherited class. + +## [CA1003](https://docs.microsoft.com/visualstudio/code-quality/ca1003): Use generic event handler instances + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A type contains an event that declares an EventHandler delegate that returns void, whose signature contains two parameters (the first an object and the second a type that is assignable to EventArgs), and the containing assembly targets Microsoft .NET Framework?2.0. + +## [CA1005](https://docs.microsoft.com/visualstudio/code-quality/ca1005): Avoid excessive parameters on generic types + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The more type parameters a generic type contains, the more difficult it is to know and remember what each type parameter represents. + +## [CA1008](https://docs.microsoft.com/visualstudio/code-quality/ca1008): Enums should have zero value + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +The default value of an uninitialized enumeration, just as other value types, is zero. A nonflags-attributed enumeration should define a member by using the value of zero so that the default value is a valid value of the enumeration. If an enumeration that has the FlagsAttribute attribute applied defines a zero-valued member, its name should be ""None"" to indicate that no values have been set in the enumeration. + +## [CA1010](https://docs.microsoft.com/visualstudio/code-quality/ca1010): Generic interface should also be implemented + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +To broaden the usability of a type, implement one of the generic interfaces. This is especially true for collections as they can then be used to populate generic collection types. + +## [CA1012](https://docs.microsoft.com/visualstudio/code-quality/ca1012): Abstract types should not have public constructors + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Constructors on abstract types can be called only by derived types. Because public constructors create instances of a type, and you cannot create instances of an abstract type, an abstract type that has a public constructor is incorrectly designed. + +## [CA1014](https://docs.microsoft.com/visualstudio/code-quality/ca1014): Mark assemblies with CLSCompliant + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The Common Language Specification (CLS) defines naming restrictions, data types, and rules to which assemblies must conform if they will be used across programming languages. Good design dictates that all assemblies explicitly indicate CLS compliance by using CLSCompliantAttribute . If this attribute is not present on an assembly, the assembly is not compliant. + +## [CA1016](https://docs.microsoft.com/visualstudio/code-quality/ca1016): Mark assemblies with assembly version + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The .NET Framework uses the version number to uniquely identify an assembly, and to bind to types in strongly named assemblies. The version number is used together with version and publisher policy. By default, applications run only with the assembly version with which they were built. + +## [CA1017](https://docs.microsoft.com/visualstudio/code-quality/ca1017): Mark assemblies with ComVisible + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +ComVisibleAttribute determines how COM clients access managed code. Good design dictates that assemblies explicitly indicate COM visibility. COM visibility can be set for the whole assembly and then overridden for individual types and type members. If this attribute is not present, the contents of the assembly are visible to COM clients. + +## [CA1018](https://docs.microsoft.com/visualstudio/code-quality/ca1018): Mark attributes with AttributeUsageAttribute + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Specify AttributeUsage on {0} + +## [CA1019](https://docs.microsoft.com/visualstudio/code-quality/ca1019): Define accessors for attribute arguments + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Remove the property setter from {0} or reduce its accessibility because it corresponds to positional argument {1} + +## [CA1021](https://docs.microsoft.com/visualstudio/code-quality/ca1021): Avoid out parameters + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Passing types by reference (using 'out' or 'ref') requires experience with pointers, understanding how value types and reference types differ, and handling methods with multiple return values. Also, the difference between 'out' and 'ref' parameters is not widely understood. + +## [CA1024](https://docs.microsoft.com/visualstudio/code-quality/ca1024): Use properties where appropriate + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A public or protected method has a name that starts with ""Get"", takes no parameters, and returns a value that is not an array. The method might be a good candidate to become a property. + +## [CA1027](https://docs.microsoft.com/visualstudio/code-quality/ca1027): Mark enums with FlagsAttribute + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +An enumeration is a value type that defines a set of related named constants. Apply FlagsAttribute to an enumeration when its named constants can be meaningfully combined. + +## [CA1028](https://docs.microsoft.com/visualstudio/code-quality/ca1028): Enum Storage should be Int32 + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +An enumeration is a value type that defines a set of related named constants. By default, the System.Int32 data type is used to store the constant value. Although you can change this underlying type, it is not required or recommended for most scenarios. + +## [CA1030](https://docs.microsoft.com/visualstudio/code-quality/ca1030): Use events where appropriate + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +This rule detects methods that have names that ordinarily would be used for events. If a method is called in response to a clearly defined state change, the method should be invoked by an event handler. Objects that call the method should raise events instead of calling the method directly. + +## [CA1031](https://docs.microsoft.com/visualstudio/code-quality/ca1031): Do not catch general exception types + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A general exception such as System.Exception or System.SystemException or a disallowed exception type is caught in a catch statement, or a general catch clause is used. General and disallowed exceptions should not be caught. + +## [CA1032](https://docs.microsoft.com/visualstudio/code-quality/ca1032): Implement standard exception constructors + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Failure to provide the full set of constructors can make it difficult to correctly handle exceptions. + +## [CA1033](https://docs.microsoft.com/visualstudio/code-quality/ca1033): Interface methods should be callable by child types + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +An unsealed externally visible type provides an explicit method implementation of a public interface and does not provide an alternative externally visible method that has the same name. + +## [CA1034](https://docs.microsoft.com/visualstudio/code-quality/ca1034): Nested types should not be visible + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A nested type is a type that is declared in the scope of another type. Nested types are useful to encapsulate private implementation details of the containing type. Used for this purpose, nested types should not be externally visible. + +## [CA1036](https://docs.microsoft.com/visualstudio/code-quality/ca1036): Override methods on comparable types + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +A public or protected type implements the System.IComparable interface. It does not override Object.Equals nor does it overload the language-specific operator for equality, inequality, less than, less than or equal, greater than or greater than or equal. + +## [CA1040](https://docs.microsoft.com/visualstudio/code-quality/ca1040): Avoid empty interfaces + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Interfaces define members that provide a behavior or usage contract. The functionality that is described by the interface can be adopted by any type, regardless of where the type appears in the inheritance hierarchy. A type implements an interface by providing implementations for the members of the interface. An empty interface does not define any members; therefore, it does not define a contract that can be implemented. + +## [CA1041](https://docs.microsoft.com/visualstudio/code-quality/ca1041): Provide ObsoleteAttribute message + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A type or member is marked by using a System.ObsoleteAttribute attribute that does not have its ObsoleteAttribute.Message property specified. When a type or member that is marked by using ObsoleteAttribute is compiled, the Message property of the attribute is displayed. This gives the user information about the obsolete type or member. + +## [CA1043](https://docs.microsoft.com/visualstudio/code-quality/ca1043): Use Integral Or String Argument For Indexers + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Indexers, that is, indexed properties, should use integer or string types for the index. These types are typically used for indexing data structures and increase the usability of the library. Use of the Object type should be restricted to those cases where the specific integer or string type cannot be specified at design time. If the design requires other types for the index, reconsider whether the type represents a logical data store. If it does not represent a logical data store, use a method. + +## [CA1044](https://docs.microsoft.com/visualstudio/code-quality/ca1044): Properties should not be write only + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Although it is acceptable and often necessary to have a read-only property, the design guidelines prohibit the use of write-only properties. This is because letting a user set a value, and then preventing the user from viewing that value, does not provide any security. Also, without read access, the state of shared objects cannot be viewed, which limits their usefulness. + +## [CA1045](https://docs.microsoft.com/visualstudio/code-quality/ca1045): Do not pass types by reference + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Passing types by reference (using out or ref) requires experience with pointers, understanding how value types and reference types differ, and handling methods that have multiple return values. Also, the difference between out and ref parameters is not widely understood. + +## [CA1046](https://docs.microsoft.com/visualstudio/code-quality/ca1046): Do not overload equality operator on reference types + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +For reference types, the default implementation of the equality operator is almost always correct. By default, two references are equal only if they point to the same object. If the operator is providing meaningful value equality, the type should implement the generic 'System.IEquatable' interface. + +## [CA1047](https://docs.microsoft.com/visualstudio/code-quality/ca1047): Do not declare protected member in sealed type + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Types declare protected members so that inheriting types can access or override the member. By definition, you cannot inherit from a sealed type, which means that protected methods on sealed types cannot be called. + +## [CA1050](https://docs.microsoft.com/visualstudio/code-quality/ca1050): Declare types in namespaces + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Types are declared in namespaces to prevent name collisions and as a way to organize related types in an object hierarchy. + +## [CA1051](https://docs.microsoft.com/visualstudio/code-quality/ca1051): Do not declare visible instance fields + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The primary use of a field should be as an implementation detail. Fields should be private or internal and should be exposed by using properties. + +## [CA1052](https://docs.microsoft.com/visualstudio/code-quality/ca1052): Static holder types should be Static or NotInheritable + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Type '{0}' is a static holder type but is neither static nor NotInheritable + +## [CA1054](https://docs.microsoft.com/visualstudio/code-quality/ca1054): URI-like parameters should not be strings + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +This rule assumes that the parameter represents a Uniform Resource Identifier (URI). A string representation or a URI is prone to parsing and encoding errors, and can lead to security vulnerabilities. 'System.Uri' class provides these services in a safe and secure manner. + +## [CA1055](https://docs.microsoft.com/visualstudio/code-quality/ca1055): URI-like return values should not be strings + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +This rule assumes that the method returns a URI. A string representation of a URI is prone to parsing and encoding errors, and can lead to security vulnerabilities. The System.Uri class provides these services in a safe and secure manner. + +## [CA1056](https://docs.microsoft.com/visualstudio/code-quality/ca1056): URI-like properties should not be strings + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +This rule assumes that the property represents a Uniform Resource Identifier (URI). A string representation of a URI is prone to parsing and encoding errors, and can lead to security vulnerabilities. The System.Uri class provides these services in a safe and secure manner. + +## [CA1058](https://docs.microsoft.com/visualstudio/code-quality/ca1058): Types should not extend certain base types + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +An externally visible type extends certain base types. Use one of the alternatives. + +## [CA1060](https://docs.microsoft.com/visualstudio/code-quality/ca1060): Move pinvokes to native methods class + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Platform Invocation methods, such as those that are marked by using the System.Runtime.InteropServices.DllImportAttribute attribute, or methods that are defined by using the Declare keyword in Visual Basic, access unmanaged code. These methods should be of the NativeMethods, SafeNativeMethods, or UnsafeNativeMethods class. + +## [CA1061](https://docs.microsoft.com/visualstudio/code-quality/ca1061): Do not hide base class methods + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A method in a base type is hidden by an identically named method in a derived type when the parameter signature of the derived method differs only by types that are more weakly derived than the corresponding types in the parameter signature of the base method. + +## [CA1062](https://docs.microsoft.com/visualstudio/code-quality/ca1062): Validate arguments of public methods + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +An externally visible method dereferences one of its reference arguments without verifying whether that argument is null (Nothing in Visual Basic). All reference arguments that are passed to externally visible methods should be checked against null. If appropriate, throw an ArgumentNullException when the argument is null or add a Code Contract precondition asserting non-null argument. If the method is designed to be called only by known assemblies, you should make the method internal. + +## [CA1063](https://docs.microsoft.com/visualstudio/code-quality/ca1063): Implement IDisposable Correctly + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +All IDisposable types should implement the Dispose pattern correctly. + +## [CA1064](https://docs.microsoft.com/visualstudio/code-quality/ca1064): Exceptions should be public + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +An internal exception is visible only inside its own internal scope. After the exception falls outside the internal scope, only the base exception can be used to catch the exception. If the internal exception is inherited from T:System.Exception, T:System.SystemException, or T:System.ApplicationException, the external code will not have sufficient information to know what to do with the exception. + +## [CA1065](https://docs.microsoft.com/visualstudio/code-quality/ca1065): Do not raise exceptions in unexpected locations + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A method that is not expected to throw exceptions throws an exception. + +## [CA1066](https://docs.microsoft.com/visualstudio/code-quality/ca1066): Implement IEquatable when overriding Object.Equals + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +When a type T overrides Object.Equals(object), the implementation must cast the object argument to the correct type T before performing the comparison. If the type implements IEquatable, and therefore offers the method T.Equals(T), and if the argument is known at compile time to be of type T, then the compiler can call IEquatable.Equals(T) instead of Object.Equals(object), and no cast is necessary, improving performance. + +## [CA1067](https://docs.microsoft.com/visualstudio/code-quality/ca1067): Override Object.Equals(object) when implementing IEquatable + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +When a type T implements the interface IEquatable, it suggests to a user who sees a call to the Equals method in source code that an instance of the type can be equated with an instance of any other type. The user might be confused if their attempt to equate the type with an instance of another type fails to compile. This violates the "principle of least surprise". + +## [CA1068](https://docs.microsoft.com/visualstudio/code-quality/ca1068): CancellationToken parameters must come last + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Method '{0}' should take CancellationToken as the last parameter + +## [CA1069](https://docs.microsoft.com/visualstudio/code-quality/ca1069): Enums values should not be duplicated + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The field reference '{0}' is duplicated in this bitwise initialization + +## [CA1070](https://docs.microsoft.com/visualstudio/code-quality/ca1070): Do not declare event fields as virtual + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Do not declare virtual events in a base class. Overridden events in a derived class have undefined behavior. The C# compiler does not handle this correctly and it is unpredictable whether a subscriber to the derived event will actually be subscribing to the base class event. + +## [CA1200](https://docs.microsoft.com/visualstudio/code-quality/ca1200): Avoid using cref tags with a prefix + +|Item|Value| +|-|-| +|Category|Documentation| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Use of cref tags with prefixes should be avoided, since it prevents the compiler from verifying references and the IDE from updating references during refactorings. It is permissible to suppress this error at a single documentation site if the cref must use a prefix because the type being mentioned is not findable by the compiler. For example, if a cref is mentioning a special attribute in the full framework but you're in a file that compiles against the portable framework, or if you want to reference a type at higher layer of Roslyn, you should suppress the error. You should not suppress the error just because you want to take a shortcut and avoid using the full syntax. + +## [CA1303](https://docs.microsoft.com/visualstudio/code-quality/ca1303): Do not pass literals as localized parameters + +|Item|Value| +|-|-| +|Category|Globalization| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A method passes a string literal as a parameter to a constructor or method in the .NET Framework class library and that string should be localizable. To fix a violation of this rule, replace the string literal with a string retrieved through an instance of the ResourceManager class. + +## [CA1304](https://docs.microsoft.com/visualstudio/code-quality/ca1304): Specify CultureInfo + +|Item|Value| +|-|-| +|Category|Globalization| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A method or constructor calls a member that has an overload that accepts a System.Globalization.CultureInfo parameter, and the method or constructor does not call the overload that takes the CultureInfo parameter. When a CultureInfo or System.IFormatProvider object is not supplied, the default value that is supplied by the overloaded member might not have the effect that you want in all locales. If the result will be displayed to the user, specify 'CultureInfo.CurrentCulture' as the 'CultureInfo' parameter. Otherwise, if the result will be stored and accessed by software, such as when it is persisted to disk or to a database, specify 'CultureInfo.InvariantCulture'. + +## [CA1305](https://docs.microsoft.com/visualstudio/code-quality/ca1305): Specify IFormatProvider + +|Item|Value| +|-|-| +|Category|Globalization| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A method or constructor calls one or more members that have overloads that accept a System.IFormatProvider parameter, and the method or constructor does not call the overload that takes the IFormatProvider parameter. When a System.Globalization.CultureInfo or IFormatProvider object is not supplied, the default value that is supplied by the overloaded member might not have the effect that you want in all locales. If the result will be based on the input from/output displayed to the user, specify 'CultureInfo.CurrentCulture' as the 'IFormatProvider'. Otherwise, if the result will be stored and accessed by software, such as when it is loaded from disk/database and when it is persisted to disk/database, specify 'CultureInfo.InvariantCulture'. + +## [CA1307](https://docs.microsoft.com/visualstudio/code-quality/ca1307): Specify StringComparison + +|Item|Value| +|-|-| +|Category|Globalization| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A string comparison operation uses a method overload that does not set a StringComparison parameter. If the result will be displayed to the user, such as when sorting a list of items for display in a list box, specify 'StringComparison.CurrentCulture' or 'StringComparison.CurrentCultureIgnoreCase' as the 'StringComparison' parameter. If comparing case-insensitive identifiers, such as file paths, environment variables, or registry keys and values, specify 'StringComparison.OrdinalIgnoreCase'. Otherwise, if comparing case-sensitive identifiers, specify 'StringComparison.Ordinal'. + +## [CA1308](https://docs.microsoft.com/visualstudio/code-quality/ca1308): Normalize strings to uppercase + +|Item|Value| +|-|-| +|Category|Globalization| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Strings should be normalized to uppercase. A small group of characters cannot make a round trip when they are converted to lowercase. To make a round trip means to convert the characters from one locale to another locale that represents character data differently, and then to accurately retrieve the original characters from the converted characters. + +## [CA1309](https://docs.microsoft.com/visualstudio/code-quality/ca1309): Use ordinal stringcomparison + +|Item|Value| +|-|-| +|Category|Globalization| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +A string comparison operation that is nonlinguistic does not set the StringComparison parameter to either Ordinal or OrdinalIgnoreCase. By explicitly setting the parameter to either StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase, your code often gains speed, becomes more correct, and becomes more reliable. + +## [CA1401](https://docs.microsoft.com/visualstudio/code-quality/ca1401): P/Invokes should not be visible + +|Item|Value| +|-|-| +|Category|Interoperability| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A public or protected method in a public type has the System.Runtime.InteropServices.DllImportAttribute attribute (also implemented by the Declare keyword in Visual Basic). Such methods should not be exposed. + +## [CA1417](https://docs.microsoft.com/visualstudio/code-quality/ca1417): Do not use 'OutAttribute' on string parameters for P/Invokes + +|Item|Value| +|-|-| +|Category|Interoperability| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +String parameters passed by value with the 'OutAttribute' can destabilize the runtime if the string is an interned string. + +## [CA1501](https://docs.microsoft.com/visualstudio/code-quality/ca1501): Avoid excessive inheritance + +|Item|Value| +|-|-| +|Category|Maintainability| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Deeply nested type hierarchies can be difficult to follow, understand, and maintain. This rule limits analysis to hierarchies in the same module. To fix a violation of this rule, derive the type from a base type that is less deep in the inheritance hierarchy or eliminate some of the intermediate base types. + +## [CA1502](https://docs.microsoft.com/visualstudio/code-quality/ca1502): Avoid excessive complexity + +|Item|Value| +|-|-| +|Category|Maintainability| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Cyclomatic complexity measures the number of linearly independent paths through the method, which is determined by the number and complexity of conditional branches. A low cyclomatic complexity generally indicates a method that is easy to understand, test, and maintain. The cyclomatic complexity is calculated from a control flow graph of the method and is given as follows: `cyclomatic complexity = the number of edges - the number of nodes + 1`, where a node represents a logic branch point and an edge represents a line between nodes. + +## [CA1505](https://docs.microsoft.com/visualstudio/code-quality/ca1505): Avoid unmaintainable code + +|Item|Value| +|-|-| +|Category|Maintainability| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The maintainability index is calculated by using the following metrics: lines of code, program volume, and cyclomatic complexity. Program volume is a measure of the difficulty of understanding of a symbol that is based on the number of operators and operands in the code. Cyclomatic complexity is a measure of the structural complexity of the type or method. A low maintainability index indicates that code is probably difficult to maintain and would be a good candidate to redesign. + +## [CA1506](https://docs.microsoft.com/visualstudio/code-quality/ca1506): Avoid excessive class coupling + +|Item|Value| +|-|-| +|Category|Maintainability| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +This rule measures class coupling by counting the number of unique type references that a symbol contains. Symbols that have a high degree of class coupling can be difficult to maintain. It is a good practice to have types and methods that exhibit low coupling and high cohesion. To fix this violation, try to redesign the code to reduce the number of types to which it is coupled. + +## [CA1507](https://docs.microsoft.com/visualstudio/code-quality/ca1507): Use nameof to express symbol names + +|Item|Value| +|-|-| +|Category|Maintainability| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Using nameof helps keep your code valid when refactoring. + +## [CA1508](https://docs.microsoft.com/visualstudio/code-quality/ca1508): Avoid dead conditional code + +|Item|Value| +|-|-| +|Category|Maintainability| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +'{0}' is never '{1}'. Remove or refactor the condition(s) to avoid dead code. + +## [CA1509](https://docs.microsoft.com/visualstudio/code-quality/ca1509): Invalid entry in code metrics rule specification file + +|Item|Value| +|-|-| +|Category|Maintainability| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Invalid entry in code metrics rule specification file. + +## [CA1700](https://docs.microsoft.com/visualstudio/code-quality/ca1700): Do not name enum values 'Reserved' + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +This rule assumes that an enumeration member that has a name that contains "reserved" is not currently used but is a placeholder to be renamed or removed in a future version. Renaming or removing a member is a breaking change. + +## [CA1707](https://docs.microsoft.com/visualstudio/code-quality/ca1707): Identifiers should not contain underscores + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +By convention, identifier names do not contain the underscore (_) character. This rule checks namespaces, types, members, and parameters. + +## [CA1708](https://docs.microsoft.com/visualstudio/code-quality/ca1708): Identifiers should differ by more than case + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Identifiers for namespaces, types, members, and parameters cannot differ only by case because languages that target the common language runtime are not required to be case-sensitive. + +## [CA1710](https://docs.microsoft.com/visualstudio/code-quality/ca1710): Identifiers should have correct suffix + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +By convention, the names of types that extend certain base types or that implement certain interfaces, or types that are derived from these types, have a suffix that is associated with the base type or interface. + +## [CA1711](https://docs.microsoft.com/visualstudio/code-quality/ca1711): Identifiers should not have incorrect suffix + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +By convention, only the names of types that extend certain base types or that implement certain interfaces, or types that are derived from these types, should end with specific reserved suffixes. Other type names should not use these reserved suffixes. + +## [CA1712](https://docs.microsoft.com/visualstudio/code-quality/ca1712): Do not prefix enum values with type name + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +An enumeration's values should not start with the type name of the enumeration. + +## [CA1713](https://docs.microsoft.com/visualstudio/code-quality/ca1713): Events should not have 'Before' or 'After' prefix + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Event names should describe the action that raises the event. To name related events that are raised in a specific sequence, use the present or past tense to indicate the relative position in the sequence of actions. For example, when naming a pair of events that is raised when closing a resource, you might name it 'Closing' and 'Closed', instead of 'BeforeClose' and 'AfterClose'. + +## [CA1714](https://docs.microsoft.com/visualstudio/code-quality/ca1714): Flags enums should have plural names + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A public enumeration has the System.FlagsAttribute attribute, and its name does not end in ""s"". Types that are marked by using FlagsAttribute have names that are plural because the attribute indicates that more than one value can be specified. + +## [CA1715](https://docs.microsoft.com/visualstudio/code-quality/ca1715): Identifiers should have correct prefix + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The name of an externally visible interface does not start with an uppercase ""I"". The name of a generic type parameter on an externally visible type or method does not start with an uppercase ""T"". + +## [CA1716](https://docs.microsoft.com/visualstudio/code-quality/ca1716): Identifiers should not match keywords + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A namespace name or a type name matches a reserved keyword in a programming language. Identifiers for namespaces and types should not match keywords that are defined by languages that target the common language runtime. + +## [CA1717](https://docs.microsoft.com/visualstudio/code-quality/ca1717): Only FlagsAttribute enums should have plural names + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Naming conventions dictate that a plural name for an enumeration indicates that more than one value of the enumeration can be specified at the same time. + +## [CA1720](https://docs.microsoft.com/visualstudio/code-quality/ca1720): Identifier contains type name + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Names of parameters and members are better used to communicate their meaning than to describe their type, which is expected to be provided by development tools. For names of members, if a data type name must be used, use a language-independent name instead of a language-specific one. + +## [CA1721](https://docs.microsoft.com/visualstudio/code-quality/ca1721): Property names should not match get methods + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The name of a public or protected member starts with ""Get"" and otherwise matches the name of a public or protected property. ""Get"" methods and properties should have names that clearly distinguish their function. + +## [CA1724](https://docs.microsoft.com/visualstudio/code-quality/ca1724): Type names should not match namespaces + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Type names should not match the names of namespaces that are defined in the .NET Framework class library. Violating this rule can reduce the usability of the library. + +## [CA1725](https://docs.microsoft.com/visualstudio/code-quality/ca1725): Parameter names should match base declaration + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Consistent naming of parameters in an override hierarchy increases the usability of the method overrides. A parameter name in a derived method that differs from the name in the base declaration can cause confusion about whether the method is an override of the base method or a new overload of the method. + +## [CA1801](https://docs.microsoft.com/visualstudio/code-quality/ca1801): Review unused parameters + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Avoid unused paramereters in your code. If the parameter cannot be removed, then change its name so it starts with an underscore and is optionally followed by an integer, such as '_', '_1', '_2', etc. These are treated as special discard symbol names. + +## [CA1802](https://docs.microsoft.com/visualstudio/code-quality/ca1802): Use literals where appropriate + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +A field is declared static and read-only (Shared and ReadOnly in Visual Basic), and is initialized by using a value that is computable at compile time. Because the value that is assigned to the targeted field is computable at compile time, change the declaration to a const (Const in Visual Basic) field so that the value is computed at compile time instead of at run?time. + +## [CA1805](https://docs.microsoft.com/visualstudio/code-quality/ca1805): Do not initialize unnecessarily + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +The .NET runtime initializes all fields of reference types to their default values before running the constructor. In most cases, explicitly initializing a field to its default value in a constructor is redundant, adding maintenance costs and potentially degrading performance (such as with increased assembly size), and the explicit initialization can be removed. In some cases, such as with static readonly fields that permanently retain their default value, consider instead changing them to be constants or properties. + +## [CA1806](https://docs.microsoft.com/visualstudio/code-quality/ca1806): Do not ignore method results + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A new object is created but never used; or a method that creates and returns a new string is called and the new string is never used; or a COM or P/Invoke method returns an HRESULT or error code that is never used. + +## [CA1810](https://docs.microsoft.com/visualstudio/code-quality/ca1810): Initialize reference type static fields inline + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A reference 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. + +## [CA1812](https://docs.microsoft.com/visualstudio/code-quality/ca1812): Avoid uninstantiated internal classes + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +An instance of an assembly-level type is not created by code in the assembly. + +## [CA1813](https://docs.microsoft.com/visualstudio/code-quality/ca1813): Avoid unsealed attributes + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +The .NET Framework class library provides methods for retrieving custom attributes. By default, these methods search the attribute inheritance hierarchy. Sealing the attribute eliminates the search through the inheritance hierarchy and can improve performance. + +## [CA1814](https://docs.microsoft.com/visualstudio/code-quality/ca1814): Prefer jagged arrays over multidimensional + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A jagged array is an array whose elements are arrays. The arrays that make up the elements can be of different sizes, leading to less wasted space for some sets of data. + +## [CA1815](https://docs.microsoft.com/visualstudio/code-quality/ca1815): Override equals and operator equals on value types + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +For value types, the inherited implementation of Equals uses the Reflection library and compares the contents of all fields. Reflection is computationally expensive, and comparing every field for equality might be unnecessary. If you expect users to compare or sort instances, or to use instances as hash table keys, your value type should implement Equals. + +## [CA1816](https://docs.microsoft.com/visualstudio/code-quality/ca1816): Dispose methods should call SuppressFinalize + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A method that is an implementation of Dispose does not call GC.SuppressFinalize; or a method that is not an implementation of Dispose calls GC.SuppressFinalize; or a method calls GC.SuppressFinalize and passes something other than this (Me in Visual?Basic). + +## [CA1819](https://docs.microsoft.com/visualstudio/code-quality/ca1819): Properties should not return arrays + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Arrays that are returned by properties are not write-protected, even when the property is read-only. To keep the array tamper-proof, the property must return a copy of the array. Typically, users will not understand the adverse performance implications of calling such a property. + +## [CA1820](https://docs.microsoft.com/visualstudio/code-quality/ca1820): Test for empty strings using string length + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Comparing strings by using the String.Length property or the String.IsNullOrEmpty method is significantly faster than using Equals. + +## [CA1821](https://docs.microsoft.com/visualstudio/code-quality/ca1821): Remove empty Finalizers + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Finalizers should be avoided where possible, to avoid the additional performance overhead involved in tracking object lifetime. + +## [CA1822](https://docs.microsoft.com/visualstudio/code-quality/ca1822): Mark members as static + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Members that do not access instance data or call instance methods can be marked as static. After you mark the methods as static, the compiler will emit nonvirtual call sites to these members. This can give you a measurable performance gain for performance-sensitive code. + +## [CA1823](https://docs.microsoft.com/visualstudio/code-quality/ca1823): Avoid unused private fields + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Private fields were detected that do not appear to be accessed in the assembly. + +## [CA1824](https://docs.microsoft.com/visualstudio/code-quality/ca1824): Mark assemblies with NeutralResourcesLanguageAttribute + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The NeutralResourcesLanguage attribute informs the ResourceManager of the language that was used to display the resources of a neutral culture for an assembly. This improves lookup performance for the first resource that you load and can reduce your working set. + +## [CA1825](https://docs.microsoft.com/visualstudio/code-quality/ca1825): Avoid zero-length array allocations + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Avoid unnecessary zero-length array allocations. Use {0} instead. + +## [CA1826](https://docs.microsoft.com/visualstudio/code-quality/ca1826): Do not use Enumerable methods on indexable collections + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +This collection is directly indexable. Going through LINQ here causes unnecessary allocations and CPU work. + +## [CA1827](https://docs.microsoft.com/visualstudio/code-quality/ca1827): Do not use Count() or LongCount() when Any() can be used + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +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. + +## [CA1828](https://docs.microsoft.com/visualstudio/code-quality/ca1828): Do not use CountAsync() or LongCountAsync() when AnyAsync() can be used + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +For non-empty collections, CountAsync() and LongCountAsync() enumerate the entire sequence, while AnyAsync() stops at the first item or the first item that satisfies a condition. + +## [CA1829](https://docs.microsoft.com/visualstudio/code-quality/ca1829): Use Length/Count property instead of Count() when available + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. + +## [CA1830](https://docs.microsoft.com/visualstudio/code-quality/ca1830): Prefer strongly-typed Append and Insert method overloads on StringBuilder + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +StringBuilder.Append and StringBuilder.Insert provide overloads for multiple types beyond System.String. When possible, prefer the strongly-typed overloads over using ToString() and the string-based overload. + +## [CA1831](https://docs.microsoft.com/visualstudio/code-quality/ca1831): Use AsSpan or AsMemory instead of Range-based indexers when appropriate + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +The Range-based indexer on string values produces a copy of requested portion of the string. This copy is usually unnecessary when it is implicitly used as a ReadOnlySpan or ReadOnlyMemory value. Use the AsSpan method to avoid the unnecessary copy. + +## [CA1832](https://docs.microsoft.com/visualstudio/code-quality/ca1832): Use AsSpan or AsMemory instead of Range-based indexers when appropriate + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +The Range-based indexer on array values produces a copy of requested portion of the array. This copy is usually unnecessary when it is implicitly used as a ReadOnlySpan or ReadOnlyMemory value. Use the AsSpan method to avoid the unnecessary copy. + +## [CA1833](https://docs.microsoft.com/visualstudio/code-quality/ca1833): Use AsSpan or AsMemory instead of Range-based indexers when appropriate + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +The Range-based indexer on array values produces a copy of requested portion of the array. This copy is often unwanted when it is implicitly used as a Span or Memory value. Use the AsSpan method to avoid the copy. + +## [CA1834](https://docs.microsoft.com/visualstudio/code-quality/ca1834): Consider using 'StringBuilder.Append(char)' when applicable + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +'StringBuilder.Append(char)' is more efficient than 'StringBuilder.Append(string)' when the string is a single character. When calling 'Append' with a constant, prefer using a constant char rather than a constant string containing one character. + +## [CA1835](https://docs.microsoft.com/visualstudio/code-quality/ca1835): Prefer the 'Memory'-based overloads for 'ReadAsync' and 'WriteAsync' + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +'Stream' has a 'ReadAsync' overload that takes a 'Memory' as the first argument, and a 'WriteAsync' overload that takes a 'ReadOnlyMemory' as the first argument. Prefer calling the memory based overloads, which are more efficient. + +## [CA1836](https://docs.microsoft.com/visualstudio/code-quality/ca1836): Prefer IsEmpty over Count + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +For determining whether the object contains or not any items, prefer using 'IsEmpty' property rather than retrieving the number of items from the 'Count' property and comparing it to 0 or 1. + +## [CA1837](https://docs.microsoft.com/visualstudio/code-quality/ca1837): Use 'Environment.ProcessId' + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +'Environment.ProcessId' is simpler and faster than 'Process.GetCurrentProcess().Id'. + +## [CA1838](https://docs.microsoft.com/visualstudio/code-quality/ca1838): Avoid 'StringBuilder' parameters for P/Invokes + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Marshalling of 'StringBuilder' always creates a native buffer copy, resulting in multiple allocations for one marshalling operation. + +## [CA2000](https://docs.microsoft.com/visualstudio/code-quality/ca2000): Dispose objects before losing scope + +|Item|Value| +|-|-| +|Category|Reliability| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2002](https://docs.microsoft.com/visualstudio/code-quality/ca2002): Do not lock on objects with weak identity + +|Item|Value| +|-|-| +|Category|Reliability| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2007](https://docs.microsoft.com/visualstudio/code-quality/ca2007): Consider calling ConfigureAwait on the awaited task + +|Item|Value| +|-|-| +|Category|Reliability| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +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. + +## [CA2008](https://docs.microsoft.com/visualstudio/code-quality/ca2008): Do not create tasks without passing a TaskScheduler + +|Item|Value| +|-|-| +|Category|Reliability| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2009](https://docs.microsoft.com/visualstudio/code-quality/ca2009): Do not call ToImmutableCollection on an ImmutableCollection value + +|Item|Value| +|-|-| +|Category|Reliability| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Do not call {0} on an {1} value + +## [CA2011](https://docs.microsoft.com/visualstudio/code-quality/ca2011): Avoid infinite recursion + +|Item|Value| +|-|-| +|Category|Reliability| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Do not assign the property within its setter. This call might result in an infinite recursion. + +## [CA2012](https://docs.microsoft.com/visualstudio/code-quality/ca2012): Use ValueTasks correctly + +|Item|Value| +|-|-| +|Category|Reliability| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +ValueTasks returned from member invocations are intended to be directly awaited. Attempts to consume a ValueTask multiple times or to directly access one's result before it's known to be completed may result in an exception or corruption. Ignoring such a ValueTask is likely an indication of a functional bug and may degrade performance. + +## [CA2013](https://docs.microsoft.com/visualstudio/code-quality/ca2013): Do not use ReferenceEquals with value types + +|Item|Value| +|-|-| +|Category|Reliability| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Value type typed arguments are uniquely boxed for each call to this method, therefore the result is always false. + +## [CA2014](https://docs.microsoft.com/visualstudio/code-quality/ca2014): Do not use stackalloc in loops + +|Item|Value| +|-|-| +|Category|Reliability| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Stack space allocated by a stackalloc is only released at the end of the current method's invocation. Using it in a loop can result in unbounded stack growth and eventual stack overflow conditions. + +## [CA2015](https://docs.microsoft.com/visualstudio/code-quality/ca2015): Do not define finalizers for types derived from MemoryManager + +|Item|Value| +|-|-| +|Category|Reliability| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Adding a finalizer to a type derived from MemoryManager may permit memory to be freed while it is still in use by a Span. + +## [CA2016](https://docs.microsoft.com/visualstudio/code-quality/ca2016): Forward the 'CancellationToken' parameter to methods that take one + +|Item|Value| +|-|-| +|Category|Reliability| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Forward the 'CancellationToken' parameter to methods that take one to ensure the operation cancellation notifications gets properly propagated, or pass in 'CancellationToken.None' explicitly to indicate intentionally not propagating the token. + +## [CA2100](https://docs.microsoft.com/visualstudio/code-quality/ca2100): Review SQL queries for security vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2101](https://docs.microsoft.com/visualstudio/code-quality/ca2101): Specify marshaling for P/Invoke string arguments + +|Item|Value| +|-|-| +|Category|Globalization| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +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. + +## [CA2109](https://docs.microsoft.com/visualstudio/code-quality/ca2109): Review visible event handlers + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A public or protected event-handling method was detected. Event-handling methods should not be exposed unless absolutely necessary. + +## [CA2119](https://docs.microsoft.com/visualstudio/code-quality/ca2119): Seal methods that satisfy private interfaces + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +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. + +## [CA2153](https://docs.microsoft.com/visualstudio/code-quality/ca2153): Do Not Catch Corrupted State Exceptions + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2200](https://docs.microsoft.com/visualstudio/code-quality/ca2200): Rethrow to preserve stack details + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Re-throwing caught exception changes stack information + +## [CA2201](https://docs.microsoft.com/visualstudio/code-quality/ca2201): Do not raise reserved exception types + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2207](https://docs.microsoft.com/visualstudio/code-quality/ca2207): Initialize value type static fields inline + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2208](https://docs.microsoft.com/visualstudio/code-quality/ca2208): Instantiate argument exceptions correctly + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +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. + +## [CA2211](https://docs.microsoft.com/visualstudio/code-quality/ca2211): Non-constant fields should not be visible + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2213](https://docs.microsoft.com/visualstudio/code-quality/ca2213): Disposable fields should be disposed + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2214](https://docs.microsoft.com/visualstudio/code-quality/ca2214): Do not call overridable methods in constructors + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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). + +## [CA2215](https://docs.microsoft.com/visualstudio/code-quality/ca2215): Dispose methods should call base class dispose + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +A type that implements System.IDisposable inherits from a type that also implements IDisposable. The Dispose method of the inheriting type does not call the Dispose method of the parent type. To fix a violation of this rule, call base.Dispose in your Dispose method. + +## [CA2216](https://docs.microsoft.com/visualstudio/code-quality/ca2216): Disposable types should declare finalizer + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2217](https://docs.microsoft.com/visualstudio/code-quality/ca2217): Do not mark enums with FlagsAttribute + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +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. + +## [CA2218](https://docs.microsoft.com/visualstudio/code-quality/ca2218): Override GetHashCode on overriding Equals + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +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. + +## [CA2219](https://docs.microsoft.com/visualstudio/code-quality/ca2219): Do not raise exceptions in finally clauses + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2224](https://docs.microsoft.com/visualstudio/code-quality/ca2224): Override Equals on overloading operator equals + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +A public type implements the equality operator but does not override Object.Equals. + +## [CA2225](https://docs.microsoft.com/visualstudio/code-quality/ca2225): Operator overloads have named alternates + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +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. + +## [CA2226](https://docs.microsoft.com/visualstudio/code-quality/ca2226): Operators should have symmetrical overloads + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +A type implements the equality or inequality operator and does not implement the opposite operator. + +## [CA2227](https://docs.microsoft.com/visualstudio/code-quality/ca2227): Collection properties should be read only + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2229](https://docs.microsoft.com/visualstudio/code-quality/ca2229): Implement serialization constructors + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +To fix a violation of this rule, implement the serialization constructor. For a sealed class, make the constructor private; otherwise, make it protected. + +## [CA2231](https://docs.microsoft.com/visualstudio/code-quality/ca2231): Overload operator equals on overriding value type Equals + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +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. + +## [CA2234](https://docs.microsoft.com/visualstudio/code-quality/ca2234): Pass system uri objects instead of strings + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2235](https://docs.microsoft.com/visualstudio/code-quality/ca2235): Mark all non-serializable fields + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +An instance field of a type that is not serializable is declared in a type that is serializable. + +## [CA2237](https://docs.microsoft.com/visualstudio/code-quality/ca2237): Mark ISerializable types with serializable + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +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. + +## [CA2241](https://docs.microsoft.com/visualstudio/code-quality/ca2241): Provide correct arguments to formatting methods + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2242](https://docs.microsoft.com/visualstudio/code-quality/ca2242): Test for NaN correctly + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +This expression tests a value against Single.Nan or Double.Nan. Use Single.IsNan(Single) or Double.IsNan(Double) to test the value. + +## [CA2243](https://docs.microsoft.com/visualstudio/code-quality/ca2243): Attribute string literals should parse correctly + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The string literal parameter of an attribute does not parse correctly for a URL, a GUID, or a version. + +## [CA2244](https://docs.microsoft.com/visualstudio/code-quality/ca2244): Do not duplicate indexed element initializations + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Indexed elements in objects initializers must initialize unique elements. A duplicate index might overwrite a previous element initialization. + +## [CA2245](https://docs.microsoft.com/visualstudio/code-quality/ca2245): Do not assign a property to itself + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The property {0} should not be assigned to itself + +## [CA2246](https://docs.microsoft.com/visualstudio/code-quality/ca2246): Assigning symbol and its member in the same statement + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2247](https://docs.microsoft.com/visualstudio/code-quality/ca2247): Argument passed to TaskCompletionSource constructor should be TaskCreationOptions enum instead of TaskContinuationOptions enum + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +TaskCompletionSource has constructors that take TaskCreationOptions that control the underlying Task, and constructors that take object state that's stored in the task. Accidentally passing a TaskContinuationOptions instead of a TaskCreationOptions will result in the call treating the options as state. + +## [CA2248](https://docs.microsoft.com/visualstudio/code-quality/ca2248): Provide correct 'enum' argument to 'Enum.HasFlag' + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +'Enum.HasFlag' method expects the 'enum' argument to be of the same 'enum' type as the instance on which the method is invoked and that this 'enum' is marked with 'System.FlagsAttribute'. If these are different 'enum' types, an unhandled exception will be thrown at runtime. If the 'enum' type is not marked with 'System.FlagsAttribute' the call will always return 'false' at runtime. + +## [CA2249](https://docs.microsoft.com/visualstudio/code-quality/ca2249): Consider using 'string.Contains' instead of 'string.IndexOf' + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Calls to 'string.IndexOf' where the result is used to check for the presence/absence of a substring can be replaced by 'string.Contains'. + +## [CA2300](https://docs.microsoft.com/visualstudio/code-quality/ca2300): Do not use insecure deserializer BinaryFormatter + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2301](https://docs.microsoft.com/visualstudio/code-quality/ca2301): Do not call BinaryFormatter.Deserialize without first setting BinaryFormatter.Binder + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. + +## [CA2302](https://docs.microsoft.com/visualstudio/code-quality/ca2302): Ensure BinaryFormatter.Binder is set before calling BinaryFormatter.Deserialize + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. + +## [CA2305](https://docs.microsoft.com/visualstudio/code-quality/ca2305): Do not use insecure deserializer LosFormatter + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The method '{0}' is insecure when deserializing untrusted data. + +## [CA2310](https://docs.microsoft.com/visualstudio/code-quality/ca2310): Do not use insecure deserializer NetDataContractSerializer + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2311](https://docs.microsoft.com/visualstudio/code-quality/ca2311): Do not deserialize without first setting NetDataContractSerializer.Binder + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. + +## [CA2312](https://docs.microsoft.com/visualstudio/code-quality/ca2312): Ensure NetDataContractSerializer.Binder is set before deserializing + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. + +## [CA2315](https://docs.microsoft.com/visualstudio/code-quality/ca2315): Do not use insecure deserializer ObjectStateFormatter + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The method '{0}' is insecure when deserializing untrusted data. + +## [CA2321](https://docs.microsoft.com/visualstudio/code-quality/ca2321): Do not deserialize with JavaScriptSerializer using a SimpleTypeResolver + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2322](https://docs.microsoft.com/visualstudio/code-quality/ca2322): Ensure JavaScriptSerializer is not initialized with SimpleTypeResolver before deserializing + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2326](https://docs.microsoft.com/visualstudio/code-quality/ca2326): Do not use TypeNameHandling values other than None + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2327](https://docs.microsoft.com/visualstudio/code-quality/ca2327): Do not use insecure JsonSerializerSettings + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2328](https://docs.microsoft.com/visualstudio/code-quality/ca2328): Ensure that JsonSerializerSettings are secure + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2329](https://docs.microsoft.com/visualstudio/code-quality/ca2329): Do not deserialize with JsonSerializer using an insecure configuration + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2330](https://docs.microsoft.com/visualstudio/code-quality/ca2330): Ensure that JsonSerializer has a secure configuration when deserializing + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2350](https://docs.microsoft.com/visualstudio/code-quality/ca2350): Do not use DataTable.ReadXml() with untrusted data + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The method '{0}' is insecure when deserializing untrusted data + +## [CA2351](https://docs.microsoft.com/visualstudio/code-quality/ca2351): Do not use DataSet.ReadXml() with untrusted data + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The method '{0}' is insecure when deserializing untrusted data + +## [CA2352](https://docs.microsoft.com/visualstudio/code-quality/ca2352): Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + +## [CA2353](https://docs.microsoft.com/visualstudio/code-quality/ca2353): Unsafe DataSet or DataTable in serializable type + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0} + +## [CA2354](https://docs.microsoft.com/visualstudio/code-quality/ca2354): Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0} + +## [CA2355](https://docs.microsoft.com/visualstudio/code-quality/ca2355): Unsafe DataSet or DataTable type found in deserializable object graph + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0} + +## [CA2356](https://docs.microsoft.com/visualstudio/code-quality/ca2356): Unsafe DataSet or DataTable type in web deserializable object graph + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0} + +## [CA2361](https://docs.microsoft.com/visualstudio/code-quality/ca2361): Ensure autogenerated class containing DataSet.ReadXml() is not used with untrusted data + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The method '{0}' is insecure when deserializing untrusted data. Make sure that autogenerated class containing the '{0}' call is not deserialized with untrusted data. + +## [CA2362](https://docs.microsoft.com/visualstudio/code-quality/ca2362): Unsafe DataSet or DataTable in autogenerated serializable type can be vulnerable to remote code execution attacks + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. Ensure that the autogenerated type is never deserialized with untrusted data. + +## [CA3001](https://docs.microsoft.com/visualstudio/code-quality/ca3001): Review code for SQL injection vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Potential SQL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. + +## [CA3002](https://docs.microsoft.com/visualstudio/code-quality/ca3002): Review code for XSS vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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}'. + +## [CA3003](https://docs.microsoft.com/visualstudio/code-quality/ca3003): Review code for file path injection vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Potential file path injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. + +## [CA3004](https://docs.microsoft.com/visualstudio/code-quality/ca3004): Review code for information disclosure vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Potential information disclosure vulnerability was found where '{0}' in method '{1}' may contain unintended information from '{2}' in method '{3}'. + +## [CA3005](https://docs.microsoft.com/visualstudio/code-quality/ca3005): Review code for LDAP injection vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Potential LDAP injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. + +## [CA3006](https://docs.microsoft.com/visualstudio/code-quality/ca3006): Review code for process command injection vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Potential process command injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. + +## [CA3007](https://docs.microsoft.com/visualstudio/code-quality/ca3007): Review code for open redirect vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Potential open redirect vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. + +## [CA3008](https://docs.microsoft.com/visualstudio/code-quality/ca3008): Review code for XPath injection vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Potential XPath injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. + +## [CA3009](https://docs.microsoft.com/visualstudio/code-quality/ca3009): Review code for XML injection vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Potential XML injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. + +## [CA3010](https://docs.microsoft.com/visualstudio/code-quality/ca3010): Review code for XAML injection vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Potential XAML injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. + +## [CA3011](https://docs.microsoft.com/visualstudio/code-quality/ca3011): Review code for DLL injection vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Potential DLL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. + +## [CA3012](https://docs.microsoft.com/visualstudio/code-quality/ca3012): Review code for regex injection vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Potential regex injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. + +## [CA3061](https://docs.microsoft.com/visualstudio/code-quality/ca3061): Do Not Add Schema By URL + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA3075](https://docs.microsoft.com/visualstudio/code-quality/ca3075): Insecure DTD processing in XML + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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.  + +## [CA3076](https://docs.microsoft.com/visualstudio/code-quality/ca3076): Insecure XSLT script processing. + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA3077](https://docs.microsoft.com/visualstudio/code-quality/ca3077): Insecure Processing in API Design, XmlDocument and XmlTextReader + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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.  + +## [CA3147](https://docs.microsoft.com/visualstudio/code-quality/ca3147): Mark Verb Handlers With Validate Antiforgery Token + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Missing ValidateAntiForgeryTokenAttribute on controller action {0} + +## [CA5350](https://docs.microsoft.com/visualstudio/code-quality/ca5350): Do Not Use Weak Cryptographic Algorithms + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5351](https://docs.microsoft.com/visualstudio/code-quality/ca5351): Do Not Use Broken Cryptographic Algorithms + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5358](https://docs.microsoft.com/visualstudio/code-quality/ca5358): Review cipher mode usage with cryptography experts + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +These cipher modes might be vulnerable to attacks. Consider using recommended modes (CBC, CTS). + +## [CA5359](https://docs.microsoft.com/visualstudio/code-quality/ca5359): Do Not Disable Certificate Validation + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5360](https://docs.microsoft.com/visualstudio/code-quality/ca5360): Do Not Call Dangerous Methods In Deserialization + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5361](https://docs.microsoft.com/visualstudio/code-quality/ca5361): Do Not Disable SChannel Use of Strong Crypto + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5362](https://docs.microsoft.com/visualstudio/code-quality/ca5362): Potential reference cycle in deserialized object graph + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Review code that processes untrusted deserialized data for handling of unexpected reference cycles. An unexpected reference cycle should not cause the code to enter an infinite loop. Otherwise, an unexpected reference cycle can allow an attacker to DOS or exhaust the memory of the process when deserializing untrusted data. + +## [CA5363](https://docs.microsoft.com/visualstudio/code-quality/ca5363): Do Not Disable Request Validation + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5364](https://docs.microsoft.com/visualstudio/code-quality/ca5364): Do Not Use Deprecated Security Protocols + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Using a deprecated security protocol rather than the system default is risky. + +## [CA5365](https://docs.microsoft.com/visualstudio/code-quality/ca5365): Do Not Disable HTTP Header Checking + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5366](https://docs.microsoft.com/visualstudio/code-quality/ca5366): Use XmlReader For DataSet Read Xml + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5367](https://docs.microsoft.com/visualstudio/code-quality/ca5367): Do Not Serialize Types With Pointer Fields + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5368](https://docs.microsoft.com/visualstudio/code-quality/ca5368): Set ViewStateUserKey For Classes Derived From Page + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5369](https://docs.microsoft.com/visualstudio/code-quality/ca5369): Use XmlReader For Deserialize + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5370](https://docs.microsoft.com/visualstudio/code-quality/ca5370): Use XmlReader For Validating Reader + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5371](https://docs.microsoft.com/visualstudio/code-quality/ca5371): Use XmlReader For Schema Read + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5372](https://docs.microsoft.com/visualstudio/code-quality/ca5372): Use XmlReader For XPathDocument + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5373](https://docs.microsoft.com/visualstudio/code-quality/ca5373): Do not use obsolete key derivation function + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5374](https://docs.microsoft.com/visualstudio/code-quality/ca5374): Do Not Use XslTransform + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Do not use XslTransform. It does not restrict potentially dangerous external references. + +## [CA5375](https://docs.microsoft.com/visualstudio/code-quality/ca5375): Do Not Use Account Shared Access Signature + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5376](https://docs.microsoft.com/visualstudio/code-quality/ca5376): Use SharedAccessProtocol HttpsOnly + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +HTTPS encrypts network traffic. Use HttpsOnly, rather than HttpOrHttps, to ensure network traffic is always encrypted to help prevent disclosure of sensitive data. + +## [CA5377](https://docs.microsoft.com/visualstudio/code-quality/ca5377): Use Container Level Access Policy + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +No access policy identifier is specified, making tokens non-revocable. + +## [CA5378](https://docs.microsoft.com/visualstudio/code-quality/ca5378): Do not disable ServicePointManagerSecurityProtocols + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5379](https://docs.microsoft.com/visualstudio/code-quality/ca5379): Do Not Use Weak Key Derivation Function Algorithm + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5380](https://docs.microsoft.com/visualstudio/code-quality/ca5380): Do Not Add Certificates To Root Store + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5381](https://docs.microsoft.com/visualstudio/code-quality/ca5381): Ensure Certificates Are Not Added To Root Store + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5382](https://docs.microsoft.com/visualstudio/code-quality/ca5382): Use Secure Cookies In ASP.Net Core + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Applications available over HTTPS must use secure cookies. + +## [CA5383](https://docs.microsoft.com/visualstudio/code-quality/ca5383): Ensure Use Secure Cookies In ASP.Net Core + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Applications available over HTTPS must use secure cookies. + +## [CA5384](https://docs.microsoft.com/visualstudio/code-quality/ca5384): Do Not Use Digital Signature Algorithm (DSA) + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +DSA is too weak to use. + +## [CA5385](https://docs.microsoft.com/visualstudio/code-quality/ca5385): Use Rivest–Shamir–Adleman (RSA) Algorithm With Sufficient Key Size + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Encryption algorithms are vulnerable to brute force attacks when too small a key size is used. + +## [CA5386](https://docs.microsoft.com/visualstudio/code-quality/ca5386): Avoid hardcoding SecurityProtocolType value + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Avoid hardcoding SecurityProtocolType {0}, and instead use SecurityProtocolType.SystemDefault to allow the operating system to choose the best Transport Layer Security protocol to use. + +## [CA5387](https://docs.microsoft.com/visualstudio/code-quality/ca5387): Do Not Use Weak Key Derivation Function With Insufficient Iteration Count + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). + +## [CA5388](https://docs.microsoft.com/visualstudio/code-quality/ca5388): Ensure Sufficient Iteration Count When Using Weak Key Derivation Function + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). + +## [CA5389](https://docs.microsoft.com/visualstudio/code-quality/ca5389): Do Not Add Archive Item's Path To The Target File System Path + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5390](https://docs.microsoft.com/visualstudio/code-quality/ca5390): Do not hard-code encryption key + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hard-coded value. + +## [CA5391](https://docs.microsoft.com/visualstudio/code-quality/ca5391): Use antiforgery tokens in ASP.NET Core MVC controllers + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5392](https://docs.microsoft.com/visualstudio/code-quality/ca5392): Use DefaultDllImportSearchPaths attribute for P/Invokes + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5393](https://docs.microsoft.com/visualstudio/code-quality/ca5393): Do not use unsafe DllImportSearchPath value + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5394](https://docs.microsoft.com/visualstudio/code-quality/ca5394): Do not use insecure randomness + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security-sensitive value will be generated. Use a cryptographically strong random number generator if an unpredictable value is required, or ensure that weak pseudo-random numbers aren't used in a security-sensitive manner. + +## [CA5395](https://docs.microsoft.com/visualstudio/code-quality/ca5395): Miss HttpVerb attribute for action methods + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5396](https://docs.microsoft.com/visualstudio/code-quality/ca5396): Set HttpOnly to true for HttpCookie + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5397](https://docs.microsoft.com/visualstudio/code-quality/ca5397): Do not use deprecated SslProtocols values + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5398](https://docs.microsoft.com/visualstudio/code-quality/ca5398): Avoid hardcoded SslProtocols values + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5399](https://docs.microsoft.com/visualstudio/code-quality/ca5399): HttpClients should enable certificate revocation list checks + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5400](https://docs.microsoft.com/visualstudio/code-quality/ca5400): Ensure HttpClient certificate revocation list check is not disabled + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5401](https://docs.microsoft.com/visualstudio/code-quality/ca5401): Do not use CreateEncryptor with non-default IV + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Symmetric encryption should always use a non-repeatable initialization vector to prevent dictionary attacks. + +## [CA5402](https://docs.microsoft.com/visualstudio/code-quality/ca5402): Use CreateEncryptor with the default IV + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Symmetric encryption should always use a non-repeatable initialization vector to prevent dictionary attacks. + +## [CA5403](https://docs.microsoft.com/visualstudio/code-quality/ca5403): Do not hard-code certificate + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Hard-coded certificates in source code are vulnerable to being exploited. + +## CA9999: Analyzer version mismatch + +|Item|Value| +|-|-| +|Category|Reliability| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [IL3000](https://docs.microsoft.com/visualstudio/code-quality/il3000): Avoid using accessing Assembly file path when publishing as a single-file + +|Item|Value| +|-|-| +|Category|Publish| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +'{0}' always returns an empty string for assemblies embedded in a single-file app. If the path to the app directory is needed, consider calling 'System.AppContext.BaseDirectory'. + +## [IL3001](https://docs.microsoft.com/visualstudio/code-quality/il3001): Avoid using accessing Assembly file path when publishing as a single-file + +|Item|Value| +|-|-| +|Category|Publish| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +'{0}' will throw for assemblies embedded in a single-file app -Rule ID | Title | Category | Enabled | Severity | CodeFix | Description | ---------|-------|----------|---------|----------|---------|--------------------------------------------------------------------------------------------------------------| -[CA1000](https://docs.microsoft.com/visualstudio/code-quality/ca1000) | Do not declare static members on generic types | Design | True | Warning | False | When a static member of a generic type is called, the type argument must be specified for the type. When a generic instance member that does not support inference is called, the type argument must be specified for the member. In these two cases, the syntax for specifying the type argument is different and easily confused. | -[CA1001](https://docs.microsoft.com/visualstudio/code-quality/ca1001) | Types that own disposable fields should be disposable | Design | True | Warning | True | A class declares and implements an instance field that is a System.IDisposable type, and the class does not implement IDisposable. A class that declares an IDisposable field indirectly owns an unmanaged resource and should implement the IDisposable interface. | -[CA1002](https://docs.microsoft.com/visualstudio/code-quality/ca1002) | Do not expose generic lists | Design | False | Warning | False | System.Collections.Generic.List is a generic collection that's designed for performance and not inheritance. List does not contain virtual members that make it easier to change the behavior of an inherited class. | -[CA1003](https://docs.microsoft.com/visualstudio/code-quality/ca1003) | Use generic event handler instances | Design | False | Warning | False | A type contains an event that declares an EventHandler delegate that returns void, whose signature contains two parameters (the first an object and the second a type that is assignable to EventArgs), and the containing assembly targets Microsoft .NET Framework?2.0. | -[CA1005](https://docs.microsoft.com/visualstudio/code-quality/ca1005) | Avoid excessive parameters on generic types | Design | False | Warning | False | The more type parameters a generic type contains, the more difficult it is to know and remember what each type parameter represents. | -[CA1008](https://docs.microsoft.com/visualstudio/code-quality/ca1008) | Enums should have zero value | Design | False | Warning | True | The default value of an uninitialized enumeration, just as other value types, is zero. A nonflags-attributed enumeration should define a member by using the value of zero so that the default value is a valid value of the enumeration. If an enumeration that has the FlagsAttribute attribute applied defines a zero-valued member, its name should be ""None"" to indicate that no values have been set in the enumeration. | -[CA1010](https://docs.microsoft.com/visualstudio/code-quality/ca1010) | Generic interface should also be implemented | Design | True | Warning | False | To broaden the usability of a type, implement one of the generic interfaces. This is especially true for collections as they can then be used to populate generic collection types. | -[CA1012](https://docs.microsoft.com/visualstudio/code-quality/ca1012) | Abstract types should not have public constructors | Design | False | Warning | True | Constructors on abstract types can be called only by derived types. Because public constructors create instances of a type, and you cannot create instances of an abstract type, an abstract type that has a public constructor is incorrectly designed. | -[CA1014](https://docs.microsoft.com/visualstudio/code-quality/ca1014) | Mark assemblies with CLSCompliant | Design | False | Warning | False | The Common Language Specification (CLS) defines naming restrictions, data types, and rules to which assemblies must conform if they will be used across programming languages. Good design dictates that all assemblies explicitly indicate CLS compliance by using CLSCompliantAttribute . If this attribute is not present on an assembly, the assembly is not compliant. | -[CA1016](https://docs.microsoft.com/visualstudio/code-quality/ca1016) | Mark assemblies with assembly version | Design | True | Warning | False | The .NET Framework uses the version number to uniquely identify an assembly, and to bind to types in strongly named assemblies. The version number is used together with version and publisher policy. By default, applications run only with the assembly version with which they were built. | -[CA1017](https://docs.microsoft.com/visualstudio/code-quality/ca1017) | Mark assemblies with ComVisible | Design | False | Warning | False | ComVisibleAttribute determines how COM clients access managed code. Good design dictates that assemblies explicitly indicate COM visibility. COM visibility can be set for the whole assembly and then overridden for individual types and type members. If this attribute is not present, the contents of the assembly are visible to COM clients. | -[CA1018](https://docs.microsoft.com/visualstudio/code-quality/ca1018) | Mark attributes with AttributeUsageAttribute | Design | True | Warning | False | Specify AttributeUsage on {0}. | -[CA1019](https://docs.microsoft.com/visualstudio/code-quality/ca1019) | Define accessors for attribute arguments | Design | False | Warning | True | Remove the property setter from {0} or reduce its accessibility because it corresponds to positional argument {1}. | -[CA1021](https://docs.microsoft.com/visualstudio/code-quality/ca1021) | Avoid out parameters | Design | False | Warning | False | Passing types by reference (using 'out' or 'ref') requires experience with pointers, understanding how value types and reference types differ, and handling methods with multiple return values. Also, the difference between 'out' and 'ref' parameters is not widely understood. | -[CA1024](https://docs.microsoft.com/visualstudio/code-quality/ca1024) | Use properties where appropriate | Design | False | Warning | False | A public or protected method has a name that starts with ""Get"", takes no parameters, and returns a value that is not an array. The method might be a good candidate to become a property. | -[CA1027](https://docs.microsoft.com/visualstudio/code-quality/ca1027) | Mark enums with FlagsAttribute | Design | False | Warning | True | An enumeration is a value type that defines a set of related named constants. Apply FlagsAttribute to an enumeration when its named constants can be meaningfully combined. | -[CA1028](https://docs.microsoft.com/visualstudio/code-quality/ca1028) | Enum Storage should be Int32 | Design | True | Warning | True | An enumeration is a value type that defines a set of related named constants. By default, the System.Int32 data type is used to store the constant value. Although you can change this underlying type, it is not required or recommended for most scenarios. | -[CA1030](https://docs.microsoft.com/visualstudio/code-quality/ca1030) | Use events where appropriate | Design | True | Warning | False | This rule detects methods that have names that ordinarily would be used for events. If a method is called in response to a clearly defined state change, the method should be invoked by an event handler. Objects that call the method should raise events instead of calling the method directly. | -[CA1031](https://docs.microsoft.com/visualstudio/code-quality/ca1031) | Do not catch general exception types | Design | True | Warning | False | A general exception such as System.Exception or System.SystemException or a disallowed exception type is caught in a catch statement, or a general catch clause is used. General and disallowed exceptions should not be caught. | -[CA1032](https://docs.microsoft.com/visualstudio/code-quality/ca1032) | Implement standard exception constructors | Design | True | Warning | True | Failure to provide the full set of constructors can make it difficult to correctly handle exceptions. | -[CA1033](https://docs.microsoft.com/visualstudio/code-quality/ca1033) | Interface methods should be callable by child types | Design | False | Warning | True | An unsealed externally visible type provides an explicit method implementation of a public interface and does not provide an alternative externally visible method that has the same name. | -[CA1034](https://docs.microsoft.com/visualstudio/code-quality/ca1034) | Nested types should not be visible | Design | True | Warning | False | A nested type is a type that is declared in the scope of another type. Nested types are useful to encapsulate private implementation details of the containing type. Used for this purpose, nested types should not be externally visible. | -[CA1036](https://docs.microsoft.com/visualstudio/code-quality/ca1036) | Override methods on comparable types | Design | True | Warning | True | A public or protected type implements the System.IComparable interface. It does not override Object.Equals nor does it overload the language-specific operator for equality, inequality, less than, less than or equal, greater than or greater than or equal. | -[CA1040](https://docs.microsoft.com/visualstudio/code-quality/ca1040) | Avoid empty interfaces | Design | True | Warning | False | Interfaces define members that provide a behavior or usage contract. The functionality that is described by the interface can be adopted by any type, regardless of where the type appears in the inheritance hierarchy. A type implements an interface by providing implementations for the members of the interface. An empty interface does not define any members; therefore, it does not define a contract that can be implemented. | -[CA1041](https://docs.microsoft.com/visualstudio/code-quality/ca1041) | Provide ObsoleteAttribute message | Design | True | Warning | False | A type or member is marked by using a System.ObsoleteAttribute attribute that does not have its ObsoleteAttribute.Message property specified. When a type or member that is marked by using ObsoleteAttribute is compiled, the Message property of the attribute is displayed. This gives the user information about the obsolete type or member. | -[CA1043](https://docs.microsoft.com/visualstudio/code-quality/ca1043) | Use Integral Or String Argument For Indexers | Design | True | Warning | False | Indexers, that is, indexed properties, should use integer or string types for the index. These types are typically used for indexing data structures and increase the usability of the library. Use of the Object type should be restricted to those cases where the specific integer or string type cannot be specified at design time. If the design requires other types for the index, reconsider whether the type represents a logical data store. If it does not represent a logical data store, use a method. | -[CA1044](https://docs.microsoft.com/visualstudio/code-quality/ca1044) | Properties should not be write only | Design | True | Warning | False | Although it is acceptable and often necessary to have a read-only property, the design guidelines prohibit the use of write-only properties. This is because letting a user set a value, and then preventing the user from viewing that value, does not provide any security. Also, without read access, the state of shared objects cannot be viewed, which limits their usefulness. | -[CA1045](https://docs.microsoft.com/visualstudio/code-quality/ca1045) | Do not pass types by reference | Design | False | Warning | False | Passing types by reference (using out or ref) requires experience with pointers, understanding how value types and reference types differ, and handling methods that have multiple return values. Also, the difference between out and ref parameters is not widely understood. | -[CA1046](https://docs.microsoft.com/visualstudio/code-quality/ca1046) | Do not overload equality operator on reference types | Design | False | Warning | False | For reference types, the default implementation of the equality operator is almost always correct. By default, two references are equal only if they point to the same object. If the operator is providing meaningful value equality, the type should implement the generic 'System.IEquatable' interface. | -[CA1047](https://docs.microsoft.com/visualstudio/code-quality/ca1047) | Do not declare protected member in sealed type | Design | True | Warning | False | Types declare protected members so that inheriting types can access or override the member. By definition, you cannot inherit from a sealed type, which means that protected methods on sealed types cannot be called. | -[CA1050](https://docs.microsoft.com/visualstudio/code-quality/ca1050) | Declare types in namespaces | Design | False | Warning | False | Types are declared in namespaces to prevent name collisions and as a way to organize related types in an object hierarchy. | -[CA1051](https://docs.microsoft.com/visualstudio/code-quality/ca1051) | Do not declare visible instance fields | Design | True | Warning | False | The primary use of a field should be as an implementation detail. Fields should be private or internal and should be exposed by using properties. | -[CA1052](https://docs.microsoft.com/visualstudio/code-quality/ca1052) | Static holder types should be Static or NotInheritable | Design | True | Warning | True | Type '{0}' is a static holder type but is neither static nor NotInheritable | -[CA1054](https://docs.microsoft.com/visualstudio/code-quality/ca1054) | Uri parameters should not be strings | Design | True | Warning | True | If a method takes a string representation of a URI, a corresponding overload should be provided that takes an instance of the URI class, which provides these services in a safe and secure manner. | -[CA1055](https://docs.microsoft.com/visualstudio/code-quality/ca1055) | Uri return values should not be strings | Design | True | Warning | False | This rule assumes that the method returns a URI. A string representation of a URI is prone to parsing and encoding errors, and can lead to security vulnerabilities. The System.Uri class provides these services in a safe and secure manner. | -[CA1056](https://docs.microsoft.com/visualstudio/code-quality/ca1056) | Uri properties should not be strings | Design | True | Warning | False | This rule assumes that the property represents a Uniform Resource Identifier (URI). A string representation of a URI is prone to parsing and encoding errors, and can lead to security vulnerabilities. The System.Uri class provides these services in a safe and secure manner. | -[CA1058](https://docs.microsoft.com/visualstudio/code-quality/ca1058) | Types should not extend certain base types | Design | True | Warning | False | An externally visible type extends certain base types. Use one of the alternatives. | -[CA1060](https://docs.microsoft.com/visualstudio/code-quality/ca1060) | Move pinvokes to native methods class | Design | False | Warning | False | Platform Invocation methods, such as those that are marked by using the System.Runtime.InteropServices.DllImportAttribute attribute, or methods that are defined by using the Declare keyword in Visual Basic, access unmanaged code. These methods should be of the NativeMethods, SafeNativeMethods, or UnsafeNativeMethods class. | -[CA1061](https://docs.microsoft.com/visualstudio/code-quality/ca1061) | Do not hide base class methods | Design | True | Warning | False | A method in a base type is hidden by an identically named method in a derived type when the parameter signature of the derived method differs only by types that are more weakly derived than the corresponding types in the parameter signature of the base method. | -[CA1062](https://docs.microsoft.com/visualstudio/code-quality/ca1062) | Validate arguments of public methods | Design | True | Warning | False | An externally visible method dereferences one of its reference arguments without verifying whether that argument is null (Nothing in Visual Basic). All reference arguments that are passed to externally visible methods should be checked against null. If appropriate, throw an ArgumentNullException when the argument is null or add a Code Contract precondition asserting non-null argument. If the method is designed to be called only by known assemblies, you should make the method internal. | -[CA1063](https://docs.microsoft.com/visualstudio/code-quality/ca1063) | Implement IDisposable Correctly | Design | True | Warning | False | All IDisposable types should implement the Dispose pattern correctly. | -[CA1064](https://docs.microsoft.com/visualstudio/code-quality/ca1064) | Exceptions should be public | Design | True | Warning | True | An internal exception is visible only inside its own internal scope. After the exception falls outside the internal scope, only the base exception can be used to catch the exception. If the internal exception is inherited from T:System.Exception, T:System.SystemException, or T:System.ApplicationException, the external code will not have sufficient information to know what to do with the exception. | -[CA1065](https://docs.microsoft.com/visualstudio/code-quality/ca1065) | Do not raise exceptions in unexpected locations | Design | True | Warning | False | A method that is not expected to throw exceptions throws an exception. | -[CA1066](https://docs.microsoft.com/visualstudio/code-quality/ca1066) | Implement IEquatable when overriding Object.Equals | Design | True | Warning | True | When a type T overrides Object.Equals(object), the implementation must cast the object argument to the correct type T before performing the comparison. If the type implements IEquatable, and therefore offers the method T.Equals(T), and if the argument is known at compile time to be of type T, then the compiler can call IEquatable.Equals(T) instead of Object.Equals(object), and no cast is necessary, improving performance. | -[CA1067](https://docs.microsoft.com/visualstudio/code-quality/ca1067) | Override Object.Equals(object) when implementing IEquatable | Design | True | Warning | True | When a type T implements the interface IEquatable, it suggests to a user who sees a call to the Equals method in source code that an instance of the type can be equated with an instance of any other type. The user might be confused if their attempt to equate the type with an instance of another type fails to compile. This violates the "principle of least surprise". | -[CA1068](https://docs.microsoft.com/visualstudio/code-quality/ca1068) | CancellationToken parameters must come last | Design | True | Warning | False | Method '{0}' should take CancellationToken as the last parameter | -[CA1069](https://docs.microsoft.com/visualstudio/code-quality/ca1069) | Enums values should not be duplicated | Design | True | Warning | False | The field reference '{0}' is duplicated in this bitwise initialization. | -[CA1070](https://docs.microsoft.com/visualstudio/code-quality/ca1070) | Do not declare event fields as virtual | Design | True | Warning | False | Do not declare virtual events in a base class. Overridden events in a derived class have undefined behavior. The C# compiler does not handle this correctly and it is unpredictable whether a subscriber to the derived event will actually be subscribing to the base class event. | -[CA1200](https://docs.microsoft.com/visualstudio/code-quality/ca1200) | Avoid using cref tags with a prefix | Documentation | True | Warning | False | Use of cref tags with prefixes should be avoided, since it prevents the compiler from verifying references and the IDE from updating references during refactorings. It is permissible to suppress this error at a single documentation site if the cref must use a prefix because the type being mentioned is not findable by the compiler. For example, if a cref is mentioning a special attribute in the full framework but you're in a file that compiles against the portable framework, or if you want to reference a type at higher layer of Roslyn, you should suppress the error. You should not suppress the error just because you want to take a shortcut and avoid using the full syntax. | -[CA1303](https://docs.microsoft.com/visualstudio/code-quality/ca1303) | Do not pass literals as localized parameters | Globalization | True | Warning | False | A method passes a string literal as a parameter to a constructor or method in the .NET Framework class library and that string should be localizable. To fix a violation of this rule, replace the string literal with a string retrieved through an instance of the ResourceManager class. | -[CA1304](https://docs.microsoft.com/visualstudio/code-quality/ca1304) | Specify CultureInfo | Globalization | True | Warning | False | A method or constructor calls a member that has an overload that accepts a System.Globalization.CultureInfo parameter, and the method or constructor does not call the overload that takes the CultureInfo parameter. When a CultureInfo or System.IFormatProvider object is not supplied, the default value that is supplied by the overloaded member might not have the effect that you want in all locales. If the result will be displayed to the user, specify 'CultureInfo.CurrentCulture' as the 'CultureInfo' parameter. Otherwise, if the result will be stored and accessed by software, such as when it is persisted to disk or to a database, specify 'CultureInfo.InvariantCulture'. | -[CA1305](https://docs.microsoft.com/visualstudio/code-quality/ca1305) | Specify IFormatProvider | Globalization | True | Warning | False | A method or constructor calls one or more members that have overloads that accept a System.IFormatProvider parameter, and the method or constructor does not call the overload that takes the IFormatProvider parameter. When a System.Globalization.CultureInfo or IFormatProvider object is not supplied, the default value that is supplied by the overloaded member might not have the effect that you want in all locales. If the result will be based on the input from/output displayed to the user, specify 'CultureInfo.CurrentCulture' as the 'IFormatProvider'. Otherwise, if the result will be stored and accessed by software, such as when it is loaded from disk/database and when it is persisted to disk/database, specify 'CultureInfo.InvariantCulture' | -[CA1307](https://docs.microsoft.com/visualstudio/code-quality/ca1307) | Specify StringComparison | Globalization | True | Warning | False | A string comparison operation uses a method overload that does not set a StringComparison parameter. If the result will be displayed to the user, such as when sorting a list of items for display in a list box, specify 'StringComparison.CurrentCulture' or 'StringComparison.CurrentCultureIgnoreCase' as the 'StringComparison' parameter. If comparing case-insensitive identifiers, such as file paths, environment variables, or registry keys and values, specify 'StringComparison.OrdinalIgnoreCase'. Otherwise, if comparing case-sensitive identifiers, specify 'StringComparison.Ordinal'. | -[CA1308](https://docs.microsoft.com/visualstudio/code-quality/ca1308) | Normalize strings to uppercase | Globalization | True | Warning | False | Strings should be normalized to uppercase. A small group of characters cannot make a round trip when they are converted to lowercase. To make a round trip means to convert the characters from one locale to another locale that represents character data differently, and then to accurately retrieve the original characters from the converted characters. | -[CA1309](https://docs.microsoft.com/visualstudio/code-quality/ca1309) | Use ordinal stringcomparison | Globalization | False | Warning | True | A string comparison operation that is nonlinguistic does not set the StringComparison parameter to either Ordinal or OrdinalIgnoreCase. By explicitly setting the parameter to either StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase, your code often gains speed, becomes more correct, and becomes more reliable. | -[CA1401](https://docs.microsoft.com/visualstudio/code-quality/ca1401) | P/Invokes should not be visible | Interoperability | True | Warning | False | A public or protected method in a public type has the System.Runtime.InteropServices.DllImportAttribute attribute (also implemented by the Declare keyword in Visual Basic). Such methods should not be exposed. | -[CA1501](https://docs.microsoft.com/visualstudio/code-quality/ca1501) | Avoid excessive inheritance | Maintainability | False | Warning | False | Deeply nested type hierarchies can be difficult to follow, understand, and maintain. This rule limits analysis to hierarchies in the same module. To fix a violation of this rule, derive the type from a base type that is less deep in the inheritance hierarchy or eliminate some of the intermediate base types. | -[CA1502](https://docs.microsoft.com/visualstudio/code-quality/ca1502) | Avoid excessive complexity | Maintainability | False | Warning | False | Cyclomatic complexity measures the number of linearly independent paths through the method, which is determined by the number and complexity of conditional branches. A low cyclomatic complexity generally indicates a method that is easy to understand, test, and maintain. The cyclomatic complexity is calculated from a control flow graph of the method and is given as follows: `cyclomatic complexity = the number of edges - the number of nodes + 1`, where a node represents a logic branch point and an edge represents a line between nodes. | -[CA1505](https://docs.microsoft.com/visualstudio/code-quality/ca1505) | Avoid unmaintainable code | Maintainability | False | Warning | False | The maintainability index is calculated by using the following metrics: lines of code, program volume, and cyclomatic complexity. Program volume is a measure of the difficulty of understanding of a symbol that is based on the number of operators and operands in the code. Cyclomatic complexity is a measure of the structural complexity of the type or method. A low maintainability index indicates that code is probably difficult to maintain and would be a good candidate to redesign. | -[CA1506](https://docs.microsoft.com/visualstudio/code-quality/ca1506) | Avoid excessive class coupling | Maintainability | False | Warning | False | This rule measures class coupling by counting the number of unique type references that a symbol contains. Symbols that have a high degree of class coupling can be difficult to maintain. It is a good practice to have types and methods that exhibit low coupling and high cohesion. To fix this violation, try to redesign the code to reduce the number of types to which it is coupled. | -[CA1507](https://docs.microsoft.com/visualstudio/code-quality/ca1507) | Use nameof to express symbol names | Maintainability | True | Warning | True | Using nameof helps keep your code valid when refactoring. | -[CA1508](https://docs.microsoft.com/visualstudio/code-quality/ca1508) | Avoid dead conditional code | Maintainability | False | Warning | False | '{0}' is never '{1}'. Remove or refactor the condition(s) to avoid dead code. | -[CA1509](https://docs.microsoft.com/visualstudio/code-quality/ca1509) | Invalid entry in code metrics rule specification file | Maintainability | False | Warning | False | Invalid entry in code metrics rule specification file | -[CA1700](https://docs.microsoft.com/visualstudio/code-quality/ca1700) | Do not name enum values 'Reserved' | Naming | False | Warning | False | This rule assumes that an enumeration member that has a name that contains "reserved" is not currently used but is a placeholder to be renamed or removed in a future version. Renaming or removing a member is a breaking change. | -[CA1707](https://docs.microsoft.com/visualstudio/code-quality/ca1707) | Identifiers should not contain underscores | Naming | True | Warning | False | By convention, identifier names do not contain the underscore (_) character. This rule checks namespaces, types, members, and parameters. | -[CA1708](https://docs.microsoft.com/visualstudio/code-quality/ca1708) | Identifiers should differ by more than case | Naming | False | Warning | False | Identifiers for namespaces, types, members, and parameters cannot differ only by case because languages that target the common language runtime are not required to be case-sensitive. | -[CA1710](https://docs.microsoft.com/visualstudio/code-quality/ca1710) | Identifiers should have correct suffix | Naming | True | Warning | False | By convention, the names of types that extend certain base types or that implement certain interfaces, or types that are derived from these types, have a suffix that is associated with the base type or interface. | -[CA1711](https://docs.microsoft.com/visualstudio/code-quality/ca1711) | Identifiers should not have incorrect suffix | Naming | False | Warning | False | By convention, only the names of types that extend certain base types or that implement certain interfaces, or types that are derived from these types, should end with specific reserved suffixes. Other type names should not use these reserved suffixes. | -[CA1712](https://docs.microsoft.com/visualstudio/code-quality/ca1712) | Do not prefix enum values with type name | Naming | True | Warning | False | An enumeration's values should not start with the type name of the enumeration. | -[CA1713](https://docs.microsoft.com/visualstudio/code-quality/ca1713) | Events should not have 'Before' or 'After' prefix | Naming | True | Warning | False | Event names should describe the action that raises the event. To name related events that are raised in a specific sequence, use the present or past tense to indicate the relative position in the sequence of actions. For example, when naming a pair of events that is raised when closing a resource, you might name it 'Closing' and 'Closed', instead of 'BeforeClose' and 'AfterClose'. | -[CA1714](https://docs.microsoft.com/visualstudio/code-quality/ca1714) | Flags enums should have plural names | Naming | True | Warning | False | A public enumeration has the System.FlagsAttribute attribute, and its name does not end in ""s"". Types that are marked by using FlagsAttribute have names that are plural because the attribute indicates that more than one value can be specified. | -[CA1715](https://docs.microsoft.com/visualstudio/code-quality/ca1715) | Identifiers should have correct prefix | Naming | True | Warning | False | Identifiers should have correct prefix | -[CA1716](https://docs.microsoft.com/visualstudio/code-quality/ca1716) | Identifiers should not match keywords | Naming | True | Warning | False | A namespace name or a type name matches a reserved keyword in a programming language. Identifiers for namespaces and types should not match keywords that are defined by languages that target the common language runtime. | -[CA1717](https://docs.microsoft.com/visualstudio/code-quality/ca1717) | Only FlagsAttribute enums should have plural names | Naming | True | Warning | False | Naming conventions dictate that a plural name for an enumeration indicates that more than one value of the enumeration can be specified at the same time. | -[CA1720](https://docs.microsoft.com/visualstudio/code-quality/ca1720) | Identifier contains type name | Naming | True | Warning | False | Names of parameters and members are better used to communicate their meaning than to describe their type, which is expected to be provided by development tools. For names of members, if a data type name must be used, use a language-independent name instead of a language-specific one. | -[CA1721](https://docs.microsoft.com/visualstudio/code-quality/ca1721) | Property names should not match get methods | Naming | True | Warning | False | The name of a public or protected member starts with ""Get"" and otherwise matches the name of a public or protected property. ""Get"" methods and properties should have names that clearly distinguish their function. | -[CA1724](https://docs.microsoft.com/visualstudio/code-quality/ca1724) | Type names should not match namespaces | Naming | True | Warning | False | Type names should not match the names of namespaces that are defined in the .NET Framework class library. Violating this rule can reduce the usability of the library. | -[CA1725](https://docs.microsoft.com/visualstudio/code-quality/ca1725) | Parameter names should match base declaration | Naming | False | Warning | True | Consistent naming of parameters in an override hierarchy increases the usability of the method overrides. A parameter name in a derived method that differs from the name in the base declaration can cause confusion about whether the method is an override of the base method or a new overload of the method. | -[CA1801](https://docs.microsoft.com/visualstudio/code-quality/ca1801) | Review unused parameters | Usage | True | Warning | True | Avoid unused paramereters in your code. If the parameter cannot be removed, then change its name so it starts with an underscore and is optionally followed by an integer, such as '_', '_1', '_2', etc. These are treated as special discard symbol names. | -[CA1802](https://docs.microsoft.com/visualstudio/code-quality/ca1802) | Use literals where appropriate | Performance | True | Warning | True | A field is declared static and read-only (Shared and ReadOnly in Visual Basic), and is initialized by using a value that is computable at compile time. Because the value that is assigned to the targeted field is computable at compile time, change the declaration to a const (Const in Visual Basic) field so that the value is computed at compile time instead of at run?time. | -[CA1805](https://docs.microsoft.com/visualstudio/code-quality/ca1805) | Do not initialize unnecessarily | Performance | True | Warning | True | The .NET runtime initializes all fields of reference types to their default values before running the constructor. In most cases, explicitly initializing a field to its default value in a constructor is redundant, adding maintenance costs and potentially degrading performance (such as with increased assembly size), and the explicit initialization can be removed. In some cases, such as with static readonly fields that permanently retain their default value, consider instead changing them to be constants or properties. | -[CA1806](https://docs.microsoft.com/visualstudio/code-quality/ca1806) | Do not ignore method results | Performance | True | Warning | False | A new object is created but never used; or a method that creates and returns a new string is called and the new string is never used; or a COM or P/Invoke method returns an HRESULT or error code that is never used. | -[CA1810](https://docs.microsoft.com/visualstudio/code-quality/ca1810) | Initialize reference type static fields inline | Performance | True | Warning | False | A reference 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. | -[CA1812](https://docs.microsoft.com/visualstudio/code-quality/ca1812) | Avoid uninstantiated internal classes | Performance | True | Warning | False | An instance of an assembly-level type is not created by code in the assembly. | -[CA1813](https://docs.microsoft.com/visualstudio/code-quality/ca1813) | Avoid unsealed attributes | Performance | False | Warning | True | The .NET Framework class library provides methods for retrieving custom attributes. By default, these methods search the attribute inheritance hierarchy. Sealing the attribute eliminates the search through the inheritance hierarchy and can improve performance. | -[CA1814](https://docs.microsoft.com/visualstudio/code-quality/ca1814) | Prefer jagged arrays over multidimensional | Performance | True | Warning | False | A jagged array is an array whose elements are arrays. The arrays that make up the elements can be of different sizes, leading to less wasted space for some sets of data. | -[CA1815](https://docs.microsoft.com/visualstudio/code-quality/ca1815) | Override equals and operator equals on value types | Performance | True | Warning | True | For value types, the inherited implementation of Equals uses the Reflection library and compares the contents of all fields. Reflection is computationally expensive, and comparing every field for equality might be unnecessary. If you expect users to compare or sort instances, or to use instances as hash table keys, your value type should implement Equals. | -[CA1816](https://docs.microsoft.com/visualstudio/code-quality/ca1816) | Dispose methods should call SuppressFinalize | Usage | True | Warning | False | A method that is an implementation of Dispose does not call GC.SuppressFinalize; or a method that is not an implementation of Dispose calls GC.SuppressFinalize; or a method calls GC.SuppressFinalize and passes something other than this (Me in Visual?Basic). | -[CA1819](https://docs.microsoft.com/visualstudio/code-quality/ca1819) | Properties should not return arrays | Performance | True | Warning | False | Arrays that are returned by properties are not write-protected, even when the property is read-only. To keep the array tamper-proof, the property must return a copy of the array. Typically, users will not understand the adverse performance implications of calling such a property. | -[CA1820](https://docs.microsoft.com/visualstudio/code-quality/ca1820) | Test for empty strings using string length | Performance | True | Warning | True | Comparing strings by using the String.Length property or the String.IsNullOrEmpty method is significantly faster than using Equals. | -[CA1821](https://docs.microsoft.com/visualstudio/code-quality/ca1821) | Remove empty Finalizers | Performance | True | Warning | True | Finalizers should be avoided where possible, to avoid the additional performance overhead involved in tracking object lifetime. | -[CA1822](https://docs.microsoft.com/visualstudio/code-quality/ca1822) | Mark members as static | Performance | True | Warning | True | Members that do not access instance data or call instance methods can be marked as static. After you mark the methods as static, the compiler will emit nonvirtual call sites to these members. This can give you a measurable performance gain for performance-sensitive code. | -[CA1823](https://docs.microsoft.com/visualstudio/code-quality/ca1823) | Avoid unused private fields | Performance | True | Warning | True | Private fields were detected that do not appear to be accessed in the assembly. | -[CA1824](https://docs.microsoft.com/visualstudio/code-quality/ca1824) | Mark assemblies with NeutralResourcesLanguageAttribute | Performance | True | Warning | False | The NeutralResourcesLanguage attribute informs the ResourceManager of the language that was used to display the resources of a neutral culture for an assembly. This improves lookup performance for the first resource that you load and can reduce your working set. | -[CA1825](https://docs.microsoft.com/visualstudio/code-quality/ca1825) | Avoid zero-length array allocations. | Performance | True | Warning | True | Avoid unnecessary zero-length array allocations. Use {0} instead. | -[CA1826](https://docs.microsoft.com/visualstudio/code-quality/ca1826) | Do not use Enumerable methods on indexable collections. Instead use the collection directly | Performance | True | Warning | True | This collection is directly indexable. Going through LINQ here causes unnecessary allocations and CPU work. | -[CA1827](https://docs.microsoft.com/visualstudio/code-quality/ca1827) | Do not use Count() or LongCount() when Any() can be used | Performance | True | Warning | 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. | -[CA1828](https://docs.microsoft.com/visualstudio/code-quality/ca1828) | Do not use CountAsync() or LongCountAsync() when AnyAsync() can be used | Performance | True | Warning | 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. | -[CA1829](https://docs.microsoft.com/visualstudio/code-quality/ca1829) | Use Length/Count property instead of Count() when available | Performance | True | Warning | True | Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. | -[CA1830](https://docs.microsoft.com/visualstudio/code-quality/ca1830) | Prefer strongly-typed Append and Insert method overloads on StringBuilder. | Performance | True | Warning | True | StringBuilder.Append and StringBuilder.Insert provide overloads for multiple types beyond System.String. When possible, prefer the strongly-typed overloads over using ToString() and the string-based overload. | -[CA1831](https://docs.microsoft.com/visualstudio/code-quality/ca1831) | Use AsSpan or AsMemory instead of Range-based indexers when appropriate | Performance | True | Warning | True | The Range-based indexer on string values produces a copy of requested portion of the string. This copy is usually unnecessary when it is implicitly used as a ReadOnlySpan or ReadOnlyMemory value. Use the AsSpan method to avoid the unnecessary copy. | -[CA1832](https://docs.microsoft.com/visualstudio/code-quality/ca1832) | Use AsSpan or AsMemory instead of Range-based indexers when appropriate | Performance | True | Warning | True | The Range-based indexer on array values produces a copy of requested portion of the array. This copy is usually unnecessary when it is implicitly used as a ReadOnlySpan or ReadOnlyMemory value. Use the AsSpan method to avoid the unnecessary copy. | -[CA1833](https://docs.microsoft.com/visualstudio/code-quality/ca1833) | Use AsSpan or AsMemory instead of Range-based indexers when appropriate | Performance | True | Warning | True | The Range-based indexer on array values produces a copy of requested portion of the array. This copy is often unwanted when it is implicitly used as a Span or Memory value. Use the AsSpan method to avoid the copy. | -[CA1834](https://docs.microsoft.com/visualstudio/code-quality/ca1834) | Consider using 'StringBuilder.Append(char)' when applicable. | Performance | True | Warning | True | 'StringBuilder.Append(char)' is more efficient than 'StringBuilder.Append(string)' when the string is a single character. When calling 'Append' with a constant, prefer using a constant char rather than a constant string containing one character. | -[CA1835](https://docs.microsoft.com/visualstudio/code-quality/ca1835) | Prefer the 'Memory'-based overloads for 'ReadAsync' and 'WriteAsync' | Performance | True | Warning | True | 'Stream' has a 'ReadAsync' overload that takes a 'Memory' as the first argument, and a 'WriteAsync' overload that takes a 'ReadOnlyMemory' as the first argument. Prefer calling the memory based overloads, which are more efficient. | -[CA1836](https://docs.microsoft.com/visualstudio/code-quality/ca1836) | Prefer IsEmpty over Count | Performance | True | Warning | True | For determining whether the object contains or not any items, prefer using 'IsEmpty' property rather than retrieving the number of items from the 'Count' property and comparing it to 0 or 1. | -[CA2000](https://docs.microsoft.com/visualstudio/code-quality/ca2000) | Dispose objects before losing scope | Reliability | True | Warning | 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. | -[CA2002](https://docs.microsoft.com/visualstudio/code-quality/ca2002) | Do not lock on objects with weak identity | Reliability | True | Warning | 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. | -[CA2007](https://docs.microsoft.com/visualstudio/code-quality/ca2007) | Consider calling ConfigureAwait on the awaited task | Reliability | True | Warning | 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. | -[CA2008](https://docs.microsoft.com/visualstudio/code-quality/ca2008) | Do not create tasks without passing a TaskScheduler | Reliability | True | Warning | 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. | -[CA2009](https://docs.microsoft.com/visualstudio/code-quality/ca2009) | Do not call ToImmutableCollection on an ImmutableCollection value | Reliability | True | Warning | True | Do not call {0} on an {1} value | -[CA2011](https://docs.microsoft.com/visualstudio/code-quality/ca2011) | Avoid infinite recursion | Reliability | True | Warning | False | Do not assign the property within its setter. This call might result in an infinite recursion. | -[CA2012](https://docs.microsoft.com/visualstudio/code-quality/ca2012) | Use ValueTasks correctly | Reliability | True | Warning | False | ValueTasks returned from member invocations are intended to be directly awaited. Attempts to consume a ValueTask multiple times or to directly access one's result before it's known to be completed may result in an exception or corruption. Ignoring such a ValueTask is likely an indication of a functional bug and may degrade performance. | -[CA2013](https://docs.microsoft.com/visualstudio/code-quality/ca2013) | Do not use ReferenceEquals with value types | Reliability | True | Warning | False | Value type typed arguments are uniquely boxed for each call to this method, therefore the result is always false. | -[CA2014](https://docs.microsoft.com/visualstudio/code-quality/ca2014) | Do not use stackalloc in loops. | Reliability | True | Warning | False | Stack space allocated by a stackalloc is only released at the end of the current method's invocation. Using it in a loop can result in unbounded stack growth and eventual stack overflow conditions. | -[CA2015](https://docs.microsoft.com/visualstudio/code-quality/ca2015) | Do not define finalizers for types derived from MemoryManager | Reliability | True | Warning | False | Adding a finalizer to a type derived from MemoryManager may permit memory to be freed while it is still in use by a Span. | -[CA2016](https://docs.microsoft.com/visualstudio/code-quality/ca2016) | Forward the 'CancellationToken' parameter to methods that take one | Reliability | True | Warning | True | Forward the 'CancellationToken' parameter to methods that take one to ensure the operation cancellation notifications gets properly propagated, or pass in 'CancellationToken.None' explicitly to indicate intentionally not propagating the token. | -[CA2100](https://docs.microsoft.com/visualstudio/code-quality/ca2100) | Review SQL queries for security vulnerabilities | Security | True | Warning | 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. | -[CA2101](https://docs.microsoft.com/visualstudio/code-quality/ca2101) | Specify marshaling for P/Invoke string arguments | Globalization | True | Warning | 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. | -[CA2109](https://docs.microsoft.com/visualstudio/code-quality/ca2109) | Review visible event handlers | Security | True | Warning | False | A public or protected event-handling method was detected. Event-handling methods should not be exposed unless absolutely necessary. | -[CA2119](https://docs.microsoft.com/visualstudio/code-quality/ca2119) | Seal methods that satisfy private interfaces | Security | True | Warning | 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. | -[CA2153](https://docs.microsoft.com/visualstudio/code-quality/ca2153) | Do Not Catch Corrupted State Exceptions | Security | True | Warning | 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 | -[CA2200](https://docs.microsoft.com/visualstudio/code-quality/ca2200) | Rethrow to preserve stack details. | Usage | True | Warning | True | Re-throwing caught exception changes stack information. | -[CA2201](https://docs.microsoft.com/visualstudio/code-quality/ca2201) | Do not raise reserved exception types | Usage | False | Warning | 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. | -[CA2207](https://docs.microsoft.com/visualstudio/code-quality/ca2207) | Initialize value type static fields inline | Usage | True | Warning | 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. | -[CA2208](https://docs.microsoft.com/visualstudio/code-quality/ca2208) | Instantiate argument exceptions correctly | Usage | True | Warning | True | A call is made to the default (parameterless) constructor of an exception type that is or derives from ArgumentException, or an incorrect string argument is passed to a parameterized constructor of an exception type that is or derives from ArgumentException. | -[CA2211](https://docs.microsoft.com/visualstudio/code-quality/ca2211) | Non-constant fields should not be visible | Usage | True | Warning | 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. | -[CA2213](https://docs.microsoft.com/visualstudio/code-quality/ca2213) | Disposable fields should be disposed | Usage | True | Warning | 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. | -[CA2214](https://docs.microsoft.com/visualstudio/code-quality/ca2214) | Do not call overridable methods in constructors | Usage | True | Warning | 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). | -[CA2215](https://docs.microsoft.com/visualstudio/code-quality/ca2215) | Dispose methods should call base class dispose | Usage | True | Warning | True | A type that implements System.IDisposable inherits from a type that also implements IDisposable. The Dispose method of the inheriting type does not call the Dispose method of the parent type. To fix a violation of this rule, call base.Dispose in your Dispose method. | -[CA2216](https://docs.microsoft.com/visualstudio/code-quality/ca2216) | Disposable types should declare finalizer | Usage | True | Warning | 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. | -[CA2217](https://docs.microsoft.com/visualstudio/code-quality/ca2217) | Do not mark enums with FlagsAttribute | Usage | False | Warning | 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. | -[CA2218](https://docs.microsoft.com/visualstudio/code-quality/ca2218) | Override GetHashCode on overriding Equals | Usage | True | Warning | 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. | -[CA2219](https://docs.microsoft.com/visualstudio/code-quality/ca2219) | Do not raise exceptions in finally clauses | Usage | True | Warning | 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. | -[CA2224](https://docs.microsoft.com/visualstudio/code-quality/ca2224) | Override Equals on overloading operator equals | Usage | True | Warning | True | A public type implements the equality operator but does not override Object.Equals. | -[CA2225](https://docs.microsoft.com/visualstudio/code-quality/ca2225) | Operator overloads have named alternates | Usage | True | Warning | 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. | -[CA2226](https://docs.microsoft.com/visualstudio/code-quality/ca2226) | Operators should have symmetrical overloads | Usage | True | Warning | True | A type implements the equality or inequality operator and does not implement the opposite operator. | -[CA2227](https://docs.microsoft.com/visualstudio/code-quality/ca2227) | Collection properties should be read only | Usage | True | Warning | 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. | -[CA2229](https://docs.microsoft.com/visualstudio/code-quality/ca2229) | Implement serialization constructors | Usage | True | Warning | True | To fix a violation of this rule, implement the serialization constructor. For a sealed class, make the constructor private; otherwise, make it protected. | -[CA2231](https://docs.microsoft.com/visualstudio/code-quality/ca2231) | Overload operator equals on overriding value type Equals | Usage | True | Warning | 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 | -[CA2234](https://docs.microsoft.com/visualstudio/code-quality/ca2234) | Pass system uri objects instead of strings | Usage | True | Warning | 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. | -[CA2235](https://docs.microsoft.com/visualstudio/code-quality/ca2235) | Mark all non-serializable fields | Usage | True | Warning | True | An instance field of a type that is not serializable is declared in a type that is serializable. | -[CA2237](https://docs.microsoft.com/visualstudio/code-quality/ca2237) | Mark ISerializable types with serializable | Usage | True | Warning | 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. | -[CA2241](https://docs.microsoft.com/visualstudio/code-quality/ca2241) | Provide correct arguments to formatting methods | Usage | True | Warning | 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. | -[CA2242](https://docs.microsoft.com/visualstudio/code-quality/ca2242) | Test for NaN correctly | Usage | True | Warning | True | This expression tests a value against Single.Nan or Double.Nan. Use Single.IsNan(Single) or Double.IsNan(Double) to test the value. | -[CA2243](https://docs.microsoft.com/visualstudio/code-quality/ca2243) | Attribute string literals should parse correctly | Usage | True | Warning | False | The string literal parameter of an attribute does not parse correctly for a URL, a GUID, or a version. | -[CA2244](https://docs.microsoft.com/visualstudio/code-quality/ca2244) | Do not duplicate indexed element initializations | Usage | True | Warning | True | Indexed elements in objects initializers must initialize unique elements. A duplicate index might overwrite a previous element initialization. | -[CA2245](https://docs.microsoft.com/visualstudio/code-quality/ca2245) | Do not assign a property to itself. | Usage | True | Warning | False | The property {0} should not be assigned to itself. | -[CA2246](https://docs.microsoft.com/visualstudio/code-quality/ca2246) | Assigning symbol and its member in the same statement. | Usage | True | Warning | 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. | -[CA2247](https://docs.microsoft.com/visualstudio/code-quality/ca2247) | Argument passed to TaskCompletionSource constructor should be TaskCreationOptions enum instead of TaskContinuationOptions enum. | Usage | True | Warning | True | TaskCompletionSource has constructors that take TaskCreationOptions that control the underlying Task, and constructors that take object state that's stored in the task. Accidentally passing a TaskContinuationOptions instead of a TaskCreationOptions will result in the call treating the options as state. | -[CA2248](https://docs.microsoft.com/visualstudio/code-quality/ca2248) | Provide correct 'enum' argument to 'Enum.HasFlag' | Usage | True | Warning | False | 'Enum.HasFlag' method expects the 'enum' argument to be of the same 'enum' type as the instance on which the method is invoked and that this 'enum' is marked with 'System.FlagsAttribute'. If these are different 'enum' types, an unhandled exception will be thrown at runtime. If the 'enum' type is not marked with 'System.FlagsAttribute' the call will always return 'false' at runtime. | -[CA2249](https://docs.microsoft.com/visualstudio/code-quality/ca2249) | Consider using 'string.Contains' instead of 'string.IndexOf' | Usage | True | Warning | True | Calls to 'string.IndexOf' where the result is used to check for the presence/absence of a substring can be replaced by 'string.Contains' | -[CA2300](https://docs.microsoft.com/visualstudio/code-quality/ca2300) | Do not use insecure deserializer BinaryFormatter | Security | False | Warning | 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. | -[CA2301](https://docs.microsoft.com/visualstudio/code-quality/ca2301) | Do not call BinaryFormatter.Deserialize without first setting BinaryFormatter.Binder | Security | False | Warning | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | -[CA2302](https://docs.microsoft.com/visualstudio/code-quality/ca2302) | Ensure BinaryFormatter.Binder is set before calling BinaryFormatter.Deserialize | Security | False | Warning | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | -[CA2305](https://docs.microsoft.com/visualstudio/code-quality/ca2305) | Do not use insecure deserializer LosFormatter | Security | False | Warning | False | The method '{0}' is insecure when deserializing untrusted data. | -[CA2310](https://docs.microsoft.com/visualstudio/code-quality/ca2310) | Do not use insecure deserializer NetDataContractSerializer | Security | False | Warning | 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. | -[CA2311](https://docs.microsoft.com/visualstudio/code-quality/ca2311) | Do not deserialize without first setting NetDataContractSerializer.Binder | Security | False | Warning | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | -[CA2312](https://docs.microsoft.com/visualstudio/code-quality/ca2312) | Ensure NetDataContractSerializer.Binder is set before deserializing | Security | False | Warning | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | -[CA2315](https://docs.microsoft.com/visualstudio/code-quality/ca2315) | Do not use insecure deserializer ObjectStateFormatter | Security | False | Warning | False | The method '{0}' is insecure when deserializing untrusted data. | -[CA2321](https://docs.microsoft.com/visualstudio/code-quality/ca2321) | Do not deserialize with JavaScriptSerializer using a SimpleTypeResolver | Security | False | Warning | 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. | -[CA2322](https://docs.microsoft.com/visualstudio/code-quality/ca2322) | Ensure JavaScriptSerializer is not initialized with SimpleTypeResolver before deserializing | Security | False | Warning | 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. | -[CA2326](https://docs.microsoft.com/visualstudio/code-quality/ca2326) | Do not use TypeNameHandling values other than None | Security | False | Warning | 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. | -[CA2327](https://docs.microsoft.com/visualstudio/code-quality/ca2327) | Do not use insecure JsonSerializerSettings | Security | False | Warning | 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. | -[CA2328](https://docs.microsoft.com/visualstudio/code-quality/ca2328) | Ensure that JsonSerializerSettings are secure | Security | False | Warning | 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. | -[CA2329](https://docs.microsoft.com/visualstudio/code-quality/ca2329) | Do not deserialize with JsonSerializer using an insecure configuration | Security | False | Warning | 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. | -[CA2330](https://docs.microsoft.com/visualstudio/code-quality/ca2330) | Ensure that JsonSerializer has a secure configuration when deserializing | Security | False | Warning | 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. | -[CA2350](https://docs.microsoft.com/visualstudio/code-quality/ca2350) | Do not use insecure deserialization with DataTable.ReadXml() | Security | False | Warning | False | The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. | -[CA2351](https://docs.microsoft.com/visualstudio/code-quality/ca2351) | Do not use insecure deserialization with DataSet.ReadXml() | Security | False | Warning | False | The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. | -[CA2352](https://docs.microsoft.com/visualstudio/code-quality/ca2352) | Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks | Security | False | Warning | False | When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. | -[CA2353](https://docs.microsoft.com/visualstudio/code-quality/ca2353) | Unsafe DataSet or DataTable in serializable type | Security | False | Warning | False | When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. | -[CA2354](https://docs.microsoft.com/visualstudio/code-quality/ca2354) | Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks | Security | False | Warning | False | When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. | -[CA2355](https://docs.microsoft.com/visualstudio/code-quality/ca2355) | Unsafe DataSet or DataTable type found in deserializable object graph | Security | False | Warning | False | When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. | -[CA2356](https://docs.microsoft.com/visualstudio/code-quality/ca2356) | Unsafe DataSet or DataTable type in web deserializable object graph | Security | False | Warning | False | When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. | -[CA3001](https://docs.microsoft.com/visualstudio/code-quality/ca3001) | Review code for SQL injection vulnerabilities | Security | False | Warning | False | Potential SQL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -[CA3002](https://docs.microsoft.com/visualstudio/code-quality/ca3002) | Review code for XSS vulnerabilities | Security | False | Warning | 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}'. | -[CA3003](https://docs.microsoft.com/visualstudio/code-quality/ca3003) | Review code for file path injection vulnerabilities | Security | False | Warning | 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}'. | -[CA3004](https://docs.microsoft.com/visualstudio/code-quality/ca3004) | Review code for information disclosure vulnerabilities | Security | False | Warning | False | Potential information disclosure vulnerability was found where '{0}' in method '{1}' may contain unintended information from '{2}' in method '{3}'. | -[CA3005](https://docs.microsoft.com/visualstudio/code-quality/ca3005) | Review code for LDAP injection vulnerabilities | Security | False | Warning | False | Potential LDAP injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -[CA3006](https://docs.microsoft.com/visualstudio/code-quality/ca3006) | Review code for process command injection vulnerabilities | Security | False | Warning | 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}'. | -[CA3007](https://docs.microsoft.com/visualstudio/code-quality/ca3007) | Review code for open redirect vulnerabilities | Security | False | Warning | False | Potential open redirect vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -[CA3008](https://docs.microsoft.com/visualstudio/code-quality/ca3008) | Review code for XPath injection vulnerabilities | Security | False | Warning | False | Potential XPath injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -[CA3009](https://docs.microsoft.com/visualstudio/code-quality/ca3009) | Review code for XML injection vulnerabilities | Security | False | Warning | False | Potential XML injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -[CA3010](https://docs.microsoft.com/visualstudio/code-quality/ca3010) | Review code for XAML injection vulnerabilities | Security | False | Warning | False | Potential XAML injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -[CA3011](https://docs.microsoft.com/visualstudio/code-quality/ca3011) | Review code for DLL injection vulnerabilities | Security | False | Warning | False | Potential DLL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -[CA3012](https://docs.microsoft.com/visualstudio/code-quality/ca3012) | Review code for regex injection vulnerabilities | Security | False | Warning | False | Potential regex injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -[CA3061](https://docs.microsoft.com/visualstudio/code-quality/ca3061) | Do Not Add Schema By URL | Security | True | Warning | 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. | -[CA3075](https://docs.microsoft.com/visualstudio/code-quality/ca3075) | Insecure DTD processing in XML | Security | True | Warning | 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.  | -[CA3076](https://docs.microsoft.com/visualstudio/code-quality/ca3076) | Insecure XSLT script processing. | Security | True | Warning | 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. | -[CA3077](https://docs.microsoft.com/visualstudio/code-quality/ca3077) | Insecure Processing in API Design, XmlDocument and XmlTextReader | Security | True | Warning | 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.  | -[CA3147](https://docs.microsoft.com/visualstudio/code-quality/ca3147) | Mark Verb Handlers With Validate Antiforgery Token | Security | True | Warning | False | Missing ValidateAntiForgeryTokenAttribute on controller action {0}. | -[CA5350](https://docs.microsoft.com/visualstudio/code-quality/ca5350) | Do Not Use Weak Cryptographic Algorithms | Security | True | Warning | 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. | -[CA5351](https://docs.microsoft.com/visualstudio/code-quality/ca5351) | Do Not Use Broken Cryptographic Algorithms | Security | True | Warning | 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. | -[CA5358](https://docs.microsoft.com/visualstudio/code-quality/ca5358) | Review cipher mode usage with cryptography experts | Security | False | Warning | False | These cipher modes might be vulnerable to attacks. Consider using recommended modes (CBC, CTS). | -[CA5359](https://docs.microsoft.com/visualstudio/code-quality/ca5359) | Do Not Disable Certificate Validation | Security | True | Warning | 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. | -[CA5360](https://docs.microsoft.com/visualstudio/code-quality/ca5360) | Do Not Call Dangerous Methods In Deserialization | Security | True | Warning | 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. | -[CA5361](https://docs.microsoft.com/visualstudio/code-quality/ca5361) | Do Not Disable SChannel Use of Strong Crypto | Security | False | Warning | 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. | -[CA5362](https://docs.microsoft.com/visualstudio/code-quality/ca5362) | Potential reference cycle in deserialized object graph | Security | False | Warning | False | Review code that processes untrusted deserialized data for handling of unexpected reference cycles. An unexpected reference cycle should not cause the code to enter an infinite loop. Otherwise, an unexpected reference cycle can allow an attacker to DOS or exhaust the memory of the process when deserializing untrusted data. | -[CA5363](https://docs.microsoft.com/visualstudio/code-quality/ca5363) | Do Not Disable Request Validation | Security | True | Warning | 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. | -[CA5364](https://docs.microsoft.com/visualstudio/code-quality/ca5364) | Do Not Use Deprecated Security Protocols | Security | True | Warning | False | Using a deprecated security protocol rather than the system default is risky. | -[CA5365](https://docs.microsoft.com/visualstudio/code-quality/ca5365) | Do Not Disable HTTP Header Checking | Security | True | Warning | 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. | -[CA5366](https://docs.microsoft.com/visualstudio/code-quality/ca5366) | Use XmlReader For DataSet Read Xml | Security | True | Warning | 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. | -[CA5367](https://docs.microsoft.com/visualstudio/code-quality/ca5367) | Do Not Serialize Types With Pointer Fields | Security | False | Warning | 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. | -[CA5368](https://docs.microsoft.com/visualstudio/code-quality/ca5368) | Set ViewStateUserKey For Classes Derived From Page | Security | True | Warning | 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. | -[CA5369](https://docs.microsoft.com/visualstudio/code-quality/ca5369) | Use XmlReader For Deserialize | Security | True | Warning | 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. | -[CA5370](https://docs.microsoft.com/visualstudio/code-quality/ca5370) | Use XmlReader For Validating Reader | Security | True | Warning | 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. | -[CA5371](https://docs.microsoft.com/visualstudio/code-quality/ca5371) | Use XmlReader For Schema Read | Security | True | Warning | 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. | -[CA5372](https://docs.microsoft.com/visualstudio/code-quality/ca5372) | Use XmlReader For XPathDocument | Security | True | Warning | 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. | -[CA5373](https://docs.microsoft.com/visualstudio/code-quality/ca5373) | Do not use obsolete key derivation function | Security | True | Warning | 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. | -[CA5374](https://docs.microsoft.com/visualstudio/code-quality/ca5374) | Do Not Use XslTransform | Security | True | Warning | False | Do not use XslTransform. It does not restrict potentially dangerous external references. | -[CA5375](https://docs.microsoft.com/visualstudio/code-quality/ca5375) | Do Not Use Account Shared Access Signature | Security | False | Warning | 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. | -[CA5376](https://docs.microsoft.com/visualstudio/code-quality/ca5376) | Use SharedAccessProtocol HttpsOnly | Security | False | Warning | False | HTTPS encrypts network traffic. Use HttpsOnly, rather than HttpOrHttps, to ensure network traffic is always encrypted to help prevent disclosure of sensitive data. | -[CA5377](https://docs.microsoft.com/visualstudio/code-quality/ca5377) | Use Container Level Access Policy | Security | False | Warning | False | No access policy identifier is specified, making tokens non-revocable. | -[CA5378](https://docs.microsoft.com/visualstudio/code-quality/ca5378) | Do not disable ServicePointManagerSecurityProtocols | Security | False | Warning | 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. | -[CA5379](https://docs.microsoft.com/visualstudio/code-quality/ca5379) | Do Not Use Weak Key Derivation Function Algorithm | Security | True | Warning | 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. | -[CA5380](https://docs.microsoft.com/visualstudio/code-quality/ca5380) | Do Not Add Certificates To Root Store | Security | False | Warning | 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. | -[CA5381](https://docs.microsoft.com/visualstudio/code-quality/ca5381) | Ensure Certificates Are Not Added To Root Store | Security | False | Warning | 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. | -[CA5382](https://docs.microsoft.com/visualstudio/code-quality/ca5382) | Use Secure Cookies In ASP.Net Core | Security | False | Warning | False | Applications available over HTTPS must use secure cookies. | -[CA5383](https://docs.microsoft.com/visualstudio/code-quality/ca5383) | Ensure Use Secure Cookies In ASP.Net Core | Security | False | Warning | False | Applications available over HTTPS must use secure cookies. | -[CA5384](https://docs.microsoft.com/visualstudio/code-quality/ca5384) | Do Not Use Digital Signature Algorithm (DSA) | Security | True | Warning | False | DSA is too weak to use. | -[CA5385](https://docs.microsoft.com/visualstudio/code-quality/ca5385) | Use Rivest–Shamir–Adleman (RSA) Algorithm With Sufficient Key Size | Security | True | Warning | False | Encryption algorithms are vulnerable to brute force attacks when too small a key size is used. | -[CA5386](https://docs.microsoft.com/visualstudio/code-quality/ca5386) | Avoid hardcoding SecurityProtocolType value | Security | False | Warning | 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. | -[CA5387](https://docs.microsoft.com/visualstudio/code-quality/ca5387) | Do Not Use Weak Key Derivation Function With Insufficient Iteration Count | Security | False | Warning | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | -[CA5388](https://docs.microsoft.com/visualstudio/code-quality/ca5388) | Ensure Sufficient Iteration Count When Using Weak Key Derivation Function | Security | False | Warning | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | -[CA5389](https://docs.microsoft.com/visualstudio/code-quality/ca5389) | Do Not Add Archive Item's Path To The Target File System Path | Security | False | Warning | 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. | -[CA5390](https://docs.microsoft.com/visualstudio/code-quality/ca5390) | Do not hard-code encryption key | Security | False | Warning | False | SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hard-coded value. | -[CA5391](https://docs.microsoft.com/visualstudio/code-quality/ca5391) | Use antiforgery tokens in ASP.NET Core MVC controllers | Security | False | Warning | 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. | -[CA5392](https://docs.microsoft.com/visualstudio/code-quality/ca5392) | Use DefaultDllImportSearchPaths attribute for P/Invokes | Security | False | Warning | 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. | -[CA5393](https://docs.microsoft.com/visualstudio/code-quality/ca5393) | Do not use unsafe DllImportSearchPath value | Security | False | Warning | 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. | -[CA5394](https://docs.microsoft.com/visualstudio/code-quality/ca5394) | Do not use insecure randomness | Security | False | Warning | False | Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security-sensitive value will be generated. Use a cryptographically strong random number generator if an unpredictable value is required, or ensure that weak pseudo-random numbers aren't used in a security-sensitive manner. | -[CA5395](https://docs.microsoft.com/visualstudio/code-quality/ca5395) | Miss HttpVerb attribute for action methods | Security | False | Warning | 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. | -[CA5396](https://docs.microsoft.com/visualstudio/code-quality/ca5396) | Set HttpOnly to true for HttpCookie | Security | False | Warning | 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. | -[CA5397](https://docs.microsoft.com/visualstudio/code-quality/ca5397) | Do not use deprecated SslProtocols values | Security | True | Warning | 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. | -[CA5398](https://docs.microsoft.com/visualstudio/code-quality/ca5398) | Avoid hardcoded SslProtocols values | Security | False | Warning | 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. | -[CA5399](https://docs.microsoft.com/visualstudio/code-quality/ca5399) | HttpClients should enable certificate revocation list checks | Security | False | Warning | 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. | -[CA5400](https://docs.microsoft.com/visualstudio/code-quality/ca5400) | Ensure HttpClient certificate revocation list check is not disabled | Security | False | Warning | 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. | -[CA5401](https://docs.microsoft.com/visualstudio/code-quality/ca5401) | Do not use CreateEncryptor with non-default IV | Security | False | Warning | False | Symmetric encryption should always use a non-repeatable initialization vector to prevent dictionary attacks. | -[CA5402](https://docs.microsoft.com/visualstudio/code-quality/ca5402) | Use CreateEncryptor with the default IV | Security | False | Warning | False | Symmetric encryption should always use a non-repeatable initialization vector to prevent dictionary attacks. | -[CA5403](https://docs.microsoft.com/visualstudio/code-quality/ca5403) | Do not hard-code certificate | Security | False | Warning | False | Hard-coded certificates in source code are vulnerable to being exploited. | -CA9999 | Analyzer version mismatch | Reliability | True | Warning | 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 f16ab10d5b..3f4740e1c2 100644 --- a/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.sarif +++ b/src/Microsoft.CodeAnalysis.FxCopAnalyzers/Microsoft.CodeAnalysis.FxCopAnalyzers.sarif @@ -237,7 +237,7 @@ "CA1018": { "id": "CA1018", "shortDescription": "Mark attributes with AttributeUsageAttribute", - "fullDescription": "Specify AttributeUsage on {0}.", + "fullDescription": "Specify AttributeUsage on {0}", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1018", "properties": { @@ -635,8 +635,8 @@ }, "CA1054": { "id": "CA1054", - "shortDescription": "Uri parameters should not be strings", - "fullDescription": "If a method takes a string representation of a URI, a corresponding overload should be provided that takes an instance of the URI class, which provides these services in a safe and secure manner.", + "shortDescription": "URI-like parameters should not be strings", + "fullDescription": "This rule assumes that the parameter represents a Uniform Resource Identifier (URI). A string representation or a URI is prone to parsing and encoding errors, and can lead to security vulnerabilities. 'System.Uri' class provides these services in a safe and secure manner.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1054", "properties": { @@ -655,7 +655,7 @@ }, "CA1055": { "id": "CA1055", - "shortDescription": "Uri return values should not be strings", + "shortDescription": "URI-like return values should not be strings", "fullDescription": "This rule assumes that the method returns a URI. A string representation of a URI is prone to parsing and encoding errors, and can lead to security vulnerabilities. The System.Uri class provides these services in a safe and secure manner.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1055", @@ -675,7 +675,7 @@ }, "CA1056": { "id": "CA1056", - "shortDescription": "Uri properties should not be strings", + "shortDescription": "URI-like properties should not be strings", "fullDescription": "This rule assumes that the property represents a Uniform Resource Identifier (URI). A string representation of a URI is prone to parsing and encoding errors, and can lead to security vulnerabilities. The System.Uri class provides these services in a safe and secure manner.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1056", @@ -854,7 +854,7 @@ "CA1069": { "id": "CA1069", "shortDescription": "Enums values should not be duplicated", - "fullDescription": "The field reference '{0}' is duplicated in this bitwise initialization.", + "fullDescription": "The field reference '{0}' is duplicated in this bitwise initialization", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1069", "properties": { @@ -991,7 +991,7 @@ "CA1509": { "id": "CA1509", "shortDescription": "Invalid entry in code metrics rule specification file", - "fullDescription": "Invalid entry in code metrics rule specification file", + "fullDescription": "Invalid entry in code metrics rule specification file.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1509", "properties": { @@ -1170,7 +1170,7 @@ "CA1715": { "id": "CA1715", "shortDescription": "Identifiers should have correct prefix", - "fullDescription": "Identifiers should have correct prefix", + "fullDescription": "The name of an externally visible interface does not start with an uppercase \"\"I\"\". The name of a generic type parameter on an externally visible type or method does not start with an uppercase \"\"T\"\".", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1715", "properties": { @@ -1387,26 +1387,6 @@ ] } }, - "CA1812": { - "id": "CA1812", - "shortDescription": "Avoid uninstantiated internal classes", - "fullDescription": "An instance of an assembly-level type is not created by code in the assembly.", - "defaultLevel": "warning", - "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1812", - "properties": { - "category": "Performance", - "isEnabledByDefault": true, - "typeName": "AvoidUninstantiatedInternalClassesAnalyzer", - "languages": [ - "C#", - "Visual Basic" - ], - "tags": [ - "PortedFromFxCop", - "Telemetry" - ] - } - }, "CA1814": { "id": "CA1814", "shortDescription": "Prefer jagged arrays over multidimensional", @@ -1573,7 +1553,7 @@ "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2109", "properties": { "category": "Security", - "isEnabledByDefault": true, + "isEnabledByDefault": false, "typeName": "ReviewVisibleEventHandlersAnalyzer", "languages": [ "C#", @@ -1748,7 +1728,7 @@ "CA2231": { "id": "CA2231", "shortDescription": "Overload operator equals on overriding value type Equals", - "fullDescription": "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", + "fullDescription": "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.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2231", "properties": { @@ -1785,8 +1765,8 @@ }, "CA2245": { "id": "CA2245", - "shortDescription": "Do not assign a property to itself.", - "fullDescription": "The property {0} should not be assigned to itself.", + "shortDescription": "Do not assign a property to itself", + "fullDescription": "The property {0} should not be assigned to itself", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2245", "properties": { @@ -1804,7 +1784,7 @@ }, "CA2246": { "id": "CA2246", - "shortDescription": "Assigning symbol and its member in the same statement.", + "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", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2246", @@ -1851,7 +1831,7 @@ "CA1019": { "id": "CA1019", "shortDescription": "Define accessors for attribute arguments", - "fullDescription": "Remove the property setter from {0} or reduce its accessibility because it corresponds to positional argument {1}.", + "fullDescription": "Remove the property setter from {0} or reduce its accessibility because it corresponds to positional argument {1}", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1019", "properties": { @@ -1941,10 +1921,29 @@ ] } }, + "CA1812": { + "id": "CA1812", + "shortDescription": "Avoid uninstantiated internal classes", + "fullDescription": "An instance of an assembly-level type is not created by code in the assembly.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1812", + "properties": { + "category": "Performance", + "isEnabledByDefault": true, + "typeName": "CSharpAvoidUninstantiatedInternalClasses", + "languages": [ + "C#" + ], + "tags": [ + "PortedFromFxCop", + "Telemetry" + ] + } + }, "CA2200": { "id": "CA2200", - "shortDescription": "Rethrow to preserve stack details.", - "fullDescription": "Re-throwing caught exception changes stack information.", + "shortDescription": "Rethrow to preserve stack details", + "fullDescription": "Re-throwing caught exception changes stack information", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2200", "properties": { @@ -2010,7 +2009,7 @@ "CA1019": { "id": "CA1019", "shortDescription": "Define accessors for attribute arguments", - "fullDescription": "Remove the property setter from {0} or reduce its accessibility because it corresponds to positional argument {1}.", + "fullDescription": "Remove the property setter from {0} or reduce its accessibility because it corresponds to positional argument {1}", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1019", "properties": { @@ -2100,10 +2099,29 @@ ] } }, + "CA1812": { + "id": "CA1812", + "shortDescription": "Avoid uninstantiated internal classes", + "fullDescription": "An instance of an assembly-level type is not created by code in the assembly.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1812", + "properties": { + "category": "Performance", + "isEnabledByDefault": true, + "typeName": "BasicAvoidUninstantiatedInternalClasses", + "languages": [ + "Visual Basic" + ], + "tags": [ + "PortedFromFxCop", + "Telemetry" + ] + } + }, "CA2200": { "id": "CA2200", - "shortDescription": "Rethrow to preserve stack details.", - "fullDescription": "Re-throwing caught exception changes stack information.", + "shortDescription": "Rethrow to preserve stack details", + "fullDescription": "Re-throwing caught exception changes stack information", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2200", "properties": { @@ -2229,7 +2247,7 @@ "CA1305": { "id": "CA1305", "shortDescription": "Specify IFormatProvider", - "fullDescription": "A method or constructor calls one or more members that have overloads that accept a System.IFormatProvider parameter, and the method or constructor does not call the overload that takes the IFormatProvider parameter. When a System.Globalization.CultureInfo or IFormatProvider object is not supplied, the default value that is supplied by the overloaded member might not have the effect that you want in all locales. If the result will be based on the input from/output displayed to the user, specify 'CultureInfo.CurrentCulture' as the 'IFormatProvider'. Otherwise, if the result will be stored and accessed by software, such as when it is loaded from disk/database and when it is persisted to disk/database, specify 'CultureInfo.InvariantCulture'", + "fullDescription": "A method or constructor calls one or more members that have overloads that accept a System.IFormatProvider parameter, and the method or constructor does not call the overload that takes the IFormatProvider parameter. When a System.Globalization.CultureInfo or IFormatProvider object is not supplied, the default value that is supplied by the overloaded member might not have the effect that you want in all locales. If the result will be based on the input from/output displayed to the user, specify 'CultureInfo.CurrentCulture' as the 'IFormatProvider'. Otherwise, if the result will be stored and accessed by software, such as when it is loaded from disk/database and when it is persisted to disk/database, specify 'CultureInfo.InvariantCulture'.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1305", "properties": { @@ -2306,6 +2324,25 @@ ] } }, + "CA1417": { + "id": "CA1417", + "shortDescription": "Do not use 'OutAttribute' on string parameters for P/Invokes", + "fullDescription": "String parameters passed by value with the 'OutAttribute' can destabilize the runtime if the string is an interned string.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1417", + "properties": { + "category": "Interoperability", + "isEnabledByDefault": true, + "typeName": "DoNotUseOutAttributeStringPInvokeParametersAnalyzer", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, "CA1810": { "id": "CA1810", "shortDescription": "Initialize reference type static fields inline", @@ -2387,7 +2424,7 @@ }, "CA1826": { "id": "CA1826", - "shortDescription": "Do not use Enumerable methods on indexable collections. Instead use the collection directly", + "shortDescription": "Do not use Enumerable methods on indexable collections", "fullDescription": "This collection is directly indexable. Going through LINQ here causes unnecessary allocations and CPU work.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1826", @@ -2463,7 +2500,7 @@ }, "CA1830": { "id": "CA1830", - "shortDescription": "Prefer strongly-typed Append and Insert method overloads on StringBuilder.", + "shortDescription": "Prefer strongly-typed Append and Insert method overloads on StringBuilder", "fullDescription": "StringBuilder.Append and StringBuilder.Insert provide overloads for multiple types beyond System.String. When possible, prefer the strongly-typed overloads over using ToString() and the string-based overload.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1830", @@ -2539,7 +2576,7 @@ }, "CA1834": { "id": "CA1834", - "shortDescription": "Consider using 'StringBuilder.Append(char)' when applicable.", + "shortDescription": "Consider using 'StringBuilder.Append(char)' when applicable", "fullDescription": "'StringBuilder.Append(char)' is more efficient than 'StringBuilder.Append(string)' when the string is a single character. When calling 'Append' with a constant, prefer using a constant char rather than a constant string containing one character.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1834", @@ -2594,6 +2631,44 @@ ] } }, + "CA1837": { + "id": "CA1837", + "shortDescription": "Use 'Environment.ProcessId'", + "fullDescription": "'Environment.ProcessId' is simpler and faster than 'Process.GetCurrentProcess().Id'.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1837", + "properties": { + "category": "Performance", + "isEnabledByDefault": true, + "typeName": "UseEnvironmentProcessId", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, + "CA1838": { + "id": "CA1838", + "shortDescription": "Avoid 'StringBuilder' parameters for P/Invokes", + "fullDescription": "Marshalling of 'StringBuilder' always creates a native buffer copy, resulting in multiple allocations for one marshalling operation.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1838", + "properties": { + "category": "Performance", + "isEnabledByDefault": false, + "typeName": "AvoidStringBuilderPInvokeParametersAnalyzer", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, "CA2000": { "id": "CA2000", "shortDescription": "Dispose objects before losing scope", @@ -2713,7 +2788,7 @@ }, "CA2014": { "id": "CA2014", - "shortDescription": "Do not use stackalloc in loops.", + "shortDescription": "Do not use stackalloc in loops", "fullDescription": "Stack space allocated by a stackalloc is only released at the end of the current method's invocation. Using it in a loop can result in unbounded stack growth and eventual stack overflow conditions.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2014", @@ -3032,7 +3107,7 @@ }, "CA2247": { "id": "CA2247", - "shortDescription": "Argument passed to TaskCompletionSource constructor should be TaskCreationOptions enum instead of TaskContinuationOptions enum.", + "shortDescription": "Argument passed to TaskCompletionSource constructor should be TaskCreationOptions enum instead of TaskContinuationOptions enum", "fullDescription": "TaskCompletionSource has constructors that take TaskCreationOptions that control the underlying Task, and constructors that take object state that's stored in the task. Accidentally passing a TaskContinuationOptions instead of a TaskCreationOptions will result in the call treating the options as state.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2247", @@ -3071,7 +3146,7 @@ "CA2249": { "id": "CA2249", "shortDescription": "Consider using 'string.Contains' instead of 'string.IndexOf'", - "fullDescription": "Calls to 'string.IndexOf' where the result is used to check for the presence/absence of a substring can be replaced by 'string.Contains'", + "fullDescription": "Calls to 'string.IndexOf' where the result is used to check for the presence/absence of a substring can be replaced by 'string.Contains'.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2249", "properties": { @@ -3384,8 +3459,8 @@ }, "CA2350": { "id": "CA2350", - "shortDescription": "Do not use insecure deserialization with DataTable.ReadXml()", - "fullDescription": "The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD.", + "shortDescription": "Do not use DataTable.ReadXml() with untrusted data", + "fullDescription": "The method '{0}' is insecure when deserializing untrusted data", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2350", "properties": { @@ -3403,8 +3478,8 @@ }, "CA2351": { "id": "CA2351", - "shortDescription": "Do not use insecure deserialization with DataSet.ReadXml()", - "fullDescription": "The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD.", + "shortDescription": "Do not use DataSet.ReadXml() with untrusted data", + "fullDescription": "The method '{0}' is insecure when deserializing untrusted data", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2351", "properties": { @@ -3442,7 +3517,7 @@ "CA2353": { "id": "CA2353", "shortDescription": "Unsafe DataSet or DataTable in serializable type", - "fullDescription": "When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}.", + "fullDescription": "When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2353", "properties": { @@ -3461,7 +3536,7 @@ "CA2354": { "id": "CA2354", "shortDescription": "Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks", - "fullDescription": "When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}.", + "fullDescription": "When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2354", "properties": { @@ -3480,7 +3555,7 @@ "CA2355": { "id": "CA2355", "shortDescription": "Unsafe DataSet or DataTable type found in deserializable object graph", - "fullDescription": "When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}.", + "fullDescription": "When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2355", "properties": { @@ -3499,7 +3574,7 @@ "CA2356": { "id": "CA2356", "shortDescription": "Unsafe DataSet or DataTable type in web deserializable object graph", - "fullDescription": "When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}.", + "fullDescription": "When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2356", "properties": { @@ -3515,6 +3590,44 @@ ] } }, + "CA2361": { + "id": "CA2361", + "shortDescription": "Ensure autogenerated class containing DataSet.ReadXml() is not used with untrusted data", + "fullDescription": "The method '{0}' is insecure when deserializing untrusted data. Make sure that autogenerated class containing the '{0}' call is not deserialized with untrusted data.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2361", + "properties": { + "category": "Security", + "isEnabledByDefault": false, + "typeName": "DoNotUseDataSetReadXml", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, + "CA2362": { + "id": "CA2362", + "shortDescription": "Unsafe DataSet or DataTable in autogenerated serializable type can be vulnerable to remote code execution attacks", + "fullDescription": "When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. Ensure that the autogenerated type is never deserialized with untrusted data.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2362", + "properties": { + "category": "Security", + "isEnabledByDefault": false, + "typeName": "DataSetDataTableInSerializableTypeAnalyzer", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, "CA3001": { "id": "CA3001", "shortDescription": "Review code for SQL injection vulnerabilities", @@ -4703,6 +4816,44 @@ "Telemetry" ] } + }, + "IL3000": { + "id": "IL3000", + "shortDescription": "Avoid using accessing Assembly file path when publishing as a single-file", + "fullDescription": "'{0}' always returns an empty string for assemblies embedded in a single-file app. If the path to the app directory is needed, consider calling 'System.AppContext.BaseDirectory'.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/il3000", + "properties": { + "category": "Publish", + "isEnabledByDefault": true, + "typeName": "AvoidAssemblyLocationInSingleFile", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, + "IL3001": { + "id": "IL3001", + "shortDescription": "Avoid using accessing Assembly file path when publishing as a single-file", + "fullDescription": "'{0}' will throw for assemblies embedded in a single-file app", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/il3001", + "properties": { + "category": "Publish", + "isEnabledByDefault": true, + "typeName": "AvoidAssemblyLocationInSingleFile", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } } } }, @@ -4753,7 +4904,7 @@ }, "CA1825": { "id": "CA1825", - "shortDescription": "Avoid zero-length array allocations.", + "shortDescription": "Avoid zero-length array allocations", "fullDescription": "Avoid unnecessary zero-length array allocations. Use {0} instead.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1825", @@ -4836,7 +4987,7 @@ }, "CA1825": { "id": "CA1825", - "shortDescription": "Avoid zero-length array allocations.", + "shortDescription": "Avoid zero-length array allocations", "fullDescription": "Avoid unnecessary zero-length array allocations. Use {0} instead.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1825", @@ -4902,7 +5053,7 @@ "CA2153": { "id": "CA2153", "shortDescription": "Do Not Catch Corrupted State Exceptions", - "fullDescription": "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", + "fullDescription": "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.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2153", "properties": { @@ -4940,7 +5091,7 @@ "CA3147": { "id": "CA3147", "shortDescription": "Mark Verb Handlers With Validate Antiforgery Token", - "fullDescription": "Missing ValidateAntiForgeryTokenAttribute on controller action {0}.", + "fullDescription": "Missing ValidateAntiForgeryTokenAttribute on controller action {0}", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca3147", "properties": { diff --git a/src/Microsoft.CodeAnalysis.VersionCheckAnalyzer/Microsoft.CodeAnalysis.VersionCheckAnalyzer.md b/src/Microsoft.CodeAnalysis.VersionCheckAnalyzer/Microsoft.CodeAnalysis.VersionCheckAnalyzer.md index 765b458dcc..8b99036ea9 100644 --- a/src/Microsoft.CodeAnalysis.VersionCheckAnalyzer/Microsoft.CodeAnalysis.VersionCheckAnalyzer.md +++ b/src/Microsoft.CodeAnalysis.VersionCheckAnalyzer/Microsoft.CodeAnalysis.VersionCheckAnalyzer.md @@ -1,4 +1,15 @@ +# Microsoft.CodeAnalysis.VersionCheckAnalyzer + +## CA9999: Analyzer version mismatch + +|Item|Value| +|-|-| +|Category|Reliability| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. -Rule ID | Title | Category | Enabled | Severity | CodeFix | Description | ---------|-------|----------|---------|----------|---------|--------------------------------------------------------------------------------------------------------------| -CA9999 | Analyzer version mismatch | Reliability | True | Warning | 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.CodeQuality.Analyzers/Microsoft.CodeQuality.Analyzers.md b/src/Microsoft.CodeQuality.Analyzers/Microsoft.CodeQuality.Analyzers.md index 56ec528269..e214247c54 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Microsoft.CodeQuality.Analyzers.md +++ b/src/Microsoft.CodeQuality.Analyzers/Microsoft.CodeQuality.Analyzers.md @@ -1,103 +1,1302 @@ +# Microsoft.CodeQuality.Analyzers + +## [CA1000](https://docs.microsoft.com/visualstudio/code-quality/ca1000): Do not declare static members on generic types + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +When a static member of a generic type is called, the type argument must be specified for the type. When a generic instance member that does not support inference is called, the type argument must be specified for the member. In these two cases, the syntax for specifying the type argument is different and easily confused. + +## [CA1001](https://docs.microsoft.com/visualstudio/code-quality/ca1001): Types that own disposable fields should be disposable + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +A class declares and implements an instance field that is a System.IDisposable type, and the class does not implement IDisposable. A class that declares an IDisposable field indirectly owns an unmanaged resource and should implement the IDisposable interface. + +## [CA1002](https://docs.microsoft.com/visualstudio/code-quality/ca1002): Do not expose generic lists + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +System.Collections.Generic.List is a generic collection that's designed for performance and not inheritance. List does not contain virtual members that make it easier to change the behavior of an inherited class. + +## [CA1003](https://docs.microsoft.com/visualstudio/code-quality/ca1003): Use generic event handler instances + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A type contains an event that declares an EventHandler delegate that returns void, whose signature contains two parameters (the first an object and the second a type that is assignable to EventArgs), and the containing assembly targets Microsoft .NET Framework?2.0. + +## [CA1005](https://docs.microsoft.com/visualstudio/code-quality/ca1005): Avoid excessive parameters on generic types + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The more type parameters a generic type contains, the more difficult it is to know and remember what each type parameter represents. + +## [CA1008](https://docs.microsoft.com/visualstudio/code-quality/ca1008): Enums should have zero value + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +The default value of an uninitialized enumeration, just as other value types, is zero. A nonflags-attributed enumeration should define a member by using the value of zero so that the default value is a valid value of the enumeration. If an enumeration that has the FlagsAttribute attribute applied defines a zero-valued member, its name should be ""None"" to indicate that no values have been set in the enumeration. + +## [CA1010](https://docs.microsoft.com/visualstudio/code-quality/ca1010): Generic interface should also be implemented + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +To broaden the usability of a type, implement one of the generic interfaces. This is especially true for collections as they can then be used to populate generic collection types. + +## [CA1012](https://docs.microsoft.com/visualstudio/code-quality/ca1012): Abstract types should not have public constructors + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Constructors on abstract types can be called only by derived types. Because public constructors create instances of a type, and you cannot create instances of an abstract type, an abstract type that has a public constructor is incorrectly designed. + +## [CA1014](https://docs.microsoft.com/visualstudio/code-quality/ca1014): Mark assemblies with CLSCompliant + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The Common Language Specification (CLS) defines naming restrictions, data types, and rules to which assemblies must conform if they will be used across programming languages. Good design dictates that all assemblies explicitly indicate CLS compliance by using CLSCompliantAttribute . If this attribute is not present on an assembly, the assembly is not compliant. + +## [CA1016](https://docs.microsoft.com/visualstudio/code-quality/ca1016): Mark assemblies with assembly version + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The .NET Framework uses the version number to uniquely identify an assembly, and to bind to types in strongly named assemblies. The version number is used together with version and publisher policy. By default, applications run only with the assembly version with which they were built. + +## [CA1017](https://docs.microsoft.com/visualstudio/code-quality/ca1017): Mark assemblies with ComVisible + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +ComVisibleAttribute determines how COM clients access managed code. Good design dictates that assemblies explicitly indicate COM visibility. COM visibility can be set for the whole assembly and then overridden for individual types and type members. If this attribute is not present, the contents of the assembly are visible to COM clients. + +## [CA1018](https://docs.microsoft.com/visualstudio/code-quality/ca1018): Mark attributes with AttributeUsageAttribute + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Specify AttributeUsage on {0} + +## [CA1019](https://docs.microsoft.com/visualstudio/code-quality/ca1019): Define accessors for attribute arguments + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Remove the property setter from {0} or reduce its accessibility because it corresponds to positional argument {1} + +## [CA1021](https://docs.microsoft.com/visualstudio/code-quality/ca1021): Avoid out parameters + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Passing types by reference (using 'out' or 'ref') requires experience with pointers, understanding how value types and reference types differ, and handling methods with multiple return values. Also, the difference between 'out' and 'ref' parameters is not widely understood. + +## [CA1024](https://docs.microsoft.com/visualstudio/code-quality/ca1024): Use properties where appropriate + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A public or protected method has a name that starts with ""Get"", takes no parameters, and returns a value that is not an array. The method might be a good candidate to become a property. + +## [CA1027](https://docs.microsoft.com/visualstudio/code-quality/ca1027): Mark enums with FlagsAttribute + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +An enumeration is a value type that defines a set of related named constants. Apply FlagsAttribute to an enumeration when its named constants can be meaningfully combined. + +## [CA1028](https://docs.microsoft.com/visualstudio/code-quality/ca1028): Enum Storage should be Int32 + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +An enumeration is a value type that defines a set of related named constants. By default, the System.Int32 data type is used to store the constant value. Although you can change this underlying type, it is not required or recommended for most scenarios. + +## [CA1030](https://docs.microsoft.com/visualstudio/code-quality/ca1030): Use events where appropriate + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +This rule detects methods that have names that ordinarily would be used for events. If a method is called in response to a clearly defined state change, the method should be invoked by an event handler. Objects that call the method should raise events instead of calling the method directly. + +## [CA1031](https://docs.microsoft.com/visualstudio/code-quality/ca1031): Do not catch general exception types + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A general exception such as System.Exception or System.SystemException or a disallowed exception type is caught in a catch statement, or a general catch clause is used. General and disallowed exceptions should not be caught. + +## [CA1032](https://docs.microsoft.com/visualstudio/code-quality/ca1032): Implement standard exception constructors + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Failure to provide the full set of constructors can make it difficult to correctly handle exceptions. + +## [CA1033](https://docs.microsoft.com/visualstudio/code-quality/ca1033): Interface methods should be callable by child types + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +An unsealed externally visible type provides an explicit method implementation of a public interface and does not provide an alternative externally visible method that has the same name. + +## [CA1034](https://docs.microsoft.com/visualstudio/code-quality/ca1034): Nested types should not be visible + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A nested type is a type that is declared in the scope of another type. Nested types are useful to encapsulate private implementation details of the containing type. Used for this purpose, nested types should not be externally visible. + +## [CA1036](https://docs.microsoft.com/visualstudio/code-quality/ca1036): Override methods on comparable types + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +A public or protected type implements the System.IComparable interface. It does not override Object.Equals nor does it overload the language-specific operator for equality, inequality, less than, less than or equal, greater than or greater than or equal. + +## [CA1040](https://docs.microsoft.com/visualstudio/code-quality/ca1040): Avoid empty interfaces + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Interfaces define members that provide a behavior or usage contract. The functionality that is described by the interface can be adopted by any type, regardless of where the type appears in the inheritance hierarchy. A type implements an interface by providing implementations for the members of the interface. An empty interface does not define any members; therefore, it does not define a contract that can be implemented. + +## [CA1041](https://docs.microsoft.com/visualstudio/code-quality/ca1041): Provide ObsoleteAttribute message + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A type or member is marked by using a System.ObsoleteAttribute attribute that does not have its ObsoleteAttribute.Message property specified. When a type or member that is marked by using ObsoleteAttribute is compiled, the Message property of the attribute is displayed. This gives the user information about the obsolete type or member. + +## [CA1043](https://docs.microsoft.com/visualstudio/code-quality/ca1043): Use Integral Or String Argument For Indexers + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Indexers, that is, indexed properties, should use integer or string types for the index. These types are typically used for indexing data structures and increase the usability of the library. Use of the Object type should be restricted to those cases where the specific integer or string type cannot be specified at design time. If the design requires other types for the index, reconsider whether the type represents a logical data store. If it does not represent a logical data store, use a method. + +## [CA1044](https://docs.microsoft.com/visualstudio/code-quality/ca1044): Properties should not be write only + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Although it is acceptable and often necessary to have a read-only property, the design guidelines prohibit the use of write-only properties. This is because letting a user set a value, and then preventing the user from viewing that value, does not provide any security. Also, without read access, the state of shared objects cannot be viewed, which limits their usefulness. + +## [CA1045](https://docs.microsoft.com/visualstudio/code-quality/ca1045): Do not pass types by reference + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Passing types by reference (using out or ref) requires experience with pointers, understanding how value types and reference types differ, and handling methods that have multiple return values. Also, the difference between out and ref parameters is not widely understood. + +## [CA1046](https://docs.microsoft.com/visualstudio/code-quality/ca1046): Do not overload equality operator on reference types + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +For reference types, the default implementation of the equality operator is almost always correct. By default, two references are equal only if they point to the same object. If the operator is providing meaningful value equality, the type should implement the generic 'System.IEquatable' interface. + +## [CA1047](https://docs.microsoft.com/visualstudio/code-quality/ca1047): Do not declare protected member in sealed type + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Types declare protected members so that inheriting types can access or override the member. By definition, you cannot inherit from a sealed type, which means that protected methods on sealed types cannot be called. + +## [CA1050](https://docs.microsoft.com/visualstudio/code-quality/ca1050): Declare types in namespaces + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Types are declared in namespaces to prevent name collisions and as a way to organize related types in an object hierarchy. + +## [CA1051](https://docs.microsoft.com/visualstudio/code-quality/ca1051): Do not declare visible instance fields + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The primary use of a field should be as an implementation detail. Fields should be private or internal and should be exposed by using properties. + +## [CA1052](https://docs.microsoft.com/visualstudio/code-quality/ca1052): Static holder types should be Static or NotInheritable + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Type '{0}' is a static holder type but is neither static nor NotInheritable + +## [CA1054](https://docs.microsoft.com/visualstudio/code-quality/ca1054): URI-like parameters should not be strings + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +This rule assumes that the parameter represents a Uniform Resource Identifier (URI). A string representation or a URI is prone to parsing and encoding errors, and can lead to security vulnerabilities. 'System.Uri' class provides these services in a safe and secure manner. + +## [CA1055](https://docs.microsoft.com/visualstudio/code-quality/ca1055): URI-like return values should not be strings + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +This rule assumes that the method returns a URI. A string representation of a URI is prone to parsing and encoding errors, and can lead to security vulnerabilities. The System.Uri class provides these services in a safe and secure manner. + +## [CA1056](https://docs.microsoft.com/visualstudio/code-quality/ca1056): URI-like properties should not be strings + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +This rule assumes that the property represents a Uniform Resource Identifier (URI). A string representation of a URI is prone to parsing and encoding errors, and can lead to security vulnerabilities. The System.Uri class provides these services in a safe and secure manner. + +## [CA1060](https://docs.microsoft.com/visualstudio/code-quality/ca1060): Move pinvokes to native methods class + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Platform Invocation methods, such as those that are marked by using the System.Runtime.InteropServices.DllImportAttribute attribute, or methods that are defined by using the Declare keyword in Visual Basic, access unmanaged code. These methods should be of the NativeMethods, SafeNativeMethods, or UnsafeNativeMethods class. + +## [CA1061](https://docs.microsoft.com/visualstudio/code-quality/ca1061): Do not hide base class methods + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A method in a base type is hidden by an identically named method in a derived type when the parameter signature of the derived method differs only by types that are more weakly derived than the corresponding types in the parameter signature of the base method. + +## [CA1062](https://docs.microsoft.com/visualstudio/code-quality/ca1062): Validate arguments of public methods + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +An externally visible method dereferences one of its reference arguments without verifying whether that argument is null (Nothing in Visual Basic). All reference arguments that are passed to externally visible methods should be checked against null. If appropriate, throw an ArgumentNullException when the argument is null or add a Code Contract precondition asserting non-null argument. If the method is designed to be called only by known assemblies, you should make the method internal. + +## [CA1063](https://docs.microsoft.com/visualstudio/code-quality/ca1063): Implement IDisposable Correctly + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +All IDisposable types should implement the Dispose pattern correctly. + +## [CA1064](https://docs.microsoft.com/visualstudio/code-quality/ca1064): Exceptions should be public + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +An internal exception is visible only inside its own internal scope. After the exception falls outside the internal scope, only the base exception can be used to catch the exception. If the internal exception is inherited from T:System.Exception, T:System.SystemException, or T:System.ApplicationException, the external code will not have sufficient information to know what to do with the exception. + +## [CA1065](https://docs.microsoft.com/visualstudio/code-quality/ca1065): Do not raise exceptions in unexpected locations + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A method that is not expected to throw exceptions throws an exception. + +## [CA1066](https://docs.microsoft.com/visualstudio/code-quality/ca1066): Implement IEquatable when overriding Object.Equals + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +When a type T overrides Object.Equals(object), the implementation must cast the object argument to the correct type T before performing the comparison. If the type implements IEquatable, and therefore offers the method T.Equals(T), and if the argument is known at compile time to be of type T, then the compiler can call IEquatable.Equals(T) instead of Object.Equals(object), and no cast is necessary, improving performance. + +## [CA1067](https://docs.microsoft.com/visualstudio/code-quality/ca1067): Override Object.Equals(object) when implementing IEquatable + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +When a type T implements the interface IEquatable, it suggests to a user who sees a call to the Equals method in source code that an instance of the type can be equated with an instance of any other type. The user might be confused if their attempt to equate the type with an instance of another type fails to compile. This violates the "principle of least surprise". + +## [CA1068](https://docs.microsoft.com/visualstudio/code-quality/ca1068): CancellationToken parameters must come last + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Method '{0}' should take CancellationToken as the last parameter + +## [CA1069](https://docs.microsoft.com/visualstudio/code-quality/ca1069): Enums values should not be duplicated + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The field reference '{0}' is duplicated in this bitwise initialization + +## [CA1070](https://docs.microsoft.com/visualstudio/code-quality/ca1070): Do not declare event fields as virtual + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Do not declare virtual events in a base class. Overridden events in a derived class have undefined behavior. The C# compiler does not handle this correctly and it is unpredictable whether a subscriber to the derived event will actually be subscribing to the base class event. + +## [CA1200](https://docs.microsoft.com/visualstudio/code-quality/ca1200): Avoid using cref tags with a prefix + +|Item|Value| +|-|-| +|Category|Documentation| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Use of cref tags with prefixes should be avoided, since it prevents the compiler from verifying references and the IDE from updating references during refactorings. It is permissible to suppress this error at a single documentation site if the cref must use a prefix because the type being mentioned is not findable by the compiler. For example, if a cref is mentioning a special attribute in the full framework but you're in a file that compiles against the portable framework, or if you want to reference a type at higher layer of Roslyn, you should suppress the error. You should not suppress the error just because you want to take a shortcut and avoid using the full syntax. + +## [CA1501](https://docs.microsoft.com/visualstudio/code-quality/ca1501): Avoid excessive inheritance + +|Item|Value| +|-|-| +|Category|Maintainability| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Deeply nested type hierarchies can be difficult to follow, understand, and maintain. This rule limits analysis to hierarchies in the same module. To fix a violation of this rule, derive the type from a base type that is less deep in the inheritance hierarchy or eliminate some of the intermediate base types. + +## [CA1502](https://docs.microsoft.com/visualstudio/code-quality/ca1502): Avoid excessive complexity + +|Item|Value| +|-|-| +|Category|Maintainability| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Cyclomatic complexity measures the number of linearly independent paths through the method, which is determined by the number and complexity of conditional branches. A low cyclomatic complexity generally indicates a method that is easy to understand, test, and maintain. The cyclomatic complexity is calculated from a control flow graph of the method and is given as follows: `cyclomatic complexity = the number of edges - the number of nodes + 1`, where a node represents a logic branch point and an edge represents a line between nodes. + +## [CA1505](https://docs.microsoft.com/visualstudio/code-quality/ca1505): Avoid unmaintainable code + +|Item|Value| +|-|-| +|Category|Maintainability| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The maintainability index is calculated by using the following metrics: lines of code, program volume, and cyclomatic complexity. Program volume is a measure of the difficulty of understanding of a symbol that is based on the number of operators and operands in the code. Cyclomatic complexity is a measure of the structural complexity of the type or method. A low maintainability index indicates that code is probably difficult to maintain and would be a good candidate to redesign. + +## [CA1506](https://docs.microsoft.com/visualstudio/code-quality/ca1506): Avoid excessive class coupling + +|Item|Value| +|-|-| +|Category|Maintainability| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +This rule measures class coupling by counting the number of unique type references that a symbol contains. Symbols that have a high degree of class coupling can be difficult to maintain. It is a good practice to have types and methods that exhibit low coupling and high cohesion. To fix this violation, try to redesign the code to reduce the number of types to which it is coupled. + +## [CA1507](https://docs.microsoft.com/visualstudio/code-quality/ca1507): Use nameof to express symbol names + +|Item|Value| +|-|-| +|Category|Maintainability| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Using nameof helps keep your code valid when refactoring. + +## [CA1508](https://docs.microsoft.com/visualstudio/code-quality/ca1508): Avoid dead conditional code + +|Item|Value| +|-|-| +|Category|Maintainability| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +'{0}' is never '{1}'. Remove or refactor the condition(s) to avoid dead code. + +## [CA1509](https://docs.microsoft.com/visualstudio/code-quality/ca1509): Invalid entry in code metrics rule specification file + +|Item|Value| +|-|-| +|Category|Maintainability| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Invalid entry in code metrics rule specification file. + +## [CA1700](https://docs.microsoft.com/visualstudio/code-quality/ca1700): Do not name enum values 'Reserved' + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +This rule assumes that an enumeration member that has a name that contains "reserved" is not currently used but is a placeholder to be renamed or removed in a future version. Renaming or removing a member is a breaking change. + +## [CA1707](https://docs.microsoft.com/visualstudio/code-quality/ca1707): Identifiers should not contain underscores + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +By convention, identifier names do not contain the underscore (_) character. This rule checks namespaces, types, members, and parameters. + +## [CA1708](https://docs.microsoft.com/visualstudio/code-quality/ca1708): Identifiers should differ by more than case + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Identifiers for namespaces, types, members, and parameters cannot differ only by case because languages that target the common language runtime are not required to be case-sensitive. + +## [CA1710](https://docs.microsoft.com/visualstudio/code-quality/ca1710): Identifiers should have correct suffix + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +By convention, the names of types that extend certain base types or that implement certain interfaces, or types that are derived from these types, have a suffix that is associated with the base type or interface. + +## [CA1711](https://docs.microsoft.com/visualstudio/code-quality/ca1711): Identifiers should not have incorrect suffix + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +By convention, only the names of types that extend certain base types or that implement certain interfaces, or types that are derived from these types, should end with specific reserved suffixes. Other type names should not use these reserved suffixes. + +## [CA1712](https://docs.microsoft.com/visualstudio/code-quality/ca1712): Do not prefix enum values with type name + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +An enumeration's values should not start with the type name of the enumeration. + +## [CA1713](https://docs.microsoft.com/visualstudio/code-quality/ca1713): Events should not have 'Before' or 'After' prefix + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Event names should describe the action that raises the event. To name related events that are raised in a specific sequence, use the present or past tense to indicate the relative position in the sequence of actions. For example, when naming a pair of events that is raised when closing a resource, you might name it 'Closing' and 'Closed', instead of 'BeforeClose' and 'AfterClose'. + +## [CA1714](https://docs.microsoft.com/visualstudio/code-quality/ca1714): Flags enums should have plural names + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A public enumeration has the System.FlagsAttribute attribute, and its name does not end in ""s"". Types that are marked by using FlagsAttribute have names that are plural because the attribute indicates that more than one value can be specified. + +## [CA1715](https://docs.microsoft.com/visualstudio/code-quality/ca1715): Identifiers should have correct prefix + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The name of an externally visible interface does not start with an uppercase ""I"". The name of a generic type parameter on an externally visible type or method does not start with an uppercase ""T"". + +## [CA1716](https://docs.microsoft.com/visualstudio/code-quality/ca1716): Identifiers should not match keywords + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A namespace name or a type name matches a reserved keyword in a programming language. Identifiers for namespaces and types should not match keywords that are defined by languages that target the common language runtime. + +## [CA1717](https://docs.microsoft.com/visualstudio/code-quality/ca1717): Only FlagsAttribute enums should have plural names + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Naming conventions dictate that a plural name for an enumeration indicates that more than one value of the enumeration can be specified at the same time. + +## [CA1720](https://docs.microsoft.com/visualstudio/code-quality/ca1720): Identifier contains type name + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Names of parameters and members are better used to communicate their meaning than to describe their type, which is expected to be provided by development tools. For names of members, if a data type name must be used, use a language-independent name instead of a language-specific one. + +## [CA1721](https://docs.microsoft.com/visualstudio/code-quality/ca1721): Property names should not match get methods + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The name of a public or protected member starts with ""Get"" and otherwise matches the name of a public or protected property. ""Get"" methods and properties should have names that clearly distinguish their function. + +## [CA1724](https://docs.microsoft.com/visualstudio/code-quality/ca1724): Type names should not match namespaces + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Type names should not match the names of namespaces that are defined in the .NET Framework class library. Violating this rule can reduce the usability of the library. + +## [CA1725](https://docs.microsoft.com/visualstudio/code-quality/ca1725): Parameter names should match base declaration + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Consistent naming of parameters in an override hierarchy increases the usability of the method overrides. A parameter name in a derived method that differs from the name in the base declaration can cause confusion about whether the method is an override of the base method or a new overload of the method. + +## [CA1801](https://docs.microsoft.com/visualstudio/code-quality/ca1801): Review unused parameters + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Avoid unused paramereters in your code. If the parameter cannot be removed, then change its name so it starts with an underscore and is optionally followed by an integer, such as '_', '_1', '_2', etc. These are treated as special discard symbol names. + +## [CA1802](https://docs.microsoft.com/visualstudio/code-quality/ca1802): Use literals where appropriate + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +A field is declared static and read-only (Shared and ReadOnly in Visual Basic), and is initialized by using a value that is computable at compile time. Because the value that is assigned to the targeted field is computable at compile time, change the declaration to a const (Const in Visual Basic) field so that the value is computed at compile time instead of at run?time. + +## [CA1805](https://docs.microsoft.com/visualstudio/code-quality/ca1805): Do not initialize unnecessarily + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +The .NET runtime initializes all fields of reference types to their default values before running the constructor. In most cases, explicitly initializing a field to its default value in a constructor is redundant, adding maintenance costs and potentially degrading performance (such as with increased assembly size), and the explicit initialization can be removed. In some cases, such as with static readonly fields that permanently retain their default value, consider instead changing them to be constants or properties. + +## [CA1806](https://docs.microsoft.com/visualstudio/code-quality/ca1806): Do not ignore method results + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A new object is created but never used; or a method that creates and returns a new string is called and the new string is never used; or a COM or P/Invoke method returns an HRESULT or error code that is never used. + +## [CA1812](https://docs.microsoft.com/visualstudio/code-quality/ca1812): Avoid uninstantiated internal classes + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +An instance of an assembly-level type is not created by code in the assembly. + +## [CA1814](https://docs.microsoft.com/visualstudio/code-quality/ca1814): Prefer jagged arrays over multidimensional + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A jagged array is an array whose elements are arrays. The arrays that make up the elements can be of different sizes, leading to less wasted space for some sets of data. + +## [CA1815](https://docs.microsoft.com/visualstudio/code-quality/ca1815): Override equals and operator equals on value types + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +For value types, the inherited implementation of Equals uses the Reflection library and compares the contents of all fields. Reflection is computationally expensive, and comparing every field for equality might be unnecessary. If you expect users to compare or sort instances, or to use instances as hash table keys, your value type should implement Equals. + +## [CA1819](https://docs.microsoft.com/visualstudio/code-quality/ca1819): Properties should not return arrays + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Arrays that are returned by properties are not write-protected, even when the property is read-only. To keep the array tamper-proof, the property must return a copy of the array. Typically, users will not understand the adverse performance implications of calling such a property. + +## [CA1821](https://docs.microsoft.com/visualstudio/code-quality/ca1821): Remove empty Finalizers + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Finalizers should be avoided where possible, to avoid the additional performance overhead involved in tracking object lifetime. + +## [CA1822](https://docs.microsoft.com/visualstudio/code-quality/ca1822): Mark members as static + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Members that do not access instance data or call instance methods can be marked as static. After you mark the methods as static, the compiler will emit nonvirtual call sites to these members. This can give you a measurable performance gain for performance-sensitive code. + +## [CA1823](https://docs.microsoft.com/visualstudio/code-quality/ca1823): Avoid unused private fields + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Private fields were detected that do not appear to be accessed in the assembly. + +## [CA2007](https://docs.microsoft.com/visualstudio/code-quality/ca2007): Consider calling ConfigureAwait on the awaited task + +|Item|Value| +|-|-| +|Category|Reliability| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +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. + +## [CA2011](https://docs.microsoft.com/visualstudio/code-quality/ca2011): Avoid infinite recursion + +|Item|Value| +|-|-| +|Category|Reliability| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Do not assign the property within its setter. This call might result in an infinite recursion. + +## [CA2109](https://docs.microsoft.com/visualstudio/code-quality/ca2109): Review visible event handlers + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A public or protected event-handling method was detected. Event-handling methods should not be exposed unless absolutely necessary. + +## [CA2119](https://docs.microsoft.com/visualstudio/code-quality/ca2119): Seal methods that satisfy private interfaces + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +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. + +## [CA2200](https://docs.microsoft.com/visualstudio/code-quality/ca2200): Rethrow to preserve stack details + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Re-throwing caught exception changes stack information + +## [CA2211](https://docs.microsoft.com/visualstudio/code-quality/ca2211): Non-constant fields should not be visible + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2214](https://docs.microsoft.com/visualstudio/code-quality/ca2214): Do not call overridable methods in constructors + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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). + +## [CA2217](https://docs.microsoft.com/visualstudio/code-quality/ca2217): Do not mark enums with FlagsAttribute + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +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. + +## [CA2218](https://docs.microsoft.com/visualstudio/code-quality/ca2218): Override GetHashCode on overriding Equals + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +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. + +## [CA2219](https://docs.microsoft.com/visualstudio/code-quality/ca2219): Do not raise exceptions in finally clauses + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2224](https://docs.microsoft.com/visualstudio/code-quality/ca2224): Override Equals on overloading operator equals + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +A public type implements the equality operator but does not override Object.Equals. + +## [CA2225](https://docs.microsoft.com/visualstudio/code-quality/ca2225): Operator overloads have named alternates + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +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. + +## [CA2226](https://docs.microsoft.com/visualstudio/code-quality/ca2226): Operators should have symmetrical overloads + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +A type implements the equality or inequality operator and does not implement the opposite operator. + +## [CA2227](https://docs.microsoft.com/visualstudio/code-quality/ca2227): Collection properties should be read only + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2231](https://docs.microsoft.com/visualstudio/code-quality/ca2231): Overload operator equals on overriding value type Equals + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +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. + +## [CA2234](https://docs.microsoft.com/visualstudio/code-quality/ca2234): Pass system uri objects instead of strings + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2244](https://docs.microsoft.com/visualstudio/code-quality/ca2244): Do not duplicate indexed element initializations + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Indexed elements in objects initializers must initialize unique elements. A duplicate index might overwrite a previous element initialization. + +## [CA2245](https://docs.microsoft.com/visualstudio/code-quality/ca2245): Do not assign a property to itself + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The property {0} should not be assigned to itself + +## [CA2246](https://docs.microsoft.com/visualstudio/code-quality/ca2246): Assigning symbol and its member in the same statement + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. -Rule ID | Title | Category | Enabled | Severity | CodeFix | Description | ---------|-------|----------|---------|----------|---------|--------------------------------------------------------------------------------------------------------------| -[CA1000](https://docs.microsoft.com/visualstudio/code-quality/ca1000) | Do not declare static members on generic types | Design | True | Warning | False | When a static member of a generic type is called, the type argument must be specified for the type. When a generic instance member that does not support inference is called, the type argument must be specified for the member. In these two cases, the syntax for specifying the type argument is different and easily confused. | -[CA1001](https://docs.microsoft.com/visualstudio/code-quality/ca1001) | Types that own disposable fields should be disposable | Design | True | Warning | True | A class declares and implements an instance field that is a System.IDisposable type, and the class does not implement IDisposable. A class that declares an IDisposable field indirectly owns an unmanaged resource and should implement the IDisposable interface. | -[CA1002](https://docs.microsoft.com/visualstudio/code-quality/ca1002) | Do not expose generic lists | Design | False | Warning | False | System.Collections.Generic.List is a generic collection that's designed for performance and not inheritance. List does not contain virtual members that make it easier to change the behavior of an inherited class. | -[CA1003](https://docs.microsoft.com/visualstudio/code-quality/ca1003) | Use generic event handler instances | Design | False | Warning | False | A type contains an event that declares an EventHandler delegate that returns void, whose signature contains two parameters (the first an object and the second a type that is assignable to EventArgs), and the containing assembly targets Microsoft .NET Framework?2.0. | -[CA1005](https://docs.microsoft.com/visualstudio/code-quality/ca1005) | Avoid excessive parameters on generic types | Design | False | Warning | False | The more type parameters a generic type contains, the more difficult it is to know and remember what each type parameter represents. | -[CA1008](https://docs.microsoft.com/visualstudio/code-quality/ca1008) | Enums should have zero value | Design | False | Warning | True | The default value of an uninitialized enumeration, just as other value types, is zero. A nonflags-attributed enumeration should define a member by using the value of zero so that the default value is a valid value of the enumeration. If an enumeration that has the FlagsAttribute attribute applied defines a zero-valued member, its name should be ""None"" to indicate that no values have been set in the enumeration. | -[CA1010](https://docs.microsoft.com/visualstudio/code-quality/ca1010) | Generic interface should also be implemented | Design | True | Warning | False | To broaden the usability of a type, implement one of the generic interfaces. This is especially true for collections as they can then be used to populate generic collection types. | -[CA1012](https://docs.microsoft.com/visualstudio/code-quality/ca1012) | Abstract types should not have public constructors | Design | False | Warning | True | Constructors on abstract types can be called only by derived types. Because public constructors create instances of a type, and you cannot create instances of an abstract type, an abstract type that has a public constructor is incorrectly designed. | -[CA1014](https://docs.microsoft.com/visualstudio/code-quality/ca1014) | Mark assemblies with CLSCompliant | Design | False | Warning | False | The Common Language Specification (CLS) defines naming restrictions, data types, and rules to which assemblies must conform if they will be used across programming languages. Good design dictates that all assemblies explicitly indicate CLS compliance by using CLSCompliantAttribute . If this attribute is not present on an assembly, the assembly is not compliant. | -[CA1016](https://docs.microsoft.com/visualstudio/code-quality/ca1016) | Mark assemblies with assembly version | Design | True | Warning | False | The .NET Framework uses the version number to uniquely identify an assembly, and to bind to types in strongly named assemblies. The version number is used together with version and publisher policy. By default, applications run only with the assembly version with which they were built. | -[CA1017](https://docs.microsoft.com/visualstudio/code-quality/ca1017) | Mark assemblies with ComVisible | Design | False | Warning | False | ComVisibleAttribute determines how COM clients access managed code. Good design dictates that assemblies explicitly indicate COM visibility. COM visibility can be set for the whole assembly and then overridden for individual types and type members. If this attribute is not present, the contents of the assembly are visible to COM clients. | -[CA1018](https://docs.microsoft.com/visualstudio/code-quality/ca1018) | Mark attributes with AttributeUsageAttribute | Design | True | Warning | False | Specify AttributeUsage on {0}. | -[CA1019](https://docs.microsoft.com/visualstudio/code-quality/ca1019) | Define accessors for attribute arguments | Design | False | Warning | True | Remove the property setter from {0} or reduce its accessibility because it corresponds to positional argument {1}. | -[CA1021](https://docs.microsoft.com/visualstudio/code-quality/ca1021) | Avoid out parameters | Design | False | Warning | False | Passing types by reference (using 'out' or 'ref') requires experience with pointers, understanding how value types and reference types differ, and handling methods with multiple return values. Also, the difference between 'out' and 'ref' parameters is not widely understood. | -[CA1024](https://docs.microsoft.com/visualstudio/code-quality/ca1024) | Use properties where appropriate | Design | False | Warning | False | A public or protected method has a name that starts with ""Get"", takes no parameters, and returns a value that is not an array. The method might be a good candidate to become a property. | -[CA1027](https://docs.microsoft.com/visualstudio/code-quality/ca1027) | Mark enums with FlagsAttribute | Design | False | Warning | True | An enumeration is a value type that defines a set of related named constants. Apply FlagsAttribute to an enumeration when its named constants can be meaningfully combined. | -[CA1028](https://docs.microsoft.com/visualstudio/code-quality/ca1028) | Enum Storage should be Int32 | Design | True | Warning | True | An enumeration is a value type that defines a set of related named constants. By default, the System.Int32 data type is used to store the constant value. Although you can change this underlying type, it is not required or recommended for most scenarios. | -[CA1030](https://docs.microsoft.com/visualstudio/code-quality/ca1030) | Use events where appropriate | Design | True | Warning | False | This rule detects methods that have names that ordinarily would be used for events. If a method is called in response to a clearly defined state change, the method should be invoked by an event handler. Objects that call the method should raise events instead of calling the method directly. | -[CA1031](https://docs.microsoft.com/visualstudio/code-quality/ca1031) | Do not catch general exception types | Design | True | Warning | False | A general exception such as System.Exception or System.SystemException or a disallowed exception type is caught in a catch statement, or a general catch clause is used. General and disallowed exceptions should not be caught. | -[CA1032](https://docs.microsoft.com/visualstudio/code-quality/ca1032) | Implement standard exception constructors | Design | True | Warning | True | Failure to provide the full set of constructors can make it difficult to correctly handle exceptions. | -[CA1033](https://docs.microsoft.com/visualstudio/code-quality/ca1033) | Interface methods should be callable by child types | Design | False | Warning | True | An unsealed externally visible type provides an explicit method implementation of a public interface and does not provide an alternative externally visible method that has the same name. | -[CA1034](https://docs.microsoft.com/visualstudio/code-quality/ca1034) | Nested types should not be visible | Design | True | Warning | False | A nested type is a type that is declared in the scope of another type. Nested types are useful to encapsulate private implementation details of the containing type. Used for this purpose, nested types should not be externally visible. | -[CA1036](https://docs.microsoft.com/visualstudio/code-quality/ca1036) | Override methods on comparable types | Design | True | Warning | True | A public or protected type implements the System.IComparable interface. It does not override Object.Equals nor does it overload the language-specific operator for equality, inequality, less than, less than or equal, greater than or greater than or equal. | -[CA1040](https://docs.microsoft.com/visualstudio/code-quality/ca1040) | Avoid empty interfaces | Design | True | Warning | False | Interfaces define members that provide a behavior or usage contract. The functionality that is described by the interface can be adopted by any type, regardless of where the type appears in the inheritance hierarchy. A type implements an interface by providing implementations for the members of the interface. An empty interface does not define any members; therefore, it does not define a contract that can be implemented. | -[CA1041](https://docs.microsoft.com/visualstudio/code-quality/ca1041) | Provide ObsoleteAttribute message | Design | True | Warning | False | A type or member is marked by using a System.ObsoleteAttribute attribute that does not have its ObsoleteAttribute.Message property specified. When a type or member that is marked by using ObsoleteAttribute is compiled, the Message property of the attribute is displayed. This gives the user information about the obsolete type or member. | -[CA1043](https://docs.microsoft.com/visualstudio/code-quality/ca1043) | Use Integral Or String Argument For Indexers | Design | True | Warning | False | Indexers, that is, indexed properties, should use integer or string types for the index. These types are typically used for indexing data structures and increase the usability of the library. Use of the Object type should be restricted to those cases where the specific integer or string type cannot be specified at design time. If the design requires other types for the index, reconsider whether the type represents a logical data store. If it does not represent a logical data store, use a method. | -[CA1044](https://docs.microsoft.com/visualstudio/code-quality/ca1044) | Properties should not be write only | Design | True | Warning | False | Although it is acceptable and often necessary to have a read-only property, the design guidelines prohibit the use of write-only properties. This is because letting a user set a value, and then preventing the user from viewing that value, does not provide any security. Also, without read access, the state of shared objects cannot be viewed, which limits their usefulness. | -[CA1045](https://docs.microsoft.com/visualstudio/code-quality/ca1045) | Do not pass types by reference | Design | False | Warning | False | Passing types by reference (using out or ref) requires experience with pointers, understanding how value types and reference types differ, and handling methods that have multiple return values. Also, the difference between out and ref parameters is not widely understood. | -[CA1046](https://docs.microsoft.com/visualstudio/code-quality/ca1046) | Do not overload equality operator on reference types | Design | False | Warning | False | For reference types, the default implementation of the equality operator is almost always correct. By default, two references are equal only if they point to the same object. If the operator is providing meaningful value equality, the type should implement the generic 'System.IEquatable' interface. | -[CA1047](https://docs.microsoft.com/visualstudio/code-quality/ca1047) | Do not declare protected member in sealed type | Design | True | Warning | False | Types declare protected members so that inheriting types can access or override the member. By definition, you cannot inherit from a sealed type, which means that protected methods on sealed types cannot be called. | -[CA1050](https://docs.microsoft.com/visualstudio/code-quality/ca1050) | Declare types in namespaces | Design | False | Warning | False | Types are declared in namespaces to prevent name collisions and as a way to organize related types in an object hierarchy. | -[CA1051](https://docs.microsoft.com/visualstudio/code-quality/ca1051) | Do not declare visible instance fields | Design | True | Warning | False | The primary use of a field should be as an implementation detail. Fields should be private or internal and should be exposed by using properties. | -[CA1052](https://docs.microsoft.com/visualstudio/code-quality/ca1052) | Static holder types should be Static or NotInheritable | Design | True | Warning | True | Type '{0}' is a static holder type but is neither static nor NotInheritable | -[CA1054](https://docs.microsoft.com/visualstudio/code-quality/ca1054) | Uri parameters should not be strings | Design | True | Warning | True | If a method takes a string representation of a URI, a corresponding overload should be provided that takes an instance of the URI class, which provides these services in a safe and secure manner. | -[CA1055](https://docs.microsoft.com/visualstudio/code-quality/ca1055) | Uri return values should not be strings | Design | True | Warning | False | This rule assumes that the method returns a URI. A string representation of a URI is prone to parsing and encoding errors, and can lead to security vulnerabilities. The System.Uri class provides these services in a safe and secure manner. | -[CA1056](https://docs.microsoft.com/visualstudio/code-quality/ca1056) | Uri properties should not be strings | Design | True | Warning | False | This rule assumes that the property represents a Uniform Resource Identifier (URI). A string representation of a URI is prone to parsing and encoding errors, and can lead to security vulnerabilities. The System.Uri class provides these services in a safe and secure manner. | -[CA1060](https://docs.microsoft.com/visualstudio/code-quality/ca1060) | Move pinvokes to native methods class | Design | False | Warning | False | Platform Invocation methods, such as those that are marked by using the System.Runtime.InteropServices.DllImportAttribute attribute, or methods that are defined by using the Declare keyword in Visual Basic, access unmanaged code. These methods should be of the NativeMethods, SafeNativeMethods, or UnsafeNativeMethods class. | -[CA1061](https://docs.microsoft.com/visualstudio/code-quality/ca1061) | Do not hide base class methods | Design | True | Warning | False | A method in a base type is hidden by an identically named method in a derived type when the parameter signature of the derived method differs only by types that are more weakly derived than the corresponding types in the parameter signature of the base method. | -[CA1062](https://docs.microsoft.com/visualstudio/code-quality/ca1062) | Validate arguments of public methods | Design | True | Warning | False | An externally visible method dereferences one of its reference arguments without verifying whether that argument is null (Nothing in Visual Basic). All reference arguments that are passed to externally visible methods should be checked against null. If appropriate, throw an ArgumentNullException when the argument is null or add a Code Contract precondition asserting non-null argument. If the method is designed to be called only by known assemblies, you should make the method internal. | -[CA1063](https://docs.microsoft.com/visualstudio/code-quality/ca1063) | Implement IDisposable Correctly | Design | True | Warning | False | All IDisposable types should implement the Dispose pattern correctly. | -[CA1064](https://docs.microsoft.com/visualstudio/code-quality/ca1064) | Exceptions should be public | Design | True | Warning | True | An internal exception is visible only inside its own internal scope. After the exception falls outside the internal scope, only the base exception can be used to catch the exception. If the internal exception is inherited from T:System.Exception, T:System.SystemException, or T:System.ApplicationException, the external code will not have sufficient information to know what to do with the exception. | -[CA1065](https://docs.microsoft.com/visualstudio/code-quality/ca1065) | Do not raise exceptions in unexpected locations | Design | True | Warning | False | A method that is not expected to throw exceptions throws an exception. | -[CA1066](https://docs.microsoft.com/visualstudio/code-quality/ca1066) | Implement IEquatable when overriding Object.Equals | Design | True | Warning | True | When a type T overrides Object.Equals(object), the implementation must cast the object argument to the correct type T before performing the comparison. If the type implements IEquatable, and therefore offers the method T.Equals(T), and if the argument is known at compile time to be of type T, then the compiler can call IEquatable.Equals(T) instead of Object.Equals(object), and no cast is necessary, improving performance. | -[CA1067](https://docs.microsoft.com/visualstudio/code-quality/ca1067) | Override Object.Equals(object) when implementing IEquatable | Design | True | Warning | True | When a type T implements the interface IEquatable, it suggests to a user who sees a call to the Equals method in source code that an instance of the type can be equated with an instance of any other type. The user might be confused if their attempt to equate the type with an instance of another type fails to compile. This violates the "principle of least surprise". | -[CA1068](https://docs.microsoft.com/visualstudio/code-quality/ca1068) | CancellationToken parameters must come last | Design | True | Warning | False | Method '{0}' should take CancellationToken as the last parameter | -[CA1069](https://docs.microsoft.com/visualstudio/code-quality/ca1069) | Enums values should not be duplicated | Design | True | Warning | False | The field reference '{0}' is duplicated in this bitwise initialization. | -[CA1070](https://docs.microsoft.com/visualstudio/code-quality/ca1070) | Do not declare event fields as virtual | Design | True | Warning | False | Do not declare virtual events in a base class. Overridden events in a derived class have undefined behavior. The C# compiler does not handle this correctly and it is unpredictable whether a subscriber to the derived event will actually be subscribing to the base class event. | -[CA1200](https://docs.microsoft.com/visualstudio/code-quality/ca1200) | Avoid using cref tags with a prefix | Documentation | True | Warning | False | Use of cref tags with prefixes should be avoided, since it prevents the compiler from verifying references and the IDE from updating references during refactorings. It is permissible to suppress this error at a single documentation site if the cref must use a prefix because the type being mentioned is not findable by the compiler. For example, if a cref is mentioning a special attribute in the full framework but you're in a file that compiles against the portable framework, or if you want to reference a type at higher layer of Roslyn, you should suppress the error. You should not suppress the error just because you want to take a shortcut and avoid using the full syntax. | -[CA1501](https://docs.microsoft.com/visualstudio/code-quality/ca1501) | Avoid excessive inheritance | Maintainability | False | Warning | False | Deeply nested type hierarchies can be difficult to follow, understand, and maintain. This rule limits analysis to hierarchies in the same module. To fix a violation of this rule, derive the type from a base type that is less deep in the inheritance hierarchy or eliminate some of the intermediate base types. | -[CA1502](https://docs.microsoft.com/visualstudio/code-quality/ca1502) | Avoid excessive complexity | Maintainability | False | Warning | False | Cyclomatic complexity measures the number of linearly independent paths through the method, which is determined by the number and complexity of conditional branches. A low cyclomatic complexity generally indicates a method that is easy to understand, test, and maintain. The cyclomatic complexity is calculated from a control flow graph of the method and is given as follows: `cyclomatic complexity = the number of edges - the number of nodes + 1`, where a node represents a logic branch point and an edge represents a line between nodes. | -[CA1505](https://docs.microsoft.com/visualstudio/code-quality/ca1505) | Avoid unmaintainable code | Maintainability | False | Warning | False | The maintainability index is calculated by using the following metrics: lines of code, program volume, and cyclomatic complexity. Program volume is a measure of the difficulty of understanding of a symbol that is based on the number of operators and operands in the code. Cyclomatic complexity is a measure of the structural complexity of the type or method. A low maintainability index indicates that code is probably difficult to maintain and would be a good candidate to redesign. | -[CA1506](https://docs.microsoft.com/visualstudio/code-quality/ca1506) | Avoid excessive class coupling | Maintainability | False | Warning | False | This rule measures class coupling by counting the number of unique type references that a symbol contains. Symbols that have a high degree of class coupling can be difficult to maintain. It is a good practice to have types and methods that exhibit low coupling and high cohesion. To fix this violation, try to redesign the code to reduce the number of types to which it is coupled. | -[CA1507](https://docs.microsoft.com/visualstudio/code-quality/ca1507) | Use nameof to express symbol names | Maintainability | True | Warning | True | Using nameof helps keep your code valid when refactoring. | -[CA1508](https://docs.microsoft.com/visualstudio/code-quality/ca1508) | Avoid dead conditional code | Maintainability | False | Warning | False | '{0}' is never '{1}'. Remove or refactor the condition(s) to avoid dead code. | -[CA1509](https://docs.microsoft.com/visualstudio/code-quality/ca1509) | Invalid entry in code metrics rule specification file | Maintainability | False | Warning | False | Invalid entry in code metrics rule specification file | -[CA1700](https://docs.microsoft.com/visualstudio/code-quality/ca1700) | Do not name enum values 'Reserved' | Naming | False | Warning | False | This rule assumes that an enumeration member that has a name that contains "reserved" is not currently used but is a placeholder to be renamed or removed in a future version. Renaming or removing a member is a breaking change. | -[CA1707](https://docs.microsoft.com/visualstudio/code-quality/ca1707) | Identifiers should not contain underscores | Naming | True | Warning | False | By convention, identifier names do not contain the underscore (_) character. This rule checks namespaces, types, members, and parameters. | -[CA1708](https://docs.microsoft.com/visualstudio/code-quality/ca1708) | Identifiers should differ by more than case | Naming | False | Warning | False | Identifiers for namespaces, types, members, and parameters cannot differ only by case because languages that target the common language runtime are not required to be case-sensitive. | -[CA1710](https://docs.microsoft.com/visualstudio/code-quality/ca1710) | Identifiers should have correct suffix | Naming | True | Warning | False | By convention, the names of types that extend certain base types or that implement certain interfaces, or types that are derived from these types, have a suffix that is associated with the base type or interface. | -[CA1711](https://docs.microsoft.com/visualstudio/code-quality/ca1711) | Identifiers should not have incorrect suffix | Naming | False | Warning | False | By convention, only the names of types that extend certain base types or that implement certain interfaces, or types that are derived from these types, should end with specific reserved suffixes. Other type names should not use these reserved suffixes. | -[CA1712](https://docs.microsoft.com/visualstudio/code-quality/ca1712) | Do not prefix enum values with type name | Naming | True | Warning | False | An enumeration's values should not start with the type name of the enumeration. | -[CA1713](https://docs.microsoft.com/visualstudio/code-quality/ca1713) | Events should not have 'Before' or 'After' prefix | Naming | True | Warning | False | Event names should describe the action that raises the event. To name related events that are raised in a specific sequence, use the present or past tense to indicate the relative position in the sequence of actions. For example, when naming a pair of events that is raised when closing a resource, you might name it 'Closing' and 'Closed', instead of 'BeforeClose' and 'AfterClose'. | -[CA1714](https://docs.microsoft.com/visualstudio/code-quality/ca1714) | Flags enums should have plural names | Naming | True | Warning | False | A public enumeration has the System.FlagsAttribute attribute, and its name does not end in ""s"". Types that are marked by using FlagsAttribute have names that are plural because the attribute indicates that more than one value can be specified. | -[CA1715](https://docs.microsoft.com/visualstudio/code-quality/ca1715) | Identifiers should have correct prefix | Naming | True | Warning | False | Identifiers should have correct prefix | -[CA1716](https://docs.microsoft.com/visualstudio/code-quality/ca1716) | Identifiers should not match keywords | Naming | True | Warning | False | A namespace name or a type name matches a reserved keyword in a programming language. Identifiers for namespaces and types should not match keywords that are defined by languages that target the common language runtime. | -[CA1717](https://docs.microsoft.com/visualstudio/code-quality/ca1717) | Only FlagsAttribute enums should have plural names | Naming | True | Warning | False | Naming conventions dictate that a plural name for an enumeration indicates that more than one value of the enumeration can be specified at the same time. | -[CA1720](https://docs.microsoft.com/visualstudio/code-quality/ca1720) | Identifier contains type name | Naming | True | Warning | False | Names of parameters and members are better used to communicate their meaning than to describe their type, which is expected to be provided by development tools. For names of members, if a data type name must be used, use a language-independent name instead of a language-specific one. | -[CA1721](https://docs.microsoft.com/visualstudio/code-quality/ca1721) | Property names should not match get methods | Naming | True | Warning | False | The name of a public or protected member starts with ""Get"" and otherwise matches the name of a public or protected property. ""Get"" methods and properties should have names that clearly distinguish their function. | -[CA1724](https://docs.microsoft.com/visualstudio/code-quality/ca1724) | Type names should not match namespaces | Naming | True | Warning | False | Type names should not match the names of namespaces that are defined in the .NET Framework class library. Violating this rule can reduce the usability of the library. | -[CA1725](https://docs.microsoft.com/visualstudio/code-quality/ca1725) | Parameter names should match base declaration | Naming | False | Warning | True | Consistent naming of parameters in an override hierarchy increases the usability of the method overrides. A parameter name in a derived method that differs from the name in the base declaration can cause confusion about whether the method is an override of the base method or a new overload of the method. | -[CA1801](https://docs.microsoft.com/visualstudio/code-quality/ca1801) | Review unused parameters | Usage | True | Warning | True | Avoid unused paramereters in your code. If the parameter cannot be removed, then change its name so it starts with an underscore and is optionally followed by an integer, such as '_', '_1', '_2', etc. These are treated as special discard symbol names. | -[CA1802](https://docs.microsoft.com/visualstudio/code-quality/ca1802) | Use literals where appropriate | Performance | True | Warning | True | A field is declared static and read-only (Shared and ReadOnly in Visual Basic), and is initialized by using a value that is computable at compile time. Because the value that is assigned to the targeted field is computable at compile time, change the declaration to a const (Const in Visual Basic) field so that the value is computed at compile time instead of at run?time. | -[CA1805](https://docs.microsoft.com/visualstudio/code-quality/ca1805) | Do not initialize unnecessarily | Performance | True | Warning | True | The .NET runtime initializes all fields of reference types to their default values before running the constructor. In most cases, explicitly initializing a field to its default value in a constructor is redundant, adding maintenance costs and potentially degrading performance (such as with increased assembly size), and the explicit initialization can be removed. In some cases, such as with static readonly fields that permanently retain their default value, consider instead changing them to be constants or properties. | -[CA1806](https://docs.microsoft.com/visualstudio/code-quality/ca1806) | Do not ignore method results | Performance | True | Warning | False | A new object is created but never used; or a method that creates and returns a new string is called and the new string is never used; or a COM or P/Invoke method returns an HRESULT or error code that is never used. | -[CA1812](https://docs.microsoft.com/visualstudio/code-quality/ca1812) | Avoid uninstantiated internal classes | Performance | True | Warning | False | An instance of an assembly-level type is not created by code in the assembly. | -[CA1814](https://docs.microsoft.com/visualstudio/code-quality/ca1814) | Prefer jagged arrays over multidimensional | Performance | True | Warning | False | A jagged array is an array whose elements are arrays. The arrays that make up the elements can be of different sizes, leading to less wasted space for some sets of data. | -[CA1815](https://docs.microsoft.com/visualstudio/code-quality/ca1815) | Override equals and operator equals on value types | Performance | True | Warning | True | For value types, the inherited implementation of Equals uses the Reflection library and compares the contents of all fields. Reflection is computationally expensive, and comparing every field for equality might be unnecessary. If you expect users to compare or sort instances, or to use instances as hash table keys, your value type should implement Equals. | -[CA1819](https://docs.microsoft.com/visualstudio/code-quality/ca1819) | Properties should not return arrays | Performance | True | Warning | False | Arrays that are returned by properties are not write-protected, even when the property is read-only. To keep the array tamper-proof, the property must return a copy of the array. Typically, users will not understand the adverse performance implications of calling such a property. | -[CA1821](https://docs.microsoft.com/visualstudio/code-quality/ca1821) | Remove empty Finalizers | Performance | True | Warning | True | Finalizers should be avoided where possible, to avoid the additional performance overhead involved in tracking object lifetime. | -[CA1822](https://docs.microsoft.com/visualstudio/code-quality/ca1822) | Mark members as static | Performance | True | Warning | True | Members that do not access instance data or call instance methods can be marked as static. After you mark the methods as static, the compiler will emit nonvirtual call sites to these members. This can give you a measurable performance gain for performance-sensitive code. | -[CA1823](https://docs.microsoft.com/visualstudio/code-quality/ca1823) | Avoid unused private fields | Performance | True | Warning | True | Private fields were detected that do not appear to be accessed in the assembly. | -[CA2007](https://docs.microsoft.com/visualstudio/code-quality/ca2007) | Consider calling ConfigureAwait on the awaited task | Reliability | True | Warning | 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. | -[CA2011](https://docs.microsoft.com/visualstudio/code-quality/ca2011) | Avoid infinite recursion | Reliability | True | Warning | False | Do not assign the property within its setter. This call might result in an infinite recursion. | -[CA2109](https://docs.microsoft.com/visualstudio/code-quality/ca2109) | Review visible event handlers | Security | True | Warning | False | A public or protected event-handling method was detected. Event-handling methods should not be exposed unless absolutely necessary. | -[CA2119](https://docs.microsoft.com/visualstudio/code-quality/ca2119) | Seal methods that satisfy private interfaces | Security | True | Warning | 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. | -[CA2200](https://docs.microsoft.com/visualstudio/code-quality/ca2200) | Rethrow to preserve stack details. | Usage | True | Warning | True | Re-throwing caught exception changes stack information. | -[CA2211](https://docs.microsoft.com/visualstudio/code-quality/ca2211) | Non-constant fields should not be visible | Usage | True | Warning | 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. | -[CA2214](https://docs.microsoft.com/visualstudio/code-quality/ca2214) | Do not call overridable methods in constructors | Usage | True | Warning | 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). | -[CA2217](https://docs.microsoft.com/visualstudio/code-quality/ca2217) | Do not mark enums with FlagsAttribute | Usage | False | Warning | 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. | -[CA2218](https://docs.microsoft.com/visualstudio/code-quality/ca2218) | Override GetHashCode on overriding Equals | Usage | True | Warning | 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. | -[CA2219](https://docs.microsoft.com/visualstudio/code-quality/ca2219) | Do not raise exceptions in finally clauses | Usage | True | Warning | 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. | -[CA2224](https://docs.microsoft.com/visualstudio/code-quality/ca2224) | Override Equals on overloading operator equals | Usage | True | Warning | True | A public type implements the equality operator but does not override Object.Equals. | -[CA2225](https://docs.microsoft.com/visualstudio/code-quality/ca2225) | Operator overloads have named alternates | Usage | True | Warning | 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. | -[CA2226](https://docs.microsoft.com/visualstudio/code-quality/ca2226) | Operators should have symmetrical overloads | Usage | True | Warning | True | A type implements the equality or inequality operator and does not implement the opposite operator. | -[CA2227](https://docs.microsoft.com/visualstudio/code-quality/ca2227) | Collection properties should be read only | Usage | True | Warning | 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. | -[CA2231](https://docs.microsoft.com/visualstudio/code-quality/ca2231) | Overload operator equals on overriding value type Equals | Usage | True | Warning | 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 | -[CA2234](https://docs.microsoft.com/visualstudio/code-quality/ca2234) | Pass system uri objects instead of strings | Usage | True | Warning | 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. | -[CA2244](https://docs.microsoft.com/visualstudio/code-quality/ca2244) | Do not duplicate indexed element initializations | Usage | True | Warning | True | Indexed elements in objects initializers must initialize unique elements. A duplicate index might overwrite a previous element initialization. | -[CA2245](https://docs.microsoft.com/visualstudio/code-quality/ca2245) | Do not assign a property to itself. | Usage | True | Warning | False | The property {0} should not be assigned to itself. | -[CA2246](https://docs.microsoft.com/visualstudio/code-quality/ca2246) | Assigning symbol and its member in the same statement. | Usage | True | Warning | 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 c723428d4d..30b7b6d644 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Microsoft.CodeQuality.Analyzers.sarif +++ b/src/Microsoft.CodeQuality.Analyzers/Microsoft.CodeQuality.Analyzers.sarif @@ -222,7 +222,7 @@ "CA1018": { "id": "CA1018", "shortDescription": "Mark attributes with AttributeUsageAttribute", - "fullDescription": "Specify AttributeUsage on {0}.", + "fullDescription": "Specify AttributeUsage on {0}", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1018", "properties": { @@ -620,8 +620,8 @@ }, "CA1054": { "id": "CA1054", - "shortDescription": "Uri parameters should not be strings", - "fullDescription": "If a method takes a string representation of a URI, a corresponding overload should be provided that takes an instance of the URI class, which provides these services in a safe and secure manner.", + "shortDescription": "URI-like parameters should not be strings", + "fullDescription": "This rule assumes that the parameter represents a Uniform Resource Identifier (URI). A string representation or a URI is prone to parsing and encoding errors, and can lead to security vulnerabilities. 'System.Uri' class provides these services in a safe and secure manner.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1054", "properties": { @@ -640,7 +640,7 @@ }, "CA1055": { "id": "CA1055", - "shortDescription": "Uri return values should not be strings", + "shortDescription": "URI-like return values should not be strings", "fullDescription": "This rule assumes that the method returns a URI. A string representation of a URI is prone to parsing and encoding errors, and can lead to security vulnerabilities. The System.Uri class provides these services in a safe and secure manner.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1055", @@ -660,7 +660,7 @@ }, "CA1056": { "id": "CA1056", - "shortDescription": "Uri properties should not be strings", + "shortDescription": "URI-like properties should not be strings", "fullDescription": "This rule assumes that the property represents a Uniform Resource Identifier (URI). A string representation of a URI is prone to parsing and encoding errors, and can lead to security vulnerabilities. The System.Uri class provides these services in a safe and secure manner.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1056", @@ -839,7 +839,7 @@ "CA1069": { "id": "CA1069", "shortDescription": "Enums values should not be duplicated", - "fullDescription": "The field reference '{0}' is duplicated in this bitwise initialization.", + "fullDescription": "The field reference '{0}' is duplicated in this bitwise initialization", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1069", "properties": { @@ -976,7 +976,7 @@ "CA1509": { "id": "CA1509", "shortDescription": "Invalid entry in code metrics rule specification file", - "fullDescription": "Invalid entry in code metrics rule specification file", + "fullDescription": "Invalid entry in code metrics rule specification file.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1509", "properties": { @@ -1155,7 +1155,7 @@ "CA1715": { "id": "CA1715", "shortDescription": "Identifiers should have correct prefix", - "fullDescription": "Identifiers should have correct prefix", + "fullDescription": "The name of an externally visible interface does not start with an uppercase \"\"I\"\". The name of a generic type parameter on an externally visible type or method does not start with an uppercase \"\"T\"\".", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1715", "properties": { @@ -1372,26 +1372,6 @@ ] } }, - "CA1812": { - "id": "CA1812", - "shortDescription": "Avoid uninstantiated internal classes", - "fullDescription": "An instance of an assembly-level type is not created by code in the assembly.", - "defaultLevel": "warning", - "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1812", - "properties": { - "category": "Performance", - "isEnabledByDefault": true, - "typeName": "AvoidUninstantiatedInternalClassesAnalyzer", - "languages": [ - "C#", - "Visual Basic" - ], - "tags": [ - "PortedFromFxCop", - "Telemetry" - ] - } - }, "CA1814": { "id": "CA1814", "shortDescription": "Prefer jagged arrays over multidimensional", @@ -1558,7 +1538,7 @@ "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2109", "properties": { "category": "Security", - "isEnabledByDefault": true, + "isEnabledByDefault": false, "typeName": "ReviewVisibleEventHandlersAnalyzer", "languages": [ "C#", @@ -1733,7 +1713,7 @@ "CA2231": { "id": "CA2231", "shortDescription": "Overload operator equals on overriding value type Equals", - "fullDescription": "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", + "fullDescription": "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.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2231", "properties": { @@ -1770,8 +1750,8 @@ }, "CA2245": { "id": "CA2245", - "shortDescription": "Do not assign a property to itself.", - "fullDescription": "The property {0} should not be assigned to itself.", + "shortDescription": "Do not assign a property to itself", + "fullDescription": "The property {0} should not be assigned to itself", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2245", "properties": { @@ -1789,7 +1769,7 @@ }, "CA2246": { "id": "CA2246", - "shortDescription": "Assigning symbol and its member in the same statement.", + "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", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2246", @@ -1836,7 +1816,7 @@ "CA1019": { "id": "CA1019", "shortDescription": "Define accessors for attribute arguments", - "fullDescription": "Remove the property setter from {0} or reduce its accessibility because it corresponds to positional argument {1}.", + "fullDescription": "Remove the property setter from {0} or reduce its accessibility because it corresponds to positional argument {1}", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1019", "properties": { @@ -1926,10 +1906,29 @@ ] } }, + "CA1812": { + "id": "CA1812", + "shortDescription": "Avoid uninstantiated internal classes", + "fullDescription": "An instance of an assembly-level type is not created by code in the assembly.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1812", + "properties": { + "category": "Performance", + "isEnabledByDefault": true, + "typeName": "CSharpAvoidUninstantiatedInternalClasses", + "languages": [ + "C#" + ], + "tags": [ + "PortedFromFxCop", + "Telemetry" + ] + } + }, "CA2200": { "id": "CA2200", - "shortDescription": "Rethrow to preserve stack details.", - "fullDescription": "Re-throwing caught exception changes stack information.", + "shortDescription": "Rethrow to preserve stack details", + "fullDescription": "Re-throwing caught exception changes stack information", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2200", "properties": { @@ -1995,7 +1994,7 @@ "CA1019": { "id": "CA1019", "shortDescription": "Define accessors for attribute arguments", - "fullDescription": "Remove the property setter from {0} or reduce its accessibility because it corresponds to positional argument {1}.", + "fullDescription": "Remove the property setter from {0} or reduce its accessibility because it corresponds to positional argument {1}", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1019", "properties": { @@ -2085,10 +2084,29 @@ ] } }, + "CA1812": { + "id": "CA1812", + "shortDescription": "Avoid uninstantiated internal classes", + "fullDescription": "An instance of an assembly-level type is not created by code in the assembly.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1812", + "properties": { + "category": "Performance", + "isEnabledByDefault": true, + "typeName": "BasicAvoidUninstantiatedInternalClasses", + "languages": [ + "Visual Basic" + ], + "tags": [ + "PortedFromFxCop", + "Telemetry" + ] + } + }, "CA2200": { "id": "CA2200", - "shortDescription": "Rethrow to preserve stack details.", - "fullDescription": "Re-throwing caught exception changes stack information.", + "shortDescription": "Rethrow to preserve stack details", + "fullDescription": "Re-throwing caught exception changes stack information", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2200", "properties": { diff --git a/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.md b/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.md index 32c51a0307..48a2272834 100644 --- a/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.md +++ b/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.md @@ -1,136 +1,1822 @@ +# Microsoft.NetCore.Analyzers + +## [CA1303](https://docs.microsoft.com/visualstudio/code-quality/ca1303): Do not pass literals as localized parameters + +|Item|Value| +|-|-| +|Category|Globalization| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A method passes a string literal as a parameter to a constructor or method in the .NET Framework class library and that string should be localizable. To fix a violation of this rule, replace the string literal with a string retrieved through an instance of the ResourceManager class. + +## [CA1304](https://docs.microsoft.com/visualstudio/code-quality/ca1304): Specify CultureInfo + +|Item|Value| +|-|-| +|Category|Globalization| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A method or constructor calls a member that has an overload that accepts a System.Globalization.CultureInfo parameter, and the method or constructor does not call the overload that takes the CultureInfo parameter. When a CultureInfo or System.IFormatProvider object is not supplied, the default value that is supplied by the overloaded member might not have the effect that you want in all locales. If the result will be displayed to the user, specify 'CultureInfo.CurrentCulture' as the 'CultureInfo' parameter. Otherwise, if the result will be stored and accessed by software, such as when it is persisted to disk or to a database, specify 'CultureInfo.InvariantCulture'. + +## [CA1305](https://docs.microsoft.com/visualstudio/code-quality/ca1305): Specify IFormatProvider + +|Item|Value| +|-|-| +|Category|Globalization| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A method or constructor calls one or more members that have overloads that accept a System.IFormatProvider parameter, and the method or constructor does not call the overload that takes the IFormatProvider parameter. When a System.Globalization.CultureInfo or IFormatProvider object is not supplied, the default value that is supplied by the overloaded member might not have the effect that you want in all locales. If the result will be based on the input from/output displayed to the user, specify 'CultureInfo.CurrentCulture' as the 'IFormatProvider'. Otherwise, if the result will be stored and accessed by software, such as when it is loaded from disk/database and when it is persisted to disk/database, specify 'CultureInfo.InvariantCulture'. + +## [CA1307](https://docs.microsoft.com/visualstudio/code-quality/ca1307): Specify StringComparison + +|Item|Value| +|-|-| +|Category|Globalization| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A string comparison operation uses a method overload that does not set a StringComparison parameter. If the result will be displayed to the user, such as when sorting a list of items for display in a list box, specify 'StringComparison.CurrentCulture' or 'StringComparison.CurrentCultureIgnoreCase' as the 'StringComparison' parameter. If comparing case-insensitive identifiers, such as file paths, environment variables, or registry keys and values, specify 'StringComparison.OrdinalIgnoreCase'. Otherwise, if comparing case-sensitive identifiers, specify 'StringComparison.Ordinal'. + +## [CA1308](https://docs.microsoft.com/visualstudio/code-quality/ca1308): Normalize strings to uppercase + +|Item|Value| +|-|-| +|Category|Globalization| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Strings should be normalized to uppercase. A small group of characters cannot make a round trip when they are converted to lowercase. To make a round trip means to convert the characters from one locale to another locale that represents character data differently, and then to accurately retrieve the original characters from the converted characters. + +## [CA1309](https://docs.microsoft.com/visualstudio/code-quality/ca1309): Use ordinal stringcomparison + +|Item|Value| +|-|-| +|Category|Globalization| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +A string comparison operation that is nonlinguistic does not set the StringComparison parameter to either Ordinal or OrdinalIgnoreCase. By explicitly setting the parameter to either StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase, your code often gains speed, becomes more correct, and becomes more reliable. + +## [CA1401](https://docs.microsoft.com/visualstudio/code-quality/ca1401): P/Invokes should not be visible + +|Item|Value| +|-|-| +|Category|Interoperability| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A public or protected method in a public type has the System.Runtime.InteropServices.DllImportAttribute attribute (also implemented by the Declare keyword in Visual Basic). Such methods should not be exposed. + +## [CA1417](https://docs.microsoft.com/visualstudio/code-quality/ca1417): Do not use 'OutAttribute' on string parameters for P/Invokes + +|Item|Value| +|-|-| +|Category|Interoperability| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +String parameters passed by value with the 'OutAttribute' can destabilize the runtime if the string is an interned string. + +## [CA1810](https://docs.microsoft.com/visualstudio/code-quality/ca1810): Initialize reference type static fields inline + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A reference 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. + +## [CA1813](https://docs.microsoft.com/visualstudio/code-quality/ca1813): Avoid unsealed attributes + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +The .NET Framework class library provides methods for retrieving custom attributes. By default, these methods search the attribute inheritance hierarchy. Sealing the attribute eliminates the search through the inheritance hierarchy and can improve performance. + +## [CA1816](https://docs.microsoft.com/visualstudio/code-quality/ca1816): Dispose methods should call SuppressFinalize + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A method that is an implementation of Dispose does not call GC.SuppressFinalize; or a method that is not an implementation of Dispose calls GC.SuppressFinalize; or a method calls GC.SuppressFinalize and passes something other than this (Me in Visual?Basic). + +## [CA1820](https://docs.microsoft.com/visualstudio/code-quality/ca1820): Test for empty strings using string length + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Comparing strings by using the String.Length property or the String.IsNullOrEmpty method is significantly faster than using Equals. + +## [CA1824](https://docs.microsoft.com/visualstudio/code-quality/ca1824): Mark assemblies with NeutralResourcesLanguageAttribute + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The NeutralResourcesLanguage attribute informs the ResourceManager of the language that was used to display the resources of a neutral culture for an assembly. This improves lookup performance for the first resource that you load and can reduce your working set. + +## [CA1825](https://docs.microsoft.com/visualstudio/code-quality/ca1825): Avoid zero-length array allocations + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Avoid unnecessary zero-length array allocations. Use {0} instead. + +## [CA1826](https://docs.microsoft.com/visualstudio/code-quality/ca1826): Do not use Enumerable methods on indexable collections + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +This collection is directly indexable. Going through LINQ here causes unnecessary allocations and CPU work. + +## [CA1827](https://docs.microsoft.com/visualstudio/code-quality/ca1827): Do not use Count() or LongCount() when Any() can be used + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +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. + +## [CA1828](https://docs.microsoft.com/visualstudio/code-quality/ca1828): Do not use CountAsync() or LongCountAsync() when AnyAsync() can be used + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +For non-empty collections, CountAsync() and LongCountAsync() enumerate the entire sequence, while AnyAsync() stops at the first item or the first item that satisfies a condition. + +## [CA1829](https://docs.microsoft.com/visualstudio/code-quality/ca1829): Use Length/Count property instead of Count() when available + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. + +## [CA1830](https://docs.microsoft.com/visualstudio/code-quality/ca1830): Prefer strongly-typed Append and Insert method overloads on StringBuilder + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +StringBuilder.Append and StringBuilder.Insert provide overloads for multiple types beyond System.String. When possible, prefer the strongly-typed overloads over using ToString() and the string-based overload. + +## [CA1831](https://docs.microsoft.com/visualstudio/code-quality/ca1831): Use AsSpan or AsMemory instead of Range-based indexers when appropriate + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +The Range-based indexer on string values produces a copy of requested portion of the string. This copy is usually unnecessary when it is implicitly used as a ReadOnlySpan or ReadOnlyMemory value. Use the AsSpan method to avoid the unnecessary copy. + +## [CA1832](https://docs.microsoft.com/visualstudio/code-quality/ca1832): Use AsSpan or AsMemory instead of Range-based indexers when appropriate + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +The Range-based indexer on array values produces a copy of requested portion of the array. This copy is usually unnecessary when it is implicitly used as a ReadOnlySpan or ReadOnlyMemory value. Use the AsSpan method to avoid the unnecessary copy. + +## [CA1833](https://docs.microsoft.com/visualstudio/code-quality/ca1833): Use AsSpan or AsMemory instead of Range-based indexers when appropriate + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +The Range-based indexer on array values produces a copy of requested portion of the array. This copy is often unwanted when it is implicitly used as a Span or Memory value. Use the AsSpan method to avoid the copy. + +## [CA1834](https://docs.microsoft.com/visualstudio/code-quality/ca1834): Consider using 'StringBuilder.Append(char)' when applicable + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +'StringBuilder.Append(char)' is more efficient than 'StringBuilder.Append(string)' when the string is a single character. When calling 'Append' with a constant, prefer using a constant char rather than a constant string containing one character. + +## [CA1835](https://docs.microsoft.com/visualstudio/code-quality/ca1835): Prefer the 'Memory'-based overloads for 'ReadAsync' and 'WriteAsync' + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +'Stream' has a 'ReadAsync' overload that takes a 'Memory' as the first argument, and a 'WriteAsync' overload that takes a 'ReadOnlyMemory' as the first argument. Prefer calling the memory based overloads, which are more efficient. + +## [CA1836](https://docs.microsoft.com/visualstudio/code-quality/ca1836): Prefer IsEmpty over Count + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +For determining whether the object contains or not any items, prefer using 'IsEmpty' property rather than retrieving the number of items from the 'Count' property and comparing it to 0 or 1. + +## [CA1837](https://docs.microsoft.com/visualstudio/code-quality/ca1837): Use 'Environment.ProcessId' + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +'Environment.ProcessId' is simpler and faster than 'Process.GetCurrentProcess().Id'. + +## [CA1838](https://docs.microsoft.com/visualstudio/code-quality/ca1838): Avoid 'StringBuilder' parameters for P/Invokes + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Marshalling of 'StringBuilder' always creates a native buffer copy, resulting in multiple allocations for one marshalling operation. + +## [CA2000](https://docs.microsoft.com/visualstudio/code-quality/ca2000): Dispose objects before losing scope + +|Item|Value| +|-|-| +|Category|Reliability| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2002](https://docs.microsoft.com/visualstudio/code-quality/ca2002): Do not lock on objects with weak identity + +|Item|Value| +|-|-| +|Category|Reliability| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2008](https://docs.microsoft.com/visualstudio/code-quality/ca2008): Do not create tasks without passing a TaskScheduler + +|Item|Value| +|-|-| +|Category|Reliability| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2009](https://docs.microsoft.com/visualstudio/code-quality/ca2009): Do not call ToImmutableCollection on an ImmutableCollection value + +|Item|Value| +|-|-| +|Category|Reliability| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Do not call {0} on an {1} value + +## [CA2012](https://docs.microsoft.com/visualstudio/code-quality/ca2012): Use ValueTasks correctly + +|Item|Value| +|-|-| +|Category|Reliability| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +ValueTasks returned from member invocations are intended to be directly awaited. Attempts to consume a ValueTask multiple times or to directly access one's result before it's known to be completed may result in an exception or corruption. Ignoring such a ValueTask is likely an indication of a functional bug and may degrade performance. + +## [CA2013](https://docs.microsoft.com/visualstudio/code-quality/ca2013): Do not use ReferenceEquals with value types + +|Item|Value| +|-|-| +|Category|Reliability| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Value type typed arguments are uniquely boxed for each call to this method, therefore the result is always false. + +## [CA2014](https://docs.microsoft.com/visualstudio/code-quality/ca2014): Do not use stackalloc in loops + +|Item|Value| +|-|-| +|Category|Reliability| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Stack space allocated by a stackalloc is only released at the end of the current method's invocation. Using it in a loop can result in unbounded stack growth and eventual stack overflow conditions. + +## [CA2015](https://docs.microsoft.com/visualstudio/code-quality/ca2015): Do not define finalizers for types derived from MemoryManager + +|Item|Value| +|-|-| +|Category|Reliability| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Adding a finalizer to a type derived from MemoryManager may permit memory to be freed while it is still in use by a Span. + +## [CA2016](https://docs.microsoft.com/visualstudio/code-quality/ca2016): Forward the 'CancellationToken' parameter to methods that take one + +|Item|Value| +|-|-| +|Category|Reliability| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Forward the 'CancellationToken' parameter to methods that take one to ensure the operation cancellation notifications gets properly propagated, or pass in 'CancellationToken.None' explicitly to indicate intentionally not propagating the token. + +## [CA2100](https://docs.microsoft.com/visualstudio/code-quality/ca2100): Review SQL queries for security vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2101](https://docs.microsoft.com/visualstudio/code-quality/ca2101): Specify marshaling for P/Invoke string arguments + +|Item|Value| +|-|-| +|Category|Globalization| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +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. + +## [CA2201](https://docs.microsoft.com/visualstudio/code-quality/ca2201): Do not raise reserved exception types + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2207](https://docs.microsoft.com/visualstudio/code-quality/ca2207): Initialize value type static fields inline + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2208](https://docs.microsoft.com/visualstudio/code-quality/ca2208): Instantiate argument exceptions correctly + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +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. + +## [CA2213](https://docs.microsoft.com/visualstudio/code-quality/ca2213): Disposable fields should be disposed + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2215](https://docs.microsoft.com/visualstudio/code-quality/ca2215): Dispose methods should call base class dispose + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +A type that implements System.IDisposable inherits from a type that also implements IDisposable. The Dispose method of the inheriting type does not call the Dispose method of the parent type. To fix a violation of this rule, call base.Dispose in your Dispose method. + +## [CA2216](https://docs.microsoft.com/visualstudio/code-quality/ca2216): Disposable types should declare finalizer + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2229](https://docs.microsoft.com/visualstudio/code-quality/ca2229): Implement serialization constructors + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +To fix a violation of this rule, implement the serialization constructor. For a sealed class, make the constructor private; otherwise, make it protected. + +## [CA2235](https://docs.microsoft.com/visualstudio/code-quality/ca2235): Mark all non-serializable fields + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +An instance field of a type that is not serializable is declared in a type that is serializable. + +## [CA2237](https://docs.microsoft.com/visualstudio/code-quality/ca2237): Mark ISerializable types with serializable + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +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. + +## [CA2241](https://docs.microsoft.com/visualstudio/code-quality/ca2241): Provide correct arguments to formatting methods + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2242](https://docs.microsoft.com/visualstudio/code-quality/ca2242): Test for NaN correctly + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +This expression tests a value against Single.Nan or Double.Nan. Use Single.IsNan(Single) or Double.IsNan(Double) to test the value. + +## [CA2243](https://docs.microsoft.com/visualstudio/code-quality/ca2243): Attribute string literals should parse correctly + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The string literal parameter of an attribute does not parse correctly for a URL, a GUID, or a version. + +## [CA2247](https://docs.microsoft.com/visualstudio/code-quality/ca2247): Argument passed to TaskCompletionSource constructor should be TaskCreationOptions enum instead of TaskContinuationOptions enum + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +TaskCompletionSource has constructors that take TaskCreationOptions that control the underlying Task, and constructors that take object state that's stored in the task. Accidentally passing a TaskContinuationOptions instead of a TaskCreationOptions will result in the call treating the options as state. + +## [CA2248](https://docs.microsoft.com/visualstudio/code-quality/ca2248): Provide correct 'enum' argument to 'Enum.HasFlag' + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +'Enum.HasFlag' method expects the 'enum' argument to be of the same 'enum' type as the instance on which the method is invoked and that this 'enum' is marked with 'System.FlagsAttribute'. If these are different 'enum' types, an unhandled exception will be thrown at runtime. If the 'enum' type is not marked with 'System.FlagsAttribute' the call will always return 'false' at runtime. + +## [CA2249](https://docs.microsoft.com/visualstudio/code-quality/ca2249): Consider using 'string.Contains' instead of 'string.IndexOf' + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Calls to 'string.IndexOf' where the result is used to check for the presence/absence of a substring can be replaced by 'string.Contains'. + +## [CA2300](https://docs.microsoft.com/visualstudio/code-quality/ca2300): Do not use insecure deserializer BinaryFormatter + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2301](https://docs.microsoft.com/visualstudio/code-quality/ca2301): Do not call BinaryFormatter.Deserialize without first setting BinaryFormatter.Binder + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. + +## [CA2302](https://docs.microsoft.com/visualstudio/code-quality/ca2302): Ensure BinaryFormatter.Binder is set before calling BinaryFormatter.Deserialize + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. + +## [CA2305](https://docs.microsoft.com/visualstudio/code-quality/ca2305): Do not use insecure deserializer LosFormatter + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The method '{0}' is insecure when deserializing untrusted data. + +## [CA2310](https://docs.microsoft.com/visualstudio/code-quality/ca2310): Do not use insecure deserializer NetDataContractSerializer + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2311](https://docs.microsoft.com/visualstudio/code-quality/ca2311): Do not deserialize without first setting NetDataContractSerializer.Binder + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. + +## [CA2312](https://docs.microsoft.com/visualstudio/code-quality/ca2312): Ensure NetDataContractSerializer.Binder is set before deserializing + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. + +## [CA2315](https://docs.microsoft.com/visualstudio/code-quality/ca2315): Do not use insecure deserializer ObjectStateFormatter + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The method '{0}' is insecure when deserializing untrusted data. + +## [CA2321](https://docs.microsoft.com/visualstudio/code-quality/ca2321): Do not deserialize with JavaScriptSerializer using a SimpleTypeResolver + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2322](https://docs.microsoft.com/visualstudio/code-quality/ca2322): Ensure JavaScriptSerializer is not initialized with SimpleTypeResolver before deserializing + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2326](https://docs.microsoft.com/visualstudio/code-quality/ca2326): Do not use TypeNameHandling values other than None + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2327](https://docs.microsoft.com/visualstudio/code-quality/ca2327): Do not use insecure JsonSerializerSettings + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2328](https://docs.microsoft.com/visualstudio/code-quality/ca2328): Ensure that JsonSerializerSettings are secure + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2329](https://docs.microsoft.com/visualstudio/code-quality/ca2329): Do not deserialize with JsonSerializer using an insecure configuration + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2330](https://docs.microsoft.com/visualstudio/code-quality/ca2330): Ensure that JsonSerializer has a secure configuration when deserializing + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2350](https://docs.microsoft.com/visualstudio/code-quality/ca2350): Do not use DataTable.ReadXml() with untrusted data + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The method '{0}' is insecure when deserializing untrusted data + +## [CA2351](https://docs.microsoft.com/visualstudio/code-quality/ca2351): Do not use DataSet.ReadXml() with untrusted data + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The method '{0}' is insecure when deserializing untrusted data + +## [CA2352](https://docs.microsoft.com/visualstudio/code-quality/ca2352): Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + +## [CA2353](https://docs.microsoft.com/visualstudio/code-quality/ca2353): Unsafe DataSet or DataTable in serializable type + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0} + +## [CA2354](https://docs.microsoft.com/visualstudio/code-quality/ca2354): Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0} + +## [CA2355](https://docs.microsoft.com/visualstudio/code-quality/ca2355): Unsafe DataSet or DataTable type found in deserializable object graph + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0} + +## [CA2356](https://docs.microsoft.com/visualstudio/code-quality/ca2356): Unsafe DataSet or DataTable type in web deserializable object graph + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0} + +## [CA2361](https://docs.microsoft.com/visualstudio/code-quality/ca2361): Ensure autogenerated class containing DataSet.ReadXml() is not used with untrusted data + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The method '{0}' is insecure when deserializing untrusted data. Make sure that autogenerated class containing the '{0}' call is not deserialized with untrusted data. + +## [CA2362](https://docs.microsoft.com/visualstudio/code-quality/ca2362): Unsafe DataSet or DataTable in autogenerated serializable type can be vulnerable to remote code execution attacks + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. Ensure that the autogenerated type is never deserialized with untrusted data. + +## [CA3001](https://docs.microsoft.com/visualstudio/code-quality/ca3001): Review code for SQL injection vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Potential SQL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. + +## [CA3002](https://docs.microsoft.com/visualstudio/code-quality/ca3002): Review code for XSS vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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}'. + +## [CA3003](https://docs.microsoft.com/visualstudio/code-quality/ca3003): Review code for file path injection vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Potential file path injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. + +## [CA3004](https://docs.microsoft.com/visualstudio/code-quality/ca3004): Review code for information disclosure vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Potential information disclosure vulnerability was found where '{0}' in method '{1}' may contain unintended information from '{2}' in method '{3}'. + +## [CA3005](https://docs.microsoft.com/visualstudio/code-quality/ca3005): Review code for LDAP injection vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Potential LDAP injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. + +## [CA3006](https://docs.microsoft.com/visualstudio/code-quality/ca3006): Review code for process command injection vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Potential process command injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. + +## [CA3007](https://docs.microsoft.com/visualstudio/code-quality/ca3007): Review code for open redirect vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Potential open redirect vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. + +## [CA3008](https://docs.microsoft.com/visualstudio/code-quality/ca3008): Review code for XPath injection vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Potential XPath injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. + +## [CA3009](https://docs.microsoft.com/visualstudio/code-quality/ca3009): Review code for XML injection vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Potential XML injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. + +## [CA3010](https://docs.microsoft.com/visualstudio/code-quality/ca3010): Review code for XAML injection vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Potential XAML injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. + +## [CA3011](https://docs.microsoft.com/visualstudio/code-quality/ca3011): Review code for DLL injection vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Potential DLL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. + +## [CA3012](https://docs.microsoft.com/visualstudio/code-quality/ca3012): Review code for regex injection vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Potential regex injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. + +## [CA3061](https://docs.microsoft.com/visualstudio/code-quality/ca3061): Do Not Add Schema By URL + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5350](https://docs.microsoft.com/visualstudio/code-quality/ca5350): Do Not Use Weak Cryptographic Algorithms + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5351](https://docs.microsoft.com/visualstudio/code-quality/ca5351): Do Not Use Broken Cryptographic Algorithms + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5358](https://docs.microsoft.com/visualstudio/code-quality/ca5358): Review cipher mode usage with cryptography experts + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +These cipher modes might be vulnerable to attacks. Consider using recommended modes (CBC, CTS). + +## [CA5359](https://docs.microsoft.com/visualstudio/code-quality/ca5359): Do Not Disable Certificate Validation + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5360](https://docs.microsoft.com/visualstudio/code-quality/ca5360): Do Not Call Dangerous Methods In Deserialization + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5361](https://docs.microsoft.com/visualstudio/code-quality/ca5361): Do Not Disable SChannel Use of Strong Crypto + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5362](https://docs.microsoft.com/visualstudio/code-quality/ca5362): Potential reference cycle in deserialized object graph + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Review code that processes untrusted deserialized data for handling of unexpected reference cycles. An unexpected reference cycle should not cause the code to enter an infinite loop. Otherwise, an unexpected reference cycle can allow an attacker to DOS or exhaust the memory of the process when deserializing untrusted data. + +## [CA5363](https://docs.microsoft.com/visualstudio/code-quality/ca5363): Do Not Disable Request Validation + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5364](https://docs.microsoft.com/visualstudio/code-quality/ca5364): Do Not Use Deprecated Security Protocols + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Using a deprecated security protocol rather than the system default is risky. + +## [CA5365](https://docs.microsoft.com/visualstudio/code-quality/ca5365): Do Not Disable HTTP Header Checking + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5366](https://docs.microsoft.com/visualstudio/code-quality/ca5366): Use XmlReader For DataSet Read Xml + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5367](https://docs.microsoft.com/visualstudio/code-quality/ca5367): Do Not Serialize Types With Pointer Fields + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5368](https://docs.microsoft.com/visualstudio/code-quality/ca5368): Set ViewStateUserKey For Classes Derived From Page + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5369](https://docs.microsoft.com/visualstudio/code-quality/ca5369): Use XmlReader For Deserialize + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5370](https://docs.microsoft.com/visualstudio/code-quality/ca5370): Use XmlReader For Validating Reader + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5371](https://docs.microsoft.com/visualstudio/code-quality/ca5371): Use XmlReader For Schema Read + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5372](https://docs.microsoft.com/visualstudio/code-quality/ca5372): Use XmlReader For XPathDocument + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5373](https://docs.microsoft.com/visualstudio/code-quality/ca5373): Do not use obsolete key derivation function + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5374](https://docs.microsoft.com/visualstudio/code-quality/ca5374): Do Not Use XslTransform + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Do not use XslTransform. It does not restrict potentially dangerous external references. + +## [CA5375](https://docs.microsoft.com/visualstudio/code-quality/ca5375): Do Not Use Account Shared Access Signature + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5376](https://docs.microsoft.com/visualstudio/code-quality/ca5376): Use SharedAccessProtocol HttpsOnly + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +HTTPS encrypts network traffic. Use HttpsOnly, rather than HttpOrHttps, to ensure network traffic is always encrypted to help prevent disclosure of sensitive data. + +## [CA5377](https://docs.microsoft.com/visualstudio/code-quality/ca5377): Use Container Level Access Policy + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +No access policy identifier is specified, making tokens non-revocable. + +## [CA5378](https://docs.microsoft.com/visualstudio/code-quality/ca5378): Do not disable ServicePointManagerSecurityProtocols + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5379](https://docs.microsoft.com/visualstudio/code-quality/ca5379): Do Not Use Weak Key Derivation Function Algorithm + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5380](https://docs.microsoft.com/visualstudio/code-quality/ca5380): Do Not Add Certificates To Root Store + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5381](https://docs.microsoft.com/visualstudio/code-quality/ca5381): Ensure Certificates Are Not Added To Root Store + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5382](https://docs.microsoft.com/visualstudio/code-quality/ca5382): Use Secure Cookies In ASP.Net Core + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Applications available over HTTPS must use secure cookies. + +## [CA5383](https://docs.microsoft.com/visualstudio/code-quality/ca5383): Ensure Use Secure Cookies In ASP.Net Core + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Applications available over HTTPS must use secure cookies. + +## [CA5384](https://docs.microsoft.com/visualstudio/code-quality/ca5384): Do Not Use Digital Signature Algorithm (DSA) + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +DSA is too weak to use. + +## [CA5385](https://docs.microsoft.com/visualstudio/code-quality/ca5385): Use Rivest–Shamir–Adleman (RSA) Algorithm With Sufficient Key Size + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Encryption algorithms are vulnerable to brute force attacks when too small a key size is used. + +## [CA5386](https://docs.microsoft.com/visualstudio/code-quality/ca5386): Avoid hardcoding SecurityProtocolType value + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Avoid hardcoding SecurityProtocolType {0}, and instead use SecurityProtocolType.SystemDefault to allow the operating system to choose the best Transport Layer Security protocol to use. + +## [CA5387](https://docs.microsoft.com/visualstudio/code-quality/ca5387): Do Not Use Weak Key Derivation Function With Insufficient Iteration Count + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). + +## [CA5388](https://docs.microsoft.com/visualstudio/code-quality/ca5388): Ensure Sufficient Iteration Count When Using Weak Key Derivation Function + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). + +## [CA5389](https://docs.microsoft.com/visualstudio/code-quality/ca5389): Do Not Add Archive Item's Path To The Target File System Path + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5390](https://docs.microsoft.com/visualstudio/code-quality/ca5390): Do not hard-code encryption key + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hard-coded value. + +## [CA5391](https://docs.microsoft.com/visualstudio/code-quality/ca5391): Use antiforgery tokens in ASP.NET Core MVC controllers + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5392](https://docs.microsoft.com/visualstudio/code-quality/ca5392): Use DefaultDllImportSearchPaths attribute for P/Invokes + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5393](https://docs.microsoft.com/visualstudio/code-quality/ca5393): Do not use unsafe DllImportSearchPath value + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5394](https://docs.microsoft.com/visualstudio/code-quality/ca5394): Do not use insecure randomness + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security-sensitive value will be generated. Use a cryptographically strong random number generator if an unpredictable value is required, or ensure that weak pseudo-random numbers aren't used in a security-sensitive manner. + +## [CA5395](https://docs.microsoft.com/visualstudio/code-quality/ca5395): Miss HttpVerb attribute for action methods + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5396](https://docs.microsoft.com/visualstudio/code-quality/ca5396): Set HttpOnly to true for HttpCookie + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5397](https://docs.microsoft.com/visualstudio/code-quality/ca5397): Do not use deprecated SslProtocols values + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5398](https://docs.microsoft.com/visualstudio/code-quality/ca5398): Avoid hardcoded SslProtocols values + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5399](https://docs.microsoft.com/visualstudio/code-quality/ca5399): HttpClients should enable certificate revocation list checks + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5400](https://docs.microsoft.com/visualstudio/code-quality/ca5400): Ensure HttpClient certificate revocation list check is not disabled + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5401](https://docs.microsoft.com/visualstudio/code-quality/ca5401): Do not use CreateEncryptor with non-default IV + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Symmetric encryption should always use a non-repeatable initialization vector to prevent dictionary attacks. + +## [CA5402](https://docs.microsoft.com/visualstudio/code-quality/ca5402): Use CreateEncryptor with the default IV + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Symmetric encryption should always use a non-repeatable initialization vector to prevent dictionary attacks. + +## [CA5403](https://docs.microsoft.com/visualstudio/code-quality/ca5403): Do not hard-code certificate + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Hard-coded certificates in source code are vulnerable to being exploited. + +## [IL3000](https://docs.microsoft.com/visualstudio/code-quality/il3000): Avoid using accessing Assembly file path when publishing as a single-file + +|Item|Value| +|-|-| +|Category|Publish| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +'{0}' always returns an empty string for assemblies embedded in a single-file app. If the path to the app directory is needed, consider calling 'System.AppContext.BaseDirectory'. + +## [IL3001](https://docs.microsoft.com/visualstudio/code-quality/il3001): Avoid using accessing Assembly file path when publishing as a single-file + +|Item|Value| +|-|-| +|Category|Publish| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +'{0}' will throw for assemblies embedded in a single-file app -Rule ID | Title | Category | Enabled | Severity | CodeFix | Description | ---------|-------|----------|---------|----------|---------|--------------------------------------------------------------------------------------------------------------| -[CA1303](https://docs.microsoft.com/visualstudio/code-quality/ca1303) | Do not pass literals as localized parameters | Globalization | True | Warning | False | A method passes a string literal as a parameter to a constructor or method in the .NET Framework class library and that string should be localizable. To fix a violation of this rule, replace the string literal with a string retrieved through an instance of the ResourceManager class. | -[CA1304](https://docs.microsoft.com/visualstudio/code-quality/ca1304) | Specify CultureInfo | Globalization | True | Warning | False | A method or constructor calls a member that has an overload that accepts a System.Globalization.CultureInfo parameter, and the method or constructor does not call the overload that takes the CultureInfo parameter. When a CultureInfo or System.IFormatProvider object is not supplied, the default value that is supplied by the overloaded member might not have the effect that you want in all locales. If the result will be displayed to the user, specify 'CultureInfo.CurrentCulture' as the 'CultureInfo' parameter. Otherwise, if the result will be stored and accessed by software, such as when it is persisted to disk or to a database, specify 'CultureInfo.InvariantCulture'. | -[CA1305](https://docs.microsoft.com/visualstudio/code-quality/ca1305) | Specify IFormatProvider | Globalization | True | Warning | False | A method or constructor calls one or more members that have overloads that accept a System.IFormatProvider parameter, and the method or constructor does not call the overload that takes the IFormatProvider parameter. When a System.Globalization.CultureInfo or IFormatProvider object is not supplied, the default value that is supplied by the overloaded member might not have the effect that you want in all locales. If the result will be based on the input from/output displayed to the user, specify 'CultureInfo.CurrentCulture' as the 'IFormatProvider'. Otherwise, if the result will be stored and accessed by software, such as when it is loaded from disk/database and when it is persisted to disk/database, specify 'CultureInfo.InvariantCulture' | -[CA1307](https://docs.microsoft.com/visualstudio/code-quality/ca1307) | Specify StringComparison | Globalization | True | Warning | False | A string comparison operation uses a method overload that does not set a StringComparison parameter. If the result will be displayed to the user, such as when sorting a list of items for display in a list box, specify 'StringComparison.CurrentCulture' or 'StringComparison.CurrentCultureIgnoreCase' as the 'StringComparison' parameter. If comparing case-insensitive identifiers, such as file paths, environment variables, or registry keys and values, specify 'StringComparison.OrdinalIgnoreCase'. Otherwise, if comparing case-sensitive identifiers, specify 'StringComparison.Ordinal'. | -[CA1308](https://docs.microsoft.com/visualstudio/code-quality/ca1308) | Normalize strings to uppercase | Globalization | True | Warning | False | Strings should be normalized to uppercase. A small group of characters cannot make a round trip when they are converted to lowercase. To make a round trip means to convert the characters from one locale to another locale that represents character data differently, and then to accurately retrieve the original characters from the converted characters. | -[CA1309](https://docs.microsoft.com/visualstudio/code-quality/ca1309) | Use ordinal stringcomparison | Globalization | False | Warning | True | A string comparison operation that is nonlinguistic does not set the StringComparison parameter to either Ordinal or OrdinalIgnoreCase. By explicitly setting the parameter to either StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase, your code often gains speed, becomes more correct, and becomes more reliable. | -[CA1401](https://docs.microsoft.com/visualstudio/code-quality/ca1401) | P/Invokes should not be visible | Interoperability | True | Warning | False | A public or protected method in a public type has the System.Runtime.InteropServices.DllImportAttribute attribute (also implemented by the Declare keyword in Visual Basic). Such methods should not be exposed. | -[CA1810](https://docs.microsoft.com/visualstudio/code-quality/ca1810) | Initialize reference type static fields inline | Performance | True | Warning | False | A reference 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. | -[CA1813](https://docs.microsoft.com/visualstudio/code-quality/ca1813) | Avoid unsealed attributes | Performance | False | Warning | True | The .NET Framework class library provides methods for retrieving custom attributes. By default, these methods search the attribute inheritance hierarchy. Sealing the attribute eliminates the search through the inheritance hierarchy and can improve performance. | -[CA1816](https://docs.microsoft.com/visualstudio/code-quality/ca1816) | Dispose methods should call SuppressFinalize | Usage | True | Warning | False | A method that is an implementation of Dispose does not call GC.SuppressFinalize; or a method that is not an implementation of Dispose calls GC.SuppressFinalize; or a method calls GC.SuppressFinalize and passes something other than this (Me in Visual?Basic). | -[CA1820](https://docs.microsoft.com/visualstudio/code-quality/ca1820) | Test for empty strings using string length | Performance | True | Warning | True | Comparing strings by using the String.Length property or the String.IsNullOrEmpty method is significantly faster than using Equals. | -[CA1824](https://docs.microsoft.com/visualstudio/code-quality/ca1824) | Mark assemblies with NeutralResourcesLanguageAttribute | Performance | True | Warning | False | The NeutralResourcesLanguage attribute informs the ResourceManager of the language that was used to display the resources of a neutral culture for an assembly. This improves lookup performance for the first resource that you load and can reduce your working set. | -[CA1825](https://docs.microsoft.com/visualstudio/code-quality/ca1825) | Avoid zero-length array allocations. | Performance | True | Warning | True | Avoid unnecessary zero-length array allocations. Use {0} instead. | -[CA1826](https://docs.microsoft.com/visualstudio/code-quality/ca1826) | Do not use Enumerable methods on indexable collections. Instead use the collection directly | Performance | True | Warning | True | This collection is directly indexable. Going through LINQ here causes unnecessary allocations and CPU work. | -[CA1827](https://docs.microsoft.com/visualstudio/code-quality/ca1827) | Do not use Count() or LongCount() when Any() can be used | Performance | True | Warning | 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. | -[CA1828](https://docs.microsoft.com/visualstudio/code-quality/ca1828) | Do not use CountAsync() or LongCountAsync() when AnyAsync() can be used | Performance | True | Warning | 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. | -[CA1829](https://docs.microsoft.com/visualstudio/code-quality/ca1829) | Use Length/Count property instead of Count() when available | Performance | True | Warning | True | Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. | -[CA1830](https://docs.microsoft.com/visualstudio/code-quality/ca1830) | Prefer strongly-typed Append and Insert method overloads on StringBuilder. | Performance | True | Warning | True | StringBuilder.Append and StringBuilder.Insert provide overloads for multiple types beyond System.String. When possible, prefer the strongly-typed overloads over using ToString() and the string-based overload. | -[CA1831](https://docs.microsoft.com/visualstudio/code-quality/ca1831) | Use AsSpan or AsMemory instead of Range-based indexers when appropriate | Performance | True | Warning | True | The Range-based indexer on string values produces a copy of requested portion of the string. This copy is usually unnecessary when it is implicitly used as a ReadOnlySpan or ReadOnlyMemory value. Use the AsSpan method to avoid the unnecessary copy. | -[CA1832](https://docs.microsoft.com/visualstudio/code-quality/ca1832) | Use AsSpan or AsMemory instead of Range-based indexers when appropriate | Performance | True | Warning | True | The Range-based indexer on array values produces a copy of requested portion of the array. This copy is usually unnecessary when it is implicitly used as a ReadOnlySpan or ReadOnlyMemory value. Use the AsSpan method to avoid the unnecessary copy. | -[CA1833](https://docs.microsoft.com/visualstudio/code-quality/ca1833) | Use AsSpan or AsMemory instead of Range-based indexers when appropriate | Performance | True | Warning | True | The Range-based indexer on array values produces a copy of requested portion of the array. This copy is often unwanted when it is implicitly used as a Span or Memory value. Use the AsSpan method to avoid the copy. | -[CA1834](https://docs.microsoft.com/visualstudio/code-quality/ca1834) | Consider using 'StringBuilder.Append(char)' when applicable. | Performance | True | Warning | True | 'StringBuilder.Append(char)' is more efficient than 'StringBuilder.Append(string)' when the string is a single character. When calling 'Append' with a constant, prefer using a constant char rather than a constant string containing one character. | -[CA1835](https://docs.microsoft.com/visualstudio/code-quality/ca1835) | Prefer the 'Memory'-based overloads for 'ReadAsync' and 'WriteAsync' | Performance | True | Warning | True | 'Stream' has a 'ReadAsync' overload that takes a 'Memory' as the first argument, and a 'WriteAsync' overload that takes a 'ReadOnlyMemory' as the first argument. Prefer calling the memory based overloads, which are more efficient. | -[CA1836](https://docs.microsoft.com/visualstudio/code-quality/ca1836) | Prefer IsEmpty over Count | Performance | True | Warning | True | For determining whether the object contains or not any items, prefer using 'IsEmpty' property rather than retrieving the number of items from the 'Count' property and comparing it to 0 or 1. | -[CA2000](https://docs.microsoft.com/visualstudio/code-quality/ca2000) | Dispose objects before losing scope | Reliability | True | Warning | 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. | -[CA2002](https://docs.microsoft.com/visualstudio/code-quality/ca2002) | Do not lock on objects with weak identity | Reliability | True | Warning | 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. | -[CA2008](https://docs.microsoft.com/visualstudio/code-quality/ca2008) | Do not create tasks without passing a TaskScheduler | Reliability | True | Warning | 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. | -[CA2009](https://docs.microsoft.com/visualstudio/code-quality/ca2009) | Do not call ToImmutableCollection on an ImmutableCollection value | Reliability | True | Warning | True | Do not call {0} on an {1} value | -[CA2012](https://docs.microsoft.com/visualstudio/code-quality/ca2012) | Use ValueTasks correctly | Reliability | True | Warning | False | ValueTasks returned from member invocations are intended to be directly awaited. Attempts to consume a ValueTask multiple times or to directly access one's result before it's known to be completed may result in an exception or corruption. Ignoring such a ValueTask is likely an indication of a functional bug and may degrade performance. | -[CA2013](https://docs.microsoft.com/visualstudio/code-quality/ca2013) | Do not use ReferenceEquals with value types | Reliability | True | Warning | False | Value type typed arguments are uniquely boxed for each call to this method, therefore the result is always false. | -[CA2014](https://docs.microsoft.com/visualstudio/code-quality/ca2014) | Do not use stackalloc in loops. | Reliability | True | Warning | False | Stack space allocated by a stackalloc is only released at the end of the current method's invocation. Using it in a loop can result in unbounded stack growth and eventual stack overflow conditions. | -[CA2015](https://docs.microsoft.com/visualstudio/code-quality/ca2015) | Do not define finalizers for types derived from MemoryManager | Reliability | True | Warning | False | Adding a finalizer to a type derived from MemoryManager may permit memory to be freed while it is still in use by a Span. | -[CA2016](https://docs.microsoft.com/visualstudio/code-quality/ca2016) | Forward the 'CancellationToken' parameter to methods that take one | Reliability | True | Warning | True | Forward the 'CancellationToken' parameter to methods that take one to ensure the operation cancellation notifications gets properly propagated, or pass in 'CancellationToken.None' explicitly to indicate intentionally not propagating the token. | -[CA2100](https://docs.microsoft.com/visualstudio/code-quality/ca2100) | Review SQL queries for security vulnerabilities | Security | True | Warning | 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. | -[CA2101](https://docs.microsoft.com/visualstudio/code-quality/ca2101) | Specify marshaling for P/Invoke string arguments | Globalization | True | Warning | 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. | -[CA2201](https://docs.microsoft.com/visualstudio/code-quality/ca2201) | Do not raise reserved exception types | Usage | False | Warning | 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. | -[CA2207](https://docs.microsoft.com/visualstudio/code-quality/ca2207) | Initialize value type static fields inline | Usage | True | Warning | 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. | -[CA2208](https://docs.microsoft.com/visualstudio/code-quality/ca2208) | Instantiate argument exceptions correctly | Usage | True | Warning | True | A call is made to the default (parameterless) constructor of an exception type that is or derives from ArgumentException, or an incorrect string argument is passed to a parameterized constructor of an exception type that is or derives from ArgumentException. | -[CA2213](https://docs.microsoft.com/visualstudio/code-quality/ca2213) | Disposable fields should be disposed | Usage | True | Warning | 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. | -[CA2215](https://docs.microsoft.com/visualstudio/code-quality/ca2215) | Dispose methods should call base class dispose | Usage | True | Warning | True | A type that implements System.IDisposable inherits from a type that also implements IDisposable. The Dispose method of the inheriting type does not call the Dispose method of the parent type. To fix a violation of this rule, call base.Dispose in your Dispose method. | -[CA2216](https://docs.microsoft.com/visualstudio/code-quality/ca2216) | Disposable types should declare finalizer | Usage | True | Warning | 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. | -[CA2229](https://docs.microsoft.com/visualstudio/code-quality/ca2229) | Implement serialization constructors | Usage | True | Warning | True | To fix a violation of this rule, implement the serialization constructor. For a sealed class, make the constructor private; otherwise, make it protected. | -[CA2235](https://docs.microsoft.com/visualstudio/code-quality/ca2235) | Mark all non-serializable fields | Usage | True | Warning | True | An instance field of a type that is not serializable is declared in a type that is serializable. | -[CA2237](https://docs.microsoft.com/visualstudio/code-quality/ca2237) | Mark ISerializable types with serializable | Usage | True | Warning | 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. | -[CA2241](https://docs.microsoft.com/visualstudio/code-quality/ca2241) | Provide correct arguments to formatting methods | Usage | True | Warning | 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. | -[CA2242](https://docs.microsoft.com/visualstudio/code-quality/ca2242) | Test for NaN correctly | Usage | True | Warning | True | This expression tests a value against Single.Nan or Double.Nan. Use Single.IsNan(Single) or Double.IsNan(Double) to test the value. | -[CA2243](https://docs.microsoft.com/visualstudio/code-quality/ca2243) | Attribute string literals should parse correctly | Usage | True | Warning | False | The string literal parameter of an attribute does not parse correctly for a URL, a GUID, or a version. | -[CA2247](https://docs.microsoft.com/visualstudio/code-quality/ca2247) | Argument passed to TaskCompletionSource constructor should be TaskCreationOptions enum instead of TaskContinuationOptions enum. | Usage | True | Warning | True | TaskCompletionSource has constructors that take TaskCreationOptions that control the underlying Task, and constructors that take object state that's stored in the task. Accidentally passing a TaskContinuationOptions instead of a TaskCreationOptions will result in the call treating the options as state. | -[CA2248](https://docs.microsoft.com/visualstudio/code-quality/ca2248) | Provide correct 'enum' argument to 'Enum.HasFlag' | Usage | True | Warning | False | 'Enum.HasFlag' method expects the 'enum' argument to be of the same 'enum' type as the instance on which the method is invoked and that this 'enum' is marked with 'System.FlagsAttribute'. If these are different 'enum' types, an unhandled exception will be thrown at runtime. If the 'enum' type is not marked with 'System.FlagsAttribute' the call will always return 'false' at runtime. | -[CA2249](https://docs.microsoft.com/visualstudio/code-quality/ca2249) | Consider using 'string.Contains' instead of 'string.IndexOf' | Usage | True | Warning | True | Calls to 'string.IndexOf' where the result is used to check for the presence/absence of a substring can be replaced by 'string.Contains' | -[CA2300](https://docs.microsoft.com/visualstudio/code-quality/ca2300) | Do not use insecure deserializer BinaryFormatter | Security | False | Warning | 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. | -[CA2301](https://docs.microsoft.com/visualstudio/code-quality/ca2301) | Do not call BinaryFormatter.Deserialize without first setting BinaryFormatter.Binder | Security | False | Warning | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | -[CA2302](https://docs.microsoft.com/visualstudio/code-quality/ca2302) | Ensure BinaryFormatter.Binder is set before calling BinaryFormatter.Deserialize | Security | False | Warning | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | -[CA2305](https://docs.microsoft.com/visualstudio/code-quality/ca2305) | Do not use insecure deserializer LosFormatter | Security | False | Warning | False | The method '{0}' is insecure when deserializing untrusted data. | -[CA2310](https://docs.microsoft.com/visualstudio/code-quality/ca2310) | Do not use insecure deserializer NetDataContractSerializer | Security | False | Warning | 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. | -[CA2311](https://docs.microsoft.com/visualstudio/code-quality/ca2311) | Do not deserialize without first setting NetDataContractSerializer.Binder | Security | False | Warning | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | -[CA2312](https://docs.microsoft.com/visualstudio/code-quality/ca2312) | Ensure NetDataContractSerializer.Binder is set before deserializing | Security | False | Warning | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | -[CA2315](https://docs.microsoft.com/visualstudio/code-quality/ca2315) | Do not use insecure deserializer ObjectStateFormatter | Security | False | Warning | False | The method '{0}' is insecure when deserializing untrusted data. | -[CA2321](https://docs.microsoft.com/visualstudio/code-quality/ca2321) | Do not deserialize with JavaScriptSerializer using a SimpleTypeResolver | Security | False | Warning | 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. | -[CA2322](https://docs.microsoft.com/visualstudio/code-quality/ca2322) | Ensure JavaScriptSerializer is not initialized with SimpleTypeResolver before deserializing | Security | False | Warning | 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. | -[CA2326](https://docs.microsoft.com/visualstudio/code-quality/ca2326) | Do not use TypeNameHandling values other than None | Security | False | Warning | 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. | -[CA2327](https://docs.microsoft.com/visualstudio/code-quality/ca2327) | Do not use insecure JsonSerializerSettings | Security | False | Warning | 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. | -[CA2328](https://docs.microsoft.com/visualstudio/code-quality/ca2328) | Ensure that JsonSerializerSettings are secure | Security | False | Warning | 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. | -[CA2329](https://docs.microsoft.com/visualstudio/code-quality/ca2329) | Do not deserialize with JsonSerializer using an insecure configuration | Security | False | Warning | 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. | -[CA2330](https://docs.microsoft.com/visualstudio/code-quality/ca2330) | Ensure that JsonSerializer has a secure configuration when deserializing | Security | False | Warning | 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. | -[CA2350](https://docs.microsoft.com/visualstudio/code-quality/ca2350) | Do not use insecure deserialization with DataTable.ReadXml() | Security | False | Warning | False | The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. | -[CA2351](https://docs.microsoft.com/visualstudio/code-quality/ca2351) | Do not use insecure deserialization with DataSet.ReadXml() | Security | False | Warning | False | The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. | -[CA2352](https://docs.microsoft.com/visualstudio/code-quality/ca2352) | Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks | Security | False | Warning | False | When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. | -[CA2353](https://docs.microsoft.com/visualstudio/code-quality/ca2353) | Unsafe DataSet or DataTable in serializable type | Security | False | Warning | False | When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. | -[CA2354](https://docs.microsoft.com/visualstudio/code-quality/ca2354) | Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks | Security | False | Warning | False | When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. | -[CA2355](https://docs.microsoft.com/visualstudio/code-quality/ca2355) | Unsafe DataSet or DataTable type found in deserializable object graph | Security | False | Warning | False | When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. | -[CA2356](https://docs.microsoft.com/visualstudio/code-quality/ca2356) | Unsafe DataSet or DataTable type in web deserializable object graph | Security | False | Warning | False | When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. | -[CA3001](https://docs.microsoft.com/visualstudio/code-quality/ca3001) | Review code for SQL injection vulnerabilities | Security | False | Warning | False | Potential SQL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -[CA3002](https://docs.microsoft.com/visualstudio/code-quality/ca3002) | Review code for XSS vulnerabilities | Security | False | Warning | 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}'. | -[CA3003](https://docs.microsoft.com/visualstudio/code-quality/ca3003) | Review code for file path injection vulnerabilities | Security | False | Warning | 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}'. | -[CA3004](https://docs.microsoft.com/visualstudio/code-quality/ca3004) | Review code for information disclosure vulnerabilities | Security | False | Warning | False | Potential information disclosure vulnerability was found where '{0}' in method '{1}' may contain unintended information from '{2}' in method '{3}'. | -[CA3005](https://docs.microsoft.com/visualstudio/code-quality/ca3005) | Review code for LDAP injection vulnerabilities | Security | False | Warning | False | Potential LDAP injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -[CA3006](https://docs.microsoft.com/visualstudio/code-quality/ca3006) | Review code for process command injection vulnerabilities | Security | False | Warning | 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}'. | -[CA3007](https://docs.microsoft.com/visualstudio/code-quality/ca3007) | Review code for open redirect vulnerabilities | Security | False | Warning | False | Potential open redirect vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -[CA3008](https://docs.microsoft.com/visualstudio/code-quality/ca3008) | Review code for XPath injection vulnerabilities | Security | False | Warning | False | Potential XPath injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -[CA3009](https://docs.microsoft.com/visualstudio/code-quality/ca3009) | Review code for XML injection vulnerabilities | Security | False | Warning | False | Potential XML injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -[CA3010](https://docs.microsoft.com/visualstudio/code-quality/ca3010) | Review code for XAML injection vulnerabilities | Security | False | Warning | False | Potential XAML injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -[CA3011](https://docs.microsoft.com/visualstudio/code-quality/ca3011) | Review code for DLL injection vulnerabilities | Security | False | Warning | False | Potential DLL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -[CA3012](https://docs.microsoft.com/visualstudio/code-quality/ca3012) | Review code for regex injection vulnerabilities | Security | False | Warning | False | Potential regex injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -[CA3061](https://docs.microsoft.com/visualstudio/code-quality/ca3061) | Do Not Add Schema By URL | Security | True | Warning | 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. | -[CA5350](https://docs.microsoft.com/visualstudio/code-quality/ca5350) | Do Not Use Weak Cryptographic Algorithms | Security | True | Warning | 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. | -[CA5351](https://docs.microsoft.com/visualstudio/code-quality/ca5351) | Do Not Use Broken Cryptographic Algorithms | Security | True | Warning | 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. | -[CA5358](https://docs.microsoft.com/visualstudio/code-quality/ca5358) | Review cipher mode usage with cryptography experts | Security | False | Warning | False | These cipher modes might be vulnerable to attacks. Consider using recommended modes (CBC, CTS). | -[CA5359](https://docs.microsoft.com/visualstudio/code-quality/ca5359) | Do Not Disable Certificate Validation | Security | True | Warning | 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. | -[CA5360](https://docs.microsoft.com/visualstudio/code-quality/ca5360) | Do Not Call Dangerous Methods In Deserialization | Security | True | Warning | 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. | -[CA5361](https://docs.microsoft.com/visualstudio/code-quality/ca5361) | Do Not Disable SChannel Use of Strong Crypto | Security | False | Warning | 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. | -[CA5362](https://docs.microsoft.com/visualstudio/code-quality/ca5362) | Potential reference cycle in deserialized object graph | Security | False | Warning | False | Review code that processes untrusted deserialized data for handling of unexpected reference cycles. An unexpected reference cycle should not cause the code to enter an infinite loop. Otherwise, an unexpected reference cycle can allow an attacker to DOS or exhaust the memory of the process when deserializing untrusted data. | -[CA5363](https://docs.microsoft.com/visualstudio/code-quality/ca5363) | Do Not Disable Request Validation | Security | True | Warning | 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. | -[CA5364](https://docs.microsoft.com/visualstudio/code-quality/ca5364) | Do Not Use Deprecated Security Protocols | Security | True | Warning | False | Using a deprecated security protocol rather than the system default is risky. | -[CA5365](https://docs.microsoft.com/visualstudio/code-quality/ca5365) | Do Not Disable HTTP Header Checking | Security | True | Warning | 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. | -[CA5366](https://docs.microsoft.com/visualstudio/code-quality/ca5366) | Use XmlReader For DataSet Read Xml | Security | True | Warning | 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. | -[CA5367](https://docs.microsoft.com/visualstudio/code-quality/ca5367) | Do Not Serialize Types With Pointer Fields | Security | False | Warning | 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. | -[CA5368](https://docs.microsoft.com/visualstudio/code-quality/ca5368) | Set ViewStateUserKey For Classes Derived From Page | Security | True | Warning | 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. | -[CA5369](https://docs.microsoft.com/visualstudio/code-quality/ca5369) | Use XmlReader For Deserialize | Security | True | Warning | 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. | -[CA5370](https://docs.microsoft.com/visualstudio/code-quality/ca5370) | Use XmlReader For Validating Reader | Security | True | Warning | 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. | -[CA5371](https://docs.microsoft.com/visualstudio/code-quality/ca5371) | Use XmlReader For Schema Read | Security | True | Warning | 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. | -[CA5372](https://docs.microsoft.com/visualstudio/code-quality/ca5372) | Use XmlReader For XPathDocument | Security | True | Warning | 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. | -[CA5373](https://docs.microsoft.com/visualstudio/code-quality/ca5373) | Do not use obsolete key derivation function | Security | True | Warning | 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. | -[CA5374](https://docs.microsoft.com/visualstudio/code-quality/ca5374) | Do Not Use XslTransform | Security | True | Warning | False | Do not use XslTransform. It does not restrict potentially dangerous external references. | -[CA5375](https://docs.microsoft.com/visualstudio/code-quality/ca5375) | Do Not Use Account Shared Access Signature | Security | False | Warning | 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. | -[CA5376](https://docs.microsoft.com/visualstudio/code-quality/ca5376) | Use SharedAccessProtocol HttpsOnly | Security | False | Warning | False | HTTPS encrypts network traffic. Use HttpsOnly, rather than HttpOrHttps, to ensure network traffic is always encrypted to help prevent disclosure of sensitive data. | -[CA5377](https://docs.microsoft.com/visualstudio/code-quality/ca5377) | Use Container Level Access Policy | Security | False | Warning | False | No access policy identifier is specified, making tokens non-revocable. | -[CA5378](https://docs.microsoft.com/visualstudio/code-quality/ca5378) | Do not disable ServicePointManagerSecurityProtocols | Security | False | Warning | 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. | -[CA5379](https://docs.microsoft.com/visualstudio/code-quality/ca5379) | Do Not Use Weak Key Derivation Function Algorithm | Security | True | Warning | 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. | -[CA5380](https://docs.microsoft.com/visualstudio/code-quality/ca5380) | Do Not Add Certificates To Root Store | Security | False | Warning | 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. | -[CA5381](https://docs.microsoft.com/visualstudio/code-quality/ca5381) | Ensure Certificates Are Not Added To Root Store | Security | False | Warning | 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. | -[CA5382](https://docs.microsoft.com/visualstudio/code-quality/ca5382) | Use Secure Cookies In ASP.Net Core | Security | False | Warning | False | Applications available over HTTPS must use secure cookies. | -[CA5383](https://docs.microsoft.com/visualstudio/code-quality/ca5383) | Ensure Use Secure Cookies In ASP.Net Core | Security | False | Warning | False | Applications available over HTTPS must use secure cookies. | -[CA5384](https://docs.microsoft.com/visualstudio/code-quality/ca5384) | Do Not Use Digital Signature Algorithm (DSA) | Security | True | Warning | False | DSA is too weak to use. | -[CA5385](https://docs.microsoft.com/visualstudio/code-quality/ca5385) | Use Rivest–Shamir–Adleman (RSA) Algorithm With Sufficient Key Size | Security | True | Warning | False | Encryption algorithms are vulnerable to brute force attacks when too small a key size is used. | -[CA5386](https://docs.microsoft.com/visualstudio/code-quality/ca5386) | Avoid hardcoding SecurityProtocolType value | Security | False | Warning | 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. | -[CA5387](https://docs.microsoft.com/visualstudio/code-quality/ca5387) | Do Not Use Weak Key Derivation Function With Insufficient Iteration Count | Security | False | Warning | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | -[CA5388](https://docs.microsoft.com/visualstudio/code-quality/ca5388) | Ensure Sufficient Iteration Count When Using Weak Key Derivation Function | Security | False | Warning | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | -[CA5389](https://docs.microsoft.com/visualstudio/code-quality/ca5389) | Do Not Add Archive Item's Path To The Target File System Path | Security | False | Warning | 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. | -[CA5390](https://docs.microsoft.com/visualstudio/code-quality/ca5390) | Do not hard-code encryption key | Security | False | Warning | False | SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hard-coded value. | -[CA5391](https://docs.microsoft.com/visualstudio/code-quality/ca5391) | Use antiforgery tokens in ASP.NET Core MVC controllers | Security | False | Warning | 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. | -[CA5392](https://docs.microsoft.com/visualstudio/code-quality/ca5392) | Use DefaultDllImportSearchPaths attribute for P/Invokes | Security | False | Warning | 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. | -[CA5393](https://docs.microsoft.com/visualstudio/code-quality/ca5393) | Do not use unsafe DllImportSearchPath value | Security | False | Warning | 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. | -[CA5394](https://docs.microsoft.com/visualstudio/code-quality/ca5394) | Do not use insecure randomness | Security | False | Warning | False | Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security-sensitive value will be generated. Use a cryptographically strong random number generator if an unpredictable value is required, or ensure that weak pseudo-random numbers aren't used in a security-sensitive manner. | -[CA5395](https://docs.microsoft.com/visualstudio/code-quality/ca5395) | Miss HttpVerb attribute for action methods | Security | False | Warning | 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. | -[CA5396](https://docs.microsoft.com/visualstudio/code-quality/ca5396) | Set HttpOnly to true for HttpCookie | Security | False | Warning | 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. | -[CA5397](https://docs.microsoft.com/visualstudio/code-quality/ca5397) | Do not use deprecated SslProtocols values | Security | True | Warning | 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. | -[CA5398](https://docs.microsoft.com/visualstudio/code-quality/ca5398) | Avoid hardcoded SslProtocols values | Security | False | Warning | 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. | -[CA5399](https://docs.microsoft.com/visualstudio/code-quality/ca5399) | HttpClients should enable certificate revocation list checks | Security | False | Warning | 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. | -[CA5400](https://docs.microsoft.com/visualstudio/code-quality/ca5400) | Ensure HttpClient certificate revocation list check is not disabled | Security | False | Warning | 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. | -[CA5401](https://docs.microsoft.com/visualstudio/code-quality/ca5401) | Do not use CreateEncryptor with non-default IV | Security | False | Warning | False | Symmetric encryption should always use a non-repeatable initialization vector to prevent dictionary attacks. | -[CA5402](https://docs.microsoft.com/visualstudio/code-quality/ca5402) | Use CreateEncryptor with the default IV | Security | False | Warning | False | Symmetric encryption should always use a non-repeatable initialization vector to prevent dictionary attacks. | -[CA5403](https://docs.microsoft.com/visualstudio/code-quality/ca5403) | Do not hard-code certificate | Security | False | Warning | False | Hard-coded certificates in source code are vulnerable to being exploited. | diff --git a/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.sarif b/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.sarif index 924a6ee7e7..0a04ae7e56 100644 --- a/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.sarif +++ b/src/Microsoft.NetCore.Analyzers/Microsoft.NetCore.Analyzers.sarif @@ -53,7 +53,7 @@ "CA1305": { "id": "CA1305", "shortDescription": "Specify IFormatProvider", - "fullDescription": "A method or constructor calls one or more members that have overloads that accept a System.IFormatProvider parameter, and the method or constructor does not call the overload that takes the IFormatProvider parameter. When a System.Globalization.CultureInfo or IFormatProvider object is not supplied, the default value that is supplied by the overloaded member might not have the effect that you want in all locales. If the result will be based on the input from/output displayed to the user, specify 'CultureInfo.CurrentCulture' as the 'IFormatProvider'. Otherwise, if the result will be stored and accessed by software, such as when it is loaded from disk/database and when it is persisted to disk/database, specify 'CultureInfo.InvariantCulture'", + "fullDescription": "A method or constructor calls one or more members that have overloads that accept a System.IFormatProvider parameter, and the method or constructor does not call the overload that takes the IFormatProvider parameter. When a System.Globalization.CultureInfo or IFormatProvider object is not supplied, the default value that is supplied by the overloaded member might not have the effect that you want in all locales. If the result will be based on the input from/output displayed to the user, specify 'CultureInfo.CurrentCulture' as the 'IFormatProvider'. Otherwise, if the result will be stored and accessed by software, such as when it is loaded from disk/database and when it is persisted to disk/database, specify 'CultureInfo.InvariantCulture'.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1305", "properties": { @@ -130,6 +130,25 @@ ] } }, + "CA1417": { + "id": "CA1417", + "shortDescription": "Do not use 'OutAttribute' on string parameters for P/Invokes", + "fullDescription": "String parameters passed by value with the 'OutAttribute' can destabilize the runtime if the string is an interned string.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1417", + "properties": { + "category": "Interoperability", + "isEnabledByDefault": true, + "typeName": "DoNotUseOutAttributeStringPInvokeParametersAnalyzer", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, "CA1810": { "id": "CA1810", "shortDescription": "Initialize reference type static fields inline", @@ -211,7 +230,7 @@ }, "CA1826": { "id": "CA1826", - "shortDescription": "Do not use Enumerable methods on indexable collections. Instead use the collection directly", + "shortDescription": "Do not use Enumerable methods on indexable collections", "fullDescription": "This collection is directly indexable. Going through LINQ here causes unnecessary allocations and CPU work.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1826", @@ -287,7 +306,7 @@ }, "CA1830": { "id": "CA1830", - "shortDescription": "Prefer strongly-typed Append and Insert method overloads on StringBuilder.", + "shortDescription": "Prefer strongly-typed Append and Insert method overloads on StringBuilder", "fullDescription": "StringBuilder.Append and StringBuilder.Insert provide overloads for multiple types beyond System.String. When possible, prefer the strongly-typed overloads over using ToString() and the string-based overload.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1830", @@ -363,7 +382,7 @@ }, "CA1834": { "id": "CA1834", - "shortDescription": "Consider using 'StringBuilder.Append(char)' when applicable.", + "shortDescription": "Consider using 'StringBuilder.Append(char)' when applicable", "fullDescription": "'StringBuilder.Append(char)' is more efficient than 'StringBuilder.Append(string)' when the string is a single character. When calling 'Append' with a constant, prefer using a constant char rather than a constant string containing one character.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1834", @@ -418,6 +437,44 @@ ] } }, + "CA1837": { + "id": "CA1837", + "shortDescription": "Use 'Environment.ProcessId'", + "fullDescription": "'Environment.ProcessId' is simpler and faster than 'Process.GetCurrentProcess().Id'.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1837", + "properties": { + "category": "Performance", + "isEnabledByDefault": true, + "typeName": "UseEnvironmentProcessId", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, + "CA1838": { + "id": "CA1838", + "shortDescription": "Avoid 'StringBuilder' parameters for P/Invokes", + "fullDescription": "Marshalling of 'StringBuilder' always creates a native buffer copy, resulting in multiple allocations for one marshalling operation.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1838", + "properties": { + "category": "Performance", + "isEnabledByDefault": false, + "typeName": "AvoidStringBuilderPInvokeParametersAnalyzer", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, "CA2000": { "id": "CA2000", "shortDescription": "Dispose objects before losing scope", @@ -537,7 +594,7 @@ }, "CA2014": { "id": "CA2014", - "shortDescription": "Do not use stackalloc in loops.", + "shortDescription": "Do not use stackalloc in loops", "fullDescription": "Stack space allocated by a stackalloc is only released at the end of the current method's invocation. Using it in a loop can result in unbounded stack growth and eventual stack overflow conditions.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2014", @@ -856,7 +913,7 @@ }, "CA2247": { "id": "CA2247", - "shortDescription": "Argument passed to TaskCompletionSource constructor should be TaskCreationOptions enum instead of TaskContinuationOptions enum.", + "shortDescription": "Argument passed to TaskCompletionSource constructor should be TaskCreationOptions enum instead of TaskContinuationOptions enum", "fullDescription": "TaskCompletionSource has constructors that take TaskCreationOptions that control the underlying Task, and constructors that take object state that's stored in the task. Accidentally passing a TaskContinuationOptions instead of a TaskCreationOptions will result in the call treating the options as state.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2247", @@ -895,7 +952,7 @@ "CA2249": { "id": "CA2249", "shortDescription": "Consider using 'string.Contains' instead of 'string.IndexOf'", - "fullDescription": "Calls to 'string.IndexOf' where the result is used to check for the presence/absence of a substring can be replaced by 'string.Contains'", + "fullDescription": "Calls to 'string.IndexOf' where the result is used to check for the presence/absence of a substring can be replaced by 'string.Contains'.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2249", "properties": { @@ -1208,8 +1265,8 @@ }, "CA2350": { "id": "CA2350", - "shortDescription": "Do not use insecure deserialization with DataTable.ReadXml()", - "fullDescription": "The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD.", + "shortDescription": "Do not use DataTable.ReadXml() with untrusted data", + "fullDescription": "The method '{0}' is insecure when deserializing untrusted data", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2350", "properties": { @@ -1227,8 +1284,8 @@ }, "CA2351": { "id": "CA2351", - "shortDescription": "Do not use insecure deserialization with DataSet.ReadXml()", - "fullDescription": "The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD.", + "shortDescription": "Do not use DataSet.ReadXml() with untrusted data", + "fullDescription": "The method '{0}' is insecure when deserializing untrusted data", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2351", "properties": { @@ -1266,7 +1323,7 @@ "CA2353": { "id": "CA2353", "shortDescription": "Unsafe DataSet or DataTable in serializable type", - "fullDescription": "When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}.", + "fullDescription": "When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2353", "properties": { @@ -1285,7 +1342,7 @@ "CA2354": { "id": "CA2354", "shortDescription": "Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks", - "fullDescription": "When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}.", + "fullDescription": "When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2354", "properties": { @@ -1304,7 +1361,7 @@ "CA2355": { "id": "CA2355", "shortDescription": "Unsafe DataSet or DataTable type found in deserializable object graph", - "fullDescription": "When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}.", + "fullDescription": "When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2355", "properties": { @@ -1323,7 +1380,7 @@ "CA2356": { "id": "CA2356", "shortDescription": "Unsafe DataSet or DataTable type in web deserializable object graph", - "fullDescription": "When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}.", + "fullDescription": "When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2356", "properties": { @@ -1339,6 +1396,44 @@ ] } }, + "CA2361": { + "id": "CA2361", + "shortDescription": "Ensure autogenerated class containing DataSet.ReadXml() is not used with untrusted data", + "fullDescription": "The method '{0}' is insecure when deserializing untrusted data. Make sure that autogenerated class containing the '{0}' call is not deserialized with untrusted data.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2361", + "properties": { + "category": "Security", + "isEnabledByDefault": false, + "typeName": "DoNotUseDataSetReadXml", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, + "CA2362": { + "id": "CA2362", + "shortDescription": "Unsafe DataSet or DataTable in autogenerated serializable type can be vulnerable to remote code execution attacks", + "fullDescription": "When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. Ensure that the autogenerated type is never deserialized with untrusted data.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2362", + "properties": { + "category": "Security", + "isEnabledByDefault": false, + "typeName": "DataSetDataTableInSerializableTypeAnalyzer", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, "CA3001": { "id": "CA3001", "shortDescription": "Review code for SQL injection vulnerabilities", @@ -2527,6 +2622,44 @@ "Telemetry" ] } + }, + "IL3000": { + "id": "IL3000", + "shortDescription": "Avoid using accessing Assembly file path when publishing as a single-file", + "fullDescription": "'{0}' always returns an empty string for assemblies embedded in a single-file app. If the path to the app directory is needed, consider calling 'System.AppContext.BaseDirectory'.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/il3000", + "properties": { + "category": "Publish", + "isEnabledByDefault": true, + "typeName": "AvoidAssemblyLocationInSingleFile", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, + "IL3001": { + "id": "IL3001", + "shortDescription": "Avoid using accessing Assembly file path when publishing as a single-file", + "fullDescription": "'{0}' will throw for assemblies embedded in a single-file app", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/il3001", + "properties": { + "category": "Publish", + "isEnabledByDefault": true, + "typeName": "AvoidAssemblyLocationInSingleFile", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } } } }, @@ -2577,7 +2710,7 @@ }, "CA1825": { "id": "CA1825", - "shortDescription": "Avoid zero-length array allocations.", + "shortDescription": "Avoid zero-length array allocations", "fullDescription": "Avoid unnecessary zero-length array allocations. Use {0} instead.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1825", @@ -2660,7 +2793,7 @@ }, "CA1825": { "id": "CA1825", - "shortDescription": "Avoid zero-length array allocations.", + "shortDescription": "Avoid zero-length array allocations", "fullDescription": "Avoid unnecessary zero-length array allocations. Use {0} instead.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1825", diff --git a/src/Microsoft.NetCore.Analyzers/RulesMissingDocumentation.md b/src/Microsoft.NetCore.Analyzers/RulesMissingDocumentation.md index 47899334e7..097a53f2ef 100644 --- a/src/Microsoft.NetCore.Analyzers/RulesMissingDocumentation.md +++ b/src/Microsoft.NetCore.Analyzers/RulesMissingDocumentation.md @@ -2,15 +2,12 @@ Rule ID | Missing Help Link | Title | --------|-------------------|-------| -CA1830 | https://docs.microsoft.com/visualstudio/code-quality/ca1830 | Prefer strongly-typed Append and Insert method overloads on StringBuilder. | -CA1831 | https://docs.microsoft.com/visualstudio/code-quality/ca1831 | Use AsSpan or AsMemory instead of Range-based indexers when appropriate | -CA1832 | https://docs.microsoft.com/visualstudio/code-quality/ca1832 | Use AsSpan or AsMemory instead of Range-based indexers when appropriate | -CA1833 | https://docs.microsoft.com/visualstudio/code-quality/ca1833 | Use AsSpan or AsMemory instead of Range-based indexers when appropriate | -CA1834 | https://docs.microsoft.com/visualstudio/code-quality/ca1834 | Consider using 'StringBuilder.Append(char)' when applicable. | -CA1835 | https://docs.microsoft.com/visualstudio/code-quality/ca1835 | Prefer the 'Memory'-based overloads for 'ReadAsync' and 'WriteAsync'. | -CA1836 | https://docs.microsoft.com/visualstudio/code-quality/ca1836 | Prefer IsEmpty over Count | +CA1834 | https://docs.microsoft.com/visualstudio/code-quality/ca1834 | Consider using 'StringBuilder.Append(char)' when applicable | +CA1837 | https://docs.microsoft.com/visualstudio/code-quality/ca1837 | Use 'Environment.ProcessId' | +CA1838 | https://docs.microsoft.com/visualstudio/code-quality/ca1838 | Avoid 'StringBuilder' parameters for P/Invokes | CA2008 | https://docs.microsoft.com/visualstudio/code-quality/ca2008 | Do not create tasks without passing a TaskScheduler | -CA2012 | https://docs.microsoft.com/visualstudio/code-quality/ca2012 | Use ValueTasks correctly | -CA2014 | https://docs.microsoft.com/visualstudio/code-quality/ca2014 | Do not use stackalloc in loops. | -CA2247 | https://docs.microsoft.com/visualstudio/code-quality/ca2247 | Argument passed to TaskCompletionSource constructor should be TaskCreationOptions enum instead of TaskContinuationOptions enum. | CA2249 | https://docs.microsoft.com/visualstudio/code-quality/ca2249 | Consider using 'string.Contains' instead of 'string.IndexOf' | +CA2361 | https://docs.microsoft.com/visualstudio/code-quality/ca2361 | Ensure autogenerated class containing DataSet.ReadXml() is not used with untrusted data | +CA2362 | https://docs.microsoft.com/visualstudio/code-quality/ca2362 | Unsafe DataSet or DataTable in autogenerated serializable type can be vulnerable to remote code execution attacks | +IL3000 | https://docs.microsoft.com/visualstudio/code-quality/il3000 | Avoid using accessing Assembly file path when publishing as a single-file | +IL3001 | https://docs.microsoft.com/visualstudio/code-quality/il3001 | Avoid using accessing Assembly file path when publishing as a single-file | diff --git a/src/Microsoft.NetFramework.Analyzers/Microsoft.NetFramework.Analyzers.md b/src/Microsoft.NetFramework.Analyzers/Microsoft.NetFramework.Analyzers.md index 0897e1d6c4..884efe6d34 100644 --- a/src/Microsoft.NetFramework.Analyzers/Microsoft.NetFramework.Analyzers.md +++ b/src/Microsoft.NetFramework.Analyzers/Microsoft.NetFramework.Analyzers.md @@ -1,9 +1,80 @@ +# Microsoft.NetFramework.Analyzers + +## [CA1058](https://docs.microsoft.com/visualstudio/code-quality/ca1058): Types should not extend certain base types + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +An externally visible type extends certain base types. Use one of the alternatives. + +## [CA2153](https://docs.microsoft.com/visualstudio/code-quality/ca2153): Do Not Catch Corrupted State Exceptions + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA3075](https://docs.microsoft.com/visualstudio/code-quality/ca3075): Insecure DTD processing in XML + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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.  + +## [CA3076](https://docs.microsoft.com/visualstudio/code-quality/ca3076): Insecure XSLT script processing. + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA3077](https://docs.microsoft.com/visualstudio/code-quality/ca3077): Insecure Processing in API Design, XmlDocument and XmlTextReader + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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.  + +## [CA3147](https://docs.microsoft.com/visualstudio/code-quality/ca3147): Mark Verb Handlers With Validate Antiforgery Token + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Missing ValidateAntiForgeryTokenAttribute on controller action {0} -Rule ID | Title | Category | Enabled | Severity | CodeFix | Description | ---------|-------|----------|---------|----------|---------|--------------------------------------------------------------------------------------------------------------| -[CA1058](https://docs.microsoft.com/visualstudio/code-quality/ca1058) | Types should not extend certain base types | Design | True | Warning | False | An externally visible type extends certain base types. Use one of the alternatives. | -[CA2153](https://docs.microsoft.com/visualstudio/code-quality/ca2153) | Do Not Catch Corrupted State Exceptions | Security | True | Warning | 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 | -[CA3075](https://docs.microsoft.com/visualstudio/code-quality/ca3075) | Insecure DTD processing in XML | Security | True | Warning | 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.  | -[CA3076](https://docs.microsoft.com/visualstudio/code-quality/ca3076) | Insecure XSLT script processing. | Security | True | Warning | 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. | -[CA3077](https://docs.microsoft.com/visualstudio/code-quality/ca3077) | Insecure Processing in API Design, XmlDocument and XmlTextReader | Security | True | Warning | 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.  | -[CA3147](https://docs.microsoft.com/visualstudio/code-quality/ca3147) | Mark Verb Handlers With Validate Antiforgery Token | Security | True | Warning | False | Missing ValidateAntiForgeryTokenAttribute on controller action {0}. | diff --git a/src/Microsoft.NetFramework.Analyzers/Microsoft.NetFramework.Analyzers.sarif b/src/Microsoft.NetFramework.Analyzers/Microsoft.NetFramework.Analyzers.sarif index 16b62a4ab6..82b10f81ed 100644 --- a/src/Microsoft.NetFramework.Analyzers/Microsoft.NetFramework.Analyzers.sarif +++ b/src/Microsoft.NetFramework.Analyzers/Microsoft.NetFramework.Analyzers.sarif @@ -32,7 +32,7 @@ "CA2153": { "id": "CA2153", "shortDescription": "Do Not Catch Corrupted State Exceptions", - "fullDescription": "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", + "fullDescription": "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.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2153", "properties": { @@ -70,7 +70,7 @@ "CA3147": { "id": "CA3147", "shortDescription": "Mark Verb Handlers With Validate Antiforgery Token", - "fullDescription": "Missing ValidateAntiForgeryTokenAttribute on controller action {0}.", + "fullDescription": "Missing ValidateAntiForgeryTokenAttribute on controller action {0}", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca3147", "properties": { diff --git a/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/UsePropertiesWhereAppropriate.cs b/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/UsePropertiesWhereAppropriate.cs index 8aab7ef31e..972602ce61 100644 --- a/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/UsePropertiesWhereAppropriate.cs +++ b/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/UsePropertiesWhereAppropriate.cs @@ -42,47 +42,63 @@ public override void Initialize(AnalysisContext analysisContext) analysisContext.EnableConcurrentExecution(); analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); - analysisContext.RegisterOperationBlockStartAction(context => + analysisContext.RegisterCompilationStartAction(context => { + var taskTypesBuilder = ImmutableHashSet.CreateBuilder(); - if (!(context.OwningSymbol is IMethodSymbol methodSymbol) || - methodSymbol.ReturnsVoid || - methodSymbol.ReturnType.Kind == SymbolKind.ArrayType || - !methodSymbol.Parameters.IsEmpty || - !methodSymbol.MatchesConfiguredVisibility(context.Options, Rule, context.Compilation, context.CancellationToken) || - methodSymbol.IsAccessorMethod() || - !IsPropertyLikeName(methodSymbol.Name)) - { - return; - } + taskTypesBuilder.AddIfNotNull( + context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksTask)); + taskTypesBuilder.AddIfNotNull( + context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksTask1)); + taskTypesBuilder.AddIfNotNull( + context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksValueTask)); + taskTypesBuilder.AddIfNotNull( + context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksValueTask1)); - // A few additional checks to reduce the noise for this diagnostic: - // Ensure that the method is non-generic, non-virtual/override, has no overloads and doesn't have special names: 'GetHashCode' or 'GetEnumerator'. - // Also avoid generating this diagnostic if the method body has any invocation expressions. - // Also avoid implicit interface implementation (explicit are handled through the member accessibility) - if (methodSymbol.IsGenericMethod || - methodSymbol.IsVirtual || - methodSymbol.IsOverride || - methodSymbol.ContainingType.GetMembers(methodSymbol.Name).Length > 1 || - methodSymbol.Name == GetHashCodeName || - methodSymbol.Name == GetEnumeratorName || - methodSymbol.IsImplementationOfAnyImplicitInterfaceMember()) - { - return; - } + var taskTypes = taskTypesBuilder.ToImmutable(); - bool hasInvocations = false; - context.RegisterOperationAction(operationContext => + context.RegisterOperationBlockStartAction(context => { - hasInvocations = true; - }, OperationKind.Invocation); + if (!(context.OwningSymbol is IMethodSymbol methodSymbol) || + methodSymbol.ReturnsVoid || + methodSymbol.ReturnType.Kind == SymbolKind.ArrayType || + !methodSymbol.Parameters.IsEmpty || + !methodSymbol.MatchesConfiguredVisibility(context.Options, Rule, context.Compilation, context.CancellationToken) || + methodSymbol.IsAccessorMethod() || + !IsPropertyLikeName(methodSymbol.Name)) + { + return; + } - context.RegisterOperationBlockEndAction(endContext => - { - if (!hasInvocations) + // A few additional checks to reduce the noise for this diagnostic: + // Ensure that the method is non-generic, non-virtual/override, has no overloads and doesn't have special names: 'GetHashCode' or 'GetEnumerator'. + // Also avoid generating this diagnostic if the method body has any invocation expressions. + // Also avoid implicit interface implementation (explicit are handled through the member accessibility) + if (methodSymbol.IsGenericMethod || + methodSymbol.IsVirtual || + methodSymbol.IsOverride || + methodSymbol.Name == GetHashCodeName || + methodSymbol.Name == GetEnumeratorName || + methodSymbol.ContainingType.GetMembers(methodSymbol.Name).Length > 1 || + taskTypes.Contains(methodSymbol.ReturnType.OriginalDefinition) || + methodSymbol.IsImplementationOfAnyImplicitInterfaceMember()) { - endContext.ReportDiagnostic(endContext.OwningSymbol.CreateDiagnostic(Rule)); + return; } + + bool hasInvocations = false; + context.RegisterOperationAction(operationContext => + { + hasInvocations = true; + }, OperationKind.Invocation); + + context.RegisterOperationBlockEndAction(endContext => + { + if (!hasInvocations) + { + endContext.ReportDiagnostic(endContext.OwningSymbol.CreateDiagnostic(Rule)); + } + }); }); }); } diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/InteropServices/RuntimePlatformCheckAnalyzer.OperationVisitor.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/InteropServices/RuntimePlatformCheckAnalyzer.OperationVisitor.cs index 55dbc5a6ce..08b1b0b6dd 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/InteropServices/RuntimePlatformCheckAnalyzer.OperationVisitor.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/InteropServices/RuntimePlatformCheckAnalyzer.OperationVisitor.cs @@ -37,7 +37,7 @@ private sealed class OperationVisitor : GlobalFlowStateDataFlowOperationVisitor if (_platformCheckMethods.Contains(method.OriginalDefinition) && !visitedArguments.IsEmpty) { - return RuntimeOSPlatformInfo.TryDecode(method, visitedArguments, DataFlowAnalysisContext.ValueContentAnalysisResultOpt, _osPlatformType, out var platformInfo) ? + return RuntimeOSPlatformInfo.TryDecode(method, visitedArguments, DataFlowAnalysisContext.ValueContentAnalysisResult, _osPlatformType, out var platformInfo) ? new GlobalFlowStateAnalysisValueSet(platformInfo) : GlobalFlowStateAnalysisValueSet.Unknown; } diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/UseCountProperly.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/UseCountProperly.cs index 7f65ce5522..a54170cc45 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/UseCountProperly.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/UseCountProperly.cs @@ -153,33 +153,36 @@ private static void OnCompilationStart(CompilationStartAnalysisContext context) methods = namedType?.GetMembers(LongCountAsync).OfType().Where(m => m.Parameters.Length <= 2); AddIfNotNull(asyncMethods, methods); - // Disallowed types that shouldn't report a diagnosis given that there is no proven benefit on doing so. - ImmutableHashSet.Builder disallowedTypesBuilder = ImmutableHashSet.CreateBuilder(); + // Allowed types that should report a CA1836 diagnosis given that there is proven benefit on doing so. + ImmutableHashSet.Builder allowedTypesBuilder = ImmutableHashSet.CreateBuilder(); - namedType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemMemory1); - disallowedTypesBuilder.AddIfNotNull(namedType); + namedType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsConcurrentConcurrentBag1); + allowedTypesBuilder.AddIfNotNull(namedType); - namedType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemSpan1); - disallowedTypesBuilder.AddIfNotNull(namedType); + namedType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsConcurrentConcurrentDictionary2); + allowedTypesBuilder.AddIfNotNull(namedType); - namedType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemReadOnlyMemory1); - disallowedTypesBuilder.AddIfNotNull(namedType); + namedType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsConcurrentConcurrentQueue1); + allowedTypesBuilder.AddIfNotNull(namedType); - namedType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemReadOnlySpan1); - disallowedTypesBuilder.AddIfNotNull(namedType); + namedType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsConcurrentConcurrentStack1); + allowedTypesBuilder.AddIfNotNull(namedType); - ImmutableHashSet disallowedTypesForCA1836 = disallowedTypesBuilder.ToImmutable(); + ImmutableHashSet allowedTypesForCA1836 = allowedTypesBuilder.ToImmutable(); if (syncMethods.Count > 0 || asyncMethods.Count > 0) { context.RegisterOperationAction(operationContext => AnalyzeInvocationOperation( - operationContext, syncMethods.ToImmutable(), asyncMethods.ToImmutable(), disallowedTypesForCA1836), + operationContext, syncMethods.ToImmutable(), asyncMethods.ToImmutable(), allowedTypesForCA1836), OperationKind.Invocation); } - context.RegisterOperationAction(operationContext => AnalyzePropertyReference( - operationContext, disallowedTypesForCA1836), - OperationKind.PropertyReference); + if (!allowedTypesForCA1836.IsEmpty) + { + context.RegisterOperationAction(operationContext => AnalyzePropertyReference( + operationContext, allowedTypesForCA1836), + OperationKind.PropertyReference); + } static void AddIfNotNull(ImmutableHashSet.Builder set, IEnumerable? others) { @@ -194,7 +197,7 @@ static void AddIfNotNull(ImmutableHashSet.Builder set, IEnumerabl OperationAnalysisContext context, ImmutableHashSet syncMethods, ImmutableHashSet asyncMethods, - ImmutableHashSet disallowedTypesForCA1836) + ImmutableHashSet allowedTypesForCA1836) { var invocationOperation = (IInvocationOperation)context.Operation; @@ -236,10 +239,10 @@ static void AddIfNotNull(ImmutableHashSet.Builder set, IEnumerabl bool shouldReplaceParent = ShouldReplaceParent(ref parentOperation, out string? operationKey, out bool shouldNegateIsEmpty); DetermineReportForInvocationAnalysis(context, invocationOperation, parentOperation, - shouldReplaceParent, isAsync, shouldNegateIsEmpty, hasPredicate, originalDefinition.Name, operationKey, disallowedTypesForCA1836); + shouldReplaceParent, isAsync, shouldNegateIsEmpty, hasPredicate, originalDefinition.Name, operationKey, allowedTypesForCA1836); } - private static void AnalyzePropertyReference(OperationAnalysisContext context, ImmutableHashSet disallowedTypesForCA1836) + private static void AnalyzePropertyReference(OperationAnalysisContext context, ImmutableHashSet allowedTypesForCA1836) { var propertyReferenceOperation = (IPropertyReferenceOperation)context.Operation; @@ -259,7 +262,7 @@ private static void AnalyzePropertyReference(OperationAnalysisContext context, I if (shouldReplaceParent) { DetermineReportForPropertyReference(context, propertyReferenceOperation, parentOperation, - operationKey, shouldNegateIsEmpty, disallowedTypesForCA1836); + operationKey, shouldNegateIsEmpty, allowedTypesForCA1836); } } @@ -409,7 +412,7 @@ private static void ReportCA1836(OperationAnalysisContext context, string operat OperationAnalysisContext context, IInvocationOperation invocationOperation, IOperation parent, bool shouldReplaceParent, bool isAsync, bool shouldNegateIsEmpty, bool hasPredicate, string methodName, string? operationKey, - ImmutableHashSet disallowedTypesForCA1836) + ImmutableHashSet allowedTypesForCA1836) { if (!shouldReplaceParent) { @@ -438,7 +441,7 @@ private static void ReportCA1836(OperationAnalysisContext context, string operat } else { - if (!disallowedTypesForCA1836.Contains(type.OriginalDefinition) && + if (allowedTypesForCA1836.Contains(type.OriginalDefinition) && TypeContainsVisibleProperty(context, type, IsEmpty, SpecialType.System_Boolean, out ISymbol? isEmptyPropertySymbol) && !IsPropertyGetOfIsEmptyUsingThisInstance(context, invocationOperation, isEmptyPropertySymbol!)) { @@ -465,12 +468,12 @@ private static void ReportCA1836(OperationAnalysisContext context, string operat private static void DetermineReportForPropertyReference( OperationAnalysisContext context, IOperation operation, IOperation parent, string? operationKey, bool shouldNegateIsEmpty, - ImmutableHashSet disallowedTypesForCA1836) + ImmutableHashSet allowedTypesForCA1836) { ITypeSymbol? type = operation.GetInstanceType(); if (type != null) { - if (!disallowedTypesForCA1836.Contains(type.OriginalDefinition) && + if (allowedTypesForCA1836.Contains(type.OriginalDefinition) && TypeContainsVisibleProperty(context, type, IsEmpty, SpecialType.System_Boolean, out ISymbol? isEmptyPropertySymbol) && !IsPropertyGetOfIsEmptyUsingThisInstance(context, operation, isEmptyPropertySymbol!)) { diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/DisposeObjectsBeforeLosingScope.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/DisposeObjectsBeforeLosingScope.cs index 68820b2b16..cd449c2383 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/DisposeObjectsBeforeLosingScope.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/DisposeObjectsBeforeLosingScope.cs @@ -120,13 +120,13 @@ public override void Initialize(AnalysisContext context) if (trackExceptionPaths) { // Compute diagnostics for undisposed objects at handled exception exit paths. - var disposeDataAtHandledExceptionPaths = disposeAnalysisResult.ExceptionPathsExitBlockOutputOpt!.Data; + var disposeDataAtHandledExceptionPaths = disposeAnalysisResult.ExceptionPathsExitBlockOutput!.Data; ComputeDiagnostics(disposeDataAtHandledExceptionPaths, notDisposedDiagnostics, mayBeNotDisposedDiagnostics, disposeAnalysisResult, pointsToAnalysisResult, disposeAnalysisKind, isDisposeDataForExceptionPaths: true); // Compute diagnostics for undisposed objects at unhandled exception exit paths, if any. - var disposeDataAtUnhandledExceptionPaths = disposeAnalysisResult.MergedStateForUnhandledThrowOperationsOpt?.Data; + var disposeDataAtUnhandledExceptionPaths = disposeAnalysisResult.MergedStateForUnhandledThrowOperations?.Data; if (disposeDataAtUnhandledExceptionPaths != null) { ComputeDiagnostics(disposeDataAtUnhandledExceptionPaths, @@ -207,7 +207,7 @@ bool CanBeDisposable(ITypeSymbol type) AbstractLocation location = kvp.Key; DisposeAbstractValue disposeValue = kvp.Value; if (disposeValue.Kind == DisposeAbstractValueKind.NotDisposable || - location.CreationOpt == null) + location.Creation == null) { continue; } diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotUseInsecureDeserializerJavascriptSerializerWithSimpleTypeResolver.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotUseInsecureDeserializerJavascriptSerializerWithSimpleTypeResolver.cs index 7314303e8a..ba25caf3e5 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotUseInsecureDeserializerJavascriptSerializerWithSimpleTypeResolver.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/DoNotUseInsecureDeserializerJavascriptSerializerWithSimpleTypeResolver.cs @@ -106,14 +106,14 @@ public override void Initialize(AnalysisContext context) break; case PointsToAbstractValueKind.KnownLocations: - if (pointsTo.Locations.Any(l => !l.IsNull && simpleTypeResolverSymbol.Equals(l.LocationTypeOpt))) + if (pointsTo.Locations.Any(l => !l.IsNull && simpleTypeResolverSymbol.Equals(l.LocationType))) { kind = PropertySetAbstractValueKind.Flagged; } else if (pointsTo.Locations.Any(l => !l.IsNull - && javaScriptTypeResolverSymbol.Equals(l.LocationTypeOpt) - && (l.CreationOpt == null || l.CreationOpt.Kind != OperationKind.ObjectCreation))) + && javaScriptTypeResolverSymbol.Equals(l.LocationType) + && (l.Creation == null || l.Creation.Kind != OperationKind.ObjectCreation))) { // Points to a JavaScriptTypeResolver, but we don't know if the instance is a SimpleTypeResolver. kind = PropertySetAbstractValueKind.MaybeFlagged; diff --git a/src/NetAnalyzers/Microsoft.CodeAnalysis.NetAnalyzers.md b/src/NetAnalyzers/Microsoft.CodeAnalysis.NetAnalyzers.md index bc6e9fc01b..617dee450d 100644 --- a/src/NetAnalyzers/Microsoft.CodeAnalysis.NetAnalyzers.md +++ b/src/NetAnalyzers/Microsoft.CodeAnalysis.NetAnalyzers.md @@ -1,240 +1,3174 @@ +# Microsoft.CodeAnalysis.NetAnalyzers + +## [CA1000](https://docs.microsoft.com/visualstudio/code-quality/ca1000): Do not declare static members on generic types + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +When a static member of a generic type is called, the type argument must be specified for the type. When a generic instance member that does not support inference is called, the type argument must be specified for the member. In these two cases, the syntax for specifying the type argument is different and easily confused. + +## [CA1001](https://docs.microsoft.com/visualstudio/code-quality/ca1001): Types that own disposable fields should be disposable + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Hidden| +|CodeFix|True| + +### Rule description + +A class declares and implements an instance field that is a System.IDisposable type, and the class does not implement IDisposable. A class that declares an IDisposable field indirectly owns an unmanaged resource and should implement the IDisposable interface. + +## [CA1002](https://docs.microsoft.com/visualstudio/code-quality/ca1002): Do not expose generic lists + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +System.Collections.Generic.List is a generic collection that's designed for performance and not inheritance. List does not contain virtual members that make it easier to change the behavior of an inherited class. + +## [CA1003](https://docs.microsoft.com/visualstudio/code-quality/ca1003): Use generic event handler instances + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A type contains an event that declares an EventHandler delegate that returns void, whose signature contains two parameters (the first an object and the second a type that is assignable to EventArgs), and the containing assembly targets Microsoft .NET Framework?2.0. + +## [CA1005](https://docs.microsoft.com/visualstudio/code-quality/ca1005): Avoid excessive parameters on generic types + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The more type parameters a generic type contains, the more difficult it is to know and remember what each type parameter represents. + +## [CA1008](https://docs.microsoft.com/visualstudio/code-quality/ca1008): Enums should have zero value + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +The default value of an uninitialized enumeration, just as other value types, is zero. A nonflags-attributed enumeration should define a member by using the value of zero so that the default value is a valid value of the enumeration. If an enumeration that has the FlagsAttribute attribute applied defines a zero-valued member, its name should be ""None"" to indicate that no values have been set in the enumeration. + +## [CA1010](https://docs.microsoft.com/visualstudio/code-quality/ca1010): Generic interface should also be implemented + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +To broaden the usability of a type, implement one of the generic interfaces. This is especially true for collections as they can then be used to populate generic collection types. + +## [CA1012](https://docs.microsoft.com/visualstudio/code-quality/ca1012): Abstract types should not have public constructors + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Constructors on abstract types can be called only by derived types. Because public constructors create instances of a type, and you cannot create instances of an abstract type, an abstract type that has a public constructor is incorrectly designed. + +## [CA1014](https://docs.microsoft.com/visualstudio/code-quality/ca1014): Mark assemblies with CLSCompliant + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The Common Language Specification (CLS) defines naming restrictions, data types, and rules to which assemblies must conform if they will be used across programming languages. Good design dictates that all assemblies explicitly indicate CLS compliance by using CLSCompliantAttribute . If this attribute is not present on an assembly, the assembly is not compliant. + +## [CA1016](https://docs.microsoft.com/visualstudio/code-quality/ca1016): Mark assemblies with assembly version + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Info| +|CodeFix|False| + +### Rule description + +The .NET Framework uses the version number to uniquely identify an assembly, and to bind to types in strongly named assemblies. The version number is used together with version and publisher policy. By default, applications run only with the assembly version with which they were built. + +## [CA1017](https://docs.microsoft.com/visualstudio/code-quality/ca1017): Mark assemblies with ComVisible + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +ComVisibleAttribute determines how COM clients access managed code. Good design dictates that assemblies explicitly indicate COM visibility. COM visibility can be set for the whole assembly and then overridden for individual types and type members. If this attribute is not present, the contents of the assembly are visible to COM clients. + +## [CA1018](https://docs.microsoft.com/visualstudio/code-quality/ca1018): Mark attributes with AttributeUsageAttribute + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Info| +|CodeFix|False| + +### Rule description + +Specify AttributeUsage on {0} + +## [CA1019](https://docs.microsoft.com/visualstudio/code-quality/ca1019): Define accessors for attribute arguments + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Remove the property setter from {0} or reduce its accessibility because it corresponds to positional argument {1} + +## [CA1021](https://docs.microsoft.com/visualstudio/code-quality/ca1021): Avoid out parameters + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Passing types by reference (using 'out' or 'ref') requires experience with pointers, understanding how value types and reference types differ, and handling methods with multiple return values. Also, the difference between 'out' and 'ref' parameters is not widely understood. + +## [CA1024](https://docs.microsoft.com/visualstudio/code-quality/ca1024): Use properties where appropriate + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A public or protected method has a name that starts with ""Get"", takes no parameters, and returns a value that is not an array. The method might be a good candidate to become a property. + +## [CA1027](https://docs.microsoft.com/visualstudio/code-quality/ca1027): Mark enums with FlagsAttribute + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +An enumeration is a value type that defines a set of related named constants. Apply FlagsAttribute to an enumeration when its named constants can be meaningfully combined. + +## [CA1028](https://docs.microsoft.com/visualstudio/code-quality/ca1028): Enum Storage should be Int32 + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +An enumeration is a value type that defines a set of related named constants. By default, the System.Int32 data type is used to store the constant value. Although you can change this underlying type, it is not required or recommended for most scenarios. + +## [CA1030](https://docs.microsoft.com/visualstudio/code-quality/ca1030): Use events where appropriate + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +This rule detects methods that have names that ordinarily would be used for events. If a method is called in response to a clearly defined state change, the method should be invoked by an event handler. Objects that call the method should raise events instead of calling the method directly. + +## [CA1031](https://docs.microsoft.com/visualstudio/code-quality/ca1031): Do not catch general exception types + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A general exception such as System.Exception or System.SystemException or a disallowed exception type is caught in a catch statement, or a general catch clause is used. General and disallowed exceptions should not be caught. + +## [CA1032](https://docs.microsoft.com/visualstudio/code-quality/ca1032): Implement standard exception constructors + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Failure to provide the full set of constructors can make it difficult to correctly handle exceptions. + +## [CA1033](https://docs.microsoft.com/visualstudio/code-quality/ca1033): Interface methods should be callable by child types + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +An unsealed externally visible type provides an explicit method implementation of a public interface and does not provide an alternative externally visible method that has the same name. + +## [CA1034](https://docs.microsoft.com/visualstudio/code-quality/ca1034): Nested types should not be visible + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A nested type is a type that is declared in the scope of another type. Nested types are useful to encapsulate private implementation details of the containing type. Used for this purpose, nested types should not be externally visible. + +## [CA1036](https://docs.microsoft.com/visualstudio/code-quality/ca1036): Override methods on comparable types + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Hidden| +|CodeFix|True| + +### Rule description + +A public or protected type implements the System.IComparable interface. It does not override Object.Equals nor does it overload the language-specific operator for equality, inequality, less than, less than or equal, greater than or greater than or equal. + +## [CA1040](https://docs.microsoft.com/visualstudio/code-quality/ca1040): Avoid empty interfaces + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Interfaces define members that provide a behavior or usage contract. The functionality that is described by the interface can be adopted by any type, regardless of where the type appears in the inheritance hierarchy. A type implements an interface by providing implementations for the members of the interface. An empty interface does not define any members; therefore, it does not define a contract that can be implemented. + +## [CA1041](https://docs.microsoft.com/visualstudio/code-quality/ca1041): Provide ObsoleteAttribute message + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Info| +|CodeFix|False| + +### Rule description + +A type or member is marked by using a System.ObsoleteAttribute attribute that does not have its ObsoleteAttribute.Message property specified. When a type or member that is marked by using ObsoleteAttribute is compiled, the Message property of the attribute is displayed. This gives the user information about the obsolete type or member. + +## [CA1043](https://docs.microsoft.com/visualstudio/code-quality/ca1043): Use Integral Or String Argument For Indexers + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Indexers, that is, indexed properties, should use integer or string types for the index. These types are typically used for indexing data structures and increase the usability of the library. Use of the Object type should be restricted to those cases where the specific integer or string type cannot be specified at design time. If the design requires other types for the index, reconsider whether the type represents a logical data store. If it does not represent a logical data store, use a method. + +## [CA1044](https://docs.microsoft.com/visualstudio/code-quality/ca1044): Properties should not be write only + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Although it is acceptable and often necessary to have a read-only property, the design guidelines prohibit the use of write-only properties. This is because letting a user set a value, and then preventing the user from viewing that value, does not provide any security. Also, without read access, the state of shared objects cannot be viewed, which limits their usefulness. + +## [CA1045](https://docs.microsoft.com/visualstudio/code-quality/ca1045): Do not pass types by reference + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Passing types by reference (using out or ref) requires experience with pointers, understanding how value types and reference types differ, and handling methods that have multiple return values. Also, the difference between out and ref parameters is not widely understood. + +## [CA1046](https://docs.microsoft.com/visualstudio/code-quality/ca1046): Do not overload equality operator on reference types + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +For reference types, the default implementation of the equality operator is almost always correct. By default, two references are equal only if they point to the same object. If the operator is providing meaningful value equality, the type should implement the generic 'System.IEquatable' interface. + +## [CA1047](https://docs.microsoft.com/visualstudio/code-quality/ca1047): Do not declare protected member in sealed type + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Info| +|CodeFix|False| + +### Rule description + +Types declare protected members so that inheriting types can access or override the member. By definition, you cannot inherit from a sealed type, which means that protected methods on sealed types cannot be called. + +## [CA1050](https://docs.microsoft.com/visualstudio/code-quality/ca1050): Declare types in namespaces + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Info| +|CodeFix|False| + +### Rule description + +Types are declared in namespaces to prevent name collisions and as a way to organize related types in an object hierarchy. + +## [CA1051](https://docs.microsoft.com/visualstudio/code-quality/ca1051): Do not declare visible instance fields + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +The primary use of a field should be as an implementation detail. Fields should be private or internal and should be exposed by using properties. + +## [CA1052](https://docs.microsoft.com/visualstudio/code-quality/ca1052): Static holder types should be Static or NotInheritable + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Type '{0}' is a static holder type but is neither static nor NotInheritable + +## [CA1054](https://docs.microsoft.com/visualstudio/code-quality/ca1054): URI-like parameters should not be strings + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +This rule assumes that the parameter represents a Uniform Resource Identifier (URI). A string representation or a URI is prone to parsing and encoding errors, and can lead to security vulnerabilities. 'System.Uri' class provides these services in a safe and secure manner. + +## [CA1055](https://docs.microsoft.com/visualstudio/code-quality/ca1055): URI-like return values should not be strings + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +This rule assumes that the method returns a URI. A string representation of a URI is prone to parsing and encoding errors, and can lead to security vulnerabilities. The System.Uri class provides these services in a safe and secure manner. + +## [CA1056](https://docs.microsoft.com/visualstudio/code-quality/ca1056): URI-like properties should not be strings + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +This rule assumes that the property represents a Uniform Resource Identifier (URI). A string representation of a URI is prone to parsing and encoding errors, and can lead to security vulnerabilities. The System.Uri class provides these services in a safe and secure manner. + +## [CA1058](https://docs.microsoft.com/visualstudio/code-quality/ca1058): Types should not extend certain base types + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +An externally visible type extends certain base types. Use one of the alternatives. + +## [CA1060](https://docs.microsoft.com/visualstudio/code-quality/ca1060): Move pinvokes to native methods class + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Platform Invocation methods, such as those that are marked by using the System.Runtime.InteropServices.DllImportAttribute attribute, or methods that are defined by using the Declare keyword in Visual Basic, access unmanaged code. These methods should be of the NativeMethods, SafeNativeMethods, or UnsafeNativeMethods class. + +## [CA1061](https://docs.microsoft.com/visualstudio/code-quality/ca1061): Do not hide base class methods + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Info| +|CodeFix|False| + +### Rule description + +A method in a base type is hidden by an identically named method in a derived type when the parameter signature of the derived method differs only by types that are more weakly derived than the corresponding types in the parameter signature of the base method. + +## [CA1062](https://docs.microsoft.com/visualstudio/code-quality/ca1062): Validate arguments of public methods + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +An externally visible method dereferences one of its reference arguments without verifying whether that argument is null (Nothing in Visual Basic). All reference arguments that are passed to externally visible methods should be checked against null. If appropriate, throw an ArgumentNullException when the argument is null or add a Code Contract precondition asserting non-null argument. If the method is designed to be called only by known assemblies, you should make the method internal. + +## [CA1063](https://docs.microsoft.com/visualstudio/code-quality/ca1063): Implement IDisposable Correctly + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +All IDisposable types should implement the Dispose pattern correctly. + +## [CA1064](https://docs.microsoft.com/visualstudio/code-quality/ca1064): Exceptions should be public + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +An internal exception is visible only inside its own internal scope. After the exception falls outside the internal scope, only the base exception can be used to catch the exception. If the internal exception is inherited from T:System.Exception, T:System.SystemException, or T:System.ApplicationException, the external code will not have sufficient information to know what to do with the exception. + +## [CA1065](https://docs.microsoft.com/visualstudio/code-quality/ca1065): Do not raise exceptions in unexpected locations + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A method that is not expected to throw exceptions throws an exception. + +## [CA1066](https://docs.microsoft.com/visualstudio/code-quality/ca1066): Implement IEquatable when overriding Object.Equals + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +When a type T overrides Object.Equals(object), the implementation must cast the object argument to the correct type T before performing the comparison. If the type implements IEquatable, and therefore offers the method T.Equals(T), and if the argument is known at compile time to be of type T, then the compiler can call IEquatable.Equals(T) instead of Object.Equals(object), and no cast is necessary, improving performance. + +## [CA1067](https://docs.microsoft.com/visualstudio/code-quality/ca1067): Override Object.Equals(object) when implementing IEquatable + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Info| +|CodeFix|True| + +### Rule description + +When a type T implements the interface IEquatable, it suggests to a user who sees a call to the Equals method in source code that an instance of the type can be equated with an instance of any other type. The user might be confused if their attempt to equate the type with an instance of another type fails to compile. This violates the "principle of least surprise". + +## [CA1068](https://docs.microsoft.com/visualstudio/code-quality/ca1068): CancellationToken parameters must come last + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Info| +|CodeFix|False| + +### Rule description + +Method '{0}' should take CancellationToken as the last parameter + +## [CA1069](https://docs.microsoft.com/visualstudio/code-quality/ca1069): Enums values should not be duplicated + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Info| +|CodeFix|False| + +### Rule description + +The field reference '{0}' is duplicated in this bitwise initialization + +## [CA1070](https://docs.microsoft.com/visualstudio/code-quality/ca1070): Do not declare event fields as virtual + +|Item|Value| +|-|-| +|Category|Design| +|Enabled|True| +|Severity|Info| +|CodeFix|False| + +### Rule description + +Do not declare virtual events in a base class. Overridden events in a derived class have undefined behavior. The C# compiler does not handle this correctly and it is unpredictable whether a subscriber to the derived event will actually be subscribing to the base class event. + +## [CA1200](https://docs.microsoft.com/visualstudio/code-quality/ca1200): Avoid using cref tags with a prefix + +|Item|Value| +|-|-| +|Category|Documentation| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +Use of cref tags with prefixes should be avoided, since it prevents the compiler from verifying references and the IDE from updating references during refactorings. It is permissible to suppress this error at a single documentation site if the cref must use a prefix because the type being mentioned is not findable by the compiler. For example, if a cref is mentioning a special attribute in the full framework but you're in a file that compiles against the portable framework, or if you want to reference a type at higher layer of Roslyn, you should suppress the error. You should not suppress the error just because you want to take a shortcut and avoid using the full syntax. + +## [CA1303](https://docs.microsoft.com/visualstudio/code-quality/ca1303): Do not pass literals as localized parameters + +|Item|Value| +|-|-| +|Category|Globalization| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A method passes a string literal as a parameter to a constructor or method in the .NET Framework class library and that string should be localizable. To fix a violation of this rule, replace the string literal with a string retrieved through an instance of the ResourceManager class. + +## [CA1304](https://docs.microsoft.com/visualstudio/code-quality/ca1304): Specify CultureInfo + +|Item|Value| +|-|-| +|Category|Globalization| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +A method or constructor calls a member that has an overload that accepts a System.Globalization.CultureInfo parameter, and the method or constructor does not call the overload that takes the CultureInfo parameter. When a CultureInfo or System.IFormatProvider object is not supplied, the default value that is supplied by the overloaded member might not have the effect that you want in all locales. If the result will be displayed to the user, specify 'CultureInfo.CurrentCulture' as the 'CultureInfo' parameter. Otherwise, if the result will be stored and accessed by software, such as when it is persisted to disk or to a database, specify 'CultureInfo.InvariantCulture'. + +## [CA1305](https://docs.microsoft.com/visualstudio/code-quality/ca1305): Specify IFormatProvider + +|Item|Value| +|-|-| +|Category|Globalization| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +A method or constructor calls one or more members that have overloads that accept a System.IFormatProvider parameter, and the method or constructor does not call the overload that takes the IFormatProvider parameter. When a System.Globalization.CultureInfo or IFormatProvider object is not supplied, the default value that is supplied by the overloaded member might not have the effect that you want in all locales. If the result will be based on the input from/output displayed to the user, specify 'CultureInfo.CurrentCulture' as the 'IFormatProvider'. Otherwise, if the result will be stored and accessed by software, such as when it is loaded from disk/database and when it is persisted to disk/database, specify 'CultureInfo.InvariantCulture'. + +## [CA1307](https://docs.microsoft.com/visualstudio/code-quality/ca1307): Specify StringComparison + +|Item|Value| +|-|-| +|Category|Globalization| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +A string comparison operation uses a method overload that does not set a StringComparison parameter. If the result will be displayed to the user, such as when sorting a list of items for display in a list box, specify 'StringComparison.CurrentCulture' or 'StringComparison.CurrentCultureIgnoreCase' as the 'StringComparison' parameter. If comparing case-insensitive identifiers, such as file paths, environment variables, or registry keys and values, specify 'StringComparison.OrdinalIgnoreCase'. Otherwise, if comparing case-sensitive identifiers, specify 'StringComparison.Ordinal'. + +## [CA1308](https://docs.microsoft.com/visualstudio/code-quality/ca1308): Normalize strings to uppercase + +|Item|Value| +|-|-| +|Category|Globalization| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Strings should be normalized to uppercase. A small group of characters cannot make a round trip when they are converted to lowercase. To make a round trip means to convert the characters from one locale to another locale that represents character data differently, and then to accurately retrieve the original characters from the converted characters. + +## [CA1309](https://docs.microsoft.com/visualstudio/code-quality/ca1309): Use ordinal stringcomparison + +|Item|Value| +|-|-| +|Category|Globalization| +|Enabled|True| +|Severity|Hidden| +|CodeFix|True| + +### Rule description + +A string comparison operation that is nonlinguistic does not set the StringComparison parameter to either Ordinal or OrdinalIgnoreCase. By explicitly setting the parameter to either StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase, your code often gains speed, becomes more correct, and becomes more reliable. + +## [CA1401](https://docs.microsoft.com/visualstudio/code-quality/ca1401): P/Invokes should not be visible + +|Item|Value| +|-|-| +|Category|Interoperability| +|Enabled|True| +|Severity|Info| +|CodeFix|False| + +### Rule description + +A public or protected method in a public type has the System.Runtime.InteropServices.DllImportAttribute attribute (also implemented by the Declare keyword in Visual Basic). Such methods should not be exposed. + +## [CA1417](https://docs.microsoft.com/visualstudio/code-quality/ca1417): Do not use 'OutAttribute' on string parameters for P/Invokes + +|Item|Value| +|-|-| +|Category|Interoperability| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +String parameters passed by value with the 'OutAttribute' can destabilize the runtime if the string is an interned string. + +## [CA1501](https://docs.microsoft.com/visualstudio/code-quality/ca1501): Avoid excessive inheritance + +|Item|Value| +|-|-| +|Category|Maintainability| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Deeply nested type hierarchies can be difficult to follow, understand, and maintain. This rule limits analysis to hierarchies in the same module. To fix a violation of this rule, derive the type from a base type that is less deep in the inheritance hierarchy or eliminate some of the intermediate base types. + +## [CA1502](https://docs.microsoft.com/visualstudio/code-quality/ca1502): Avoid excessive complexity + +|Item|Value| +|-|-| +|Category|Maintainability| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Cyclomatic complexity measures the number of linearly independent paths through the method, which is determined by the number and complexity of conditional branches. A low cyclomatic complexity generally indicates a method that is easy to understand, test, and maintain. The cyclomatic complexity is calculated from a control flow graph of the method and is given as follows: `cyclomatic complexity = the number of edges - the number of nodes + 1`, where a node represents a logic branch point and an edge represents a line between nodes. + +## [CA1505](https://docs.microsoft.com/visualstudio/code-quality/ca1505): Avoid unmaintainable code + +|Item|Value| +|-|-| +|Category|Maintainability| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The maintainability index is calculated by using the following metrics: lines of code, program volume, and cyclomatic complexity. Program volume is a measure of the difficulty of understanding of a symbol that is based on the number of operators and operands in the code. Cyclomatic complexity is a measure of the structural complexity of the type or method. A low maintainability index indicates that code is probably difficult to maintain and would be a good candidate to redesign. + +## [CA1506](https://docs.microsoft.com/visualstudio/code-quality/ca1506): Avoid excessive class coupling + +|Item|Value| +|-|-| +|Category|Maintainability| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +This rule measures class coupling by counting the number of unique type references that a symbol contains. Symbols that have a high degree of class coupling can be difficult to maintain. It is a good practice to have types and methods that exhibit low coupling and high cohesion. To fix this violation, try to redesign the code to reduce the number of types to which it is coupled. + +## [CA1507](https://docs.microsoft.com/visualstudio/code-quality/ca1507): Use nameof to express symbol names + +|Item|Value| +|-|-| +|Category|Maintainability| +|Enabled|True| +|Severity|Info| +|CodeFix|True| + +### Rule description + +Using nameof helps keep your code valid when refactoring. + +## [CA1508](https://docs.microsoft.com/visualstudio/code-quality/ca1508): Avoid dead conditional code + +|Item|Value| +|-|-| +|Category|Maintainability| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +'{0}' is never '{1}'. Remove or refactor the condition(s) to avoid dead code. + +## [CA1509](https://docs.microsoft.com/visualstudio/code-quality/ca1509): Invalid entry in code metrics rule specification file + +|Item|Value| +|-|-| +|Category|Maintainability| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Invalid entry in code metrics rule specification file. + +## [CA1700](https://docs.microsoft.com/visualstudio/code-quality/ca1700): Do not name enum values 'Reserved' + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +This rule assumes that an enumeration member that has a name that contains "reserved" is not currently used but is a placeholder to be renamed or removed in a future version. Renaming or removing a member is a breaking change. + +## [CA1707](https://docs.microsoft.com/visualstudio/code-quality/ca1707): Identifiers should not contain underscores + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +By convention, identifier names do not contain the underscore (_) character. This rule checks namespaces, types, members, and parameters. + +## [CA1708](https://docs.microsoft.com/visualstudio/code-quality/ca1708): Identifiers should differ by more than case + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +Identifiers for namespaces, types, members, and parameters cannot differ only by case because languages that target the common language runtime are not required to be case-sensitive. + +## [CA1710](https://docs.microsoft.com/visualstudio/code-quality/ca1710): Identifiers should have correct suffix + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +By convention, the names of types that extend certain base types or that implement certain interfaces, or types that are derived from these types, have a suffix that is associated with the base type or interface. + +## [CA1711](https://docs.microsoft.com/visualstudio/code-quality/ca1711): Identifiers should not have incorrect suffix + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +By convention, only the names of types that extend certain base types or that implement certain interfaces, or types that are derived from these types, should end with specific reserved suffixes. Other type names should not use these reserved suffixes. + +## [CA1712](https://docs.microsoft.com/visualstudio/code-quality/ca1712): Do not prefix enum values with type name + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +An enumeration's values should not start with the type name of the enumeration. + +## [CA1713](https://docs.microsoft.com/visualstudio/code-quality/ca1713): Events should not have 'Before' or 'After' prefix + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Event names should describe the action that raises the event. To name related events that are raised in a specific sequence, use the present or past tense to indicate the relative position in the sequence of actions. For example, when naming a pair of events that is raised when closing a resource, you might name it 'Closing' and 'Closed', instead of 'BeforeClose' and 'AfterClose'. + +## [CA1715](https://docs.microsoft.com/visualstudio/code-quality/ca1715): Identifiers should have correct prefix + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +The name of an externally visible interface does not start with an uppercase ""I"". The name of a generic type parameter on an externally visible type or method does not start with an uppercase ""T"". + +## [CA1716](https://docs.microsoft.com/visualstudio/code-quality/ca1716): Identifiers should not match keywords + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +A namespace name or a type name matches a reserved keyword in a programming language. Identifiers for namespaces and types should not match keywords that are defined by languages that target the common language runtime. + +## [CA1720](https://docs.microsoft.com/visualstudio/code-quality/ca1720): Identifier contains type name + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +Names of parameters and members are better used to communicate their meaning than to describe their type, which is expected to be provided by development tools. For names of members, if a data type name must be used, use a language-independent name instead of a language-specific one. + +## [CA1721](https://docs.microsoft.com/visualstudio/code-quality/ca1721): Property names should not match get methods + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The name of a public or protected member starts with ""Get"" and otherwise matches the name of a public or protected property. ""Get"" methods and properties should have names that clearly distinguish their function. + +## [CA1724](https://docs.microsoft.com/visualstudio/code-quality/ca1724): Type names should not match namespaces + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Type names should not match the names of namespaces that are defined in the .NET Framework class library. Violating this rule can reduce the usability of the library. + +## [CA1725](https://docs.microsoft.com/visualstudio/code-quality/ca1725): Parameter names should match base declaration + +|Item|Value| +|-|-| +|Category|Naming| +|Enabled|True| +|Severity|Hidden| +|CodeFix|True| + +### Rule description + +Consistent naming of parameters in an override hierarchy increases the usability of the method overrides. A parameter name in a derived method that differs from the name in the base declaration can cause confusion about whether the method is an override of the base method or a new overload of the method. + +## [CA1801](https://docs.microsoft.com/visualstudio/code-quality/ca1801): Review unused parameters + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Avoid unused paramereters in your code. If the parameter cannot be removed, then change its name so it starts with an underscore and is optionally followed by an integer, such as '_', '_1', '_2', etc. These are treated as special discard symbol names. + +## [CA1802](https://docs.microsoft.com/visualstudio/code-quality/ca1802): Use literals where appropriate + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +A field is declared static and read-only (Shared and ReadOnly in Visual Basic), and is initialized by using a value that is computable at compile time. Because the value that is assigned to the targeted field is computable at compile time, change the declaration to a const (Const in Visual Basic) field so that the value is computed at compile time instead of at run?time. + +## [CA1805](https://docs.microsoft.com/visualstudio/code-quality/ca1805): Do not initialize unnecessarily + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Info| +|CodeFix|True| + +### Rule description + +The .NET runtime initializes all fields of reference types to their default values before running the constructor. In most cases, explicitly initializing a field to its default value in a constructor is redundant, adding maintenance costs and potentially degrading performance (such as with increased assembly size), and the explicit initialization can be removed. In some cases, such as with static readonly fields that permanently retain their default value, consider instead changing them to be constants or properties. + +## [CA1806](https://docs.microsoft.com/visualstudio/code-quality/ca1806): Do not ignore method results + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Info| +|CodeFix|False| + +### Rule description + +A new object is created but never used; or a method that creates and returns a new string is called and the new string is never used; or a COM or P/Invoke method returns an HRESULT or error code that is never used. + +## [CA1810](https://docs.microsoft.com/visualstudio/code-quality/ca1810): Initialize reference type static fields inline + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A reference 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. + +## [CA1812](https://docs.microsoft.com/visualstudio/code-quality/ca1812): Avoid uninstantiated internal classes + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +An instance of an assembly-level type is not created by code in the assembly. + +## [CA1813](https://docs.microsoft.com/visualstudio/code-quality/ca1813): Avoid unsealed attributes + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +The .NET Framework class library provides methods for retrieving custom attributes. By default, these methods search the attribute inheritance hierarchy. Sealing the attribute eliminates the search through the inheritance hierarchy and can improve performance. + +## [CA1814](https://docs.microsoft.com/visualstudio/code-quality/ca1814): Prefer jagged arrays over multidimensional + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A jagged array is an array whose elements are arrays. The arrays that make up the elements can be of different sizes, leading to less wasted space for some sets of data. + +## [CA1815](https://docs.microsoft.com/visualstudio/code-quality/ca1815): Override equals and operator equals on value types + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +For value types, the inherited implementation of Equals uses the Reflection library and compares the contents of all fields. Reflection is computationally expensive, and comparing every field for equality might be unnecessary. If you expect users to compare or sort instances, or to use instances as hash table keys, your value type should implement Equals. + +## [CA1816](https://docs.microsoft.com/visualstudio/code-quality/ca1816): Dispose methods should call SuppressFinalize + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Info| +|CodeFix|False| + +### Rule description + +A method that is an implementation of Dispose does not call GC.SuppressFinalize; or a method that is not an implementation of Dispose calls GC.SuppressFinalize; or a method calls GC.SuppressFinalize and passes something other than this (Me in Visual?Basic). + +## [CA1819](https://docs.microsoft.com/visualstudio/code-quality/ca1819): Properties should not return arrays + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Arrays that are returned by properties are not write-protected, even when the property is read-only. To keep the array tamper-proof, the property must return a copy of the array. Typically, users will not understand the adverse performance implications of calling such a property. + +## [CA1820](https://docs.microsoft.com/visualstudio/code-quality/ca1820): Test for empty strings using string length + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Comparing strings by using the String.Length property or the String.IsNullOrEmpty method is significantly faster than using Equals. + +## [CA1821](https://docs.microsoft.com/visualstudio/code-quality/ca1821): Remove empty Finalizers + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Info| +|CodeFix|True| + +### Rule description + +Finalizers should be avoided where possible, to avoid the additional performance overhead involved in tracking object lifetime. + +## [CA1822](https://docs.microsoft.com/visualstudio/code-quality/ca1822): Mark members as static + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Info| +|CodeFix|True| + +### Rule description + +Members that do not access instance data or call instance methods can be marked as static. After you mark the methods as static, the compiler will emit nonvirtual call sites to these members. This can give you a measurable performance gain for performance-sensitive code. + +## [CA1823](https://docs.microsoft.com/visualstudio/code-quality/ca1823): Avoid unused private fields + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Private fields were detected that do not appear to be accessed in the assembly. + +## [CA1824](https://docs.microsoft.com/visualstudio/code-quality/ca1824): Mark assemblies with NeutralResourcesLanguageAttribute + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Info| +|CodeFix|False| + +### Rule description + +The NeutralResourcesLanguage attribute informs the ResourceManager of the language that was used to display the resources of a neutral culture for an assembly. This improves lookup performance for the first resource that you load and can reduce your working set. + +## [CA1825](https://docs.microsoft.com/visualstudio/code-quality/ca1825): Avoid zero-length array allocations + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Info| +|CodeFix|True| + +### Rule description + +Avoid unnecessary zero-length array allocations. Use {0} instead. + +## [CA1826](https://docs.microsoft.com/visualstudio/code-quality/ca1826): Do not use Enumerable methods on indexable collections + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Info| +|CodeFix|True| + +### Rule description + +This collection is directly indexable. Going through LINQ here causes unnecessary allocations and CPU work. + +## [CA1827](https://docs.microsoft.com/visualstudio/code-quality/ca1827): Do not use Count() or LongCount() when Any() can be used + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Info| +|CodeFix|True| + +### Rule description + +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. + +## [CA1828](https://docs.microsoft.com/visualstudio/code-quality/ca1828): Do not use CountAsync() or LongCountAsync() when AnyAsync() can be used + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Info| +|CodeFix|True| + +### Rule description + +For non-empty collections, CountAsync() and LongCountAsync() enumerate the entire sequence, while AnyAsync() stops at the first item or the first item that satisfies a condition. + +## [CA1829](https://docs.microsoft.com/visualstudio/code-quality/ca1829): Use Length/Count property instead of Count() when available + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Info| +|CodeFix|True| + +### Rule description + +Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. + +## [CA1830](https://docs.microsoft.com/visualstudio/code-quality/ca1830): Prefer strongly-typed Append and Insert method overloads on StringBuilder + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Info| +|CodeFix|True| + +### Rule description + +StringBuilder.Append and StringBuilder.Insert provide overloads for multiple types beyond System.String. When possible, prefer the strongly-typed overloads over using ToString() and the string-based overload. + +## [CA1831](https://docs.microsoft.com/visualstudio/code-quality/ca1831): Use AsSpan or AsMemory instead of Range-based indexers when appropriate + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +The Range-based indexer on string values produces a copy of requested portion of the string. This copy is usually unnecessary when it is implicitly used as a ReadOnlySpan or ReadOnlyMemory value. Use the AsSpan method to avoid the unnecessary copy. + +## [CA1832](https://docs.microsoft.com/visualstudio/code-quality/ca1832): Use AsSpan or AsMemory instead of Range-based indexers when appropriate + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Info| +|CodeFix|True| + +### Rule description + +The Range-based indexer on array values produces a copy of requested portion of the array. This copy is usually unnecessary when it is implicitly used as a ReadOnlySpan or ReadOnlyMemory value. Use the AsSpan method to avoid the unnecessary copy. + +## [CA1833](https://docs.microsoft.com/visualstudio/code-quality/ca1833): Use AsSpan or AsMemory instead of Range-based indexers when appropriate + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Info| +|CodeFix|True| + +### Rule description + +The Range-based indexer on array values produces a copy of requested portion of the array. This copy is often unwanted when it is implicitly used as a Span or Memory value. Use the AsSpan method to avoid the copy. + +## [CA1834](https://docs.microsoft.com/visualstudio/code-quality/ca1834): Consider using 'StringBuilder.Append(char)' when applicable + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Info| +|CodeFix|True| + +### Rule description + +'StringBuilder.Append(char)' is more efficient than 'StringBuilder.Append(string)' when the string is a single character. When calling 'Append' with a constant, prefer using a constant char rather than a constant string containing one character. + +## [CA1835](https://docs.microsoft.com/visualstudio/code-quality/ca1835): Prefer the 'Memory'-based overloads for 'ReadAsync' and 'WriteAsync' + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Info| +|CodeFix|True| + +### Rule description + +'Stream' has a 'ReadAsync' overload that takes a 'Memory' as the first argument, and a 'WriteAsync' overload that takes a 'ReadOnlyMemory' as the first argument. Prefer calling the memory based overloads, which are more efficient. + +## [CA1836](https://docs.microsoft.com/visualstudio/code-quality/ca1836): Prefer IsEmpty over Count + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Info| +|CodeFix|True| + +### Rule description + +For determining whether the object contains or not any items, prefer using 'IsEmpty' property rather than retrieving the number of items from the 'Count' property and comparing it to 0 or 1. + +## [CA1837](https://docs.microsoft.com/visualstudio/code-quality/ca1837): Use 'Environment.ProcessId' + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Info| +|CodeFix|True| + +### Rule description + +'Environment.ProcessId' is simpler and faster than 'Process.GetCurrentProcess().Id'. + +## [CA1838](https://docs.microsoft.com/visualstudio/code-quality/ca1838): Avoid 'StringBuilder' parameters for P/Invokes + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +Marshalling of 'StringBuilder' always creates a native buffer copy, resulting in multiple allocations for one marshalling operation. + +## [CA2000](https://docs.microsoft.com/visualstudio/code-quality/ca2000): Dispose objects before losing scope + +|Item|Value| +|-|-| +|Category|Reliability| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2002](https://docs.microsoft.com/visualstudio/code-quality/ca2002): Do not lock on objects with weak identity + +|Item|Value| +|-|-| +|Category|Reliability| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2007](https://docs.microsoft.com/visualstudio/code-quality/ca2007): Consider calling ConfigureAwait on the awaited task + +|Item|Value| +|-|-| +|Category|Reliability| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +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. + +## [CA2008](https://docs.microsoft.com/visualstudio/code-quality/ca2008): Do not create tasks without passing a TaskScheduler + +|Item|Value| +|-|-| +|Category|Reliability| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2009](https://docs.microsoft.com/visualstudio/code-quality/ca2009): Do not call ToImmutableCollection on an ImmutableCollection value + +|Item|Value| +|-|-| +|Category|Reliability| +|Enabled|True| +|Severity|Info| +|CodeFix|True| + +### Rule description + +Do not call {0} on an {1} value + +## [CA2011](https://docs.microsoft.com/visualstudio/code-quality/ca2011): Avoid infinite recursion + +|Item|Value| +|-|-| +|Category|Reliability| +|Enabled|True| +|Severity|Info| +|CodeFix|False| + +### Rule description + +Do not assign the property within its setter. This call might result in an infinite recursion. + +## [CA2012](https://docs.microsoft.com/visualstudio/code-quality/ca2012): Use ValueTasks correctly + +|Item|Value| +|-|-| +|Category|Reliability| +|Enabled|True| +|Severity|Info| +|CodeFix|False| + +### Rule description + +ValueTasks returned from member invocations are intended to be directly awaited. Attempts to consume a ValueTask multiple times or to directly access one's result before it's known to be completed may result in an exception or corruption. Ignoring such a ValueTask is likely an indication of a functional bug and may degrade performance. + +## [CA2013](https://docs.microsoft.com/visualstudio/code-quality/ca2013): Do not use ReferenceEquals with value types + +|Item|Value| +|-|-| +|Category|Reliability| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Value type typed arguments are uniquely boxed for each call to this method, therefore the result is always false. + +## [CA2014](https://docs.microsoft.com/visualstudio/code-quality/ca2014): Do not use stackalloc in loops + +|Item|Value| +|-|-| +|Category|Reliability| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Stack space allocated by a stackalloc is only released at the end of the current method's invocation. Using it in a loop can result in unbounded stack growth and eventual stack overflow conditions. + +## [CA2015](https://docs.microsoft.com/visualstudio/code-quality/ca2015): Do not define finalizers for types derived from MemoryManager + +|Item|Value| +|-|-| +|Category|Reliability| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Adding a finalizer to a type derived from MemoryManager may permit memory to be freed while it is still in use by a Span. + +## [CA2016](https://docs.microsoft.com/visualstudio/code-quality/ca2016): Forward the 'CancellationToken' parameter to methods that take one + +|Item|Value| +|-|-| +|Category|Reliability| +|Enabled|True| +|Severity|Info| +|CodeFix|True| + +### Rule description + +Forward the 'CancellationToken' parameter to methods that take one to ensure the operation cancellation notifications gets properly propagated, or pass in 'CancellationToken.None' explicitly to indicate intentionally not propagating the token. + +## [CA2100](https://docs.microsoft.com/visualstudio/code-quality/ca2100): Review SQL queries for security vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2101](https://docs.microsoft.com/visualstudio/code-quality/ca2101): Specify marshaling for P/Invoke string arguments + +|Item|Value| +|-|-| +|Category|Globalization| +|Enabled|True| +|Severity|Info| +|CodeFix|True| + +### Rule description + +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. + +## [CA2109](https://docs.microsoft.com/visualstudio/code-quality/ca2109): Review visible event handlers + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +A public or protected event-handling method was detected. Event-handling methods should not be exposed unless absolutely necessary. + +## [CA2119](https://docs.microsoft.com/visualstudio/code-quality/ca2119): Seal methods that satisfy private interfaces + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +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. + +## [CA2153](https://docs.microsoft.com/visualstudio/code-quality/ca2153): Do Not Catch Corrupted State Exceptions + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2200](https://docs.microsoft.com/visualstudio/code-quality/ca2200): Rethrow to preserve stack details + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Info| +|CodeFix|True| + +### Rule description + +Re-throwing caught exception changes stack information + +## [CA2201](https://docs.microsoft.com/visualstudio/code-quality/ca2201): Do not raise reserved exception types + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +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. + +## [CA2207](https://docs.microsoft.com/visualstudio/code-quality/ca2207): Initialize value type static fields inline + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2208](https://docs.microsoft.com/visualstudio/code-quality/ca2208): Instantiate argument exceptions correctly + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Info| +|CodeFix|True| + +### Rule description + +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. + +## [CA2211](https://docs.microsoft.com/visualstudio/code-quality/ca2211): Non-constant fields should not be visible + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Info| +|CodeFix|False| + +### Rule description + +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. + +## [CA2213](https://docs.microsoft.com/visualstudio/code-quality/ca2213): Disposable fields should be disposed + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2214](https://docs.microsoft.com/visualstudio/code-quality/ca2214): Do not call overridable methods in constructors + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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). + +## [CA2215](https://docs.microsoft.com/visualstudio/code-quality/ca2215): Dispose methods should call base class dispose + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Hidden| +|CodeFix|True| + +### Rule description + +A type that implements System.IDisposable inherits from a type that also implements IDisposable. The Dispose method of the inheriting type does not call the Dispose method of the parent type. To fix a violation of this rule, call base.Dispose in your Dispose method. + +## [CA2216](https://docs.microsoft.com/visualstudio/code-quality/ca2216): Disposable types should declare finalizer + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2217](https://docs.microsoft.com/visualstudio/code-quality/ca2217): Do not mark enums with FlagsAttribute + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +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. + +## [CA2218](https://docs.microsoft.com/visualstudio/code-quality/ca2218): Override GetHashCode on overriding Equals + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Info| +|CodeFix|True| + +### Rule description + +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. + +## [CA2219](https://docs.microsoft.com/visualstudio/code-quality/ca2219): Do not raise exceptions in finally clauses + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Info| +|CodeFix|False| + +### Rule description + +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. + +## [CA2224](https://docs.microsoft.com/visualstudio/code-quality/ca2224): Override Equals on overloading operator equals + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Info| +|CodeFix|True| + +### Rule description + +A public type implements the equality operator but does not override Object.Equals. + +## [CA2225](https://docs.microsoft.com/visualstudio/code-quality/ca2225): Operator overloads have named alternates + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +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. + +## [CA2226](https://docs.microsoft.com/visualstudio/code-quality/ca2226): Operators should have symmetrical overloads + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +A type implements the equality or inequality operator and does not implement the opposite operator. + +## [CA2227](https://docs.microsoft.com/visualstudio/code-quality/ca2227): Collection properties should be read only + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2229](https://docs.microsoft.com/visualstudio/code-quality/ca2229): Implement serialization constructors + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Hidden| +|CodeFix|True| + +### Rule description + +To fix a violation of this rule, implement the serialization constructor. For a sealed class, make the constructor private; otherwise, make it protected. + +## [CA2231](https://docs.microsoft.com/visualstudio/code-quality/ca2231): Overload operator equals on overriding value type Equals + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Info| +|CodeFix|True| + +### Rule description + +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. + +## [CA2234](https://docs.microsoft.com/visualstudio/code-quality/ca2234): Pass system uri objects instead of strings + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2235](https://docs.microsoft.com/visualstudio/code-quality/ca2235): Mark all non-serializable fields + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +An instance field of a type that is not serializable is declared in a type that is serializable. + +## [CA2237](https://docs.microsoft.com/visualstudio/code-quality/ca2237): Mark ISerializable types with serializable + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +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. + +## [CA2241](https://docs.microsoft.com/visualstudio/code-quality/ca2241): Provide correct arguments to formatting methods + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Info| +|CodeFix|False| + +### Rule description + +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. + +## [CA2242](https://docs.microsoft.com/visualstudio/code-quality/ca2242): Test for NaN correctly + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Info| +|CodeFix|True| + +### Rule description + +This expression tests a value against Single.Nan or Double.Nan. Use Single.IsNan(Single) or Double.IsNan(Double) to test the value. + +## [CA2243](https://docs.microsoft.com/visualstudio/code-quality/ca2243): Attribute string literals should parse correctly + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The string literal parameter of an attribute does not parse correctly for a URL, a GUID, or a version. + +## [CA2244](https://docs.microsoft.com/visualstudio/code-quality/ca2244): Do not duplicate indexed element initializations + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Info| +|CodeFix|True| + +### Rule description + +Indexed elements in objects initializers must initialize unique elements. A duplicate index might overwrite a previous element initialization. + +## [CA2245](https://docs.microsoft.com/visualstudio/code-quality/ca2245): Do not assign a property to itself + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Info| +|CodeFix|False| + +### Rule description + +The property {0} should not be assigned to itself + +## [CA2246](https://docs.microsoft.com/visualstudio/code-quality/ca2246): Assigning symbol and its member in the same statement + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Info| +|CodeFix|False| + +### Rule description + +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. + +## [CA2247](https://docs.microsoft.com/visualstudio/code-quality/ca2247): Argument passed to TaskCompletionSource constructor should be TaskCreationOptions enum instead of TaskContinuationOptions enum + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +TaskCompletionSource has constructors that take TaskCreationOptions that control the underlying Task, and constructors that take object state that's stored in the task. Accidentally passing a TaskContinuationOptions instead of a TaskCreationOptions will result in the call treating the options as state. + +## [CA2248](https://docs.microsoft.com/visualstudio/code-quality/ca2248): Provide correct 'enum' argument to 'Enum.HasFlag' + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Info| +|CodeFix|False| + +### Rule description + +'Enum.HasFlag' method expects the 'enum' argument to be of the same 'enum' type as the instance on which the method is invoked and that this 'enum' is marked with 'System.FlagsAttribute'. If these are different 'enum' types, an unhandled exception will be thrown at runtime. If the 'enum' type is not marked with 'System.FlagsAttribute' the call will always return 'false' at runtime. + +## [CA2249](https://docs.microsoft.com/visualstudio/code-quality/ca2249): Consider using 'string.Contains' instead of 'string.IndexOf' + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|True| +|Severity|Info| +|CodeFix|True| + +### Rule description + +Calls to 'string.IndexOf' where the result is used to check for the presence/absence of a substring can be replaced by 'string.Contains'. + +## [CA2300](https://docs.microsoft.com/visualstudio/code-quality/ca2300): Do not use insecure deserializer BinaryFormatter + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2301](https://docs.microsoft.com/visualstudio/code-quality/ca2301): Do not call BinaryFormatter.Deserialize without first setting BinaryFormatter.Binder + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. + +## [CA2302](https://docs.microsoft.com/visualstudio/code-quality/ca2302): Ensure BinaryFormatter.Binder is set before calling BinaryFormatter.Deserialize + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. + +## [CA2305](https://docs.microsoft.com/visualstudio/code-quality/ca2305): Do not use insecure deserializer LosFormatter + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The method '{0}' is insecure when deserializing untrusted data. + +## [CA2310](https://docs.microsoft.com/visualstudio/code-quality/ca2310): Do not use insecure deserializer NetDataContractSerializer + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2311](https://docs.microsoft.com/visualstudio/code-quality/ca2311): Do not deserialize without first setting NetDataContractSerializer.Binder + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. + +## [CA2312](https://docs.microsoft.com/visualstudio/code-quality/ca2312): Ensure NetDataContractSerializer.Binder is set before deserializing + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. + +## [CA2315](https://docs.microsoft.com/visualstudio/code-quality/ca2315): Do not use insecure deserializer ObjectStateFormatter + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The method '{0}' is insecure when deserializing untrusted data. + +## [CA2321](https://docs.microsoft.com/visualstudio/code-quality/ca2321): Do not deserialize with JavaScriptSerializer using a SimpleTypeResolver + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2322](https://docs.microsoft.com/visualstudio/code-quality/ca2322): Ensure JavaScriptSerializer is not initialized with SimpleTypeResolver before deserializing + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2326](https://docs.microsoft.com/visualstudio/code-quality/ca2326): Do not use TypeNameHandling values other than None + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2327](https://docs.microsoft.com/visualstudio/code-quality/ca2327): Do not use insecure JsonSerializerSettings + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2328](https://docs.microsoft.com/visualstudio/code-quality/ca2328): Ensure that JsonSerializerSettings are secure + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2329](https://docs.microsoft.com/visualstudio/code-quality/ca2329): Do not deserialize with JsonSerializer using an insecure configuration + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2330](https://docs.microsoft.com/visualstudio/code-quality/ca2330): Ensure that JsonSerializer has a secure configuration when deserializing + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA2350](https://docs.microsoft.com/visualstudio/code-quality/ca2350): Do not use DataTable.ReadXml() with untrusted data + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The method '{0}' is insecure when deserializing untrusted data + +## [CA2351](https://docs.microsoft.com/visualstudio/code-quality/ca2351): Do not use DataSet.ReadXml() with untrusted data + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The method '{0}' is insecure when deserializing untrusted data + +## [CA2352](https://docs.microsoft.com/visualstudio/code-quality/ca2352): Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. + +## [CA2353](https://docs.microsoft.com/visualstudio/code-quality/ca2353): Unsafe DataSet or DataTable in serializable type + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0} + +## [CA2354](https://docs.microsoft.com/visualstudio/code-quality/ca2354): Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0} + +## [CA2355](https://docs.microsoft.com/visualstudio/code-quality/ca2355): Unsafe DataSet or DataTable type found in deserializable object graph + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0} + +## [CA2356](https://docs.microsoft.com/visualstudio/code-quality/ca2356): Unsafe DataSet or DataTable type in web deserializable object graph + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0} + +## [CA2361](https://docs.microsoft.com/visualstudio/code-quality/ca2361): Ensure autogenerated class containing DataSet.ReadXml() is not used with untrusted data + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The method '{0}' is insecure when deserializing untrusted data. Make sure that autogenerated class containing the '{0}' call is not deserialized with untrusted data. + +## [CA2362](https://docs.microsoft.com/visualstudio/code-quality/ca2362): Unsafe DataSet or DataTable in autogenerated serializable type can be vulnerable to remote code execution attacks + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. Ensure that the autogenerated type is never deserialized with untrusted data. + +## [CA3001](https://docs.microsoft.com/visualstudio/code-quality/ca3001): Review code for SQL injection vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Potential SQL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. + +## [CA3002](https://docs.microsoft.com/visualstudio/code-quality/ca3002): Review code for XSS vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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}'. + +## [CA3003](https://docs.microsoft.com/visualstudio/code-quality/ca3003): Review code for file path injection vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Potential file path injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. + +## [CA3004](https://docs.microsoft.com/visualstudio/code-quality/ca3004): Review code for information disclosure vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Potential information disclosure vulnerability was found where '{0}' in method '{1}' may contain unintended information from '{2}' in method '{3}'. + +## [CA3005](https://docs.microsoft.com/visualstudio/code-quality/ca3005): Review code for LDAP injection vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Potential LDAP injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. + +## [CA3006](https://docs.microsoft.com/visualstudio/code-quality/ca3006): Review code for process command injection vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Potential process command injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. + +## [CA3007](https://docs.microsoft.com/visualstudio/code-quality/ca3007): Review code for open redirect vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Potential open redirect vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. + +## [CA3008](https://docs.microsoft.com/visualstudio/code-quality/ca3008): Review code for XPath injection vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Potential XPath injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. + +## [CA3009](https://docs.microsoft.com/visualstudio/code-quality/ca3009): Review code for XML injection vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Potential XML injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. + +## [CA3010](https://docs.microsoft.com/visualstudio/code-quality/ca3010): Review code for XAML injection vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Potential XAML injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. + +## [CA3011](https://docs.microsoft.com/visualstudio/code-quality/ca3011): Review code for DLL injection vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Potential DLL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. + +## [CA3012](https://docs.microsoft.com/visualstudio/code-quality/ca3012): Review code for regex injection vulnerabilities + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Potential regex injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. + +## [CA3061](https://docs.microsoft.com/visualstudio/code-quality/ca3061): Do Not Add Schema By URL + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +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. + +## [CA3075](https://docs.microsoft.com/visualstudio/code-quality/ca3075): Insecure DTD processing in XML + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +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.  + +## [CA3076](https://docs.microsoft.com/visualstudio/code-quality/ca3076): Insecure XSLT script processing. + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +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. + +## [CA3077](https://docs.microsoft.com/visualstudio/code-quality/ca3077): Insecure Processing in API Design, XmlDocument and XmlTextReader + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +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.  + +## [CA3147](https://docs.microsoft.com/visualstudio/code-quality/ca3147): Mark Verb Handlers With Validate Antiforgery Token + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +Missing ValidateAntiForgeryTokenAttribute on controller action {0} + +## [CA5350](https://docs.microsoft.com/visualstudio/code-quality/ca5350): Do Not Use Weak Cryptographic Algorithms + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +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. + +## [CA5351](https://docs.microsoft.com/visualstudio/code-quality/ca5351): Do Not Use Broken Cryptographic Algorithms + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +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. + +## [CA5358](https://docs.microsoft.com/visualstudio/code-quality/ca5358): Review cipher mode usage with cryptography experts + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +These cipher modes might be vulnerable to attacks. Consider using recommended modes (CBC, CTS). + +## [CA5359](https://docs.microsoft.com/visualstudio/code-quality/ca5359): Do Not Disable Certificate Validation + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +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. + +## [CA5360](https://docs.microsoft.com/visualstudio/code-quality/ca5360): Do Not Call Dangerous Methods In Deserialization + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +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. + +## [CA5361](https://docs.microsoft.com/visualstudio/code-quality/ca5361): Do Not Disable SChannel Use of Strong Crypto + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5362](https://docs.microsoft.com/visualstudio/code-quality/ca5362): Potential reference cycle in deserialized object graph + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Review code that processes untrusted deserialized data for handling of unexpected reference cycles. An unexpected reference cycle should not cause the code to enter an infinite loop. Otherwise, an unexpected reference cycle can allow an attacker to DOS or exhaust the memory of the process when deserializing untrusted data. + +## [CA5363](https://docs.microsoft.com/visualstudio/code-quality/ca5363): Do Not Disable Request Validation + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +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. + +## [CA5364](https://docs.microsoft.com/visualstudio/code-quality/ca5364): Do Not Use Deprecated Security Protocols + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +Using a deprecated security protocol rather than the system default is risky. + +## [CA5365](https://docs.microsoft.com/visualstudio/code-quality/ca5365): Do Not Disable HTTP Header Checking + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +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. + +## [CA5366](https://docs.microsoft.com/visualstudio/code-quality/ca5366): Use XmlReader For DataSet Read Xml + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +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. + +## [CA5367](https://docs.microsoft.com/visualstudio/code-quality/ca5367): Do Not Serialize Types With Pointer Fields + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5368](https://docs.microsoft.com/visualstudio/code-quality/ca5368): Set ViewStateUserKey For Classes Derived From Page + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +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. + +## [CA5369](https://docs.microsoft.com/visualstudio/code-quality/ca5369): Use XmlReader For Deserialize + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +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. + +## [CA5370](https://docs.microsoft.com/visualstudio/code-quality/ca5370): Use XmlReader For Validating Reader + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +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. + +## [CA5371](https://docs.microsoft.com/visualstudio/code-quality/ca5371): Use XmlReader For Schema Read + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +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. + +## [CA5372](https://docs.microsoft.com/visualstudio/code-quality/ca5372): Use XmlReader For XPathDocument + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +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. + +## [CA5373](https://docs.microsoft.com/visualstudio/code-quality/ca5373): Do not use obsolete key derivation function + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +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. + +## [CA5374](https://docs.microsoft.com/visualstudio/code-quality/ca5374): Do Not Use XslTransform + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +Do not use XslTransform. It does not restrict potentially dangerous external references. + +## [CA5375](https://docs.microsoft.com/visualstudio/code-quality/ca5375): Do Not Use Account Shared Access Signature + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5376](https://docs.microsoft.com/visualstudio/code-quality/ca5376): Use SharedAccessProtocol HttpsOnly + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +HTTPS encrypts network traffic. Use HttpsOnly, rather than HttpOrHttps, to ensure network traffic is always encrypted to help prevent disclosure of sensitive data. + +## [CA5377](https://docs.microsoft.com/visualstudio/code-quality/ca5377): Use Container Level Access Policy + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +No access policy identifier is specified, making tokens non-revocable. + +## [CA5378](https://docs.microsoft.com/visualstudio/code-quality/ca5378): Do not disable ServicePointManagerSecurityProtocols + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5379](https://docs.microsoft.com/visualstudio/code-quality/ca5379): Do Not Use Weak Key Derivation Function Algorithm + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +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. + +## [CA5380](https://docs.microsoft.com/visualstudio/code-quality/ca5380): Do Not Add Certificates To Root Store + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5381](https://docs.microsoft.com/visualstudio/code-quality/ca5381): Ensure Certificates Are Not Added To Root Store + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5382](https://docs.microsoft.com/visualstudio/code-quality/ca5382): Use Secure Cookies In ASP.Net Core + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Applications available over HTTPS must use secure cookies. + +## [CA5383](https://docs.microsoft.com/visualstudio/code-quality/ca5383): Ensure Use Secure Cookies In ASP.Net Core + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Applications available over HTTPS must use secure cookies. + +## [CA5384](https://docs.microsoft.com/visualstudio/code-quality/ca5384): Do Not Use Digital Signature Algorithm (DSA) + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +DSA is too weak to use. + +## [CA5385](https://docs.microsoft.com/visualstudio/code-quality/ca5385): Use Rivest–Shamir–Adleman (RSA) Algorithm With Sufficient Key Size + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +Encryption algorithms are vulnerable to brute force attacks when too small a key size is used. + +## [CA5386](https://docs.microsoft.com/visualstudio/code-quality/ca5386): Avoid hardcoding SecurityProtocolType value + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Avoid hardcoding SecurityProtocolType {0}, and instead use SecurityProtocolType.SystemDefault to allow the operating system to choose the best Transport Layer Security protocol to use. + +## [CA5387](https://docs.microsoft.com/visualstudio/code-quality/ca5387): Do Not Use Weak Key Derivation Function With Insufficient Iteration Count + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). + +## [CA5388](https://docs.microsoft.com/visualstudio/code-quality/ca5388): Ensure Sufficient Iteration Count When Using Weak Key Derivation Function + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). + +## [CA5389](https://docs.microsoft.com/visualstudio/code-quality/ca5389): Do Not Add Archive Item's Path To The Target File System Path + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5390](https://docs.microsoft.com/visualstudio/code-quality/ca5390): Do not hard-code encryption key + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hard-coded value. + +## [CA5391](https://docs.microsoft.com/visualstudio/code-quality/ca5391): Use antiforgery tokens in ASP.NET Core MVC controllers + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5392](https://docs.microsoft.com/visualstudio/code-quality/ca5392): Use DefaultDllImportSearchPaths attribute for P/Invokes + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5393](https://docs.microsoft.com/visualstudio/code-quality/ca5393): Do not use unsafe DllImportSearchPath value + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5394](https://docs.microsoft.com/visualstudio/code-quality/ca5394): Do not use insecure randomness + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security-sensitive value will be generated. Use a cryptographically strong random number generator if an unpredictable value is required, or ensure that weak pseudo-random numbers aren't used in a security-sensitive manner. + +## [CA5395](https://docs.microsoft.com/visualstudio/code-quality/ca5395): Miss HttpVerb attribute for action methods + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5396](https://docs.microsoft.com/visualstudio/code-quality/ca5396): Set HttpOnly to true for HttpCookie + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5397](https://docs.microsoft.com/visualstudio/code-quality/ca5397): Do not use deprecated SslProtocols values + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|True| +|Severity|Hidden| +|CodeFix|False| + +### Rule description + +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. + +## [CA5398](https://docs.microsoft.com/visualstudio/code-quality/ca5398): Avoid hardcoded SslProtocols values + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5399](https://docs.microsoft.com/visualstudio/code-quality/ca5399): HttpClients should enable certificate revocation list checks + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5400](https://docs.microsoft.com/visualstudio/code-quality/ca5400): Ensure HttpClient certificate revocation list check is not disabled + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +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. + +## [CA5401](https://docs.microsoft.com/visualstudio/code-quality/ca5401): Do not use CreateEncryptor with non-default IV + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Symmetric encryption should always use a non-repeatable initialization vector to prevent dictionary attacks. + +## [CA5402](https://docs.microsoft.com/visualstudio/code-quality/ca5402): Use CreateEncryptor with the default IV + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Symmetric encryption should always use a non-repeatable initialization vector to prevent dictionary attacks. + +## [CA5403](https://docs.microsoft.com/visualstudio/code-quality/ca5403): Do not hard-code certificate + +|Item|Value| +|-|-| +|Category|Security| +|Enabled|False| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Hard-coded certificates in source code are vulnerable to being exploited. + +## [IL3000](https://docs.microsoft.com/visualstudio/code-quality/il3000): Avoid using accessing Assembly file path when publishing as a single-file + +|Item|Value| +|-|-| +|Category|Publish| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +'{0}' always returns an empty string for assemblies embedded in a single-file app. If the path to the app directory is needed, consider calling 'System.AppContext.BaseDirectory'. + +## [IL3001](https://docs.microsoft.com/visualstudio/code-quality/il3001): Avoid using accessing Assembly file path when publishing as a single-file + +|Item|Value| +|-|-| +|Category|Publish| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +'{0}' will throw for assemblies embedded in a single-file app -Rule ID | Title | Category | Enabled | Severity | CodeFix | Description | ---------|-------|----------|---------|----------|---------|--------------------------------------------------------------------------------------------------------------| -[CA1000](https://docs.microsoft.com/visualstudio/code-quality/ca1000) | Do not declare static members on generic types | Design | True | Hidden | False | When a static member of a generic type is called, the type argument must be specified for the type. When a generic instance member that does not support inference is called, the type argument must be specified for the member. In these two cases, the syntax for specifying the type argument is different and easily confused. | -[CA1001](https://docs.microsoft.com/visualstudio/code-quality/ca1001) | Types that own disposable fields should be disposable | Design | True | Hidden | True | A class declares and implements an instance field that is a System.IDisposable type, and the class does not implement IDisposable. A class that declares an IDisposable field indirectly owns an unmanaged resource and should implement the IDisposable interface. | -[CA1002](https://docs.microsoft.com/visualstudio/code-quality/ca1002) | Do not expose generic lists | Design | False | Warning | False | System.Collections.Generic.List is a generic collection that's designed for performance and not inheritance. List does not contain virtual members that make it easier to change the behavior of an inherited class. | -[CA1003](https://docs.microsoft.com/visualstudio/code-quality/ca1003) | Use generic event handler instances | Design | False | Warning | False | A type contains an event that declares an EventHandler delegate that returns void, whose signature contains two parameters (the first an object and the second a type that is assignable to EventArgs), and the containing assembly targets Microsoft .NET Framework?2.0. | -[CA1005](https://docs.microsoft.com/visualstudio/code-quality/ca1005) | Avoid excessive parameters on generic types | Design | False | Warning | False | The more type parameters a generic type contains, the more difficult it is to know and remember what each type parameter represents. | -[CA1008](https://docs.microsoft.com/visualstudio/code-quality/ca1008) | Enums should have zero value | Design | False | Warning | True | The default value of an uninitialized enumeration, just as other value types, is zero. A nonflags-attributed enumeration should define a member by using the value of zero so that the default value is a valid value of the enumeration. If an enumeration that has the FlagsAttribute attribute applied defines a zero-valued member, its name should be ""None"" to indicate that no values have been set in the enumeration. | -[CA1010](https://docs.microsoft.com/visualstudio/code-quality/ca1010) | Generic interface should also be implemented | Design | True | Hidden | False | To broaden the usability of a type, implement one of the generic interfaces. This is especially true for collections as they can then be used to populate generic collection types. | -[CA1012](https://docs.microsoft.com/visualstudio/code-quality/ca1012) | Abstract types should not have public constructors | Design | False | Warning | True | Constructors on abstract types can be called only by derived types. Because public constructors create instances of a type, and you cannot create instances of an abstract type, an abstract type that has a public constructor is incorrectly designed. | -[CA1014](https://docs.microsoft.com/visualstudio/code-quality/ca1014) | Mark assemblies with CLSCompliant | Design | False | Warning | False | The Common Language Specification (CLS) defines naming restrictions, data types, and rules to which assemblies must conform if they will be used across programming languages. Good design dictates that all assemblies explicitly indicate CLS compliance by using CLSCompliantAttribute . If this attribute is not present on an assembly, the assembly is not compliant. | -[CA1016](https://docs.microsoft.com/visualstudio/code-quality/ca1016) | Mark assemblies with assembly version | Design | True | Info | False | The .NET Framework uses the version number to uniquely identify an assembly, and to bind to types in strongly named assemblies. The version number is used together with version and publisher policy. By default, applications run only with the assembly version with which they were built. | -[CA1017](https://docs.microsoft.com/visualstudio/code-quality/ca1017) | Mark assemblies with ComVisible | Design | False | Warning | False | ComVisibleAttribute determines how COM clients access managed code. Good design dictates that assemblies explicitly indicate COM visibility. COM visibility can be set for the whole assembly and then overridden for individual types and type members. If this attribute is not present, the contents of the assembly are visible to COM clients. | -[CA1018](https://docs.microsoft.com/visualstudio/code-quality/ca1018) | Mark attributes with AttributeUsageAttribute | Design | True | Info | False | Specify AttributeUsage on {0}. | -[CA1019](https://docs.microsoft.com/visualstudio/code-quality/ca1019) | Define accessors for attribute arguments | Design | False | Warning | True | Remove the property setter from {0} or reduce its accessibility because it corresponds to positional argument {1}. | -[CA1021](https://docs.microsoft.com/visualstudio/code-quality/ca1021) | Avoid out parameters | Design | False | Warning | False | Passing types by reference (using 'out' or 'ref') requires experience with pointers, understanding how value types and reference types differ, and handling methods with multiple return values. Also, the difference between 'out' and 'ref' parameters is not widely understood. | -[CA1024](https://docs.microsoft.com/visualstudio/code-quality/ca1024) | Use properties where appropriate | Design | False | Warning | False | A public or protected method has a name that starts with ""Get"", takes no parameters, and returns a value that is not an array. The method might be a good candidate to become a property. | -[CA1027](https://docs.microsoft.com/visualstudio/code-quality/ca1027) | Mark enums with FlagsAttribute | Design | False | Warning | True | An enumeration is a value type that defines a set of related named constants. Apply FlagsAttribute to an enumeration when its named constants can be meaningfully combined. | -[CA1028](https://docs.microsoft.com/visualstudio/code-quality/ca1028) | Enum Storage should be Int32 | Design | False | Warning | True | An enumeration is a value type that defines a set of related named constants. By default, the System.Int32 data type is used to store the constant value. Although you can change this underlying type, it is not required or recommended for most scenarios. | -[CA1030](https://docs.microsoft.com/visualstudio/code-quality/ca1030) | Use events where appropriate | Design | False | Warning | False | This rule detects methods that have names that ordinarily would be used for events. If a method is called in response to a clearly defined state change, the method should be invoked by an event handler. Objects that call the method should raise events instead of calling the method directly. | -[CA1031](https://docs.microsoft.com/visualstudio/code-quality/ca1031) | Do not catch general exception types | Design | False | Warning | False | A general exception such as System.Exception or System.SystemException or a disallowed exception type is caught in a catch statement, or a general catch clause is used. General and disallowed exceptions should not be caught. | -[CA1032](https://docs.microsoft.com/visualstudio/code-quality/ca1032) | Implement standard exception constructors | Design | False | Warning | True | Failure to provide the full set of constructors can make it difficult to correctly handle exceptions. | -[CA1033](https://docs.microsoft.com/visualstudio/code-quality/ca1033) | Interface methods should be callable by child types | Design | False | Warning | True | An unsealed externally visible type provides an explicit method implementation of a public interface and does not provide an alternative externally visible method that has the same name. | -[CA1034](https://docs.microsoft.com/visualstudio/code-quality/ca1034) | Nested types should not be visible | Design | False | Warning | False | A nested type is a type that is declared in the scope of another type. Nested types are useful to encapsulate private implementation details of the containing type. Used for this purpose, nested types should not be externally visible. | -[CA1036](https://docs.microsoft.com/visualstudio/code-quality/ca1036) | Override methods on comparable types | Design | True | Hidden | True | A public or protected type implements the System.IComparable interface. It does not override Object.Equals nor does it overload the language-specific operator for equality, inequality, less than, less than or equal, greater than or greater than or equal. | -[CA1040](https://docs.microsoft.com/visualstudio/code-quality/ca1040) | Avoid empty interfaces | Design | False | Warning | False | Interfaces define members that provide a behavior or usage contract. The functionality that is described by the interface can be adopted by any type, regardless of where the type appears in the inheritance hierarchy. A type implements an interface by providing implementations for the members of the interface. An empty interface does not define any members; therefore, it does not define a contract that can be implemented. | -[CA1041](https://docs.microsoft.com/visualstudio/code-quality/ca1041) | Provide ObsoleteAttribute message | Design | True | Info | False | A type or member is marked by using a System.ObsoleteAttribute attribute that does not have its ObsoleteAttribute.Message property specified. When a type or member that is marked by using ObsoleteAttribute is compiled, the Message property of the attribute is displayed. This gives the user information about the obsolete type or member. | -[CA1043](https://docs.microsoft.com/visualstudio/code-quality/ca1043) | Use Integral Or String Argument For Indexers | Design | False | Warning | False | Indexers, that is, indexed properties, should use integer or string types for the index. These types are typically used for indexing data structures and increase the usability of the library. Use of the Object type should be restricted to those cases where the specific integer or string type cannot be specified at design time. If the design requires other types for the index, reconsider whether the type represents a logical data store. If it does not represent a logical data store, use a method. | -[CA1044](https://docs.microsoft.com/visualstudio/code-quality/ca1044) | Properties should not be write only | Design | False | Warning | False | Although it is acceptable and often necessary to have a read-only property, the design guidelines prohibit the use of write-only properties. This is because letting a user set a value, and then preventing the user from viewing that value, does not provide any security. Also, without read access, the state of shared objects cannot be viewed, which limits their usefulness. | -[CA1045](https://docs.microsoft.com/visualstudio/code-quality/ca1045) | Do not pass types by reference | Design | False | Warning | False | Passing types by reference (using out or ref) requires experience with pointers, understanding how value types and reference types differ, and handling methods that have multiple return values. Also, the difference between out and ref parameters is not widely understood. | -[CA1046](https://docs.microsoft.com/visualstudio/code-quality/ca1046) | Do not overload equality operator on reference types | Design | False | Warning | False | For reference types, the default implementation of the equality operator is almost always correct. By default, two references are equal only if they point to the same object. If the operator is providing meaningful value equality, the type should implement the generic 'System.IEquatable' interface. | -[CA1047](https://docs.microsoft.com/visualstudio/code-quality/ca1047) | Do not declare protected member in sealed type | Design | True | Info | False | Types declare protected members so that inheriting types can access or override the member. By definition, you cannot inherit from a sealed type, which means that protected methods on sealed types cannot be called. | -[CA1050](https://docs.microsoft.com/visualstudio/code-quality/ca1050) | Declare types in namespaces | Design | True | Info | False | Types are declared in namespaces to prevent name collisions and as a way to organize related types in an object hierarchy. | -[CA1051](https://docs.microsoft.com/visualstudio/code-quality/ca1051) | Do not declare visible instance fields | Design | True | Hidden | False | The primary use of a field should be as an implementation detail. Fields should be private or internal and should be exposed by using properties. | -[CA1052](https://docs.microsoft.com/visualstudio/code-quality/ca1052) | Static holder types should be Static or NotInheritable | Design | False | Warning | True | Type '{0}' is a static holder type but is neither static nor NotInheritable | -[CA1054](https://docs.microsoft.com/visualstudio/code-quality/ca1054) | Uri parameters should not be strings | Design | False | Warning | True | If a method takes a string representation of a URI, a corresponding overload should be provided that takes an instance of the URI class, which provides these services in a safe and secure manner. | -[CA1055](https://docs.microsoft.com/visualstudio/code-quality/ca1055) | Uri return values should not be strings | Design | False | Warning | False | This rule assumes that the method returns a URI. A string representation of a URI is prone to parsing and encoding errors, and can lead to security vulnerabilities. The System.Uri class provides these services in a safe and secure manner. | -[CA1056](https://docs.microsoft.com/visualstudio/code-quality/ca1056) | Uri properties should not be strings | Design | False | Warning | False | This rule assumes that the property represents a Uniform Resource Identifier (URI). A string representation of a URI is prone to parsing and encoding errors, and can lead to security vulnerabilities. The System.Uri class provides these services in a safe and secure manner. | -[CA1058](https://docs.microsoft.com/visualstudio/code-quality/ca1058) | Types should not extend certain base types | Design | False | Warning | False | An externally visible type extends certain base types. Use one of the alternatives. | -[CA1060](https://docs.microsoft.com/visualstudio/code-quality/ca1060) | Move pinvokes to native methods class | Design | False | Warning | False | Platform Invocation methods, such as those that are marked by using the System.Runtime.InteropServices.DllImportAttribute attribute, or methods that are defined by using the Declare keyword in Visual Basic, access unmanaged code. These methods should be of the NativeMethods, SafeNativeMethods, or UnsafeNativeMethods class. | -[CA1061](https://docs.microsoft.com/visualstudio/code-quality/ca1061) | Do not hide base class methods | Design | True | Info | False | A method in a base type is hidden by an identically named method in a derived type when the parameter signature of the derived method differs only by types that are more weakly derived than the corresponding types in the parameter signature of the base method. | -[CA1062](https://docs.microsoft.com/visualstudio/code-quality/ca1062) | Validate arguments of public methods | Design | False | Warning | False | An externally visible method dereferences one of its reference arguments without verifying whether that argument is null (Nothing in Visual Basic). All reference arguments that are passed to externally visible methods should be checked against null. If appropriate, throw an ArgumentNullException when the argument is null or add a Code Contract precondition asserting non-null argument. If the method is designed to be called only by known assemblies, you should make the method internal. | -[CA1063](https://docs.microsoft.com/visualstudio/code-quality/ca1063) | Implement IDisposable Correctly | Design | False | Warning | False | All IDisposable types should implement the Dispose pattern correctly. | -[CA1064](https://docs.microsoft.com/visualstudio/code-quality/ca1064) | Exceptions should be public | Design | False | Warning | True | An internal exception is visible only inside its own internal scope. After the exception falls outside the internal scope, only the base exception can be used to catch the exception. If the internal exception is inherited from T:System.Exception, T:System.SystemException, or T:System.ApplicationException, the external code will not have sufficient information to know what to do with the exception. | -[CA1065](https://docs.microsoft.com/visualstudio/code-quality/ca1065) | Do not raise exceptions in unexpected locations | Design | False | Warning | False | A method that is not expected to throw exceptions throws an exception. | -[CA1066](https://docs.microsoft.com/visualstudio/code-quality/ca1066) | Implement IEquatable when overriding Object.Equals | Design | False | Warning | True | When a type T overrides Object.Equals(object), the implementation must cast the object argument to the correct type T before performing the comparison. If the type implements IEquatable, and therefore offers the method T.Equals(T), and if the argument is known at compile time to be of type T, then the compiler can call IEquatable.Equals(T) instead of Object.Equals(object), and no cast is necessary, improving performance. | -[CA1067](https://docs.microsoft.com/visualstudio/code-quality/ca1067) | Override Object.Equals(object) when implementing IEquatable | Design | True | Info | True | When a type T implements the interface IEquatable, it suggests to a user who sees a call to the Equals method in source code that an instance of the type can be equated with an instance of any other type. The user might be confused if their attempt to equate the type with an instance of another type fails to compile. This violates the "principle of least surprise". | -[CA1068](https://docs.microsoft.com/visualstudio/code-quality/ca1068) | CancellationToken parameters must come last | Design | True | Info | False | Method '{0}' should take CancellationToken as the last parameter | -[CA1069](https://docs.microsoft.com/visualstudio/code-quality/ca1069) | Enums values should not be duplicated | Design | True | Info | False | The field reference '{0}' is duplicated in this bitwise initialization. | -[CA1070](https://docs.microsoft.com/visualstudio/code-quality/ca1070) | Do not declare event fields as virtual | Design | True | Info | False | Do not declare virtual events in a base class. Overridden events in a derived class have undefined behavior. The C# compiler does not handle this correctly and it is unpredictable whether a subscriber to the derived event will actually be subscribing to the base class event. | -[CA1200](https://docs.microsoft.com/visualstudio/code-quality/ca1200) | Avoid using cref tags with a prefix | Documentation | True | Hidden | False | Use of cref tags with prefixes should be avoided, since it prevents the compiler from verifying references and the IDE from updating references during refactorings. It is permissible to suppress this error at a single documentation site if the cref must use a prefix because the type being mentioned is not findable by the compiler. For example, if a cref is mentioning a special attribute in the full framework but you're in a file that compiles against the portable framework, or if you want to reference a type at higher layer of Roslyn, you should suppress the error. You should not suppress the error just because you want to take a shortcut and avoid using the full syntax. | -[CA1303](https://docs.microsoft.com/visualstudio/code-quality/ca1303) | Do not pass literals as localized parameters | Globalization | False | Warning | False | A method passes a string literal as a parameter to a constructor or method in the .NET Framework class library and that string should be localizable. To fix a violation of this rule, replace the string literal with a string retrieved through an instance of the ResourceManager class. | -[CA1304](https://docs.microsoft.com/visualstudio/code-quality/ca1304) | Specify CultureInfo | Globalization | True | Hidden | False | A method or constructor calls a member that has an overload that accepts a System.Globalization.CultureInfo parameter, and the method or constructor does not call the overload that takes the CultureInfo parameter. When a CultureInfo or System.IFormatProvider object is not supplied, the default value that is supplied by the overloaded member might not have the effect that you want in all locales. If the result will be displayed to the user, specify 'CultureInfo.CurrentCulture' as the 'CultureInfo' parameter. Otherwise, if the result will be stored and accessed by software, such as when it is persisted to disk or to a database, specify 'CultureInfo.InvariantCulture'. | -[CA1305](https://docs.microsoft.com/visualstudio/code-quality/ca1305) | Specify IFormatProvider | Globalization | True | Hidden | False | A method or constructor calls one or more members that have overloads that accept a System.IFormatProvider parameter, and the method or constructor does not call the overload that takes the IFormatProvider parameter. When a System.Globalization.CultureInfo or IFormatProvider object is not supplied, the default value that is supplied by the overloaded member might not have the effect that you want in all locales. If the result will be based on the input from/output displayed to the user, specify 'CultureInfo.CurrentCulture' as the 'IFormatProvider'. Otherwise, if the result will be stored and accessed by software, such as when it is loaded from disk/database and when it is persisted to disk/database, specify 'CultureInfo.InvariantCulture' | -[CA1307](https://docs.microsoft.com/visualstudio/code-quality/ca1307) | Specify StringComparison | Globalization | True | Hidden | False | A string comparison operation uses a method overload that does not set a StringComparison parameter. If the result will be displayed to the user, such as when sorting a list of items for display in a list box, specify 'StringComparison.CurrentCulture' or 'StringComparison.CurrentCultureIgnoreCase' as the 'StringComparison' parameter. If comparing case-insensitive identifiers, such as file paths, environment variables, or registry keys and values, specify 'StringComparison.OrdinalIgnoreCase'. Otherwise, if comparing case-sensitive identifiers, specify 'StringComparison.Ordinal'. | -[CA1308](https://docs.microsoft.com/visualstudio/code-quality/ca1308) | Normalize strings to uppercase | Globalization | False | Warning | False | Strings should be normalized to uppercase. A small group of characters cannot make a round trip when they are converted to lowercase. To make a round trip means to convert the characters from one locale to another locale that represents character data differently, and then to accurately retrieve the original characters from the converted characters. | -[CA1309](https://docs.microsoft.com/visualstudio/code-quality/ca1309) | Use ordinal stringcomparison | Globalization | True | Hidden | True | A string comparison operation that is nonlinguistic does not set the StringComparison parameter to either Ordinal or OrdinalIgnoreCase. By explicitly setting the parameter to either StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase, your code often gains speed, becomes more correct, and becomes more reliable. | -[CA1401](https://docs.microsoft.com/visualstudio/code-quality/ca1401) | P/Invokes should not be visible | Interoperability | True | Info | False | A public or protected method in a public type has the System.Runtime.InteropServices.DllImportAttribute attribute (also implemented by the Declare keyword in Visual Basic). Such methods should not be exposed. | -[CA1501](https://docs.microsoft.com/visualstudio/code-quality/ca1501) | Avoid excessive inheritance | Maintainability | False | Warning | False | Deeply nested type hierarchies can be difficult to follow, understand, and maintain. This rule limits analysis to hierarchies in the same module. To fix a violation of this rule, derive the type from a base type that is less deep in the inheritance hierarchy or eliminate some of the intermediate base types. | -[CA1502](https://docs.microsoft.com/visualstudio/code-quality/ca1502) | Avoid excessive complexity | Maintainability | False | Warning | False | Cyclomatic complexity measures the number of linearly independent paths through the method, which is determined by the number and complexity of conditional branches. A low cyclomatic complexity generally indicates a method that is easy to understand, test, and maintain. The cyclomatic complexity is calculated from a control flow graph of the method and is given as follows: `cyclomatic complexity = the number of edges - the number of nodes + 1`, where a node represents a logic branch point and an edge represents a line between nodes. | -[CA1505](https://docs.microsoft.com/visualstudio/code-quality/ca1505) | Avoid unmaintainable code | Maintainability | False | Warning | False | The maintainability index is calculated by using the following metrics: lines of code, program volume, and cyclomatic complexity. Program volume is a measure of the difficulty of understanding of a symbol that is based on the number of operators and operands in the code. Cyclomatic complexity is a measure of the structural complexity of the type or method. A low maintainability index indicates that code is probably difficult to maintain and would be a good candidate to redesign. | -[CA1506](https://docs.microsoft.com/visualstudio/code-quality/ca1506) | Avoid excessive class coupling | Maintainability | False | Warning | False | This rule measures class coupling by counting the number of unique type references that a symbol contains. Symbols that have a high degree of class coupling can be difficult to maintain. It is a good practice to have types and methods that exhibit low coupling and high cohesion. To fix this violation, try to redesign the code to reduce the number of types to which it is coupled. | -[CA1507](https://docs.microsoft.com/visualstudio/code-quality/ca1507) | Use nameof to express symbol names | Maintainability | True | Info | True | Using nameof helps keep your code valid when refactoring. | -[CA1508](https://docs.microsoft.com/visualstudio/code-quality/ca1508) | Avoid dead conditional code | Maintainability | False | Warning | False | '{0}' is never '{1}'. Remove or refactor the condition(s) to avoid dead code. | -[CA1509](https://docs.microsoft.com/visualstudio/code-quality/ca1509) | Invalid entry in code metrics rule specification file | Maintainability | False | Warning | False | Invalid entry in code metrics rule specification file | -[CA1700](https://docs.microsoft.com/visualstudio/code-quality/ca1700) | Do not name enum values 'Reserved' | Naming | False | Warning | False | This rule assumes that an enumeration member that has a name that contains "reserved" is not currently used but is a placeholder to be renamed or removed in a future version. Renaming or removing a member is a breaking change. | -[CA1707](https://docs.microsoft.com/visualstudio/code-quality/ca1707) | Identifiers should not contain underscores | Naming | True | Hidden | False | By convention, identifier names do not contain the underscore (_) character. This rule checks namespaces, types, members, and parameters. | -[CA1708](https://docs.microsoft.com/visualstudio/code-quality/ca1708) | Identifiers should differ by more than case | Naming | True | Hidden | False | Identifiers for namespaces, types, members, and parameters cannot differ only by case because languages that target the common language runtime are not required to be case-sensitive. | -[CA1710](https://docs.microsoft.com/visualstudio/code-quality/ca1710) | Identifiers should have correct suffix | Naming | True | Hidden | False | By convention, the names of types that extend certain base types or that implement certain interfaces, or types that are derived from these types, have a suffix that is associated with the base type or interface. | -[CA1711](https://docs.microsoft.com/visualstudio/code-quality/ca1711) | Identifiers should not have incorrect suffix | Naming | True | Hidden | False | By convention, only the names of types that extend certain base types or that implement certain interfaces, or types that are derived from these types, should end with specific reserved suffixes. Other type names should not use these reserved suffixes. | -[CA1712](https://docs.microsoft.com/visualstudio/code-quality/ca1712) | Do not prefix enum values with type name | Naming | True | Hidden | False | An enumeration's values should not start with the type name of the enumeration. | -[CA1713](https://docs.microsoft.com/visualstudio/code-quality/ca1713) | Events should not have 'Before' or 'After' prefix | Naming | False | Warning | False | Event names should describe the action that raises the event. To name related events that are raised in a specific sequence, use the present or past tense to indicate the relative position in the sequence of actions. For example, when naming a pair of events that is raised when closing a resource, you might name it 'Closing' and 'Closed', instead of 'BeforeClose' and 'AfterClose'. | -[CA1715](https://docs.microsoft.com/visualstudio/code-quality/ca1715) | Identifiers should have correct prefix | Naming | True | Hidden | False | Identifiers should have correct prefix | -[CA1716](https://docs.microsoft.com/visualstudio/code-quality/ca1716) | Identifiers should not match keywords | Naming | True | Hidden | False | A namespace name or a type name matches a reserved keyword in a programming language. Identifiers for namespaces and types should not match keywords that are defined by languages that target the common language runtime. | -[CA1720](https://docs.microsoft.com/visualstudio/code-quality/ca1720) | Identifier contains type name | Naming | True | Hidden | False | Names of parameters and members are better used to communicate their meaning than to describe their type, which is expected to be provided by development tools. For names of members, if a data type name must be used, use a language-independent name instead of a language-specific one. | -[CA1721](https://docs.microsoft.com/visualstudio/code-quality/ca1721) | Property names should not match get methods | Naming | False | Warning | False | The name of a public or protected member starts with ""Get"" and otherwise matches the name of a public or protected property. ""Get"" methods and properties should have names that clearly distinguish their function. | -[CA1724](https://docs.microsoft.com/visualstudio/code-quality/ca1724) | Type names should not match namespaces | Naming | False | Warning | False | Type names should not match the names of namespaces that are defined in the .NET Framework class library. Violating this rule can reduce the usability of the library. | -[CA1725](https://docs.microsoft.com/visualstudio/code-quality/ca1725) | Parameter names should match base declaration | Naming | True | Hidden | True | Consistent naming of parameters in an override hierarchy increases the usability of the method overrides. A parameter name in a derived method that differs from the name in the base declaration can cause confusion about whether the method is an override of the base method or a new overload of the method. | -[CA1801](https://docs.microsoft.com/visualstudio/code-quality/ca1801) | Review unused parameters | Usage | False | Warning | True | Avoid unused paramereters in your code. If the parameter cannot be removed, then change its name so it starts with an underscore and is optionally followed by an integer, such as '_', '_1', '_2', etc. These are treated as special discard symbol names. | -[CA1802](https://docs.microsoft.com/visualstudio/code-quality/ca1802) | Use literals where appropriate | Performance | False | Warning | True | A field is declared static and read-only (Shared and ReadOnly in Visual Basic), and is initialized by using a value that is computable at compile time. Because the value that is assigned to the targeted field is computable at compile time, change the declaration to a const (Const in Visual Basic) field so that the value is computed at compile time instead of at run?time. | -[CA1805](https://docs.microsoft.com/visualstudio/code-quality/ca1805) | Do not initialize unnecessarily | Performance | True | Info | True | The .NET runtime initializes all fields of reference types to their default values before running the constructor. In most cases, explicitly initializing a field to its default value in a constructor is redundant, adding maintenance costs and potentially degrading performance (such as with increased assembly size), and the explicit initialization can be removed. In some cases, such as with static readonly fields that permanently retain their default value, consider instead changing them to be constants or properties. | -[CA1806](https://docs.microsoft.com/visualstudio/code-quality/ca1806) | Do not ignore method results | Performance | True | Info | False | A new object is created but never used; or a method that creates and returns a new string is called and the new string is never used; or a COM or P/Invoke method returns an HRESULT or error code that is never used. | -[CA1810](https://docs.microsoft.com/visualstudio/code-quality/ca1810) | Initialize reference type static fields inline | Performance | False | Warning | False | A reference 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. | -[CA1812](https://docs.microsoft.com/visualstudio/code-quality/ca1812) | Avoid uninstantiated internal classes | Performance | False | Warning | False | An instance of an assembly-level type is not created by code in the assembly. | -[CA1813](https://docs.microsoft.com/visualstudio/code-quality/ca1813) | Avoid unsealed attributes | Performance | False | Warning | True | The .NET Framework class library provides methods for retrieving custom attributes. By default, these methods search the attribute inheritance hierarchy. Sealing the attribute eliminates the search through the inheritance hierarchy and can improve performance. | -[CA1814](https://docs.microsoft.com/visualstudio/code-quality/ca1814) | Prefer jagged arrays over multidimensional | Performance | False | Warning | False | A jagged array is an array whose elements are arrays. The arrays that make up the elements can be of different sizes, leading to less wasted space for some sets of data. | -[CA1815](https://docs.microsoft.com/visualstudio/code-quality/ca1815) | Override equals and operator equals on value types | Performance | False | Warning | True | For value types, the inherited implementation of Equals uses the Reflection library and compares the contents of all fields. Reflection is computationally expensive, and comparing every field for equality might be unnecessary. If you expect users to compare or sort instances, or to use instances as hash table keys, your value type should implement Equals. | -[CA1816](https://docs.microsoft.com/visualstudio/code-quality/ca1816) | Dispose methods should call SuppressFinalize | Usage | True | Info | False | A method that is an implementation of Dispose does not call GC.SuppressFinalize; or a method that is not an implementation of Dispose calls GC.SuppressFinalize; or a method calls GC.SuppressFinalize and passes something other than this (Me in Visual?Basic). | -[CA1819](https://docs.microsoft.com/visualstudio/code-quality/ca1819) | Properties should not return arrays | Performance | False | Warning | False | Arrays that are returned by properties are not write-protected, even when the property is read-only. To keep the array tamper-proof, the property must return a copy of the array. Typically, users will not understand the adverse performance implications of calling such a property. | -[CA1820](https://docs.microsoft.com/visualstudio/code-quality/ca1820) | Test for empty strings using string length | Performance | False | Warning | True | Comparing strings by using the String.Length property or the String.IsNullOrEmpty method is significantly faster than using Equals. | -[CA1821](https://docs.microsoft.com/visualstudio/code-quality/ca1821) | Remove empty Finalizers | Performance | True | Info | True | Finalizers should be avoided where possible, to avoid the additional performance overhead involved in tracking object lifetime. | -[CA1822](https://docs.microsoft.com/visualstudio/code-quality/ca1822) | Mark members as static | Performance | True | Info | True | Members that do not access instance data or call instance methods can be marked as static. After you mark the methods as static, the compiler will emit nonvirtual call sites to these members. This can give you a measurable performance gain for performance-sensitive code. | -[CA1823](https://docs.microsoft.com/visualstudio/code-quality/ca1823) | Avoid unused private fields | Performance | False | Warning | True | Private fields were detected that do not appear to be accessed in the assembly. | -[CA1824](https://docs.microsoft.com/visualstudio/code-quality/ca1824) | Mark assemblies with NeutralResourcesLanguageAttribute | Performance | True | Info | False | The NeutralResourcesLanguage attribute informs the ResourceManager of the language that was used to display the resources of a neutral culture for an assembly. This improves lookup performance for the first resource that you load and can reduce your working set. | -[CA1825](https://docs.microsoft.com/visualstudio/code-quality/ca1825) | Avoid zero-length array allocations. | Performance | True | Info | True | Avoid unnecessary zero-length array allocations. Use {0} instead. | -[CA1826](https://docs.microsoft.com/visualstudio/code-quality/ca1826) | Do not use Enumerable methods on indexable collections. Instead use the collection directly | Performance | True | Info | True | This collection is directly indexable. Going through LINQ here causes unnecessary allocations and CPU work. | -[CA1827](https://docs.microsoft.com/visualstudio/code-quality/ca1827) | Do not use Count() or LongCount() when Any() can be used | Performance | True | Info | 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. | -[CA1828](https://docs.microsoft.com/visualstudio/code-quality/ca1828) | Do not use CountAsync() or LongCountAsync() when AnyAsync() can be used | Performance | True | Info | 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. | -[CA1829](https://docs.microsoft.com/visualstudio/code-quality/ca1829) | Use Length/Count property instead of Count() when available | Performance | True | Info | True | Enumerable.Count() potentially enumerates the sequence while a Length/Count property is a direct access. | -[CA1830](https://docs.microsoft.com/visualstudio/code-quality/ca1830) | Prefer strongly-typed Append and Insert method overloads on StringBuilder. | Performance | True | Info | True | StringBuilder.Append and StringBuilder.Insert provide overloads for multiple types beyond System.String. When possible, prefer the strongly-typed overloads over using ToString() and the string-based overload. | -[CA1831](https://docs.microsoft.com/visualstudio/code-quality/ca1831) | Use AsSpan or AsMemory instead of Range-based indexers when appropriate | Performance | True | Warning | True | The Range-based indexer on string values produces a copy of requested portion of the string. This copy is usually unnecessary when it is implicitly used as a ReadOnlySpan or ReadOnlyMemory value. Use the AsSpan method to avoid the unnecessary copy. | -[CA1832](https://docs.microsoft.com/visualstudio/code-quality/ca1832) | Use AsSpan or AsMemory instead of Range-based indexers when appropriate | Performance | True | Info | True | The Range-based indexer on array values produces a copy of requested portion of the array. This copy is usually unnecessary when it is implicitly used as a ReadOnlySpan or ReadOnlyMemory value. Use the AsSpan method to avoid the unnecessary copy. | -[CA1833](https://docs.microsoft.com/visualstudio/code-quality/ca1833) | Use AsSpan or AsMemory instead of Range-based indexers when appropriate | Performance | True | Info | True | The Range-based indexer on array values produces a copy of requested portion of the array. This copy is often unwanted when it is implicitly used as a Span or Memory value. Use the AsSpan method to avoid the copy. | -[CA1834](https://docs.microsoft.com/visualstudio/code-quality/ca1834) | Consider using 'StringBuilder.Append(char)' when applicable. | Performance | True | Info | True | 'StringBuilder.Append(char)' is more efficient than 'StringBuilder.Append(string)' when the string is a single character. When calling 'Append' with a constant, prefer using a constant char rather than a constant string containing one character. | -[CA1835](https://docs.microsoft.com/visualstudio/code-quality/ca1835) | Prefer the 'Memory'-based overloads for 'ReadAsync' and 'WriteAsync' | Performance | True | Info | True | 'Stream' has a 'ReadAsync' overload that takes a 'Memory' as the first argument, and a 'WriteAsync' overload that takes a 'ReadOnlyMemory' as the first argument. Prefer calling the memory based overloads, which are more efficient. | -[CA1836](https://docs.microsoft.com/visualstudio/code-quality/ca1836) | Prefer IsEmpty over Count | Performance | True | Info | True | For determining whether the object contains or not any items, prefer using 'IsEmpty' property rather than retrieving the number of items from the 'Count' property and comparing it to 0 or 1. | -[CA2000](https://docs.microsoft.com/visualstudio/code-quality/ca2000) | Dispose objects before losing scope | Reliability | False | Warning | 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. | -[CA2002](https://docs.microsoft.com/visualstudio/code-quality/ca2002) | Do not lock on objects with weak identity | Reliability | False | Warning | 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. | -[CA2007](https://docs.microsoft.com/visualstudio/code-quality/ca2007) | Consider calling ConfigureAwait on the awaited task | Reliability | False | Warning | 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. | -[CA2008](https://docs.microsoft.com/visualstudio/code-quality/ca2008) | Do not create tasks without passing a TaskScheduler | Reliability | False | Warning | 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. | -[CA2009](https://docs.microsoft.com/visualstudio/code-quality/ca2009) | Do not call ToImmutableCollection on an ImmutableCollection value | Reliability | True | Info | True | Do not call {0} on an {1} value | -[CA2011](https://docs.microsoft.com/visualstudio/code-quality/ca2011) | Avoid infinite recursion | Reliability | True | Info | False | Do not assign the property within its setter. This call might result in an infinite recursion. | -[CA2012](https://docs.microsoft.com/visualstudio/code-quality/ca2012) | Use ValueTasks correctly | Reliability | True | Hidden | False | ValueTasks returned from member invocations are intended to be directly awaited. Attempts to consume a ValueTask multiple times or to directly access one's result before it's known to be completed may result in an exception or corruption. Ignoring such a ValueTask is likely an indication of a functional bug and may degrade performance. | -[CA2013](https://docs.microsoft.com/visualstudio/code-quality/ca2013) | Do not use ReferenceEquals with value types | Reliability | True | Warning | False | Value type typed arguments are uniquely boxed for each call to this method, therefore the result is always false. | -[CA2014](https://docs.microsoft.com/visualstudio/code-quality/ca2014) | Do not use stackalloc in loops. | Reliability | True | Warning | False | Stack space allocated by a stackalloc is only released at the end of the current method's invocation. Using it in a loop can result in unbounded stack growth and eventual stack overflow conditions. | -[CA2015](https://docs.microsoft.com/visualstudio/code-quality/ca2015) | Do not define finalizers for types derived from MemoryManager | Reliability | True | Warning | False | Adding a finalizer to a type derived from MemoryManager may permit memory to be freed while it is still in use by a Span. | -[CA2016](https://docs.microsoft.com/visualstudio/code-quality/ca2016) | Forward the 'CancellationToken' parameter to methods that take one | Reliability | True | Info | True | Forward the 'CancellationToken' parameter to methods that take one to ensure the operation cancellation notifications gets properly propagated, or pass in 'CancellationToken.None' explicitly to indicate intentionally not propagating the token. | -[CA2100](https://docs.microsoft.com/visualstudio/code-quality/ca2100) | Review SQL queries for security vulnerabilities | Security | False | Warning | 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. | -[CA2101](https://docs.microsoft.com/visualstudio/code-quality/ca2101) | Specify marshaling for P/Invoke string arguments | Globalization | True | Info | 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. | -[CA2109](https://docs.microsoft.com/visualstudio/code-quality/ca2109) | Review visible event handlers | Security | False | Warning | False | A public or protected event-handling method was detected. Event-handling methods should not be exposed unless absolutely necessary. | -[CA2119](https://docs.microsoft.com/visualstudio/code-quality/ca2119) | Seal methods that satisfy private interfaces | Security | False | Warning | 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. | -[CA2153](https://docs.microsoft.com/visualstudio/code-quality/ca2153) | Do Not Catch Corrupted State Exceptions | Security | False | Warning | 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 | -[CA2200](https://docs.microsoft.com/visualstudio/code-quality/ca2200) | Rethrow to preserve stack details. | Usage | True | Info | True | Re-throwing caught exception changes stack information. | -[CA2201](https://docs.microsoft.com/visualstudio/code-quality/ca2201) | Do not raise reserved exception types | Usage | True | Hidden | 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. | -[CA2207](https://docs.microsoft.com/visualstudio/code-quality/ca2207) | Initialize value type static fields inline | Usage | False | Warning | 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. | -[CA2208](https://docs.microsoft.com/visualstudio/code-quality/ca2208) | Instantiate argument exceptions correctly | Usage | True | Info | True | A call is made to the default (parameterless) constructor of an exception type that is or derives from ArgumentException, or an incorrect string argument is passed to a parameterized constructor of an exception type that is or derives from ArgumentException. | -[CA2211](https://docs.microsoft.com/visualstudio/code-quality/ca2211) | Non-constant fields should not be visible | Usage | True | Info | 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. | -[CA2213](https://docs.microsoft.com/visualstudio/code-quality/ca2213) | Disposable fields should be disposed | Usage | False | Warning | 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. | -[CA2214](https://docs.microsoft.com/visualstudio/code-quality/ca2214) | Do not call overridable methods in constructors | Usage | False | Warning | 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). | -[CA2215](https://docs.microsoft.com/visualstudio/code-quality/ca2215) | Dispose methods should call base class dispose | Usage | True | Hidden | True | A type that implements System.IDisposable inherits from a type that also implements IDisposable. The Dispose method of the inheriting type does not call the Dispose method of the parent type. To fix a violation of this rule, call base.Dispose in your Dispose method. | -[CA2216](https://docs.microsoft.com/visualstudio/code-quality/ca2216) | Disposable types should declare finalizer | Usage | False | Warning | 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. | -[CA2217](https://docs.microsoft.com/visualstudio/code-quality/ca2217) | Do not mark enums with FlagsAttribute | Usage | False | Warning | 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. | -[CA2218](https://docs.microsoft.com/visualstudio/code-quality/ca2218) | Override GetHashCode on overriding Equals | Usage | True | Info | 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. | -[CA2219](https://docs.microsoft.com/visualstudio/code-quality/ca2219) | Do not raise exceptions in finally clauses | Usage | True | Info | 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. | -[CA2224](https://docs.microsoft.com/visualstudio/code-quality/ca2224) | Override Equals on overloading operator equals | Usage | True | Info | True | A public type implements the equality operator but does not override Object.Equals. | -[CA2225](https://docs.microsoft.com/visualstudio/code-quality/ca2225) | Operator overloads have named alternates | Usage | False | Warning | 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. | -[CA2226](https://docs.microsoft.com/visualstudio/code-quality/ca2226) | Operators should have symmetrical overloads | Usage | False | Warning | True | A type implements the equality or inequality operator and does not implement the opposite operator. | -[CA2227](https://docs.microsoft.com/visualstudio/code-quality/ca2227) | Collection properties should be read only | Usage | False | Warning | 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. | -[CA2229](https://docs.microsoft.com/visualstudio/code-quality/ca2229) | Implement serialization constructors | Usage | True | Hidden | True | To fix a violation of this rule, implement the serialization constructor. For a sealed class, make the constructor private; otherwise, make it protected. | -[CA2231](https://docs.microsoft.com/visualstudio/code-quality/ca2231) | Overload operator equals on overriding value type Equals | Usage | True | Info | 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 | -[CA2234](https://docs.microsoft.com/visualstudio/code-quality/ca2234) | Pass system uri objects instead of strings | Usage | False | Warning | 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. | -[CA2235](https://docs.microsoft.com/visualstudio/code-quality/ca2235) | Mark all non-serializable fields | Usage | False | Warning | True | An instance field of a type that is not serializable is declared in a type that is serializable. | -[CA2237](https://docs.microsoft.com/visualstudio/code-quality/ca2237) | Mark ISerializable types with serializable | Usage | False | Warning | 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. | -[CA2241](https://docs.microsoft.com/visualstudio/code-quality/ca2241) | Provide correct arguments to formatting methods | Usage | True | Info | 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. | -[CA2242](https://docs.microsoft.com/visualstudio/code-quality/ca2242) | Test for NaN correctly | Usage | True | Info | True | This expression tests a value against Single.Nan or Double.Nan. Use Single.IsNan(Single) or Double.IsNan(Double) to test the value. | -[CA2243](https://docs.microsoft.com/visualstudio/code-quality/ca2243) | Attribute string literals should parse correctly | Usage | False | Warning | False | The string literal parameter of an attribute does not parse correctly for a URL, a GUID, or a version. | -[CA2244](https://docs.microsoft.com/visualstudio/code-quality/ca2244) | Do not duplicate indexed element initializations | Usage | True | Info | True | Indexed elements in objects initializers must initialize unique elements. A duplicate index might overwrite a previous element initialization. | -[CA2245](https://docs.microsoft.com/visualstudio/code-quality/ca2245) | Do not assign a property to itself. | Usage | True | Info | False | The property {0} should not be assigned to itself. | -[CA2246](https://docs.microsoft.com/visualstudio/code-quality/ca2246) | Assigning symbol and its member in the same statement. | Usage | True | Info | 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. | -[CA2247](https://docs.microsoft.com/visualstudio/code-quality/ca2247) | Argument passed to TaskCompletionSource constructor should be TaskCreationOptions enum instead of TaskContinuationOptions enum. | Usage | True | Warning | True | TaskCompletionSource has constructors that take TaskCreationOptions that control the underlying Task, and constructors that take object state that's stored in the task. Accidentally passing a TaskContinuationOptions instead of a TaskCreationOptions will result in the call treating the options as state. | -[CA2248](https://docs.microsoft.com/visualstudio/code-quality/ca2248) | Provide correct 'enum' argument to 'Enum.HasFlag' | Usage | True | Info | False | 'Enum.HasFlag' method expects the 'enum' argument to be of the same 'enum' type as the instance on which the method is invoked and that this 'enum' is marked with 'System.FlagsAttribute'. If these are different 'enum' types, an unhandled exception will be thrown at runtime. If the 'enum' type is not marked with 'System.FlagsAttribute' the call will always return 'false' at runtime. | -[CA2249](https://docs.microsoft.com/visualstudio/code-quality/ca2249) | Consider using 'string.Contains' instead of 'string.IndexOf' | Usage | True | Info | True | Calls to 'string.IndexOf' where the result is used to check for the presence/absence of a substring can be replaced by 'string.Contains' | -[CA2300](https://docs.microsoft.com/visualstudio/code-quality/ca2300) | Do not use insecure deserializer BinaryFormatter | Security | False | Warning | 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. | -[CA2301](https://docs.microsoft.com/visualstudio/code-quality/ca2301) | Do not call BinaryFormatter.Deserialize without first setting BinaryFormatter.Binder | Security | False | Warning | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | -[CA2302](https://docs.microsoft.com/visualstudio/code-quality/ca2302) | Ensure BinaryFormatter.Binder is set before calling BinaryFormatter.Deserialize | Security | False | Warning | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | -[CA2305](https://docs.microsoft.com/visualstudio/code-quality/ca2305) | Do not use insecure deserializer LosFormatter | Security | False | Warning | False | The method '{0}' is insecure when deserializing untrusted data. | -[CA2310](https://docs.microsoft.com/visualstudio/code-quality/ca2310) | Do not use insecure deserializer NetDataContractSerializer | Security | False | Warning | 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. | -[CA2311](https://docs.microsoft.com/visualstudio/code-quality/ca2311) | Do not deserialize without first setting NetDataContractSerializer.Binder | Security | False | Warning | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | -[CA2312](https://docs.microsoft.com/visualstudio/code-quality/ca2312) | Ensure NetDataContractSerializer.Binder is set before deserializing | Security | False | Warning | False | The method '{0}' is insecure when deserializing untrusted data without a SerializationBinder to restrict the type of objects in the deserialized object graph. | -[CA2315](https://docs.microsoft.com/visualstudio/code-quality/ca2315) | Do not use insecure deserializer ObjectStateFormatter | Security | False | Warning | False | The method '{0}' is insecure when deserializing untrusted data. | -[CA2321](https://docs.microsoft.com/visualstudio/code-quality/ca2321) | Do not deserialize with JavaScriptSerializer using a SimpleTypeResolver | Security | False | Warning | 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. | -[CA2322](https://docs.microsoft.com/visualstudio/code-quality/ca2322) | Ensure JavaScriptSerializer is not initialized with SimpleTypeResolver before deserializing | Security | False | Warning | 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. | -[CA2326](https://docs.microsoft.com/visualstudio/code-quality/ca2326) | Do not use TypeNameHandling values other than None | Security | False | Warning | 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. | -[CA2327](https://docs.microsoft.com/visualstudio/code-quality/ca2327) | Do not use insecure JsonSerializerSettings | Security | False | Warning | 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. | -[CA2328](https://docs.microsoft.com/visualstudio/code-quality/ca2328) | Ensure that JsonSerializerSettings are secure | Security | False | Warning | 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. | -[CA2329](https://docs.microsoft.com/visualstudio/code-quality/ca2329) | Do not deserialize with JsonSerializer using an insecure configuration | Security | False | Warning | 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. | -[CA2330](https://docs.microsoft.com/visualstudio/code-quality/ca2330) | Ensure that JsonSerializer has a secure configuration when deserializing | Security | False | Warning | 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. | -[CA2350](https://docs.microsoft.com/visualstudio/code-quality/ca2350) | Do not use insecure deserialization with DataTable.ReadXml() | Security | False | Warning | False | The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. | -[CA2351](https://docs.microsoft.com/visualstudio/code-quality/ca2351) | Do not use insecure deserialization with DataSet.ReadXml() | Security | False | Warning | False | The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD. | -[CA2352](https://docs.microsoft.com/visualstudio/code-quality/ca2352) | Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks | Security | False | Warning | False | When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. | -[CA2353](https://docs.microsoft.com/visualstudio/code-quality/ca2353) | Unsafe DataSet or DataTable in serializable type | Security | False | Warning | False | When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. | -[CA2354](https://docs.microsoft.com/visualstudio/code-quality/ca2354) | Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks | Security | False | Warning | False | When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. | -[CA2355](https://docs.microsoft.com/visualstudio/code-quality/ca2355) | Unsafe DataSet or DataTable type found in deserializable object graph | Security | False | Warning | False | When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. | -[CA2356](https://docs.microsoft.com/visualstudio/code-quality/ca2356) | Unsafe DataSet or DataTable type in web deserializable object graph | Security | False | Warning | False | When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. | -[CA3001](https://docs.microsoft.com/visualstudio/code-quality/ca3001) | Review code for SQL injection vulnerabilities | Security | False | Warning | False | Potential SQL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -[CA3002](https://docs.microsoft.com/visualstudio/code-quality/ca3002) | Review code for XSS vulnerabilities | Security | False | Warning | 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}'. | -[CA3003](https://docs.microsoft.com/visualstudio/code-quality/ca3003) | Review code for file path injection vulnerabilities | Security | False | Warning | 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}'. | -[CA3004](https://docs.microsoft.com/visualstudio/code-quality/ca3004) | Review code for information disclosure vulnerabilities | Security | False | Warning | False | Potential information disclosure vulnerability was found where '{0}' in method '{1}' may contain unintended information from '{2}' in method '{3}'. | -[CA3005](https://docs.microsoft.com/visualstudio/code-quality/ca3005) | Review code for LDAP injection vulnerabilities | Security | False | Warning | False | Potential LDAP injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -[CA3006](https://docs.microsoft.com/visualstudio/code-quality/ca3006) | Review code for process command injection vulnerabilities | Security | False | Warning | 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}'. | -[CA3007](https://docs.microsoft.com/visualstudio/code-quality/ca3007) | Review code for open redirect vulnerabilities | Security | False | Warning | False | Potential open redirect vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -[CA3008](https://docs.microsoft.com/visualstudio/code-quality/ca3008) | Review code for XPath injection vulnerabilities | Security | False | Warning | False | Potential XPath injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -[CA3009](https://docs.microsoft.com/visualstudio/code-quality/ca3009) | Review code for XML injection vulnerabilities | Security | False | Warning | False | Potential XML injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -[CA3010](https://docs.microsoft.com/visualstudio/code-quality/ca3010) | Review code for XAML injection vulnerabilities | Security | False | Warning | False | Potential XAML injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -[CA3011](https://docs.microsoft.com/visualstudio/code-quality/ca3011) | Review code for DLL injection vulnerabilities | Security | False | Warning | False | Potential DLL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -[CA3012](https://docs.microsoft.com/visualstudio/code-quality/ca3012) | Review code for regex injection vulnerabilities | Security | False | Warning | False | Potential regex injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. | -[CA3061](https://docs.microsoft.com/visualstudio/code-quality/ca3061) | Do Not Add Schema By URL | Security | True | Hidden | 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. | -[CA3075](https://docs.microsoft.com/visualstudio/code-quality/ca3075) | Insecure DTD processing in XML | Security | True | Hidden | 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.  | -[CA3076](https://docs.microsoft.com/visualstudio/code-quality/ca3076) | Insecure XSLT script processing. | Security | True | Hidden | 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. | -[CA3077](https://docs.microsoft.com/visualstudio/code-quality/ca3077) | Insecure Processing in API Design, XmlDocument and XmlTextReader | Security | True | Hidden | 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.  | -[CA3147](https://docs.microsoft.com/visualstudio/code-quality/ca3147) | Mark Verb Handlers With Validate Antiforgery Token | Security | True | Hidden | False | Missing ValidateAntiForgeryTokenAttribute on controller action {0}. | -[CA5350](https://docs.microsoft.com/visualstudio/code-quality/ca5350) | Do Not Use Weak Cryptographic Algorithms | Security | True | Hidden | 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. | -[CA5351](https://docs.microsoft.com/visualstudio/code-quality/ca5351) | Do Not Use Broken Cryptographic Algorithms | Security | True | Hidden | 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. | -[CA5358](https://docs.microsoft.com/visualstudio/code-quality/ca5358) | Review cipher mode usage with cryptography experts | Security | False | Warning | False | These cipher modes might be vulnerable to attacks. Consider using recommended modes (CBC, CTS). | -[CA5359](https://docs.microsoft.com/visualstudio/code-quality/ca5359) | Do Not Disable Certificate Validation | Security | True | Hidden | 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. | -[CA5360](https://docs.microsoft.com/visualstudio/code-quality/ca5360) | Do Not Call Dangerous Methods In Deserialization | Security | True | Hidden | 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. | -[CA5361](https://docs.microsoft.com/visualstudio/code-quality/ca5361) | Do Not Disable SChannel Use of Strong Crypto | Security | False | Warning | 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. | -[CA5362](https://docs.microsoft.com/visualstudio/code-quality/ca5362) | Potential reference cycle in deserialized object graph | Security | False | Warning | False | Review code that processes untrusted deserialized data for handling of unexpected reference cycles. An unexpected reference cycle should not cause the code to enter an infinite loop. Otherwise, an unexpected reference cycle can allow an attacker to DOS or exhaust the memory of the process when deserializing untrusted data. | -[CA5363](https://docs.microsoft.com/visualstudio/code-quality/ca5363) | Do Not Disable Request Validation | Security | True | Hidden | 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. | -[CA5364](https://docs.microsoft.com/visualstudio/code-quality/ca5364) | Do Not Use Deprecated Security Protocols | Security | True | Hidden | False | Using a deprecated security protocol rather than the system default is risky. | -[CA5365](https://docs.microsoft.com/visualstudio/code-quality/ca5365) | Do Not Disable HTTP Header Checking | Security | True | Hidden | 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. | -[CA5366](https://docs.microsoft.com/visualstudio/code-quality/ca5366) | Use XmlReader For DataSet Read Xml | Security | True | Hidden | 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. | -[CA5367](https://docs.microsoft.com/visualstudio/code-quality/ca5367) | Do Not Serialize Types With Pointer Fields | Security | False | Warning | 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. | -[CA5368](https://docs.microsoft.com/visualstudio/code-quality/ca5368) | Set ViewStateUserKey For Classes Derived From Page | Security | True | Hidden | 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. | -[CA5369](https://docs.microsoft.com/visualstudio/code-quality/ca5369) | Use XmlReader For Deserialize | Security | True | Hidden | 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. | -[CA5370](https://docs.microsoft.com/visualstudio/code-quality/ca5370) | Use XmlReader For Validating Reader | Security | True | Hidden | 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. | -[CA5371](https://docs.microsoft.com/visualstudio/code-quality/ca5371) | Use XmlReader For Schema Read | Security | True | Hidden | 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. | -[CA5372](https://docs.microsoft.com/visualstudio/code-quality/ca5372) | Use XmlReader For XPathDocument | Security | True | Hidden | 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. | -[CA5373](https://docs.microsoft.com/visualstudio/code-quality/ca5373) | Do not use obsolete key derivation function | Security | True | Hidden | 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. | -[CA5374](https://docs.microsoft.com/visualstudio/code-quality/ca5374) | Do Not Use XslTransform | Security | True | Hidden | False | Do not use XslTransform. It does not restrict potentially dangerous external references. | -[CA5375](https://docs.microsoft.com/visualstudio/code-quality/ca5375) | Do Not Use Account Shared Access Signature | Security | False | Warning | 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. | -[CA5376](https://docs.microsoft.com/visualstudio/code-quality/ca5376) | Use SharedAccessProtocol HttpsOnly | Security | False | Warning | False | HTTPS encrypts network traffic. Use HttpsOnly, rather than HttpOrHttps, to ensure network traffic is always encrypted to help prevent disclosure of sensitive data. | -[CA5377](https://docs.microsoft.com/visualstudio/code-quality/ca5377) | Use Container Level Access Policy | Security | False | Warning | False | No access policy identifier is specified, making tokens non-revocable. | -[CA5378](https://docs.microsoft.com/visualstudio/code-quality/ca5378) | Do not disable ServicePointManagerSecurityProtocols | Security | False | Warning | 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. | -[CA5379](https://docs.microsoft.com/visualstudio/code-quality/ca5379) | Do Not Use Weak Key Derivation Function Algorithm | Security | True | Hidden | 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. | -[CA5380](https://docs.microsoft.com/visualstudio/code-quality/ca5380) | Do Not Add Certificates To Root Store | Security | False | Warning | 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. | -[CA5381](https://docs.microsoft.com/visualstudio/code-quality/ca5381) | Ensure Certificates Are Not Added To Root Store | Security | False | Warning | 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. | -[CA5382](https://docs.microsoft.com/visualstudio/code-quality/ca5382) | Use Secure Cookies In ASP.Net Core | Security | False | Warning | False | Applications available over HTTPS must use secure cookies. | -[CA5383](https://docs.microsoft.com/visualstudio/code-quality/ca5383) | Ensure Use Secure Cookies In ASP.Net Core | Security | False | Warning | False | Applications available over HTTPS must use secure cookies. | -[CA5384](https://docs.microsoft.com/visualstudio/code-quality/ca5384) | Do Not Use Digital Signature Algorithm (DSA) | Security | True | Hidden | False | DSA is too weak to use. | -[CA5385](https://docs.microsoft.com/visualstudio/code-quality/ca5385) | Use Rivest–Shamir–Adleman (RSA) Algorithm With Sufficient Key Size | Security | True | Hidden | False | Encryption algorithms are vulnerable to brute force attacks when too small a key size is used. | -[CA5386](https://docs.microsoft.com/visualstudio/code-quality/ca5386) | Avoid hardcoding SecurityProtocolType value | Security | False | Warning | 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. | -[CA5387](https://docs.microsoft.com/visualstudio/code-quality/ca5387) | Do Not Use Weak Key Derivation Function With Insufficient Iteration Count | Security | False | Warning | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | -[CA5388](https://docs.microsoft.com/visualstudio/code-quality/ca5388) | Ensure Sufficient Iteration Count When Using Weak Key Derivation Function | Security | False | Warning | False | When deriving cryptographic keys from user-provided inputs such as password, use sufficient iteration count (at least 100k). | -[CA5389](https://docs.microsoft.com/visualstudio/code-quality/ca5389) | Do Not Add Archive Item's Path To The Target File System Path | Security | False | Warning | 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. | -[CA5390](https://docs.microsoft.com/visualstudio/code-quality/ca5390) | Do not hard-code encryption key | Security | False | Warning | False | SymmetricAlgorithm's .Key property, or a method's rgbKey parameter, should never be a hard-coded value. | -[CA5391](https://docs.microsoft.com/visualstudio/code-quality/ca5391) | Use antiforgery tokens in ASP.NET Core MVC controllers | Security | False | Warning | 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. | -[CA5392](https://docs.microsoft.com/visualstudio/code-quality/ca5392) | Use DefaultDllImportSearchPaths attribute for P/Invokes | Security | False | Warning | 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. | -[CA5393](https://docs.microsoft.com/visualstudio/code-quality/ca5393) | Do not use unsafe DllImportSearchPath value | Security | False | Warning | 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. | -[CA5394](https://docs.microsoft.com/visualstudio/code-quality/ca5394) | Do not use insecure randomness | Security | False | Warning | False | Using a cryptographically weak pseudo-random number generator may allow an attacker to predict what security-sensitive value will be generated. Use a cryptographically strong random number generator if an unpredictable value is required, or ensure that weak pseudo-random numbers aren't used in a security-sensitive manner. | -[CA5395](https://docs.microsoft.com/visualstudio/code-quality/ca5395) | Miss HttpVerb attribute for action methods | Security | False | Warning | 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. | -[CA5396](https://docs.microsoft.com/visualstudio/code-quality/ca5396) | Set HttpOnly to true for HttpCookie | Security | False | Warning | 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. | -[CA5397](https://docs.microsoft.com/visualstudio/code-quality/ca5397) | Do not use deprecated SslProtocols values | Security | True | Hidden | 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. | -[CA5398](https://docs.microsoft.com/visualstudio/code-quality/ca5398) | Avoid hardcoded SslProtocols values | Security | False | Warning | 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. | -[CA5399](https://docs.microsoft.com/visualstudio/code-quality/ca5399) | HttpClients should enable certificate revocation list checks | Security | False | Warning | 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. | -[CA5400](https://docs.microsoft.com/visualstudio/code-quality/ca5400) | Ensure HttpClient certificate revocation list check is not disabled | Security | False | Warning | 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. | -[CA5401](https://docs.microsoft.com/visualstudio/code-quality/ca5401) | Do not use CreateEncryptor with non-default IV | Security | False | Warning | False | Symmetric encryption should always use a non-repeatable initialization vector to prevent dictionary attacks. | -[CA5402](https://docs.microsoft.com/visualstudio/code-quality/ca5402) | Use CreateEncryptor with the default IV | Security | False | Warning | False | Symmetric encryption should always use a non-repeatable initialization vector to prevent dictionary attacks. | -[CA5403](https://docs.microsoft.com/visualstudio/code-quality/ca5403) | Do not hard-code certificate | Security | False | Warning | False | Hard-coded certificates in source code are vulnerable to being exploited. | diff --git a/src/NetAnalyzers/Microsoft.CodeAnalysis.NetAnalyzers.sarif b/src/NetAnalyzers/Microsoft.CodeAnalysis.NetAnalyzers.sarif index fe3d1321da..85d21fcf05 100644 --- a/src/NetAnalyzers/Microsoft.CodeAnalysis.NetAnalyzers.sarif +++ b/src/NetAnalyzers/Microsoft.CodeAnalysis.NetAnalyzers.sarif @@ -31,7 +31,7 @@ "CA1019": { "id": "CA1019", "shortDescription": "Define accessors for attribute arguments", - "fullDescription": "Remove the property setter from {0} or reduce its accessibility because it corresponds to positional argument {1}.", + "fullDescription": "Remove the property setter from {0} or reduce its accessibility because it corresponds to positional argument {1}", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1019", "properties": { @@ -140,6 +140,25 @@ ] } }, + "CA1812": { + "id": "CA1812", + "shortDescription": "Avoid uninstantiated internal classes", + "fullDescription": "An instance of an assembly-level type is not created by code in the assembly.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1812", + "properties": { + "category": "Performance", + "isEnabledByDefault": false, + "typeName": "CSharpAvoidUninstantiatedInternalClasses", + "languages": [ + "C#" + ], + "tags": [ + "PortedFromFxCop", + "Telemetry" + ] + } + }, "CA1824": { "id": "CA1824", "shortDescription": "Mark assemblies with NeutralResourcesLanguageAttribute", @@ -161,7 +180,7 @@ }, "CA1825": { "id": "CA1825", - "shortDescription": "Avoid zero-length array allocations.", + "shortDescription": "Avoid zero-length array allocations", "fullDescription": "Avoid unnecessary zero-length array allocations. Use {0} instead.", "defaultLevel": "note", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1825", @@ -197,8 +216,8 @@ }, "CA2200": { "id": "CA2200", - "shortDescription": "Rethrow to preserve stack details.", - "fullDescription": "Re-throwing caught exception changes stack information.", + "shortDescription": "Rethrow to preserve stack details", + "fullDescription": "Re-throwing caught exception changes stack information", "defaultLevel": "note", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2200", "properties": { @@ -482,7 +501,7 @@ "CA1018": { "id": "CA1018", "shortDescription": "Mark attributes with AttributeUsageAttribute", - "fullDescription": "Specify AttributeUsage on {0}.", + "fullDescription": "Specify AttributeUsage on {0}", "defaultLevel": "note", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1018", "properties": { @@ -880,8 +899,8 @@ }, "CA1054": { "id": "CA1054", - "shortDescription": "Uri parameters should not be strings", - "fullDescription": "If a method takes a string representation of a URI, a corresponding overload should be provided that takes an instance of the URI class, which provides these services in a safe and secure manner.", + "shortDescription": "URI-like parameters should not be strings", + "fullDescription": "This rule assumes that the parameter represents a Uniform Resource Identifier (URI). A string representation or a URI is prone to parsing and encoding errors, and can lead to security vulnerabilities. 'System.Uri' class provides these services in a safe and secure manner.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1054", "properties": { @@ -900,7 +919,7 @@ }, "CA1055": { "id": "CA1055", - "shortDescription": "Uri return values should not be strings", + "shortDescription": "URI-like return values should not be strings", "fullDescription": "This rule assumes that the method returns a URI. A string representation of a URI is prone to parsing and encoding errors, and can lead to security vulnerabilities. The System.Uri class provides these services in a safe and secure manner.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1055", @@ -920,7 +939,7 @@ }, "CA1056": { "id": "CA1056", - "shortDescription": "Uri properties should not be strings", + "shortDescription": "URI-like properties should not be strings", "fullDescription": "This rule assumes that the property represents a Uniform Resource Identifier (URI). A string representation of a URI is prone to parsing and encoding errors, and can lead to security vulnerabilities. The System.Uri class provides these services in a safe and secure manner.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1056", @@ -1119,7 +1138,7 @@ "CA1069": { "id": "CA1069", "shortDescription": "Enums values should not be duplicated", - "fullDescription": "The field reference '{0}' is duplicated in this bitwise initialization.", + "fullDescription": "The field reference '{0}' is duplicated in this bitwise initialization", "defaultLevel": "note", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1069", "properties": { @@ -1197,7 +1216,7 @@ "CA1305": { "id": "CA1305", "shortDescription": "Specify IFormatProvider", - "fullDescription": "A method or constructor calls one or more members that have overloads that accept a System.IFormatProvider parameter, and the method or constructor does not call the overload that takes the IFormatProvider parameter. When a System.Globalization.CultureInfo or IFormatProvider object is not supplied, the default value that is supplied by the overloaded member might not have the effect that you want in all locales. If the result will be based on the input from/output displayed to the user, specify 'CultureInfo.CurrentCulture' as the 'IFormatProvider'. Otherwise, if the result will be stored and accessed by software, such as when it is loaded from disk/database and when it is persisted to disk/database, specify 'CultureInfo.InvariantCulture'", + "fullDescription": "A method or constructor calls one or more members that have overloads that accept a System.IFormatProvider parameter, and the method or constructor does not call the overload that takes the IFormatProvider parameter. When a System.Globalization.CultureInfo or IFormatProvider object is not supplied, the default value that is supplied by the overloaded member might not have the effect that you want in all locales. If the result will be based on the input from/output displayed to the user, specify 'CultureInfo.CurrentCulture' as the 'IFormatProvider'. Otherwise, if the result will be stored and accessed by software, such as when it is loaded from disk/database and when it is persisted to disk/database, specify 'CultureInfo.InvariantCulture'.", "defaultLevel": "hidden", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1305", "properties": { @@ -1274,6 +1293,25 @@ ] } }, + "CA1417": { + "id": "CA1417", + "shortDescription": "Do not use 'OutAttribute' on string parameters for P/Invokes", + "fullDescription": "String parameters passed by value with the 'OutAttribute' can destabilize the runtime if the string is an interned string.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1417", + "properties": { + "category": "Interoperability", + "isEnabledByDefault": true, + "typeName": "DoNotUseOutAttributeStringPInvokeParametersAnalyzer", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, "CA1501": { "id": "CA1501", "shortDescription": "Avoid excessive inheritance", @@ -1377,7 +1415,7 @@ "CA1509": { "id": "CA1509", "shortDescription": "Invalid entry in code metrics rule specification file", - "fullDescription": "Invalid entry in code metrics rule specification file", + "fullDescription": "Invalid entry in code metrics rule specification file.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1509", "properties": { @@ -1536,7 +1574,7 @@ "CA1715": { "id": "CA1715", "shortDescription": "Identifiers should have correct prefix", - "fullDescription": "Identifiers should have correct prefix", + "fullDescription": "The name of an externally visible interface does not start with an uppercase \"\"I\"\". The name of a generic type parameter on an externally visible type or method does not start with an uppercase \"\"T\"\".", "defaultLevel": "hidden", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1715", "properties": { @@ -1753,26 +1791,6 @@ ] } }, - "CA1812": { - "id": "CA1812", - "shortDescription": "Avoid uninstantiated internal classes", - "fullDescription": "An instance of an assembly-level type is not created by code in the assembly.", - "defaultLevel": "warning", - "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1812", - "properties": { - "category": "Performance", - "isEnabledByDefault": false, - "typeName": "AvoidUninstantiatedInternalClassesAnalyzer", - "languages": [ - "C#", - "Visual Basic" - ], - "tags": [ - "PortedFromFxCop", - "Telemetry" - ] - } - }, "CA1813": { "id": "CA1813", "shortDescription": "Avoid unsealed attributes", @@ -1954,7 +1972,7 @@ }, "CA1826": { "id": "CA1826", - "shortDescription": "Do not use Enumerable methods on indexable collections. Instead use the collection directly", + "shortDescription": "Do not use Enumerable methods on indexable collections", "fullDescription": "This collection is directly indexable. Going through LINQ here causes unnecessary allocations and CPU work.", "defaultLevel": "note", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1826", @@ -2030,7 +2048,7 @@ }, "CA1830": { "id": "CA1830", - "shortDescription": "Prefer strongly-typed Append and Insert method overloads on StringBuilder.", + "shortDescription": "Prefer strongly-typed Append and Insert method overloads on StringBuilder", "fullDescription": "StringBuilder.Append and StringBuilder.Insert provide overloads for multiple types beyond System.String. When possible, prefer the strongly-typed overloads over using ToString() and the string-based overload.", "defaultLevel": "note", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1830", @@ -2106,7 +2124,7 @@ }, "CA1834": { "id": "CA1834", - "shortDescription": "Consider using 'StringBuilder.Append(char)' when applicable.", + "shortDescription": "Consider using 'StringBuilder.Append(char)' when applicable", "fullDescription": "'StringBuilder.Append(char)' is more efficient than 'StringBuilder.Append(string)' when the string is a single character. When calling 'Append' with a constant, prefer using a constant char rather than a constant string containing one character.", "defaultLevel": "note", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1834", @@ -2161,6 +2179,44 @@ ] } }, + "CA1837": { + "id": "CA1837", + "shortDescription": "Use 'Environment.ProcessId'", + "fullDescription": "'Environment.ProcessId' is simpler and faster than 'Process.GetCurrentProcess().Id'.", + "defaultLevel": "note", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1837", + "properties": { + "category": "Performance", + "isEnabledByDefault": true, + "typeName": "UseEnvironmentProcessId", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, + "CA1838": { + "id": "CA1838", + "shortDescription": "Avoid 'StringBuilder' parameters for P/Invokes", + "fullDescription": "Marshalling of 'StringBuilder' always creates a native buffer copy, resulting in multiple allocations for one marshalling operation.", + "defaultLevel": "hidden", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1838", + "properties": { + "category": "Performance", + "isEnabledByDefault": true, + "typeName": "AvoidStringBuilderPInvokeParametersAnalyzer", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, "CA2000": { "id": "CA2000", "shortDescription": "Dispose objects before losing scope", @@ -2282,7 +2338,7 @@ "id": "CA2012", "shortDescription": "Use ValueTasks correctly", "fullDescription": "ValueTasks returned from member invocations are intended to be directly awaited. Attempts to consume a ValueTask multiple times or to directly access one's result before it's known to be completed may result in an exception or corruption. Ignoring such a ValueTask is likely an indication of a functional bug and may degrade performance.", - "defaultLevel": "hidden", + "defaultLevel": "note", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2012", "properties": { "category": "Reliability", @@ -2318,7 +2374,7 @@ }, "CA2014": { "id": "CA2014", - "shortDescription": "Do not use stackalloc in loops.", + "shortDescription": "Do not use stackalloc in loops", "fullDescription": "Stack space allocated by a stackalloc is only released at the end of the current method's invocation. Using it in a loop can result in unbounded stack growth and eventual stack overflow conditions.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2014", @@ -2437,7 +2493,7 @@ "CA2153": { "id": "CA2153", "shortDescription": "Do Not Catch Corrupted State Exceptions", - "fullDescription": "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", + "fullDescription": "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.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2153", "properties": { @@ -2737,7 +2793,7 @@ "CA2231": { "id": "CA2231", "shortDescription": "Overload operator equals on overriding value type Equals", - "fullDescription": "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", + "fullDescription": "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.", "defaultLevel": "note", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2231", "properties": { @@ -2874,8 +2930,8 @@ }, "CA2245": { "id": "CA2245", - "shortDescription": "Do not assign a property to itself.", - "fullDescription": "The property {0} should not be assigned to itself.", + "shortDescription": "Do not assign a property to itself", + "fullDescription": "The property {0} should not be assigned to itself", "defaultLevel": "note", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2245", "properties": { @@ -2893,7 +2949,7 @@ }, "CA2246": { "id": "CA2246", - "shortDescription": "Assigning symbol and its member in the same statement.", + "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": "note", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2246", @@ -2911,7 +2967,7 @@ }, "CA2247": { "id": "CA2247", - "shortDescription": "Argument passed to TaskCompletionSource constructor should be TaskCreationOptions enum instead of TaskContinuationOptions enum.", + "shortDescription": "Argument passed to TaskCompletionSource constructor should be TaskCreationOptions enum instead of TaskContinuationOptions enum", "fullDescription": "TaskCompletionSource has constructors that take TaskCreationOptions that control the underlying Task, and constructors that take object state that's stored in the task. Accidentally passing a TaskContinuationOptions instead of a TaskCreationOptions will result in the call treating the options as state.", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2247", @@ -2950,7 +3006,7 @@ "CA2249": { "id": "CA2249", "shortDescription": "Consider using 'string.Contains' instead of 'string.IndexOf'", - "fullDescription": "Calls to 'string.IndexOf' where the result is used to check for the presence/absence of a substring can be replaced by 'string.Contains'", + "fullDescription": "Calls to 'string.IndexOf' where the result is used to check for the presence/absence of a substring can be replaced by 'string.Contains'.", "defaultLevel": "note", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2249", "properties": { @@ -3263,8 +3319,8 @@ }, "CA2350": { "id": "CA2350", - "shortDescription": "Do not use insecure deserialization with DataTable.ReadXml()", - "fullDescription": "The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD.", + "shortDescription": "Do not use DataTable.ReadXml() with untrusted data", + "fullDescription": "The method '{0}' is insecure when deserializing untrusted data", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2350", "properties": { @@ -3282,8 +3338,8 @@ }, "CA2351": { "id": "CA2351", - "shortDescription": "Do not use insecure deserialization with DataSet.ReadXml()", - "fullDescription": "The method '{0}' is insecure when deserializing untrusted data. If deserializing untrusted data, replace with TBD.", + "shortDescription": "Do not use DataSet.ReadXml() with untrusted data", + "fullDescription": "The method '{0}' is insecure when deserializing untrusted data", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2351", "properties": { @@ -3321,7 +3377,7 @@ "CA2353": { "id": "CA2353", "shortDescription": "Unsafe DataSet or DataTable in serializable type", - "fullDescription": "When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}.", + "fullDescription": "When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2353", "properties": { @@ -3340,7 +3396,7 @@ "CA2354": { "id": "CA2354", "shortDescription": "Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks", - "fullDescription": "When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}.", + "fullDescription": "When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2354", "properties": { @@ -3359,7 +3415,7 @@ "CA2355": { "id": "CA2355", "shortDescription": "Unsafe DataSet or DataTable type found in deserializable object graph", - "fullDescription": "When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}.", + "fullDescription": "When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2355", "properties": { @@ -3378,7 +3434,7 @@ "CA2356": { "id": "CA2356", "shortDescription": "Unsafe DataSet or DataTable type in web deserializable object graph", - "fullDescription": "When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}.", + "fullDescription": "When deserializing untrusted input, deserializing a {0} object is insecure. '{1}' either is or derives from {0}", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2356", "properties": { @@ -3394,6 +3450,44 @@ ] } }, + "CA2361": { + "id": "CA2361", + "shortDescription": "Ensure autogenerated class containing DataSet.ReadXml() is not used with untrusted data", + "fullDescription": "The method '{0}' is insecure when deserializing untrusted data. Make sure that autogenerated class containing the '{0}' call is not deserialized with untrusted data.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2361", + "properties": { + "category": "Security", + "isEnabledByDefault": false, + "typeName": "DoNotUseDataSetReadXml", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, + "CA2362": { + "id": "CA2362", + "shortDescription": "Unsafe DataSet or DataTable in autogenerated serializable type can be vulnerable to remote code execution attacks", + "fullDescription": "When deserializing untrusted input with an IFormatter-based serializer, deserializing a {0} object is insecure. '{1}' either is or derives from {0}. Ensure that the autogenerated type is never deserialized with untrusted data.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2362", + "properties": { + "category": "Security", + "isEnabledByDefault": false, + "typeName": "DataSetDataTableInSerializableTypeAnalyzer", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, "CA3001": { "id": "CA3001", "shortDescription": "Review code for SQL injection vulnerabilities", @@ -3675,7 +3769,7 @@ "CA3147": { "id": "CA3147", "shortDescription": "Mark Verb Handlers With Validate Antiforgery Token", - "fullDescription": "Missing ValidateAntiForgeryTokenAttribute on controller action {0}.", + "fullDescription": "Missing ValidateAntiForgeryTokenAttribute on controller action {0}", "defaultLevel": "hidden", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca3147", "properties": { @@ -4620,6 +4714,44 @@ "Telemetry" ] } + }, + "IL3000": { + "id": "IL3000", + "shortDescription": "Avoid using accessing Assembly file path when publishing as a single-file", + "fullDescription": "'{0}' always returns an empty string for assemblies embedded in a single-file app. If the path to the app directory is needed, consider calling 'System.AppContext.BaseDirectory'.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/il3000", + "properties": { + "category": "Publish", + "isEnabledByDefault": true, + "typeName": "AvoidAssemblyLocationInSingleFile", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, + "IL3001": { + "id": "IL3001", + "shortDescription": "Avoid using accessing Assembly file path when publishing as a single-file", + "fullDescription": "'{0}' will throw for assemblies embedded in a single-file app", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/il3001", + "properties": { + "category": "Publish", + "isEnabledByDefault": true, + "typeName": "AvoidAssemblyLocationInSingleFile", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } } } }, @@ -4652,7 +4784,7 @@ "CA1019": { "id": "CA1019", "shortDescription": "Define accessors for attribute arguments", - "fullDescription": "Remove the property setter from {0} or reduce its accessibility because it corresponds to positional argument {1}.", + "fullDescription": "Remove the property setter from {0} or reduce its accessibility because it corresponds to positional argument {1}", "defaultLevel": "warning", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1019", "properties": { @@ -4761,6 +4893,25 @@ ] } }, + "CA1812": { + "id": "CA1812", + "shortDescription": "Avoid uninstantiated internal classes", + "fullDescription": "An instance of an assembly-level type is not created by code in the assembly.", + "defaultLevel": "warning", + "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1812", + "properties": { + "category": "Performance", + "isEnabledByDefault": false, + "typeName": "BasicAvoidUninstantiatedInternalClasses", + "languages": [ + "Visual Basic" + ], + "tags": [ + "PortedFromFxCop", + "Telemetry" + ] + } + }, "CA1824": { "id": "CA1824", "shortDescription": "Mark assemblies with NeutralResourcesLanguageAttribute", @@ -4782,7 +4933,7 @@ }, "CA1825": { "id": "CA1825", - "shortDescription": "Avoid zero-length array allocations.", + "shortDescription": "Avoid zero-length array allocations", "fullDescription": "Avoid unnecessary zero-length array allocations. Use {0} instead.", "defaultLevel": "note", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca1825", @@ -4818,8 +4969,8 @@ }, "CA2200": { "id": "CA2200", - "shortDescription": "Rethrow to preserve stack details.", - "fullDescription": "Re-throwing caught exception changes stack information.", + "shortDescription": "Rethrow to preserve stack details", + "fullDescription": "Re-throwing caught exception changes stack information", "defaultLevel": "note", "helpUri": "https://docs.microsoft.com/visualstudio/code-quality/ca2200", "properties": { diff --git a/src/NetAnalyzers/RulesMissingDocumentation.md b/src/NetAnalyzers/RulesMissingDocumentation.md index 47899334e7..097a53f2ef 100644 --- a/src/NetAnalyzers/RulesMissingDocumentation.md +++ b/src/NetAnalyzers/RulesMissingDocumentation.md @@ -2,15 +2,12 @@ Rule ID | Missing Help Link | Title | --------|-------------------|-------| -CA1830 | https://docs.microsoft.com/visualstudio/code-quality/ca1830 | Prefer strongly-typed Append and Insert method overloads on StringBuilder. | -CA1831 | https://docs.microsoft.com/visualstudio/code-quality/ca1831 | Use AsSpan or AsMemory instead of Range-based indexers when appropriate | -CA1832 | https://docs.microsoft.com/visualstudio/code-quality/ca1832 | Use AsSpan or AsMemory instead of Range-based indexers when appropriate | -CA1833 | https://docs.microsoft.com/visualstudio/code-quality/ca1833 | Use AsSpan or AsMemory instead of Range-based indexers when appropriate | -CA1834 | https://docs.microsoft.com/visualstudio/code-quality/ca1834 | Consider using 'StringBuilder.Append(char)' when applicable. | -CA1835 | https://docs.microsoft.com/visualstudio/code-quality/ca1835 | Prefer the 'Memory'-based overloads for 'ReadAsync' and 'WriteAsync'. | -CA1836 | https://docs.microsoft.com/visualstudio/code-quality/ca1836 | Prefer IsEmpty over Count | +CA1834 | https://docs.microsoft.com/visualstudio/code-quality/ca1834 | Consider using 'StringBuilder.Append(char)' when applicable | +CA1837 | https://docs.microsoft.com/visualstudio/code-quality/ca1837 | Use 'Environment.ProcessId' | +CA1838 | https://docs.microsoft.com/visualstudio/code-quality/ca1838 | Avoid 'StringBuilder' parameters for P/Invokes | CA2008 | https://docs.microsoft.com/visualstudio/code-quality/ca2008 | Do not create tasks without passing a TaskScheduler | -CA2012 | https://docs.microsoft.com/visualstudio/code-quality/ca2012 | Use ValueTasks correctly | -CA2014 | https://docs.microsoft.com/visualstudio/code-quality/ca2014 | Do not use stackalloc in loops. | -CA2247 | https://docs.microsoft.com/visualstudio/code-quality/ca2247 | Argument passed to TaskCompletionSource constructor should be TaskCreationOptions enum instead of TaskContinuationOptions enum. | CA2249 | https://docs.microsoft.com/visualstudio/code-quality/ca2249 | Consider using 'string.Contains' instead of 'string.IndexOf' | +CA2361 | https://docs.microsoft.com/visualstudio/code-quality/ca2361 | Ensure autogenerated class containing DataSet.ReadXml() is not used with untrusted data | +CA2362 | https://docs.microsoft.com/visualstudio/code-quality/ca2362 | Unsafe DataSet or DataTable in autogenerated serializable type can be vulnerable to remote code execution attacks | +IL3000 | https://docs.microsoft.com/visualstudio/code-quality/il3000 | Avoid using accessing Assembly file path when publishing as a single-file | +IL3001 | https://docs.microsoft.com/visualstudio/code-quality/il3001 | Avoid using accessing Assembly file path when publishing as a single-file | diff --git a/src/NetAnalyzers/UnitTests/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/UsePropertiesWhereAppropriateTests.cs b/src/NetAnalyzers/UnitTests/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/UsePropertiesWhereAppropriateTests.cs index ac31cd7e45..a123583892 100644 --- a/src/NetAnalyzers/UnitTests/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/UsePropertiesWhereAppropriateTests.cs +++ b/src/NetAnalyzers/UnitTests/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/UsePropertiesWhereAppropriateTests.cs @@ -439,6 +439,45 @@ public object GetContent() "); } + [Fact, WorkItem(3877, "https://github.com/dotnet/roslyn-analyzers/issues/3877")] + public async Task CA1024_ReturnsTask_NoDiagnostic() + { + await VerifyCS.VerifyAnalyzerAsync(@" +using System.Threading.Tasks; + +public class Something +{ + public Task GetTask() => default(Task); + public Task GetGenericTask() => default(Task); + + public ValueTask GetValueTask() => default(ValueTask); + public ValueTask GetGenericValueTask() => default(ValueTask); +} +"); + + await VerifyVB.VerifyAnalyzerAsync(@" +Imports System.Threading.Tasks + +Public Class Something + Public Function GetTask() As Task + Return Nothing + End Function + + Public Function GetGenericTask() As Task(Of Integer) + Return Nothing + End Function + + Public Function GetValueTask() As ValueTask + Return Nothing + End Function + + Public Function GetGenericValueTask() As ValueTask(Of Integer) + Return Nothing + End Function +End Class +"); + } + private static DiagnosticResult GetCA1024CSharpResultAt(int line, int column, string methodName) => VerifyCS.Diagnostic() .WithLocation(line, column) diff --git a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Performance/PreferIsEmptyOverCountTests.cs b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Performance/PreferIsEmptyOverCountTests.cs index dd871a2982..b7b8358c76 100644 --- a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Performance/PreferIsEmptyOverCountTests.cs +++ b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Performance/PreferIsEmptyOverCountTests.cs @@ -24,26 +24,16 @@ public class PreferIsEmptyOverCountTests private const string IsEmpty = nameof(IsEmpty); private const string csSnippet = @" -using System; -using System.Linq; - public class Test {{ - public int Count {{ get; }} - public bool IsEmpty {{ get; }} - + private System.Collections.Concurrent.ConcurrentDictionary _concurrent; public bool DummyProperty => {0}; }} "; private const string vbSnippet = @" -Imports System -Imports System.Collections.Concurrent - Public Class Test - Public ReadOnly Property Count As Integer - Public ReadOnly Property IsEmpty As Boolean - + Private _concurrent As System.Collections.Concurrent.ConcurrentDictionary(Of string, string) Public ReadOnly Property DummyProperty As Boolean Get Return {0} @@ -159,55 +149,49 @@ End Class } [Theory] - [InlineData("(Count) > 0")] - [InlineData("Count > (0)")] - [InlineData("(Count) > (0)")] - [InlineData("(this.Count) > 0")] - [InlineData("this.Count > (0)")] - [InlineData("(this.Count) > (0)")] - [InlineData("((this).Count) > (0)")] - public Task CSharpTestFixOnParentheses(string condition) + [InlineData("(_concurrent.Count) > 0", "!_concurrent.IsEmpty")] + [InlineData("_concurrent.Count > (0)", "!_concurrent.IsEmpty")] + [InlineData("(_concurrent.Count) > (0)", "!_concurrent.IsEmpty")] + [InlineData("((_concurrent).Count) > (0)", "!(_concurrent).IsEmpty")] + public Task CSharpTestFixOnParentheses(string condition, string expectedFix) { string input = string.Format(CultureInfo.InvariantCulture, csSnippet, condition); - string fix = string.Format(CultureInfo.InvariantCulture, csSnippet, $"!{IsEmpty}"); + string fix = string.Format(CultureInfo.InvariantCulture, csSnippet, expectedFix); return VerifyCS.VerifyCodeFixAsync( input, - VerifyCS.Diagnostic(UseCountProperlyAnalyzer.s_rule_CA1836).WithSpan(10, 34, 10, 34 + condition.Length), + VerifyCS.Diagnostic(UseCountProperlyAnalyzer.s_rule_CA1836).WithSpan(5, 34, 5, 34 + condition.Length), fix); } [Theory] - [InlineData("(Count) > 0", "Not IsEmpty")] - [InlineData("Count > (0)", "Not IsEmpty")] - [InlineData("(Count) > (0)", "Not IsEmpty")] - [InlineData("(Me.Count) > 0", "Not IsEmpty")] - [InlineData("Me.Count > (0)", "Not IsEmpty")] - [InlineData("(Me.Count) > (0)", "Not IsEmpty")] + [InlineData("(_concurrent.Count) > 0", "Not _concurrent.IsEmpty")] + [InlineData("_concurrent.Count > (0)", "Not _concurrent.IsEmpty")] + [InlineData("(_concurrent.Count) > (0)", "Not _concurrent.IsEmpty")] // TODO: Reduce suggested fix to avoid special casing here. - [InlineData("((Me).Count) > (0)", "Not (Me).IsEmpty")] - public Task BasicTestFixOnParentheses(string condition, string replacement) + [InlineData("((_concurrent).Count) > (0)", "Not (_concurrent).IsEmpty")] + public Task BasicTestFixOnParentheses(string condition, string expectedFix) { string input = string.Format(CultureInfo.InvariantCulture, vbSnippet, condition); - string fix = string.Format(CultureInfo.InvariantCulture, vbSnippet, replacement); + string fix = string.Format(CultureInfo.InvariantCulture, vbSnippet, expectedFix); return VerifyVB.VerifyCodeFixAsync( input, - VerifyVB.Diagnostic(UseCountProperlyAnalyzer.s_rule_CA1836).WithSpan(11, 20, 11, 20 + condition.Length), + VerifyVB.Diagnostic(UseCountProperlyAnalyzer.s_rule_CA1836).WithSpan(6, 20, 6, 20 + condition.Length), fix); } [Theory] - [InlineData("array.Length > 0", true)] - [InlineData("(array.Length) > 0", true)] - [InlineData("array.Length > (0)", true)] - [InlineData("array.Count() == 0", false)] - [InlineData("(array.Count()) == 0", false)] - [InlineData("array.Count() == (0)", false)] - [InlineData("array.Length.Equals(0)", false)] - [InlineData("0.Equals(array.Length)", false)] - [InlineData("array.Count().Equals(0)", false)] - [InlineData("0.Equals(array.Count())", false)] + [InlineData("queue.Count > 0", true)] + [InlineData("(queue.Count) > 0", true)] + [InlineData("queue.Count > (0)", true)] + [InlineData("queue.Count() == 0", false)] + [InlineData("(queue.Count()) == 0", false)] + [InlineData("queue.Count() == (0)", false)] + [InlineData("queue.Count.Equals(0)", false)] + [InlineData("0.Equals(queue.Count)", false)] + [InlineData("queue.Count().Equals(0)", false)] + [InlineData("0.Equals(queue.Count())", false)] public Task CSharpTestExpressionAsArgument(string expression, bool negate) => VerifyCS.VerifyCodeFixAsync( $@"using System; @@ -216,51 +200,51 @@ public Task CSharpTestExpressionAsArgument(string expression, bool negate) public class Test {{ public static void TakeBool(bool isEmpty) {{ }} - public static void M(System.Collections.Immutable.ImmutableArray array) => TakeBool({expression}); + public static void M(System.Collections.Concurrent.ConcurrentQueue queue) => TakeBool({expression}); }}", - VerifyCS.Diagnostic(UseCountProperlyAnalyzer.s_rule_CA1836).WithLocation(7, 94), + VerifyCS.Diagnostic(UseCountProperlyAnalyzer.s_rule_CA1836).WithLocation(7, 96), $@"using System; using System.Linq; public class Test {{ public static void TakeBool(bool isEmpty) {{ }} - public static void M(System.Collections.Immutable.ImmutableArray array) => TakeBool({(negate ? "!" : "")}array.IsEmpty); + public static void M(System.Collections.Concurrent.ConcurrentQueue queue) => TakeBool({(negate ? "!" : "")}queue.IsEmpty); }}"); [Theory] - [InlineData("(uint)Count > 0", true)] - [InlineData("(uint)Count == 0", false)] - [InlineData("((uint)Count).Equals(0)", false)] - [InlineData("0.Equals((uint)Count)", false)] + [InlineData("(uint)_concurrent.Count > 0", true)] + [InlineData("(uint)_concurrent.Count == 0", false)] + [InlineData("((uint)_concurrent.Count).Equals(0)", false)] + [InlineData("0.Equals((uint)_concurrent.Count)", false)] public Task CSharpTestCastExpression(string expression, bool negate) => VerifyCS.VerifyCodeFixAsync( string.Format(CultureInfo.InvariantCulture, csSnippet, expression), - VerifyCS.Diagnostic(UseCountProperlyAnalyzer.s_rule_CA1836).WithLocation(10, 34), - string.Format(CultureInfo.InvariantCulture, csSnippet, $"{(negate ? "!" : "")}IsEmpty")); + VerifyCS.Diagnostic(UseCountProperlyAnalyzer.s_rule_CA1836).WithLocation(5, 34), + string.Format(CultureInfo.InvariantCulture, csSnippet, $"{(negate ? "!" : "")}_concurrent.IsEmpty")); [Theory] - [InlineData("CType(Count, UInteger) > 0", true)] - [InlineData("CType(Count, UInteger) = 0", false)] - [InlineData("CType(Count, UInteger).Equals(0)", false)] - [InlineData("0.Equals(CType(Count, UInteger))", false)] + [InlineData("CType(_concurrent.Count, UInteger) > 0", true)] + [InlineData("CType(_concurrent.Count, UInteger) = 0", false)] + [InlineData("CType(_concurrent.Count, UInteger).Equals(0)", false)] + [InlineData("0.Equals(CType(_concurrent.Count, UInteger))", false)] public Task BasicTestCastExpression(string expression, bool negate) => VerifyVB.VerifyCodeFixAsync( string.Format(CultureInfo.InvariantCulture, vbSnippet, expression), - VerifyVB.Diagnostic(UseCountProperlyAnalyzer.s_rule_CA1836).WithLocation(11, 20), - string.Format(CultureInfo.InvariantCulture, vbSnippet, $"{(negate ? "Not " : "")}IsEmpty")); + VerifyVB.Diagnostic(UseCountProperlyAnalyzer.s_rule_CA1836).WithLocation(6, 20), + string.Format(CultureInfo.InvariantCulture, vbSnippet, $"{(negate ? "Not " : "")}_concurrent.IsEmpty")); [Theory] - [InlineData("array.Length > 0", true)] - [InlineData("(array.Length) > 0", true)] - [InlineData("array.Length > (0)", true)] - [InlineData("array.Count() = 0", false)] - [InlineData("(array.Count()) = 0", false)] - [InlineData("array.Count() = (0)", false)] - [InlineData("array.Length.Equals(0)", false)] - [InlineData("0.Equals(array.Length)", false)] - [InlineData("array.Count().Equals(0)", false)] - [InlineData("0.Equals(array.Count())", false)] + [InlineData("queue.Count > 0", true)] + [InlineData("(queue.Count) > 0", true)] + [InlineData("queue.Count > (0)", true)] + [InlineData("queue.Count() = 0", false)] + [InlineData("(queue.Count()) = 0", false)] + [InlineData("queue.Count() = (0)", false)] + [InlineData("queue.Count.Equals(0)", false)] + [InlineData("0.Equals(queue.Count)", false)] + [InlineData("queue.Count().Equals(0)", false)] + [InlineData("0.Equals(queue.Count())", false)] public Task BasicTestExpressionAsArgument(string expression, bool negate) => VerifyVB.VerifyCodeFixAsync( $@"Imports System @@ -270,7 +254,7 @@ Imports System.Linq Public Shared Sub TakeBool(ByVal isEmpty As Boolean) End Sub - Public Shared Sub M(ByVal array As System.Collections.Immutable.ImmutableArray(Of Integer)) + Public Shared Sub M(ByVal queue As System.Collections.Concurrent.ConcurrentQueue(Of Integer)) TakeBool({expression}) End Sub End Class", @@ -282,12 +266,12 @@ Imports System.Linq Public Shared Sub TakeBool(ByVal isEmpty As Boolean) End Sub - Public Shared Sub M(ByVal array As System.Collections.Immutable.ImmutableArray(Of Integer)) - TakeBool({(negate ? "Not " : "")}array.IsEmpty) + Public Shared Sub M(ByVal queue As System.Collections.Concurrent.ConcurrentQueue(Of Integer)) + TakeBool({(negate ? "Not " : "")}queue.IsEmpty) End Sub End Class"); - [Theory] + [Theory(Skip = "Removed default support for all types but this scenario can be useful for .editorconfig")] [InlineData(false)] [InlineData(true)] public Task CSharpTestIsEmptyGetter_NoDiagnosis(bool useThis) @@ -304,7 +288,7 @@ public Task CSharpTestIsEmptyGetter_NoDiagnosis(bool useThis) public int Count => _list.Count; }}"); - [Theory] + [Theory(Skip = "Removed default support for all types but this scenario can be useful for .editorconfig")] [InlineData(false)] [InlineData(true)] public Task BasicTestIsEmptyGetter_NoDiagnosis(bool useMe) @@ -597,58 +581,4 @@ public CSharpPreferIsEmptyOverCountLinqTests_Concurrent() new CSharpVerifier(UseCountProperlyAnalyzer.CA1836)) { } } - - public class CSharpPreferIsEmptyOverCountTests_Immutable - : PreferIsEmptyOverCountTestsBase - { - public CSharpPreferIsEmptyOverCountTests_Immutable() - : base( - new CSharpTestsSourceCodeProvider( - "Length", - "global::System.Collections.Immutable.ImmutableArray", - extensionsNamespace: null, extensionsClass: null, isAsync: false), - new CSharpVerifier(UseCountProperlyAnalyzer.CA1836)) - { } - } - - public class CSharpPreferIsEmptyOverCountLinqTests_Immutable - : PreferIsEmptyOverCountLinqTestsBase - { - public CSharpPreferIsEmptyOverCountLinqTests_Immutable() - : base( - new CSharpTestsSourceCodeProvider( - "Length", - "global::System.Collections.Immutable.ImmutableArray", - extensionsNamespace: "System.Linq", extensionsClass: "Enumerable", - isAsync: false), - new CSharpVerifier(UseCountProperlyAnalyzer.CA1836)) - { } - } - - public class BasicPreferIsEmptyOverCountTests_Immutable - : PreferIsEmptyOverCountTestsBase - { - public BasicPreferIsEmptyOverCountTests_Immutable() - : base( - new BasicTestsSourceCodeProvider( - "Length", - "Global.System.Collections.Immutable.ImmutableArray(Of Integer)", - extensionsNamespace: null, extensionsClass: null, isAsync: false), - new BasicVerifier(UseCountProperlyAnalyzer.CA1836)) - { } - } - - public class BasicPreferIsEmptyOverCountLinqTests_Immutable - : PreferIsEmptyOverCountLinqTestsBase - { - public BasicPreferIsEmptyOverCountLinqTests_Immutable() - : base( - new BasicTestsSourceCodeProvider( - "Length", - "Global.System.Collections.Immutable.ImmutableArray(Of Integer)", - extensionsNamespace: "System.Linq", extensionsClass: "Enumerable", - isAsync: false), - new BasicVerifier(UseCountProperlyAnalyzer.CA1836)) - { } - } } diff --git a/src/PerformanceSensitiveAnalyzers/Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.md b/src/PerformanceSensitiveAnalyzers/Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.md index 42311bd708..bc116b70b3 100644 --- a/src/PerformanceSensitiveAnalyzers/Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.md +++ b/src/PerformanceSensitiveAnalyzers/Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.md @@ -1,19 +1,210 @@ +# Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers + +## HAA0101: Array allocation for params parameter + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +This call site is calling into a function with a 'params' parameter. This results in an array allocation. + +## HAA0102: Non-overridden virtual method call on value type + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Non-overridden virtual method call on a value type adds a boxing or constrained instruction + +## [HAA0201](http://msdn.microsoft.com/en-us/library/2839d5h5(v=vs.110).aspx): Implicit string concatenation allocation + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Considering using StringBuilder + +## [HAA0202](http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx): Value type to reference type conversion allocation for string concatenation + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Value type ({0}) is being boxed to a reference type for a string concatenation + +## HAA0301: Closure Allocation Source + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Heap allocation of closure Captures: {0} + +## HAA0302: Display class allocation to capture closure + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The compiler will emit a class that will hold this as a field to allow capturing of this closure + +## HAA0303: Lambda or anonymous method in a generic method allocates a delegate instance + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Considering moving this out of the generic method + +## HAA0401: Possible allocation of reference type enumerator + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Non-ValueType enumerator may result in a heap allocation + +## HAA0501: Explicit new array type allocation + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Info| +|CodeFix|False| + +### Rule description + +Explicit new array type allocation + +## HAA0502: Explicit new reference type allocation + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Info| +|CodeFix|False| + +### Rule description + +Explicit new reference type allocation + +## [HAA0503](http://msdn.microsoft.com/en-us/library/bb397696.aspx): Explicit new anonymous object allocation + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Info| +|CodeFix|False| + +### Rule description + +Explicit new anonymous object allocation + +## HAA0506: Let clause induced allocation + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Info| +|CodeFix|False| + +### Rule description + +Let clause induced allocation + +## HAA0601: Value type to reference type conversion causing boxing allocation + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Value type to reference type conversion causes boxing at call site (here), and unboxing at the callee-site. Consider using generics if applicable. + +## HAA0602: Delegate on struct instance caused a boxing allocation + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Struct instance method being used for delegate creation, this will result in a boxing instruction + +## HAA0603: Delegate allocation from a method group + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +This will allocate a delegate instance + +## HAA0604: Delegate allocation from a method group + +|Item|Value| +|-|-| +|Category|Performance| +|Enabled|True| +|Severity|Info| +|CodeFix|False| + +### Rule description + +This will allocate a delegate instance -Rule ID | Title | Category | Enabled | Severity | CodeFix | Description | ---------|-------|----------|---------|----------|---------|--------------------------------------------------------------------------------------------------------------| -HAA0101 | Array allocation for params parameter | Performance | True | Warning | False | This call site is calling into a function with a 'params' parameter. This results in an array allocation | -HAA0102 | Non-overridden virtual method call on value type | Performance | True | Warning | False | Non-overridden virtual method call on a value type adds a boxing or constrained instruction | -[HAA0201](http://msdn.microsoft.com/en-us/library/2839d5h5(v=vs.110).aspx) | Implicit string concatenation allocation | Performance | True | Warning | False | Considering using StringBuilder | -[HAA0202](http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx) | Value type to reference type conversion allocation for string concatenation | Performance | True | Warning | False | Value type ({0}) is being boxed to a reference type for a string concatenation. | -HAA0301 | Closure Allocation Source | Performance | True | Warning | False | Heap allocation of closure Captures: {0} | -HAA0302 | Display class allocation to capture closure | Performance | True | Warning | False | The compiler will emit a class that will hold this as a field to allow capturing of this closure | -HAA0303 | Lambda or anonymous method in a generic method allocates a delegate instance | Performance | True | Warning | False | Considering moving this out of the generic method | -HAA0401 | Possible allocation of reference type enumerator | Performance | True | Warning | False | Non-ValueType enumerator may result in a heap allocation | -HAA0501 | Explicit new array type allocation | Performance | True | Info | False | Explicit new array type allocation | -HAA0502 | Explicit new reference type allocation | Performance | True | Info | False | Explicit new reference type allocation | -[HAA0503](http://msdn.microsoft.com/en-us/library/bb397696.aspx) | Explicit new anonymous object allocation | Performance | True | Info | False | Explicit new anonymous object allocation | -HAA0506 | Let clause induced allocation | Performance | True | Info | False | Let clause induced allocation | -HAA0601 | Value type to reference type conversion causing boxing allocation | Performance | True | Warning | False | Value type to reference type conversion causes boxing at call site (here), and unboxing at the callee-site. Consider using generics if applicable | -HAA0602 | Delegate on struct instance caused a boxing allocation | Performance | True | Warning | False | Struct instance method being used for delegate creation, this will result in a boxing instruction | -HAA0603 | Delegate allocation from a method group | Performance | True | Warning | False | This will allocate a delegate instance | -HAA0604 | Delegate allocation from a method group | Performance | True | Info | False | This will allocate a delegate instance | diff --git a/src/PerformanceSensitiveAnalyzers/Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.sarif b/src/PerformanceSensitiveAnalyzers/Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.sarif index 5ef1bd53ef..41bbd0bed2 100644 --- a/src/PerformanceSensitiveAnalyzers/Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.sarif +++ b/src/PerformanceSensitiveAnalyzers/Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers.sarif @@ -12,7 +12,7 @@ "HAA0101": { "id": "HAA0101", "shortDescription": "Array allocation for params parameter", - "fullDescription": "This call site is calling into a function with a 'params' parameter. This results in an array allocation", + "fullDescription": "This call site is calling into a function with a 'params' parameter. This results in an array allocation.", "defaultLevel": "warning", "properties": { "category": "Performance", @@ -55,7 +55,7 @@ "HAA0202": { "id": "HAA0202", "shortDescription": "Value type to reference type conversion allocation for string concatenation", - "fullDescription": "Value type ({0}) is being boxed to a reference type for a string concatenation.", + "fullDescription": "Value type ({0}) is being boxed to a reference type for a string concatenation", "defaultLevel": "warning", "helpUri": "http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx", "properties": { @@ -126,7 +126,7 @@ "HAA0601": { "id": "HAA0601", "shortDescription": "Value type to reference type conversion causing boxing allocation", - "fullDescription": "Value type to reference type conversion causes boxing at call site (here), and unboxing at the callee-site. Consider using generics if applicable", + "fullDescription": "Value type to reference type conversion causes boxing at call site (here), and unboxing at the callee-site. Consider using generics if applicable.", "defaultLevel": "warning", "properties": { "category": "Performance", diff --git a/src/PublicApiAnalyzers/Microsoft.CodeAnalysis.PublicApiAnalyzers.md b/src/PublicApiAnalyzers/Microsoft.CodeAnalysis.PublicApiAnalyzers.md index 77a1e03bed..18445a3f5a 100644 --- a/src/PublicApiAnalyzers/Microsoft.CodeAnalysis.PublicApiAnalyzers.md +++ b/src/PublicApiAnalyzers/Microsoft.CodeAnalysis.PublicApiAnalyzers.md @@ -1,14 +1,145 @@ +# Microsoft.CodeAnalysis.PublicApiAnalyzers + +## [RS0016](https://github.com/dotnet/roslyn-analyzers/blob/master/src/PublicApiAnalyzers/PublicApiAnalyzers.Help.md): Add public types and members to the declared API + +|Item|Value| +|-|-| +|Category|ApiDesign| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +All public types and members should be declared in PublicAPI.txt. This draws attention to API changes in the code reviews and source control history, and helps prevent breaking changes. + +## [RS0017](https://github.com/dotnet/roslyn-analyzers/blob/master/src/PublicApiAnalyzers/PublicApiAnalyzers.Help.md): Remove deleted types and members from the declared API + +|Item|Value| +|-|-| +|Category|ApiDesign| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +When removing a public type or member the corresponding entry in PublicAPI.txt should also be removed. This draws attention to API changes in the code reviews and source control history, and helps prevent breaking changes. + +## [RS0022](https://github.com/dotnet/roslyn-analyzers/blob/master/src/PublicApiAnalyzers/PublicApiAnalyzers.Help.md): Constructor make noninheritable base class inheritable + +|Item|Value| +|-|-| +|Category|ApiDesign| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Constructor makes its noninheritable base class inheritable, thereby exposing its protected members. + +## [RS0024](https://github.com/dotnet/roslyn-analyzers/blob/master/src/PublicApiAnalyzers/PublicApiAnalyzers.Help.md): The contents of the public API files are invalid + +|Item|Value| +|-|-| +|Category|ApiDesign| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The contents of the public API files are invalid: {0} + +## [RS0025](https://github.com/dotnet/roslyn-analyzers/blob/master/src/PublicApiAnalyzers/PublicApiAnalyzers.Help.md): Do not duplicate symbols in public API files + +|Item|Value| +|-|-| +|Category|ApiDesign| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +The symbol '{0}' appears more than once in the public API files. + +## [RS0026](https://github.com/dotnet/roslyn/blob/master/docs/Adding%20Optional%20Parameters%20in%20Public%20API.md): Do not add multiple public overloads with optional parameters + +|Item|Value| +|-|-| +|Category|ApiDesign| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Symbol '{0}' violates the backcompat requirement: 'Do not add multiple overloads with optional parameters'. See '{1}' for details. + +## [RS0027](https://github.com/dotnet/roslyn/blob/master/docs/Adding%20Optional%20Parameters%20in%20Public%20API.md): Public API with optional parameter(s) should have the most parameters amongst its public overloads. + +|Item|Value| +|-|-| +|Category|ApiDesign| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Symbol '{0}' violates the backcompat requirement: 'Public API with optional parameter(s) should have the most parameters amongst its public overloads'. See '{1}' for details. + +## [RS0036](https://github.com/dotnet/roslyn-analyzers/blob/master/src/PublicApiAnalyzers/PublicApiAnalyzers.Help.md): Annotate nullability of public types and members in the declared API + +|Item|Value| +|-|-| +|Category|ApiDesign| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +All public types and members should be declared with nullability annotations in PublicAPI.txt. This draws attention to API nullability changes in the code reviews and source control history, and helps prevent breaking changes. + +## [RS0037](https://github.com/dotnet/roslyn-analyzers/blob/master/src/PublicApiAnalyzers/PublicApiAnalyzers.Help.md): Enable tracking of nullability of reference types in the declared API + +|Item|Value| +|-|-| +|Category|ApiDesign| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +PublicAPI.txt files should have `#nullable enable` to track nullability information, or this diagnostic should be suppressed. With nullability enabled, PublicAPI.txt records which types are nullable (suffix `?` on type) or non-nullable (suffix `!`). It also tracks any API that is still using an oblivious reference type (prefix `~` on line). + +## [RS0041](https://github.com/dotnet/roslyn-analyzers/blob/master/src/PublicApiAnalyzers/PublicApiAnalyzers.Help.md): Public members should not use oblivious types + +|Item|Value| +|-|-| +|Category|ApiDesign| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +All public members should use either nullable or non-nullable reference types, but no oblivious reference types. + +## [RS0048](https://github.com/dotnet/roslyn-analyzers/blob/master/src/PublicApiAnalyzers/PublicApiAnalyzers.Help.md): Missing shipped or unshipped public API file + +|Item|Value| +|-|-| +|Category|ApiDesign| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Public API file '{0}' is missing or not marked as an additional analyzer file -Rule ID | Title | Category | Enabled | Severity | CodeFix | Description | ---------|-------|----------|---------|----------|---------|--------------------------------------------------------------------------------------------------------------| -[RS0016](https://github.com/dotnet/roslyn-analyzers/blob/master/src/PublicApiAnalyzers/PublicApiAnalyzers.Help.md) | Add public types and members to the declared API | ApiDesign | True | Warning | True | All public types and members should be declared in PublicAPI.txt. This draws attention to API changes in the code reviews and source control history, and helps prevent breaking changes. | -[RS0017](https://github.com/dotnet/roslyn-analyzers/blob/master/src/PublicApiAnalyzers/PublicApiAnalyzers.Help.md) | Remove deleted types and members from the declared API | ApiDesign | True | Warning | False | When removing a public type or member the corresponding entry in PublicAPI.txt should also be removed. This draws attention to API changes in the code reviews and source control history, and helps prevent breaking changes. | -[RS0022](https://github.com/dotnet/roslyn-analyzers/blob/master/src/PublicApiAnalyzers/PublicApiAnalyzers.Help.md) | Constructor make noninheritable base class inheritable | ApiDesign | True | Warning | False | Constructor makes its noninheritable base class inheritable, thereby exposing its protected members. | -[RS0024](https://github.com/dotnet/roslyn-analyzers/blob/master/src/PublicApiAnalyzers/PublicApiAnalyzers.Help.md) | The contents of the public API files are invalid | ApiDesign | True | Warning | False | The contents of the public API files are invalid: {0} | -[RS0025](https://github.com/dotnet/roslyn-analyzers/blob/master/src/PublicApiAnalyzers/PublicApiAnalyzers.Help.md) | Do not duplicate symbols in public API files | ApiDesign | True | Warning | False | The symbol '{0}' appears more than once in the public API files. | -[RS0026](https://github.com/dotnet/roslyn/blob/master/docs/Adding%20Optional%20Parameters%20in%20Public%20API.md) | Do not add multiple public overloads with optional parameters | ApiDesign | True | Warning | False | Symbol '{0}' violates the backcompat requirement: 'Do not add multiple overloads with optional parameters'. See '{1}' for details. | -[RS0027](https://github.com/dotnet/roslyn/blob/master/docs/Adding%20Optional%20Parameters%20in%20Public%20API.md) | Public API with optional parameter(s) should have the most parameters amongst its public overloads. | ApiDesign | True | Warning | False | Symbol '{0}' violates the backcompat requirement: 'Public API with optional parameter(s) should have the most parameters amongst its public overloads'. See '{1}' for details. | -[RS0036](https://github.com/dotnet/roslyn-analyzers/blob/master/src/PublicApiAnalyzers/PublicApiAnalyzers.Help.md) | Annotate nullability of public types and members in the declared API | ApiDesign | True | Warning | True | All public types and members should be declared with nullability annotations in PublicAPI.txt. This draws attention to API nullability changes in the code reviews and source control history, and helps prevent breaking changes. | -[RS0037](https://github.com/dotnet/roslyn-analyzers/blob/master/src/PublicApiAnalyzers/PublicApiAnalyzers.Help.md) | Enable tracking of nullability of reference types in the declared API | ApiDesign | True | Warning | True | PublicAPI.txt files should have `#nullable enable` to track nullability information, or this diagnostic should be suppressed. With nullability enabled, PublicAPI.txt records which types are nullable (suffix `?` on type) or non-nullable (suffix `!`). It also tracks any API that is still using an oblivious reference type (prefix `~` on line). | -[RS0041](https://github.com/dotnet/roslyn-analyzers/blob/master/src/PublicApiAnalyzers/PublicApiAnalyzers.Help.md) | Public members should not use oblivious types | ApiDesign | True | Warning | False | All public members should use either nullable or non-nullable reference types, but no oblivious reference types. | -[RS0048](https://github.com/dotnet/roslyn-analyzers/blob/master/src/PublicApiAnalyzers/PublicApiAnalyzers.Help.md) | Missing shipped or unshipped public API file | ApiDesign | True | Warning | False | Public API file '{0}' is missing or not marked as an additional analyzer file | diff --git a/src/Roslyn.Diagnostics.Analyzers/Roslyn.Diagnostics.Analyzers.md b/src/Roslyn.Diagnostics.Analyzers/Roslyn.Diagnostics.Analyzers.md index b70b9e16ef..abfaba1162 100644 --- a/src/Roslyn.Diagnostics.Analyzers/Roslyn.Diagnostics.Analyzers.md +++ b/src/Roslyn.Diagnostics.Analyzers/Roslyn.Diagnostics.Analyzers.md @@ -1,21 +1,236 @@ +# Roslyn.Diagnostics.Analyzers + +## RS0001: Use 'SpecializedCollections.EmptyEnumerable()' + +|Item|Value| +|-|-| +|Category|RoslynDiagnosticsPerformance| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Use 'SpecializedCollections.EmptyEnumerable()' + +## RS0002: Use 'SpecializedCollections.SingletonEnumerable()' + +|Item|Value| +|-|-| +|Category|RoslynDiagnosticsPerformance| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Use 'SpecializedCollections.SingletonEnumerable()' + +## RS0004: Invoke the correct property to ensure correct use site diagnostics + +|Item|Value| +|-|-| +|Category|Usage| +|Enabled|False| +|Severity|Error| +|CodeFix|False| + +### Rule description + +Invoke the correct property to ensure correct use site diagnostics + +## RS0005: Do not use generic 'CodeAction.Create' to create 'CodeAction' + +|Item|Value| +|-|-| +|Category|RoslynDiagnosticsPerformance| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Do not use generic 'CodeAction.Create' to create 'CodeAction' + +## RS0006: Do not mix attributes from different versions of MEF + +|Item|Value| +|-|-| +|Category|RoslynDiagnosticsReliability| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Do not mix attributes from different versions of MEF. + +## RS0019: 'SymbolDeclaredEvent' must be generated for source symbols + +|Item|Value| +|-|-| +|Category|RoslynDiagnosticsReliability| +|Enabled|False| +|Severity|Error| +|CodeFix|False| + +### Rule description + +Compilation event queue is required to generate symbol declared events for all declared source symbols. Hence, every source symbol type or one of its base types must generate a symbol declared event. + +## RS0023: Parts exported with MEFv2 must be marked with 'SharedAttribute' + +|Item|Value| +|-|-| +|Category|RoslynDiagnosticsReliability| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Part exported with MEFv2 must be marked with the 'SharedAttribute'. + +## RS0032: Test exports should not be discoverable + +|Item|Value| +|-|-| +|Category|RoslynDiagnosticsReliability| +|Enabled|False| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Test exports should not be discoverable. + +## RS0033: Importing constructor should be marked with 'ObsoleteAttribute' + +|Item|Value| +|-|-| +|Category|RoslynDiagnosticsReliability| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Importing constructor should be marked with 'ObsoleteAttribute'. + +## RS0034: Exported parts should be marked with 'ImportingConstructorAttribute' + +|Item|Value| +|-|-| +|Category|RoslynDiagnosticsReliability| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Exported parts should be marked with 'ImportingConstructorAttribute'. + +## RS0038: Prefer null literal + +|Item|Value| +|-|-| +|Category|RoslynDiagnosticsMaintainability| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Use 'null' instead of 'default' for nullable types. + +## RS0040: Defaultable types should have defaultable fields + +|Item|Value| +|-|-| +|Category|RoslynDiagnosticsReliability| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Defaultable types should have defaultable fields. + +## RS0042: Do not copy value + +|Item|Value| +|-|-| +|Category|RoslynDiagnosticsReliability| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +Do not unbox non-copyable value types. + +## RS0043: Do not call 'GetTestAccessor()' + +|Item|Value| +|-|-| +|Category|RoslynDiagnosticsMaintainability| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| + +### Rule description + +'GetTestAccessor()' is a helper method reserved for testing. Production code must not call this member. + +## RS0046: Avoid the 'Opt' suffix + +|Item|Value| +|-|-| +|Category|RoslynDiagnosticsDesign| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Avoid the 'Opt' suffix in a nullable-enabled code. + +## RS0100: Statements must be placed on their own line + +|Item|Value| +|-|-| +|Category|RoslynDiagnosticsMaintainability| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Statements must be placed on their own line + +## RS0101: Avoid multiple blank lines + +|Item|Value| +|-|-| +|Category|RoslynDiagnosticsMaintainability| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Avoid multiple blank lines + +## RS0102: Braces must not have blank lines between them + +|Item|Value| +|-|-| +|Category|RoslynDiagnosticsMaintainability| +|Enabled|True| +|Severity|Warning| +|CodeFix|True| + +### Rule description + +Braces must not have blank lines between them -Rule ID | Title | Category | Enabled | Severity | CodeFix | Description | ---------|-------|----------|---------|----------|---------|--------------------------------------------------------------------------------------------------------------| -RS0001 | Use 'SpecializedCollections.EmptyEnumerable()' | RoslynDiagnosticsPerformance | True | Warning | False | Use 'SpecializedCollections.EmptyEnumerable()' | -RS0002 | Use 'SpecializedCollections.SingletonEnumerable()' | RoslynDiagnosticsPerformance | True | Warning | False | Use 'SpecializedCollections.SingletonEnumerable()' | -RS0004 | Invoke the correct property to ensure correct use site diagnostics | Usage | False | Error | False | Invoke the correct property to ensure correct use site diagnostics | -RS0005 | Do not use generic 'CodeAction.Create' to create 'CodeAction' | RoslynDiagnosticsPerformance | True | Warning | False | Do not use generic 'CodeAction.Create' to create 'CodeAction' | -RS0006 | Do not mix attributes from different versions of MEF | RoslynDiagnosticsReliability | True | Warning | False | Do not mix attributes from different versions of MEF. | -RS0019 | 'SymbolDeclaredEvent' must be generated for source symbols | RoslynDiagnosticsReliability | False | Error | False | Compilation event queue is required to generate symbol declared events for all declared source symbols. Hence, every source symbol type or one of its base types must generate a symbol declared event. | -RS0023 | Parts exported with MEFv2 must be marked with 'SharedAttribute' | RoslynDiagnosticsReliability | True | Warning | False | Part exported with MEFv2 must be marked with the 'SharedAttribute'. | -RS0032 | Test exports should not be discoverable | RoslynDiagnosticsReliability | False | Warning | True | Test exports should not be discoverable. | -RS0033 | Importing constructor should be marked with 'ObsoleteAttribute' | RoslynDiagnosticsReliability | True | Warning | True | Importing constructor should be marked with 'ObsoleteAttribute'. | -RS0034 | Exported parts should be marked with 'ImportingConstructorAttribute' | RoslynDiagnosticsReliability | True | Warning | True | Exported parts should be marked with 'ImportingConstructorAttribute'. | -RS0038 | Prefer null literal | RoslynDiagnosticsMaintainability | True | Warning | True | Use 'null' instead of 'default' for nullable types. | -RS0040 | Defaultable types should have defaultable fields | RoslynDiagnosticsReliability | True | Warning | False | Defaultable types should have defaultable fields. | -RS0042 | Do not copy value | RoslynDiagnosticsReliability | True | Warning | False | Do not unbox non-copyable value types. | -RS0043 | Do not call 'GetTestAccessor()' | RoslynDiagnosticsMaintainability | True | Warning | False | 'GetTestAccessor()' is a helper method reserved for testing. Production code must not call this member. | -RS0046 | Avoid the 'Opt' suffix | RoslynDiagnosticsDesign | True | Warning | True | Avoid the 'Opt' suffix in a nullable-enabled code. | -RS0100 | Statements must be placed on their own line | RoslynDiagnosticsMaintainability | True | Warning | True | Statements must be placed on their own line | -RS0101 | Avoid multiple blank lines | RoslynDiagnosticsMaintainability | True | Warning | True | Avoid multiple blank lines | -RS0102 | Braces must not have blank lines between them | RoslynDiagnosticsMaintainability | True | Warning | True | Braces must not have blank lines between them | diff --git a/src/Tools/GenerateDocumentationAndConfigFiles/Program.cs b/src/Tools/GenerateDocumentationAndConfigFiles/Program.cs index a8c747809d..bf9d91d6b4 100644 --- a/src/Tools/GenerateDocumentationAndConfigFiles/Program.cs +++ b/src/Tools/GenerateDocumentationAndConfigFiles/Program.cs @@ -20,7 +20,7 @@ public static class Program { public static int Main(string[] args) { - const int expectedArguments = 16; + const int expectedArguments = 17; if (args.Length != expectedArguments) { @@ -36,13 +36,14 @@ public static int Main(string[] args) var assemblyList = args[5].Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList(); string propsFileDir = args[6]; string propsFileName = args[7]; - string analyzerDocumentationFileDir = args[8]; - string analyzerDocumentationFileName = args[9]; - string analyzerSarifFileDir = args[10]; - string analyzerSarifFileName = args[11]; - var analyzerVersion = args[12]; - var analyzerPackageName = args[13]; - if (!bool.TryParse(args[14], out var containsPortedFxCopRules)) + string propsFileToDisableNetAnalyzersInNuGetPackageName = args[8]; + string analyzerDocumentationFileDir = args[9]; + string analyzerDocumentationFileName = args[10]; + string analyzerSarifFileDir = args[11]; + string analyzerSarifFileName = args[12]; + var analyzerVersion = args[13]; + var analyzerPackageName = args[14]; + if (!bool.TryParse(args[15], out var containsPortedFxCopRules)) { containsPortedFxCopRules = false; } @@ -149,7 +150,7 @@ public static int Main(string[] args) customTag: customTag); } - createPropsFile(); + createPropsFiles(); createAnalyzerDocumentationFile(); @@ -179,21 +180,65 @@ static void AnalyzerFileReference_AnalyzerLoadFailed(object? sender, AnalyzerLoa return; } - void createPropsFile() + void createPropsFiles() { if (string.IsNullOrEmpty(propsFileDir) || string.IsNullOrEmpty(propsFileName)) { Debug.Assert(!containsPortedFxCopRules); + Debug.Assert(string.IsNullOrEmpty(propsFileToDisableNetAnalyzersInNuGetPackageName)); return; } + var disableNetAnalyzersImport = getDisableNetAnalyzersImport(); + var fileContents = -$@" - {getCodeAnalysisTreatWarningsNotAsErrors()} +$@" + {disableNetAnalyzersImport}{getCodeAnalysisTreatWarningsNotAsErrors()} "; var directory = Directory.CreateDirectory(propsFileDir); var fileWithPath = Path.Combine(directory.FullName, propsFileName); File.WriteAllText(fileWithPath, fileContents); + + if (!string.IsNullOrEmpty(disableNetAnalyzersImport)) + { + fileWithPath = Path.Combine(directory.FullName, propsFileToDisableNetAnalyzersInNuGetPackageName); + fileContents = +$@" + + + false + +"; + File.WriteAllText(fileWithPath, fileContents); + } + + return; + + string getDisableNetAnalyzersImport() + { + if (!string.IsNullOrEmpty(propsFileToDisableNetAnalyzersInNuGetPackageName)) + { + Debug.Assert(analyzerPackageName == "Microsoft.CodeAnalysis.NetAnalyzers" || + analyzerPackageName == "Microsoft.CodeAnalysis.FxCopAnalyzers" || + analyzerPackageName == "Microsoft.NetCore.Analyzers" || + analyzerPackageName == "Microsoft.NetFramework.Analyzers" || + analyzerPackageName == "Microsoft.CodeQuality.Analyzers"); + + return $@" + + +"; + } + + Debug.Assert(!containsPortedFxCopRules); + return string.Empty; + } } string getCodeAnalysisTreatWarningsNotAsErrors() @@ -221,10 +266,10 @@ void createAnalyzerDocumentationFile() var fileWithPath = Path.Combine(directory.FullName, analyzerDocumentationFileName); var builder = new StringBuilder(); - builder.Append(@" -Rule ID | Title | Category | Enabled | Severity | CodeFix | Description | ---------|-------|----------|---------|----------|---------|--------------------------------------------------------------------------------------------------------------| -"); + + var title = Path.GetFileNameWithoutExtension(analyzerDocumentationFileName); + builder.AppendLine($"# {title}"); + builder.AppendLine(); foreach (var ruleById in allRulesById) { @@ -237,7 +282,20 @@ void createAnalyzerDocumentationFile() ruleIdWithHyperLink = $"[{ruleIdWithHyperLink}]({descriptor.HelpLinkUri})"; } + builder.AppendLine($"## {ruleIdWithHyperLink}: {descriptor.Title}"); + builder.AppendLine(); + + builder.AppendLine("|Item|Value|"); + builder.AppendLine("|-|-|"); + builder.AppendLine($"|Category|{descriptor.Category}|"); + builder.AppendLine($"|Enabled|{descriptor.IsEnabledByDefault}|"); + builder.AppendLine($"|Severity|{descriptor.DefaultSeverity}|"); var hasCodeFix = fixableDiagnosticIds.Contains(descriptor.Id); + builder.AppendLine($"|CodeFix|{hasCodeFix}|"); + builder.AppendLine(); + + builder.AppendLine($"### Rule description"); + builder.AppendLine(); var description = descriptor.Description.ToString(CultureInfo.InvariantCulture); if (string.IsNullOrWhiteSpace(description)) @@ -248,8 +306,8 @@ void createAnalyzerDocumentationFile() // Replace line breaks with HTML breaks so that new // lines don't break the markdown table formatting. description = System.Text.RegularExpressions.Regex.Replace(description, "\r?\n", "
"); - - builder.AppendLine($"{ruleIdWithHyperLink} | {descriptor.Title} | {descriptor.Category} | {descriptor.IsEnabledByDefault} | {descriptor.DefaultSeverity} | {hasCodeFix} | {description} |"); + builder.AppendLine(description); + builder.AppendLine(); } File.WriteAllText(fileWithPath, builder.ToString()); diff --git a/src/Utilities.UnitTests/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysisTests.cs b/src/Utilities.UnitTests/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysisTests.cs index cb8eb938ba..fbd1edaf9a 100644 --- a/src/Utilities.UnitTests/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysisTests.cs +++ b/src/Utilities.UnitTests/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysisTests.cs @@ -829,8 +829,8 @@ void TestMethod() // Better to compare LocationTypeOpt to INamedTypeSymbol, but for this demonstration, just using MetadataName. PropertySetAbstractValueKind kind; if (argumentPointsToAbstractValues[1].Locations.Any(l => - l.LocationTypeOpt != null - && l.LocationTypeOpt.MetadataName == "BitArray")) + l.LocationType != null + && l.LocationType.MetadataName == "BitArray")) { kind = PropertySetAbstractValueKind.Flagged; } @@ -849,8 +849,8 @@ void TestMethod() // Better to compare LocationTypeOpt to INamedTypeSymbol, but for this demonstration, just using MetadataName. PropertySetAbstractValueKind kind; if (pointsToAbstractValue.Locations.Any(l => - l.LocationTypeOpt != null - && l.LocationTypeOpt.MetadataName == "BitArray")) + l.LocationType != null + && l.LocationType.MetadataName == "BitArray")) { kind = PropertySetAbstractValueKind.Flagged; } diff --git a/src/Utilities/Compiler/WellKnownTypeNames.cs b/src/Utilities/Compiler/WellKnownTypeNames.cs index 40cd442d9e..b23b394af3 100644 --- a/src/Utilities/Compiler/WellKnownTypeNames.cs +++ b/src/Utilities/Compiler/WellKnownTypeNames.cs @@ -94,6 +94,10 @@ internal static class WellKnownTypeNames public const string SystemChar = "System.Char"; public const string SystemCLSCompliantAttribute = "System.CLSCompliantAttribute"; public const string SystemCodeDomCompilerGeneratedCodeAttribute = "System.CodeDom.Compiler.GeneratedCodeAttribute"; + public const string SystemCollectionsConcurrentConcurrentBag1 = "System.Collections.Concurrent.ConcurrentBag`1"; + public const string SystemCollectionsConcurrentConcurrentDictionary2 = "System.Collections.Concurrent.ConcurrentDictionary`2"; + public const string SystemCollectionsConcurrentConcurrentQueue1 = "System.Collections.Concurrent.ConcurrentQueue`1"; + public const string SystemCollectionsConcurrentConcurrentStack1 = "System.Collections.Concurrent.ConcurrentStack`1"; public const string SystemCollectionsGenericICollection1 = "System.Collections.Generic.ICollection`1"; public const string SystemCollectionsGenericIEnumerable1 = "System.Collections.Generic.IEnumerable`1"; public const string SystemCollectionsGenericIEnumerator1 = "System.Collections.Generic.IEnumerator`1"; diff --git a/src/Utilities/FlowAnalysis/BranchWithInfo.cs b/src/Utilities/FlowAnalysis/BranchWithInfo.cs index 3335e3f2c6..60a8a86996 100644 --- a/src/Utilities/FlowAnalysis/BranchWithInfo.cs +++ b/src/Utilities/FlowAnalysis/BranchWithInfo.cs @@ -49,7 +49,7 @@ internal BranchWithInfo(BasicBlock destination) EnteringRegions = enteringRegions; LeavingRegions = leavingRegions; FinallyRegions = finallyRegions; - BranchValueOpt = branchValue; + BranchValue = branchValue; ControlFlowConditionKind = controlFlowConditionKind; LeavingRegionLocals = leavingRegionLocals; LeavingRegionFlowCaptures = leavingRegionFlowCaptures; @@ -60,7 +60,7 @@ internal BranchWithInfo(BasicBlock destination) public ImmutableArray EnteringRegions { get; } public ImmutableArray FinallyRegions { get; } public ImmutableArray LeavingRegions { get; } - public IOperation? BranchValueOpt { get; } + public IOperation? BranchValue { get; } #pragma warning disable CA1721 // Property names should not match get methods - https://github.com/dotnet/roslyn-analyzers/issues/2085 public ControlFlowConditionKind ControlFlowConditionKind { get; } @@ -77,7 +77,7 @@ internal BranchWithInfo WithEmptyRegions(BasicBlock destination) leavingRegions: ImmutableArray.Empty, finallyRegions: ImmutableArray.Empty, kind: Kind, - branchValue: BranchValueOpt, + branchValue: BranchValue, controlFlowConditionKind: ControlFlowConditionKind, leavingRegionLocals: ImmutableHashSet.Empty, leavingRegionFlowCaptures: ImmutableHashSet.Empty); diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/CopyAnalysis/CopyAnalysis.CopyDataFlowOperationVisitor.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/CopyAnalysis/CopyAnalysis.CopyDataFlowOperationVisitor.cs index a0be050f15..4a838c4579 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/CopyAnalysis/CopyAnalysis.CopyDataFlowOperationVisitor.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/CopyAnalysis/CopyAnalysis.CopyDataFlowOperationVisitor.cs @@ -30,7 +30,7 @@ public CopyDataFlowOperationVisitor(CopyAnalysisContext analysisContext) var coreAnalysisDomain = new CoreCopyAnalysisDataDomain(CopyAbstractValueDomain.Default, GetDefaultCopyValue); AnalysisDomain = new CopyAnalysisDomain(coreAnalysisDomain); - analysisContext.InterproceduralAnalysisDataOpt?.InitialAnalysisData.AssertValidCopyAnalysisData(); + analysisContext.InterproceduralAnalysisData?.InitialAnalysisData.AssertValidCopyAnalysisData(); } public CopyAnalysisDomain AnalysisDomain { get; } @@ -248,9 +248,9 @@ protected override void SetValueForParameterOnEntry(IParameterSymbol parameter, if (assignedValue != null) { var assignedEntities = assignedValue.Value.AnalysisEntities; - if (assignedValue.AnalysisEntityOpt != null && !assignedEntities.Contains(assignedValue.AnalysisEntityOpt)) + if (assignedValue.AnalysisEntity != null && !assignedEntities.Contains(assignedValue.AnalysisEntity)) { - assignedEntities = assignedEntities.Add(assignedValue.AnalysisEntityOpt); + assignedEntities = assignedEntities.Add(assignedValue.AnalysisEntity); } var newAnalysisEntities = assignedEntities; @@ -259,7 +259,7 @@ protected override void SetValueForParameterOnEntry(IParameterSymbol parameter, { newKind = assignedValue.Value.Kind; } - else if (assignedValue.AnalysisEntityOpt == null || assignedValue.AnalysisEntityOpt.Type.IsValueType) + else if (assignedValue.AnalysisEntity == null || assignedValue.AnalysisEntity.Type.IsValueType) { newKind = CopyAbstractValueKind.KnownValueCopy; } @@ -463,7 +463,7 @@ public override (CopyAbstractValue Value, PredicateValueKind PredicateValueKind) var returnValueAndPredicateKind = base.GetReturnValueAndPredicateKind(); if (returnValueAndPredicateKind.HasValue && returnValueAndPredicateKind.Value.Value.Kind.IsKnown() && - DataFlowAnalysisContext.InterproceduralAnalysisDataOpt != null) + DataFlowAnalysisContext.InterproceduralAnalysisData != null) { var entitiesToFilterBuilder = PooledHashSet.GetInstance(); var copyValue = returnValueAndPredicateKind.Value.Value; @@ -581,7 +581,7 @@ protected override CopyAnalysisData GetTrimmedCurrentAnalysisData(IEnumerable> argumentValuesMap, IDictionary? pointsToValues, diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/CopyAnalysis/CopyAnalysisContext.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/CopyAnalysis/CopyAnalysisContext.cs index 3b1b6bff9d..1390b7cc01 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/CopyAnalysis/CopyAnalysisContext.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/CopyAnalysis/CopyAnalysisContext.cs @@ -66,7 +66,7 @@ public sealed class CopyAnalysisContext : AbstractDataFlowAnalysisContext addPart) diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/DisposeAnalysis/DisposeAnalysis.DisposeDataFlowOperationVisitor.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/DisposeAnalysis/DisposeAnalysis.DisposeDataFlowOperationVisitor.cs index b17915a87e..466d433e59 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/DisposeAnalysis/DisposeAnalysis.DisposeDataFlowOperationVisitor.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/DisposeAnalysis/DisposeAnalysis.DisposeDataFlowOperationVisitor.cs @@ -32,7 +32,7 @@ public DisposeDataFlowOperationVisitor(DisposeAnalysisContext analysisContext) Debug.Assert(IDisposableNamedType != null); Debug.Assert(CollectionNamedTypes.All(ct => ct.TypeKind == TypeKind.Interface)); Debug.Assert(analysisContext.DisposeOwnershipTransferLikelyTypes != null); - Debug.Assert(analysisContext.PointsToAnalysisResultOpt != null); + Debug.Assert(analysisContext.PointsToAnalysisResult != null); if (analysisContext.TrackInstanceFields) { @@ -62,9 +62,9 @@ public DisposeDataFlowOperationVisitor(DisposeAnalysisContext analysisContext) protected override void SetAbstractValue(AbstractLocation location, DisposeAbstractValue value) { if (!location.IsNull && - location.LocationTypeOpt != null && - (!location.LocationTypeOpt.IsValueType || location.LocationTypeOpt.IsRefLikeType) && - IsDisposable(location.LocationTypeOpt)) + location.LocationType != null && + (!location.LocationType.IsValueType || location.LocationType.IsRefLikeType) && + IsDisposable(location.LocationType)) { CurrentAnalysisData[location] = value; } @@ -190,7 +190,7 @@ protected override void EscapeValueForParameterPointsToLocationOnExit(IParameter Debug.Assert(!escapedLocations.IsEmpty); Debug.Assert(parameter.RefKind != RefKind.None); var escapedDisposableLocations = - escapedLocations.Where(l => IsDisposable(l.LocationTypeOpt)); + escapedLocations.Where(l => IsDisposable(l.LocationType)); SetAbstractValue(escapedDisposableLocations, ValueDomain.UnknownOrMayBeValue); } diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/DisposeAnalysis/DisposeAnalysisContext.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/DisposeAnalysis/DisposeAnalysisContext.cs index ae7b6fb215..abfc5a318a 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/DisposeAnalysis/DisposeAnalysisContext.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/DisposeAnalysis/DisposeAnalysisContext.cs @@ -101,7 +101,7 @@ public sealed class DisposeAnalysisContext : AbstractDataFlowAnalysisContext DisposeOwnershipTransferLikelyTypes { get; } diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/DisposeAnalysis/DisposeAnalysisHelper.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/DisposeAnalysis/DisposeAnalysisHelper.cs index 7e996fe00e..8597f35472 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/DisposeAnalysis/DisposeAnalysisHelper.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/DisposeAnalysis/DisposeAnalysisHelper.cs @@ -178,13 +178,13 @@ public ImmutableHashSet GetDisposableFields(INamedTypeSymbol named /// public bool IsDisposableCreationOrDisposeOwnershipTransfer(AbstractLocation location, IMethodSymbol containingMethod) { - if (location.CreationOpt == null) + if (location.Creation == null) { - return location.SymbolOpt?.Kind == SymbolKind.Parameter && + return location.Symbol?.Kind == SymbolKind.Parameter && HasDisposableOwnershipTransferForConstructorParameter(containingMethod); } - return IsDisposableCreation(location.CreationOpt); + return IsDisposableCreation(location.Creation); } public bool IsDisposable([NotNullWhen(returnValue: true)] ITypeSymbol? type) diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/GlobalFlowStateAnalysis/GlobalFlowStateAnalysisContext.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/GlobalFlowStateAnalysis/GlobalFlowStateAnalysisContext.cs index e4619c573d..a4a0f8560e 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/GlobalFlowStateAnalysis/GlobalFlowStateAnalysisContext.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/GlobalFlowStateAnalysis/GlobalFlowStateAnalysisContext.cs @@ -81,7 +81,7 @@ internal sealed class GlobalFlowStateAnalysisContext : AbstractDataFlowAnalysisC return new GlobalFlowStateAnalysisContext(ValueDomain, WellKnownTypeProvider, invokedCfg, invokedMethod, AnalyzerOptions, InterproceduralAnalysisConfiguration, PessimisticAnalysis, pointsToAnalysisResult, valueContentAnalysisResult, TryGetOrComputeAnalysisResult, - ControlFlowGraph, interproceduralAnalysisData, InterproceduralAnalysisPredicateOpt); + ControlFlowGraph, interproceduralAnalysisData, InterproceduralAnalysisPredicate); } protected override void ComputeHashCodePartsSpecific(Action addPart) diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/GlobalFlowStateAnalysis/GlobalFlowStateDataFlowOperationVisitor.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/GlobalFlowStateAnalysis/GlobalFlowStateDataFlowOperationVisitor.cs index 0bb8e0c7fe..9d5b8c0fd4 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/GlobalFlowStateAnalysis/GlobalFlowStateDataFlowOperationVisitor.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/GlobalFlowStateAnalysis/GlobalFlowStateDataFlowOperationVisitor.cs @@ -34,14 +34,14 @@ protected GlobalFlowStateDataFlowOperationVisitor(GlobalFlowStateAnalysisContext private static AnalysisEntity GetGlobalEntity(GlobalFlowStateAnalysisContext analysisContext) { ISymbol owningSymbol; - if (analysisContext.InterproceduralAnalysisDataOpt == null) + if (analysisContext.InterproceduralAnalysisData == null) { owningSymbol = analysisContext.OwningSymbol; } else { - owningSymbol = analysisContext.InterproceduralAnalysisDataOpt.MethodsBeingAnalyzed - .Single(m => m.InterproceduralAnalysisDataOpt == null) + owningSymbol = analysisContext.InterproceduralAnalysisData.MethodsBeingAnalyzed + .Single(m => m.InterproceduralAnalysisData == null) .OwningSymbol; } @@ -84,10 +84,10 @@ public sealed override (GlobalFlowStateAnalysisData output, bool isFeasibleBranc if (_hasPredicatedGlobalState && branch.ControlFlowConditionKind != ControlFlowConditionKind.None && - branch.BranchValueOpt != null && + branch.BranchValue != null && result.isFeasibleBranch) { - var branchValue = GetCachedAbstractValue(branch.BranchValueOpt); + var branchValue = GetCachedAbstractValue(branch.BranchValue); var negate = branch.ControlFlowConditionKind == ControlFlowConditionKind.WhenFalse; MergeAndSetGlobalState(branchValue, negate); } diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/ParameterValidationAnalysis/ParameterValidationAnalysis.ParameterValidationDataFlowOperationVisitor.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/ParameterValidationAnalysis/ParameterValidationAnalysis.ParameterValidationDataFlowOperationVisitor.cs index 96538cfc08..6deea5a67f 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/ParameterValidationAnalysis/ParameterValidationAnalysis.ParameterValidationDataFlowOperationVisitor.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/ParameterValidationAnalysis/ParameterValidationAnalysis.ParameterValidationDataFlowOperationVisitor.cs @@ -28,7 +28,7 @@ public ParameterValidationDataFlowOperationVisitor(ParameterValidationAnalysisCo : base(analysisContext) { Debug.Assert(analysisContext.OwningSymbol.Kind == SymbolKind.Method); - Debug.Assert(analysisContext.PointsToAnalysisResultOpt != null); + Debug.Assert(analysisContext.PointsToAnalysisResult != null); if (analysisContext.TrackHazardousParameterUsages) { @@ -57,19 +57,19 @@ protected override ParameterValidationAbstractValue GetAbstractValue(AbstractLoc private bool IsTrackedLocation(AbstractLocation location) { return CurrentAnalysisData.ContainsKey(location) || - location.SymbolOpt is IParameterSymbol parameter && + location.Symbol is IParameterSymbol parameter && parameter.Type.IsReferenceType && Equals(parameter.ContainingSymbol, GetBottomOfStackOwningSymbol()); ISymbol GetBottomOfStackOwningSymbol() { - if (DataFlowAnalysisContext.InterproceduralAnalysisDataOpt == null) + if (DataFlowAnalysisContext.InterproceduralAnalysisData == null) { return OwningSymbol; } - return DataFlowAnalysisContext.InterproceduralAnalysisDataOpt.MethodsBeingAnalyzed - .Single(m => m.InterproceduralAnalysisDataOpt == null) + return DataFlowAnalysisContext.InterproceduralAnalysisData.MethodsBeingAnalyzed + .Single(m => m.InterproceduralAnalysisData == null) .OwningSymbol; } } @@ -184,7 +184,7 @@ private void HandleHazardousOperation(SyntaxNode syntaxNode, IEnumerable Equals(l.SymbolOpt, parameter))); + HandleHazardousOperation(syntaxNode, notValidatedLocations.Where(l => Equals(l.Symbol, parameter))); } } } diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/ParameterValidationAnalysis/ParameterValidationAnalysisContext.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/ParameterValidationAnalysis/ParameterValidationAnalysisContext.cs index d05730fa0c..9035423b6d 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/ParameterValidationAnalysis/ParameterValidationAnalysisContext.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/ParameterValidationAnalysis/ParameterValidationAnalysisContext.cs @@ -90,8 +90,8 @@ public ParameterValidationAnalysisContext WithTrackHazardousParameterUsages() ValueDomain, WellKnownTypeProvider, ControlFlowGraph, OwningSymbol, AnalyzerOptions, NullCheckValidationMethodNames, InterproceduralAnalysisConfiguration, PessimisticAnalysis, - PointsToAnalysisResultOpt, TryGetOrComputeAnalysisResult, ParentControlFlowGraphOpt, - InterproceduralAnalysisDataOpt, trackHazardousParameterUsages: true); + PointsToAnalysisResult, TryGetOrComputeAnalysisResult, ParentControlFlowGraph, + InterproceduralAnalysisData, trackHazardousParameterUsages: true); public bool TrackHazardousParameterUsages { get; } diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/DefaultPointsToValueGenerator.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/DefaultPointsToValueGenerator.cs index d5e824ecbb..1dff703d03 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/DefaultPointsToValueGenerator.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/DefaultPointsToValueGenerator.cs @@ -25,9 +25,9 @@ public PointsToAbstractValue GetOrCreateDefaultValue(AnalysisEntity analysisEnti { if (!_defaultPointsToValueMapBuilder.TryGetValue(analysisEntity, out PointsToAbstractValue value)) { - if (analysisEntity.SymbolOpt?.Kind == SymbolKind.Local || - analysisEntity.SymbolOpt is IParameterSymbol parameter && parameter.RefKind == RefKind.Out || - analysisEntity.CaptureIdOpt != null) + if (analysisEntity.Symbol?.Kind == SymbolKind.Local || + analysisEntity.Symbol is IParameterSymbol parameter && parameter.RefKind == RefKind.Out || + analysisEntity.CaptureId != null) { return PointsToAbstractValue.Undefined; } diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAbstractValue.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAbstractValue.cs index 67becc8c00..5a68ff30c5 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAbstractValue.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAbstractValue.cs @@ -33,7 +33,7 @@ private PointsToAbstractValue(ImmutableHashSet locations, Null Debug.Assert(locations.All(location => !location.IsNull) || nullState != NullAbstractValue.NotNull); Debug.Assert(nullState != NullAbstractValue.Undefined); Debug.Assert(nullState != NullAbstractValue.Invalid); - Debug.Assert(!locations.Any(l => l.IsAnalysisEntityDefaultLocation && l.AnalysisEntityOpt!.HasUnknownInstanceLocation)); + Debug.Assert(!locations.Any(l => l.IsAnalysisEntityDefaultLocation && l.AnalysisEntity!.HasUnknownInstanceLocation)); Debug.Assert(locations.Count <= LocationThreshold); Locations = locations; diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAnalysis.PointsToDataFlowOperationVisitor.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAnalysis.PointsToDataFlowOperationVisitor.cs index 7b2670945e..9f24dc083e 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAnalysis.PointsToDataFlowOperationVisitor.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAnalysis.PointsToDataFlowOperationVisitor.cs @@ -40,7 +40,7 @@ private sealed class PointsToDataFlowOperationVisitor : _escapedReturnValueLocationsBuilder = PooledDictionary.Builder>.GetInstance(); _escapedEntityLocationsBuilder = PooledDictionary.Builder>.GetInstance(); - analysisContext.InterproceduralAnalysisDataOpt?.InitialAnalysisData.AssertValidPointsToAnalysisData(); + analysisContext.InterproceduralAnalysisData?.InitialAnalysisData.AssertValidPointsToAnalysisData(); } internal TrackedEntitiesBuilder TrackedEntitiesBuilder { get; } @@ -178,7 +178,7 @@ protected override void SetAbstractValue(AnalysisEntity analysisEntity, PointsTo Debug.Assert(value == _defaultPointsToValueGenerator.GetOrCreateDefaultValue(analysisEntity)); Debug.Assert(!CurrentAnalysisData.TryGetValue(analysisEntity, out var currentValue) || currentValue.Kind == PointsToAbstractValueKind.Unknown && - (analysisEntity.SymbolOpt as IParameterSymbol)?.RefKind == RefKind.Out); + (analysisEntity.Symbol as IParameterSymbol)?.RefKind == RefKind.Out); return; } @@ -255,7 +255,7 @@ private static void ResetAbstractValueIfTracked(AnalysisEntity analysisEntity, P protected override PointsToAbstractValue GetDefaultValueForParameterOnEntry(IParameterSymbol parameter, AnalysisEntity analysisEntity) => PointsToAnalysis.ShouldBeTracked(parameter.Type) ? PointsToAbstractValue.Create( - AbstractLocation.CreateSymbolLocation(parameter, DataFlowAnalysisContext.InterproceduralAnalysisDataOpt?.CallStack), + AbstractLocation.CreateSymbolLocation(parameter, DataFlowAnalysisContext.InterproceduralAnalysisData?.CallStack), mayBeNull: !parameter.IsParams) : PointsToAbstractValue.NoLocation; @@ -264,7 +264,7 @@ protected override void EscapeValueForParameterOnExit(IParameterSymbol parameter // Mark PointsTo values for ref/out parameters in non-interprocedural context as escaped. if (parameter.RefKind == RefKind.Ref || parameter.RefKind == RefKind.Out) { - Debug.Assert(DataFlowAnalysisContext.InterproceduralAnalysisDataOpt == null); + Debug.Assert(DataFlowAnalysisContext.InterproceduralAnalysisData == null); var pointsToValue = GetAbstractValue(analysisEntity); HandleEscapingLocations(analysisEntity, _escapedEntityLocationsBuilder, analysisEntity, pointsToValue); } @@ -322,7 +322,7 @@ protected override void PostProcessArgument(IArgumentOperation operation, bool i { CacheAbstractValue(operation, GetAbstractValue(analysisEntity)); - if (analysisEntity.SymbolOpt?.Kind == SymbolKind.Field) + if (analysisEntity.Symbol?.Kind == SymbolKind.Field) { // Ref/Out field argument is considered escaped. HandleEscapingOperation(operation, operation); @@ -348,7 +348,7 @@ protected override void ProcessReturnValue(IOperation? returnValue) // Escape the return value if we are not analyzing an invoked method during interprocedural analysis. if (returnValue != null && - DataFlowAnalysisContext.InterproceduralAnalysisDataOpt == null) + DataFlowAnalysisContext.InterproceduralAnalysisData == null) { HandleEscapingOperation(escapingOperation: returnValue, escapedInstance: returnValue, _escapedReturnValueLocationsBuilder); } @@ -560,7 +560,7 @@ protected override PointsToAnalysisData GetTrimmedCurrentAnalysisData(IEnumerabl protected override PointsToAnalysisData GetInitialInterproceduralAnalysisData( IMethodSymbol invokedMethod, - (AnalysisEntity? InstanceOpt, PointsToAbstractValue PointsToValue)? invocationInstance, + (AnalysisEntity? Instance, PointsToAbstractValue PointsToValue)? invocationInstance, (AnalysisEntity Instance, PointsToAbstractValue PointsToValue)? thisOrMeInstanceForCaller, ImmutableDictionary> argumentValuesMap, IDictionary? pointsToValues, @@ -659,7 +659,7 @@ private static void HandleEscapingLocations(PointsToAbstractValue pointsToValueO { // Only escape locations associated with creations. // We can expand this for more cases in future if need arises. - if (escapedLocation.CreationOpt != null) + if (escapedLocation.Creation != null) { builder.Add(escapedLocation); } @@ -739,7 +739,7 @@ public override PointsToAbstractValue VisitInstanceReference(IInstanceReferenceO var value = currentInstanceOperation != null ? GetCachedAbstractValue(currentInstanceOperation) : ThisOrMePointsToAbstractValue; - Debug.Assert(value.NullState == NullAbstractValue.NotNull || DataFlowAnalysisContext.InterproceduralAnalysisDataOpt != null); + Debug.Assert(value.NullState == NullAbstractValue.NotNull || DataFlowAnalysisContext.InterproceduralAnalysisData != null); return value; } @@ -863,7 +863,7 @@ private PointsToAbstractValue VisitInvocationCommon(IOperation operation, IOpera { if (TryGetInterproceduralAnalysisResult(operation, out var interproceduralResult)) { - return interproceduralResult.ReturnValueAndPredicateKindOpt!.Value.Value; + return interproceduralResult.ReturnValueAndPredicateKind!.Value.Value; } AbstractLocation location = AbstractLocation.CreateAllocationLocation(operation, operation.Type, DataFlowAnalysisContext); diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAnalysisContext.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAnalysisContext.cs index 680381d04f..77e3b38a53 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAnalysisContext.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAnalysisContext.cs @@ -77,7 +77,7 @@ public sealed class PointsToAnalysisContext : AbstractDataFlowAnalysisContext addPart) diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAnalysisData.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAnalysisData.cs index 88a6c92be5..fe3249a93e 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAnalysisData.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAnalysisData.cs @@ -89,7 +89,7 @@ private static void AssertNoFlowCaptureEntitiesTracked(CorePointsToAnalysisData { foreach (var key in map.Keys) { - Debug.Assert(key.CaptureIdOpt == null); + Debug.Assert(key.CaptureId == null); } } diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysis.PropertySetDataFlowOperationVisitor.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysis.PropertySetDataFlowOperationVisitor.cs index ee3233df9d..b36ecbd76c 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysis.PropertySetDataFlowOperationVisitor.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysis.PropertySetDataFlowOperationVisitor.cs @@ -53,7 +53,7 @@ private sealed partial class PropertySetDataFlowOperationVisitor : public PropertySetDataFlowOperationVisitor(PropertySetAnalysisContext analysisContext) : base(analysisContext) { - Debug.Assert(analysisContext.PointsToAnalysisResultOpt != null); + Debug.Assert(analysisContext.PointsToAnalysisResult != null); this._hazardousUsageBuilder = ImmutableDictionary.CreateBuilder<(Location Location, IMethodSymbol? Method), HazardousUsageEvaluationResult>(); @@ -187,7 +187,7 @@ public override PropertySetAbstractValue VisitObjectCreation(IObjectCreationOper } else if (constructorMapper.MapFromValueContentAbstractValue != null) { - Debug.Assert(this.DataFlowAnalysisContext.ValueContentAnalysisResultOpt != null); + Debug.Assert(this.DataFlowAnalysisContext.ValueContentAnalysisResult != null); ArrayBuilder pointsToBuilder = ArrayBuilder.GetInstance(); ArrayBuilder valueContentBuilder = ArrayBuilder.GetInstance(); try @@ -319,7 +319,7 @@ protected override PropertySetAbstractValue VisitAssignmentOperation(IAssignment } else if (propertyMapper.MapFromValueContentAbstractValue != null) { - Debug.Assert(this.DataFlowAnalysisContext.ValueContentAnalysisResultOpt != null); + Debug.Assert(this.DataFlowAnalysisContext.ValueContentAnalysisResult != null); propertySetAbstractValueKind = propertyMapper.MapFromValueContentAbstractValue( this.GetValueContentAbstractValue(operation.Value)); } @@ -379,7 +379,7 @@ internal void ProcessExitBlock(PropertySetBlockAnalysisResult exitBlockOutput) foreach (KeyValuePair kvp in this.TrackedFieldPropertyAssignments) { - if (!this.DataFlowAnalysisContext.PointsToAnalysisResultOpt!.ExitBlockOutput.Data.TryGetValue( + if (!this.DataFlowAnalysisContext.PointsToAnalysisResult!.ExitBlockOutput.Data.TryGetValue( kvp.Key, out PointsToAbstractValue pointsToAbstractValue)) { continue; diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/TaintedDataAnalysis/TaintedDataAnalysis.TaintedDataOperationVisitor.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/TaintedDataAnalysis/TaintedDataAnalysis.TaintedDataOperationVisitor.cs index be4185d59e..0648514848 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/TaintedDataAnalysis/TaintedDataAnalysis.TaintedDataOperationVisitor.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/TaintedDataAnalysis/TaintedDataAnalysis.TaintedDataOperationVisitor.cs @@ -248,8 +248,8 @@ public override TaintedDataAbstractValue VisitObjectCreation(IObjectCreationOper else if (this.DataFlowAnalysisContext.SourceInfos.IsSourceMethod( method, visitedArguments, - new Lazy(() => DataFlowAnalysisContext.PointsToAnalysisResultOpt), - new Lazy<(PointsToAnalysisResult?, ValueContentAnalysisResult?)>(() => (DataFlowAnalysisContext.PointsToAnalysisResultOpt, DataFlowAnalysisContext.ValueContentAnalysisResultOpt)), + new Lazy(() => DataFlowAnalysisContext.PointsToAnalysisResult), + new Lazy<(PointsToAnalysisResult?, ValueContentAnalysisResult?)>(() => (DataFlowAnalysisContext.PointsToAnalysisResult, DataFlowAnalysisContext.ValueContentAnalysisResult)), out taintedTargets)) { foreach (string taintedTarget in taintedTargets) diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/TaintedDataAnalysis/TaintedDataAnalysis.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/TaintedDataAnalysis/TaintedDataAnalysis.cs index 4574aa483f..5f5a11817f 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/TaintedDataAnalysis/TaintedDataAnalysis.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/TaintedDataAnalysis/TaintedDataAnalysis.cs @@ -116,7 +116,7 @@ private TaintedDataAnalysis(TaintedDataAnalysisDomain analysisDomain, TaintedDat private static TaintedDataAnalysisResult? TryGetOrComputeResultForAnalysisContext(TaintedDataAnalysisContext analysisContext) { - TaintedDataAnalysisDomain analysisDomain = new TaintedDataAnalysisDomain(new CoreTaintedDataAnalysisDataDomain(analysisContext.PointsToAnalysisResultOpt)); + TaintedDataAnalysisDomain analysisDomain = new TaintedDataAnalysisDomain(new CoreTaintedDataAnalysisDataDomain(analysisContext.PointsToAnalysisResult)); TaintedDataOperationVisitor visitor = new TaintedDataOperationVisitor(analysisDomain, analysisContext); TaintedDataAnalysis analysis = new TaintedDataAnalysis(analysisDomain, visitor); return analysis.TryGetOrComputeResultCore(analysisContext, cacheResult: true); diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/ValueContentAnalysis/ValueContentAnalysis.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/ValueContentAnalysis/ValueContentAnalysis.cs index d7c364a1b8..f4faed8d71 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/ValueContentAnalysis/ValueContentAnalysis.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/ValueContentAnalysis/ValueContentAnalysis.cs @@ -99,7 +99,7 @@ private ValueContentAnalysis(ValueContentAnalysisDomain analysisDomain, ValueCon private static ValueContentAnalysisResult? TryGetOrComputeResultForAnalysisContext(ValueContentAnalysisContext analysisContext) { - var analysisDomain = new ValueContentAnalysisDomain(analysisContext.PointsToAnalysisResultOpt); + var analysisDomain = new ValueContentAnalysisDomain(analysisContext.PointsToAnalysisResult); var operationVisitor = new ValueContentDataFlowOperationVisitor(analysisDomain, analysisContext); var nullAnalysis = new ValueContentAnalysis(analysisDomain, operationVisitor); return nullAnalysis.TryGetOrComputeResultCore(analysisContext, cacheResult: true); diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/ValueContentAnalysis/ValueContentAnalysisContext.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/ValueContentAnalysis/ValueContentAnalysisContext.cs index 79fe7c8bf3..946e1c40e3 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/ValueContentAnalysis/ValueContentAnalysisContext.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/ValueContentAnalysis/ValueContentAnalysisContext.cs @@ -71,7 +71,7 @@ public sealed class ValueContentAnalysisContext : AbstractDataFlowAnalysisContex return new ValueContentAnalysisContext(ValueDomain, WellKnownTypeProvider, invokedControlFlowGraph, invokedMethod, AnalyzerOptions, InterproceduralAnalysisConfiguration, PessimisticAnalysis, copyAnalysisResult, pointsToAnalysisResult, TryGetOrComputeAnalysisResult, ControlFlowGraph, interproceduralAnalysisData, - InterproceduralAnalysisPredicateOpt); + InterproceduralAnalysisPredicate); } protected override void ComputeHashCodePartsSpecific(Action addPart) diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AbstractDataFlowAnalysisContext.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AbstractDataFlowAnalysisContext.cs index d3769fc2dd..6216b52e65 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AbstractDataFlowAnalysisContext.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AbstractDataFlowAnalysisContext.cs @@ -55,19 +55,19 @@ public abstract class AbstractDataFlowAnalysisContext ValueDomain { get; } @@ -79,16 +79,16 @@ public abstract class AbstractDataFlowAnalysisContext TryGetOrComputeAnalysisResult { get; } - protected ControlFlowGraph? ParentControlFlowGraphOpt { get; } + protected ControlFlowGraph? ParentControlFlowGraph { get; } // Optional data for context sensitive analysis. - public InterproceduralAnalysisData? InterproceduralAnalysisDataOpt { get; } - public InterproceduralAnalysisPredicate? InterproceduralAnalysisPredicateOpt { get; } + public InterproceduralAnalysisData? InterproceduralAnalysisData { get; } + public InterproceduralAnalysisPredicate? InterproceduralAnalysisPredicate { get; } public abstract TAnalysisContext ForkForInterproceduralAnalysis( IMethodSymbol invokedMethod, @@ -111,9 +111,9 @@ public abstract class AbstractDataFlowAnalysisContext context.ControlFlowGraph == ParentControlFlowGraphOpt); + var parentAnalysisContext = InterproceduralAnalysisData.MethodsBeingAnalyzed.FirstOrDefault(context => context.ControlFlowGraph == ParentControlFlowGraph); return parentAnalysisContext?.GetLocalFunctionControlFlowGraph(localFunction); } @@ -135,9 +135,9 @@ public abstract class AbstractDataFlowAnalysisContext context.ControlFlowGraph == ParentControlFlowGraphOpt); + var parentAnalysisContext = InterproceduralAnalysisData.MethodsBeingAnalyzed.FirstOrDefault(context => context.ControlFlowGraph == ParentControlFlowGraph); return parentAnalysisContext?.GetAnonymousFunctionControlFlowGraph(lambda); } @@ -162,11 +162,11 @@ protected sealed override void ComputeHashCodeParts(Action addPart) addPart(PessimisticAnalysis.GetHashCode()); addPart(PredicateAnalysis.GetHashCode()); addPart(ExceptionPathsAnalysis.GetHashCode()); - addPart(CopyAnalysisResultOpt.GetHashCodeOrDefault()); - addPart(PointsToAnalysisResultOpt.GetHashCodeOrDefault()); - addPart(ValueContentAnalysisResultOpt.GetHashCodeOrDefault()); - addPart(InterproceduralAnalysisDataOpt.GetHashCodeOrDefault()); - addPart(InterproceduralAnalysisPredicateOpt.GetHashCodeOrDefault()); + addPart(CopyAnalysisResult.GetHashCodeOrDefault()); + addPart(PointsToAnalysisResult.GetHashCodeOrDefault()); + addPart(ValueContentAnalysisResult.GetHashCodeOrDefault()); + addPart(InterproceduralAnalysisData.GetHashCodeOrDefault()); + addPart(InterproceduralAnalysisPredicate.GetHashCodeOrDefault()); ComputeHashCodePartsSpecific(addPart); } } diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AbstractLocation.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AbstractLocation.cs index 5fa24e43ae..b1303b8f7b 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AbstractLocation.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AbstractLocation.cs @@ -13,7 +13,7 @@ namespace Microsoft.CodeAnalysis.FlowAnalysis.DataFlow /// /// /// Represents an abstract analysis location. - /// This is may be used to represent a location where an resides, i.e. or + /// This is may be used to represent a location where an resides, i.e. or /// a location that is pointed to by a reference type variable, and tracked with . /// /// @@ -35,12 +35,12 @@ private AbstractLocation(IOperation? creation, ImmutableStack? creat { Debug.Assert(isSpecialSingleton ^ (locationType != null)); - CreationOpt = creation; + Creation = creation; CreationCallStack = creationCallStack ?? ImmutableStack.Empty; - AnalysisEntityOpt = analysisEntity; - SymbolOpt = symbol; - CaptureIdOpt = captureId; - LocationTypeOpt = locationType; + AnalysisEntity = analysisEntity; + Symbol = symbol; + CaptureId = captureId; + LocationType = locationType; _isSpecialSingleton = isSpecialSingleton; } @@ -53,7 +53,7 @@ private static AbstractLocation Create(IOperation? creation, ImmutableStack CreateAllocationLocation(creation, locationType, analysisContext.InterproceduralAnalysisDataOpt?.CallStack); + => CreateAllocationLocation(creation, locationType, analysisContext.InterproceduralAnalysisData?.CallStack); internal static AbstractLocation CreateAllocationLocation(IOperation creation, ITypeSymbol locationType, ImmutableStack? callStack) => Create(creation, callStack, analysisEntity: null, symbol: null, captureId: null, locationType: locationType); public static AbstractLocation CreateAnalysisEntityDefaultLocation(AnalysisEntity analysisEntity) @@ -65,43 +65,43 @@ public static AbstractLocation CreateSymbolLocation(ISymbol symbol, ImmutableSta public static AbstractLocation CreateFlowCaptureLocation(InterproceduralCaptureId captureId, ITypeSymbol locationType, ImmutableStack? creationCallStack) => Create(creation: null, creationCallStack: creationCallStack, analysisEntity: null, symbol: null, captureId: captureId, locationType: locationType); - public IOperation? CreationOpt { get; } + public IOperation? Creation { get; } public ImmutableStack CreationCallStack { get; } /// /// Returns the top of if this location was created through an interprocedural method invocation, i.e. is non-empty. - /// Otherwise, returns . + /// Otherwise, returns . /// public IOperation? GetTopOfCreationCallStackOrCreation() { if (CreationCallStack.IsEmpty) { - return CreationOpt; + return Creation; } return CreationCallStack.Peek(); } - public AnalysisEntity? AnalysisEntityOpt { get; } - public ISymbol? SymbolOpt { get; } - public InterproceduralCaptureId? CaptureIdOpt { get; } - public ITypeSymbol? LocationTypeOpt { get; } + public AnalysisEntity? AnalysisEntity { get; } + public ISymbol? Symbol { get; } + public InterproceduralCaptureId? CaptureId { get; } + public ITypeSymbol? LocationType { get; } public bool IsNull => ReferenceEquals(this, Null); public bool IsNoLocation => ReferenceEquals(this, NoLocation); /// /// Indicates this represents the initial unknown but distinct location for an analysis entity. /// - public bool IsAnalysisEntityDefaultLocation => AnalysisEntityOpt != null; + public bool IsAnalysisEntityDefaultLocation => AnalysisEntity != null; protected override void ComputeHashCodeParts(Action addPart) { - addPart(CreationOpt.GetHashCodeOrDefault()); + addPart(Creation.GetHashCodeOrDefault()); addPart(HashUtilities.Combine(CreationCallStack)); - addPart(SymbolOpt.GetHashCodeOrDefault()); - addPart(CaptureIdOpt.GetHashCodeOrDefault()); - addPart(AnalysisEntityOpt.GetHashCodeOrDefault()); - addPart(LocationTypeOpt.GetHashCodeOrDefault()); + addPart(Symbol.GetHashCodeOrDefault()); + addPart(CaptureId.GetHashCodeOrDefault()); + addPart(AnalysisEntity.GetHashCodeOrDefault()); + addPart(LocationType.GetHashCodeOrDefault()); addPart(_isSpecialSingleton.GetHashCode()); addPart(IsNull.GetHashCode()); } @@ -112,7 +112,7 @@ protected override void ComputeHashCodeParts(Action addPart) /// public SyntaxNode? TryGetNodeToReportDiagnostic(PointsToAnalysisResult? pointsToAnalysisResult) { - Debug.Assert(CreationOpt != null); + Debug.Assert(Creation != null); if (pointsToAnalysisResult != null) { @@ -134,7 +134,7 @@ protected override void ComputeHashCodeParts(Action addPart) } // Fallback to reporting the diagnostic on the allocation location. - return CreationOpt?.Syntax; + return Creation?.Syntax; // Local functions. SyntaxNode? TryGetSyntaxNodeToReportDiagnostic(IOperation creation, PointsToAnalysisResult pointsToAnalysisResult) @@ -175,8 +175,8 @@ protected override void ComputeHashCodeParts(Action addPart) } } - if (pointsToAnalysisResult.TaskWrappedValuesMapOpt != null && - pointsToAnalysisResult.TaskWrappedValuesMapOpt.TryGetValue(pointsToValue, out var wrappedValue)) + if (pointsToAnalysisResult.TaskWrappedValuesMap != null && + pointsToAnalysisResult.TaskWrappedValuesMap.TryGetValue(pointsToValue, out var wrappedValue)) { return TryGetSyntaxNodeToReportDiagnosticForPointsValue(wrappedValue, operation); } diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AbstractLocationDataFlowOperationVisitor.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AbstractLocationDataFlowOperationVisitor.cs index c727484b4c..71f5359ecd 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AbstractLocationDataFlowOperationVisitor.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AbstractLocationDataFlowOperationVisitor.cs @@ -20,7 +20,7 @@ public abstract class AbstractLocationDataFlowOperationVisitor locations, TAbstra protected abstract void StopTrackingAbstractValue(AbstractLocation location); protected override void StopTrackingDataForParameter(IParameterSymbol parameter, AnalysisEntity analysisEntity) { - Debug.Assert(DataFlowAnalysisContext.InterproceduralAnalysisDataOpt != null); + Debug.Assert(DataFlowAnalysisContext.InterproceduralAnalysisData != null); if (parameter.RefKind == RefKind.None) { foreach (var location in analysisEntity.InstanceLocation.Locations) @@ -94,8 +94,8 @@ protected override void SetValueForParameterOnEntry(IParameterSymbol parameter, // Only set the value for non-interprocedural case. // For interprocedural case, we have already initialized values for the underlying locations // of arguments from the input analysis data. - Debug.Assert(Equals(analysisEntity.SymbolOpt, parameter)); - if (DataFlowAnalysisContext.InterproceduralAnalysisDataOpt == null && + Debug.Assert(Equals(analysisEntity.Symbol, parameter)); + if (DataFlowAnalysisContext.InterproceduralAnalysisData == null && TryGetPointsToAbstractValueAtEntryBlockEnd(analysisEntity, out PointsToAbstractValue pointsToAbstractValue)) { SetValueForParameterPointsToLocationOnEntry(parameter, pointsToAbstractValue); @@ -104,7 +104,7 @@ protected override void SetValueForParameterOnEntry(IParameterSymbol parameter, protected override void EscapeValueForParameterOnExit(IParameterSymbol parameter, AnalysisEntity analysisEntity) { - Debug.Assert(Equals(analysisEntity.SymbolOpt, parameter)); + Debug.Assert(Equals(analysisEntity.Symbol, parameter)); var escapedLocationsForParameter = GetEscapedLocations(analysisEntity); if (!escapedLocationsForParameter.IsEmpty) { diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AddressSharedEntitiesProvider.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AddressSharedEntitiesProvider.cs index fe4347e088..a7c907fa7c 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AddressSharedEntitiesProvider.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AddressSharedEntitiesProvider.cs @@ -25,7 +25,7 @@ internal sealed class AddressSharedEntitiesProvider(); - SetAddressSharedEntities(analysisContext.InterproceduralAnalysisDataOpt?.AddressSharedEntities); + SetAddressSharedEntities(analysisContext.InterproceduralAnalysisData?.AddressSharedEntities); } public void SetAddressSharedEntities(ImmutableDictionary? addressSharedEntities) @@ -40,7 +40,7 @@ public void SetAddressSharedEntities(ImmutableDictionary? assignedValue) { if (parameter.RefKind != RefKind.None && - assignedValue?.AnalysisEntityOpt != null) + assignedValue?.AnalysisEntity != null) { var addressSharedEntities = ComputeAddressSharedEntities(); var isReferenceCopy = !addressSharedEntities.Any(a => a.Type.IsValueType); @@ -53,15 +53,15 @@ public void UpdateAddressSharedEntitiesForParameter(IParameterSymbol parameter, ImmutableHashSet ComputeAddressSharedEntities() { - RoslynDebug.Assert(assignedValue?.AnalysisEntityOpt != null); + RoslynDebug.Assert(assignedValue?.AnalysisEntity != null); var builder = PooledHashSet.GetInstance(); AddIfHasKnownInstanceLocation(analysisEntity, builder); - AddIfHasKnownInstanceLocation(assignedValue.AnalysisEntityOpt, builder); + AddIfHasKnownInstanceLocation(assignedValue.AnalysisEntity, builder); // We need to handle multiple ref/out parameters passed the same location. // For example, "M(ref a, ref a);" - if (_addressSharedEntitiesBuilder.TryGetValue(assignedValue.AnalysisEntityOpt, out var existingValue)) + if (_addressSharedEntitiesBuilder.TryGetValue(assignedValue.AnalysisEntity, out var existingValue)) { foreach (var entity in existingValue.AnalysisEntities) { diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AnalysisEntity.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AnalysisEntity.cs index ad3d5c8824..d4067ee567 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AnalysisEntity.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AnalysisEntity.cs @@ -48,13 +48,13 @@ public sealed class AnalysisEntity : CacheBasedEquatable Debug.Assert(symbol != null || !indices.IsEmpty || instanceReferenceOperationSyntax != null || captureId.HasValue); Debug.Assert(parent == null || parent.Type.HasValueCopySemantics() || !indices.IsEmpty); - SymbolOpt = symbol; + Symbol = symbol; Indices = indices; - InstanceReferenceOperationSyntaxOpt = instanceReferenceOperationSyntax; - CaptureIdOpt = captureId; + InstanceReferenceOperationSyntax = instanceReferenceOperationSyntax; + CaptureId = captureId; InstanceLocation = location; Type = type; - ParentOpt = parent; + Parent = parent; IsThisOrMeInstance = isThisOrMeInstance; _ignoringLocationHashCodeParts = ComputeIgnoringLocationHashCodeParts(); @@ -111,8 +111,8 @@ public static AnalysisEntity Create(IInstanceReferenceOperation instanceReferenc public static AnalysisEntity CreateThisOrMeInstance(INamedTypeSymbol typeSymbol, PointsToAbstractValue instanceLocation) { Debug.Assert(instanceLocation.Locations.Count == 1); - Debug.Assert(instanceLocation.Locations.Single().CreationOpt == null); - Debug.Assert(Equals(instanceLocation.Locations.Single().SymbolOpt, typeSymbol)); + Debug.Assert(instanceLocation.Locations.Single().Creation == null); + Debug.Assert(Equals(instanceLocation.Locations.Single().Symbol, typeSymbol)); return new AnalysisEntity(typeSymbol, instanceLocation, isThisOrMeInstance: true); } @@ -123,7 +123,7 @@ public AnalysisEntity WithMergedInstanceLocation(AnalysisEntity analysisEntityTo Debug.Assert(!InstanceLocation.Equals(analysisEntityToMerge.InstanceLocation)); var mergedInstanceLocation = PointsToAnalysis.PointsToAnalysis.PointsToAbstractValueDomainInstance.Merge(InstanceLocation, analysisEntityToMerge.InstanceLocation); - return new AnalysisEntity(SymbolOpt, Indices, InstanceReferenceOperationSyntaxOpt, CaptureIdOpt, mergedInstanceLocation, Type, ParentOpt, IsThisOrMeInstance); + return new AnalysisEntity(Symbol, Indices, InstanceReferenceOperationSyntax, CaptureId, mergedInstanceLocation, Type, Parent, IsThisOrMeInstance); } public bool IsChildOrInstanceMember @@ -136,11 +136,11 @@ public bool IsChildOrInstanceMember } bool result; - if (SymbolOpt != null) + if (Symbol != null) { - result = SymbolOpt.Kind != SymbolKind.Parameter && - SymbolOpt.Kind != SymbolKind.Local && - !SymbolOpt.IsStatic; + result = Symbol.Kind != SymbolKind.Parameter && + Symbol.Kind != SymbolKind.Local && + !Symbol.IsStatic; } else if (!Indices.IsEmpty) { @@ -151,7 +151,7 @@ public bool IsChildOrInstanceMember result = false; } - Debug.Assert(ParentOpt == null || result); + Debug.Assert(Parent == null || result); return result; } } @@ -166,14 +166,14 @@ internal bool IsChildOrInstanceMemberNeedingCompletePointsToAnalysis() // PERF: This is the core performance optimization for partial PointsToAnalysisKind. // We avoid tracking PointsToValues for all entities that are child or instance members, // except when they are fields or members of a value type (for example, tuple elements or struct members). - return ParentOpt == null || !ParentOpt.Type.HasValueCopySemantics(); + return Parent == null || !Parent.Type.HasValueCopySemantics(); } public bool HasConstantValue { get { - return SymbolOpt switch + return Symbol switch { IFieldSymbol field => field.HasConstantValue, @@ -184,13 +184,13 @@ public bool HasConstantValue } } - public ISymbol? SymbolOpt { get; } + public ISymbol? Symbol { get; } public ImmutableArray Indices { get; } - public SyntaxNode? InstanceReferenceOperationSyntaxOpt { get; } - public InterproceduralCaptureId? CaptureIdOpt { get; } + public SyntaxNode? InstanceReferenceOperationSyntax { get; } + public InterproceduralCaptureId? CaptureId { get; } public PointsToAbstractValue InstanceLocation { get; } public ITypeSymbol Type { get; } - public AnalysisEntity? ParentOpt { get; } + public AnalysisEntity? Parent { get; } public bool IsThisOrMeInstance { get; } public bool HasUnknownInstanceLocation @@ -210,7 +210,7 @@ public bool HasUnknownInstanceLocation } } - public bool IsLValueFlowCaptureEntity => CaptureIdOpt.HasValue && CaptureIdOpt.Value.IsLValueFlowCapture; + public bool IsLValueFlowCaptureEntity => CaptureId.HasValue && CaptureId.Value.IsLValueFlowCapture; public bool EqualsIgnoringInstanceLocation(AnalysisEntity? other) { @@ -240,12 +240,12 @@ protected override void ComputeHashCodeParts(Action addPart) private void ComputeHashCodePartsIgnoringLocation(Action addPart) { - addPart(SymbolOpt.GetHashCodeOrDefault()); + addPart(Symbol.GetHashCodeOrDefault()); addPart(HashUtilities.Combine(Indices)); - addPart(InstanceReferenceOperationSyntaxOpt.GetHashCodeOrDefault()); - addPart(CaptureIdOpt.GetHashCodeOrDefault()); + addPart(InstanceReferenceOperationSyntax.GetHashCodeOrDefault()); + addPart(CaptureId.GetHashCodeOrDefault()); addPart(Type.GetHashCode()); - addPart(ParentOpt.GetHashCodeOrDefault()); + addPart(Parent.GetHashCodeOrDefault()); addPart(IsThisOrMeInstance.GetHashCode()); } @@ -258,7 +258,7 @@ private ImmutableArray ComputeIgnoringLocationHashCodeParts() public bool HasAncestor(AnalysisEntity ancestor) { - AnalysisEntity? current = this.ParentOpt; + AnalysisEntity? current = this.Parent; while (current != null) { if (current == ancestor) @@ -266,7 +266,7 @@ public bool HasAncestor(AnalysisEntity ancestor) return true; } - current = current.ParentOpt; + current = current.Parent; } return false; diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AnalysisEntityDataFlowOperationVisitor.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AnalysisEntityDataFlowOperationVisitor.cs index b15de63703..312008e447 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AnalysisEntityDataFlowOperationVisitor.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AnalysisEntityDataFlowOperationVisitor.cs @@ -159,7 +159,7 @@ private void StopTrackingDataForEntity(AnalysisEntity analysisEntity, TAnalysisD private void StopTrackingDataForParamArrayParameterIndices(AnalysisEntity analysisEntity, TAnalysisData analysisData, PooledHashSet allEntities) { - Debug.Assert(analysisEntity.SymbolOpt is IParameterSymbol parameter && parameter.IsParams); + Debug.Assert(analysisEntity.Symbol is IParameterSymbol parameter && parameter.IsParams); foreach (var entity in allEntities) { @@ -312,7 +312,7 @@ private void SetAbstractValueForAssignment(AnalysisEntity targetAnalysisEntity, protected override void SetValueForParameterOnEntry(IParameterSymbol parameter, AnalysisEntity analysisEntity, ArgumentInfo? assignedValue) { - Debug.Assert(Equals(analysisEntity.SymbolOpt, parameter)); + Debug.Assert(Equals(analysisEntity.Symbol, parameter)); if (assignedValue != null) { SetAbstractValueForAssignment(analysisEntity, assignedValue.Operation, assignedValue.Value); @@ -325,7 +325,7 @@ protected override void SetValueForParameterOnEntry(IParameterSymbol parameter, protected override void EscapeValueForParameterOnExit(IParameterSymbol parameter, AnalysisEntity analysisEntity) { - Debug.Assert(Equals(analysisEntity.SymbolOpt, parameter)); + Debug.Assert(Equals(analysisEntity.Symbol, parameter)); if (parameter.RefKind != RefKind.None) { SetAbstractValue(analysisEntity, GetDefaultValueForParameterOnExit(analysisEntity.Type)); @@ -487,7 +487,7 @@ private ImmutableHashSet GetChildAnalysisEntities(Func> argumentValuesMap, IDictionary? pointsToValues, @@ -530,7 +530,7 @@ private ImmutableHashSet GetChildAnalysisEntities(Func GetChildAnalysisEntities(Func ind public AnalysisEntity CreateWithNewInstanceRoot(AnalysisEntity analysisEntity, AnalysisEntity newRootInstance) { if (analysisEntity.InstanceLocation == newRootInstance.InstanceLocation && - analysisEntity.ParentOpt == newRootInstance.ParentOpt) + analysisEntity.Parent == newRootInstance.Parent) { return analysisEntity; } - if (analysisEntity.ParentOpt == null) + if (analysisEntity.Parent == null) { return newRootInstance; } - AnalysisEntity parentOpt = CreateWithNewInstanceRoot(analysisEntity.ParentOpt, newRootInstance); - return Create(analysisEntity.SymbolOpt, analysisEntity.Indices, analysisEntity.Type, newRootInstance.InstanceLocation, parentOpt); + AnalysisEntity parentOpt = CreateWithNewInstanceRoot(analysisEntity.Parent, newRootInstance); + return Create(analysisEntity.Symbol, analysisEntity.Indices, analysisEntity.Type, newRootInstance.InstanceLocation, parentOpt); } } } \ No newline at end of file diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AnalysisEntityMapAbstractDomain.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AnalysisEntityMapAbstractDomain.cs index b6e10dc85a..c16ad2ad81 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AnalysisEntityMapAbstractDomain.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AnalysisEntityMapAbstractDomain.cs @@ -50,8 +50,8 @@ private bool CanSkipNewEntity(AnalysisEntity analysisEntity) return false; } - if (analysisEntity.ParentOpt != null && - !CanSkipNewEntity(analysisEntity.ParentOpt)) + if (analysisEntity.Parent != null && + !CanSkipNewEntity(analysisEntity.Parent)) { return false; } @@ -120,7 +120,7 @@ protected virtual void AssertValidAnalysisData(DictionaryAnalysisData entity.SymbolOpt?.Kind == SymbolKind.Field || entity.SymbolOpt?.Kind == SymbolKind.Property; + => entity.Symbol?.Kind == SymbolKind.Field || entity.Symbol?.Kind == SymbolKind.Property; TValue GetMergedValueForEntityPresentInOneMap(AnalysisEntity key, TValue value) { diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/ArgumentInfo.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/ArgumentInfo.cs index a514ece950..918ee268c6 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/ArgumentInfo.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/ArgumentInfo.cs @@ -18,21 +18,21 @@ public sealed class ArgumentInfo : CacheBasedEquatable addPart) { addPart(Operation.GetHashCode()); - addPart(AnalysisEntityOpt.GetHashCodeOrDefault()); + addPart(AnalysisEntity.GetHashCodeOrDefault()); addPart(InstanceLocation.GetHashCode()); addPart(Value.GetHashCodeOrDefault()); } diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/DataFlowAnalysis.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/DataFlowAnalysis.cs index 8aa9db22a9..229199aab8 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/DataFlowAnalysis.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/DataFlowAnalysis.cs @@ -40,7 +40,7 @@ protected DataFlowAnalysis(AbstractAnalysisDomain analysisDomain, } // Don't add interprocedural analysis result to our static results cache. - if (!cacheResult || analysisContext.InterproceduralAnalysisDataOpt != null) + if (!cacheResult || analysisContext.InterproceduralAnalysisData != null) { return Run(analysisContext); } @@ -104,7 +104,7 @@ protected DataFlowAnalysis(AbstractAnalysisDomain analysisDomain, // Initialize the input of the entry block. // For context sensitive inter-procedural analysis, use the provided initial analysis data. // Otherwise, initialize with the default bottom value of the analysis domain. - var initialAnalysisData = analysisContext.InterproceduralAnalysisDataOpt?.InitialAnalysisData; + var initialAnalysisData = analysisContext.InterproceduralAnalysisData?.InitialAnalysisData; UpdateInput(resultBuilder, entry, GetClonedAnalysisDataOrEmptyData(initialAnalysisData)); // Add the block to the worklist. @@ -156,7 +156,7 @@ protected DataFlowAnalysis(AbstractAnalysisDomain analysisDomain, OperationVisitor.GetPredicateValueKindMap(), OperationVisitor.GetReturnValueAndPredicateKind(), OperationVisitor.InterproceduralResultsMap, resultBuilder.EntryBlockOutputData!, normalPathsExitBlockData!, exceptionPathsExitBlockData, mergedDataForUnhandledThrowOperations, OperationVisitor.AnalysisDataForUnhandledThrowOperations, - OperationVisitor.TaskWrappedValuesMapOpt, cfg, OperationVisitor.ValueDomain.UnknownOrMayBeValue); + OperationVisitor.TaskWrappedValuesMap, cfg, OperationVisitor.ValueDomain.UnknownOrMayBeValue); return ToResult(analysisContext, dataflowAnalysisResult); } finally diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/DataFlowAnalysisResult.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/DataFlowAnalysisResult.cs index 61f6635bdc..e17602e8b2 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/DataFlowAnalysisResult.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/DataFlowAnalysisResult.cs @@ -44,22 +44,22 @@ public class DataFlowAnalysisResult other) - : this(other._basicBlockStateMap, other._operationStateMap, other._predicateValueKindMap, other.ReturnValueAndPredicateKindOpt, - other._interproceduralResultsMap, other.EntryBlockOutput, other.ExitBlockOutput, other.ExceptionPathsExitBlockOutputOpt, - other.MergedStateForUnhandledThrowOperationsOpt, other._analysisDataForUnhandledThrowOperations, other.TaskWrappedValuesMapOpt, + : this(other._basicBlockStateMap, other._operationStateMap, other._predicateValueKindMap, other.ReturnValueAndPredicateKind, + other._interproceduralResultsMap, other.EntryBlockOutput, other.ExitBlockOutput, other.ExceptionPathsExitBlockOutput, + other.MergedStateForUnhandledThrowOperations, other._analysisDataForUnhandledThrowOperations, other.TaskWrappedValuesMap, other.ControlFlowGraph, other._defaultUnknownValue) { } @@ -69,9 +69,9 @@ protected DataFlowAnalysisResult(DataFlowAnalysisResult( - _basicBlockStateMap, _operationStateMap, _predicateValueKindMap, ReturnValueAndPredicateKindOpt, - _interproceduralResultsMap, EntryBlockOutput, ExitBlockOutput, ExceptionPathsExitBlockOutputOpt, mergedStateForUnhandledThrowOperationsOpt, - analysisDataForUnhandledThrowOperations, TaskWrappedValuesMapOpt, ControlFlowGraph, _defaultUnknownValue); + _basicBlockStateMap, _operationStateMap, _predicateValueKindMap, ReturnValueAndPredicateKind, + _interproceduralResultsMap, EntryBlockOutput, ExitBlockOutput, ExceptionPathsExitBlockOutput, mergedStateForUnhandledThrowOperationsOpt, + analysisDataForUnhandledThrowOperations, TaskWrappedValuesMap, ControlFlowGraph, _defaultUnknownValue); } #pragma warning disable CA1043 // Use Integral Or String Argument For Indexers @@ -136,19 +136,19 @@ protected DataFlowAnalysisResult(DataFlowAnalysisResult.AnalysisDataForUnhandledThrowOperationsOpt + object? IDataFlowAnalysisResult.AnalysisDataForUnhandledThrowOperations => _analysisDataForUnhandledThrowOperations; - object? IDataFlowAnalysisResult.TaskWrappedValuesMapOpt - => TaskWrappedValuesMapOpt; + object? IDataFlowAnalysisResult.TaskWrappedValuesMap + => TaskWrappedValuesMap; - public TBlockAnalysisResult? MergedStateForUnhandledThrowOperationsOpt { get; } + public TBlockAnalysisResult? MergedStateForUnhandledThrowOperations { get; } public PredicateValueKind GetPredicateKind(IOperation operation) => _predicateValueKindMap.TryGetValue(operation, out var valueKind) ? valueKind : PredicateValueKind.Unknown; - internal Dictionary? TaskWrappedValuesMapOpt { get; } + internal Dictionary? TaskWrappedValuesMap { get; } } } diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/DataFlowOperationVisitor.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/DataFlowOperationVisitor.cs index 686d889973..d94dc0e12c 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/DataFlowOperationVisitor.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/DataFlowOperationVisitor.cs @@ -122,7 +122,7 @@ private uint MaxInterproceduralLambdaOrLocalFunctionCallChain /// Optional map from points to values of tasks to the underlying abstract value returned by the task. /// Awaiting the task produces the task wrapped value from this map. /// - internal Dictionary? TaskWrappedValuesMapOpt { get; private set; } + internal Dictionary? TaskWrappedValuesMap { get; private set; } protected TAnalysisContext DataFlowAnalysisContext { get; } public AbstractValueDomain ValueDomain => DataFlowAnalysisContext.ValueDomain; @@ -203,7 +203,7 @@ private ThrownExceptionInfo DefaultThrownExceptionInfo if (!_exceptionPathsThrownExceptionInfoMap.TryGetValue(CurrentBasicBlock, out var info)) { info = ThrownExceptionInfo.CreateDefaultInfoForExceptionsPathAnalysis( - CurrentBasicBlock, WellKnownTypeProvider, DataFlowAnalysisContext.InterproceduralAnalysisDataOpt?.CallStack); + CurrentBasicBlock, WellKnownTypeProvider, DataFlowAnalysisContext.InterproceduralAnalysisData?.CallStack); } return info; @@ -243,14 +243,14 @@ protected DataFlowOperationVisitor(TAnalysisContext analysisContext) _interproceduralCallStack = new Stack(); _addressSharedEntitiesProvider = new AddressSharedEntitiesProvider(analysisContext); - if (analysisContext.InterproceduralAnalysisDataOpt != null) + if (analysisContext.InterproceduralAnalysisData != null) { - foreach (var argumentInfo in analysisContext.InterproceduralAnalysisDataOpt.ArgumentValuesMap.Values) + foreach (var argumentInfo in analysisContext.InterproceduralAnalysisData.ArgumentValuesMap.Values) { CacheAbstractValue(argumentInfo.Operation, argumentInfo.Value); } - foreach (var operation in analysisContext.InterproceduralAnalysisDataOpt.CallStack) + foreach (var operation in analysisContext.InterproceduralAnalysisData.CallStack) { _interproceduralCallStack.Push(operation); } @@ -263,9 +263,9 @@ protected DataFlowOperationVisitor(TAnalysisContext analysisContext) } AnalysisEntity? interproceduralInvocationInstance; - if (analysisContext.InterproceduralAnalysisDataOpt?.InvocationInstanceOpt.HasValue == true) + if (analysisContext.InterproceduralAnalysisData?.InvocationInstance.HasValue == true) { - (interproceduralInvocationInstance, ThisOrMePointsToAbstractValue) = analysisContext.InterproceduralAnalysisDataOpt.InvocationInstanceOpt!.Value; + (interproceduralInvocationInstance, ThisOrMePointsToAbstractValue) = analysisContext.InterproceduralAnalysisData.InvocationInstance!.Value; } else { @@ -275,7 +275,7 @@ protected DataFlowOperationVisitor(TAnalysisContext analysisContext) var pointsToAnalysisKind = analysisContext is PointsToAnalysisContext pointsToAnalysisContext ? pointsToAnalysisContext.PointsToAnalysisKind - : analysisContext.PointsToAnalysisResultOpt?.PointsToAnalysisKind ?? PointsToAnalysisKind.None; + : analysisContext.PointsToAnalysisResult?.PointsToAnalysisKind ?? PointsToAnalysisKind.None; HasPointsToAnalysisResult = pointsToAnalysisKind != PointsToAnalysisKind.None; HasCompletePointsToAnalysisResult = pointsToAnalysisKind == PointsToAnalysisKind.Complete; @@ -289,10 +289,10 @@ protected DataFlowOperationVisitor(TAnalysisContext analysisContext) getIsLValueFlowCapture: IsLValueFlowCapture, containingTypeSymbol: analysisContext.OwningSymbol.ContainingType, interproceduralInvocationInstance: interproceduralInvocationInstance, - interproceduralThisOrMeInstanceForCaller: analysisContext.InterproceduralAnalysisDataOpt?.ThisOrMeInstanceForCallerOpt?.Instance, - interproceduralCallStack: analysisContext.InterproceduralAnalysisDataOpt?.CallStack, - interproceduralCapturedVariablesMap: analysisContext.InterproceduralAnalysisDataOpt?.CapturedVariablesMap, - interproceduralGetAnalysisEntityForFlowCapture: analysisContext.InterproceduralAnalysisDataOpt?.GetAnalysisEntityForFlowCapture, + interproceduralThisOrMeInstanceForCaller: analysisContext.InterproceduralAnalysisData?.ThisOrMeInstanceForCaller?.Instance, + interproceduralCallStack: analysisContext.InterproceduralAnalysisData?.CallStack, + interproceduralCapturedVariablesMap: analysisContext.InterproceduralAnalysisData?.CapturedVariablesMap, + interproceduralGetAnalysisEntityForFlowCapture: analysisContext.InterproceduralAnalysisData?.GetAnalysisEntityForFlowCapture, getInterproceduralCallStackForOwningSymbol: GetInterproceduralCallStackForOwningSymbol); return; @@ -359,7 +359,7 @@ private static PointsToAbstractValue GetThisOrMeInstancePointsToValue(TAnalysisC if (!owningSymbol.IsStatic && !owningSymbol.ContainingType.HasValueCopySemantics()) { - var thisOrMeLocation = AbstractLocation.CreateThisOrMeLocation(owningSymbol.ContainingType, analysisContext.InterproceduralAnalysisDataOpt?.CallStack); + var thisOrMeLocation = AbstractLocation.CreateThisOrMeLocation(owningSymbol.ContainingType, analysisContext.InterproceduralAnalysisData?.CallStack); return PointsToAbstractValue.Create(thisOrMeLocation, mayBeNull: false); } else @@ -439,8 +439,8 @@ public TAnalysisData OnEndBlockAnalysis(BasicBlock block, TAnalysisData analysis { foreach (var (exceptionInfo, dataAtException) in AnalysisDataForUnhandledThrowOperations) { - if (exceptionInfo.ContainingFinallyRegionOpt == null || - !finallyRegion.ContainsRegionOrSelf(exceptionInfo.ContainingFinallyRegionOpt)) + if (exceptionInfo.ContainingFinallyRegion == null || + !finallyRegion.ContainsRegionOrSelf(exceptionInfo.ContainingFinallyRegion)) { AssertValidAnalysisData(dataAtException); UpdateValuesForAnalysisData(dataAtException); @@ -515,7 +515,7 @@ private void OnStartEntryBlockAnalysis(BasicBlock entryBlock) !method.Parameters.IsEmpty) { var builder = ImmutableDictionary.CreateBuilder(); - var argumentValuesMap = DataFlowAnalysisContext.InterproceduralAnalysisDataOpt?.ArgumentValuesMap ?? + var argumentValuesMap = DataFlowAnalysisContext.InterproceduralAnalysisData?.ArgumentValuesMap ?? ImmutableDictionary>.Empty; foreach (var parameter in method.Parameters) @@ -551,7 +551,7 @@ private void OnStartExitBlockAnalysis(BasicBlock exitBlock) AnalysisEntity analysisEntity = kvp.Value; // Escape parameter values on exit, except for ref/out parameters in interprocedural analysis. - if (parameter.RefKind == RefKind.None || DataFlowAnalysisContext.InterproceduralAnalysisDataOpt == null) + if (parameter.RefKind == RefKind.None || DataFlowAnalysisContext.InterproceduralAnalysisData == null) { EscapeValueForParameterOnExit(parameter, analysisEntity); } @@ -572,16 +572,16 @@ private void OnEndExitBlockAnalysis(BasicBlock exitBlock) // For context-sensitive interprocedural analysis, we need to stop tracking data for the parameters // as they will no longer be in caller's analysis scope. - if (_lazyParameterEntities != null && DataFlowAnalysisContext.InterproceduralAnalysisDataOpt != null) + if (_lazyParameterEntities != null && DataFlowAnalysisContext.InterproceduralAnalysisData != null) { // Reset address shared entities to caller's address shared entities. - _addressSharedEntitiesProvider.SetAddressSharedEntities(DataFlowAnalysisContext.InterproceduralAnalysisDataOpt.AddressSharedEntities); + _addressSharedEntitiesProvider.SetAddressSharedEntities(DataFlowAnalysisContext.InterproceduralAnalysisData.AddressSharedEntities); StopTrackingDataForParameters(_lazyParameterEntities); } } protected bool IsParameterEntityForCurrentMethod(AnalysisEntity analysisEntity) - => analysisEntity.SymbolOpt is IParameterSymbol parameter && + => analysisEntity.Symbol is IParameterSymbol parameter && _lazyParameterEntities != null && _lazyParameterEntities.TryGetValue(parameter, out var parameterEntity) && parameterEntity == analysisEntity; @@ -599,19 +599,19 @@ protected bool IsParameterEntityForCurrentMethod(AnalysisEntity analysisEntity) CurrentBasicBlock = fromBlock; CurrentAnalysisData = input; - if (branch.BranchValueOpt != null) + if (branch.BranchValue != null) { FlowBranchConditionKind = branch.ControlFlowConditionKind; - Visit(branch.BranchValueOpt, null); + Visit(branch.BranchValue, null); if (branch.ControlFlowConditionKind != ControlFlowConditionKind.None) { // We visit the condition twice - once for the condition true branch, and once for the condition false branch. // Below check ensures we execute AfterVisitRoot only once. - if (!_visitedFlowBranchConditions.Add(branch.BranchValueOpt)) + if (!_visitedFlowBranchConditions.Add(branch.BranchValue)) { - AfterVisitRoot(branch.BranchValueOpt); - _visitedFlowBranchConditions.Remove(branch.BranchValueOpt); + AfterVisitRoot(branch.BranchValue); + _visitedFlowBranchConditions.Remove(branch.BranchValue); } if (isConditionalBranchNeverTaken()) @@ -621,7 +621,7 @@ protected bool IsParameterEntityForCurrentMethod(AnalysisEntity analysisEntity) } else { - AfterVisitRoot(branch.BranchValueOpt); + AfterVisitRoot(branch.BranchValue); } FlowBranchConditionKind = ControlFlowConditionKind.None; @@ -631,22 +631,22 @@ protected bool IsParameterEntityForCurrentMethod(AnalysisEntity analysisEntity) switch (branch.Kind) { case ControlFlowBranchSemantics.Return: - ProcessReturnValue(branch.BranchValueOpt); + ProcessReturnValue(branch.BranchValue); break; case ControlFlowBranchSemantics.Throw: case ControlFlowBranchSemantics.Rethrow: // Update the tracked merged analysis data at throw branches. - var thrownExceptionType = branch.BranchValueOpt?.Type ?? CurrentBasicBlock.GetEnclosingRegionExceptionType(); + var thrownExceptionType = branch.BranchValue?.Type ?? CurrentBasicBlock.GetEnclosingRegionExceptionType(); if (thrownExceptionType is INamedTypeSymbol exceptionType && exceptionType.DerivesFrom(ExceptionNamedType, baseTypesOnly: true)) { AnalysisDataForUnhandledThrowOperations ??= new Dictionary(); - var info = ThrownExceptionInfo.Create(CurrentBasicBlock, exceptionType, DataFlowAnalysisContext.InterproceduralAnalysisDataOpt?.CallStack); + var info = ThrownExceptionInfo.Create(CurrentBasicBlock, exceptionType, DataFlowAnalysisContext.InterproceduralAnalysisData?.CallStack); AnalysisDataForUnhandledThrowOperations[info] = GetClonedCurrentAnalysisData(); } - ProcessThrowValue(branch.BranchValueOpt); + ProcessThrowValue(branch.BranchValue); break; } @@ -654,13 +654,13 @@ protected bool IsParameterEntityForCurrentMethod(AnalysisEntity analysisEntity) bool isConditionalBranchNeverTaken() { - RoslynDebug.Assert(branch.BranchValueOpt != null); + RoslynDebug.Assert(branch.BranchValue != null); Debug.Assert(branch.ControlFlowConditionKind != ControlFlowConditionKind.None); - if (branch.BranchValueOpt.Type?.SpecialType == SpecialType.System_Boolean && - branch.BranchValueOpt.ConstantValue.HasValue) + if (branch.BranchValue.Type?.SpecialType == SpecialType.System_Boolean && + branch.BranchValue.ConstantValue.HasValue) { - var alwaysTrue = (bool)branch.BranchValueOpt.ConstantValue.Value; + var alwaysTrue = (bool)branch.BranchValue.ConstantValue.Value; if (alwaysTrue && branch.ControlFlowConditionKind == ControlFlowConditionKind.WhenFalse || !alwaysTrue && branch.ControlFlowConditionKind == ControlFlowConditionKind.WhenTrue) { @@ -669,26 +669,26 @@ bool isConditionalBranchNeverTaken() } if (PredicateAnalysis && - _predicateValueKindCacheBuilder.TryGetValue(branch.BranchValueOpt, out PredicateValueKind valueKind) && + _predicateValueKindCacheBuilder.TryGetValue(branch.BranchValue, out PredicateValueKind valueKind) && isPredicateAlwaysFalseForBranch(valueKind)) { return true; } - if (DataFlowAnalysisContext.PointsToAnalysisResultOpt != null && - isPredicateAlwaysFalseForBranch(DataFlowAnalysisContext.PointsToAnalysisResultOpt.GetPredicateKind(branch.BranchValueOpt))) + if (DataFlowAnalysisContext.PointsToAnalysisResult != null && + isPredicateAlwaysFalseForBranch(DataFlowAnalysisContext.PointsToAnalysisResult.GetPredicateKind(branch.BranchValue))) { return true; } - if (DataFlowAnalysisContext.CopyAnalysisResultOpt != null && - isPredicateAlwaysFalseForBranch(DataFlowAnalysisContext.CopyAnalysisResultOpt.GetPredicateKind(branch.BranchValueOpt))) + if (DataFlowAnalysisContext.CopyAnalysisResult != null && + isPredicateAlwaysFalseForBranch(DataFlowAnalysisContext.CopyAnalysisResult.GetPredicateKind(branch.BranchValue))) { return true; } - if (DataFlowAnalysisContext.ValueContentAnalysisResultOpt != null && - isPredicateAlwaysFalseForBranch(DataFlowAnalysisContext.ValueContentAnalysisResultOpt.GetPredicateKind(branch.BranchValueOpt))) + if (DataFlowAnalysisContext.ValueContentAnalysisResult != null && + isPredicateAlwaysFalseForBranch(DataFlowAnalysisContext.ValueContentAnalysisResult.GetPredicateKind(branch.BranchValue))) { return true; } @@ -752,7 +752,7 @@ private TAbstractAnalysisValue GetAbstractValueForReturnOperation(IOperation ret method.ReturnType.OriginalDefinition.Equals(GenericTaskNamedType) && !method.ReturnType.Equals(returnValueOperation.Type)) { - var location = AbstractLocation.CreateAllocationLocation(returnValueOperation, method.ReturnType, DataFlowAnalysisContext.InterproceduralAnalysisDataOpt?.CallStack); + var location = AbstractLocation.CreateAllocationLocation(returnValueOperation, method.ReturnType, DataFlowAnalysisContext.InterproceduralAnalysisData?.CallStack); implicitTaskPointsToValue = PointsToAbstractValue.Create(location, mayBeNull: false); return GetAbstractValueForImplicitWrappingTaskCreation(returnValueOperation, returnValue, implicitTaskPointsToValue); } @@ -768,7 +768,7 @@ protected virtual void HandlePossibleThrowingOperation(IOperation operation) // Bail out if we are not analyzing an interprocedural call and there is no // tracked analysis data. if (!HasAnyAbstractValue(CurrentAnalysisData) && - DataFlowAnalysisContext.InterproceduralAnalysisDataOpt == null) + DataFlowAnalysisContext.InterproceduralAnalysisData == null) { return; } @@ -959,9 +959,9 @@ public TAbstractAnalysisValue GetCachedAbstractValue(IOperation operation) return state; } - if (DataFlowAnalysisContext.InterproceduralAnalysisDataOpt != null) + if (DataFlowAnalysisContext.InterproceduralAnalysisData != null) { - return DataFlowAnalysisContext.InterproceduralAnalysisDataOpt.GetCachedAbstractValueFromCaller(operation); + return DataFlowAnalysisContext.InterproceduralAnalysisData.GetCachedAbstractValueFromCaller(operation); } // We were unable to find cached abstract value for requested operation. @@ -995,78 +995,78 @@ protected void CacheAbstractValue(IOperation operation, TAbstractAnalysisValue v protected virtual CopyAbstractValue GetCopyAbstractValue(IOperation operation) { - if (DataFlowAnalysisContext.CopyAnalysisResultOpt == null) + if (DataFlowAnalysisContext.CopyAnalysisResult == null) { return CopyAbstractValue.Unknown; } else { - return DataFlowAnalysisContext.CopyAnalysisResultOpt[operation]; + return DataFlowAnalysisContext.CopyAnalysisResult[operation]; } } protected virtual PointsToAbstractValue GetPointsToAbstractValue(IOperation operation) { - if (DataFlowAnalysisContext.PointsToAnalysisResultOpt == null) + if (DataFlowAnalysisContext.PointsToAnalysisResult == null) { return PointsToAbstractValue.Unknown; } else { - return DataFlowAnalysisContext.PointsToAnalysisResultOpt[operation]; + return DataFlowAnalysisContext.PointsToAnalysisResult[operation]; } } protected virtual ValueContentAbstractValue GetValueContentAbstractValue(IOperation operation) { - if (DataFlowAnalysisContext.ValueContentAnalysisResultOpt == null) + if (DataFlowAnalysisContext.ValueContentAnalysisResult == null) { return ValueContentAbstractValue.MayBeContainsNonLiteralState; } else { - return DataFlowAnalysisContext.ValueContentAnalysisResultOpt[operation]; + return DataFlowAnalysisContext.ValueContentAnalysisResult[operation]; } } protected ImmutableHashSet GetEscapedLocations(IOperation operation) { - if (operation == null || DataFlowAnalysisContext.PointsToAnalysisResultOpt == null) + if (operation == null || DataFlowAnalysisContext.PointsToAnalysisResult == null) { return ImmutableHashSet.Empty; } else { - return DataFlowAnalysisContext.PointsToAnalysisResultOpt.GetEscapedAbstractLocations(operation); + return DataFlowAnalysisContext.PointsToAnalysisResult.GetEscapedAbstractLocations(operation); } } protected ImmutableHashSet GetEscapedLocations(AnalysisEntity parameterEntity) { - Debug.Assert(parameterEntity.SymbolOpt?.Kind == SymbolKind.Parameter); - if (parameterEntity == null || DataFlowAnalysisContext.PointsToAnalysisResultOpt == null) + Debug.Assert(parameterEntity.Symbol?.Kind == SymbolKind.Parameter); + if (parameterEntity == null || DataFlowAnalysisContext.PointsToAnalysisResult == null) { return ImmutableHashSet.Empty; } else { - return DataFlowAnalysisContext.PointsToAnalysisResultOpt.GetEscapedAbstractLocations(parameterEntity); + return DataFlowAnalysisContext.PointsToAnalysisResult.GetEscapedAbstractLocations(parameterEntity); } } protected bool TryGetPointsToAbstractValueAtEntryBlockEnd(AnalysisEntity analysisEntity, out PointsToAbstractValue pointsToAbstractValue) { Debug.Assert(CurrentBasicBlock.Kind == BasicBlockKind.Entry); - RoslynDebug.Assert(DataFlowAnalysisContext.PointsToAnalysisResultOpt != null); + RoslynDebug.Assert(DataFlowAnalysisContext.PointsToAnalysisResult != null); - var outputData = DataFlowAnalysisContext.PointsToAnalysisResultOpt.EntryBlockOutput.Data; + var outputData = DataFlowAnalysisContext.PointsToAnalysisResult.EntryBlockOutput.Data; return outputData.TryGetValue(analysisEntity, out pointsToAbstractValue); } protected bool TryGetNullAbstractValueAtCurrentBlockEntry(AnalysisEntity analysisEntity, out NullAbstractValue nullAbstractValue) { - RoslynDebug.Assert(DataFlowAnalysisContext.PointsToAnalysisResultOpt != null); - var inputData = DataFlowAnalysisContext.PointsToAnalysisResultOpt[CurrentBasicBlock].Data; + RoslynDebug.Assert(DataFlowAnalysisContext.PointsToAnalysisResult != null); + var inputData = DataFlowAnalysisContext.PointsToAnalysisResult[CurrentBasicBlock].Data; if (inputData.TryGetValue(analysisEntity, out PointsToAbstractValue pointsToAbstractValue)) { nullAbstractValue = pointsToAbstractValue.NullState; @@ -1079,8 +1079,8 @@ protected bool TryGetNullAbstractValueAtCurrentBlockEntry(AnalysisEntity analysi protected bool TryGetMergedNullAbstractValueAtUnhandledThrowOperationsInGraph(AnalysisEntity analysisEntity, out NullAbstractValue nullAbstractValue) { - RoslynDebug.Assert(DataFlowAnalysisContext.PointsToAnalysisResultOpt != null); - var inputData = DataFlowAnalysisContext.PointsToAnalysisResultOpt.MergedStateForUnhandledThrowOperationsOpt?.Data; + RoslynDebug.Assert(DataFlowAnalysisContext.PointsToAnalysisResult != null); + var inputData = DataFlowAnalysisContext.PointsToAnalysisResult.MergedStateForUnhandledThrowOperations?.Data; if (inputData == null || !inputData.TryGetValue(analysisEntity, out PointsToAbstractValue pointsToAbstractValue)) { nullAbstractValue = NullAbstractValue.MaybeNull; @@ -1098,19 +1098,19 @@ private protected void SetTaskWrappedValue(PointsToAbstractValue pointsToValueFo return; } - TaskWrappedValuesMapOpt ??= new Dictionary(); - TaskWrappedValuesMapOpt[pointsToValueForTask] = wrappedValue; + TaskWrappedValuesMap ??= new Dictionary(); + TaskWrappedValuesMap[pointsToValueForTask] = wrappedValue; } private protected bool TryGetTaskWrappedValue(PointsToAbstractValue pointsToAbstractValue, out TAbstractAnalysisValue wrappedValue) { - if (TaskWrappedValuesMapOpt == null) + if (TaskWrappedValuesMap == null) { wrappedValue = ValueDomain.UnknownOrMayBeValue; return false; } - return TaskWrappedValuesMapOpt.TryGetValue(pointsToAbstractValue, out wrappedValue); + return TaskWrappedValuesMap.TryGetValue(pointsToAbstractValue, out wrappedValue); } protected virtual TAbstractAnalysisValue ComputeAnalysisValueForReferenceOperation(IOperation operation, TAbstractAnalysisValue defaultValue) @@ -1211,9 +1211,9 @@ internal bool TryInferConversion(IIsPatternOperation operation, out ConversionIn !IsInterfaceOrTypeParameter(targetType) && pointsToValue.Locations.All(location => location.IsNull || (!location.IsNoLocation && - !IsInterfaceOrTypeParameter(location.LocationTypeOpt) && - !targetType.DerivesFrom(location.LocationTypeOpt) && - !location.LocationTypeOpt.DerivesFrom(targetType)))) + !IsInterfaceOrTypeParameter(location.LocationType) && + !targetType.DerivesFrom(location.LocationType) && + !location.LocationType.DerivesFrom(targetType)))) { if (PredicateAnalysis) { @@ -1230,7 +1230,7 @@ internal bool TryInferConversion(IIsPatternOperation operation, out ConversionIn { // Infer if a TryCast will always succeed. if (isTryCast && - pointsToValue.Locations.All(location => location.IsNoLocation || !location.IsNull && location.LocationTypeOpt.DerivesFrom(targetType))) + pointsToValue.Locations.All(location => location.IsNoLocation || !location.IsNull && location.LocationType.DerivesFrom(targetType))) { // TryCast which is guaranteed to succeed, and potentially can be changed to DirectCast. if (PredicateAnalysis) @@ -1270,9 +1270,9 @@ protected virtual bool IsReachableBlockData(TAnalysisData analysisData) private bool GetBlockReachability(BasicBlock basicBlock) { return basicBlock.IsReachable && - (DataFlowAnalysisContext.CopyAnalysisResultOpt == null || DataFlowAnalysisContext.CopyAnalysisResultOpt[basicBlock].IsReachable) && - (DataFlowAnalysisContext.PointsToAnalysisResultOpt == null || DataFlowAnalysisContext.PointsToAnalysisResultOpt[basicBlock].IsReachable) && - (DataFlowAnalysisContext.ValueContentAnalysisResultOpt == null || DataFlowAnalysisContext.ValueContentAnalysisResultOpt[basicBlock].IsReachable); + (DataFlowAnalysisContext.CopyAnalysisResult == null || DataFlowAnalysisContext.CopyAnalysisResult[basicBlock].IsReachable) && + (DataFlowAnalysisContext.PointsToAnalysisResult == null || DataFlowAnalysisContext.PointsToAnalysisResult[basicBlock].IsReachable) && + (DataFlowAnalysisContext.ValueContentAnalysisResult == null || DataFlowAnalysisContext.ValueContentAnalysisResult[basicBlock].IsReachable); } protected bool IsCurrentBlockReachable() @@ -1337,7 +1337,7 @@ private void PerformPredicateAnalysis(IOperation operation) var result = AnalysisEntityFactory.TryCreate(operation, out AnalysisEntity? flowCaptureReferenceEntity); Debug.Assert(result); RoslynDebug.Assert(flowCaptureReferenceEntity != null); - RoslynDebug.Assert(flowCaptureReferenceEntity.CaptureIdOpt != null); + RoslynDebug.Assert(flowCaptureReferenceEntity.CaptureId != null); Debug.Assert(HasPredicatedDataForEntity(flowCaptureReferenceEntity)); TransferPredicatedData(fromEntity: flowCaptureReferenceEntity, toEntity: predicatedFlowCaptureEntity); } @@ -1428,7 +1428,7 @@ bool IsRootOfCondition() if (AnalysisEntityFactory.TryCreate(current, out var targetEntity) && targetEntity.IsCandidatePredicateEntity()) { - Debug.Assert(targetEntity.CaptureIdOpt != null); + Debug.Assert(targetEntity.CaptureId != null); return targetEntity; } @@ -1533,7 +1533,7 @@ private void PerformPredicateAnalysisCore(IOperation operation, TAnalysisData ta var result = AnalysisEntityFactory.TryCreate(operation, out AnalysisEntity? flowCaptureReferenceEntity); Debug.Assert(result); RoslynDebug.Assert(flowCaptureReferenceEntity != null); - RoslynDebug.Assert(flowCaptureReferenceEntity.CaptureIdOpt != null); + RoslynDebug.Assert(flowCaptureReferenceEntity.CaptureId != null); if (!HasPredicatedDataForEntity(targetAnalysisData, flowCaptureReferenceEntity)) { return; @@ -1937,7 +1937,7 @@ protected virtual void AssertValidAnalysisData(TAnalysisData analysisData) /// protected virtual TAnalysisData GetInitialInterproceduralAnalysisData( IMethodSymbol invokedMethod, - (AnalysisEntity? InstanceOpt, PointsToAbstractValue PointsToValue)? invocationInstance, + (AnalysisEntity? Instance, PointsToAbstractValue PointsToValue)? invocationInstance, (AnalysisEntity Instance, PointsToAbstractValue PointsToValue)? thisOrMeInstanceForCaller, ImmutableDictionary> argumentValuesMap, IDictionary? pointsToValues, @@ -1967,7 +1967,7 @@ private void ApplyInterproceduralAnalysisDataForUnhandledThrowOperations(Diction foreach (var (exceptionInfo, analysisDataAtException) in interproceduralUnhandledThrowOperationsData) { // Adjust the thrown exception info from the interprocedural context to current context. - var adjustedExceptionInfo = exceptionInfo.With(CurrentBasicBlock, DataFlowAnalysisContext.InterproceduralAnalysisDataOpt?.CallStack); + var adjustedExceptionInfo = exceptionInfo.With(CurrentBasicBlock, DataFlowAnalysisContext.InterproceduralAnalysisData?.CallStack); // Used cloned analysis data var clonedAnalysisDataAtException = GetClonedAnalysisData(analysisDataAtException); @@ -2024,7 +2024,7 @@ protected bool TryGetInterproceduralAnalysisResult(IOperation operation, [NotNul // Bail out if configured not to execute interprocedural analysis. var skipInterproceduralAnalysis = !isLambdaOrLocalFunction && InterproceduralAnalysisKind == InterproceduralAnalysisKind.None || - DataFlowAnalysisContext.InterproceduralAnalysisPredicateOpt?.SkipInterproceduralAnalysis(invokedMethod, isLambdaOrLocalFunction) == true || + DataFlowAnalysisContext.InterproceduralAnalysisPredicate?.SkipInterproceduralAnalysis(invokedMethod, isLambdaOrLocalFunction) == true || invokedMethod.IsConfiguredToSkipAnalysis(OwningSymbol, DataFlowAnalysisContext.AnalyzerOptions, s_dummyDataflowAnalysisDescriptor, WellKnownTypeProvider.Compilation, CancellationToken.None); // Also bail out for non-source methods and methods where we are not sure about the actual runtime target method. @@ -2039,7 +2039,7 @@ protected bool TryGetInterproceduralAnalysisResult(IOperation operation, [NotNul } // Bail out if we are already analyzing the current context. - var currentMethodsBeingAnalyzed = DataFlowAnalysisContext.InterproceduralAnalysisDataOpt?.MethodsBeingAnalyzed ?? ImmutableHashSet.Empty; + var currentMethodsBeingAnalyzed = DataFlowAnalysisContext.InterproceduralAnalysisData?.MethodsBeingAnalyzed ?? ImmutableHashSet.Empty; var newMethodsBeingAnalyzed = currentMethodsBeingAnalyzed.Add(DataFlowAnalysisContext); if (currentMethodsBeingAnalyzed.Count == newMethodsBeingAnalyzed.Count) { @@ -2057,9 +2057,9 @@ protected bool TryGetInterproceduralAnalysisResult(IOperation operation, [NotNul } // Compute the dependent interprocedural PointsTo and Copy analysis results, if any. - var pointsToAnalysisResult = (PointsToAnalysisResult?)DataFlowAnalysisContext.PointsToAnalysisResultOpt?.TryGetInterproceduralResult(originalOperation); - var copyAnalysisResult = DataFlowAnalysisContext.CopyAnalysisResultOpt?.TryGetInterproceduralResult(originalOperation); - var valueContentAnalysisResult = DataFlowAnalysisContext.ValueContentAnalysisResultOpt?.TryGetInterproceduralResult(originalOperation); + var pointsToAnalysisResult = (PointsToAnalysisResult?)DataFlowAnalysisContext.PointsToAnalysisResult?.TryGetInterproceduralResult(originalOperation); + var copyAnalysisResult = DataFlowAnalysisContext.CopyAnalysisResult?.TryGetInterproceduralResult(originalOperation); + var valueContentAnalysisResult = DataFlowAnalysisContext.ValueContentAnalysisResult?.TryGetInterproceduralResult(originalOperation); // Compute the CFG for the invoked method. var cfg = pointsToAnalysisResult?.ControlFlowGraph ?? @@ -2093,7 +2093,7 @@ protected bool TryGetInterproceduralAnalysisResult(IOperation operation, [NotNul invokedMethod, cfg, originalOperation, pointsToAnalysisResult, copyAnalysisResult, valueContentAnalysisResult, interproceduralAnalysisData); // Check if the client configured skipping analysis for the given interprocedural analysis context. - if (DataFlowAnalysisContext.InterproceduralAnalysisPredicateOpt?.SkipInterproceduralAnalysis(interproceduralDataFlowAnalysisContext) == true) + if (DataFlowAnalysisContext.InterproceduralAnalysisPredicate?.SkipInterproceduralAnalysis(interproceduralDataFlowAnalysisContext) == true) { return ResetAnalysisDataAndReturnDefaultValue(); } @@ -2115,12 +2115,12 @@ protected bool TryGetInterproceduralAnalysisResult(IOperation operation, [NotNul if (isContextSensitive) { // Apply any interprocedural analysis data for unhandled exceptions paths. - if (analysisResult.AnalysisDataForUnhandledThrowOperationsOpt is Dictionary interproceduralUnhandledThrowOperationsDataOpt) + if (analysisResult.AnalysisDataForUnhandledThrowOperations is Dictionary interproceduralUnhandledThrowOperationsDataOpt) { ApplyInterproceduralAnalysisDataForUnhandledThrowOperations(interproceduralUnhandledThrowOperationsDataOpt); } - if (analysisResult.TaskWrappedValuesMapOpt is Dictionary taskWrappedValuesMap) + if (analysisResult.TaskWrappedValuesMap is Dictionary taskWrappedValuesMap) { foreach (var (key, value) in taskWrappedValuesMap) { @@ -2152,20 +2152,20 @@ protected bool TryGetInterproceduralAnalysisResult(IOperation operation, [NotNul interproceduralAnalysisData?.InitialAnalysisData?.Dispose(); } - RoslynDebug.Assert(invokedMethod.ReturnsVoid == !analysisResult.ReturnValueAndPredicateKindOpt.HasValue); + RoslynDebug.Assert(invokedMethod.ReturnsVoid == !analysisResult.ReturnValueAndPredicateKind.HasValue); if (invokedMethod.ReturnsVoid) { return defaultValue; } - RoslynDebug.Assert(analysisResult.ReturnValueAndPredicateKindOpt != null); + RoslynDebug.Assert(analysisResult.ReturnValueAndPredicateKind != null); if (PredicateAnalysis) { - SetPredicateValueKind(originalOperation, CurrentAnalysisData, analysisResult.ReturnValueAndPredicateKindOpt.Value.PredicateValueKind); + SetPredicateValueKind(originalOperation, CurrentAnalysisData, analysisResult.ReturnValueAndPredicateKind.Value.PredicateValueKind); } - return analysisResult.ReturnValueAndPredicateKindOpt.Value.Value; + return analysisResult.ReturnValueAndPredicateKind.Value.Value; // Local functions TAbstractAnalysisValue ResetAnalysisDataAndReturnDefaultValue() @@ -2641,7 +2641,7 @@ void PerformFlowCaptureReferencePredicateAnalysis() var result = AnalysisEntityFactory.TryCreate(operation, out var flowCaptureReferenceEntity); Debug.Assert(result); RoslynDebug.Assert(flowCaptureReferenceEntity != null); - RoslynDebug.Assert(flowCaptureReferenceEntity.CaptureIdOpt != null); + RoslynDebug.Assert(flowCaptureReferenceEntity.CaptureId != null); if (!HasPredicatedDataForEntity(flowCaptureReferenceEntity)) { return; @@ -2674,7 +2674,7 @@ void PerformFlowCapturePredicateAnalysis() if (operation.Value.TryGetBoolConstantValue(out bool constantValue) && AnalysisEntityFactory.TryCreate(operation, out var flowCaptureEntity)) { - Debug.Assert(flowCaptureEntity.CaptureIdOpt != null); + Debug.Assert(flowCaptureEntity.CaptureId != null); TAnalysisData predicatedData = GetEmptyAnalysisData(); TAnalysisData? truePredicatedData, falsePredicatedData; if (constantValue) @@ -2942,7 +2942,7 @@ out HashSet<(IMethodSymbol method, IOperation? instance)>? resolvedMethodTargets knownTargetInvocations = true; foreach (var location in invocationTarget.Locations) { - if (!HandleCreationOpt(location.CreationOpt)) + if (!HandleCreationOpt(location.Creation)) { knownTargetInvocations = false; break; @@ -3122,9 +3122,9 @@ TAnalysisData AnalyzePossibleTargetInvocation(Func compu private ControlFlowGraph? GetInterproceduralControlFlowGraph(IMethodSymbol method) { - if (DataFlowAnalysisContext.InterproceduralAnalysisDataOpt != null) + if (DataFlowAnalysisContext.InterproceduralAnalysisData != null) { - return DataFlowAnalysisContext.InterproceduralAnalysisDataOpt.GetInterproceduralControlFlowGraph(method); + return DataFlowAnalysisContext.InterproceduralAnalysisData.GetInterproceduralControlFlowGraph(method); } RoslynDebug.Assert(_interproceduralMethodToCfgMap != null); @@ -3143,10 +3143,10 @@ TAnalysisData AnalyzePossibleTargetInvocation(Func compu { if (OwningSymbol.Equals(forOwningSymbol)) { - return DataFlowAnalysisContext.InterproceduralAnalysisDataOpt?.CallStack; + return DataFlowAnalysisContext.InterproceduralAnalysisData?.CallStack; } - return DataFlowAnalysisContext.InterproceduralAnalysisDataOpt?.GetInterproceduralCallStackForOwningSymbol(forOwningSymbol); + return DataFlowAnalysisContext.InterproceduralAnalysisData?.GetInterproceduralCallStackForOwningSymbol(forOwningSymbol); } public virtual TAbstractAnalysisValue VisitInvocation_LocalFunction( @@ -3325,7 +3325,7 @@ private void MergeAnalysisDataFromUnhandledThrowOperations(ITypeSymbol? caughtEx bool ShouldHandlePendingThrow(ThrownExceptionInfo pendingThrow) { - if (pendingThrow.HandlingCatchRegionOpt == CurrentBasicBlock.EnclosingRegion) + if (pendingThrow.HandlingCatchRegion == CurrentBasicBlock.EnclosingRegion) { // Catch region explicitly handling the thrown exception. return true; diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/IDataFlowAnalysisResult.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/IDataFlowAnalysisResult.cs index d92d0e0388..7735c471fa 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/IDataFlowAnalysisResult.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/IDataFlowAnalysisResult.cs @@ -9,8 +9,8 @@ namespace Microsoft.CodeAnalysis.FlowAnalysis.DataFlow public interface IDataFlowAnalysisResult { ControlFlowGraph ControlFlowGraph { get; } - (TAbstractAnalysisValue Value, PredicateValueKind PredicateValueKind)? ReturnValueAndPredicateKindOpt { get; } - object? AnalysisDataForUnhandledThrowOperationsOpt { get; } - object? TaskWrappedValuesMapOpt { get; } + (TAbstractAnalysisValue Value, PredicateValueKind PredicateValueKind)? ReturnValueAndPredicateKind { get; } + object? AnalysisDataForUnhandledThrowOperations { get; } + object? TaskWrappedValuesMap { get; } } } diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/InterproceduralAnalysisData.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/InterproceduralAnalysisData.cs index 855cfeace1..0f9147bf83 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/InterproceduralAnalysisData.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/InterproceduralAnalysisData.cs @@ -38,8 +38,8 @@ public sealed class InterproceduralAnalysisData?> getInterproceduralCallStackForOwningSymbol) { InitialAnalysisData = initialAnalysisData; - InvocationInstanceOpt = invocationInstance; - ThisOrMeInstanceForCallerOpt = thisOrMeInstanceForCaller; + InvocationInstance = invocationInstance; + ThisOrMeInstanceForCaller = thisOrMeInstanceForCaller; ArgumentValuesMap = argumentValuesMap; CapturedVariablesMap = capturedVariablesMap; AddressSharedEntities = addressSharedEntities; @@ -52,8 +52,8 @@ public sealed class InterproceduralAnalysisData> ArgumentValuesMap { get; } public ImmutableDictionary CapturedVariablesMap { get; } public ImmutableDictionary AddressSharedEntities { get; } @@ -67,8 +67,8 @@ public sealed class InterproceduralAnalysisData addPart) { addPart(InitialAnalysisData.GetHashCodeOrDefault()); - AddHashCodeParts(InvocationInstanceOpt, addPart); - AddHashCodeParts(ThisOrMeInstanceForCallerOpt, addPart); + AddHashCodeParts(InvocationInstance, addPart); + AddHashCodeParts(ThisOrMeInstanceForCaller, addPart); addPart(HashUtilities.Combine(ArgumentValuesMap)); addPart(HashUtilities.Combine(CapturedVariablesMap)); addPart(HashUtilities.Combine(AddressSharedEntities)); @@ -77,12 +77,12 @@ protected override void ComputeHashCodeParts(Action addPart) } private static void AddHashCodeParts( - (AnalysisEntity? InstanceOpt, PointsToAbstractValue PointsToValue)? instanceAndPointsToValue, + (AnalysisEntity? Instance, PointsToAbstractValue PointsToValue)? instanceAndPointsToValue, Action addPart) { if (instanceAndPointsToValue.HasValue) { - addPart(instanceAndPointsToValue.Value.InstanceOpt.GetHashCodeOrDefault()); + addPart(instanceAndPointsToValue.Value.Instance.GetHashCodeOrDefault()); addPart(instanceAndPointsToValue.Value.PointsToValue.GetHashCode()); } else diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/PredicatedAnalysisData.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/PredicatedAnalysisData.cs index 048a63c3fe..3a80ee8b46 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/PredicatedAnalysisData.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/PredicatedAnalysisData.cs @@ -90,7 +90,7 @@ private void EnsurePredicatedData() protected void StartTrackingPredicatedData(AnalysisEntity predicatedEntity, DictionaryAnalysisData? truePredicatedData, DictionaryAnalysisData? falsePredicatedData) { Debug.Assert(predicatedEntity.IsCandidatePredicateEntity()); - Debug.Assert(predicatedEntity.CaptureIdOpt != null, "Currently we only support predicated data tracking for flow captures"); + Debug.Assert(predicatedEntity.CaptureId != null, "Currently we only support predicated data tracking for flow captures"); AssertValidAnalysisData(); @@ -104,7 +104,7 @@ public void StopTrackingPredicatedData(AnalysisEntity predicatedEntity) { RoslynDebug.Assert(_lazyPredicateDataMap != null); Debug.Assert(HasPredicatedDataForEntity(predicatedEntity)); - RoslynDebug.Assert(predicatedEntity.CaptureIdOpt != null, "Currently we only support predicated data tracking for flow captures"); + RoslynDebug.Assert(predicatedEntity.CaptureId != null, "Currently we only support predicated data tracking for flow captures"); AssertValidAnalysisData(); if (_lazyPredicateDataMap.TryGetValue(predicatedEntity, out var perEntityPredicatedAnalysisData)) @@ -128,8 +128,8 @@ public void TransferPredicatedData(AnalysisEntity fromEntity, AnalysisEntity toE { Debug.Assert(HasPredicatedDataForEntity(fromEntity)); RoslynDebug.Assert(_lazyPredicateDataMap != null); - RoslynDebug.Assert(fromEntity.CaptureIdOpt != null, "Currently we only support predicated data tracking for flow captures"); - RoslynDebug.Assert(toEntity.CaptureIdOpt != null, "Currently we only support predicated data tracking for flow captures"); + RoslynDebug.Assert(fromEntity.CaptureId != null, "Currently we only support predicated data tracking for flow captures"); + RoslynDebug.Assert(toEntity.CaptureId != null, "Currently we only support predicated data tracking for flow captures"); AssertValidAnalysisData(); if (_lazyPredicateDataMap!.TryGetValue(fromEntity, out var fromEntityPredicatedData)) diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/ThrownExceptionInfo.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/ThrownExceptionInfo.cs index 262cc91e26..4454db30cb 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/ThrownExceptionInfo.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/ThrownExceptionInfo.cs @@ -18,8 +18,8 @@ public sealed class ThrownExceptionInfo : IEquatable bool isDefaultExceptionForExceptionsPathAnalysis) { BasicBlockOrdinal = block.Ordinal; - HandlingCatchRegionOpt = GetHandlerRegion(block, exceptionType); - ContainingFinallyRegionOpt = block.GetContainingRegionOfKind(ControlFlowRegionKind.Finally); + HandlingCatchRegion = GetHandlerRegion(block, exceptionType); + ContainingFinallyRegion = block.GetContainingRegionOfKind(ControlFlowRegionKind.Finally); ExceptionType = exceptionType ?? throw new ArgumentNullException(nameof(exceptionType)); InterproceduralCallStack = interproceduralCallStack ?? ImmutableStack.Empty; IsDefaultExceptionForExceptionsPathAnalysis = isDefaultExceptionForExceptionsPathAnalysis; @@ -77,12 +77,12 @@ internal ThrownExceptionInfo With(BasicBlock block, ImmutableStack? /// /// Optional catch handler that handles this exception. /// - internal ControlFlowRegion? HandlingCatchRegionOpt { get; } + internal ControlFlowRegion? HandlingCatchRegion { get; } /// /// If the exception happens within a finally region, this points to that finally. /// - internal ControlFlowRegion? ContainingFinallyRegionOpt { get; } + internal ControlFlowRegion? ContainingFinallyRegion { get; } internal INamedTypeSymbol ExceptionType { get; } internal ImmutableStack InterproceduralCallStack { get; } @@ -92,8 +92,8 @@ public bool Equals(ThrownExceptionInfo? other) { return other != null && BasicBlockOrdinal == other.BasicBlockOrdinal && - HandlingCatchRegionOpt == other.HandlingCatchRegionOpt && - ContainingFinallyRegionOpt == other.ContainingFinallyRegionOpt && + HandlingCatchRegion == other.HandlingCatchRegion && + ContainingFinallyRegion == other.ContainingFinallyRegion && Equals(ExceptionType, other.ExceptionType) && InterproceduralCallStack.SequenceEqual(other.InterproceduralCallStack) && IsDefaultExceptionForExceptionsPathAnalysis == other.IsDefaultExceptionForExceptionsPathAnalysis; @@ -105,8 +105,8 @@ public override bool Equals(object obj) public override int GetHashCode() => HashUtilities.Combine(InterproceduralCallStack, HashUtilities.Combine(BasicBlockOrdinal.GetHashCodeOrDefault(), - HashUtilities.Combine(HandlingCatchRegionOpt.GetHashCodeOrDefault(), - HashUtilities.Combine(ContainingFinallyRegionOpt.GetHashCodeOrDefault(), + HashUtilities.Combine(HandlingCatchRegion.GetHashCodeOrDefault(), + HashUtilities.Combine(ContainingFinallyRegion.GetHashCodeOrDefault(), HashUtilities.Combine(ExceptionType.GetHashCode(), IsDefaultExceptionForExceptionsPathAnalysis.GetHashCode()))))); } }