Browse Source

Reenable CA1305 warnings (#49695)

Stephen Halter 2 years ago
parent
commit
7ca3fdacae

+ 1 - 2
.editorconfig

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

+ 2 - 1
src/Antiforgery/samples/MinimalFormSample/Program.cs

@@ -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;
 
@@ -54,7 +55,7 @@ app.MapPost("/todo-raw", async context =>
 {
     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);

+ 2 - 1
src/Components/Endpoints/src/Rendering/EndpointHtmlRenderer.EventDispatch.cs

@@ -6,6 +6,7 @@ using Microsoft.AspNetCore.Components.RenderTree;
 using Microsoft.AspNetCore.Http;
 using Microsoft.Extensions.DependencyInjection;
 using Microsoft.Extensions.Hosting;
+using System.Globalization;
 using System.Linq;
 using System.Text;
 
@@ -58,7 +59,7 @@ internal partial class EndpointHtmlRenderer
 
         foreach (var location in locations)
         {
-            sb.Append($"\n - {GenerateComponentPath(location.ComponentId)}");
+            sb.Append(CultureInfo.InvariantCulture, $"\n - {GenerateComponentPath(location.ComponentId)}");
         }
 
         return sb.ToString();

+ 3 - 2
src/Components/test/E2ETest/Tests/ComponentRenderingTestBase.cs

@@ -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;
@@ -401,7 +402,7 @@ public abstract class ComponentRenderingTestBase : ServerTestBase<ToggleExecutio
         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]
@@ -456,7 +457,7 @@ public abstract class ComponentRenderingTestBase : ServerTestBase<ToggleExecutio
         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]

+ 1 - 1
src/Framework/AspNetCoreAnalyzers/src/Analyzers/RouteEmbeddedLanguage/FrameworkParametersCompletionProvider.cs

@@ -263,7 +263,7 @@ public sealed class FrameworkParametersCompletionProvider : CompletionProvider
 
             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.

+ 1 - 1
src/Framework/AspNetCoreAnalyzers/src/Analyzers/RouteEmbeddedLanguage/RoutePatternCompletionProvider.cs

@@ -142,7 +142,7 @@ public class RoutePatternCompletionProvider : CompletionProvider
 
             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.

+ 12 - 11
src/Http/Routing/test/FunctionalTests/AntiforgeryTests.cs

@@ -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;
@@ -56,7 +57,7 @@ public class AntiforgeryTests
             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);
 
@@ -88,7 +89,7 @@ public class AntiforgeryTests
                                 {
                                     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));
@@ -116,7 +117,7 @@ public class AntiforgeryTests
             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);
 
@@ -161,7 +162,7 @@ public class AntiforgeryTests
         {
             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);
 
@@ -200,7 +201,7 @@ public class AntiforgeryTests
         {
             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);
 
@@ -277,7 +278,7 @@ public class AntiforgeryTests
         {
             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);
 
@@ -303,7 +304,7 @@ public class AntiforgeryTests
                     {
                         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);
                 }),
@@ -317,7 +318,7 @@ public class AntiforgeryTests
                     {
                         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);
                 }),
@@ -331,7 +332,7 @@ public class AntiforgeryTests
                     {
                         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);
                 }),
@@ -373,7 +374,7 @@ public class AntiforgeryTests
         {
             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);
 
@@ -430,7 +431,7 @@ public class AntiforgeryTests
             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);
 

+ 7 - 6
src/Identity/test/Identity.FunctionalTests/MapIdentityApiTests.cs

@@ -3,6 +3,7 @@
 
 #nullable enable
 
+using System.Globalization;
 using System.Net;
 using System.Net.Http;
 using System.Net.Http.Json;
@@ -612,7 +613,7 @@ public class MapIdentityApiTests : LoggedTest
         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>();
@@ -652,7 +653,7 @@ public class MapIdentityApiTests : LoggedTest
         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>();
@@ -702,7 +703,7 @@ public class MapIdentityApiTests : LoggedTest
         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");
@@ -718,7 +719,7 @@ public class MapIdentityApiTests : LoggedTest
         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 }),
@@ -748,7 +749,7 @@ public class MapIdentityApiTests : LoggedTest
         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>();
@@ -815,7 +816,7 @@ public class MapIdentityApiTests : LoggedTest
         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>();

+ 1 - 1
src/Middleware/Session/test/SessionTests.cs

@@ -463,7 +463,7 @@ public class SessionTests
                         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"))
                         {

+ 3 - 2
src/Security/Authentication/test/JwtBearerTests_Handler.cs

@@ -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;
@@ -951,11 +952,11 @@ public class JwtBearerTests_Handler : SharedAuthenticationTests<JwtBearerOptions
         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);
     }