From cf6f17c1719ac4d3b1f162366d1b66182d427174 Mon Sep 17 00:00:00 2001 From: Martijn van Dijk Date: Fri, 4 Aug 2023 13:41:55 +0200 Subject: [PATCH 1/2] Add polyfill for older .net versions and fixes --- Directory.Build.props | 30 +++- FileUploader/FileUpload.cs | 6 +- Minio.Examples/Cases/CustomRequestLogger.cs | 2 +- Minio.Examples/Cases/FGetObject.cs | 2 +- Minio.Examples/Cases/FPutObject.cs | 2 +- Minio.Examples/Cases/GetObjectQuery.cs | 2 +- Minio.Examples/Cases/GetObjectVersion.cs | 2 +- Minio.Examples/Cases/GetPartialObject.cs | 4 +- Minio.Examples/Cases/MyRequestLogger.cs | 12 +- Minio.Examples/Cases/PutObject.cs | 2 +- Minio.Examples/Cases/PutObjectWithTags.cs | 2 +- Minio.Examples/Cases/RetryPolicyObject.cs | 6 +- Minio.Examples/Cases/SelectObjectContent.cs | 14 +- Minio.Examples/Program.cs | 6 +- Minio.Functional.Tests/FunctionalTest.cs | 152 +++++++++--------- Minio.Functional.Tests/Program.cs | 2 +- .../RandomStreamGenerator.cs | 4 +- Minio.Tests/AuthenticatorTest.cs | 8 +- Minio.Tests/EndpointTest.cs | 2 +- Minio.Tests/NegativeTest.cs | 2 +- Minio.Tests/OperationsTest.cs | 6 +- Minio.Tests/RetryHandlerTest.cs | 6 +- Minio.Tests/ReuseTcpConnectionTest.cs | 10 +- Minio.Tests/TestHelper.cs | 2 +- Minio/ApiEndpoints/ObjectOperations.cs | 8 +- .../Args/ListenBucketNotificationsArgs.cs | 4 - Minio/DataModel/ObjectStat.cs | 2 +- Minio/DataModel/PostPolicy.cs | 5 +- .../DataModel/Select/SelectResponseStream.cs | 8 +- Minio/DataModel/Tags/Tagging.cs | 4 +- Minio/Helper/BuilderUtil.cs | 4 +- Minio/Helper/RequestUtil.cs | 9 +- Minio/Helper/S3utils.cs | 2 +- Minio/Helper/Utils.cs | 72 ++++----- Minio/Minio.csproj | 3 +- Minio/MinioClient.cs | 7 +- Minio/MinioClientExtensions.cs | 2 +- Minio/V4Authenticator.cs | 8 +- SimpleTest/Program.cs | 2 +- 39 files changed, 214 insertions(+), 212 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index dfafca1c2d..398ecf1575 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -28,6 +28,7 @@ latest Default true + true $(MSBuildProjectName.Contains('Test')) @@ -59,28 +60,43 @@ - - \ No newline at end of file diff --git a/FileUploader/FileUpload.cs b/FileUploader/FileUpload.cs index 65347ca532..14c7c018cf 100644 --- a/FileUploader/FileUpload.cs +++ b/FileUploader/FileUpload.cs @@ -58,7 +58,7 @@ private static async Task Main(string[] args) Console.WriteLine(ex.Message); } - if (IsWindows()) Console.ReadLine(); + if (IsWindows()) _ = Console.ReadLine(); } /// @@ -96,7 +96,7 @@ private static async Task Run(IMinioClient minio) .WithObject(objectName) .WithFileName(filePath) .WithContentType(contentType); - await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); Console.WriteLine($"\nSuccessfully uploaded {objectName}\n"); } catch (Exception e) @@ -106,6 +106,6 @@ private static async Task Run(IMinioClient minio) // Added for Windows folks. Without it, the window, tests // run in, dissappears as soon as the test code completes. - if (IsWindows()) Console.ReadLine(); + if (IsWindows()) _ = Console.ReadLine(); } } diff --git a/Minio.Examples/Cases/CustomRequestLogger.cs b/Minio.Examples/Cases/CustomRequestLogger.cs index 5e111e68ad..51b2fb1591 100644 --- a/Minio.Examples/Cases/CustomRequestLogger.cs +++ b/Minio.Examples/Cases/CustomRequestLogger.cs @@ -27,7 +27,7 @@ public static async Task Run(IMinioClient minio) { Console.WriteLine("Running example for: set custom request logger"); minio.SetTraceOn(new MyRequestLogger()); - await minio.ListBucketsAsync().ConfigureAwait(false); + _ = await minio.ListBucketsAsync().ConfigureAwait(false); minio.SetTraceOff(); Console.WriteLine(); } diff --git a/Minio.Examples/Cases/FGetObject.cs b/Minio.Examples/Cases/FGetObject.cs index 085b418da0..a9d20d0040 100644 --- a/Minio.Examples/Cases/FGetObject.cs +++ b/Minio.Examples/Cases/FGetObject.cs @@ -37,7 +37,7 @@ public static async Task Run(IMinioClient minio, .WithObject(objectName) .WithFile(fileName) .WithServerSideEncryption(sse); - await minio.GetObjectAsync(args).ConfigureAwait(false); + _ = await minio.GetObjectAsync(args).ConfigureAwait(false); Console.WriteLine($"Downloaded the file {fileName} from bucket {bucketName}"); Console.WriteLine(); } diff --git a/Minio.Examples/Cases/FPutObject.cs b/Minio.Examples/Cases/FPutObject.cs index e2fa913fe0..2a0ff1e44f 100644 --- a/Minio.Examples/Cases/FPutObject.cs +++ b/Minio.Examples/Cases/FPutObject.cs @@ -34,7 +34,7 @@ public static async Task Run(IMinioClient minio, .WithObject(objectName) .WithContentType("application/octet-stream") .WithFileName(fileName); - await minio.PutObjectAsync(args).ConfigureAwait(false); + _ = await minio.PutObjectAsync(args).ConfigureAwait(false); Console.WriteLine($"Uploaded object {objectName} to bucket {bucketName}"); Console.WriteLine(); diff --git a/Minio.Examples/Cases/GetObjectQuery.cs b/Minio.Examples/Cases/GetObjectQuery.cs index 6de157c055..34cdd78e64 100644 --- a/Minio.Examples/Cases/GetObjectQuery.cs +++ b/Minio.Examples/Cases/GetObjectQuery.cs @@ -40,7 +40,7 @@ public static async Task Run(IMinioClient minio, .WithFile(fileName) .WithMatchETag(matchEtag) .WithModifiedSince(modifiedSince); - await minio.GetObjectAsync(args).ConfigureAwait(false); + _ = await minio.GetObjectAsync(args).ConfigureAwait(false); Console.WriteLine( $"Downloaded the file {fileName} for object {objectName} with given query parameters in bucket {bucketName}"); Console.WriteLine(); diff --git a/Minio.Examples/Cases/GetObjectVersion.cs b/Minio.Examples/Cases/GetObjectVersion.cs index 2f0e234d52..b3ef0a77c3 100644 --- a/Minio.Examples/Cases/GetObjectVersion.cs +++ b/Minio.Examples/Cases/GetObjectVersion.cs @@ -41,7 +41,7 @@ public static async Task Run(IMinioClient minio, .WithObject(objectName) .WithVersionId(versionId) .WithFile(fileName); - await minio.GetObjectAsync(args).ConfigureAwait(false); + _ = await minio.GetObjectAsync(args).ConfigureAwait(false); Console.WriteLine( $"Downloaded the file {fileName} for object {objectName} with version {versionId} in bucket {bucketName}"); Console.WriteLine(); diff --git a/Minio.Examples/Cases/GetPartialObject.cs b/Minio.Examples/Cases/GetPartialObject.cs index ed4463a649..a509b107d7 100644 --- a/Minio.Examples/Cases/GetPartialObject.cs +++ b/Minio.Examples/Cases/GetPartialObject.cs @@ -35,7 +35,7 @@ public static async Task Run(IMinioClient minio, var statObjectArgs = new StatObjectArgs() .WithBucket(bucketName) .WithObject(objectName); - await minio.StatObjectAsync(statObjectArgs).ConfigureAwait(false); + _ = await minio.StatObjectAsync(statObjectArgs).ConfigureAwait(false); // Get object content starting at byte position 1024 and length of 4096 var getObjectArgs = new GetObjectArgs() @@ -55,7 +55,7 @@ public static async Task Run(IMinioClient minio, $"Successfully downloaded object with requested offset and length {writtenInfo.Length} into file"); stream.Dispose(); }); - await minio.GetObjectAsync(getObjectArgs).ConfigureAwait(false); + _ = await minio.GetObjectAsync(getObjectArgs).ConfigureAwait(false); Console.WriteLine(); } catch (Exception e) diff --git a/Minio.Examples/Cases/MyRequestLogger.cs b/Minio.Examples/Cases/MyRequestLogger.cs index ef10e9dafa..55c479afb1 100644 --- a/Minio.Examples/Cases/MyRequestLogger.cs +++ b/Minio.Examples/Cases/MyRequestLogger.cs @@ -25,13 +25,13 @@ public void LogRequest(RequestToLog requestToLog, ResponseToLog responseToLog, d { var sb = new StringBuilder(); - sb.AppendLine("My logger says:"); - sb.Append("statusCode: "); - sb.AppendLine(responseToLog.StatusCode.ToString()); - sb.AppendLine(); + _ = sb.AppendLine("My logger says:"); + _ = sb.Append("statusCode: "); + _ = sb.AppendLine(responseToLog.StatusCode.ToString()); + _ = sb.AppendLine(); - sb.AppendLine("Response: "); - sb.Append(responseToLog.Content); + _ = sb.AppendLine("Response: "); + _ = sb.Append(responseToLog.Content); Console.WriteLine(sb.ToString()); } diff --git a/Minio.Examples/Cases/PutObject.cs b/Minio.Examples/Cases/PutObject.cs index ee958972d6..4e54b798df 100644 --- a/Minio.Examples/Cases/PutObject.cs +++ b/Minio.Examples/Cases/PutObject.cs @@ -51,7 +51,7 @@ public static async Task Run(IMinioClient minio, .WithHeaders(metaData) .WithProgress(progress) .WithServerSideEncryption(sse); - await minio.PutObjectAsync(args).ConfigureAwait(false); + _ = await minio.PutObjectAsync(args).ConfigureAwait(false); Console.WriteLine($"Uploaded object {objectName} to bucket {bucketName}"); Console.WriteLine(); diff --git a/Minio.Examples/Cases/PutObjectWithTags.cs b/Minio.Examples/Cases/PutObjectWithTags.cs index 923bcddc95..73591717a5 100644 --- a/Minio.Examples/Cases/PutObjectWithTags.cs +++ b/Minio.Examples/Cases/PutObjectWithTags.cs @@ -42,7 +42,7 @@ public static async Task Run(IMinioClient minio, .WithContentType("application/octet-stream") .WithFileName(fileName) .WithTagging(Tagging.GetObjectTags(tags)); - await minio.PutObjectAsync(args).ConfigureAwait(false); + _ = await minio.PutObjectAsync(args).ConfigureAwait(false); Console.WriteLine($"Uploaded object {objectName} to bucket {bucketName}"); Console.WriteLine(); diff --git a/Minio.Examples/Cases/RetryPolicyObject.cs b/Minio.Examples/Cases/RetryPolicyObject.cs index 47e8ef1c2a..62519ea9dc 100644 --- a/Minio.Examples/Cases/RetryPolicyObject.cs +++ b/Minio.Examples/Cases/RetryPolicyObject.cs @@ -38,7 +38,7 @@ public static async Task Run(MinioClient minio, 2, (r, i) => Console.WriteLine($"On retry #{i}. Result: {r.Exception?.Message}")); - minio.WithRetryPolicy(customPolicy); + _ = minio.WithRetryPolicy(customPolicy); Console.WriteLine("Running example for API: RetryPolicyObject"); @@ -48,7 +48,7 @@ public static async Task Run(MinioClient minio, .WithBucket("bad-bucket") .WithObject("bad-file") .WithCallbackStream(s => { }); - await minio.GetObjectAsync(getObjectArgs).ConfigureAwait(false); + _ = await minio.GetObjectAsync(getObjectArgs).ConfigureAwait(false); } catch (BucketNotFoundException ex) { @@ -63,7 +63,7 @@ public static async Task Run(MinioClient minio, } finally { - minio.WithRetryPolicy(null); + _ = minio.WithRetryPolicy(null); } } } diff --git a/Minio.Examples/Cases/SelectObjectContent.cs b/Minio.Examples/Cases/SelectObjectContent.cs index eeaed4e31f..33d6c61447 100644 --- a/Minio.Examples/Cases/SelectObjectContent.cs +++ b/Minio.Examples/Cases/SelectObjectContent.cs @@ -37,12 +37,12 @@ public static async Task Run(IMinioClient minio, Console.WriteLine("Running example for API: SelectObjectContentAsync"); var csvString = new StringBuilder(); - csvString.AppendLine("Employee,Manager,Group"); - csvString.AppendLine("Employee4,Employee2,500"); - csvString.AppendLine("Employee3,Employee1,500"); - csvString.AppendLine("Employee1,,1000"); - csvString.AppendLine("Employee5,Employee1,500"); - csvString.AppendLine("Employee2,Employee1,800"); + _ = csvString.AppendLine("Employee,Manager,Group"); + _ = csvString.AppendLine("Employee4,Employee2,500"); + _ = csvString.AppendLine("Employee3,Employee1,500"); + _ = csvString.AppendLine("Employee1,,1000"); + _ = csvString.AppendLine("Employee5,Employee1,500"); + _ = csvString.AppendLine("Employee2,Employee1,800"); ReadOnlyMemory csvBytes = Encoding.UTF8.GetBytes(csvString.ToString()); using var stream = csvBytes.AsStream(); var putObjectArgs = new PutObjectArgs() @@ -50,7 +50,7 @@ public static async Task Run(IMinioClient minio, .WithObject(newObjectName) .WithStreamData(stream) .WithObjectSize(stream.Length); - await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); var queryType = QueryExpressionType.SQL; var queryExpr = "select count(*) from s3object"; diff --git a/Minio.Examples/Program.cs b/Minio.Examples/Program.cs index 2c7fb2818d..6b7cff341d 100644 --- a/Minio.Examples/Program.cs +++ b/Minio.Examples/Program.cs @@ -49,7 +49,7 @@ public static string GetRandomName() { var characters = "0123456789abcdefghijklmnopqrstuvwxyz"; var result = new StringBuilder(5); - for (var i = 0; i < 5; i++) result.Append(characters[rnd.Next(characters.Length)]); + for (var i = 0; i < 5; i++) _ = result.Append(characters[rnd.Next(characters.Length)]); return "minio-dotnet-example-" + result; } @@ -69,7 +69,7 @@ public static async Task Main(string[] args) { port = int.Parse(endPoint.Substring(posColon + 1, endPoint.Length - posColon - 1), NumberStyles.Integer, CultureInfo.InvariantCulture); - endPoint = endPoint.Substring(0, posColon); + endPoint = endPoint[..posColon]; } accessKey = Environment.GetEnvironmentVariable("ACCESS_KEY"); @@ -280,6 +280,6 @@ await SetBucketReplication.Run(minioClient, bucketName, destBucketName, replicat File.Delete(smallFileName); File.Delete(bigFileName); - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) Console.ReadLine(); + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) _ = Console.ReadLine(); } } diff --git a/Minio.Functional.Tests/FunctionalTest.cs b/Minio.Functional.Tests/FunctionalTest.cs index 3b98607f9c..519d3dd709 100644 --- a/Minio.Functional.Tests/FunctionalTest.cs +++ b/Minio.Functional.Tests/FunctionalTest.cs @@ -17,6 +17,7 @@ using System.Collections.Concurrent; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Net; using System.Runtime.InteropServices; @@ -44,6 +45,7 @@ namespace Minio.Functional.Tests; +[SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Keep private const lowercase")] public static class FunctionalTest { private const int KB = 1024; @@ -231,7 +233,7 @@ private static string Bash(string cmd) } }; - process.Start(); + _ = process.Start(); var result = process.StandardOutput.ReadLine(); process.WaitForExit(); @@ -278,7 +280,7 @@ public static string GetRandomName(int length = 5) if (length > 50) length = 50; var result = new StringBuilder(length); - for (var i = 0; i < length; i++) result.Append(characters[rnd.Next(characters.Length)]); + for (var i = 0; i < length; i++) _ = result.Append(characters[rnd.Next(characters.Length)]); return "minio-dotnet-example-" + result; } @@ -314,7 +316,7 @@ public static string GetFilePath(string fileName) return $"{path}/{fileName}"; } - internal static async Task RunCoreTests(MinioClient minioClient) + internal static Task RunCoreTests(MinioClient minioClient) { ConcurrentBag coreTestsTasks = new() { @@ -344,7 +346,7 @@ internal static async Task RunCoreTests(MinioClient minioClient) GetBucketPolicy_Test1(minioClient) }; - await coreTestsTasks.ForEachAsync().ConfigureAwait(false); + return coreTestsTasks.ForEachAsync(); } internal static async Task BucketExists_Test(MinioClient minio) @@ -625,7 +627,7 @@ internal static async Task TearDown(MinioClient minio, string bucketName) else objectNames.Add(item.Key); }, - ex => exceptionList.Add(ex), + exceptionList.Add, () => { }); await Task.Delay(4500).ConfigureAwait(false); @@ -1069,7 +1071,7 @@ internal static async Task StatObject_Test1(MinioClient minio) try { await Setup_Test(minio, bucketName).ConfigureAwait(false); - await PutObject_Tester(minio, bucketName, objectName, null, null, 0, null, + _ = await PutObject_Tester(minio, bucketName, objectName, null, null, 0, null, rsg.GenerateStreamFromSeed(1 * KB)).ConfigureAwait(false); new MintLogger(nameof(StatObject_Test1), statObjectSignature, "Tests whether StatObject passes", TestStatus.PASS, DateTime.Now - startTime, args: args).Log(); @@ -1104,7 +1106,7 @@ internal static async Task FPutObject_Test1(MinioClient minio) .WithBucket(bucketName) .WithObject(objectName) .WithFileName(fileName); - await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); new MintLogger("FPutObject_Test1", putObjectSignature, "Tests whether FPutObject for multipart upload passes", TestStatus.PASS, DateTime.Now - startTime, args: args).Log(); @@ -1141,7 +1143,7 @@ internal static async Task FPutObject_Test2(MinioClient minio) .WithBucket(bucketName) .WithObject(objectName) .WithFileName(fileName); - await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); new MintLogger("FPutObject_Test2", putObjectSignature, "Tests whether FPutObject for small upload passes", TestStatus.PASS, DateTime.Now - startTime, args: args).Log(); } @@ -1181,7 +1183,7 @@ internal static async Task RemoveObject_Test1(MinioClient minio) .WithStreamData(filestream) .WithObjectSize(filestream.Length); - await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); } new MintLogger("RemoveObject_Test1", removeObjectSignature1, @@ -1375,7 +1377,7 @@ internal static async Task PresignedPostPolicy_Test1(MinioClient minio) foreach (var pair in policyTuple.Item2) curlCommand += $" -F {pair.Key}=\"{pair.Value}\""; curlCommand += $" -F file=\"@{fileName}\" {uri}"; - Bash(curlCommand); + _ = Bash(curlCommand); // Validate var statObjectArgs = new StatObjectArgs() @@ -1433,7 +1435,7 @@ internal static async Task RemoveIncompleteUpload_Test(MinioClient minio) .WithStreamData(filestream) .WithObjectSize(filestream.Length) .WithContentType(contentType); - await minio.PutObjectAsync(putObjectArgs, cts.Token).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs, cts.Token).ConfigureAwait(false); } catch (OperationCanceledException) { @@ -1725,7 +1727,7 @@ internal static async Task LegalHoldStatusAsync_Test1(MinioClient minio) .WithStreamData(filestream) .WithObjectSize(filestream.Length) .WithContentType(null); - await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); } var legalHoldArgs = new SetObjectLegalHoldArgs() @@ -1949,7 +1951,7 @@ internal static async Task ObjectTagsAsync_Test1(MinioClient minio) .WithStreamData(filestream) .WithObjectSize(filestream.Length) .WithContentType(null); - await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); } var tagsArgs = new SetObjectTagsArgs() @@ -2095,7 +2097,7 @@ internal static async Task ObjectVersioningAsync_Test1(MinioClient minio) .WithStreamData(filestream) .WithObjectSize(filestream.Length) .WithContentType(null); - await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); } using (var filestream = rsg.GenerateStreamFromSeed(size)) @@ -2106,7 +2108,7 @@ internal static async Task ObjectVersioningAsync_Test1(MinioClient minio) .WithStreamData(filestream) .WithObjectSize(filestream.Length) .WithContentType(null); - await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); } // In each run, there will be 2 more versions of the object @@ -2196,7 +2198,7 @@ internal static async Task ObjectLockConfigurationAsync_Test1(MinioClient minio) .WithObjectSize(filestream.Length) .WithRetentionConfiguration(objectRetention) .WithContentType(null); - await minio.PutObjectAsync(putObjectArgs1).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs1).ConfigureAwait(false); } using (var filestream = rsg.GenerateStreamFromSeed(1 * KB)) @@ -2208,7 +2210,7 @@ internal static async Task ObjectLockConfigurationAsync_Test1(MinioClient minio) .WithObjectSize(filestream.Length) .WithRetentionConfiguration(objectRetention) .WithContentType(null); - await minio.PutObjectAsync(putObjectArgs2).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs2).ConfigureAwait(false); } } } @@ -2375,7 +2377,7 @@ internal static async Task ObjectRetentionAsync_Test1(MinioClient minio) .WithStreamData(filestream) .WithObjectSize(filestream.Length) .WithContentType(null); - await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); } var untilDate = DateTime.Now.AddDays(plusDays); @@ -2504,7 +2506,7 @@ internal static MemoryStream CreateZipFile(string prefix, int nFiles) zipStream.SetLevel(3); //0-9, 9 being the highest level of compression - Directory.CreateDirectory(prefix); + _ = Directory.CreateDirectory(prefix); for (var i = 1; i <= nFiles; i++) { // Make a single 1Mb file @@ -2525,7 +2527,7 @@ internal static MemoryStream CreateZipFile(string prefix, int nFiles) zipStream.Close(); outputMemStream.Position = 0; - outputMemStream.Seek(0, SeekOrigin.Begin); + _ = outputMemStream.Seek(0, SeekOrigin.Begin); return outputMemStream; } @@ -2551,7 +2553,7 @@ internal static async Task GetObjectS3Zip_Test1(MinioClient minio) .WithObject(objectName) .WithStreamData(memStream) .WithObjectSize(memStream.Length); - await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); var extractHeader = new Dictionary (StringComparer.Ordinal) { { "x-minio-extract", "true" } }; @@ -2662,12 +2664,12 @@ internal static async Task ListenBucketNotificationsAsync_Test1(MinioClient mini .WithEvents(eventsList); var events = minio.ListenBucketNotificationsAsync(listenArgs); var subscription = events.Subscribe( - ev => received.Add(ev), + received.Add, ex => { }, () => { } ); - await PutObject_Tester(minio, bucketName, objectName, null, contentType, + _ = await PutObject_Tester(minio, bucketName, objectName, null, contentType, 0, null, rsg.GenerateStreamFromSeed(1 * KB)).ConfigureAwait(false); // wait for notifications @@ -2692,8 +2694,8 @@ await PutObject_Tester(minio, bucketName, objectName, null, contentType, // data. This is required to match and convert json data // "receivedJson" into class "ErrorResponse" var len = "{'Error':".Length; - var trimmedFront = receivedJson.Substring(len); - var trimmedFull = trimmedFront.Substring(0, trimmedFront.Length - 1); + var trimmedFront = receivedJson[len..]; + var trimmedFull = trimmedFront[..^1]; var err = JsonSerializer.Deserialize(trimmedFull); @@ -2835,7 +2837,7 @@ void Notify(MinioNotificationRaw data) .WithStreamData(stream) .WithObjectSize(stream.Length); - await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); // Waits until the Put event is detected // Times out if the event is not caught in 3 seconds @@ -2923,7 +2925,7 @@ internal static async Task ListenBucketNotificationsAsync_Test3(MinioClient mini var sleepTime = 1000; // Milliseconds await Task.Delay(sleepTime).ConfigureAwait(false); - await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); var stTime = DateTime.UtcNow; var waitTime = 25; // Milliseconds @@ -3124,7 +3126,7 @@ internal static async Task MakeBucket_Test5(MinioClient minio) try { - await Assert.ThrowsExceptionAsync(() => + _ = await Assert.ThrowsExceptionAsync(() => minio.MakeBucketAsync(new MakeBucketArgs() .WithBucket(bucketName))).ConfigureAwait(false); new MintLogger(nameof(MakeBucket_Test5), makeBucketSignature, @@ -3234,7 +3236,7 @@ internal static async Task PutObject_Test2(MinioClient minio) try { await Setup_Test(minio, bucketName).ConfigureAwait(false); - await PutObject_Tester(minio, bucketName, objectName, null, contentType, 0, null, + _ = await PutObject_Tester(minio, bucketName, objectName, null, contentType, 0, null, rsg.GenerateStreamFromSeed(6 * MB)).ConfigureAwait(false); new MintLogger(nameof(PutObject_Test2), putObjectSignature, "Tests whether multipart PutObject passes", TestStatus.PASS, DateTime.Now - startTime, args: args).Log(); @@ -3269,7 +3271,7 @@ internal static async Task PutObject_Test3(MinioClient minio) try { await Setup_Test(minio, bucketName).ConfigureAwait(false); - await PutObject_Tester(minio, bucketName, objectName, null, contentType, 0, null, + _ = await PutObject_Tester(minio, bucketName, objectName, null, contentType, 0, null, rsg.GenerateStreamFromSeed(1 * MB)).ConfigureAwait(false); new MintLogger(nameof(PutObject_Test3), putObjectSignature, "Tests whether PutObject with custom content-type passes", TestStatus.PASS, DateTime.Now - startTime, @@ -3351,7 +3353,8 @@ internal static async Task PutObject_Test5(MinioClient minio) try { await Setup_Test(minio, bucketName).ConfigureAwait(false); - await PutObject_Tester(minio, bucketName, objectName, null, null, 0, null, rsg.GenerateStreamFromSeed(1)) + _ = await PutObject_Tester(minio, bucketName, objectName, null, null, 0, null, + rsg.GenerateStreamFromSeed(1)) .ConfigureAwait(false); new MintLogger(nameof(PutObject_Test5), putObjectSignature, "Tests whether PutObject with no content-type passes for small object", TestStatus.PASS, @@ -3400,7 +3403,7 @@ internal static async Task PutObject_Test7(MinioClient minio) .WithStreamData(filestream) .WithObjectSize(size) .WithContentType(contentType); - await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); var rmArgs = new RemoveObjectArgs() .WithBucket(bucketName) .WithObject(objectName); @@ -3454,7 +3457,7 @@ internal static async Task PutObject_Test8(MinioClient minio) .WithStreamData(filestream) .WithObjectSize(size) .WithContentType(contentType); - await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); var rmArgs = new RemoveObjectArgs() .WithBucket(bucketName) .WithObject(objectName); @@ -3502,7 +3505,7 @@ internal static async Task PutObject_Test9(MinioClient minio) try { await Setup_Test(minio, bucketName).ConfigureAwait(false); - await PutObject_Tester(minio, bucketName, objectName, null, contentType, 0, null, + _ = await PutObject_Tester(minio, bucketName, objectName, null, contentType, 0, null, rsg.GenerateStreamFromSeed(1 * MB), progress).ConfigureAwait(false); Assert.IsTrue(percentage == 100); Assert.IsTrue(totalBytesTransferred == 1 * MB); @@ -3554,7 +3557,7 @@ internal static async Task PutObject_Test10(MinioClient minio) try { await Setup_Test(minio, bucketName).ConfigureAwait(false); - await PutObject_Tester(minio, bucketName, objectName, null, contentType, 0, null, + _ = await PutObject_Tester(minio, bucketName, objectName, null, contentType, 0, null, rsg.GenerateStreamFromSeed(64 * MB), progress).ConfigureAwait(false); Assert.IsTrue(percentage == 100); Assert.IsTrue(totalBytesTransferred == 64 * MB); @@ -3610,7 +3613,7 @@ internal static async Task CopyObject_Test1(MinioClient minio) .WithStreamData(filestream) .WithObjectSize(filestream.Length); // .WithHeaders(null); - await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); } var copySourceObjectArgs = new CopySourceObjectArgs() @@ -3627,7 +3630,7 @@ internal static async Task CopyObject_Test1(MinioClient minio) .WithBucket(destBucketName) .WithObject(destObjectName) .WithFile(outFileName); - await minio.GetObjectAsync(getObjectArgs).ConfigureAwait(false); + _ = await minio.GetObjectAsync(getObjectArgs).ConfigureAwait(false); File.Delete(outFileName); var rmArgs1 = new RemoveObjectArgs() .WithBucket(bucketName) @@ -3681,7 +3684,7 @@ internal static async Task CopyObject_Test2(MinioClient minio) .WithStreamData(filestream) .WithObjectSize(filestream.Length) .WithHeaders(null); - await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); } catch (Exception ex) { @@ -3769,7 +3772,7 @@ internal static async Task CopyObject_Test3(MinioClient minio) .WithObject(objectName) .WithStreamData(filestream) .WithObjectSize(filestream.Length); - await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); } var statObjectArgs = new StatObjectArgs() @@ -3793,7 +3796,7 @@ internal static async Task CopyObject_Test3(MinioClient minio) .WithBucket(destBucketName) .WithObject(destObjectName) .WithFile(outFileName); - await minio.GetObjectAsync(getObjectArgs).ConfigureAwait(false); + _ = await minio.GetObjectAsync(getObjectArgs).ConfigureAwait(false); statObjectArgs = new StatObjectArgs() .WithBucket(destBucketName) .WithObject(destObjectName); @@ -3823,7 +3826,6 @@ internal static async Task CopyObject_Test4(MinioClient minio) var bucketName = GetRandomName(15); var objectName = GetRandomObjectName(10); var destBucketName = GetRandomName(15); - var destObjectName = GetRandomName(10); var outFileName = "outFileName-CopyObject_Test4"; var args = new Dictionary (StringComparer.Ordinal) @@ -3847,7 +3849,7 @@ internal static async Task CopyObject_Test4(MinioClient minio) .WithObject(objectName) .WithStreamData(filestream) .WithObjectSize(filestream.Length); - await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); } var conditions = new CopyConditions(); @@ -3866,7 +3868,7 @@ internal static async Task CopyObject_Test4(MinioClient minio) .WithBucket(bucketName) .WithObject(objectName) .WithFile(outFileName); - await minio.GetObjectAsync(getObjectArgs).ConfigureAwait(false); + _ = await minio.GetObjectAsync(getObjectArgs).ConfigureAwait(false); var statObjectArgs = new StatObjectArgs() .WithBucket(destBucketName) .WithObject(objectName); @@ -3921,7 +3923,7 @@ internal static async Task CopyObject_Test5(MinioClient minio) .WithObject(objectName) .WithStreamData(filestream) .WithObjectSize(filestream.Length); - await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); } var conditions = new CopyConditions(); @@ -3999,7 +4001,7 @@ internal static async Task CopyObject_Test6(MinioClient minio) .WithObject(objectName) .WithStreamData(filestream) .WithObjectSize(filestream.Length); - await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); } var statObjectArgs = new StatObjectArgs() @@ -4024,7 +4026,7 @@ internal static async Task CopyObject_Test6(MinioClient minio) .WithBucket(destBucketName) .WithObject(destObjectName) .WithFile(outFileName); - await minio.GetObjectAsync(getObjectArgs).ConfigureAwait(false); + _ = await minio.GetObjectAsync(getObjectArgs).ConfigureAwait(false); statObjectArgs = new StatObjectArgs() .WithBucket(destBucketName) .WithObject(destObjectName); @@ -4079,7 +4081,7 @@ internal static async Task CopyObject_Test7(MinioClient minio) .WithObject(objectName) .WithStreamData(filestream) .WithObjectSize(filestream.Length); - await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); } var statObjectArgs = new StatObjectArgs() @@ -4162,7 +4164,7 @@ internal static async Task CopyObject_Test8(MinioClient minio) { { "Orig", "orig-val with spaces" } }); - await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); } var statObjectArgs = new StatObjectArgs() @@ -4250,7 +4252,7 @@ internal static async Task CopyObject_Test9(MinioClient minio) .WithStreamData(filestream) .WithObjectSize(filestream.Length); - await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); var putTags = new Dictionary (StringComparer.Ordinal) { { "key1", "PutObjectTags" } }; var setObjectTagsArgs = new SetObjectTagsArgs() @@ -4346,7 +4348,7 @@ internal static async Task EncryptedCopyObject_Test1(MinioClient minio) .WithStreamData(filestream) .WithObjectSize(filestream.Length) .WithServerSideEncryption(ssec); - await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); } var copySourceObjectArgs = new CopySourceObjectArgs() @@ -4364,7 +4366,7 @@ internal static async Task EncryptedCopyObject_Test1(MinioClient minio) .WithObject(destObjectName) .WithServerSideEncryption(ssecDst) .WithFile(outFileName); - await minio.GetObjectAsync(getObjectArgs).ConfigureAwait(false); + _ = await minio.GetObjectAsync(getObjectArgs).ConfigureAwait(false); new MintLogger("EncryptedCopyObject_Test1", copyObjectSignature, "Tests whether encrypted CopyObject passes", TestStatus.PASS, DateTime.Now - startTime, args: args) .Log(); @@ -4428,7 +4430,7 @@ internal static async Task EncryptedCopyObject_Test2(MinioClient minio) .WithObjectSize(filestream.Length) .WithServerSideEncryption(ssec); - await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); } var copySourceObjectArgs = new CopySourceObjectArgs() @@ -4446,7 +4448,7 @@ internal static async Task EncryptedCopyObject_Test2(MinioClient minio) .WithBucket(destBucketName) .WithObject(destObjectName) .WithFile(outFileName); - await minio.GetObjectAsync(getObjectArgs).ConfigureAwait(false); + _ = await minio.GetObjectAsync(getObjectArgs).ConfigureAwait(false); new MintLogger("EncryptedCopyObject_Test2", copyObjectSignature, "Tests whether encrypted CopyObject passes", TestStatus.PASS, DateTime.Now - startTime, args: args) .Log(); @@ -4509,7 +4511,7 @@ internal static async Task EncryptedCopyObject_Test3(MinioClient minio) .WithStreamData(filestream) .WithObjectSize(filestream.Length) .WithServerSideEncryption(ssec); - await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); } var copySourceObjectArgs = new CopySourceObjectArgs() @@ -4526,7 +4528,7 @@ internal static async Task EncryptedCopyObject_Test3(MinioClient minio) .WithBucket(destBucketName) .WithObject(destObjectName) .WithFile(outFileName); - await minio.GetObjectAsync(getObjectArgs).ConfigureAwait(false); + _ = await minio.GetObjectAsync(getObjectArgs).ConfigureAwait(false); new MintLogger("EncryptedCopyObject_Test3", copyObjectSignature, "Tests whether encrypted CopyObject passes", TestStatus.PASS, DateTime.Now - startTime, args: args) .Log(); @@ -4580,7 +4582,7 @@ internal static async Task EncryptedCopyObject_Test4(MinioClient minio) .WithStreamData(filestream) .WithObjectSize(filestream.Length) .WithServerSideEncryption(sses3); - await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); } var copySourceObjectArgs = new CopySourceObjectArgs() @@ -4598,7 +4600,7 @@ internal static async Task EncryptedCopyObject_Test4(MinioClient minio) .WithBucket(destBucketName) .WithObject(destObjectName) .WithFile(outFileName); - await minio.GetObjectAsync(getObjectArgs).ConfigureAwait(false); + _ = await minio.GetObjectAsync(getObjectArgs).ConfigureAwait(false); new MintLogger("EncryptedCopyObject_Test4", copyObjectSignature, "Tests whether encrypted CopyObject passes", TestStatus.PASS, DateTime.Now - startTime, args: args) .Log(); @@ -4712,7 +4714,7 @@ internal static async Task GetObject_Test2(MinioClient minio) .WithStreamData(filestream) .WithObjectSize(filestream.Length); - await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); } catch (Exception ex) { @@ -4729,7 +4731,7 @@ internal static async Task GetObject_Test2(MinioClient minio) .WithObject(objectName) .WithFile(fileName); - await minio.GetObjectAsync(getObjectArgs).ConfigureAwait(false); + _ = await minio.GetObjectAsync(getObjectArgs).ConfigureAwait(false); Assert.IsTrue(File.Exists(fileName)); new MintLogger("GetObject_Test2", getObjectSignature, "Tests whether GetObject with a file name works", TestStatus.PASS, DateTime.Now - startTime, args: args).Log(); @@ -4922,14 +4924,14 @@ internal static async Task GetObject_AsyncCallback_Test1(MinioClient minio) .WithObjectSize(filestream.Length) .WithContentType(contentType); - await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); - var callbackAsync = async (Stream stream, CancellationToken cancellationToken) => + async Task callbackAsync(Stream stream, CancellationToken cancellationToken) { var dest = new FileStream(destFileName, FileMode.Create, FileAccess.Write); await stream.CopyToAsync(dest, cancellationToken).ConfigureAwait(false); await dest.DisposeAsync().ConfigureAwait(false); - }; + } var getObjectArgs = new GetObjectArgs() .WithBucket(bucketName) @@ -4937,7 +4939,7 @@ internal static async Task GetObject_AsyncCallback_Test1(MinioClient minio) .WithCallbackStream(async (stream, cancellationToken) => await callbackAsync(stream, cancellationToken).ConfigureAwait(false)); - await minio.GetObjectAsync(getObjectArgs).ConfigureAwait(false); + _ = await minio.GetObjectAsync(getObjectArgs).ConfigureAwait(false); var writtenInfo = new FileInfo(destFileName); file_read_size = writtenInfo.Length; Assert.AreEqual(size, file_read_size); @@ -4985,14 +4987,14 @@ internal static async Task FGetObject_Test1(MinioClient minio) .WithObject(objectName) .WithStreamData(filestream) .WithObjectSize(filestream.Length); - await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); } var getObjectArgs = new GetObjectArgs() .WithBucket(bucketName) .WithObject(objectName) .WithFile(outFileName); - await minio.GetObjectAsync(getObjectArgs).ConfigureAwait(false); + _ = await minio.GetObjectAsync(getObjectArgs).ConfigureAwait(false); new MintLogger("FGetObject_Test1", getObjectSignature, "Tests whether FGetObject passes for small upload", TestStatus.PASS, DateTime.Now - startTime, args: args).Log(); } @@ -5421,7 +5423,7 @@ internal static async Task PresignedGetObject_Test1(MinioClient minio) .WithStreamData(filestream) .WithObjectSize(filestream.Length); - await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); } var statObjectArgs = new StatObjectArgs() @@ -5483,7 +5485,7 @@ internal static async Task PresignedGetObject_Test2(MinioClient minio) .WithStreamData(filestream) .WithObjectSize(filestream.Length); - await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); } var statObjectArgs = new StatObjectArgs() @@ -5555,7 +5557,7 @@ internal static async Task PresignedGetObject_Test3(MinioClient minio) .WithStreamData(filestream) .WithObjectSize(filestream.Length); - await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); } var statObjectArgs = new StatObjectArgs() @@ -5697,7 +5699,7 @@ internal static async Task PresignedPutObject_Test2(MinioClient minio) .WithStreamData(filestream) .WithObjectSize(filestream.Length); - await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); } var statObjectArgs = new StatObjectArgs() @@ -5760,7 +5762,7 @@ internal static async Task ListIncompleteUpload_Test1(MinioClient minio) .WithStreamData(filestream) .WithObjectSize(filestream.Length) .WithContentType(contentType); - await minio.PutObjectAsync(putObjectArgs, cts.Token).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs, cts.Token).ConfigureAwait(false); } catch (OperationCanceledException) { @@ -5821,7 +5823,7 @@ internal static async Task ListIncompleteUpload_Test2(MinioClient minio) .WithStreamData(filestream) .WithObjectSize(filestream.Length) .WithContentType(contentType); - await minio.PutObjectAsync(putObjectArgs, cts.Token).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs, cts.Token).ConfigureAwait(false); } catch (OperationCanceledException) { @@ -5878,7 +5880,7 @@ internal static async Task ListIncompleteUpload_Test3(MinioClient minio) .WithStreamData(filestream) .WithObjectSize(filestream.Length) .WithContentType(contentType); - await minio.PutObjectAsync(putObjectArgs, cts.Token).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs, cts.Token).ConfigureAwait(false); } catch (OperationCanceledException) { @@ -5927,7 +5929,7 @@ internal static async Task SetBucketPolicy_Test1(MinioClient minio) var args = new Dictionary (StringComparer.Ordinal) { - { "bucketName", bucketName }, { "objectPrefix", objectName.Substring(5) }, { "policyType", "readonly" } + { "bucketName", bucketName }, { "objectPrefix", objectName[5..] }, { "policyType", "readonly" } }; try { @@ -5939,7 +5941,7 @@ internal static async Task SetBucketPolicy_Test1(MinioClient minio) .WithObject(objectName) .WithStreamData(filestream) .WithObjectSize(filestream.Length); - await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); } var policyJson = @@ -5993,7 +5995,7 @@ internal static async Task GetBucketPolicy_Test1(MinioClient minio) .WithObject(objectName) .WithStreamData(filestream) .WithObjectSize(filestream.Length); - await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + _ = await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false); } var setPolicyArgs = new SetPolicyArgs() diff --git a/Minio.Functional.Tests/Program.cs b/Minio.Functional.Tests/Program.cs index 567ca563d4..488ddcb5bb 100644 --- a/Minio.Functional.Tests/Program.cs +++ b/Minio.Functional.Tests/Program.cs @@ -42,7 +42,7 @@ public static async Task Main(string[] args) { port = int.Parse(endPoint.Substring(posColon + 1, endPoint.Length - posColon - 1), NumberStyles.Integer, CultureInfo.InvariantCulture); - endPoint = endPoint.Substring(0, posColon); + endPoint = endPoint[..posColon]; } accessKey = Environment.GetEnvironmentVariable("ACCESS_KEY"); diff --git a/Minio.Functional.Tests/RandomStreamGenerator.cs b/Minio.Functional.Tests/RandomStreamGenerator.cs index aa34b9813e..4e2f27bbae 100644 --- a/Minio.Functional.Tests/RandomStreamGenerator.cs +++ b/Minio.Functional.Tests/RandomStreamGenerator.cs @@ -40,8 +40,8 @@ public Stream GenerateStreamFromSeed(int size) Memory buffer = new byte[size]; - _seedBuffer.Slice(randomWindow, size - randomWindow).CopyTo(buffer.Slice(0, size - randomWindow)); - _seedBuffer.Slice(0, randomWindow).CopyTo(buffer.Slice(size - randomWindow, randomWindow)); + _seedBuffer[randomWindow..size].CopyTo(buffer[..(size - randomWindow)]); + _seedBuffer[..randomWindow].CopyTo(buffer.Slice(size - randomWindow, randomWindow)); return buffer.AsStream(); } diff --git a/Minio.Tests/AuthenticatorTest.cs b/Minio.Tests/AuthenticatorTest.cs index e790b09d6c..3e6e936419 100644 --- a/Minio.Tests/AuthenticatorTest.cs +++ b/Minio.Tests/AuthenticatorTest.cs @@ -34,7 +34,7 @@ public void TestAnonymousInsecureRequestHeaders() var authenticatorInsecure = new V4Authenticator(false, "a", "b"); Assert.IsFalse(authenticatorInsecure.IsAnonymous); - authenticatorInsecure.Authenticate(request); + _ = authenticatorInsecure.Authenticate(request); Assert.IsTrue(HasPayloadHeader(request, "x-amz-content-sha256")); } @@ -51,7 +51,7 @@ public void TestAnonymousSecureRequestHeaders() var authenticatorSecure = new V4Authenticator(true, "a", "b"); Assert.IsFalse(authenticatorSecure.IsAnonymous); - authenticatorSecure.Authenticate(request); + _ = authenticatorSecure.Authenticate(request); Assert.IsTrue(HasPayloadHeader(request, "x-amz-content-sha256")); } @@ -65,7 +65,7 @@ public void TestSecureRequestHeaders() var request = new HttpRequestMessageBuilder(HttpMethod.Put, "http://localhost:9000/bucketname/objectname"); request.AddJsonBody("[]"); - authenticator.Authenticate(request); + _ = authenticator.Authenticate(request); Assert.IsTrue(HasPayloadHeader(request, "x-amz-content-sha256")); var match = GetHeaderKV(request, "x-amz-content-sha256"); Assert.IsTrue(match?.Item2.Equals("UNSIGNED-PAYLOAD", StringComparison.Ordinal) == true); @@ -80,7 +80,7 @@ public void TestInsecureRequestHeaders() Assert.IsFalse(authenticator.IsAnonymous); var request = new HttpRequestMessageBuilder(HttpMethod.Put, "http://localhost:9000/bucketname/objectname"); request.AddJsonBody("[]"); - authenticator.Authenticate(request); + _ = authenticator.Authenticate(request); Assert.IsTrue(HasPayloadHeader(request, "x-amz-content-sha256")); Assert.IsFalse(HasPayloadHeader(request, "Content-Md5")); } diff --git a/Minio.Tests/EndpointTest.cs b/Minio.Tests/EndpointTest.cs index 5baf74f0fb..3844f50d27 100644 --- a/Minio.Tests/EndpointTest.cs +++ b/Minio.Tests/EndpointTest.cs @@ -26,7 +26,7 @@ public class EndpointTest [TestMethod] public void TestGetEndpointURL() { - RequestUtil.GetEndpointURL("s3.amazonaws.com", true); + _ = RequestUtil.GetEndpointURL("s3.amazonaws.com", true); object[] parameterValuesArray = { new object[] { "s3.amazonaws.com", true, "testbucket", null, false }, diff --git a/Minio.Tests/NegativeTest.cs b/Minio.Tests/NegativeTest.cs index cd47e3ae94..cd540fe22b 100644 --- a/Minio.Tests/NegativeTest.cs +++ b/Minio.Tests/NegativeTest.cs @@ -52,7 +52,7 @@ public async Task TestInvalidBucketNameError() .Build(); var args = new BucketExistsArgs() .WithBucket(badName); - await Assert + _ = await Assert .ThrowsExceptionAsync(async () => await minio.BucketExistsAsync(args).ConfigureAwait(false)).ConfigureAwait(false); } diff --git a/Minio.Tests/OperationsTest.cs b/Minio.Tests/OperationsTest.cs index 76e0c9b90e..cc825de50a 100644 --- a/Minio.Tests/OperationsTest.cs +++ b/Minio.Tests/OperationsTest.cs @@ -27,7 +27,7 @@ private async Task ObjectExistsAsync(IMinioClient client, string bucket, s .WithBucket(bucket) .WithObject(objectName) .WithCallbackStream(stream => { }); - await client.GetObjectAsync(getObjectArgs).ConfigureAwait(false); + _ = await client.GetObjectAsync(getObjectArgs).ConfigureAwait(false); return true; } @@ -69,7 +69,7 @@ public async Task PresignedGetObject() .WithObject(objectName) .WithStreamData(helloStream) .WithObjectSize(helloData.Length); - await client.PutObjectAsync(PutObjectArgs).ConfigureAwait(false); + _ = await client.PutObjectAsync(PutObjectArgs).ConfigureAwait(false); } var presignedGetObjectArgs = new PresignedGetObjectArgs() @@ -119,7 +119,7 @@ public async Task PresignedGetObjectWithHeaders() .WithObject(objectName) .WithStreamData(helloStream) .WithObjectSize(helloData.Length); - await client.PutObjectAsync(PutObjectArgs).ConfigureAwait(false); + _ = await client.PutObjectAsync(PutObjectArgs).ConfigureAwait(false); } var presignedGetObjectArgs = new PresignedGetObjectArgs() diff --git a/Minio.Tests/RetryHandlerTest.cs b/Minio.Tests/RetryHandlerTest.cs index 644311ab96..2aef0162b3 100644 --- a/Minio.Tests/RetryHandlerTest.cs +++ b/Minio.Tests/RetryHandlerTest.cs @@ -33,7 +33,7 @@ public async Task TestRetryPolicyOnSuccess() .Build(); var invokeCount = 0; - client.WithRetryPolicy( + _ = client.WithRetryPolicy( async callback => { invokeCount++; @@ -58,7 +58,7 @@ public async Task TestRetryPolicyOnFailure() var invokeCount = 0; var retryCount = 3; - client.WithRetryPolicy( + _ = client.WithRetryPolicy( async callback => { Exception exception = null; @@ -82,7 +82,7 @@ public async Task TestRetryPolicyOnFailure() .WithBucket(Guid.NewGuid().ToString()) .WithObject("aa") .WithCallbackStream(s => { }); - await Assert.ThrowsExceptionAsync( + _ = await Assert.ThrowsExceptionAsync( () => client.GetObjectAsync(getObjectArgs)).ConfigureAwait(false); Assert.AreEqual(invokeCount, retryCount); } diff --git a/Minio.Tests/ReuseTcpConnectionTest.cs b/Minio.Tests/ReuseTcpConnectionTest.cs index b49583fb08..17e9e3b5c8 100644 --- a/Minio.Tests/ReuseTcpConnectionTest.cs +++ b/Minio.Tests/ReuseTcpConnectionTest.cs @@ -33,7 +33,7 @@ private async Task ObjectExistsAsync(MinioClient client, string bucket, st .WithBucket(bucket) .WithObject(objectName) .WithFile("testfile"); - await client.GetObjectAsync(getObjectArgs).ConfigureAwait(false); + _ = await client.GetObjectAsync(getObjectArgs).ConfigureAwait(false); return true; } @@ -68,14 +68,14 @@ public async Task ReuseTcpTest() .WithObject(objectName) .WithStreamData(helloStream) .WithObjectSize(helloData.Length); - await minioClient.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + _ = await minioClient.PutObjectAsync(putObjectArgs).ConfigureAwait(false); } - await GetObjectLength(bucket, objectName).ConfigureAwait(false); + _ = await GetObjectLength(bucket, objectName).ConfigureAwait(false); for (var i = 0; i < 100; i++) // sequential execution, produce one tcp connection, check by netstat -an | grep 9000 - await GetObjectLength(bucket, objectName).ConfigureAwait(false); + _ = await GetObjectLength(bucket, objectName).ConfigureAwait(false); ConcurrentBag reuseTcpConnectionTasks = new(Enumerable.Range(0, 500).Select(_ => GetObjectLength(bucket, objectName))); @@ -90,7 +90,7 @@ private async Task GetObjectLength(string bucket, string objectName) .WithBucket(bucket) .WithObject(objectName) .WithCallbackStream(stream => stream.Dispose()); - await minioClient.GetObjectAsync(getObjectArgs).ConfigureAwait(false); + _ = await minioClient.GetObjectAsync(getObjectArgs).ConfigureAwait(false); return objectLength; } diff --git a/Minio.Tests/TestHelper.cs b/Minio.Tests/TestHelper.cs index 66f2d9b5de..1048a1068a 100644 --- a/Minio.Tests/TestHelper.cs +++ b/Minio.Tests/TestHelper.cs @@ -32,7 +32,7 @@ public static string GetRandomName(int length = 5) var characters = "0123456789abcdefghijklmnopqrstuvwxyz"; var result = new StringBuilder(length); - for (var i = 0; i < length; i++) result.Append(characters[rnd.Next(characters.Length)]); + for (var i = 0; i < length; i++) _ = result.Append(characters[rnd.Next(characters.Length)]); return result.ToString(); } } diff --git a/Minio/ApiEndpoints/ObjectOperations.cs b/Minio/ApiEndpoints/ObjectOperations.cs index 501a813961..90661ed3b8 100644 --- a/Minio/ApiEndpoints/ObjectOperations.cs +++ b/Minio/ApiEndpoints/ObjectOperations.cs @@ -251,7 +251,7 @@ public async Task PresignedGetObjectAsync(PresignedGetObjectArgs args) args.Policy.FormData["policy"] = policyBase64; args.Policy.FormData["x-amz-algorithm"] = signV4Algorithm; args.Policy.FormData["x-amz-credential"] = credential; - args.Policy.FormData["x-amz-date"] = t.ToString("yyyyMMddTHHmmssZ"); + args.Policy.FormData["x-amz-date"] = t.ToString("yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture); if (!string.IsNullOrEmpty(SessionToken)) args.Policy.FormData["x-amz-security-token"] = SessionToken; args.Policy.FormData["x-amz-signature"] = signature; @@ -1255,10 +1255,10 @@ internal async Task> ReadFullAsync(Stream data, int current while (totalRead < currentPartSize) { Memory curData = new byte[currentPartSize - totalRead]; - var curRead = await data.ReadAsync(curData.Slice(0, currentPartSize - totalRead)).ConfigureAwait(false); + var curRead = await data.ReadAsync(curData[..(currentPartSize - totalRead)]).ConfigureAwait(false); if (curRead == 0) break; for (var i = 0; i < curRead; i++) - curData.Slice(i, 1).CopyTo(result.Slice(totalRead + i)); + curData.Slice(i, 1).CopyTo(result[(totalRead + i)..]); totalRead += curRead; } @@ -1268,7 +1268,7 @@ internal async Task> ReadFullAsync(Stream data, int current Memory truncatedResult = new byte[totalRead]; for (var i = 0; i < totalRead; i++) - result.Slice(i, 1).CopyTo(truncatedResult.Slice(i)); + result.Slice(i, 1).CopyTo(truncatedResult[i..]); return truncatedResult; } diff --git a/Minio/DataModel/Args/ListenBucketNotificationsArgs.cs b/Minio/DataModel/Args/ListenBucketNotificationsArgs.cs index 18be8730fd..feacda9599 100644 --- a/Minio/DataModel/Args/ListenBucketNotificationsArgs.cs +++ b/Minio/DataModel/Args/ListenBucketNotificationsArgs.cs @@ -74,11 +74,7 @@ internal override HttpRequestMessageBuilder BuildRequest(HttpRequestMessageBuild while (!sr.EndOfStream) try { -#if NETSTANDARD || NET6_0 - var line = await sr.ReadLineAsync().ConfigureAwait(false); -#elif NET7_0_OR_GREATER var line = await sr.ReadLineAsync(cancellationToken).ConfigureAwait(false); -#endif if (string.IsNullOrEmpty(line)) break; diff --git a/Minio/DataModel/ObjectStat.cs b/Minio/DataModel/ObjectStat.cs index 31a12bf843..fd3bcc794a 100644 --- a/Minio/DataModel/ObjectStat.cs +++ b/Minio/DataModel/ObjectStat.cs @@ -131,7 +131,7 @@ public static ObjectStat FromResponseHeaders(string objectName, IDictionarySet date for the policy public void SetDate(DateTime date) { - var dateStr = date.ToString("yyyyMMddTHHmmssZ"); + var dateStr = date.ToString("yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture); Conditions.Add(new List<(string, string, string)> { ("eq", "$x-amz-date", dateStr) }); // this.formData.Add("x-amz-date", dateStr); } @@ -267,7 +267,8 @@ private ReadOnlySpan MarshalJSON() // expiration and policies will never be empty because of checks at PresignedPostPolicy() var sb = new StringBuilder(); _ = sb.Append('{'); - _ = sb.Append("\"expiration\":\"").Append(Expiration.ToString("yyyy-MM-ddTHH:mm:ss.fffZ")).Append('"') + _ = sb.Append("\"expiration\":\"") + .Append(Expiration.ToString("yyyy-MM-ddTHH:mm:ss.fffZ", CultureInfo.InvariantCulture)).Append('"') .Append(','); _ = sb.Append("\"conditions\":[").Append(string.Join(",", policyList)).Append(']'); _ = sb.Append('}'); diff --git a/Minio/DataModel/Select/SelectResponseStream.cs b/Minio/DataModel/Select/SelectResponseStream.cs index 7fac5ecfe0..bd31fe8685 100644 --- a/Minio/DataModel/Select/SelectResponseStream.cs +++ b/Minio/DataModel/Select/SelectResponseStream.cs @@ -104,16 +104,16 @@ private void Start() if (BitConverter.IsLittleEndian) preludeCRCBytes.Reverse(); numBytesRead += n; Span inputArray = new byte[prelude.Length + 4]; - prelude.Span.CopyTo(inputArray.Slice(0, prelude.Length)); + prelude.Span.CopyTo(inputArray[..prelude.Length]); var destinationPrelude = inputArray.Slice(inputArray.Length - 4, 4); - var isValidPrelude = Crc32.TryHash(inputArray.Slice(0, inputArray.Length - 4), destinationPrelude, out _); + var isValidPrelude = Crc32.TryHash(inputArray[..^4], destinationPrelude, out _); if (!isValidPrelude) throw new ArgumentException("invalid prelude CRC", nameof(destinationPrelude)); if (!destinationPrelude.SequenceEqual(preludeCRCBytes)) throw new ArgumentException("Prelude CRC Mismatch", nameof(preludeCRCBytes)); - var preludeBytes = prelude.Slice(0, 4).Span; + var preludeBytes = prelude[..4].Span; Span bytes = new byte[preludeBytes.Length]; preludeBytes.CopyTo(bytes); if (BitConverter.IsLittleEndian) bytes.Reverse(); @@ -158,7 +158,7 @@ private void Start() payload.Span.CopyTo(inputArray.Slice(prelude.Length + preludeCRC.Length + headerLength, payloadLength)); var destinationMessage = inputArray.Slice(inputArray.Length - 4, 4); - var isValidMessage = Crc32.TryHash(inputArray.Slice(0, inputArray.Length - 4), destinationMessage, out _); + var isValidMessage = Crc32.TryHash(inputArray[..^4], destinationMessage, out _); if (!isValidMessage) throw new ArgumentException("invalid message CRC", nameof(destinationMessage)); if (!destinationMessage.SequenceEqual(messageCRCBytes)) diff --git a/Minio/DataModel/Tags/Tagging.cs b/Minio/DataModel/Tags/Tagging.cs index a351817e39..75d0bdd7ec 100644 --- a/Minio/DataModel/Tags/Tagging.cs +++ b/Minio/DataModel/Tags/Tagging.cs @@ -1,4 +1,4 @@ -/* +/* * MinIO .NET Library for Amazon S3 Compatible Cloud Storage, (C) 2020, 2021 MinIO, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -83,7 +83,7 @@ internal bool ValidateTagKey(string key) if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key) || key.Length > MAX_TAG_KEY_LENGTH || - key.Contains('&')) + key.Contains('&', StringComparison.Ordinal)) return false; return true; diff --git a/Minio/Helper/BuilderUtil.cs b/Minio/Helper/BuilderUtil.cs index 5750349651..85c0c852a3 100644 --- a/Minio/Helper/BuilderUtil.cs +++ b/Minio/Helper/BuilderUtil.cs @@ -92,7 +92,7 @@ private static bool IsValidOctetVal(string val) private static bool IsValidIPv4(string ip) { var posColon = ip.LastIndexOf(':'); - if (posColon != -1) ip = ip.Substring(0, posColon); + if (posColon != -1) ip = ip[..posColon]; var octetsStr = ip.Split('.'); if (octetsStr.Length != 4) return false; var isValidSmallInt = Array.TrueForAll(octetsStr, IsValidSmallInt); @@ -127,7 +127,7 @@ public static bool IsValidHostnameOrIPAddress(string host) return false; } - host = host.Substring(0, posColon); + host = host[..posColon]; } // Check host if it is a hostname. diff --git a/Minio/Helper/RequestUtil.cs b/Minio/Helper/RequestUtil.cs index 558599fef6..78d9cfae80 100644 --- a/Minio/Helper/RequestUtil.cs +++ b/Minio/Helper/RequestUtil.cs @@ -25,11 +25,11 @@ internal static class RequestUtil { internal static Uri GetEndpointURL(string endPoint, bool secure) { - if (endPoint.Contains(':')) + if (endPoint.Contains(':', StringComparison.Ordinal)) { var parts = endPoint.Split(':'); var host = parts[0]; - var port = parts[1]; + //var port = parts[1]; if (!S3utils.IsValidIP(host) && !IsValidEndpoint(host)) throw new InvalidEndpointException("Endpoint: " + endPoint + " does not follow ip address or domain name standards."); @@ -91,7 +91,6 @@ internal static Uri TryCreateUri(string endpoint, bool secure) internal static void ValidateEndpoint(Uri uri, string endpoint) { if (string.IsNullOrEmpty(uri.OriginalString)) throw new InvalidEndpointException("Endpoint cannot be empty."); - var host = uri.Host; if (!IsValidEndpoint(uri.Host)) throw new InvalidEndpointException(endpoint, "Invalid endpoint."); if (!uri.AbsolutePath.Equals("/", StringComparison.OrdinalIgnoreCase)) @@ -114,11 +113,11 @@ internal static bool IsValidEndpoint(string endpoint) // endpoint may be a hostname // refer https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_host_names // why checks are as shown below. - if (endpoint.Length < 1 || endpoint.Length > 253) return false; + if (endpoint.Length is < 1 or > 253) return false; foreach (var label in endpoint.Split('.')) { - if (label.Length < 1 || label.Length > 63) return false; + if (label.Length is < 1 or > 63) return false; var validLabel = new Regex("^[a-zA-Z0-9]([A-Za-z0-9-_]*[a-zA-Z0-9])?$", RegexOptions.ExplicitCapture, TimeSpan.FromHours(1)); diff --git a/Minio/Helper/S3utils.cs b/Minio/Helper/S3utils.cs index eee5e2f194..1a4530365c 100644 --- a/Minio/Helper/S3utils.cs +++ b/Minio/Helper/S3utils.cs @@ -51,7 +51,7 @@ internal static bool IsVirtualHostSupported(Uri endpointURL, string bucketName) // bucketName can be valid but '.' in the hostname will fail SSL // certificate validation. So do not use host-style for such buckets. if (string.Equals(endpointURL.Scheme, "https", StringComparison.OrdinalIgnoreCase) && - bucketName.Contains('.')) return false; + bucketName.Contains('.', StringComparison.Ordinal)) return false; // Return true for all other cases return IsAmazonEndPoint(endpointURL.Host); } diff --git a/Minio/Helper/Utils.cs b/Minio/Helper/Utils.cs index 50de4945c8..814a3d102c 100644 --- a/Minio/Helper/Utils.cs +++ b/Minio/Helper/Utils.cs @@ -15,7 +15,6 @@ */ using System.ComponentModel; -using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; using System.Security.Cryptography; @@ -58,10 +57,8 @@ internal static void ValidateBucketName(string bucketName) throw new InvalidBucketNameException(bucketName, "Bucket name cannot be smaller than 3 characters."); if (bucketName.Length > 63) throw new InvalidBucketNameException(bucketName, "Bucket name cannot be greater than 63 characters."); -#pragma warning disable IDE0056 // Use index operator: not possible in netstandard2.0 - if (bucketName[0] == '.' || bucketName[bucketName.Length - 1] == '.') + if (bucketName[0] == '.' || bucketName[^1] == '.') throw new InvalidBucketNameException(bucketName, "Bucket name cannot start or end with a '.' dot."); -#pragma warning restore IDE0056 // Use index operator if (bucketName.Any(char.IsUpper)) throw new InvalidBucketNameException(bucketName, "Bucket name cannot have upper case characters"); if (invalidDotBucketName.IsMatch(bucketName)) @@ -90,39 +87,37 @@ internal static void ValidateObjectPrefix(string objectPrefix) } // Return url encoded string where reserved characters have been percent-encoded - [SuppressMessage("Usage", "MA0074:Avoid implicit culture-sensitive methods", - Justification = "Not possible right now with netstandard2.0 support")] internal static string UrlEncode(string input) { // The following characters are not allowed on the server side // '-', '_', '.', '/', '*' - return Uri.EscapeDataString(input).Replace("\\!", "%21") - .Replace("\\\"", "%22") - .Replace("\\#", "%23") - .Replace("\\$", "%24") - .Replace("\\%", "%25") - .Replace("\\&", "%26") - .Replace("\\'", "%27") - .Replace("\\(", "%28") - .Replace("\\)", "%29") - .Replace("\\+", "%2B") - .Replace("\\,", "%2C") - .Replace("\\:", "%3A") - .Replace("\\;", "%3B") - .Replace("\\<", "%3C") - .Replace("\\=", "%3D") - .Replace("\\>", "%3E") - .Replace("\\?", "%3F") - .Replace("\\@", "%40") - .Replace("\\[", "%5B") - .Replace("\\\\", "%5C") - .Replace("\\]", "%5D") - .Replace("\\^", "%5E") - .Replace("\\'", "%60") - .Replace("\\{", "%7B") - .Replace("\\|", "%7C") - .Replace("\\}", "%7D") - .Replace("\\~", "%7E"); + return Uri.EscapeDataString(input).Replace("\\!", "%21", StringComparison.Ordinal) + .Replace("\\\"", "%22", StringComparison.Ordinal) + .Replace("\\#", "%23", StringComparison.Ordinal) + .Replace("\\$", "%24", StringComparison.Ordinal) + .Replace("\\%", "%25", StringComparison.Ordinal) + .Replace("\\&", "%26", StringComparison.Ordinal) + .Replace("\\'", "%27", StringComparison.Ordinal) + .Replace("\\(", "%28", StringComparison.Ordinal) + .Replace("\\)", "%29", StringComparison.Ordinal) + .Replace("\\+", "%2B", StringComparison.Ordinal) + .Replace("\\,", "%2C", StringComparison.Ordinal) + .Replace("\\:", "%3A", StringComparison.Ordinal) + .Replace("\\;", "%3B", StringComparison.Ordinal) + .Replace("\\<", "%3C", StringComparison.Ordinal) + .Replace("\\=", "%3D", StringComparison.Ordinal) + .Replace("\\>", "%3E", StringComparison.Ordinal) + .Replace("\\?", "%3F", StringComparison.Ordinal) + .Replace("\\@", "%40", StringComparison.Ordinal) + .Replace("\\[", "%5B", StringComparison.Ordinal) + .Replace("\\\\", "%5C", StringComparison.Ordinal) + .Replace("\\]", "%5D", StringComparison.Ordinal) + .Replace("\\^", "%5E", StringComparison.Ordinal) + .Replace("\\'", "%60", StringComparison.Ordinal) + .Replace("\\{", "%7B", StringComparison.Ordinal) + .Replace("\\|", "%7C", StringComparison.Ordinal) + .Replace("\\}", "%7D", StringComparison.Ordinal) + .Replace("\\~", "%7E", StringComparison.Ordinal); } // Return encoded path where extra "/" are trimmed off. @@ -160,7 +155,7 @@ internal static void ValidateFile(string filePath, string contentType = null) throw new ArgumentException($"'{fileName}': not a regular file", nameof(filePath)); } - contentType ??= GetContentType(filePath); + //contentType ??= GetContentType(filePath); } internal static string GetContentType(string fileName) @@ -252,11 +247,8 @@ public static bool CaseInsensitiveContains(string text, string value, { if (string.IsNullOrEmpty(text)) throw new ArgumentException($"'{nameof(text)}' cannot be null or empty.", nameof(text)); -#if NETSTANDARD - return text.IndexOf(value, stringComparison) >= 0; -#else + return text.Contains(value, stringComparison); -#endif } /// @@ -935,9 +927,7 @@ public static Uri GetBaseUrl(string endpoint) nameof(endpoint)); if (endpoint.EndsWith("/", StringComparison.OrdinalIgnoreCase)) -#pragma warning disable IDE0057 // Use range operator: not possible in netstandard2.0 - endpoint = endpoint.Substring(0, endpoint.Length - 1); -#pragma warning restore IDE0057 // Use range operator + endpoint = endpoint[..^1]; if (!endpoint.StartsWith("http", StringComparison.OrdinalIgnoreCase) && !BuilderUtil.IsValidHostnameOrIPAddress(endpoint)) throw new InvalidEndpointException( diff --git a/Minio/Minio.csproj b/Minio/Minio.csproj index f60a73f6cd..da1f7bd53f 100644 --- a/Minio/Minio.csproj +++ b/Minio/Minio.csproj @@ -24,7 +24,8 @@ - + + diff --git a/Minio/MinioClient.cs b/Minio/MinioClient.cs index 0a3aec7fa6..5939880925 100644 --- a/Minio/MinioClient.cs +++ b/Minio/MinioClient.cs @@ -334,7 +334,7 @@ internal async Task CreateRequest( else if (resourcePath?.Contains("location") == true) // use path style for location query usePathStyle = true; - else if (bucketName.Contains('.') && Secure) + else if (bucketName.Contains('.', StringComparison.Ordinal) && Secure) // use path style where '.' in bucketName causes SSL certificate validation error usePathStyle = true; @@ -405,11 +405,6 @@ private async Task ExecuteTaskCoreAsync( CancellationToken cancellationToken = default) { var startTime = DateTime.Now; - // Logs full url when HTTPtracing is enabled. - if (trace) - { - var fullUrl = requestMessageBuilder.RequestUri; - } var v4Authenticator = new V4Authenticator(Secure, AccessKey, SecretKey, Region, diff --git a/Minio/MinioClientExtensions.cs b/Minio/MinioClientExtensions.cs index 1740f92c54..9525f22382 100644 --- a/Minio/MinioClientExtensions.cs +++ b/Minio/MinioClientExtensions.cs @@ -253,7 +253,7 @@ internal static Uri GetBaseUrl(string endpoint) nameof(endpoint)); if (endpoint.EndsWith("/", StringComparison.OrdinalIgnoreCase)) - endpoint = endpoint.Substring(0, endpoint.Length - 1); + endpoint = endpoint[..^1]; if (!BuilderUtil.IsValidHostnameOrIPAddress(endpoint)) throw new InvalidEndpointException( string.Format(CultureInfo.InvariantCulture, "{0} is invalid hostname.", endpoint), "endpoint"); diff --git a/Minio/V4Authenticator.cs b/Minio/V4Authenticator.cs index 860fbb4704..8cf38db6d6 100644 --- a/Minio/V4Authenticator.cs +++ b/Minio/V4Authenticator.cs @@ -181,7 +181,8 @@ private ReadOnlySpan GenerateSigningKey(string region, DateTime signingDat ReadOnlySpan requestBytes; ReadOnlySpan serviceBytes = Encoding.UTF8.GetBytes(GetService(isSts)); - ReadOnlySpan formattedDateBytes = Encoding.UTF8.GetBytes(signingDate.ToString("yyyyMMdd")); + ReadOnlySpan formattedDateBytes = + Encoding.UTF8.GetBytes(signingDate.ToString("yyyyMMdd", CultureInfo.InvariantCulture)); ReadOnlySpan formattedKeyBytes = Encoding.UTF8.GetBytes($"AWS4{secretKey}"); var dateKey = SignHmac(formattedKeyBytes, formattedDateBytes); ReadOnlySpan regionBytes = Encoding.UTF8.GetBytes(region); @@ -312,7 +313,7 @@ internal string PresignURL(HttpRequestMessageBuilder requestBuilder, int expires + Uri.EscapeDataString(accessKey + "/" + GetScope(region, signingDate)) + "&"; requestQuery += "X-Amz-Date=" - + signingDate.ToString("yyyyMMddTHHmmssZ") + + signingDate.ToString("yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture) + "&"; requestQuery += "X-Amz-Expires=" + expires @@ -487,7 +488,8 @@ private SortedDictionary GetHeadersToSign(HttpRequestMessageBuil /// Date for signature to be signed private void SetDateHeader(HttpRequestMessageBuilder requestBuilder, DateTime signingDate) { - requestBuilder.AddOrUpdateHeaderParameter("x-amz-date", signingDate.ToString("yyyyMMddTHHmmssZ")); + requestBuilder.AddOrUpdateHeaderParameter("x-amz-date", + signingDate.ToString("yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture)); } /// diff --git a/SimpleTest/Program.cs b/SimpleTest/Program.cs index fd8ae37080..57bcfb4b4d 100644 --- a/SimpleTest/Program.cs +++ b/SimpleTest/Program.cs @@ -55,7 +55,7 @@ private static async Task Main(string[] args) var found = await IsBucketExists(minio, bucketName).ConfigureAwait(false); Console.WriteLine("Bucket exists? = " + found); - Console.ReadLine(); + _ = Console.ReadLine(); } private static Task IsBucketExists(IMinioClient minio, string bucketName) From cf71536f307ecc67899d5b4f0520a6d8a63676fc Mon Sep 17 00:00:00 2001 From: Martijn van Dijk Date: Mon, 7 Aug 2023 20:51:34 +0200 Subject: [PATCH 2/2] Update --- Directory.Build.props | 2 +- Minio.Examples/Cases/GetPartialObject.cs | 2 +- Minio.Functional.Tests/FunctionalTest.cs | 36 +++++-------------- .../DataModel/Select/SelectResponseStream.cs | 9 +---- Minio/HttpRequestMessageBuilder.cs | 5 +-- Minio/ResponseResult.cs | 8 ----- Minio/V4Authenticator.cs | 13 ++----- 7 files changed, 16 insertions(+), 59 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index 398ecf1575..70d4206094 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -60,7 +60,7 @@ - + all runtime; build; native; contentfiles; analyzers diff --git a/Minio.Examples/Cases/GetPartialObject.cs b/Minio.Examples/Cases/GetPartialObject.cs index a509b107d7..f3e5ace85b 100644 --- a/Minio.Examples/Cases/GetPartialObject.cs +++ b/Minio.Examples/Cases/GetPartialObject.cs @@ -45,7 +45,7 @@ public static async Task Run(IMinioClient minio, .WithCallbackStream(async (stream, cancellationToken) => { var fileStream = File.Create(fileName); - await stream.CopyToAsync(fileStream).ConfigureAwait(false); + await stream.CopyToAsync(fileStream, cancellationToken).ConfigureAwait(false); await fileStream.DisposeAsync().ConfigureAwait(false); var writtenInfo = new FileInfo(fileName); var file_read_size = writtenInfo.Length; diff --git a/Minio.Functional.Tests/FunctionalTest.cs b/Minio.Functional.Tests/FunctionalTest.cs index 519d3dd709..81410863b7 100644 --- a/Minio.Functional.Tests/FunctionalTest.cs +++ b/Minio.Functional.Tests/FunctionalTest.cs @@ -739,13 +739,8 @@ internal static async Task PutGetStatEncryptedObject_Test1(MinioClient minio) { using var fileStream = File.Create(tempFileName); -#if NETFRAMEWORK - await stream.CopyToAsync(fileStream).ConfigureAwait(false); - fileStream.Dispose(); -#else await stream.CopyToAsync(fileStream, cancellationToken).ConfigureAwait(false); await fileStream.DisposeAsync().ConfigureAwait(false); -#endif var writtenInfo = new FileInfo(tempFileName); file_read_size = writtenInfo.Length; @@ -831,13 +826,8 @@ internal static async Task PutGetStatEncryptedObject_Test2(MinioClient minio) { using var fileStream = File.Create(tempFileName); -#if NETFRAMEWORK - await stream.CopyToAsync(fileStream).ConfigureAwait(false); - fileStream.Dispose(); -#else await stream.CopyToAsync(fileStream, cancellationToken).ConfigureAwait(false); await fileStream.DisposeAsync().ConfigureAwait(false); -#endif var writtenInfo = new FileInfo(tempFileName); file_read_size = writtenInfo.Length; @@ -919,13 +909,10 @@ internal static async Task PutGetStatEncryptedObject_Test3(MinioClient minio) .WithCallbackStream(async (stream, cancellationToken) => { using var fileStream = File.Create(tempFileName); -#if NETFRAMEWORK - await stream.CopyToAsync(fileStream).ConfigureAwait(false); - fileStream.Dispose(); -#else + await stream.CopyToAsync(fileStream, cancellationToken).ConfigureAwait(false); await fileStream.DisposeAsync().ConfigureAwait(false); -#endif + var writtenInfo = new FileInfo(tempFileName); file_read_size = writtenInfo.Length; @@ -1316,14 +1303,15 @@ internal static async Task RemoveObjects_Test3(MinioClient minio) } } - internal static async Task DownloadObjectAsync(MinioClient minio, string url, string filePath) + internal static async Task DownloadObjectAsync(MinioClient minio, string url, string filePath, + CancellationToken cancellationToken = default) { using var response = await minio.WrapperGetAsync(url).ConfigureAwait(false); if (string.IsNullOrEmpty(Convert.ToString(response.Content)) || !HttpStatusCode.OK.Equals(response.StatusCode)) throw new ArgumentNullException(nameof(response.Content), "Unable to download via presigned URL"); using var fs = new FileStream(filePath, FileMode.CreateNew); - await response.Content.CopyToAsync(fs).ConfigureAwait(false); + await response.Content.CopyToAsync(fs, cancellationToken).ConfigureAwait(false); } internal static async Task UploadObjectAsync(MinioClient minio, string url, string filePath) @@ -4658,13 +4646,10 @@ internal static async Task GetObject_Test1(MinioClient minio) .WithCallbackStream(async (stream, cancellationToken) => { var fileStream = File.Create(tempFileName); -#if NETFRAMEWORK - await stream.CopyToAsync(fileStream).ConfigureAwait(false); - fileStream.Dispose(); -#else + await stream.CopyToAsync(fileStream, cancellationToken).ConfigureAwait(false); await fileStream.DisposeAsync().ConfigureAwait(false); -#endif + var writtenInfo = new FileInfo(tempFileName); file_read_size = writtenInfo.Length; @@ -4844,13 +4829,10 @@ internal static async Task GetObject_3_OffsetLength_Tests(MinioClient minio) .WithCallbackStream(async (stream, cancellationToken) => { var fileStream = File.Create(tempFileName); -#if NETFRAMEWORK - await stream.CopyToAsync(fileStream).ConfigureAwait(false); - fileStream.Dispose(); -#else + await stream.CopyToAsync(fileStream, cancellationToken).ConfigureAwait(false); await fileStream.DisposeAsync().ConfigureAwait(false); -#endif + var writtenInfo = new FileInfo(tempFileName); actualFileSize = writtenInfo.Length; diff --git a/Minio/DataModel/Select/SelectResponseStream.cs b/Minio/DataModel/Select/SelectResponseStream.cs index bd31fe8685..decb6c410c 100644 --- a/Minio/DataModel/Select/SelectResponseStream.cs +++ b/Minio/DataModel/Select/SelectResponseStream.cs @@ -226,11 +226,8 @@ private IDictionary ExtractHeaders(Span data) var nameLength = data[offset++]; var b = data.Slice(offset, nameLength); -#if NETSTANDARD - var name = Encoding.UTF8.GetString(b.ToArray()); -#else var name = Encoding.UTF8.GetString(b); -#endif + offset += nameLength; var hdrValue = data[offset++]; if (hdrValue != 7) throw new IOException("header value type is not 7"); @@ -245,11 +242,7 @@ private IDictionary ExtractHeaders(Span data) #endif b = data.Slice(offset, headerValLength); -#if NETSTANDARD - var value = Encoding.UTF8.GetString(b.ToArray()); -#else var value = Encoding.UTF8.GetString(b); -#endif offset += headerValLength; headerMap.Add(name, value); } diff --git a/Minio/HttpRequestMessageBuilder.cs b/Minio/HttpRequestMessageBuilder.cs index 857a09b5db..9de4752c39 100644 --- a/Minio/HttpRequestMessageBuilder.cs +++ b/Minio/HttpRequestMessageBuilder.cs @@ -71,11 +71,8 @@ public HttpRequestMessage Request var requestUri = requestUriBuilder.Uri; var request = new HttpRequestMessage(Method, requestUri); -#if NETSTANDARD - if (!Content.IsEmpty) request.Content = new ByteArrayContent(Content.ToArray()); -#else if (!Content.IsEmpty) request.Content = new ReadOnlyMemoryContent(Content); -#endif + foreach (var parameter in HeaderParameters) { var key = parameter.Key.ToLowerInvariant(); diff --git a/Minio/ResponseResult.cs b/Minio/ResponseResult.cs index fb81151541..a7cc7f1088 100644 --- a/Minio/ResponseResult.cs +++ b/Minio/ResponseResult.cs @@ -61,11 +61,7 @@ public Stream ContentStream get { if (Response is null) return null; -#if NETSTANDARD - return stream ??= Response.Content.ReadAsStreamAsync().GetAwaiter().GetResult(); -#else return stream ??= Response.Content.ReadAsStream(); -#endif } } @@ -92,11 +88,7 @@ public string Content get { if (ContentBytes.Length == 0) return ""; -#if NETSTANDARD - content ??= Encoding.UTF8.GetString(ContentBytes.ToArray()); -#else content ??= Encoding.UTF8.GetString(ContentBytes.Span); -#endif return content; } } diff --git a/Minio/V4Authenticator.cs b/Minio/V4Authenticator.cs index 8cf38db6d6..ed18b7cb80 100644 --- a/Minio/V4Authenticator.cs +++ b/Minio/V4Authenticator.cs @@ -189,12 +189,9 @@ private ReadOnlySpan GenerateSigningKey(string region, DateTime signingDat var dateRegionKey = SignHmac(dateKey, regionBytes); dateRegionServiceKey = SignHmac(dateRegionKey, serviceBytes); requestBytes = Encoding.UTF8.GetBytes("aws4_request"); - var hmac = SignHmac(dateRegionServiceKey, requestBytes); -#if NETSTANDARD - var signingKey = Encoding.UTF8.GetString(hmac.ToArray()); -#else - var signingKey = Encoding.UTF8.GetString(hmac); -#endif + + //var hmac = SignHmac(dateRegionServiceKey, requestBytes); + //var signingKey = Encoding.UTF8.GetString(hmac); return SignHmac(dateRegionServiceKey, requestBytes); } @@ -426,11 +423,7 @@ private string GetCanonicalRequest(HttpRequestMessageBuilder requestBuilder, cntntByteData = requestBuilder.Request.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult(); // UTF conversion - String from bytes -#if NETSTANDARD - queryParams = Encoding.UTF8.GetString(cntntByteData.ToArray(), 0, cntntByteData.Length); -#else queryParams = Encoding.UTF8.GetString(cntntByteData); -#endif } if (!string.IsNullOrEmpty(queryParams) &&