Skip to content

Reenable CA1305 warnings #49695

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jul 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,7 @@ dotnet_diagnostic.CA1018.severity = warning
dotnet_diagnostic.CA1047.severity = warning

# CA1305: Specify IFormatProvider
# TODO: Renable as warning after https://github.com/dotnet/roslyn-analyzers/issues/6746 is resolved
dotnet_diagnostic.CA1305.severity = suggestion
dotnet_diagnostic.CA1305.severity = warning

# CA1507: Use nameof to express symbol names
dotnet_diagnostic.CA1507.severity = warning
Expand Down
3 changes: 2 additions & 1 deletion src/Antiforgery/samples/MinimalFormSample/Program.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Globalization;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Mvc;

Expand Down Expand Up @@ -54,7 +55,7 @@
{
var form = await context.Request.ReadFormAsync();
var name = form["name"].ToString();
var dueDate = DateTime.Parse(form["dueDate"].ToString());
var dueDate = DateTime.Parse(form["dueDate"].ToString(), CultureInfo.InvariantCulture);
var isCompleted = bool.Parse(form["isCompleted"].ToString());
var result = Results.Ok(new Todo(name, isCompleted, dueDate));
await result.ExecuteAsync(context);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Globalization;
using System.Linq;
using System.Text;

Expand Down Expand Up @@ -58,7 +59,7 @@ private string CreateMessageForAmbiguousNamedSubmitEvent(string scopeQualifiedNa

foreach (var location in locations)
{
sb.Append($"\n - {GenerateComponentPath(location.ComponentId)}");
sb.Append(CultureInfo.InvariantCulture, $"\n - {GenerateComponentPath(location.ComponentId)}");
}

return sb.ToString();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System.Configuration.Assemblies;
using System.Globalization;
using System.Numerics;
using BasicTestApp;
using BasicTestApp.HierarchicalImportsTest.Subdir;
Expand Down Expand Up @@ -401,7 +402,7 @@ public void CanUseFocusExtensionToFocusElement()
string getFocusedElementId() => Browser.SwitchTo().ActiveElement().GetAttribute("id");

// A local helper that gets window.PageYOffset
int getPageYOffset() => Convert.ToInt32(((IJavaScriptExecutor)Browser).ExecuteScript("return window.pageYOffset"));
int getPageYOffset() => Convert.ToInt32(((IJavaScriptExecutor)Browser).ExecuteScript("return window.pageYOffset"), CultureInfo.InvariantCulture);
}

[Fact]
Expand Down Expand Up @@ -456,7 +457,7 @@ public void CanUseFocusExtensionToFocusElementPreventScroll()
string getFocusedElementId() => Browser.SwitchTo().ActiveElement().GetAttribute("id");

// A local helper that gets window.PageYOffset
int getPageYOffset() => Convert.ToInt32(((IJavaScriptExecutor)Browser).ExecuteScript("return window.pageYOffset"));
int getPageYOffset() => Convert.ToInt32(((IJavaScriptExecutor)Browser).ExecuteScript("return window.pageYOffset"), CultureInfo.InvariantCulture);
}

[Theory]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ public override async Task ProvideCompletionsAsync(CompletionContext context)

if (change.NewPosition != null)
{
properties.Add(NewPositionKey, change.NewPosition.ToString());
properties.Add(NewPositionKey, change.NewPosition.Value.ToString(CultureInfo.InvariantCulture));
}

// Keep everything sorted in the order we just produced the items in.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ not CompletionTriggerKind.InvokeAndCommitIfUnique and

if (change.NewPosition != null)
{
properties.Add(NewPositionKey, change.NewPosition.ToString());
properties.Add(NewPositionKey, change.NewPosition.Value.ToString(CultureInfo.InvariantCulture));
}

// Keep everything sorted in the order we just produced the items in.
Expand Down
23 changes: 12 additions & 11 deletions src/Http/Routing/test/FunctionalTests/AntiforgeryTests.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Globalization;
using System.Net;
using System.Net.Http;
using System.Text.Json;
Expand Down Expand Up @@ -56,7 +57,7 @@ public async Task MapPost_WithForm_ValidToken_Works()
new KeyValuePair<string,string>("__RequestVerificationToken", tokens.RequestToken),
new KeyValuePair<string,string>("name", "Test task"),
new KeyValuePair<string,string>("isComplete", "false"),
new KeyValuePair<string,string>("dueDate", DateTime.Today.AddDays(1).ToString()),
new KeyValuePair<string,string>("dueDate", DateTime.Today.AddDays(1).ToString(CultureInfo.InvariantCulture)),
};
request.Content = new FormUrlEncodedContent(nameValueCollection);

Expand Down Expand Up @@ -88,7 +89,7 @@ public async Task MapRequestDelegate_WithForm_RequiresValidation_ValidToken_Work
{
Name = form["name"],
IsCompleted = bool.Parse(form["isComplete"]),
DueDate = DateTime.Parse(form["dueDate"])
DueDate = DateTime.Parse(form["dueDate"], CultureInfo.InvariantCulture)
};
await context.Response.WriteAsJsonAsync(todo);
}).WithMetadata(AntiforgeryMetadata.ValidationRequired));
Expand Down Expand Up @@ -116,7 +117,7 @@ public async Task MapRequestDelegate_WithForm_RequiresValidation_ValidToken_Work
new KeyValuePair<string,string>("__RequestVerificationToken", tokens.RequestToken),
new KeyValuePair<string,string>("name", "Test task"),
new KeyValuePair<string,string>("isComplete", "false"),
new KeyValuePair<string,string>("dueDate", DateTime.Today.AddDays(1).ToString()),
new KeyValuePair<string,string>("dueDate", DateTime.Today.AddDays(1).ToString(CultureInfo.InvariantCulture)),
};
request.Content = new FormUrlEncodedContent(nameValueCollection);

Expand Down Expand Up @@ -161,7 +162,7 @@ public async Task MapPost_WithForm_InvalidToken_Fails()
{
new KeyValuePair<string,string>("name", "Test task"),
new KeyValuePair<string,string>("isComplete", "false"),
new KeyValuePair<string,string>("dueDate", DateTime.Today.AddDays(1).ToString()),
new KeyValuePair<string,string>("dueDate", DateTime.Today.AddDays(1).ToString(CultureInfo.InvariantCulture)),
};
request.Content = new FormUrlEncodedContent(nameValueCollection);

Expand Down Expand Up @@ -200,7 +201,7 @@ public async Task MapPost_WithForm_WithoutMiddleware_ThrowsException()
{
new KeyValuePair<string,string>("name", "Test task"),
new KeyValuePair<string,string>("isComplete", "false"),
new KeyValuePair<string,string>("dueDate", DateTime.Today.AddDays(1).ToString()),
new KeyValuePair<string,string>("dueDate", DateTime.Today.AddDays(1).ToString(CultureInfo.InvariantCulture)),
};
request.Content = new FormUrlEncodedContent(nameValueCollection);

Expand Down Expand Up @@ -277,7 +278,7 @@ public async Task MapPost_WithForm_WithoutAntiforgery_WithoutMiddleware_Works()
{
new KeyValuePair<string,string>("name", "Test task"),
new KeyValuePair<string,string>("isComplete", "false"),
new KeyValuePair<string,string>("dueDate", DateTime.Today.AddDays(1).ToString()),
new KeyValuePair<string,string>("dueDate", DateTime.Today.AddDays(1).ToString(CultureInfo.InvariantCulture)),
};
request.Content = new FormUrlEncodedContent(nameValueCollection);

Expand All @@ -303,7 +304,7 @@ public static IEnumerable<object[]> RequestDelegateData
{
Name = form["name"],
IsCompleted = bool.Parse(form["isComplete"]),
DueDate = DateTime.Parse(form["dueDate"])
DueDate = DateTime.Parse(form["dueDate"], CultureInfo.InvariantCulture)
};
await context.Response.WriteAsJsonAsync(todo);
}),
Expand All @@ -317,7 +318,7 @@ public static IEnumerable<object[]> RequestDelegateData
{
Name = form["name"],
IsCompleted = bool.Parse(form["isComplete"]),
DueDate = DateTime.Parse(form["dueDate"])
DueDate = DateTime.Parse(form["dueDate"], CultureInfo.InvariantCulture)
};
await context.Response.WriteAsJsonAsync(todo);
}),
Expand All @@ -331,7 +332,7 @@ public static IEnumerable<object[]> RequestDelegateData
{
Name = form["name"],
IsCompleted = bool.Parse(form["isComplete"]),
DueDate = DateTime.Parse(form["dueDate"])
DueDate = DateTime.Parse(form["dueDate"], CultureInfo.InvariantCulture)
};
await context.Response.WriteAsJsonAsync(todo);
}),
Expand Down Expand Up @@ -373,7 +374,7 @@ public async Task MapRequestDelegate_WithForm_RequiresValidation_InvalidToken_Fa
{
new KeyValuePair<string,string>("name", "Test task"),
new KeyValuePair<string,string>("isComplete", "false"),
new KeyValuePair<string,string>("dueDate", DateTime.Today.AddDays(1).ToString()),
new KeyValuePair<string,string>("dueDate", DateTime.Today.AddDays(1).ToString(CultureInfo.InvariantCulture)),
};
request.Content = new FormUrlEncodedContent(nameValueCollection);

Expand Down Expand Up @@ -430,7 +431,7 @@ public async Task MapPost_WithForm_ValidToken_RequestSizeLimit_Works(bool hasLim
new KeyValuePair<string,string>("__RequestVerificationToken", tokens.RequestToken),
new KeyValuePair<string,string>("name", "Test task"),
new KeyValuePair<string,string>("isComplete", "false"),
new KeyValuePair<string,string>("dueDate", DateTime.Today.AddDays(1).ToString()),
new KeyValuePair<string,string>("dueDate", DateTime.Today.AddDays(1).ToString(CultureInfo.InvariantCulture)),
};
request.Content = new FormUrlEncodedContent(nameValueCollection);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

#nullable enable

using System.Globalization;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
Expand Down Expand Up @@ -612,7 +613,7 @@ public async Task CanEnableAndLoginWithTwoFactor(string addIdentityMode)
var keyBytes = Base32.FromBase32(sharedKey);
var unixTimestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
var timestep = Convert.ToInt64(unixTimestamp / 30);
var twoFactorCode = Rfc6238AuthenticationService.ComputeTotp(keyBytes, (ulong)timestep, modifierBytes: null).ToString();
var twoFactorCode = Rfc6238AuthenticationService.ComputeTotp(keyBytes, (ulong)timestep, modifierBytes: null).ToString(CultureInfo.InvariantCulture);

var enable2faResponse = await client.PostAsJsonAsync("/identity/account/2fa", new { twoFactorCode, Enable = true });
var enable2faContent = await enable2faResponse.Content.ReadFromJsonAsync<JsonElement>();
Expand Down Expand Up @@ -652,7 +653,7 @@ public async Task CanLoginWithRecoveryCodeAndDisableTwoFactor()
var keyBytes = Base32.FromBase32(sharedKey);
var unixTimestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
var timestep = Convert.ToInt64(unixTimestamp / 30);
var twoFactorCode = Rfc6238AuthenticationService.ComputeTotp(keyBytes, (ulong)timestep, modifierBytes: null).ToString();
var twoFactorCode = Rfc6238AuthenticationService.ComputeTotp(keyBytes, (ulong)timestep, modifierBytes: null).ToString(CultureInfo.InvariantCulture);

var enable2faResponse = await client.PostAsJsonAsync("/identity/account/2fa", new { twoFactorCode, Enable = true });
var enable2faContent = await enable2faResponse.Content.ReadFromJsonAsync<JsonElement>();
Expand Down Expand Up @@ -702,7 +703,7 @@ public async Task CanResetSharedKey()
var keyBytes = Base32.FromBase32(sharedKey);
var unixTimestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
var timestep = Convert.ToInt64(unixTimestamp / 30);
var twoFactorCode = Rfc6238AuthenticationService.ComputeTotp(keyBytes, (ulong)timestep, modifierBytes: null).ToString();
var twoFactorCode = Rfc6238AuthenticationService.ComputeTotp(keyBytes, (ulong)timestep, modifierBytes: null).ToString(CultureInfo.InvariantCulture);

await AssertValidationProblemAsync(await client.PostAsJsonAsync("/identity/account/2fa", new { twoFactorCode, Enable = true, ResetSharedKey = true }),
"CannotResetSharedKeyAndEnable");
Expand All @@ -718,7 +719,7 @@ public async Task CanResetSharedKey()
var resetSharedKey = resetKeyContent.GetProperty("sharedKey").GetString();

var resetKeyBytes = Base32.FromBase32(sharedKey);
var resetTwoFactorCode = Rfc6238AuthenticationService.ComputeTotp(keyBytes, (ulong)timestep, modifierBytes: null).ToString();
var resetTwoFactorCode = Rfc6238AuthenticationService.ComputeTotp(keyBytes, (ulong)timestep, modifierBytes: null).ToString(CultureInfo.InvariantCulture);

// The old 2fa code no longer works
await AssertValidationProblemAsync(await client.PostAsJsonAsync("/identity/account/2fa", new { twoFactorCode, Enable = true }),
Expand Down Expand Up @@ -748,7 +749,7 @@ public async Task CanResetRecoveryCodes()
var keyBytes = Base32.FromBase32(sharedKey);
var unixTimestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
var timestep = Convert.ToInt64(unixTimestamp / 30);
var twoFactorCode = Rfc6238AuthenticationService.ComputeTotp(keyBytes, (ulong)timestep, modifierBytes: null).ToString();
var twoFactorCode = Rfc6238AuthenticationService.ComputeTotp(keyBytes, (ulong)timestep, modifierBytes: null).ToString(CultureInfo.InvariantCulture);

var enable2faResponse = await client.PostAsJsonAsync("/identity/account/2fa", new { twoFactorCode, Enable = true });
var enable2faContent = await enable2faResponse.Content.ReadFromJsonAsync<JsonElement>();
Expand Down Expand Up @@ -815,7 +816,7 @@ public async Task CanUsePersistentTwoFactorCookies()
var keyBytes = Base32.FromBase32(sharedKey);
var unixTimestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
var timestep = Convert.ToInt64(unixTimestamp / 30);
var twoFactorCode = Rfc6238AuthenticationService.ComputeTotp(keyBytes, (ulong)timestep, modifierBytes: null).ToString();
var twoFactorCode = Rfc6238AuthenticationService.ComputeTotp(keyBytes, (ulong)timestep, modifierBytes: null).ToString(CultureInfo.InvariantCulture);

var enable2faResponse = await client.PostAsJsonAsync("/identity/account/2fa", new { twoFactorCode, Enable = true });
var enable2faContent = await enable2faResponse.Content.ReadFromJsonAsync<JsonElement>();
Expand Down
2 changes: 1 addition & 1 deletion src/Middleware/Session/test/SessionTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -463,7 +463,7 @@ public async Task RefreshesSession_WhenSessionData_IsNotModified()
else if (context.Request.Path == new PathString("/AccessSessionData"))
{
var value = context.Session.GetInt32("Key");
responseData = (value == null) ? "No value found in session." : value.ToString();
responseData = (value == null) ? "No value found in session." : value.Value.ToString(CultureInfo.InvariantCulture);
}
else if (context.Request.Path == new PathString("/DoNotAccessSessionData"))
{
Expand Down
5 changes: 3 additions & 2 deletions src/Security/Authentication/test/JwtBearerTests_Handler.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Globalization;
using System.IdentityModel.Tokens.Jwt;
using System.Net;
using System.Net.Http;
Expand Down Expand Up @@ -951,11 +952,11 @@ public async Task ExpirationAndIssuedWhenMinOrMaxValue()
var expiresElement = dom.RootElement.GetProperty("expires");
Assert.Equal(JsonValueKind.String, expiresElement.ValueKind);

var elementValue = DateTime.Parse(expiresElement.GetString());
var elementValue = DateTime.Parse(expiresElement.GetString(), CultureInfo.InvariantCulture);
var elementValueUtc = elementValue.ToUniversalTime();
// roundtrip DateTime.MaxValue through parsing because it is lossy and we
// need equivalent values to compare against.
var max = DateTime.Parse(DateTime.MaxValue.ToString());
var max = DateTime.Parse(DateTime.MaxValue.ToString(CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);

Assert.Equal(max, elementValueUtc);
}
Expand Down