Skip to content

Commit

Permalink
Enable CA1821, CA1825-CA1834
Browse files Browse the repository at this point in the history
Contributes to #24055
  • Loading branch information
pranavkm committed May 26, 2021
1 parent e7b5aa6 commit 5d0ede4
Show file tree
Hide file tree
Showing 60 changed files with 196 additions and 157 deletions.
41 changes: 41 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,40 @@ dotnet_diagnostic.CA1802.severity = warning
# CA1805: Do not initialize unnecessarily
dotnet_diagnostic.CA1805.severity = warning

# CA1823: Remove empty Finalizers
dotnet_diagnostic.CA1821.severity = warning

# CA1823: Avoid unused private fields
dotnet_diagnostic.CA1823.severity = warning

# CA1823: Avoid zero-length array allocations
dotnet_diagnostic.CA1825.severity = warning

# CA1826: Do not use Enumerable methods on indexable collections. Instead use the collection directly
dotnet_diagnostic.CA1826.severity = warning

# CA1827: Do not use Count() or LongCount() when Any() can be used
dotnet_diagnostic.CA1827.severity = warning

# CA1828: Do not use CountAsync() or LongCountAsync() when AnyAsync() can be used
dotnet_diagnostic.CA1828.severity = warning

# CA1829: Use Length/Count property instead of Count() when available
dotnet_diagnostic.CA1829.severity = warning

# CA1830: Prefer strongly-typed Append and Insert method overloads on StringBuilder
dotnet_diagnostic.CA1830.severity = warning

# CA1831: Use AsSpan or AsMemory instead of Range-based indexers when appropriate
# CA1832: Use AsSpan or AsMemory instead of Range-based indexers when appropriate
# CA1833: Use AsSpan or AsMemory instead of Range-based indexers when appropriate
dotnet_diagnostic.CA1831.severity = warning
dotnet_diagnostic.CA1832.severity = warning
dotnet_diagnostic.CA1833.severity = warning

# CA1834: Consider using 'StringBuilder.Append(char)' when applicable
dotnet_diagnostic.CA1834.severity = warning

# CA2012: Use ValueTask correctly
dotnet_diagnostic.CA2012.severity = warning

Expand All @@ -110,5 +141,15 @@ dotnet_diagnostic.CA1507.severity = suggestion
dotnet_diagnostic.CA1802.severity = suggestion
# CA1805: Do not initialize unnecessarily
dotnet_diagnostic.CA1805.severity = suggestion
# CA1823: Avoid zero-length array allocations
dotnet_diagnostic.CA1825.severity = suggestion
# CA1826: Do not use Enumerable methods on indexable collections. Instead use the collection directly
dotnet_diagnostic.CA1826.severity = suggestion
# CA1827: Do not use Count() or LongCount() when Any() can be used
dotnet_diagnostic.CA1827.severity = suggestion
# CA1829: Use Length/Count property instead of Count() when available
dotnet_diagnostic.CA1829.severity = suggestion
# CA1834: Consider using 'StringBuilder.Append(char)' when applicable
dotnet_diagnostic.CA1834.severity = suggestion
# CA2012: Use ValueTask correctly
dotnet_diagnostic.CA2012.severity = suggestion
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ private void VerifyDiagnostics(string[] sources, string language, DiagnosticAnal
/// <param name="expectedResults">Diagnostic Results that should have appeared in the code</param>
private static void VerifyDiagnosticResults(IEnumerable<Diagnostic> actualResults, DiagnosticAnalyzer analyzer, params DiagnosticResult[] expectedResults)
{
int expectedCount = expectedResults.Count();
int expectedCount = expectedResults.Length;
int actualCount = actualResults.Count();

if (expectedCount != actualCount)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,9 +119,9 @@ private void CreateDefaultLogMessage(StringBuilder logBuilder, LogLevel logLevel
logBuilder.Append(GetLogLevelString(logLevel));
logBuilder.Append(_loglevelPadding);
logBuilder.Append(logName);
logBuilder.Append("[");
logBuilder.Append('[');
logBuilder.Append(eventId);
logBuilder.Append("]");
logBuilder.Append(']');

if (!string.IsNullOrEmpty(message))
{
Expand Down
4 changes: 2 additions & 2 deletions src/Components/WebView/WebView/src/QueryString.cs
Original file line number Diff line number Diff line change
Expand Up @@ -292,9 +292,9 @@ public override int GetHashCode()

private static void AppendKeyValuePair(StringBuilder builder, string key, string? value, bool first)
{
builder.Append(first ? "?" : "&");
builder.Append(first ? '?' : '&');
builder.Append(UrlEncoder.Default.Encode(key));
builder.Append("=");
builder.Append('=');
if (!string.IsNullOrEmpty(value))
{
builder.Append(UrlEncoder.Default.Encode(value));
Expand Down
2 changes: 1 addition & 1 deletion src/FileProviders/Embedded/src/Manifest/ManifestParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ private static string EnsureName(XElement element)

private static string EnsureText(XElement element)
{
if (element.Elements().Count() == 0 &&
if (!element.Elements().Any() &&
!element.IsEmpty &&
element.Nodes().Count() == 1 &&
element.FirstNode?.NodeType == XmlNodeType.Text)
Expand Down
2 changes: 1 addition & 1 deletion src/Http/Headers/src/CookieHeaderValue.cs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ public override string ToString()
var header = new StringBuilder();

header.Append(_name.AsSpan());
header.Append("=");
header.Append('=');
header.Append(_value.AsSpan());

return header.ToString();
Expand Down
4 changes: 2 additions & 2 deletions src/Http/Headers/src/SetCookieHeaderValue.cs
Original file line number Diff line number Diff line change
Expand Up @@ -329,7 +329,7 @@ private static void Append(ref Span<char> span, ReadOnlySpan<char> other)
public void AppendToStringBuilder(StringBuilder builder)
{
builder.Append(_name.AsSpan());
builder.Append("=");
builder.Append('=');
builder.Append(_value.AsSpan());

if (Expires.HasValue)
Expand Down Expand Up @@ -388,7 +388,7 @@ private static void AppendSegment(StringBuilder builder, StringSegment name, Str
builder.Append(name.AsSpan());
if (value != null)
{
builder.Append("=");
builder.Append('=');
builder.Append(value.AsSpan());
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/Http/Http.Abstractions/src/QueryString.cs
Original file line number Diff line number Diff line change
Expand Up @@ -286,9 +286,9 @@ public override int GetHashCode()

private static void AppendKeyValuePair(StringBuilder builder, string key, string? value, bool first)
{
builder.Append(first ? "?" : "&");
builder.Append(first ? '?' : '&');
builder.Append(UrlEncoder.Default.Encode(key));
builder.Append("=");
builder.Append('=');
if (!string.IsNullOrEmpty(value))
{
builder.Append(UrlEncoder.Default.Encode(value));
Expand Down
12 changes: 6 additions & 6 deletions src/Http/Routing/src/DefaultLinkGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -480,14 +480,14 @@ private static string FormatRouteValues(IReadOnlyDictionary<string, object> valu

foreach (var kvp in values.OrderBy(kvp => kvp.Key))
{
builder.Append("\"");
builder.Append('"');
builder.Append(kvp.Key);
builder.Append("\"");
builder.Append(":");
builder.Append(" ");
builder.Append("\"");
builder.Append('"');
builder.Append(':');
builder.Append(' ');
builder.Append('"');
builder.Append(kvp.Value);
builder.Append("\"");
builder.Append('"');
builder.Append(", ");
}

Expand Down
14 changes: 7 additions & 7 deletions src/Http/Routing/src/Patterns/RoutePatternParameterPart.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,37 +80,37 @@ internal RoutePatternParameterPart(
internal override string DebuggerToString()
{
var builder = new StringBuilder();
builder.Append("{");
builder.Append('{');

if (IsCatchAll)
{
builder.Append("*");
builder.Append('*');
if (!EncodeSlashes)
{
builder.Append("*");
builder.Append('*');
}
}

builder.Append(Name);

foreach (var constraint in ParameterPolicies)
{
builder.Append(":");
builder.Append(':');
builder.Append(constraint.ParameterPolicy);
}

if (Default != null)
{
builder.Append("=");
builder.Append('=');
builder.Append(Default);
}

if (IsOptional)
{
builder.Append("?");
builder.Append('?');
}

builder.Append("}");
builder.Append('}');
return builder.ToString();
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/Http/Routing/src/Tree/LinkGenerationDecisionTree.cs
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ private void FlattenTree(Stack<string> branchStack, StringBuilder sb, DecisionTr
{
matchesSb.Insert(0, branch);
}
sb.Append(matchesSb.ToString());
sb.Append(matchesSb);
sb.Append(" (Matches: ");
sb.AppendJoin(", ", node.Matches.Select(m => m.Entry.RouteTemplate.TemplateText));
sb.AppendLine(")");
Expand Down
6 changes: 3 additions & 3 deletions src/Http/Routing/src/UriBuildingContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ public bool Accept(string? value, bool encodeSlashes)
{
if (_path.Length != 0)
{
_path.Append("/");
_path.Append('/');
}
}

Expand All @@ -124,7 +124,7 @@ public bool Accept(string? value, bool encodeSlashes)
// This prevents the leading slash from PathString segments from being encoded.
if (_path.Length == 0 && value.Length > 0 && value[0] == '/')
{
_path.Append("/");
_path.Append('/');
EncodeValue(value, 1, value.Length - 1, encodeSlashes);
}
else
Expand Down Expand Up @@ -305,7 +305,7 @@ internal void EncodeValue(string value, int start, int characterCount, bool enco
while ((end = value.IndexOf('/', start, characterCount)) >= 0)
{
_urlEncoder.Encode(PathWriter, value, start, end - start);
_path.Append("/");
_path.Append('/');

start = end + 1;
characterCount = length - start;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ private static string GenerateRequestUrl(RouteTemplate template)
// We don't yet handle complex segments
var part = template.Segments[i].Parts[0];

url.Append("/");
url.Append('/');
url.Append(part.IsLiteral ? part.Text : GenerateParameterValue(part));
}

Expand Down
2 changes: 1 addition & 1 deletion src/Identity/Extensions.Core/src/Base32.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public static byte[] FromBase32(string input)
input = input.TrimEnd('=').ToUpperInvariant();
if (input.Length == 0)
{
return new byte[0];
return Array.Empty<byte>();
}

var output = new byte[input.Length * 5 / 8];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1826,7 +1826,7 @@ public async Task CanGetValidTwoFactor()
await manager.ConfirmEmailAsync(user, token);
factors = await manager.GetValidTwoFactorProvidersAsync(user);
Assert.NotNull(factors);
Assert.Equal(2, factors.Count());
Assert.Equal(2, factors.Count);
IdentityResultAssert.IsSuccess(await manager.SetEmailAsync(user, null));
factors = await manager.GetValidTwoFactorProvidersAsync(user);
Assert.NotNull(factors);
Expand All @@ -1835,7 +1835,7 @@ public async Task CanGetValidTwoFactor()
IdentityResultAssert.IsSuccess(await manager.ResetAuthenticatorKeyAsync(user));
factors = await manager.GetValidTwoFactorProvidersAsync(user);
Assert.NotNull(factors);
Assert.Equal(2, factors.Count());
Assert.Equal(2, factors.Count);
Assert.Equal("Authenticator", factors[1]);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -182,12 +182,12 @@ private string FormatKey(string unformattedKey)
int currentPosition = 0;
while (currentPosition + 4 < unformattedKey.Length)
{
result.Append(unformattedKey.Substring(currentPosition, 4)).Append(" ");
result.Append(unformattedKey.AsSpan(currentPosition, 4)).Append(' ');
currentPosition += 4;
}
if (currentPosition < unformattedKey.Length)
{
result.Append(unformattedKey.Substring(currentPosition));
result.Append(unformattedKey.AsSpan(currentPosition));
}

return result.ToString().ToLowerInvariant();
Expand Down
4 changes: 2 additions & 2 deletions src/Identity/test/InMemory.Test/InMemoryStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ namespace Microsoft.AspNetCore.Identity.InMemory
public class InMemoryStore<TUser, TRole> :
InMemoryUserStore<TUser>,
IUserRoleStore<TUser>,
IQueryableRoleStore<TRole>,
IQueryableRoleStore<TRole>,
IRoleClaimStore<TRole>
where TRole : PocoRole
where TUser : PocoUser
Expand Down Expand Up @@ -72,7 +72,7 @@ public class InMemoryStore<TUser, TRole> :
{
return Task.FromResult<IList<TUser>>(new List<TUser>());
}
return Task.FromResult<IList<TUser>>(Users.Where(u => (u.Roles.Where(x => x.RoleId == role.Id).Count() > 0)).Select(x => x).ToList());
return Task.FromResult<IList<TUser>>(Users.Where(u => (u.Roles.Where(x => x.RoleId == role.Id).Any())).Select(x => x).ToList());
}

private readonly Dictionary<string, TRole> _roles = new Dictionary<string, TRole>();
Expand Down
8 changes: 4 additions & 4 deletions src/Middleware/CORS/src/Infrastructure/CorsPolicy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -161,16 +161,16 @@ public override string ToString()
builder.Append(SupportsCredentials);
builder.Append(", Origins: {");
builder.AppendJoin(",", Origins);
builder.Append("}");
builder.Append('}');
builder.Append(", Methods: {");
builder.AppendJoin(",", Methods);
builder.Append("}");
builder.Append('}');
builder.Append(", Headers: {");
builder.AppendJoin(",", Headers);
builder.Append("}");
builder.Append('}');
builder.Append(", ExposedHeaders: {");
builder.AppendJoin(",", ExposedHeaders);
builder.Append("}");
builder.Append('}');
return builder.ToString();
}

Expand Down
6 changes: 3 additions & 3 deletions src/Middleware/CORS/src/Infrastructure/CorsResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -93,13 +93,13 @@ public override string ToString()
builder.Append(AllowedOrigin);
builder.Append(", AllowExposedHeaders: {");
builder.AppendJoin(",", AllowedExposedHeaders);
builder.Append("}");
builder.Append('}');
builder.Append(", AllowHeaders: {");
builder.AppendJoin(",", AllowedHeaders);
builder.Append("}");
builder.Append('}');
builder.Append(", AllowMethods: {");
builder.AppendJoin(",", AllowedMethods);
builder.Append("}");
builder.Append('}');
return builder.ToString();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ public virtual async Task Invoke(HttpContext httpContext)
var contextType = _localDiagnostic.Value!.ContextType;
var details = await httpContext.GetContextDetailsAsync(contextType!, _logger);

if (details != null && (details.PendingModelChanges || details.PendingMigrations.Count() > 0))
if (details != null && (details.PendingModelChanges || details.PendingMigrations.Any()))
{
var page = new DatabaseErrorPage
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public async Task CheckAsync_CustomTest_Healthy()
// Arrange
var services = CreateServices(async (c, ct) =>
{
return 0 < await c.Blogs.CountAsync();
return await c.Blogs.AnyAsync();
});

using (var scope = services.GetRequiredService<IServiceScopeFactory>().CreateScope())
Expand All @@ -66,7 +66,7 @@ public async Task CheckAsync_CustomTestWithDegradedFailureStatusSpecified_Degrad
// Arrange
var services = CreateServices(async (c, ct) =>
{
return 0 < await c.Blogs.CountAsync();
return await c.Blogs.AnyAsync();
}, failureStatus: HealthStatus.Degraded);

using (var scope = services.GetRequiredService<IServiceScopeFactory>().CreateScope())
Expand All @@ -88,7 +88,7 @@ public async Task CheckAsync_CustomTestWithUnhealthyFailureStatusSpecified_Unhea
// Arrange
var services = CreateServices(async (c, ct) =>
{
return 0 < await c.Blogs.CountAsync();
return await c.Blogs.AnyAsync();
}, failureStatus: HealthStatus.Unhealthy);

using (var scope = services.GetRequiredService<IServiceScopeFactory>().CreateScope())
Expand All @@ -110,7 +110,7 @@ public async Task CheckAsync_CustomTestWithNoFailureStatusSpecified_Unhealthy()
// Arrange
var services = CreateServices(async (c, ct) =>
{
return 0 < await c.Blogs.CountAsync();
return await c.Blogs.AnyAsync();
}, failureStatus: null);

using (var scope = services.GetRequiredService<IServiceScopeFactory>().CreateScope())
Expand Down
Loading

0 comments on commit 5d0ede4

Please sign in to comment.