From e3265e1d95c0f0f7354a21201817facb69b08cce Mon Sep 17 00:00:00 2001 From: Francois Raminosona Date: Sun, 22 Nov 2026 21:38:10 +0100 Subject: [PATCH] fix: resolve CodeQL code quality findings - AssemblyExtensions: reject a filename with a directory part. A rooted filename made Path.Combine drop targetDirectory, and ".." escaped it. Path.Join is used from there on. - NumericRangeTools: drop the unreachable zero-step guard inside the range iterators and validate step with IsFinite plus an epsilon check. - Replace "HasValue == false" with a negation in TaskExtensions and SemaphoreSlimExtensions. - UriExtensions, StringExtensions: filter with OfType/Where instead of a foreach whose body is a single if. - Tests: dispose CancellationTokenSource, use Path.Join, stop swallowing exceptions with a bare catch, avoid dereferencing a null-initialised local, and cover the new filename validation. --- .../AssemblyExtensionsTests.cs | 114 +++++++++++++++--- .../CancellationTokenExtensionsTests.cs | 18 +-- .../ConcurrentDictioneryExtensionsTests.cs | 26 ++-- .../DictionaryExtensionsTests.cs | 2 +- .../EnumerableExtensionsTests.cs | 2 +- .../ExceptionExtensionsTests.cs | 2 +- .../ListExtensionsTests.cs | 2 +- .../SemaphoreSlimExtensionsTests.cs | 4 +- .../TaskExtensionsTests.cs | 40 ++---- .../AssemblyExtensions.cs | 30 +++-- .../NumericRangeTools.cs | 14 +-- .../SemaphoreSlimExtensions.cs | 4 +- Plugin.BaseTypeExtensions/StringExtensions.cs | 9 +- Plugin.BaseTypeExtensions/TaskExtensions.cs | 4 +- Plugin.BaseTypeExtensions/UriExtensions.cs | 7 +- 15 files changed, 171 insertions(+), 107 deletions(-) diff --git a/Plugin.BaseTypeExtensions.Tests/AssemblyExtensionsTests.cs b/Plugin.BaseTypeExtensions.Tests/AssemblyExtensionsTests.cs index ffb9acc..9ace8ba 100644 --- a/Plugin.BaseTypeExtensions.Tests/AssemblyExtensionsTests.cs +++ b/Plugin.BaseTypeExtensions.Tests/AssemblyExtensionsTests.cs @@ -8,7 +8,7 @@ public class AssemblyExtensionsTests private static string CreateTempDirectory() { - var path = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); + var path = Path.Join(Path.GetTempPath(), Guid.NewGuid().ToString("N")); Directory.CreateDirectory(path); return path; } @@ -62,7 +62,7 @@ public void MoveManifestResourceToDirectory_GeneratesRandomFilename() public void MoveManifestResourceToDirectory_CreatesDirectoryIfNotExists() { var parentDirectory = CreateTempDirectory(); - var targetDirectory = Path.Combine(parentDirectory, "subdir", "nested"); + var targetDirectory = Path.Join(parentDirectory, "subdir", "nested"); try { var assembly = typeof(AssemblyExtensionsTests).Assembly; @@ -89,7 +89,7 @@ public void MoveManifestResourceToDirectory_HandlesFileAlreadyExistsBehavior(Ass var directory = CreateTempDirectory(); try { - var targetFile = Path.Combine(directory, "resource.txt"); + var targetFile = Path.Join(directory, "resource.txt"); File.WriteAllText(targetFile, "existing"); var assembly = typeof(AssemblyExtensionsTests).Assembly; @@ -129,7 +129,7 @@ public void MoveManifestResourceToDirectory_FailThrows() var directory = CreateTempDirectory(); try { - var targetFile = Path.Combine(directory, "resource.txt"); + var targetFile = Path.Join(directory, "resource.txt"); File.WriteAllText(targetFile, "existing"); var assembly = typeof(AssemblyExtensionsTests).Assembly; @@ -154,9 +154,9 @@ public void MoveManifestResourceToDirectory_RenameHandlesMultipleConflicts() try { // Create multiple existing files - File.WriteAllText(Path.Combine(directory, "resource.txt"), "existing"); - File.WriteAllText(Path.Combine(directory, "resource_1.txt"), "existing_1"); - File.WriteAllText(Path.Combine(directory, "resource_2.txt"), "existing_2"); + File.WriteAllText(Path.Join(directory, "resource.txt"), "existing"); + File.WriteAllText(Path.Join(directory, "resource_1.txt"), "existing_1"); + File.WriteAllText(Path.Join(directory, "resource_2.txt"), "existing_2"); var assembly = typeof(AssemblyExtensionsTests).Assembly; var result = assembly.MoveManifestResourceToDirectory( @@ -180,7 +180,7 @@ public void MoveManifestResourceToDirectory_RenameWithExtension() var directory = CreateTempDirectory(); try { - var targetFile = Path.Combine(directory, "document.docx"); + var targetFile = Path.Join(directory, "document.docx"); File.WriteAllText(targetFile, "existing"); var assembly = typeof(AssemblyExtensionsTests).Assembly; @@ -205,7 +205,7 @@ public void MoveManifestResourceToDirectory_RenameWithoutExtension() var directory = CreateTempDirectory(); try { - var targetFile = Path.Combine(directory, "document"); + var targetFile = Path.Join(directory, "document"); File.WriteAllText(targetFile, "existing"); var assembly = typeof(AssemblyExtensionsTests).Assembly; @@ -272,7 +272,7 @@ public async Task MoveManifestResourceToDirectoryAsync_GeneratesRandomFilename() public async Task MoveManifestResourceToDirectoryAsync_CreatesDirectoryIfNotExists() { var parentDirectory = CreateTempDirectory(); - var targetDirectory = Path.Combine(parentDirectory, "async_subdir", "nested"); + var targetDirectory = Path.Join(parentDirectory, "async_subdir", "nested"); try { var assembly = typeof(AssemblyExtensionsTests).Assembly; @@ -299,7 +299,7 @@ public async Task MoveManifestResourceToDirectoryAsync_HandlesFileAlreadyExistsB var directory = CreateTempDirectory(); try { - var targetFile = Path.Combine(directory, "async_resource.txt"); + var targetFile = Path.Join(directory, "async_resource.txt"); File.WriteAllText(targetFile, "existing async"); var assembly = typeof(AssemblyExtensionsTests).Assembly; @@ -339,7 +339,7 @@ public async Task MoveManifestResourceToDirectoryAsync_FailThrows() var directory = CreateTempDirectory(); try { - var targetFile = Path.Combine(directory, "async_resource.txt"); + var targetFile = Path.Join(directory, "async_resource.txt"); File.WriteAllText(targetFile, "existing async"); var assembly = typeof(AssemblyExtensionsTests).Assembly; @@ -406,7 +406,7 @@ public async Task MoveManifestResourceToDirectoryAsync_CancellationCleanupPartia catch (OperationCanceledException) { // Expected - verify partial file cleanup - var expectedFile = Path.Combine(directory, "cancel_test.txt"); + var expectedFile = Path.Join(directory, "cancel_test.txt"); File.Exists(expectedFile).Should().BeFalse("Partial file should be cleaned up on cancellation"); } } @@ -479,7 +479,7 @@ public void MoveManifestResourceToCache_WithAllFileAlreadyExistsBehaviors() var assembly = typeof(AssemblyExtensionsTests).Assembly; // Test Skip behavior - var existingFile = Path.Combine(tempCacheDirectory, "test_skip.txt"); + var existingFile = Path.Join(tempCacheDirectory, "test_skip.txt"); File.WriteAllText(existingFile, "existing content"); var result = assembly.MoveManifestResourceToCache( @@ -575,7 +575,7 @@ public async Task MoveManifestResourceToCacheAsync_WithAllFileAlreadyExistsBehav var assembly = typeof(AssemblyExtensionsTests).Assembly; // Test Skip behavior - var existingFile = Path.Combine(tempCacheDirectory, "test_async_skip.txt"); + var existingFile = Path.Join(tempCacheDirectory, "test_async_skip.txt"); File.WriteAllText(existingFile, "existing async content"); var result = await assembly.MoveManifestResourceToCacheAsync( @@ -829,6 +829,86 @@ public async Task MoveManifestResourceToCacheAsync_ThrowsOnEmptyResourceName() await action.Should().ThrowAsync().WithParameterName("manifestResourceName"); } + [Theory] + [InlineData("../escape.txt")] + [InlineData("sub/file.txt")] + public void MoveManifestResourceToDirectory_ThrowsOnFilenameWithDirectoryPart(string filename) + { + var directory = CreateTempDirectory(); + try + { + var assembly = typeof(AssemblyExtensionsTests).Assembly; + Action action = () => assembly.MoveManifestResourceToDirectory( + "Plugin.BaseTypeExtensions.Tests.Resources.FirstResource.txt", directory, filename); + action.Should().Throw().WithParameterName("filename"); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + + [Fact] + public void MoveManifestResourceToDirectory_ThrowsOnRootedFilename_AndWritesNothing() + { + var directory = CreateTempDirectory(); + var elsewhere = CreateTempDirectory(); + try + { + var rootedFilename = Path.Join(elsewhere, "escape.txt"); + var assembly = typeof(AssemblyExtensionsTests).Assembly; + Action action = () => assembly.MoveManifestResourceToDirectory( + "Plugin.BaseTypeExtensions.Tests.Resources.FirstResource.txt", directory, rootedFilename); + action.Should().Throw().WithParameterName("filename"); + File.Exists(rootedFilename).Should().BeFalse(); + } + finally + { + Directory.Delete(directory, recursive: true); + Directory.Delete(elsewhere, recursive: true); + } + } + + [Theory] + [InlineData("../escape.txt")] + [InlineData("sub/file.txt")] + public async Task MoveManifestResourceToDirectoryAsync_ThrowsOnFilenameWithDirectoryPart(string filename) + { + var directory = CreateTempDirectory(); + try + { + var assembly = typeof(AssemblyExtensionsTests).Assembly; + Func action = () => assembly.MoveManifestResourceToDirectoryAsync( + "Plugin.BaseTypeExtensions.Tests.Resources.FirstResource.txt", directory, filename); + await action.Should().ThrowAsync().WithParameterName("filename"); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + + [Fact] + public async Task MoveManifestResourceToDirectoryAsync_ThrowsOnRootedFilename_AndWritesNothing() + { + var directory = CreateTempDirectory(); + var elsewhere = CreateTempDirectory(); + try + { + var rootedFilename = Path.Join(elsewhere, "escape.txt"); + var assembly = typeof(AssemblyExtensionsTests).Assembly; + Func action = () => assembly.MoveManifestResourceToDirectoryAsync( + "Plugin.BaseTypeExtensions.Tests.Resources.FirstResource.txt", directory, rootedFilename); + await action.Should().ThrowAsync().WithParameterName("filename"); + File.Exists(rootedFilename).Should().BeFalse(); + } + finally + { + Directory.Delete(directory, recursive: true); + Directory.Delete(elsewhere, recursive: true); + } + } + #endregion #region Edge Case Tests @@ -844,7 +924,7 @@ public void MoveManifestResourceToDirectory_RenameCounterLimit() var assembly = typeof(AssemblyExtensionsTests).Assembly; // Create a file that would cause the rename logic to increment - File.WriteAllText(Path.Combine(directory, "test.txt"), "existing"); + File.WriteAllText(Path.Join(directory, "test.txt"), "existing"); // This should work normally - just testing the edge case exists var result = assembly.MoveManifestResourceToDirectory( @@ -951,7 +1031,7 @@ public void FileAlreadyExistsBehavior_DefaultValue_IsFail() var directory = CreateTempDirectory(); try { - var targetFile = Path.Combine(directory, "default_test.txt"); + var targetFile = Path.Join(directory, "default_test.txt"); File.WriteAllText(targetFile, "existing"); var assembly = typeof(AssemblyExtensionsTests).Assembly; diff --git a/Plugin.BaseTypeExtensions.Tests/CancellationTokenExtensionsTests.cs b/Plugin.BaseTypeExtensions.Tests/CancellationTokenExtensionsTests.cs index 47637b0..0641772 100644 --- a/Plugin.BaseTypeExtensions.Tests/CancellationTokenExtensionsTests.cs +++ b/Plugin.BaseTypeExtensions.Tests/CancellationTokenExtensionsTests.cs @@ -6,7 +6,8 @@ public class CancellationTokenExtensionsTests public void WithTimeout_TimeSpan_CreatesCombinedToken() { // Arrange - var originalToken = new CancellationTokenSource().Token; + using var cts = new CancellationTokenSource(); + var originalToken = cts.Token; var timeout = TimeSpan.FromMilliseconds(100); // Act @@ -21,7 +22,8 @@ public void WithTimeout_TimeSpan_CreatesCombinedToken() public void WithTimeout_Milliseconds_CreatesCombinedToken() { // Arrange - var originalToken = new CancellationTokenSource().Token; + using var cts = new CancellationTokenSource(); + var originalToken = cts.Token; var timeoutMs = 100; // Act @@ -76,7 +78,7 @@ public void WithTimeout_ZeroTimeSpan_ReturnsAlreadyCanceledToken() public void WithTimeout_AlreadyCanceledToken_ReturnsSameToken() { // Arrange - var cts = new CancellationTokenSource(); + using var cts = new CancellationTokenSource(); cts.Cancel(); var canceledToken = cts.Token; @@ -92,7 +94,7 @@ public void WithTimeout_AlreadyCanceledToken_ReturnsSameToken() public void AsTask_ReturnsTaskThatCompletesOnCancellation() { // Arrange - var cts = new CancellationTokenSource(); + using var cts = new CancellationTokenSource(); var token = cts.Token; // Act @@ -120,7 +122,7 @@ public void AsTask_NeverCompletesForNonCanceledToken() public void AsTask_AlreadyCanceledToken_ReturnsCompletedTask() { // Arrange - var cts = new CancellationTokenSource(); + using var cts = new CancellationTokenSource(); cts.Cancel(); var token = cts.Token; @@ -136,7 +138,7 @@ public void AsTask_AlreadyCanceledToken_ReturnsCompletedTask() public void ThrowIfCanceledAfter_ThrowsWhenCanceled() { // Arrange - var cts = new CancellationTokenSource(); + using var cts = new CancellationTokenSource(); var token = cts.Token; cts.Cancel(); @@ -174,7 +176,7 @@ public void ThrowIfCanceledAfter_ZeroTimeout_ThrowsOperationCanceledException() public void ThrowIfCanceledAfter_TimeoutExpires_ThrowsOperationCanceledException() { // Arrange - var cts = new CancellationTokenSource(); + using var cts = new CancellationTokenSource(); var token = cts.Token; // Act & Assert @@ -187,7 +189,7 @@ public void ThrowIfCanceledAfter_TimeoutExpires_ThrowsOperationCanceledException public void WaitHandle_ReturnsTrueWhenCanceled() { // Arrange - var cts = new CancellationTokenSource(); + using var cts = new CancellationTokenSource(); var token = cts.Token; cts.Cancel(); diff --git a/Plugin.BaseTypeExtensions.Tests/ConcurrentDictioneryExtensionsTests.cs b/Plugin.BaseTypeExtensions.Tests/ConcurrentDictioneryExtensionsTests.cs index 109edc2..4a686ab 100644 --- a/Plugin.BaseTypeExtensions.Tests/ConcurrentDictioneryExtensionsTests.cs +++ b/Plugin.BaseTypeExtensions.Tests/ConcurrentDictioneryExtensionsTests.cs @@ -95,7 +95,7 @@ public async Task TryAddAsync_WithCancellation_ThrowsOperationCanceledException( { // Arrange var dictionary = new ConcurrentDictionary(); - var cts = new CancellationTokenSource(); + using var cts = new CancellationTokenSource(); cts.Cancel(); // Act @@ -111,7 +111,7 @@ public async Task TryAddAsync_WithCancellationDuringRetries_ThrowsOperationCance // Arrange var dictionary = new ConcurrentDictionary(); dictionary.TryAdd("test", 1); // Ensure first attempt fails - var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(50)); + using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(50)); // Act Func act = async () => await dictionary.TryAddAsync("test", 42, retryCount: 10, delayBetweenRetries: TimeSpan.FromMilliseconds(100), cancellationToken: cts.Token); @@ -124,10 +124,10 @@ public async Task TryAddAsync_WithCancellationDuringRetries_ThrowsOperationCance public async Task TryAddAsync_WithNullDictionary_ThrowsArgumentNullException() { // Arrange - ConcurrentDictionary? dictionary = null; + ConcurrentDictionary dictionary = null!; // Act - Func act = async () => await dictionary!.TryAddAsync("test", 42); + Func act = async () => await dictionary.TryAddAsync("test", 42); // Assert await act.Should().ThrowAsync() @@ -265,7 +265,7 @@ public async Task TryRemoveAsync_WithCancellation_ThrowsOperationCanceledExcepti { // Arrange var dictionary = new ConcurrentDictionary(); - var cts = new CancellationTokenSource(); + using var cts = new CancellationTokenSource(); cts.Cancel(); // Act @@ -279,10 +279,10 @@ public async Task TryRemoveAsync_WithCancellation_ThrowsOperationCanceledExcepti public async Task TryRemoveAsync_WithNullDictionary_ThrowsArgumentNullException() { // Arrange - ConcurrentDictionary? dictionary = null; + ConcurrentDictionary dictionary = null!; // Act - Func act = async () => await dictionary!.TryRemoveAsync("test"); + Func act = async () => await dictionary.TryRemoveAsync("test"); // Assert await act.Should().ThrowAsync() @@ -422,7 +422,7 @@ public async Task TryUpdateAsync_WithCancellation_ThrowsOperationCanceledExcepti { // Arrange var dictionary = new ConcurrentDictionary(); - var cts = new CancellationTokenSource(); + using var cts = new CancellationTokenSource(); cts.Cancel(); // Act @@ -436,10 +436,10 @@ public async Task TryUpdateAsync_WithCancellation_ThrowsOperationCanceledExcepti public async Task TryUpdateAsync_WithNullDictionary_ThrowsArgumentNullException() { // Arrange - ConcurrentDictionary? dictionary = null; + ConcurrentDictionary dictionary = null!; // Act - Func act = async () => await dictionary!.TryUpdateAsync("test", newValue: 42, comparisonValue: 1); + Func act = async () => await dictionary.TryUpdateAsync("test", newValue: 42, comparisonValue: 1); // Assert await act.Should().ThrowAsync() @@ -562,7 +562,7 @@ public async Task TryGetValueAsync_WithCancellation_ThrowsOperationCanceledExcep { // Arrange var dictionary = new ConcurrentDictionary(); - var cts = new CancellationTokenSource(); + using var cts = new CancellationTokenSource(); cts.Cancel(); // Act @@ -576,10 +576,10 @@ public async Task TryGetValueAsync_WithCancellation_ThrowsOperationCanceledExcep public async Task TryGetValueAsync_WithNullDictionary_ThrowsArgumentNullException() { // Arrange - ConcurrentDictionary? dictionary = null; + ConcurrentDictionary dictionary = null!; // Act - Func act = async () => await dictionary!.TryGetValueAsync("test"); + Func act = async () => await dictionary.TryGetValueAsync("test"); // Assert await act.Should().ThrowAsync() diff --git a/Plugin.BaseTypeExtensions.Tests/DictionaryExtensionsTests.cs b/Plugin.BaseTypeExtensions.Tests/DictionaryExtensionsTests.cs index 02e54ba..6705365 100644 --- a/Plugin.BaseTypeExtensions.Tests/DictionaryExtensionsTests.cs +++ b/Plugin.BaseTypeExtensions.Tests/DictionaryExtensionsTests.cs @@ -215,7 +215,7 @@ await dict.UpdateFromAsync( public async Task UpdateFromAsync_WithCancellation_ThrowsOperationCanceledException() { var dict = new Dictionary { ["a"] = 1 }; - var cts = new CancellationTokenSource(); + using var cts = new CancellationTokenSource(); cts.Cancel(); var action = async () => await dict.UpdateFromAsync( diff --git a/Plugin.BaseTypeExtensions.Tests/EnumerableExtensionsTests.cs b/Plugin.BaseTypeExtensions.Tests/EnumerableExtensionsTests.cs index a596465..514bfbf 100644 --- a/Plugin.BaseTypeExtensions.Tests/EnumerableExtensionsTests.cs +++ b/Plugin.BaseTypeExtensions.Tests/EnumerableExtensionsTests.cs @@ -195,7 +195,7 @@ await output.UpdateFromAsync( public async Task UpdateFromAsync_WithCancellation_ThrowsOperationCanceledException() { var output = new List { 1, 2, 3 }; - var cts = new CancellationTokenSource(); + using var cts = new CancellationTokenSource(); cts.Cancel(); var action = async () => await output.UpdateFromAsync( diff --git a/Plugin.BaseTypeExtensions.Tests/ExceptionExtensionsTests.cs b/Plugin.BaseTypeExtensions.Tests/ExceptionExtensionsTests.cs index ae918d5..66072eb 100644 --- a/Plugin.BaseTypeExtensions.Tests/ExceptionExtensionsTests.cs +++ b/Plugin.BaseTypeExtensions.Tests/ExceptionExtensionsTests.cs @@ -41,7 +41,7 @@ public void GetStackTraceWithoutSystemCalls_FiltersSystemCalls() { throw new InvalidOperationException("Test with stack trace"); } - catch (Exception ex) + catch (InvalidOperationException ex) { exception = ex; } diff --git a/Plugin.BaseTypeExtensions.Tests/ListExtensionsTests.cs b/Plugin.BaseTypeExtensions.Tests/ListExtensionsTests.cs index 5e19b7f..97aa710 100644 --- a/Plugin.BaseTypeExtensions.Tests/ListExtensionsTests.cs +++ b/Plugin.BaseTypeExtensions.Tests/ListExtensionsTests.cs @@ -144,7 +144,7 @@ await list.UpdateFromAsync( public async Task UpdateFromAsync_WithCancellation_ThrowsOperationCanceledException() { var list = new List { 1, 2 }; - var cts = new CancellationTokenSource(); + using var cts = new CancellationTokenSource(); cts.Cancel(); var action = async () => await list.UpdateFromAsync( diff --git a/Plugin.BaseTypeExtensions.Tests/SemaphoreSlimExtensionsTests.cs b/Plugin.BaseTypeExtensions.Tests/SemaphoreSlimExtensionsTests.cs index 3c0f3df..bae2323 100644 --- a/Plugin.BaseTypeExtensions.Tests/SemaphoreSlimExtensionsTests.cs +++ b/Plugin.BaseTypeExtensions.Tests/SemaphoreSlimExtensionsTests.cs @@ -79,7 +79,7 @@ public async Task WaitBetterAsync_TimeSpan_WithCancellationToken_RespectsToken() { // Arrange using var semaphore = new SemaphoreSlim(0, 1); // No permits available - var cts = new CancellationTokenSource(); + using var cts = new CancellationTokenSource(); // Act var waitTask = semaphore.WaitBetterAsync(TimeSpan.FromSeconds(10), cts.Token); @@ -180,7 +180,7 @@ public async Task WaitBetterAsync_Int_WithCancellationToken_RespectsToken() { // Arrange using var semaphore = new SemaphoreSlim(0, 1); // No permits available - var cts = new CancellationTokenSource(); + using var cts = new CancellationTokenSource(); // Act var waitTask = semaphore.WaitBetterAsync(10000, cts.Token); diff --git a/Plugin.BaseTypeExtensions.Tests/TaskExtensionsTests.cs b/Plugin.BaseTypeExtensions.Tests/TaskExtensionsTests.cs index 3c472d5..097a120 100644 --- a/Plugin.BaseTypeExtensions.Tests/TaskExtensionsTests.cs +++ b/Plugin.BaseTypeExtensions.Tests/TaskExtensionsTests.cs @@ -86,7 +86,7 @@ public async Task WaitAsync_Generic_WithCancellationToken_RespectsToken() { // Arrange var tcs = new TaskCompletionSource(); - var cts = new CancellationTokenSource(); + using var cts = new CancellationTokenSource(); // Act var waitTask = tcs.Task.WaitBetterAsync(TimeSpan.FromSeconds(10), cts.Token); @@ -169,7 +169,7 @@ public async Task WaitAsync_NonGeneric_WithCancellationToken_RespectsToken() { // Arrange var tcs = new TaskCompletionSource(); - var cts = new CancellationTokenSource(); + using var cts = new CancellationTokenSource(); // Act var waitTask = tcs.Task.WaitBetterAsync(TimeSpan.FromSeconds(10), cts.Token); @@ -200,7 +200,7 @@ public async Task WaitAsync_LargeTimeout_DoesNotThrow() public async Task WaitAsync_CancelledTask_PropagatesCancellation() { // Arrange - var cts = new CancellationTokenSource(); + using var cts = new CancellationTokenSource(); cts.Cancel(); var cancelledTask = Task.FromCanceled(cts.Token); @@ -476,15 +476,9 @@ public async Task StartAndForget_WithTCS_TaskThatThrows_SetsException() // Act task.StartAndForget(tcs); - // Wait for the task to complete by awaiting tcs.Task with exception handling - try - { - await tcs.Task; - } - catch - { - // Exception is expected, assertions below will verify - } + // Wait for the task to complete + Func awaitCompletion = async () => await tcs.Task; + await awaitCompletion.Should().ThrowAsync(); // Assert tcs.Task.IsFaulted.Should().BeTrue(); @@ -505,15 +499,9 @@ public async Task StartAndForget_WithTCS_ExceptionPropagatedCorrectly() // Act task.StartAndForget(tcs); - // Wait for exception to be set by awaiting tcs.Task with exception handling - try - { - await tcs.Task; - } - catch - { - // Exception is expected, assertions below will verify - } + // Wait for exception to be set + Func awaitCompletion = async () => await tcs.Task; + await awaitCompletion.Should().ThrowAsync(); // Assert tcs.Task.IsFaulted.Should().BeTrue(); @@ -584,14 +572,8 @@ public async Task StartAndForget_WithTCS_CancelledTask_SetsException() task.StartAndForget(tcs); // Wait for exception to be set - try - { - await tcs.Task; - } - catch - { - // Exception is expected, assertions below will verify - } + Func awaitCompletion = async () => await tcs.Task; + await awaitCompletion.Should().ThrowAsync(); // Assert tcs.Task.IsFaulted.Should().BeTrue(); diff --git a/Plugin.BaseTypeExtensions/AssemblyExtensions.cs b/Plugin.BaseTypeExtensions/AssemblyExtensions.cs index f87a309..6f7df73 100644 --- a/Plugin.BaseTypeExtensions/AssemblyExtensions.cs +++ b/Plugin.BaseTypeExtensions/AssemblyExtensions.cs @@ -43,7 +43,7 @@ public enum FileAlreadyExistsBehavior /// Behavior when the target file already exists. /// A object representing the extracted file. /// Thrown when required parameters are null. - /// Thrown when manifestResourceName is empty or whitespace. + /// Thrown when manifestResourceName is empty or whitespace, or when filename is not a plain file name (it has a directory part). /// Thrown when the target directory cannot be created or accessed. /// Thrown when the manifest resource cannot be found. /// Thrown when file operations fail or when fileAlreadyExistsBehavior is Fail and file exists. @@ -61,6 +61,7 @@ public static FileInfo MoveManifestResourceToDirectory(this Assembly assembly, s // Generate filename if not provided filename ??= $"{DateTime.Now.Ticks}_{Path.GetRandomFileName()}"; + ThrowIfNotPlainFileName(filename); // Ensure target directory exists if (!Directory.Exists(targetDirectory)) @@ -75,7 +76,7 @@ public static FileInfo MoveManifestResourceToDirectory(this Assembly assembly, s } } - var outputFilePath = Path.Combine(targetDirectory, filename); + var outputFilePath = Path.Join(targetDirectory, filename); // Handle existing file based on specified behavior if (File.Exists(outputFilePath)) @@ -100,7 +101,7 @@ public static FileInfo MoveManifestResourceToDirectory(this Assembly assembly, s do { filename = $"{nameWithoutExtension}_{counter}{extension}"; - outputFilePath = Path.Combine(targetDirectory, filename); + outputFilePath = Path.Join(targetDirectory, filename); counter++; // Prevent infinite loop in case of extreme edge cases @@ -173,7 +174,7 @@ public static FileInfo MoveManifestResourceToDirectory(this Assembly assembly, s /// A token to cancel the operation. /// A representing the asynchronous operation that returns a object for the extracted file. /// Thrown when required parameters are null. - /// Thrown when manifestResourceName is empty or whitespace. + /// Thrown when manifestResourceName is empty or whitespace, or when filename is not a plain file name (it has a directory part). /// Thrown when the target directory cannot be created or accessed. /// Thrown when the manifest resource cannot be found. /// Thrown when file operations fail or when fileAlreadyExistsBehavior is Fail and file exists. @@ -194,6 +195,7 @@ public static async Task MoveManifestResourceToDirectoryAsync(this Ass // Generate filename if not provided filename ??= $"{DateTime.Now.Ticks}_{Path.GetRandomFileName()}"; + ThrowIfNotPlainFileName(filename); // Ensure target directory exists if (!Directory.Exists(targetDirectory)) @@ -208,7 +210,7 @@ public static async Task MoveManifestResourceToDirectoryAsync(this Ass } } - var outputFilePath = Path.Combine(targetDirectory, filename); + var outputFilePath = Path.Join(targetDirectory, filename); // Handle existing file based on specified behavior if (File.Exists(outputFilePath)) @@ -233,7 +235,7 @@ public static async Task MoveManifestResourceToDirectoryAsync(this Ass do { filename = $"{nameWithoutExtension}_{counter}{extension}"; - outputFilePath = Path.Combine(targetDirectory, filename); + outputFilePath = Path.Join(targetDirectory, filename); counter++; // Prevent infinite loop in case of extreme edge cases @@ -311,7 +313,7 @@ public static async Task MoveManifestResourceToDirectoryAsync(this Ass /// Behavior when the target file already exists. /// A object representing the extracted file. /// Thrown when required parameters are null. - /// Thrown when manifestResourceName is empty or whitespace. + /// Thrown when manifestResourceName is empty or whitespace, or when filename is not a plain file name (it has a directory part). /// Thrown when the cache directory cannot be created or accessed. /// Thrown when the manifest resource cannot be found. /// Thrown when file operations fail or when fileAlreadyExistsBehavior is Fail and file exists. @@ -330,7 +332,7 @@ public static FileInfo MoveManifestResourceToCache(this Assembly assembly, strin /// A token to cancel the operation. /// A representing the asynchronous operation that returns a object for the extracted file. /// Thrown when required parameters are null. - /// Thrown when manifestResourceName is empty or whitespace. + /// Thrown when manifestResourceName is empty or whitespace, or when filename is not a plain file name (it has a directory part). /// Thrown when the cache directory cannot be created or accessed. /// Thrown when the manifest resource cannot be found. /// Thrown when file operations fail or when fileAlreadyExistsBehavior is Fail and file exists. @@ -339,4 +341,16 @@ public static async Task MoveManifestResourceToCacheAsync(this Assembl { return await MoveManifestResourceToDirectoryAsync(assembly, manifestResourceName, CacheDirectory, filename, fileAlreadyExistsBehavior, cancellationToken).ConfigureAwait(false); } + + /// + /// Rejects names that would resolve outside the target directory: a rooted path (which + /// would let replace the directory) or one with a directory part such as ... + /// + private static void ThrowIfNotPlainFileName(string filename) + { + if (string.IsNullOrWhiteSpace(filename) || Path.GetFileName(filename) != filename) + { + throw new ArgumentException($"Filename '{filename}' must be a plain file name without any directory part.", nameof(filename)); + } + } } diff --git a/Plugin.BaseTypeExtensions/NumericRangeTools.cs b/Plugin.BaseTypeExtensions/NumericRangeTools.cs index 6a3b305..b87a999 100644 --- a/Plugin.BaseTypeExtensions/NumericRangeTools.cs +++ b/Plugin.BaseTypeExtensions/NumericRangeTools.cs @@ -59,7 +59,7 @@ public static IEnumerable GetRange(T start, T end, T step) where T : INumb /// public static IEnumerable GetRange(double start, double end, double step) { - if (step is 0 or double.NaN || double.IsInfinity(step)) + if (!double.IsFinite(step) || Math.Abs(step) < double.Epsilon) { return Array.Empty(); } @@ -71,11 +71,6 @@ IEnumerable Iterate() var isAscending = end >= start; var increment = Math.Abs(step); - if (increment == 0) - { - yield break; - } - if (!isAscending) { increment = -increment; @@ -103,7 +98,7 @@ IEnumerable Iterate() /// public static IEnumerable GetRange(float start, float end, float step) { - if (step is 0 or float.NaN || float.IsInfinity(step)) + if (!float.IsFinite(step) || MathF.Abs(step) < float.Epsilon) { return Array.Empty(); } @@ -115,11 +110,6 @@ IEnumerable Iterate() var isAscending = end >= start; var increment = MathF.Abs(step); - if (increment == 0) - { - yield break; - } - if (!isAscending) { increment = -increment; diff --git a/Plugin.BaseTypeExtensions/SemaphoreSlimExtensions.cs b/Plugin.BaseTypeExtensions/SemaphoreSlimExtensions.cs index f229533..b810893 100644 --- a/Plugin.BaseTypeExtensions/SemaphoreSlimExtensions.cs +++ b/Plugin.BaseTypeExtensions/SemaphoreSlimExtensions.cs @@ -25,7 +25,7 @@ public static class SemaphoreSlimExtensions public static async Task WaitBetterAsync(this SemaphoreSlim semaphore, TimeSpan? timeout, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(semaphore); - if (timeout.HasValue == false || timeout.Value <= TimeSpan.Zero) + if (!timeout.HasValue || timeout.Value <= TimeSpan.Zero) { await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false); return true; @@ -63,7 +63,7 @@ public static async Task WaitBetterAsync(this SemaphoreSlim semaphore, Tim public static async Task WaitBetterAsync(this SemaphoreSlim semaphore, int? millisecondsTimeout, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(semaphore); - if (millisecondsTimeout.HasValue == false || millisecondsTimeout.Value <= 0) + if (!millisecondsTimeout.HasValue || millisecondsTimeout.Value <= 0) { await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false); return true; diff --git a/Plugin.BaseTypeExtensions/StringExtensions.cs b/Plugin.BaseTypeExtensions/StringExtensions.cs index a539fa9..1565023 100644 --- a/Plugin.BaseTypeExtensions/StringExtensions.cs +++ b/Plugin.BaseTypeExtensions/StringExtensions.cs @@ -38,16 +38,15 @@ public static string RemoveSpecialCharacters(this string? input) } var result = new StringBuilder(input.Length); - foreach (var c in input) + foreach (var c in input.Where(IsKeptByRemoveSpecialCharacters)) { - if (char.IsLetterOrDigit(c) || char.IsWhiteSpace(c) || c == '-') - { - result.Append(c); - } + result.Append(c); } return result.ToString(); } + private static bool IsKeptByRemoveSpecialCharacters(char c) => char.IsLetterOrDigit(c) || char.IsWhiteSpace(c) || c == '-'; + #region String Validation & Checks /// diff --git a/Plugin.BaseTypeExtensions/TaskExtensions.cs b/Plugin.BaseTypeExtensions/TaskExtensions.cs index fde1f80..2616301 100644 --- a/Plugin.BaseTypeExtensions/TaskExtensions.cs +++ b/Plugin.BaseTypeExtensions/TaskExtensions.cs @@ -28,7 +28,7 @@ public static class TaskExtensions public static Task WaitBetterAsync(this Task task, TimeSpan? timeout, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(task); - if (timeout.HasValue == false || timeout.Value <= TimeSpan.Zero) + if (!timeout.HasValue || timeout.Value <= TimeSpan.Zero) { return task; } @@ -66,7 +66,7 @@ public static Task WaitBetterAsync(this Task task, TimeSpan? timeout, C public static Task WaitBetterAsync(this Task task, TimeSpan? timeout, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(task); - if (timeout.HasValue == false || timeout.Value <= TimeSpan.Zero) + if (!timeout.HasValue || timeout.Value <= TimeSpan.Zero) { return task; } diff --git a/Plugin.BaseTypeExtensions/UriExtensions.cs b/Plugin.BaseTypeExtensions/UriExtensions.cs index ed6073d..4f4a484 100644 --- a/Plugin.BaseTypeExtensions/UriExtensions.cs +++ b/Plugin.BaseTypeExtensions/UriExtensions.cs @@ -145,12 +145,9 @@ public static Dictionary GetQueryParameters(this Uri uri) var result = new Dictionary(StringComparer.OrdinalIgnoreCase); var query = HttpUtility.ParseQueryString(uri.Query); - foreach (var key in query.AllKeys) + foreach (var key in query.AllKeys.OfType()) { - if (key != null) - { - result[key] = query[key] ?? string.Empty; - } + result[key] = query[key] ?? string.Empty; } return result;