From ec0a599450884fe538d9e161e4c501a8049f6e9a Mon Sep 17 00:00:00 2001 From: Ivan Maximov Date: Thu, 9 May 2019 01:47:01 +0300 Subject: [PATCH] Code cleanup (#303) - Idiomatic style changes - Code formatting. --- Docs/API.md | 48 +- FileUploader/FileUpload.cs | 2 +- Minio.Examples/Cases/BucketExists.cs | 2 +- Minio.Examples/Cases/CopyObject.cs | 8 +- Minio.Examples/Cases/CopyObjectMetadata.cs | 14 +- Minio.Examples/Cases/FGetObject.cs | 2 +- Minio.Examples/Cases/GetBucketNotification.cs | 2 +- Minio.Examples/Cases/GetBucketPolicy.cs | 2 +- Minio.Examples/Cases/GetObject.cs | 8 +- Minio.Examples/Cases/GetPartialObject.cs | 10 +- Minio.Examples/Cases/MakeBucket.cs | 2 +- Minio.Examples/Cases/PresignedGetObject.cs | 2 +- Minio.Examples/Cases/PresignedPostPolicy.cs | 2 +- Minio.Examples/Cases/PutObject.cs | 12 +- .../Cases/RemoveIncompleteUpload.cs | 2 +- Minio.Examples/Cases/RemoveObject.cs | 2 +- Minio.Examples/Cases/RemoveObjects.cs | 2 +- Minio.Examples/Cases/StatObject.cs | 4 +- Minio.Examples/Program.cs | 16 +- Minio.Functional.Tests/FunctionalTest.cs | 998 +++++++++--------- Minio.Functional.Tests/MintLogger.cs | 4 +- Minio.Tests/AuthenticatorTest.cs | 4 +- Minio.Tests/DictionaryExtensionMethods.cs | 3 +- Minio.Tests/EndpointTest.cs | 72 +- Minio.Tests/RegionTest.cs | 6 +- Minio.Tests/UnitTest1.cs | 2 +- Minio.Tests/UtilsTest.cs | 25 +- Minio/AWSS3Endpoints.cs | 11 +- Minio/ApiEndpoints/BucketOperations.cs | 48 +- Minio/ApiEndpoints/IBucketOperations.cs | 6 +- Minio/ApiEndpoints/IObjectOperations.cs | 10 +- Minio/ApiEndpoints/ObjectOperations.cs | 87 +- Minio/BucketRegionCache.cs | 23 +- Minio/DataModel/CopyConditions.cs | 16 +- Minio/DataModel/CreateBucketConfiguration.cs | 2 +- Minio/DataModel/DeleteObject.cs | 6 +- Minio/DataModel/DeleteObjectsRequest.cs | 6 +- Minio/DataModel/DeleteObjectsResult.cs | 10 +- Minio/DataModel/DeletedObject.cs | 10 +- Minio/DataModel/Item.cs | 2 +- Minio/DataModel/Notification/Arn.cs | 19 +- .../Notification/BucketNotification.cs | 27 +- Minio/DataModel/Notification/Filter.cs | 5 +- Minio/DataModel/Notification/FilterRule.cs | 10 +- Minio/DataModel/Notification/LambdaConfig.cs | 7 +- .../Notification/NotificationConfiguration.cs | 17 +- Minio/DataModel/Notification/QueueConfig.cs | 9 +- Minio/DataModel/Notification/S3Key.cs | 5 +- Minio/DataModel/Notification/TopicConfig.cs | 7 +- Minio/DataModel/ObjectStat.cs | 2 +- Minio/DataModel/Part.cs | 9 +- Minio/DataModel/PostPolicy.cs | 78 +- Minio/DataModel/ServerSideEncryption.cs | 26 +- Minio/Exceptions/AccessDeniedException.cs | 5 - Minio/Exceptions/BucketNotFoundException.cs | 8 +- Minio/Exceptions/DeleteError.cs | 2 +- Minio/Exceptions/ErrorResponse.cs | 2 +- Minio/Exceptions/ErrorResponseException.cs | 10 +- Minio/Exceptions/ForbiddenException.cs | 5 - Minio/Exceptions/InternalServerException.cs | 5 - .../Exceptions/InvalidBucketNameException.cs | 7 +- .../InvalidContentLengthException.cs | 4 +- Minio/Exceptions/InvalidEndpointException.cs | 2 +- .../Exceptions/InvalidExpiryRangeException.cs | 5 - .../Exceptions/InvalidObjectNameException.cs | 7 +- .../InvalidObjectPrefixException.cs | 7 +- Minio/Exceptions/MinioException.cs | 5 +- Minio/Exceptions/ObjectNotFoundException.cs | 7 +- Minio/Exceptions/RedirectionException.cs | 5 - .../UnexpectedShortReadException.cs | 5 - Minio/Helper/Constants.cs | 4 +- Minio/Helper/RequestUtil.cs | 33 +- Minio/Helper/s3utils.cs | 9 +- Minio/Helper/utils.cs | 41 +- Minio/MinioClient.cs | 73 +- Minio/Regions.cs | 4 +- Minio/V4Authenticator.cs | 25 +- 77 files changed, 939 insertions(+), 1055 deletions(-) diff --git a/Docs/API.md b/Docs/API.md index f54999c18..d6ffc4e78 100644 --- a/Docs/API.md +++ b/Docs/API.md @@ -38,8 +38,8 @@ var s3Client = new MinioClient("s3.amazonaws.com", | | |---| -|`public MinioClient(string endpoint, string accessKey = "", string secretKey = "", string region="", string sessionToken="")` | -| Creates MinIO client object with given endpoint.AccessKey,secretKey, region and sessionToken are optional parameters,and can be omitted for anonymous access. +|`public MinioClient(string endpoint, string accessKey = "", string secretKey = "", string region = "", string sessionToken="")` | +| Creates MinIO client object with given endpoint.AccessKey, secretKey, region and sessionToken are optional parameters, and can be omitted for anonymous access. The client object uses Http access by default. To use Https, chain method WithSSL() to client object to use secure transfer protocol | @@ -86,11 +86,11 @@ MinioClient minioClient = new MinioClient("play.min.io:9000", ).WithSSL(); // 3. Initializing minio client with proxy -IWebProxy proxy = new WebProxy("192.168.0.1",8000); -MinioClient minioClient = new MinioClient("my-ip-address:9000","minio","minio123").WithSSL().WithProxy(proxy); +IWebProxy proxy = new WebProxy("192.168.0.1", 8000); +MinioClient minioClient = new MinioClient("my-ip-address:9000", "minio", "minio123").WithSSL().WithProxy(proxy); // 4. Initializing minio client with temporary credentials -MinioClient minioClient = new MinioClient("my-ip-address:9000","tempuserid","temppasswd",sessionToken:"sessionToken"); +MinioClient minioClient = new MinioClient("my-ip-address:9000", "tempuserid", "temppasswd", sessionToken:"sessionToken"); ``` @@ -110,7 +110,7 @@ MinioClient s3Client = new MinioClient("s3.amazonaws.com:80", ## 2. Bucket operations -### MakeBucketAsync(string bucketName, string location="us-east-1") +### MakeBucketAsync(string bucketName, string location = "us-east-1") `Task MakeBucketAsync(string bucketName, string location = "us-east-1", CancellationToken cancellationToken = default(CancellationToken))` Creates a new bucket. @@ -487,7 +487,7 @@ catch (MinioException e) -### SetBucketNotificationAsync(string bucketName,BucketNotification notification) +### SetBucketNotificationAsync(string bucketName, BucketNotification notification) `Task SetBucketNotificationAsync(string bucketName, BucketNotification notification, CancellationToken cancellationToken = default(CancellationToken))` Sets notification configuration for a given bucket @@ -677,7 +677,7 @@ try ``` -### GetObjectAsync(string bucketName, string objectName, long offset,long length, Action callback, ServerSideEncryption sse) +### GetObjectAsync(string bucketName, string objectName, long offset, long length, Action callback, ServerSideEncryption sse) `Task GetObjectAsync(string bucketName, string objectName, long offset, long length, Action callback, ServerSideEncryption sse = null, CancellationToken cancellationToken = default(CancellationToken))` @@ -779,9 +779,9 @@ catch (MinioException e) } ``` -### PutObjectAsync(string bucketName, string objectName, Stream data, long size, string contentType,ServerSideEncryption sse) +### PutObjectAsync(string bucketName, string objectName, Stream data, long size, string contentType, ServerSideEncryption sse) -` Task PutObjectAsync(string bucketName, string objectName, Stream data, long size, string contentType,Dictionary metaData=null,ServerSideEncryption sse = null,CancellationToken cancellationToken = default(CancellationToken))` +` Task PutObjectAsync(string bucketName, string objectName, Stream data, long size, string contentType, Dictionary metaData = null, ServerSideEncryption sse = null, CancellationToken cancellationToken = default(CancellationToken))` Uploads contents from a stream to objectName. @@ -833,7 +833,7 @@ try "island.jpg", filestream, filestream.Length, - "application/octet-stream",ssec); + "application/octet-stream", ssec); Console.Out.WriteLine("island.jpg is uploaded successfully"); } catch(MinioException e) @@ -843,9 +843,9 @@ catch(MinioException e) ``` -### PutObjectAsync(string bucketName, string objectName, string filePath, string contentType=null,ServerSideEncryption sse) +### PutObjectAsync(string bucketName, string objectName, string filePath, string contentType=null, ServerSideEncryption sse) -` Task PutObjectAsync(string bucketName, string objectName, string filePath, string contentType=null,Dictionary metaData=null, ServerSideEncryption sse=null,CancellationToken cancellationToken = default(CancellationToken))` +` Task PutObjectAsync(string bucketName, string objectName, string filePath, string contentType = null, Dictionary metaData = null, ServerSideEncryption sse = null, CancellationToken cancellationToken = default(CancellationToken))` Uploads contents from a file to objectName. @@ -883,7 +883,7 @@ The maximum size of a single object is limited to 5TB. putObject transparently u ```cs try { - await minio.PutObjectAsync("mybucket", "island.jpg", "/mnt/photos/island.jpg",contentType: "application/octet-stream"); + await minio.PutObjectAsync("mybucket", "island.jpg", "/mnt/photos/island.jpg", contentType: "application/octet-stream"); Console.Out.WriteLine("island.jpg is uploaded successfully"); } catch(MinioException e) @@ -892,9 +892,9 @@ catch(MinioException e) } ``` -### StatObjectAsync(string bucketName, string objectName,ServerSideEncryption sse) +### StatObjectAsync(string bucketName, string objectName, ServerSideEncryption sse) -`Task StatObjectAsync(string bucketName, string objectName,ServerSideEncryption sse = null, CancellationToken cancellationToken = default(CancellationToken))` +`Task StatObjectAsync(string bucketName, string objectName, ServerSideEncryption sse = null, CancellationToken cancellationToken = default(CancellationToken))` Gets metadata of an object. @@ -936,9 +936,9 @@ catch(MinioException e) ``` -### CopyObjectAsync(string bucketName, string objectName, string destBucketName, string destObjectName = null, CopyConditions copyConditions = null,Dictionary metadata = null, ServerSideEncryption sseSrc = null, ServerSideEncryption sseDest = null) +### CopyObjectAsync(string bucketName, string objectName, string destBucketName, string destObjectName = null, CopyConditions copyConditions = null, Dictionary metadata = null, ServerSideEncryption sseSrc = null, ServerSideEncryption sseDest = null) -*`Task CopyObjectAsync(string bucketName, string objectName, string destBucketName, string destObjectName = null, CopyConditions copyConditions = null, Dictionary metadata = null,ServerSideEncryption sseSrc = null, ServerSideEncryption sseDest = null,CancellationToken cancellationToken = default(CancellationToken))`* +*`Task CopyObjectAsync(string bucketName, string objectName, string destBucketName, string destObjectName = null, CopyConditions copyConditions = null, Dictionary metadata = null, ServerSideEncryption sseSrc = null, ServerSideEncryption sseDest = null, CancellationToken cancellationToken = default(CancellationToken))`* Copies content from objectName to destObjectName. @@ -977,7 +977,7 @@ try { CopyConditions copyConditions = new CopyConditions(); copyConditions.setMatchETagNone("TestETag"); - ServerSideEncryption sseSrc,sseDst; + ServerSideEncryption sseSrc, sseDst; // Uncomment to specify source and destination Server-side encryption options /* Aes aesEncryption = Aes.Create(); @@ -986,7 +986,7 @@ try sseSrc = new SSEC(aesEncryption.Key); sseDst = new SSES3(); */ - await minioClient.CopyObjectAsync("mybucket", "island.jpg", "mydestbucket", "processed.png", copyConditions,sseSrc:sseSrc, sseDest:sseDst); + await minioClient.CopyObjectAsync("mybucket", "island.jpg", "mydestbucket", "processed.png", copyConditions, sseSrc:sseSrc, sseDest:sseDst); Console.Out.WriteLine("island.jpg is uploaded successfully"); } catch(MinioException e) @@ -1130,8 +1130,8 @@ catch(MinioException e) ## 4. Presigned operations -### PresignedGetObjectAsync(string bucketName, string objectName, int expiresInt, Dictionary reqParams = null, DateTime? reqDate = null); -`Task PresignedGetObjectAsync(string bucketName, string objectName, int expiresInt, Dictionary reqParams = null, DateTime? reqDate = null)` +### PresignedGetObjectAsync(string bucketName, string objectName, int expiresInt, Dictionary reqParams = null, DateTime? reqDate = null); +`Task PresignedGetObjectAsync(string bucketName, string objectName, int expiresInt, Dictionary reqParams = null, DateTime? reqDate = null)` Generates a presigned URL for HTTP GET operations. Browsers/Mobile clients may point to this URL to directly download objects even if the bucket is private. This presigned URL can have an associated expiration time in seconds after which it is no longer operational. The default expiry is set to 7 days. @@ -1225,7 +1225,7 @@ __Parameters__ | Return Type | Exceptions | |:--- |:--- | -| ``Task>``: Map of strings to construct form-data. | Listed Exceptions: | +| ``Task>``: Map of strings to construct form-data. | Listed Exceptions: | | | ``InvalidBucketNameException`` : upon invalid bucket name | | | ``ConnectionException`` : upon connection error | | | ``NoSuchAlgorithmException`` : upon requested algorithm was not found during signature calculation. | @@ -1262,7 +1262,7 @@ catch(MinioException e) ``` ## Client Custom Settings -### SetAppInfo(string appName, tring appVersion) +### SetAppInfo(string appName, string appVersion) Adds application details to User-Agent. __Parameters__ diff --git a/FileUploader/FileUpload.cs b/FileUploader/FileUpload.cs index 754b6268c..111b20d6e 100644 --- a/FileUploader/FileUpload.cs +++ b/FileUploader/FileUpload.cs @@ -38,7 +38,7 @@ static void Main(string[] args) try { var minio = new MinioClient(endpoint, accessKey, secretKey).WithSSL(); - FileUpload.Run(minio).Wait(); + Run(minio).Wait(); } catch (Exception ex) { diff --git a/Minio.Examples/Cases/BucketExists.cs b/Minio.Examples/Cases/BucketExists.cs index 69aa93515..6f5c43385 100644 --- a/Minio.Examples/Cases/BucketExists.cs +++ b/Minio.Examples/Cases/BucketExists.cs @@ -29,7 +29,7 @@ public async static Task Run(MinioClient minio, { Console.Out.WriteLine("Running example for API: BucketExistsAsync"); bool found = await minio.BucketExistsAsync(bucketName); - Console.Out.WriteLine(((found == true) ? "Found" : "Couldn't find ") + "bucket " + bucketName); + Console.Out.WriteLine((found ? "Found" : "Couldn't find ") + "bucket " + bucketName); Console.Out.WriteLine(); } catch (Exception e) diff --git a/Minio.Examples/Cases/CopyObject.cs b/Minio.Examples/Cases/CopyObject.cs index 16d58bc4d..a54061873 100644 --- a/Minio.Examples/Cases/CopyObject.cs +++ b/Minio.Examples/Cases/CopyObject.cs @@ -25,10 +25,10 @@ class CopyObject { // Copy object from one bucket to another public async static Task Run(Minio.MinioClient minio, - string fromBucketName="from-bucket-name", - string fromObjectName="from-object-name", - string destBucketName="dest-bucket", - string destObjectName="to-object-name", + string fromBucketName = "from-bucket-name", + string fromObjectName = "from-object-name", + string destBucketName = "dest-bucket", + string destObjectName =" to-object-name", ServerSideEncryption sseSrc = null, ServerSideEncryption sseDest = null) { diff --git a/Minio.Examples/Cases/CopyObjectMetadata.cs b/Minio.Examples/Cases/CopyObjectMetadata.cs index 294e407db..36f711a68 100644 --- a/Minio.Examples/Cases/CopyObjectMetadata.cs +++ b/Minio.Examples/Cases/CopyObjectMetadata.cs @@ -24,10 +24,10 @@ class CopyObjectMetadata { // Copy object from one bucket to another public async static Task Run(Minio.MinioClient minio, - string fromBucketName="from-bucket-name", - string fromObjectName="from-object-name", - string destBucketName="dest-bucket", - string destObjectName="to-object-name") + string fromBucketName = "from-bucket-name", + string fromObjectName = "from-object-name", + string destBucketName = "dest-bucket", + string destObjectName = "to-object-name") { try { @@ -38,10 +38,10 @@ public async static Task Run(Minio.MinioClient minio, copyCond.SetReplaceMetadataDirective(); // set custom metadata - Dictionary metadata = new Dictionary() + var metadata = new Dictionary { - { "Content-Type", "application/css"}, - {"X-Amz-Meta-Mynewkey","my-new-value"} + { "Content-Type", "application/css" }, + { "X-Amz-Meta-Mynewkey", "my-new-value" } }; await minio.CopyObjectAsync(fromBucketName, fromObjectName, diff --git a/Minio.Examples/Cases/FGetObject.cs b/Minio.Examples/Cases/FGetObject.cs index 104a59ece..a5074af25 100644 --- a/Minio.Examples/Cases/FGetObject.cs +++ b/Minio.Examples/Cases/FGetObject.cs @@ -28,7 +28,7 @@ class FGetObject public async static Task Run(Minio.MinioClient minio, string bucketName = "my-bucket-name", string objectName = "my-object-name", - string fileName="local-filename", + string fileName = "local-filename", ServerSideEncryption sse = null) { try diff --git a/Minio.Examples/Cases/GetBucketNotification.cs b/Minio.Examples/Cases/GetBucketNotification.cs index 5d68062cf..8f4021556 100644 --- a/Minio.Examples/Cases/GetBucketNotification.cs +++ b/Minio.Examples/Cases/GetBucketNotification.cs @@ -35,7 +35,7 @@ public async static Task Run(Minio.MinioClient minio, } catch (Exception e) { - Console.Out.WriteLine("Error parsing bucket notifications - make sure that you are running this call against AWS end point"); + Console.Out.WriteLine("Error parsing bucket notifications - make sure that you are running this call against AWS end point: " + e.Message); } } } diff --git a/Minio.Examples/Cases/GetBucketPolicy.cs b/Minio.Examples/Cases/GetBucketPolicy.cs index 47c50f3f6..590000a48 100644 --- a/Minio.Examples/Cases/GetBucketPolicy.cs +++ b/Minio.Examples/Cases/GetBucketPolicy.cs @@ -25,7 +25,7 @@ class GetBucketPolicy // Get bucket policy public async static Task Run(Minio.MinioClient minio, string bucketName = "my-bucket-name", - string prefix="") + string prefix = "") { try { diff --git a/Minio.Examples/Cases/GetObject.cs b/Minio.Examples/Cases/GetObject.cs index 43f8d9f76..896e0dbb7 100644 --- a/Minio.Examples/Cases/GetObject.cs +++ b/Minio.Examples/Cases/GetObject.cs @@ -24,9 +24,9 @@ class GetObject { // Get object in a bucket public async static Task Run(MinioClient minio, - string bucketName="my-bucket-name", - string objectName="my-object-name", - string fileName="my-file-name") + string bucketName = "my-bucket-name", + string objectName = "my-object-name", + string fileName = "my-file-name") { try { @@ -34,7 +34,7 @@ public async static Task Run(MinioClient minio, await minio.GetObjectAsync(bucketName, objectName, (stream) => { - // Uncommment to print the file on output console + // Uncomment to print the file on output console // stream.CopyTo(Console.OpenStandardOutput()); }); Console.WriteLine("Downloaded the file " + fileName + " in bucket " + bucketName); diff --git a/Minio.Examples/Cases/GetPartialObject.cs b/Minio.Examples/Cases/GetPartialObject.cs index e26729138..8c207850a 100644 --- a/Minio.Examples/Cases/GetPartialObject.cs +++ b/Minio.Examples/Cases/GetPartialObject.cs @@ -25,9 +25,9 @@ class GetPartialObject // Get object in a bucket for a particular offset range. Dotnet SDK currently // requires both start offset and end public async static Task Run(MinioClient minio, - string bucketName="my-bucket-name", - string objectName="my-object-name", - string fileName="my-file-name") + string bucketName = "my-bucket-name", + string objectName = "my-object-name", + string fileName = "my-file-name") { try { @@ -45,9 +45,9 @@ await minio.GetObjectAsync(bucketName, objectName, 1024L, 4096L, fileStream.Dispose(); FileInfo writtenInfo = new FileInfo(fileName); long file_read_size = writtenInfo.Length; - // Uncommment to print the file on output console + // Uncomment to print the file on output console // stream.CopyTo(Console.OpenStandardOutput()); - Console.WriteLine("Successfully downloaded object with requested offset and length {0} into file",writtenInfo.Length); + Console.WriteLine("Successfully downloaded object with requested offset and length {0} into file", writtenInfo.Length); stream.Dispose(); }); Console.Out.WriteLine(); diff --git a/Minio.Examples/Cases/MakeBucket.cs b/Minio.Examples/Cases/MakeBucket.cs index e1c566a36..1faf2027d 100644 --- a/Minio.Examples/Cases/MakeBucket.cs +++ b/Minio.Examples/Cases/MakeBucket.cs @@ -23,7 +23,7 @@ public class MakeBucket { // Make a bucket public async static Task Run(Minio.MinioClient minio, - string bucketName="my-bucket-name") + string bucketName = "my-bucket-name") { try { diff --git a/Minio.Examples/Cases/PresignedGetObject.cs b/Minio.Examples/Cases/PresignedGetObject.cs index bc0a08c04..e9b48d711 100644 --- a/Minio.Examples/Cases/PresignedGetObject.cs +++ b/Minio.Examples/Cases/PresignedGetObject.cs @@ -29,7 +29,7 @@ public async static Task Run(MinioClient client, { try { - Dictionary reqParams = new Dictionary(){{"response-content-type", "application/json"}}; + var reqParams = new Dictionary { {"response-content-type", "application/json" } }; string presigned_url = await client.PresignedGetObjectAsync(bucketName, objectName, 1000, reqParams); Console.Out.WriteLine(presigned_url); } diff --git a/Minio.Examples/Cases/PresignedPostPolicy.cs b/Minio.Examples/Cases/PresignedPostPolicy.cs index 3f7fc223d..83bebb7dd 100644 --- a/Minio.Examples/Cases/PresignedPostPolicy.cs +++ b/Minio.Examples/Cases/PresignedPostPolicy.cs @@ -37,7 +37,7 @@ public async static Task Run(MinioClient client) string curlCommand = "curl -X POST "; foreach (KeyValuePair pair in tuple.Item2) { - curlCommand = curlCommand + String.Format(" -F {0}={1}", pair.Key, pair.Value); + curlCommand = curlCommand + string.Format(" -F {0}={1}", pair.Key, pair.Value); } curlCommand = curlCommand + " -F file=@/etc/bashrc " + tuple.Item1; // https://s3.amazonaws.com/my-bucketname"; Console.Out.WriteLine(curlCommand); diff --git a/Minio.Examples/Cases/PutObject.cs b/Minio.Examples/Cases/PutObject.cs index b0b741138..d88a74e34 100644 --- a/Minio.Examples/Cases/PutObject.cs +++ b/Minio.Examples/Cases/PutObject.cs @@ -26,13 +26,13 @@ namespace Minio.Examples.Cases { class PutObject { - private static int MB = 1024 * 1024; + private const int MB = 1024 * 1024; // Put an object from a local stream into bucket public async static Task Run(Minio.MinioClient minio, string bucketName = "my-bucket-name", string objectName = "my-object-name", - string fileName="location-of-file", + string fileName = "location-of-file", ServerSideEncryption sse = null) { try @@ -48,10 +48,10 @@ public async static Task Run(Minio.MinioClient minio, { Console.Out.WriteLine("Running example for API: PutObjectAsync with Stream and MultiPartUpload"); } - var metaData = new Dictionary() - { - {"X-Amz-Meta-Test", "Test Test"} - }; + var metaData = new Dictionary + { + { "X-Amz-Meta-Test", "Test Test" } + }; await minio.PutObjectAsync(bucketName, objectName, filestream, diff --git a/Minio.Examples/Cases/RemoveIncompleteUpload.cs b/Minio.Examples/Cases/RemoveIncompleteUpload.cs index e7c06ff37..9fc5224e4 100644 --- a/Minio.Examples/Cases/RemoveIncompleteUpload.cs +++ b/Minio.Examples/Cases/RemoveIncompleteUpload.cs @@ -31,7 +31,7 @@ public async static Task Run(MinioClient minio, { Console.Out.WriteLine("Running example for API: RemoveIncompleteUploadAsync"); await minio.RemoveIncompleteUploadAsync(bucketName, objectName); - Console.Out.WriteLine("Removed object {0} from bucket {1} successfully",objectName, bucketName); + Console.Out.WriteLine("Removed object {0} from bucket {1} successfully", objectName, bucketName); Console.Out.WriteLine(); } catch (Exception e) diff --git a/Minio.Examples/Cases/RemoveObject.cs b/Minio.Examples/Cases/RemoveObject.cs index 7db12877b..3cde9308c 100644 --- a/Minio.Examples/Cases/RemoveObject.cs +++ b/Minio.Examples/Cases/RemoveObject.cs @@ -29,7 +29,7 @@ public async static Task Run(MinioClient minio, try { Console.Out.WriteLine("Running example for API: RemoveObjectAsync"); - await minio.RemoveObjectAsync(bucketName,objectName); + await minio.RemoveObjectAsync(bucketName, objectName); Console.Out.WriteLine("Removed object " + objectName + " from bucket " + bucketName + " successfully"); Console.Out.WriteLine(); } diff --git a/Minio.Examples/Cases/RemoveObjects.cs b/Minio.Examples/Cases/RemoveObjects.cs index bf3094bfa..e4db83d6f 100644 --- a/Minio.Examples/Cases/RemoveObjects.cs +++ b/Minio.Examples/Cases/RemoveObjects.cs @@ -26,7 +26,7 @@ class RemoveObjects // Remove a list of objects from a bucket public async static Task Run(MinioClient minio, string bucketName = "my-bucket-name", - List objectsList=null) + List objectsList = null) { try { diff --git a/Minio.Examples/Cases/StatObject.cs b/Minio.Examples/Cases/StatObject.cs index 6da7be184..26d05930e 100644 --- a/Minio.Examples/Cases/StatObject.cs +++ b/Minio.Examples/Cases/StatObject.cs @@ -25,7 +25,7 @@ class StatObject // Get stats on a object public async static Task Run(Minio.MinioClient minio, string bucketName = "my-bucket-name", - string bucketObject="my-object-name") + string bucketObject = "my-object-name") { try { @@ -36,7 +36,7 @@ public async static Task Run(Minio.MinioClient minio, } catch (Exception e) { - Console.WriteLine("[StatObject] {0}-{1} Exception: {2}",bucketName, bucketObject, e); + Console.WriteLine("[StatObject] {0}-{1} Exception: {2}", bucketName, bucketObject, e); } } } diff --git a/Minio.Examples/Program.cs b/Minio.Examples/Program.cs index d99741fd3..a76157060 100644 --- a/Minio.Examples/Program.cs +++ b/Minio.Examples/Program.cs @@ -29,7 +29,7 @@ namespace Minio.Examples public class Program { private static Random rnd = new Random(); - private static int UNIT_MB = 1024 * 1024; + private const int UNIT_MB = 1024 * 1024; // Create a file of given size from random byte array private static String CreateFile(int size) @@ -157,18 +157,18 @@ public static void Main(string[] args) // Specify SSE-C source side encryption for Copy operations var sseCpy = new SSECopy(aesEncryption.Key); - // Uncommment to specify SSE-S3 encryption option + // Uncomment to specify SSE-S3 encryption option // var sses3 = new SSES3(); - // Uncommment to specify SSE-KMS encryption option - // var sseKms = new SSEKMS("kms-key",new Dictionary{{ "kms-context", "somevalue"}}); + // Uncomment to specify SSE-KMS encryption option + // var sseKms = new SSEKMS("kms-key", new Dictionary{{ "kms-context", "somevalue"}}); // Upload encrypted object - Cases.PutObject.Run(minioClient, bucketName, objectName, smallFileName,sse:ssec).Wait(); + Cases.PutObject.Run(minioClient, bucketName, objectName, smallFileName, sse:ssec).Wait(); // Copy SSE-C encrypted object to unencrypted object - Cases.CopyObject.Run(minioClient, bucketName, objectName, destBucketName, objectName,sseSrc:sseCpy,sseDest:ssec).Wait(); + Cases.CopyObject.Run(minioClient, bucketName, objectName, destBucketName, objectName, sseSrc:sseCpy, sseDest:ssec).Wait(); // Download SSE-C encrypted object - Cases.FGetObject.Run(minioClient, destBucketName, objectName, bigFileName,sse:ssec).Wait(); + Cases.FGetObject.Run(minioClient, destBucketName, objectName, bigFileName, sse:ssec).Wait(); // List the incomplete uploads Cases.ListIncompleteUploads.Run(minioClient, bucketName); @@ -208,7 +208,7 @@ public static void Main(string[] args) // Delete the object Cases.RemoveObject.Run(minioClient, destBucketName, objectName).Wait(); - // Tacing request with custom logger + // Tracing request with custom logger Cases.CustomRequestLogger.Run(minioClient).Wait(); // Remove the buckets diff --git a/Minio.Functional.Tests/FunctionalTest.cs b/Minio.Functional.Tests/FunctionalTest.cs index 2284dd997..0bab67f6f 100644 --- a/Minio.Functional.Tests/FunctionalTest.cs +++ b/Minio.Functional.Tests/FunctionalTest.cs @@ -32,40 +32,40 @@ namespace Minio.Functional.Tests { public class FunctionalTest { - private static Random rnd = new Random(); - private static int KB = 1024; - private static int MB = 1024 * 1024; + private static readonly Random rnd = new Random(); + private const int KB = 1024; + private const int MB = 1024 * 1024; - private static string dataFile1B = "datafile-1-b"; + private const string dataFile1B = "datafile-1-b"; - private static string dataFile10KB = "datafile-10-kB"; - private static string dataFile6MB = "datafile-6-MB"; + private const string dataFile10KB = "datafile-10-kB"; + private const string dataFile6MB = "datafile-6-MB"; private static RandomStreamGenerator rsg = new RandomStreamGenerator(100 * MB); - private static string makeBucketSignature = "Task MakeBucketAsync(string bucketName, string location = 'us-east-1', CancellationToken cancellationToken = default(CancellationToken))"; - private static string listBucketsSignature = "Task ListBucketsAsync(CancellationToken cancellationToken = default(CancellationToken))"; - private static string bucketExistsSignature = "Task BucketExistsAsync(string bucketName, CancellationToken cancellationToken = default(CancellationToken))"; - private static string removeBucketSignature = "Task RemoveBucketAsync(string bucketName, CancellationToken cancellationToken = default(CancellationToken))"; - private static string listObjectsSignature = "IObservable ListObjectsAsync(string bucketName, string prefix = null, bool recursive = false, CancellationToken cancellationToken = default(CancellationToken))"; - private static string listIncompleteUploadsSignature = "IObservable ListIncompleteUploads(string bucketName, string prefix, bool recursive, CancellationToken cancellationToken = default(CancellationToken))"; - private static string getObjectSignature1 = "Task GetObjectAsync(string bucketName, string objectName, Action callback, CancellationToken cancellationToken = default(CancellationToken))"; - private static string getObjectSignature2 = "Task GetObjectAsync(string bucketName, string objectName, Action callback, CancellationToken cancellationToken = default(CancellationToken))"; - private static string getObjectSignature3 = "Task GetObjectAsync(string bucketName, string objectName, string fileName, CancellationToken cancellationToken = default(CancellationToken))"; - private static string putObjectSignature1 = "Task PutObjectAsync(string bucketName, string objectName, Stream data, long size, string contentType,Dictionary metaData=null, CancellationToken cancellationToken = default(CancellationToken))"; - private static string putObjectSignature2 = "Task PutObjectAsync(string bucketName, string objectName, string filePath, string contentType=null,Dictionary metaData=null, CancellationToken cancellationToken = default(CancellationToken))"; - private static string statObjectSignature = "Task StatObjectAsync(string bucketName, string objectName, CancellationToken cancellationToken = default(CancellationToken))"; - private static string copyObjectSignature = "Task CopyObjectAsync(string bucketName, string objectName, string destBucketName, string destObjectName = null, CopyConditions copyConditions = null, CancellationToken cancellationToken = default(CancellationToken))"; - private static string removeObjectSignature1 = "Task RemoveObjectAsync(string bucketName, string objectName, CancellationToken cancellationToken = default(CancellationToken))"; - private static string removeObjectSignature2 = "Task> RemoveObjectAsync(string bucketName, IEnumerable objectsList, CancellationToken cancellationToken = default(CancellationToken))"; - private static string removeIncompleteUploadSignature = "Task RemoveIncompleteUploadAsync(string bucketName, string objectName, CancellationToken cancellationToken = default(CancellationToken))"; - private static string presignedGetObjectSignature = "Task PresignedGetObjectAsync(string bucketName, string objectName, int expiresInt, Dictionary reqParams = null)"; - private static string presignedPutObjectSignature = "Task PresignedPutObjectAsync(string bucketName, string objectName, int expiresInt)"; - private static string presignedPostPolicySignature = "Task> PresignedPostPolicyAsync(PostPolicy policy)"; - private static string getBucketPolicySignature = "Task GetPolicyAsync(string bucketName,CancellationToken cancellationToken = default(CancellationToken))"; - private static string setBucketPolicySignature = "Task SetPolicyAsync(string bucketName, string policyJson, CancellationToken cancellationToken = default(CancellationToken))"; - private static string getBucketNotificationSignature = "Task GetBucketNotificationAsync(string bucketName, CancellationToken cancellationToken = default(CancellationToken))"; - private static string setBucketNotificationSignature = "Task SetBucketNotificationAsync(string bucketName, BucketNotification notification, CancellationToken cancellationToken = default(CancellationToken))"; - private static string removeAllBucketsNotificationSignature = "Task RemoveAllBucketNotificationsAsync(string bucketName, CancellationToken cancellationToken = default(CancellationToken))"; + private const string makeBucketSignature = "Task MakeBucketAsync(string bucketName, string location = 'us-east-1', CancellationToken cancellationToken = default(CancellationToken))"; + private const string listBucketsSignature = "Task ListBucketsAsync(CancellationToken cancellationToken = default(CancellationToken))"; + private const string bucketExistsSignature = "Task BucketExistsAsync(string bucketName, CancellationToken cancellationToken = default(CancellationToken))"; + private const string removeBucketSignature = "Task RemoveBucketAsync(string bucketName, CancellationToken cancellationToken = default(CancellationToken))"; + private const string listObjectsSignature = "IObservable ListObjectsAsync(string bucketName, string prefix = null, bool recursive = false, CancellationToken cancellationToken = default(CancellationToken))"; + private const string listIncompleteUploadsSignature = "IObservable ListIncompleteUploads(string bucketName, string prefix, bool recursive, CancellationToken cancellationToken = default(CancellationToken))"; + private const string getObjectSignature1 = "Task GetObjectAsync(string bucketName, string objectName, Action callback, CancellationToken cancellationToken = default(CancellationToken))"; + private const string getObjectSignature2 = "Task GetObjectAsync(string bucketName, string objectName, Action callback, CancellationToken cancellationToken = default(CancellationToken))"; + private const string getObjectSignature3 = "Task GetObjectAsync(string bucketName, string objectName, string fileName, CancellationToken cancellationToken = default(CancellationToken))"; + private const string putObjectSignature1 = "Task PutObjectAsync(string bucketName, string objectName, Stream data, long size, string contentType, Dictionary metaData=null, CancellationToken cancellationToken = default(CancellationToken))"; + private const string putObjectSignature2 = "Task PutObjectAsync(string bucketName, string objectName, string filePath, string contentType=null, Dictionary metaData=null, CancellationToken cancellationToken = default(CancellationToken))"; + private const string statObjectSignature = "Task StatObjectAsync(string bucketName, string objectName, CancellationToken cancellationToken = default(CancellationToken))"; + private const string copyObjectSignature = "Task CopyObjectAsync(string bucketName, string objectName, string destBucketName, string destObjectName = null, CopyConditions copyConditions = null, CancellationToken cancellationToken = default(CancellationToken))"; + private const string removeObjectSignature1 = "Task RemoveObjectAsync(string bucketName, string objectName, CancellationToken cancellationToken = default(CancellationToken))"; + private const string removeObjectSignature2 = "Task> RemoveObjectAsync(string bucketName, IEnumerable objectsList, CancellationToken cancellationToken = default(CancellationToken))"; + private const string removeIncompleteUploadSignature = "Task RemoveIncompleteUploadAsync(string bucketName, string objectName, CancellationToken cancellationToken = default(CancellationToken))"; + private const string presignedGetObjectSignature = "Task PresignedGetObjectAsync(string bucketName, string objectName, int expiresInt, Dictionary reqParams = null)"; + private const string presignedPutObjectSignature = "Task PresignedPutObjectAsync(string bucketName, string objectName, int expiresInt)"; + private const string presignedPostPolicySignature = "Task> PresignedPostPolicyAsync(PostPolicy policy)"; + private const string getBucketPolicySignature = "Task GetPolicyAsync(string bucketName, CancellationToken cancellationToken = default(CancellationToken))"; + private const string setBucketPolicySignature = "Task SetPolicyAsync(string bucketName, string policyJson, CancellationToken cancellationToken = default(CancellationToken))"; + private const string getBucketNotificationSignature = "Task GetBucketNotificationAsync(string bucketName, CancellationToken cancellationToken = default(CancellationToken))"; + private const string setBucketNotificationSignature = "Task SetBucketNotificationAsync(string bucketName, BucketNotification notification, CancellationToken cancellationToken = default(CancellationToken))"; + private const string removeAllBucketsNotificationSignature = "Task RemoveAllBucketNotificationsAsync(string bucketName, CancellationToken cancellationToken = default(CancellationToken))"; // Create a file of given size from random byte array or optionally create a symbolic link // to the dataFileName residing in MINT_DATA_DIR @@ -99,16 +99,18 @@ public static String GetRandomName(int length = 5) } return "miniodotnet" + result.ToString(); } + // Return true if running in Mint mode public static bool IsMintEnv() { - return !String.IsNullOrEmpty(Environment.GetEnvironmentVariable("MINT_DATA_DIR")); + return !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("MINT_DATA_DIR")); } + // Get full path of file public static string GetFilePath(string fileName) { var dataDir = Environment.GetEnvironmentVariable("MINT_DATA_DIR"); - if (!String.IsNullOrEmpty(dataDir)) + if (!string.IsNullOrEmpty(dataDir)) { return dataDir + "/" + fileName; } @@ -118,6 +120,7 @@ public static string GetFilePath(string fileName) return path + "/" + fileName; } } + public static void Main(string[] args) { String endPoint = null; @@ -145,7 +148,7 @@ public static void Main(string[] args) } MinioClient minioClient = null; - if (enableHttps.Equals("1")) + if (enableHttps == "1") // WithSSL() enables SSL support in MinIO client minioClient = new MinioClient(endPoint, accessKey, secretKey).WithSSL(); else @@ -167,7 +170,7 @@ public static void Main(string[] args) string runMode = Environment.GetEnvironmentVariable("MINT_MODE"); - if (!String.IsNullOrEmpty(runMode) && runMode.Equals("core")) + if (!string.IsNullOrEmpty(runMode) && runMode == "core") { runCoreTests(minioClient); System.Environment.Exit(0); @@ -254,7 +257,7 @@ public static void Main(string[] args) GetBucketPolicy_Test1(minioClient).Wait(); // Test encryption - if (enableHttps.Equals("1")) + if (enableHttps == "1") { ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true; PutGetStatEncryptedObject_Test1(minioClient).Wait(); @@ -263,7 +266,7 @@ public static void Main(string[] args) EncryptedCopyObject_Test1(minioClient).Wait(); EncryptedCopyObject_Test2(minioClient).Wait(); } - if (kmsEnabled != null && kmsEnabled.Equals("1")) + if (kmsEnabled != null && kmsEnabled == "1") { PutGetStatEncryptedObject_Test3(minioClient).Wait(); EncryptedCopyObject_Test3(minioClient).Wait(); @@ -271,6 +274,7 @@ public static void Main(string[] args) } } + private static void runCoreTests(MinioClient minioClient) { // Check if bucket exists @@ -299,13 +303,14 @@ private static void runCoreTests(MinioClient minioClient) GetBucketPolicy_Test1(minioClient).Wait(); } + private async static Task BucketExists_Test(MinioClient minio) { DateTime startTime = DateTime.Now; string bucketName = GetRandomName(); - Dictionary args = new Dictionary + var args = new Dictionary { - { "bucketName", bucketName}, + { "bucketName", bucketName }, }; try @@ -314,11 +319,11 @@ private async static Task BucketExists_Test(MinioClient minio) bool found = await minio.BucketExistsAsync(bucketName); Assert.IsTrue(found); await minio.RemoveBucketAsync(bucketName); - new MintLogger("BucketExists_Test",bucketExistsSignature,"Tests whether BucketExists passes",TestStatus.PASS,(DateTime.Now - startTime),args:args).Log(); + new MintLogger("BucketExists_Test", bucketExistsSignature, "Tests whether BucketExists passes", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { - new MintLogger("BucketExists_Test",bucketExistsSignature,"Tests whether BucketExists passes",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(),args).Log(); + new MintLogger("BucketExists_Test", bucketExistsSignature, "Tests whether BucketExists passes", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } @@ -326,10 +331,10 @@ private async static Task MakeBucket_Test1(MinioClient minio) { DateTime startTime = DateTime.Now; string bucketName = GetRandomName(length: 60); - Dictionary args = new Dictionary + var args = new Dictionary { - { "bucketName", bucketName}, - {"region","us-east-1"}, + { "bucketName", bucketName }, + { "region", "us-east-1" }, }; try @@ -338,11 +343,11 @@ private async static Task MakeBucket_Test1(MinioClient minio) bool found = await minio.BucketExistsAsync(bucketName); Assert.IsTrue(found); await minio.RemoveBucketAsync(bucketName); - new MintLogger("MakeBucket_Test1",makeBucketSignature,"Tests whether MakeBucket passes",TestStatus.PASS,(DateTime.Now - startTime),args:args).Log(); + new MintLogger("MakeBucket_Test1", makeBucketSignature, "Tests whether MakeBucket passes", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { - new MintLogger("MakeBucket_Test1",makeBucketSignature,"Tests whether MakeBucket passes",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message,ex.ToString(),args).Log(); + new MintLogger("MakeBucket_Test1", makeBucketSignature, "Tests whether MakeBucket passes", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } @@ -350,10 +355,10 @@ private async static Task MakeBucket_Test2(MinioClient minio) { DateTime startTime = DateTime.Now; string bucketName = GetRandomName(length: 10) + ".withperiod"; - Dictionary args = new Dictionary + var args = new Dictionary { - { "bucketName", bucketName}, - {"region","us-east-1"}, + { "bucketName", bucketName }, + { "region", "us-east-1" }, }; string testType = "Test whether make bucket passes when bucketname has a period."; @@ -363,24 +368,25 @@ private async static Task MakeBucket_Test2(MinioClient minio) bool found = await minio.BucketExistsAsync(bucketName); Assert.IsTrue(found); await minio.RemoveBucketAsync(bucketName); - new MintLogger("MakeBucket_Test2",makeBucketSignature, testType,TestStatus.PASS,(DateTime.Now - startTime),args:args).Log(); + new MintLogger("MakeBucket_Test2", makeBucketSignature, testType, TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { - new MintLogger("MakeBucket_Test2",makeBucketSignature,testType,TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(),args).Log(); + new MintLogger("MakeBucket_Test2", makeBucketSignature, testType, TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } + private async static Task MakeBucket_Test3(MinioClient minio, bool aws = false) { if (!aws) return; DateTime startTime = DateTime.Now; string bucketName = GetRandomName(length: 60); - Dictionary args = new Dictionary + var args = new Dictionary { - { "bucketName", bucketName}, - {"region","eu-central-1"}, + { "bucketName", bucketName }, + { "region", "eu-central-1" }, }; try { @@ -393,25 +399,26 @@ private async static Task MakeBucket_Test3(MinioClient minio, bool aws = false) await minio.RemoveBucketAsync(bucketName); } - new MintLogger("MakeBucket_Test3",makeBucketSignature,"Tests whether MakeBucket with region passes",TestStatus.PASS,(DateTime.Now - startTime),args:args).Log(); + new MintLogger("MakeBucket_Test3", makeBucketSignature, "Tests whether MakeBucket with region passes", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { // Assert.AreEqual(ex.message, "Your previous request to create the named bucket succeeded and you already own it."); - new MintLogger("MakeBucket_Test3",makeBucketSignature,"Tests whether MakeBucket with region passes",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(),args).Log(); + new MintLogger("MakeBucket_Test3", makeBucketSignature, "Tests whether MakeBucket with region passes", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } + private async static Task MakeBucket_Test4(MinioClient minio, bool aws = false) { if (!aws) return; DateTime startTime = DateTime.Now; string bucketName = GetRandomName(length: 20) + ".withperiod"; - Dictionary args = new Dictionary + var args = new Dictionary { - { "bucketName", bucketName}, - {"region","us-west-2"}, + { "bucketName", bucketName }, + { "region", "us-west-2" }, }; try { @@ -423,11 +430,11 @@ private async static Task MakeBucket_Test4(MinioClient minio, bool aws = false) await minio.RemoveBucketAsync(bucketName); } - new MintLogger("MakeBucket_Test4",makeBucketSignature,"Tests whether MakeBucket with region and bucketname with . passes",TestStatus.PASS,(DateTime.Now - startTime),args:args).Log(); + new MintLogger("MakeBucket_Test4", makeBucketSignature, "Tests whether MakeBucket with region and bucketname with . passes", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { - new MintLogger("MakeBucket_Test4",makeBucketSignature,"Tests whether MakeBucket with region and bucketname with . passes",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(),args).Log(); + new MintLogger("MakeBucket_Test4", makeBucketSignature, "Tests whether MakeBucket with region and bucketname with . passes", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } @@ -435,9 +442,9 @@ private async static Task RemoveBucket_Test1(MinioClient minio) { DateTime startTime = DateTime.Now; string bucketName = GetRandomName(length: 20); - Dictionary args = new Dictionary + var args = new Dictionary { - { "bucketName", bucketName}, + { "bucketName", bucketName }, }; try { @@ -447,17 +454,18 @@ private async static Task RemoveBucket_Test1(MinioClient minio) await minio.RemoveBucketAsync(bucketName); found = await minio.BucketExistsAsync(bucketName); Assert.IsFalse(found); - new MintLogger("RemoveBucket_Test1",removeBucketSignature,"Tests whether RemoveBucket passes",TestStatus.PASS,(DateTime.Now - startTime),args:args).Log(); + new MintLogger("RemoveBucket_Test1", removeBucketSignature, "Tests whether RemoveBucket passes", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { - new MintLogger("RemoveBucket_Test1",removeBucketSignature,"Tests whether RemoveBucket passes",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(),args).Log(); + new MintLogger("RemoveBucket_Test1", removeBucketSignature, "Tests whether RemoveBucket passes", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } + private async static Task ListBuckets_Test(MinioClient minio) { DateTime startTime = DateTime.Now; - Dictionary args = new Dictionary{}; + var args = new Dictionary(); try { var list = await minio.ListBucketsAsync(); @@ -466,13 +474,14 @@ private async static Task ListBuckets_Test(MinioClient minio) // Ignore continue; } - new MintLogger("ListBuckets_Test",listBucketsSignature,"Tests whether ListBucket passes",TestStatus.PASS,(DateTime.Now - startTime),args:args).Log(); + new MintLogger("ListBuckets_Test", listBucketsSignature, "Tests whether ListBucket passes", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (Exception ex) { - new MintLogger("ListBuckets_Test",listBucketsSignature,"Tests whether ListBucket passes",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(),args).Log(); + new MintLogger("ListBuckets_Test", listBucketsSignature, "Tests whether ListBucket passes", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } + private async static Task Setup_Test(MinioClient minio, string bucketName) { await minio.MakeBucketAsync(bucketName); @@ -484,56 +493,56 @@ private async static Task TearDown(MinioClient minio, string bucketName) { await minio.RemoveBucketAsync(bucketName); } + private async static Task PutObject_Test1(MinioClient minio) { DateTime startTime = DateTime.Now; string bucketName = GetRandomName(15); string objectName = GetRandomName(10); string contentType = "application/octet-stream"; - Dictionary args = new Dictionary + var args = new Dictionary { - { "bucketName", bucketName}, - {"objectName",objectName}, - {"contentType", contentType}, - {"size","1MB"} + { "bucketName", bucketName }, + { "objectName", objectName }, + { "contentType", contentType }, + { "size", "1MB" } }; try { await Setup_Test(minio, bucketName); await PutObject_Tester(minio, bucketName, objectName, null, contentType, 0, null, rsg.GenerateStreamFromSeed(1 * KB)); await TearDown(minio, bucketName); - new MintLogger("PutObject_Test1",putObjectSignature1,"Tests whether PutObject passes for small object",TestStatus.PASS,(DateTime.Now - startTime),args:args).Log(); + new MintLogger("PutObject_Test1", putObjectSignature1, "Tests whether PutObject passes for small object", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (Exception ex) { - new MintLogger("PutObject_Test1",putObjectSignature1,"Tests whether PutObject passes for small object",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(),args).Log(); + new MintLogger("PutObject_Test1", putObjectSignature1, "Tests whether PutObject passes for small object", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } - private async static Task PutObject_Test2(MinioClient minio) { DateTime startTime = DateTime.Now; string bucketName = GetRandomName(15); string objectName = GetRandomName(10); string contentType = "application/octet-stream"; - Dictionary args = new Dictionary + var args = new Dictionary { - { "bucketName", bucketName}, - {"objectName",objectName}, - {"contentType", contentType}, - {"size","6MB"} + { "bucketName", bucketName }, + { "objectName", objectName }, + { "contentType", contentType }, + { "size", "6MB" } }; try { await Setup_Test(minio, bucketName); await PutObject_Tester(minio, bucketName, objectName, null, contentType, 0, null, rsg.GenerateStreamFromSeed(6 * MB)); await TearDown(minio, bucketName); - new MintLogger("PutObject_Test2",putObjectSignature1,"Tests whether multipart PutObject passes",TestStatus.PASS,(DateTime.Now - startTime),args:args).Log(); + new MintLogger("PutObject_Test2", putObjectSignature1, "Tests whether multipart PutObject passes", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (Exception ex) { - new MintLogger("PutObject_Test2",putObjectSignature1,"Tests whether multipart PutObject passes",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(),args).Log(); + new MintLogger("PutObject_Test2", putObjectSignature1, "Tests whether multipart PutObject passes", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } @@ -543,12 +552,12 @@ private async static Task PutObject_Test3(MinioClient minio) string bucketName = GetRandomName(15); string objectName = GetRandomName(10); string contentType = "custom-contenttype"; - Dictionary args = new Dictionary + var args = new Dictionary { - { "bucketName", bucketName}, - {"objectName",objectName}, - {"contentType", contentType}, - {"size","1MB"} + { "bucketName", bucketName }, + { "objectName", objectName }, + { "contentType", contentType }, + { "size", "1MB" } }; try @@ -556,13 +565,14 @@ private async static Task PutObject_Test3(MinioClient minio) await Setup_Test(minio, bucketName); await PutObject_Tester(minio, bucketName, objectName, null, contentType, 0, null, rsg.GenerateStreamFromSeed(1 * KB)); await TearDown(minio, bucketName); - new MintLogger("PutObject_Test3",putObjectSignature1,"Tests whether PutObject with custom content-type passes",TestStatus.PASS,(DateTime.Now - startTime),args:args).Log(); + new MintLogger("PutObject_Test3", putObjectSignature1, "Tests whether PutObject with custom content-type passes", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (Exception ex) { - new MintLogger("PutObject_Test3",putObjectSignature1,"Tests whether PutObject with custom content-type passes",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(),args).Log(); + new MintLogger("PutObject_Test3", putObjectSignature1, "Tests whether PutObject with custom content-type passes", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } + private async static Task PutObject_Test4(MinioClient minio) { DateTime startTime = DateTime.Now; @@ -570,17 +580,18 @@ private async static Task PutObject_Test4(MinioClient minio) string objectName = GetRandomName(10); string fileName = CreateFile(1, dataFile1B); string contentType = "custom/contenttype"; - Dictionary metaData = new Dictionary(){ - { "x-amz-meta-customheader", "minio dotnet"} + var metaData = new Dictionary + { + { "x-amz-meta-customheader", "minio dotnet" } }; - Dictionary args = new Dictionary - { - { "bucketName", bucketName}, - {"objectName",objectName}, - {"contentType", contentType}, - {"data","1B"}, - {"size","1B"}, - {"metaData","x-amz-meta-customheader:minio-dotnet"} + var args = new Dictionary + { + { "bucketName", bucketName }, + { "objectName", objectName }, + { "contentType", contentType }, + { "data", "1B" }, + { "size", "1B" }, + { "metaData", "x-amz-meta-customheader:minio-dotnet" } }; try { @@ -588,88 +599,91 @@ private async static Task PutObject_Test4(MinioClient minio) ObjectStat statObject = await PutObject_Tester(minio, bucketName, objectName, fileName, contentType: contentType, metaData: metaData); Assert.IsTrue(statObject != null); Assert.IsTrue(statObject.metaData != null); - Dictionary statMeta = new Dictionary(statObject.metaData, StringComparer.OrdinalIgnoreCase); + var statMeta = new Dictionary(statObject.metaData, StringComparer.OrdinalIgnoreCase); Assert.IsTrue(statMeta.ContainsKey("x-amz-meta-customheader")); Assert.IsTrue(statObject.metaData.ContainsKey("Content-Type") && statObject.metaData["Content-Type"].Equals("custom/contenttype")); await TearDown(minio, bucketName); - new MintLogger("PutObject_Test4",putObjectSignature1,"Tests whether PutObject with different content-type passes",TestStatus.PASS,(DateTime.Now - startTime), args:args).Log(); + new MintLogger("PutObject_Test4", putObjectSignature1, "Tests whether PutObject with different content-type passes", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { - new MintLogger("PutObject_Test4",putObjectSignature1,"Tests whether PutObject with different content-type passes",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(),args).Log(); + new MintLogger("PutObject_Test4", putObjectSignature1, "Tests whether PutObject with different content-type passes", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } if (!IsMintEnv()) { File.Delete(fileName); } } + private async static Task PutObject_Test5(MinioClient minio) { DateTime startTime = DateTime.Now; string bucketName = GetRandomName(15); string objectName = GetRandomName(10); - Dictionary args = new Dictionary + var args = new Dictionary { - { "bucketName", bucketName}, - {"objectName",objectName}, - {"data","1B"}, - {"size","1B"}, + { "bucketName", bucketName }, + { "objectName", objectName }, + { "data", "1B" }, + { "size", "1B" }, }; try { await Setup_Test(minio, bucketName); await PutObject_Tester(minio, bucketName, objectName, null, null, 0, null, rsg.GenerateStreamFromSeed(1)); await TearDown(minio, bucketName); - new MintLogger("PutObject_Test5",putObjectSignature1,"Tests whether PutObject with no content-type passes for small object",TestStatus.PASS,(DateTime.Now - startTime),args:args).Log(); + new MintLogger("PutObject_Test5", putObjectSignature1, "Tests whether PutObject with no content-type passes for small object", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (Exception ex) { - new MintLogger("PutObject_Test5",putObjectSignature1,"Tests whether PutObject with no content-type passes for small object",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(), args).Log(); + new MintLogger("PutObject_Test5", putObjectSignature1, "Tests whether PutObject with no content-type passes for small object", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } + private async static Task PutObject_Test6(MinioClient minio) { DateTime startTime = DateTime.Now; string bucketName = GetRandomName(15); string objectName = "parallelput"; - Dictionary args = new Dictionary + var args = new Dictionary { - { "bucketName", bucketName}, - {"objectName",objectName}, - {"data","10KB"}, - {"size","10KB"}, + { "bucketName", bucketName }, + { "objectName", objectName }, + { "data", "10KB" }, + { "size", "10KB" }, }; try { await Setup_Test(minio, bucketName); Task[] tasks = new Task[7]; for (int i = 0; i < 7; i++) { - tasks[i]= PutObject_Task(minio, bucketName, objectName, null, null, 0, null, rsg.GenerateStreamFromSeed(10*KB)); + tasks[i] = PutObject_Task(minio, bucketName, objectName, null, null, 0, null, rsg.GenerateStreamFromSeed(10*KB)); } await Task.WhenAll(tasks); await minio.RemoveObjectAsync(bucketName, objectName); await TearDown(minio, bucketName); - new MintLogger("PutObject_Test6",putObjectSignature1,"Tests thread safety of minioclient on a parallel put operation",TestStatus.PASS,(DateTime.Now - startTime), args:args).Log(); + new MintLogger("PutObject_Test6", putObjectSignature1, "Tests thread safety of minioclient on a parallel put operation", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (Exception ex) { - new MintLogger("PutObject_Test6",putObjectSignature1,"Tests thread safety of minioclient on a parallel put operation",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(), args).Log(); + new MintLogger("PutObject_Test6", putObjectSignature1, "Tests thread safety of minioclient on a parallel put operation", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } + private async static Task PutObject_Test7(MinioClient minio) { DateTime startTime = DateTime.Now; string bucketName = GetRandomName(15); string objectName = GetRandomName(10); string contentType = "application/octet-stream"; - Dictionary args = new Dictionary + var args = new Dictionary { - { "bucketName", bucketName}, - {"objectName",objectName}, - {"contentType", contentType}, - {"data","10KB"}, - {"size","-1"}, + { "bucketName", bucketName }, + { "objectName", objectName }, + { "contentType", contentType }, + { "data", "10KB" }, + { "size", "-1" }, }; try { @@ -689,26 +703,27 @@ await minio.PutObjectAsync(bucketName, await minio.RemoveObjectAsync(bucketName, objectName); await TearDown(minio, bucketName); } - new MintLogger("PutObject_Test7",putObjectSignature1,"Tests whether PutObject with unknown stream-size passes",TestStatus.PASS,(DateTime.Now - startTime), args:args).Log(); + new MintLogger("PutObject_Test7", putObjectSignature1, "Tests whether PutObject with unknown stream-size passes", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (Exception ex) { - new MintLogger("PutObject_Test7",putObjectSignature1,"Tests whether PutObject with unknown stream-size passes",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(), args).Log(); + new MintLogger("PutObject_Test7", putObjectSignature1, "Tests whether PutObject with unknown stream-size passes", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } + private async static Task PutObject_Test8(MinioClient minio) { DateTime startTime = DateTime.Now; string bucketName = GetRandomName(15); string objectName = GetRandomName(10); string contentType = "application/octet-stream"; - Dictionary args = new Dictionary + var args = new Dictionary { - { "bucketName", bucketName}, - {"objectName",objectName}, - {"contentType", contentType}, - {"data","0B"}, - {"size","-1"}, + { "bucketName", bucketName }, + { "objectName", objectName }, + { "contentType", contentType }, + { "data", "0B" }, + { "size", "-1" }, }; try { @@ -727,26 +742,27 @@ await minio.PutObjectAsync(bucketName, await minio.RemoveObjectAsync(bucketName, objectName); await TearDown(minio, bucketName); } - new MintLogger("PutObject_Test8",putObjectSignature1,"Tests PutObject where unknown stream sends 0 bytes",TestStatus.PASS,(DateTime.Now - startTime), args:args).Log(); + new MintLogger("PutObject_Test8", putObjectSignature1, "Tests PutObject where unknown stream sends 0 bytes", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (Exception ex) { - new MintLogger("PutObject_Test8",putObjectSignature1,"Tests PutObject where unknown stream sends 0 bytes",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(), args).Log(); + new MintLogger("PutObject_Test8", putObjectSignature1, "Tests PutObject where unknown stream sends 0 bytes", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } + private async static Task PutGetStatEncryptedObject_Test1(MinioClient minio) { DateTime startTime = DateTime.Now; string bucketName = GetRandomName(15); string objectName = GetRandomName(10); string contentType = "application/octet-stream"; - Dictionary args = new Dictionary + var args = new Dictionary { - { "bucketName", bucketName}, - {"objectName",objectName}, - {"contentType", contentType}, - {"data","1KB"}, - {"size","1KB"}, + { "bucketName", bucketName }, + { "objectName", objectName }, + { "contentType", contentType }, + { "data", "1KB" }, + { "size", "1KB" }, }; try { @@ -766,7 +782,7 @@ await minio.PutObjectAsync(bucketName, objectName, filestream, filestream.Length, - contentType,sse: ssec); + contentType, sse: ssec); await minio.GetObjectAsync(bucketName, objectName, (stream) => @@ -779,33 +795,33 @@ await minio.GetObjectAsync(bucketName, objectName, Assert.AreEqual(file_read_size, file_write_size); File.Delete(tempFileName); - },sse:ssec); - await minio.StatObjectAsync(bucketName, objectName,sse:ssec); + }, sse:ssec); + await minio.StatObjectAsync(bucketName, objectName, sse:ssec); await minio.RemoveObjectAsync(bucketName, objectName); } await TearDown(minio, bucketName); - new MintLogger("PutGetStatEncryptedObject_Test1",putObjectSignature1,"Tests whether Put/Get/Stat Object with encryption passes",TestStatus.PASS,(DateTime.Now - startTime), args:args).Log(); + new MintLogger("PutGetStatEncryptedObject_Test1", putObjectSignature1, "Tests whether Put/Get/Stat Object with encryption passes", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (Exception ex) { - new MintLogger("PutGetStatEncryptedObject_Test1",putObjectSignature1,"Tests whether Put/Get/Stat Object with encryption passes",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(), args).Log(); + new MintLogger("PutGetStatEncryptedObject_Test1", putObjectSignature1, "Tests whether Put/Get/Stat Object with encryption passes", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } - private async static Task PutGetStatEncryptedObject_Test2(MinioClient minio) + private async static Task PutGetStatEncryptedObject_Test2(MinioClient minio) { DateTime startTime = DateTime.Now; string bucketName = GetRandomName(15); string objectName = GetRandomName(10); string contentType = "application/octet-stream"; - Dictionary args = new Dictionary + var args = new Dictionary { - { "bucketName", bucketName}, - {"objectName",objectName}, - {"contentType", contentType}, - {"data","6MB"}, - {"size","6MB"}, + { "bucketName", bucketName }, + { "objectName", objectName }, + { "contentType", contentType }, + { "data", "6MB" }, + { "size", "6MB" }, }; try { @@ -825,7 +841,7 @@ await minio.PutObjectAsync(bucketName, objectName, filestream, filestream.Length, - contentType,sse: ssec); + contentType, sse: ssec); await minio.GetObjectAsync(bucketName, objectName, (stream) => @@ -838,33 +854,33 @@ await minio.GetObjectAsync(bucketName, objectName, Assert.AreEqual(file_read_size, file_write_size); File.Delete(tempFileName); - },sse:ssec); - await minio.StatObjectAsync(bucketName, objectName,sse:ssec); + }, sse:ssec); + await minio.StatObjectAsync(bucketName, objectName, sse:ssec); await minio.RemoveObjectAsync(bucketName, objectName); } await TearDown(minio, bucketName); - new MintLogger("PutGetStatEncryptedObject_Test2",putObjectSignature1,"Tests whether Put/Get/Stat multipart upload with encryption passes",TestStatus.PASS,(DateTime.Now - startTime), args:args).Log(); + new MintLogger("PutGetStatEncryptedObject_Test2", putObjectSignature1, "Tests whether Put/Get/Stat multipart upload with encryption passes", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (Exception ex) { - new MintLogger("PutGetStatEncryptedObject_Test2",putObjectSignature2,"Tests whether Put/Get/Stat multipart upload with encryption passes",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(), args).Log(); + new MintLogger("PutGetStatEncryptedObject_Test2", putObjectSignature2, "Tests whether Put/Get/Stat multipart upload with encryption passes", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } - private async static Task PutGetStatEncryptedObject_Test3(MinioClient minio) + private async static Task PutGetStatEncryptedObject_Test3(MinioClient minio) { DateTime startTime = DateTime.Now; string bucketName = GetRandomName(15); string objectName = GetRandomName(10); string contentType = "application/octet-stream"; - Dictionary args = new Dictionary + var args = new Dictionary { - { "bucketName", bucketName}, - {"objectName",objectName}, - {"contentType", contentType}, - {"data","6MB"}, - {"size","6MB"}, + { "bucketName", bucketName }, + { "objectName", objectName }, + { "contentType", contentType }, + { "data", "6MB" }, + { "size", "6MB" }, }; try { @@ -882,7 +898,7 @@ await minio.PutObjectAsync(bucketName, objectName, filestream, filestream.Length, - contentType,sse: sses3); + contentType, sse: sses3); await minio.GetObjectAsync(bucketName, objectName, (stream) => @@ -901,13 +917,14 @@ await minio.GetObjectAsync(bucketName, objectName, } await TearDown(minio, bucketName); - new MintLogger("PutGetStatEncryptedObject_Test3",putObjectSignature1,"Tests whether Put/Get/Stat multipart upload with encryption passes",TestStatus.PASS,(DateTime.Now - startTime), args:args).Log(); + new MintLogger("PutGetStatEncryptedObject_Test3", putObjectSignature1, "Tests whether Put/Get/Stat multipart upload with encryption passes", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (Exception ex) { - new MintLogger("PutGetStatEncryptedObject_Test3",putObjectSignature2,"Tests whether Put/Get/Stat multipart upload with encryption passes",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(), args).Log(); + new MintLogger("PutGetStatEncryptedObject_Test3", putObjectSignature2, "Tests whether Put/Get/Stat multipart upload with encryption passes", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } + private async static Task PutObject_Task(MinioClient minio, string bucketName, string objectName, string fileName = null, string contentType = "application/octet-stream", long size = 0, Dictionary metaData = null, MemoryStream mstream = null) { DateTime startTime = DateTime.Now; @@ -935,6 +952,7 @@ await minio.PutObjectAsync(bucketName, File.Delete(tempFileName); } } + private async static Task PutObject_Tester(MinioClient minio, string bucketName, string objectName, string fileName = null, string contentType = "application/octet-stream", long size = 0, Dictionary metaData = null, MemoryStream mstream = null) { ObjectStat statObject = null; @@ -984,19 +1002,20 @@ await minio.GetObjectAsync(bucketName, objectName, } return statObject; } + private async static Task StatObject_Test1(MinioClient minio) { DateTime startTime = DateTime.Now; string bucketName = GetRandomName(15); string objectName = GetRandomName(10); string contentType = "gzip"; - Dictionary args = new Dictionary + var args = new Dictionary { - { "bucketName", bucketName}, - {"objectName",objectName}, - {"contentType", contentType}, - {"data","1KB"}, - {"size","1KB"}, + { "bucketName", bucketName }, + { "objectName", objectName }, + { "contentType", contentType }, + { "data", "1KB" }, + { "size", "1KB" }, }; try { @@ -1004,11 +1023,11 @@ private async static Task StatObject_Test1(MinioClient minio) await PutObject_Tester(minio, bucketName, objectName, null, null, 0, null, rsg.GenerateStreamFromSeed(1 * KB)); await TearDown(minio, bucketName); - new MintLogger("StatObject_Test1",statObjectSignature,"Tests whether StatObject passes",TestStatus.PASS,(DateTime.Now - startTime), args:args).Log(); + new MintLogger("StatObject_Test1", statObjectSignature, "Tests whether StatObject passes", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { - new MintLogger("StatObject_Test1",statObjectSignature,"Tests whether StatObject passes",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(), args).Log(); + new MintLogger("StatObject_Test1", statObjectSignature, "Tests whether StatObject passes", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } @@ -1019,14 +1038,14 @@ private async static Task CopyObject_Test1(MinioClient minio) string objectName = GetRandomName(10); string destBucketName = GetRandomName(15); string destObjectName = GetRandomName(10); - Dictionary args = new Dictionary - { - {"bucketName", bucketName}, - {"objectName",objectName}, - {"destBucketName", destBucketName}, - {"destObjectName", destObjectName}, - {"data","1KB"}, - {"size","1KB"}, + var args = new Dictionary + { + { "bucketName", bucketName }, + { "objectName", objectName }, + { "destBucketName", destBucketName }, + { "destObjectName", destObjectName }, + { "data", "1KB" }, + { "size", "1KB" }, }; try { @@ -1051,11 +1070,11 @@ await minio.PutObjectAsync(bucketName, await TearDown(minio, bucketName); await TearDown(minio, destBucketName); - new MintLogger("CopyObject_Test1",copyObjectSignature,"Tests whether CopyObject passes",TestStatus.PASS,(DateTime.Now - startTime), args:args).Log(); + new MintLogger("CopyObject_Test1", copyObjectSignature, "Tests whether CopyObject passes", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { - new MintLogger("CopyObject_Test1",copyObjectSignature,"Tests whether CopyObject passes",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(),args).Log(); + new MintLogger("CopyObject_Test1", copyObjectSignature, "Tests whether CopyObject passes", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } @@ -1066,14 +1085,14 @@ private async static Task CopyObject_Test2(MinioClient minio) string objectName = GetRandomName(10); string destBucketName = GetRandomName(15); string destObjectName = GetRandomName(10); - Dictionary args = new Dictionary - { - {"bucketName", bucketName}, - {"objectName",objectName}, - {"destBucketName", destBucketName}, - {"destObjectName", destObjectName}, - {"data","1KB"}, - {"size","1KB"}, + var args = new Dictionary + { + { "bucketName", bucketName }, + { "objectName", objectName }, + { "destBucketName", destBucketName }, + { "destObjectName", destObjectName }, + { "data", "1KB" }, + { "size", "1KB" }, }; try { @@ -1104,13 +1123,14 @@ await minio.PutObjectAsync(bucketName, await TearDown(minio, bucketName); await TearDown(minio, destBucketName); - new MintLogger("CopyObject_Test2",copyObjectSignature,"Tests whether CopyObject with Etag mismatch passes",TestStatus.PASS,(DateTime.Now - startTime), args:args).Log(); + new MintLogger("CopyObject_Test2", copyObjectSignature, "Tests whether CopyObject with Etag mismatch passes", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { - new MintLogger("CopyObject_Test2",copyObjectSignature, "Tests whether CopyObject with Etag mismatch passes",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(), args).Log(); + new MintLogger("CopyObject_Test2", copyObjectSignature, "Tests whether CopyObject with Etag mismatch passes", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } + private async static Task CopyObject_Test3(MinioClient minio) { DateTime startTime = DateTime.Now; @@ -1118,14 +1138,14 @@ private async static Task CopyObject_Test3(MinioClient minio) string objectName = GetRandomName(10); string destBucketName = GetRandomName(15); string destObjectName = GetRandomName(10); - Dictionary args = new Dictionary - { - {"bucketName", bucketName}, - {"objectName",objectName}, - {"destBucketName", destBucketName}, - {"destObjectName", destObjectName}, - {"data","1KB"}, - {"size","1KB"}, + var args = new Dictionary + { + { "bucketName", bucketName }, + { "objectName", objectName }, + { "destBucketName", destBucketName }, + { "destObjectName", destObjectName }, + { "data", "1KB" }, + { "size", "1KB" }, }; try { @@ -1156,14 +1176,15 @@ await minio.PutObjectAsync(bucketName, await TearDown(minio, bucketName); await TearDown(minio, destBucketName); - new MintLogger("CopyObject_Test3",copyObjectSignature,"Tests whether CopyObject with Etag match passes",TestStatus.PASS,(DateTime.Now - startTime),args:args).Log(); + new MintLogger("CopyObject_Test3", copyObjectSignature, "Tests whether CopyObject with Etag match passes", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { - new MintLogger("CopyObject_Test3",copyObjectSignature,"Tests whether CopyObject with Etag match passes",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(),args).Log(); + new MintLogger("CopyObject_Test3", copyObjectSignature, "Tests whether CopyObject with Etag match passes", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } + private async static Task CopyObject_Test4(MinioClient minio) { DateTime startTime = DateTime.Now; @@ -1171,13 +1192,13 @@ private async static Task CopyObject_Test4(MinioClient minio) string objectName = GetRandomName(10); string destBucketName = GetRandomName(15); string destObjectName = GetRandomName(10); - Dictionary args = new Dictionary + var args = new Dictionary { - {"bucketName", bucketName}, - {"objectName",objectName}, - {"destBucketName", destBucketName}, - {"data","1KB"}, - {"size","1KB"}, + { "bucketName", bucketName }, + { "objectName", objectName }, + { "destBucketName", destBucketName }, + { "data", "1KB" }, + { "size", "1KB" }, }; try { @@ -1206,29 +1227,30 @@ await minio.PutObjectAsync(bucketName, await minio.RemoveObjectAsync(destBucketName, objectName); await TearDown(minio, bucketName); await TearDown(minio, destBucketName); - new MintLogger("CopyObject_Test4",copyObjectSignature,"Tests whether CopyObject defaults targetName to objectName",TestStatus.PASS,(DateTime.Now - startTime),args:args).Log(); + new MintLogger("CopyObject_Test4", copyObjectSignature, "Tests whether CopyObject defaults targetName to objectName", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { - new MintLogger("CopyObject_Test4",copyObjectSignature,"Tests whether CopyObject defaults targetName to objectName",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(),args).Log(); + new MintLogger("CopyObject_Test4", copyObjectSignature, "Tests whether CopyObject defaults targetName to objectName", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } + private async static Task CopyObject_Test5(MinioClient minio) { DateTime startTime = DateTime.Now; - string bucketName = GetRandomName(15); + string bucketName = GetRandomName(15); string objectName = GetRandomName(10); string destBucketName = GetRandomName(15); string destObjectName = GetRandomName(10); - Dictionary args = new Dictionary - { - {"bucketName", bucketName}, - {"objectName",objectName}, - {"destBucketName", destBucketName}, - {"destObjectName", destObjectName}, - {"data","6MB"}, - {"size","6MB"}, + var args = new Dictionary + { + { "bucketName", bucketName }, + { "objectName", objectName }, + { "destBucketName", destBucketName }, + { "destObjectName", destObjectName }, + { "data", "6MB" }, + { "size", "6MB" }, }; try { @@ -1261,17 +1283,17 @@ await minio.PutObjectAsync(bucketName, await TearDown(minio, bucketName); await TearDown(minio, destBucketName); - new MintLogger("CopyObject_Test5",copyObjectSignature,"Tests whether CopyObject multi-part copy upload for large files works",TestStatus.PASS,(DateTime.Now - startTime),args:args).Log(); + new MintLogger("CopyObject_Test5", copyObjectSignature, "Tests whether CopyObject multi-part copy upload for large files works", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { if (ex.message.Equals("A header you provided implies functionality that is not implemented")) { - new MintLogger("CopyObject_Test5",copyObjectSignature,"Tests whether CopyObject multi-part copy upload for large files works",TestStatus.NA,(DateTime.Now - startTime),args:args).Log(); + new MintLogger("CopyObject_Test5", copyObjectSignature, "Tests whether CopyObject multi-part copy upload for large files works", TestStatus.NA, (DateTime.Now - startTime), args:args).Log(); } else { - new MintLogger("CopyObject_Test5",copyObjectSignature,"Tests whether CopyObject multi-part copy upload for large files works",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(),args).Log(); + new MintLogger("CopyObject_Test5", copyObjectSignature, "Tests whether CopyObject multi-part copy upload for large files works", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } @@ -1284,14 +1306,14 @@ private async static Task CopyObject_Test6(MinioClient minio) string objectName = GetRandomName(10); string destBucketName = GetRandomName(15); string destObjectName = GetRandomName(10); - Dictionary args = new Dictionary - { - {"bucketName", bucketName}, - {"objectName",objectName}, - {"destBucketName", destBucketName}, - {"destObjectName", destObjectName}, - {"data","1KB"}, - {"size","1KB"}, + var args = new Dictionary + { + { "bucketName", bucketName }, + { "objectName", objectName }, + { "destBucketName", destBucketName }, + { "destObjectName", destObjectName }, + { "data", "1KB" }, + { "size", "1KB" }, }; try { @@ -1323,14 +1345,15 @@ await minio.PutObjectAsync(bucketName, await TearDown(minio, bucketName); await TearDown(minio, destBucketName); - new MintLogger("CopyObject_Test6",copyObjectSignature,"Tests whether CopyObject with positive test for modified date passes",TestStatus.PASS,(DateTime.Now - startTime),args:args).Log(); + new MintLogger("CopyObject_Test6", copyObjectSignature, "Tests whether CopyObject with positive test for modified date passes", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { - new MintLogger("CopyObject_Test6",copyObjectSignature,"Tests whether CopyObject with positive test for modified date passes",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(),args).Log(); + new MintLogger("CopyObject_Test6", copyObjectSignature, "Tests whether CopyObject with positive test for modified date passes", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } + private async static Task CopyObject_Test7(MinioClient minio) { DateTime startTime = DateTime.Now; @@ -1338,14 +1361,14 @@ private async static Task CopyObject_Test7(MinioClient minio) string objectName = GetRandomName(10); string destBucketName = GetRandomName(15); string destObjectName = GetRandomName(10); - Dictionary args = new Dictionary - { - {"bucketName", bucketName}, - {"objectName",objectName}, - {"destBucketName", destBucketName}, - {"destObjectName", destObjectName}, - {"data","1KB"}, - {"size","1KB"}, + var args = new Dictionary + { + { "bucketName", bucketName }, + { "objectName", objectName }, + { "destBucketName", destBucketName }, + { "destObjectName", destObjectName }, + { "data", "1KB" }, + { "size", "1KB" }, }; try { @@ -1372,7 +1395,7 @@ await minio.PutObjectAsync(bucketName, } catch (Exception ex) { - Assert.AreEqual("MinIO API responded with message=At least one of the pre-conditions you specified did not hold",ex.Message); + Assert.AreEqual("MinIO API responded with message=At least one of the pre-conditions you specified did not hold", ex.Message); } await minio.RemoveObjectAsync(bucketName, objectName); @@ -1380,11 +1403,11 @@ await minio.PutObjectAsync(bucketName, await TearDown(minio, bucketName); await TearDown(minio, destBucketName); - new MintLogger("CopyObject_Test7",copyObjectSignature,"Tests whether CopyObject with negative test for modified date passes",TestStatus.PASS,(DateTime.Now - startTime),args:args).Log(); + new MintLogger("CopyObject_Test7", copyObjectSignature, "Tests whether CopyObject with negative test for modified date passes", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { - new MintLogger("CopyObject_Test7",copyObjectSignature,"Tests whether CopyObject with negative test for modified date passes",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(),args).Log(); + new MintLogger("CopyObject_Test7", copyObjectSignature, "Tests whether CopyObject with negative test for modified date passes", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } @@ -1396,15 +1419,15 @@ private async static Task CopyObject_Test8(MinioClient minio) string objectName = GetRandomName(10); string destBucketName = GetRandomName(15); string destObjectName = GetRandomName(10); - Dictionary args = new Dictionary - { - {"bucketName", bucketName}, - {"objectName",objectName}, - {"destBucketName", destBucketName}, - {"destObjectName", destObjectName}, - {"data","1KB"}, - {"size","1KB"}, - {"copyconditions","x-amz-metadata-directive:REPLACE"}, + var args = new Dictionary + { + { "bucketName", bucketName }, + { "objectName", objectName }, + { "destBucketName", destBucketName }, + { "destObjectName", destObjectName }, + { "data", "1KB" }, + { "size", "1KB" }, + { "copyconditions", "x-amz-metadata-directive:REPLACE" }, }; try { @@ -1414,7 +1437,7 @@ private async static Task CopyObject_Test8(MinioClient minio) { await minio.PutObjectAsync(bucketName, objectName, - filestream, filestream.Length, metaData:new Dictionary{{"X-Amz-Meta-Orig", "orig-val with spaces"}}); + filestream, filestream.Length, metaData:new Dictionary{{"X-Amz-Meta-Orig", "orig-val with spaces"}}); } ObjectStat stats = await minio.StatObjectAsync(bucketName, objectName); @@ -1424,12 +1447,12 @@ await minio.PutObjectAsync(bucketName, copyCond.SetReplaceMetadataDirective(); // set custom metadata - Dictionary metadata = new Dictionary() + var metadata = new Dictionary { - { "Content-Type", "application/css"}, - {"X-Amz-Meta-Mynewkey","test test"} + { "Content-Type", "application/css" }, + { "X-Amz-Meta-Mynewkey", "test test" } }; - await minio.CopyObjectAsync(bucketName, objectName, destBucketName, destObjectName,copyConditions:copyCond,metadata: metadata); + await minio.CopyObjectAsync(bucketName, objectName, destBucketName, destObjectName, copyConditions:copyCond, metadata: metadata); ObjectStat dstats = await minio.StatObjectAsync(destBucketName, destObjectName); Assert.IsTrue(dstats.metaData["X-Amz-Meta-Mynewkey"] != null); @@ -1439,11 +1462,11 @@ await minio.PutObjectAsync(bucketName, await TearDown(minio, bucketName); await TearDown(minio, destBucketName); - new MintLogger("CopyObject_Test8",copyObjectSignature,"Tests whether CopyObject with metadata replacement passes",TestStatus.PASS,(DateTime.Now - startTime), args:args).Log(); + new MintLogger("CopyObject_Test8", copyObjectSignature, "Tests whether CopyObject with metadata replacement passes", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { - new MintLogger("CopyObject_Test8",copyObjectSignature,"Tests whether CopyObject with metadata replacement passes",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(),args).Log(); + new MintLogger("CopyObject_Test8", copyObjectSignature, "Tests whether CopyObject with metadata replacement passes", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } @@ -1454,14 +1477,14 @@ private async static Task EncryptedCopyObject_Test1(MinioClient minio) string objectName = GetRandomName(10); string destBucketName = GetRandomName(15); string destObjectName = GetRandomName(10); - Dictionary args = new Dictionary - { - {"bucketName", bucketName}, - {"objectName",objectName}, - {"destBucketName", destBucketName}, - {"destObjectName", destObjectName}, - {"data","1KB"}, - {"size","1KB"}, + var args = new Dictionary + { + { "bucketName", bucketName }, + { "objectName", objectName }, + { "destBucketName", destBucketName }, + { "destObjectName", destObjectName }, + { "data", "1KB" }, + { "size", "1KB" }, }; try { @@ -1484,10 +1507,10 @@ await minio.PutObjectAsync(bucketName, filestream, filestream.Length, null, sse:ssec); } - await minio.CopyObjectAsync(bucketName, objectName, destBucketName, destObjectName,sseSrc:sseCpy,sseDest:ssecDst); + await minio.CopyObjectAsync(bucketName, objectName, destBucketName, destObjectName, sseSrc:sseCpy, sseDest:ssecDst); string outFileName = "outFileName"; - await minio.GetObjectAsync(destBucketName, destObjectName, outFileName,sse:ssecDst); + await minio.GetObjectAsync(destBucketName, destObjectName, outFileName, sse:ssecDst); File.Delete(outFileName); await minio.RemoveObjectAsync(bucketName, objectName); await minio.RemoveObjectAsync(destBucketName, destObjectName); @@ -1495,11 +1518,11 @@ await minio.PutObjectAsync(bucketName, await TearDown(minio, bucketName); await TearDown(minio, destBucketName); - new MintLogger("EncryptedCopyObject_Test1",copyObjectSignature,"Tests whether encrypted CopyObject passes",TestStatus.PASS,(DateTime.Now - startTime), args:args).Log(); + new MintLogger("EncryptedCopyObject_Test1", copyObjectSignature, "Tests whether encrypted CopyObject passes", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { - new MintLogger("EncryptedCopyObject_Test1",copyObjectSignature,"Tests whether encrypted CopyObject passes",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(),args).Log(); + new MintLogger("EncryptedCopyObject_Test1", copyObjectSignature, "Tests whether encrypted CopyObject passes", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } @@ -1510,14 +1533,14 @@ private async static Task EncryptedCopyObject_Test2(MinioClient minio) string objectName = GetRandomName(10); string destBucketName = GetRandomName(15); string destObjectName = GetRandomName(10); - Dictionary args = new Dictionary - { - {"bucketName", bucketName}, - {"objectName",objectName}, - {"destBucketName", destBucketName}, - {"destObjectName", destObjectName}, - {"data","1KB"}, - {"size","1KB"}, + var args = new Dictionary + { + { "bucketName", bucketName }, + { "objectName", objectName }, + { "destBucketName", destBucketName }, + { "destObjectName", destObjectName }, + { "data", "1KB" }, + { "size", "1KB" }, }; try { @@ -1537,7 +1560,7 @@ await minio.PutObjectAsync(bucketName, filestream, filestream.Length, null, sse:ssec); } - await minio.CopyObjectAsync(bucketName, objectName, destBucketName, destObjectName,sseSrc:sseCpy,sseDest:null); + await minio.CopyObjectAsync(bucketName, objectName, destBucketName, destObjectName, sseSrc:sseCpy, sseDest:null); string outFileName = "outFileName"; await minio.GetObjectAsync(destBucketName, destObjectName, outFileName); @@ -1548,11 +1571,11 @@ await minio.PutObjectAsync(bucketName, await TearDown(minio, bucketName); await TearDown(minio, destBucketName); - new MintLogger("EncryptedCopyObject_Test2",copyObjectSignature,"Tests whether encrypted CopyObject passes",TestStatus.PASS,(DateTime.Now - startTime), args:args).Log(); + new MintLogger("EncryptedCopyObject_Test2", copyObjectSignature, "Tests whether encrypted CopyObject passes", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { - new MintLogger("EncryptedCopyObject_Test2",copyObjectSignature,"Tests whether encrypted CopyObject passes",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(),args).Log(); + new MintLogger("EncryptedCopyObject_Test2", copyObjectSignature, "Tests whether encrypted CopyObject passes", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } @@ -1563,14 +1586,14 @@ private async static Task EncryptedCopyObject_Test3(MinioClient minio) string objectName = GetRandomName(10); string destBucketName = GetRandomName(15); string destObjectName = GetRandomName(10); - Dictionary args = new Dictionary - { - {"bucketName", bucketName}, - {"objectName",objectName}, - {"destBucketName", destBucketName}, - {"destObjectName", destObjectName}, - {"data","1KB"}, - {"size","1KB"}, + var args = new Dictionary + { + { "bucketName", bucketName }, + { "objectName", objectName }, + { "destBucketName", destBucketName }, + { "destObjectName", destObjectName }, + { "data", "1KB" }, + { "size", "1KB" }, }; try { @@ -1591,7 +1614,7 @@ await minio.PutObjectAsync(bucketName, filestream, filestream.Length, null, sse:ssec); } - await minio.CopyObjectAsync(bucketName, objectName, destBucketName, destObjectName,sseSrc:sseCpy,sseDest:sses3); + await minio.CopyObjectAsync(bucketName, objectName, destBucketName, destObjectName, sseSrc:sseCpy, sseDest:sses3); string outFileName = "outFileName"; await minio.GetObjectAsync(destBucketName, destObjectName, outFileName); @@ -1602,11 +1625,11 @@ await minio.PutObjectAsync(bucketName, await TearDown(minio, bucketName); await TearDown(minio, destBucketName); - new MintLogger("EncryptedCopyObject_Test3",copyObjectSignature,"Tests whether encrypted CopyObject passes",TestStatus.PASS,(DateTime.Now - startTime), args:args).Log(); + new MintLogger("EncryptedCopyObject_Test3", copyObjectSignature, "Tests whether encrypted CopyObject passes", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { - new MintLogger("EncryptedCopyObject_Test3",copyObjectSignature,"Tests whether encrypted CopyObject passes",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(),args).Log(); + new MintLogger("EncryptedCopyObject_Test3", copyObjectSignature, "Tests whether encrypted CopyObject passes", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } @@ -1617,14 +1640,14 @@ private async static Task EncryptedCopyObject_Test4(MinioClient minio) string objectName = GetRandomName(10); string destBucketName = GetRandomName(15); string destObjectName = GetRandomName(10); - Dictionary args = new Dictionary - { - {"bucketName", bucketName}, - {"objectName",objectName}, - {"destBucketName", destBucketName}, - {"destObjectName", destObjectName}, - {"data","1KB"}, - {"size","1KB"}, + var args = new Dictionary + { + { "bucketName", bucketName }, + { "objectName", objectName }, + { "destBucketName", destBucketName }, + { "destObjectName", destObjectName }, + { "data", "1KB" }, + { "size", "1KB" }, }; try { @@ -1641,7 +1664,7 @@ await minio.PutObjectAsync(bucketName, filestream, filestream.Length, null, sse:sses3); } - await minio.CopyObjectAsync(bucketName, objectName, destBucketName, destObjectName,sseSrc:null,sseDest:sses3); + await minio.CopyObjectAsync(bucketName, objectName, destBucketName, destObjectName, sseSrc:null, sseDest:sses3); string outFileName = "outFileName"; await minio.GetObjectAsync(destBucketName, destObjectName, outFileName); @@ -1652,24 +1675,25 @@ await minio.PutObjectAsync(bucketName, await TearDown(minio, bucketName); await TearDown(minio, destBucketName); - new MintLogger("EncryptedCopyObject_Test4",copyObjectSignature,"Tests whether encrypted CopyObject passes",TestStatus.PASS,(DateTime.Now - startTime), args:args).Log(); + new MintLogger("EncryptedCopyObject_Test4", copyObjectSignature, "Tests whether encrypted CopyObject passes", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { - new MintLogger("EncryptedCopyObject_Test4",copyObjectSignature,"Tests whether encrypted CopyObject passes",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(),args).Log(); + new MintLogger("EncryptedCopyObject_Test4", copyObjectSignature, "Tests whether encrypted CopyObject passes", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } + private async static Task GetObject_Test1(MinioClient minio) { DateTime startTime = DateTime.Now; string bucketName = GetRandomName(15); string objectName = GetRandomName(10); string contentType = null; - Dictionary args = new Dictionary + var args = new Dictionary { - {"bucketName", bucketName}, - {"objectName",objectName}, - {"contentType", contentType}, + { "bucketName", bucketName }, + { "objectName", objectName }, + { "contentType", contentType }, }; try { @@ -1703,25 +1727,26 @@ await minio.GetObjectAsync(bucketName, objectName, } await TearDown(minio, bucketName); - new MintLogger("GetObject_Test1",getObjectSignature1,"Tests whether GetObject as stream works",TestStatus.PASS,(DateTime.Now - startTime),args:args).Log(); + new MintLogger("GetObject_Test1", getObjectSignature1, "Tests whether GetObject as stream works", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { - new MintLogger("GetObject_Test1",getObjectSignature1,"Tests whether GetObject as stream works",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(),args).Log(); + new MintLogger("GetObject_Test1", getObjectSignature1, "Tests whether GetObject as stream works", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } + private async static Task GetObject_Test2(MinioClient minio) { DateTime startTime = DateTime.Now; string bucketName = GetRandomName(15); string objectName = GetRandomName(10); string fileName = GetRandomName(10); - Dictionary args = new Dictionary + var args = new Dictionary { - {"bucketName", bucketName}, - {"objectName",objectName}, - {"fileName", fileName}, + { "bucketName", bucketName }, + { "objectName", objectName }, + { "fileName", fileName }, }; try { @@ -1737,27 +1762,28 @@ private async static Task GetObject_Test2(MinioClient minio) } await TearDown(minio, bucketName); - new MintLogger("GetObject_Test2",getObjectSignature1,"Tests for non-existent GetObject",TestStatus.PASS,(DateTime.Now - startTime),args:args).Log(); + new MintLogger("GetObject_Test2", getObjectSignature1, "Tests for non-existent GetObject", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { - new MintLogger("GetObject_Test2",getObjectSignature1,"Tests for non-existent GetObject",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(),args).Log(); + new MintLogger("GetObject_Test2", getObjectSignature1, "Tests for non-existent GetObject", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } + private async static Task GetObject_Test3(MinioClient minio) { DateTime startTime = DateTime.Now; string bucketName = GetRandomName(15); string objectName = GetRandomName(10); string contentType = null; - Dictionary args = new Dictionary + var args = new Dictionary { - {"bucketName", bucketName}, - {"objectName",objectName}, - {"contentType", contentType}, - {"size", "1024L"}, - {"length", "10L"}, + { "bucketName", bucketName }, + { "objectName", objectName }, + { "contentType", contentType }, + { "size", "1024L" }, + { "length", "10L" }, }; try { @@ -1789,25 +1815,26 @@ await minio.GetObjectAsync(bucketName, objectName, 1024L, file_write_size, await minio.RemoveObjectAsync(bucketName, objectName); } await TearDown(minio, bucketName); - new MintLogger("GetObject_Test3",getObjectSignature2,"Tests whether GetObject returns all the data",TestStatus.PASS,(DateTime.Now - startTime), args:args).Log(); + new MintLogger("GetObject_Test3", getObjectSignature2, "Tests whether GetObject returns all the data", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { - new MintLogger("GetObject_Test3",getObjectSignature2,"Tests whether GetObject returns all the data",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(),args).Log(); + new MintLogger("GetObject_Test3", getObjectSignature2, "Tests whether GetObject returns all the data", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } + private async static Task FGetObject_Test1(MinioClient minio) { DateTime startTime = DateTime.Now; string bucketName = GetRandomName(15); string objectName = GetRandomName(10); string outFileName = "outFileName"; - Dictionary args = new Dictionary + var args = new Dictionary { - {"bucketName", bucketName}, - {"objectName",objectName}, - {"fileName", outFileName}, + { "bucketName", bucketName }, + { "objectName", objectName }, + { "fileName", outFileName }, }; try { @@ -1823,26 +1850,26 @@ await minio.PutObjectAsync(bucketName, File.Delete(outFileName); await minio.RemoveObjectAsync(bucketName, objectName); await TearDown(minio, bucketName); - new MintLogger("FGetObject_Test1",getObjectSignature3,"Tests whether FGetObject passes for small upload",TestStatus.PASS,(DateTime.Now - startTime), args:args).Log(); + new MintLogger("FGetObject_Test1", getObjectSignature3, "Tests whether FGetObject passes for small upload", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { - new MintLogger("FGetObject_Test1",getObjectSignature3,"Tests whether FGetObject passes for small upload",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(),args).Log(); + new MintLogger("FGetObject_Test1", getObjectSignature3, "Tests whether FGetObject passes for small upload", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } private async static Task FPutObject_Test1(MinioClient minio) { - DateTime startTime = DateTime.Now; - string bucketName = GetRandomName(15); - string objectName = GetRandomName(10); - string fileName = CreateFile(6 * MB, dataFile6MB); - Dictionary args = new Dictionary + DateTime startTime = DateTime.Now; + string bucketName = GetRandomName(15); + string objectName = GetRandomName(10); + string fileName = CreateFile(6 * MB, dataFile6MB); + var args = new Dictionary { - {"bucketName", bucketName}, - {"objectName",objectName}, - {"fileName", fileName}, + { "bucketName", bucketName }, + { "objectName", objectName }, + { "fileName", fileName }, }; try { @@ -1854,11 +1881,11 @@ await minio.PutObjectAsync(bucketName, await minio.RemoveObjectAsync(bucketName, objectName); await TearDown(minio, bucketName); - new MintLogger("FPutObject_Test1",putObjectSignature2,"Tests whether FPutObject for multipart upload passes",TestStatus.PASS,(DateTime.Now - startTime), args:args).Log(); + new MintLogger("FPutObject_Test1", putObjectSignature2, "Tests whether FPutObject for multipart upload passes", TestStatus.PASS, (DateTime.Now - startTime), args: args).Log(); } catch (MinioException ex) { - new MintLogger("FPutObject_Test1",putObjectSignature2,"Tests whether FPutObject for multipart upload passes",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(),args).Log(); + new MintLogger("FPutObject_Test1", putObjectSignature2, "Tests whether FPutObject for multipart upload passes", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } if (!IsMintEnv()) { @@ -1872,12 +1899,12 @@ private async static Task FPutObject_Test2(MinioClient minio) string bucketName = GetRandomName(15); string objectName = GetRandomName(10); string fileName = CreateFile(10 * KB, dataFile10KB); - Dictionary args = new Dictionary - { - {"bucketName", bucketName}, - {"objectName",objectName}, - {"fileName", fileName}, - }; + var args = new Dictionary + { + { "bucketName", bucketName }, + { "objectName", objectName }, + { "fileName", fileName }, + }; try { await Setup_Test(minio, bucketName); @@ -1887,11 +1914,11 @@ await minio.PutObjectAsync(bucketName, await minio.RemoveObjectAsync(bucketName, objectName); await TearDown(minio, bucketName); - new MintLogger("FPutObject_Test2",putObjectSignature2,"Tests whether FPutObject for small upload passes",TestStatus.PASS,(DateTime.Now - startTime),args:args).Log(); + new MintLogger("FPutObject_Test2", putObjectSignature2, "Tests whether FPutObject for small upload passes", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { - new MintLogger("FPutObject_Test2",putObjectSignature2,"Tests whether FPutObject for small upload passes",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(),args).Log(); + new MintLogger("FPutObject_Test2", putObjectSignature2, "Tests whether FPutObject for small upload passes", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } if (!IsMintEnv()) { @@ -1905,33 +1932,33 @@ private async static Task ListObjects_Test1(MinioClient minio) string bucketName = GetRandomName(15); string prefix = "minix"; string objectName = prefix + GetRandomName(10); - Dictionary args = new Dictionary + var args = new Dictionary { - {"bucketName", bucketName}, - {"objectName",objectName}, - {"prefix", prefix}, - {"recursive","false"}, + { "bucketName", bucketName }, + { "objectName", objectName }, + { "prefix", prefix }, + { "recursive", "false" }, }; try { await Setup_Test(minio, bucketName); Task[] tasks = new Task[2]; for (int i = 0; i < 2; i++) { - tasks[i]= PutObject_Task(minio, bucketName, objectName + i.ToString(), null, null, 0, null, rsg.GenerateStreamFromSeed(1)); + tasks[i] = PutObject_Task(minio, bucketName, objectName + i.ToString(), null, null, 0, null, rsg.GenerateStreamFromSeed(1)); } await Task.WhenAll(tasks); - ListObjects_Test(minio, bucketName, prefix, 2,false).Wait(); + ListObjects_Test(minio, bucketName, prefix, 2, false).Wait(); System.Threading.Thread.Sleep(2000); await minio.RemoveObjectAsync(bucketName, objectName + "0"); await minio.RemoveObjectAsync(bucketName, objectName + "1"); await TearDown(minio, bucketName); - new MintLogger("ListObjects_Test1",listObjectsSignature,"Tests whether ListObjects lists all objects matching a prefix non-recursive",TestStatus.PASS,(DateTime.Now - startTime),args:args).Log(); + new MintLogger("ListObjects_Test1", listObjectsSignature, "Tests whether ListObjects lists all objects matching a prefix non-recursive", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { - new MintLogger("ListObjects_Test1",listObjectsSignature,"Tests whether ListObjects lists all objects matching a prefix non-recursive",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(), args).Log(); + new MintLogger("ListObjects_Test1", listObjectsSignature, "Tests whether ListObjects lists all objects matching a prefix non-recursive", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } @@ -1939,9 +1966,9 @@ private async static Task ListObjects_Test2(MinioClient minio) { DateTime startTime = DateTime.Now; string bucketName = GetRandomName(15); - Dictionary args = new Dictionary + var args = new Dictionary { - {"bucketName", bucketName}, + { "bucketName", bucketName }, }; try { @@ -1949,33 +1976,33 @@ private async static Task ListObjects_Test2(MinioClient minio) ListObjects_Test(minio, bucketName, null, 0).Wait(1000); await TearDown(minio, bucketName); - new MintLogger("ListObjects_Test2",listObjectsSignature,"Tests whether ListObjects passes when bucket is empty",TestStatus.PASS,(DateTime.Now - startTime),args:args).Log(); + new MintLogger("ListObjects_Test2", listObjectsSignature, "Tests whether ListObjects passes when bucket is empty", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { - new MintLogger("ListObjects_Test2",listObjectsSignature,"Tests whether ListObjects passes when bucket is empty",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(), args).Log(); + new MintLogger("ListObjects_Test2", listObjectsSignature, "Tests whether ListObjects passes when bucket is empty", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } - private async static Task ListObjects_Test3(MinioClient minio) + private async static Task ListObjects_Test3(MinioClient minio) { DateTime startTime = DateTime.Now; string bucketName = GetRandomName(15); string prefix = "minix"; string objectName = prefix + "/"+ GetRandomName(10) + "/suffix"; - Dictionary args = new Dictionary + var args = new Dictionary { - {"bucketName", bucketName}, - {"objectName",objectName}, - {"prefix", prefix}, - {"recursive", "true"} + { "bucketName", bucketName }, + { "objectName", objectName }, + { "prefix", prefix }, + { "recursive", "true" } }; try { await Setup_Test(minio, bucketName); Task[] tasks = new Task[2]; for (int i = 0; i < 2; i++) { - tasks[i]= PutObject_Task(minio, bucketName, objectName + i.ToString(), null, null, 0, null, rsg.GenerateStreamFromSeed(1*KB)); + tasks[i] = PutObject_Task(minio, bucketName, objectName + i.ToString(), null, null, 0, null, rsg.GenerateStreamFromSeed(1*KB)); } await Task.WhenAll(tasks); @@ -1984,11 +2011,11 @@ private async static Task ListObjects_Test3(MinioClient minio) await minio.RemoveObjectAsync(bucketName, objectName + "0"); await minio.RemoveObjectAsync(bucketName, objectName + "1"); await TearDown(minio, bucketName); - new MintLogger("ListObjects_Test3",listObjectsSignature,"Tests whether ListObjects lists all objects matching a prefix and recursive",TestStatus.PASS,(DateTime.Now - startTime),args:args).Log(); + new MintLogger("ListObjects_Test3", listObjectsSignature, "Tests whether ListObjects lists all objects matching a prefix and recursive", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { - new MintLogger("ListObjects_Test3",listObjectsSignature,"Tests whether ListObjects lists all objects matching a prefix and recursive",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(), args).Log(); + new MintLogger("ListObjects_Test3", listObjectsSignature, "Tests whether ListObjects lists all objects matching a prefix and recursive", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } @@ -1997,18 +2024,18 @@ private async static Task ListObjects_Test4(MinioClient minio) DateTime startTime = DateTime.Now; string bucketName = GetRandomName(15); string objectName = GetRandomName(10); - Dictionary args = new Dictionary + var args = new Dictionary { - {"bucketName", bucketName}, - {"objectName",objectName}, - {"recursive", "false"} + { "bucketName", bucketName }, + { "objectName", objectName }, + { "recursive", "false" } }; try { await Setup_Test(minio, bucketName); Task[] tasks = new Task[2]; for (int i = 0; i < 2; i++) { - tasks[i]= PutObject_Task(minio, bucketName, objectName + i.ToString(), null, null, 0, null, rsg.GenerateStreamFromSeed(1*KB)); + tasks[i] = PutObject_Task(minio, bucketName, objectName + i.ToString(), null, null, 0, null, rsg.GenerateStreamFromSeed(1*KB)); } await Task.WhenAll(tasks); @@ -2018,23 +2045,24 @@ private async static Task ListObjects_Test4(MinioClient minio) await minio.RemoveObjectAsync(bucketName, objectName + "0"); await minio.RemoveObjectAsync(bucketName, objectName + "1"); await TearDown(minio, bucketName); - new MintLogger("ListObjects_Test4",listObjectsSignature,"Tests whether ListObjects lists all objects when no prefix is specified",TestStatus.PASS,(DateTime.Now - startTime),args:args).Log(); + new MintLogger("ListObjects_Test4", listObjectsSignature, "Tests whether ListObjects lists all objects when no prefix is specified", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { - new MintLogger("ListObjects_Test4",listObjectsSignature,"Tests whether ListObjects lists all objects when no prefix is specified",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(),args).Log(); + new MintLogger("ListObjects_Test4", listObjectsSignature, "Tests whether ListObjects lists all objects when no prefix is specified", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } - private async static Task ListObjects_Test5(MinioClient minio) + + private async static Task ListObjects_Test5(MinioClient minio) { DateTime startTime = DateTime.Now; string bucketName = GetRandomName(15); string objectNamePrefix = GetRandomName(10); - Dictionary args = new Dictionary + var args = new Dictionary { - {"bucketName", bucketName}, - {"objectName",objectNamePrefix}, - {"recursive", "false"} + { "bucketName", bucketName }, + { "objectName", objectNamePrefix }, + { "recursive", "false" } }; try { @@ -2042,9 +2070,9 @@ private async static Task ListObjects_Test5(MinioClient minio) await Setup_Test(minio, bucketName); Task[] tasks = new Task[numObjects]; for (int i = 1; i <= numObjects; i++) { - tasks[i - 1]= PutObject_Task(minio, bucketName, objectNamePrefix + i.ToString(), null, null, 0, null, rsg.GenerateStreamFromSeed(1)); + tasks[i - 1] = PutObject_Task(minio, bucketName, objectNamePrefix + i.ToString(), null, null, 0, null, rsg.GenerateStreamFromSeed(1)); // Add sleep to avoid flooding server with concurrent requests - if (i % 50 == 0){ + if (i % 50 == 0) { System.Threading.Thread.Sleep(2000); } } @@ -2055,16 +2083,17 @@ private async static Task ListObjects_Test5(MinioClient minio) for(int index=1; index <= numObjects; index++) { string objectName = objectNamePrefix + index.ToString(); - await minio.RemoveObjectAsync(bucketName,objectName); + await minio.RemoveObjectAsync(bucketName, objectName); } await TearDown(minio, bucketName); - new MintLogger("ListObjects_Test5",listObjectsSignature,"Tests whether ListObjects lists all objects when number of objects == 100",TestStatus.PASS,(DateTime.Now - startTime),args:args).Log(); + new MintLogger("ListObjects_Test5", listObjectsSignature, "Tests whether ListObjects lists all objects when number of objects == 100", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { - new MintLogger("ListObjects_Test5",listObjectsSignature,"Tests whether ListObjects lists all objects when number of objects == 100",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(),args).Log(); + new MintLogger("ListObjects_Test5", listObjectsSignature, "Tests whether ListObjects lists all objects when number of objects == 100", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } + private async static Task ListObjects_Test(MinioClient minio, string bucketName, string prefix, int numObjects, bool recursive = true) { DateTime startTime = DateTime.Now; @@ -2080,7 +2109,6 @@ private async static Task ListObjects_Test(MinioClient minio, string bucketName, () => { Assert.AreEqual(count, numObjects); - }); } @@ -2089,10 +2117,10 @@ private async static Task RemoveObject_Test1(MinioClient minio) DateTime startTime = DateTime.Now; string bucketName = GetRandomName(15); string objectName = GetRandomName(10); - Dictionary args = new Dictionary + var args = new Dictionary { - {"bucketName", bucketName}, - {"objectName",objectName}, + { "bucketName", bucketName }, + { "objectName", objectName }, }; try { @@ -2105,13 +2133,12 @@ await minio.PutObjectAsync(bucketName, filestream, filestream.Length, null); await minio.RemoveObjectAsync(bucketName, objectName); await TearDown(minio, bucketName); - } - new MintLogger("RemoveObject_Test1",removeObjectSignature1,"Tests whether RemoveObjectAsync for existing object passes",TestStatus.PASS,(DateTime.Now - startTime),args:args).Log(); + new MintLogger("RemoveObject_Test1", removeObjectSignature1, "Tests whether RemoveObjectAsync for existing object passes", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { - new MintLogger("RemoveObject_Test1",removeObjectSignature1,"Tests whether RemoveObjectAsync for existing object passes",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(),args).Log(); + new MintLogger("RemoveObject_Test1", removeObjectSignature1, "Tests whether RemoveObjectAsync for existing object passes", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } @@ -2120,10 +2147,10 @@ private async static Task RemoveObjects_Test2(MinioClient minio) DateTime startTime = DateTime.Now; string bucketName = GetRandomName(15); string objectName = GetRandomName(6); - Dictionary args = new Dictionary + var args = new Dictionary { - {"bucketName", bucketName}, - {"objectNames","[" + objectName + "0..." + objectName + "50]"}, + { "bucketName", bucketName }, + { "objectNames", "[" + objectName + "0..." + objectName + "50]" }, }; try { @@ -2141,20 +2168,19 @@ private async static Task RemoveObjects_Test2(MinioClient minio) DeleteError de; IObservable observable = await minio.RemoveObjectAsync(bucketName, objectsList); IDisposable subscription = observable.Subscribe( - deleteError => de= deleteError, + deleteError => de = deleteError, () => { TearDown(minio, bucketName).Wait(); }); - new MintLogger("RemoveObject_Test2",removeObjectSignature2,"Tests whether RemoveObjectAsync for multi objects delete passes",TestStatus.PASS,(DateTime.Now - startTime),args:args).Log(); + new MintLogger("RemoveObject_Test2", removeObjectSignature2, "Tests whether RemoveObjectAsync for multi objects delete passes", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { - new MintLogger("RemoveObjects_Test2", removeObjectSignature2, "Tests whether RemoveObjectAsync for multi objects delete passes", TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(), args).Log(); + new MintLogger("RemoveObjects_Test2", removeObjectSignature2, "Tests whether RemoveObjectAsync for multi objects delete passes", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } - private async static Task PresignedGetObject_Test1(MinioClient minio) { DateTime startTime = DateTime.Now; @@ -2163,11 +2189,11 @@ private async static Task PresignedGetObject_Test1(MinioClient minio) int expiresInt = 1000; string downloadFile = "downloadFileName"; - Dictionary args = new Dictionary + var args = new Dictionary { - {"bucketName", bucketName}, - {"objectName",objectName}, - {"expiresInt", expiresInt.ToString()} + { "bucketName", bucketName }, + { "objectName", objectName }, + { "expiresInt", expiresInt.ToString() } }; try { @@ -2193,11 +2219,11 @@ await minio.PutObjectAsync(bucketName, await TearDown(minio, bucketName); File.Delete(downloadFile); - new MintLogger("PresignedGetObject_Test1",presignedGetObjectSignature,"Tests whether PresignedGetObject url retrieves object from bucket",TestStatus.PASS,(DateTime.Now - startTime), args:args).Log(); + new MintLogger("PresignedGetObject_Test1", presignedGetObjectSignature, "Tests whether PresignedGetObject url retrieves object from bucket", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { - new MintLogger("PresignedGetObject_Test1",presignedGetObjectSignature,"Tests whether PresignedGetObject url retrieves object from bucket",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(),args).Log(); + new MintLogger("PresignedGetObject_Test1", presignedGetObjectSignature, "Tests whether PresignedGetObject url retrieves object from bucket", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } @@ -2207,11 +2233,11 @@ private async static Task PresignedGetObject_Test2(MinioClient minio) string bucketName = GetRandomName(15); string objectName = GetRandomName(10); int expiresInt = 0; - Dictionary args = new Dictionary + var args = new Dictionary { - {"bucketName", bucketName}, - {"objectName",objectName}, - {"expiresInt", expiresInt.ToString()} + { "bucketName", bucketName }, + { "objectName", objectName }, + { "expiresInt", expiresInt.ToString() } }; try { @@ -2227,16 +2253,17 @@ await minio.PutObjectAsync(bucketName, } catch (InvalidExpiryRangeException) { - new MintLogger("PresignedGetObject_Test2",presignedGetObjectSignature,"Tests whether PresignedGetObject url retrieves object from bucket when invalid expiry is set.",TestStatus.PASS,(DateTime.Now - startTime),args:args).Log(); + new MintLogger("PresignedGetObject_Test2", presignedGetObjectSignature, "Tests whether PresignedGetObject url retrieves object from bucket when invalid expiry is set.", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } await minio.RemoveObjectAsync(bucketName, objectName); await TearDown(minio, bucketName); } catch (Exception ex) { - new MintLogger("PresignedGetObject_Test2",presignedGetObjectSignature,"Tests whether PresignedGetObject url retrieves object from bucket when invalid expiry is set.",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(),args).Log(); + new MintLogger("PresignedGetObject_Test2", presignedGetObjectSignature, "Tests whether PresignedGetObject url retrieves object from bucket when invalid expiry is set.", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } + private async static Task PresignedGetObject_Test3(MinioClient minio) { DateTime startTime = DateTime.Now; @@ -2244,13 +2271,13 @@ private async static Task PresignedGetObject_Test3(MinioClient minio) string objectName = GetRandomName(10); int expiresInt = 1000; DateTime reqDate = DateTime.UtcNow.AddSeconds(-50); - Dictionary args = new Dictionary + var args = new Dictionary { - {"bucketName", bucketName}, - {"objectName", objectName}, - {"expiresInt", expiresInt.ToString()}, - {"reqParams", "response-content-type:application/json,response-content-disposition:attachment;filename=MyDocument.json;"}, - {"reqDate", reqDate.ToString()}, + { "bucketName", bucketName }, + { "objectName", objectName }, + { "expiresInt", expiresInt.ToString() }, + { "reqParams", "response-content-type:application/json,response-content-disposition:attachment;filename=MyDocument.json;" }, + { "reqDate", reqDate.ToString() }, }; try { @@ -2261,16 +2288,18 @@ await minio.PutObjectAsync(bucketName, objectName, filestream, filestream.Length, null); ObjectStat stats = await minio.StatObjectAsync(bucketName, objectName); - Dictionary reqParams = new Dictionary(); - reqParams["response-content-type"] = "application/json"; - reqParams["response-content-disposition"] = "attachment;filename=MyDocument.json;"; + var reqParams = new Dictionary + { + ["response-content-type"] = "application/json", + ["response-content-disposition"] = "attachment;filename=MyDocument.json;" + }; string presigned_url = await minio.PresignedGetObjectAsync(bucketName, objectName, 1000, reqParams, reqDate); WebRequest httpRequest = WebRequest.Create(presigned_url); var response = (HttpWebResponse)(await Task.Factory.FromAsync(httpRequest.BeginGetResponse, httpRequest.EndGetResponse, null)); - Assert.AreEqual(response.ContentType,reqParams["response-content-type"]); - Assert.AreEqual(response.Headers["Content-Disposition"],"attachment;filename=MyDocument.json;"); - Assert.AreEqual(response.Headers["Content-Type"],"application/json"); - Assert.AreEqual(response.Headers["Content-Length"],stats.Size.ToString()); + Assert.AreEqual(response.ContentType, reqParams["response-content-type"]); + Assert.AreEqual(response.Headers["Content-Disposition"], "attachment;filename=MyDocument.json;"); + Assert.AreEqual(response.Headers["Content-Type"], "application/json"); + Assert.AreEqual(response.Headers["Content-Length"], stats.Size.ToString()); Stream stream = response.GetResponseStream(); var fileStream = File.Create(downloadFile); stream.CopyTo(fileStream); @@ -2285,13 +2314,14 @@ await minio.PutObjectAsync(bucketName, await TearDown(minio, bucketName); File.Delete(downloadFile); - new MintLogger("PresignedGetObject_Test3",presignedGetObjectSignature,"Tests whether PresignedGetObject url retrieves object from bucket when override response headers sent",TestStatus.PASS,(DateTime.Now - startTime),args:args).Log(); + new MintLogger("PresignedGetObject_Test3", presignedGetObjectSignature, "Tests whether PresignedGetObject url retrieves object from bucket when override response headers sent", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { - new MintLogger("PresignedGetObject_Test3",presignedGetObjectSignature,"Tests whether PresignedGetObject url retrieves object from bucket when override response headers sent",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(),args).Log(); + new MintLogger("PresignedGetObject_Test3", presignedGetObjectSignature, "Tests whether PresignedGetObject url retrieves object from bucket when override response headers sent", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } + private async static Task PresignedPutObject_Test1(MinioClient minio) { DateTime startTime = DateTime.Now; @@ -2300,11 +2330,11 @@ private async static Task PresignedPutObject_Test1(MinioClient minio) int expiresInt = 1000; string fileName = CreateFile(10 * KB, dataFile10KB); - Dictionary args = new Dictionary + var args = new Dictionary { - {"bucketName", bucketName}, - {"objectName", objectName}, - {"expiresInt", expiresInt.ToString()}, + { "bucketName", bucketName }, + { "objectName", objectName }, + { "expiresInt", expiresInt.ToString() }, }; try { @@ -2322,11 +2352,11 @@ private async static Task PresignedPutObject_Test1(MinioClient minio) await minio.RemoveObjectAsync(bucketName, objectName); await TearDown(minio, bucketName); - new MintLogger("PresignedPutObject_Test1",presignedPutObjectSignature,"Tests whether PresignedPutObject url uploads object to bucket",TestStatus.PASS,(DateTime.Now - startTime),args:args).Log(); + new MintLogger("PresignedPutObject_Test1", presignedPutObjectSignature, "Tests whether PresignedPutObject url uploads object to bucket", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { - new MintLogger("PresignedPutObject_Test1",presignedPutObjectSignature,"Tests whether PresignedPutObject url uploads object to bucket",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(), args).Log(); + new MintLogger("PresignedPutObject_Test1", presignedPutObjectSignature, "Tests whether PresignedPutObject url uploads object to bucket", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } if (!IsMintEnv()) { @@ -2341,11 +2371,11 @@ private async static Task PresignedPutObject_Test2(MinioClient minio) string objectName = GetRandomName(10); int expiresInt = 0; - Dictionary args = new Dictionary + var args = new Dictionary { - {"bucketName", bucketName}, - {"objectName", objectName}, - {"expiresInt", expiresInt.ToString()}, + { "bucketName", bucketName }, + { "objectName", objectName }, + { "expiresInt", expiresInt.ToString() }, }; try { @@ -2361,14 +2391,14 @@ await minio.PutObjectAsync(bucketName, } catch (InvalidExpiryRangeException) { - new MintLogger("PresignedPutObject_Test2",presignedPutObjectSignature,"Tests whether PresignedPutObject url retrieves object from bucket when invalid expiry is set.",TestStatus.PASS,(DateTime.Now - startTime),args:args).Log(); + new MintLogger("PresignedPutObject_Test2", presignedPutObjectSignature, "Tests whether PresignedPutObject url retrieves object from bucket when invalid expiry is set.", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } await minio.RemoveObjectAsync(bucketName, objectName); await TearDown(minio, bucketName); } catch (Exception ex) { - new MintLogger("PresignedPutObject_Test2",presignedPutObjectSignature,"Tests whether PresignedPutObject url retrieves object from bucket when invalid expiry is set.",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(),args).Log(); + new MintLogger("PresignedPutObject_Test2", presignedPutObjectSignature, "Tests whether PresignedPutObject url retrieves object from bucket when invalid expiry is set.", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } @@ -2402,9 +2432,9 @@ private async static Task PresignedPostPolicy_Test1(MinioClient minio) form.SetKey(objectName); form.SetBucket(bucketName); form.SetUserMetadata(metadataKey, metadataValue); - Dictionary args = new Dictionary + var args = new Dictionary { - {"form", form.Base64()}, + { "form", form.Base64() }, }; string fileName = CreateFile(10 * KB, dataFile10KB); @@ -2432,11 +2462,11 @@ await minio.PutObjectAsync(bucketName, String policy = await minio.GetPolicyAsync(bucketName); await minio.RemoveObjectAsync(bucketName, objectName); await TearDown(minio, bucketName); - new MintLogger("PresignedPostPolicy_Test1",presignedPostPolicySignature,"Tests whether PresignedPostPolicy url applies policy on server",TestStatus.PASS,(DateTime.Now - startTime), args:args).Log(); + new MintLogger("PresignedPostPolicy_Test1", presignedPostPolicySignature, "Tests whether PresignedPostPolicy url applies policy on server", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (Exception ex) { - new MintLogger("PresignedPostPolicy_Test1",presignedPostPolicySignature,"Tests whether PresignedPostPolicy url applies policy on server",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(), args).Log(); + new MintLogger("PresignedPostPolicy_Test1", presignedPostPolicySignature, "Tests whether PresignedPostPolicy url applies policy on server", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } await minio.RemoveObjectAsync(bucketName, objectName); @@ -2455,10 +2485,10 @@ private async static Task ListIncompleteUpload_Test1(MinioClient minio) string bucketName = GetRandomName(15); string objectName = GetRandomName(10); string contentType = "gzip"; - Dictionary args = new Dictionary + var args = new Dictionary { - {"bucketName", bucketName}, - {"recursive","true"} + { "bucketName", bucketName }, + { "recursive", "true" } }; try { @@ -2475,7 +2505,7 @@ await minio.PutObjectAsync(bucketName, objectName, filestream, filestream.Length, - contentType, cancellationToken:cts.Token); + contentType, cancellationToken: cts.Token); } } catch (OperationCanceledException) @@ -2490,17 +2520,18 @@ await minio.PutObjectAsync(bucketName, } catch (Exception ex) { - new MintLogger("ListIncompleteUpload_Test1",listIncompleteUploadsSignature,"Tests whether ListIncompleteUpload passes",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString()).Log(); + new MintLogger("ListIncompleteUpload_Test1", listIncompleteUploadsSignature, "Tests whether ListIncompleteUpload passes", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString()).Log(); return; } await TearDown(minio, bucketName); - new MintLogger("ListIncompleteUpload_Test1",listIncompleteUploadsSignature, "Tests whether ListIncompleteUpload passes",TestStatus.PASS,(DateTime.Now - startTime)).Log(); + new MintLogger("ListIncompleteUpload_Test1", listIncompleteUploadsSignature, "Tests whether ListIncompleteUpload passes", TestStatus.PASS, (DateTime.Now - startTime)).Log(); } catch (MinioException ex) { - new MintLogger("ListIncompleteUpload_Test1",listIncompleteUploadsSignature,"Tests whether ListIncompleteUpload passes",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString()).Log(); + new MintLogger("ListIncompleteUpload_Test1", listIncompleteUploadsSignature, "Tests whether ListIncompleteUpload passes", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString()).Log(); } } + private async static Task ListIncompleteUpload_Test2(MinioClient minio) { DateTime startTime = DateTime.Now; @@ -2508,11 +2539,11 @@ private async static Task ListIncompleteUpload_Test2(MinioClient minio) string prefix = "minioprefix/"; string objectName = prefix + GetRandomName(10); string contentType = "gzip"; - Dictionary args = new Dictionary + var args = new Dictionary { - {"bucketName", bucketName}, - {"prefix", prefix}, - {"recursive","false"} + { "bucketName", bucketName }, + { "prefix", prefix }, + { "recursive", "false" } }; try { @@ -2529,7 +2560,7 @@ await minio.PutObjectAsync(bucketName, objectName, filestream, filestream.Length, - contentType, cancellationToken:cts.Token); + contentType, cancellationToken: cts.Token); } } catch (OperationCanceledException) @@ -2543,11 +2574,11 @@ await minio.PutObjectAsync(bucketName, await minio.RemoveIncompleteUploadAsync(bucketName, objectName); } await TearDown(minio, bucketName); - new MintLogger("ListIncompleteUpload_Test2",listIncompleteUploadsSignature,"Tests whether ListIncompleteUpload passes when qualified by prefix",TestStatus.PASS,(DateTime.Now - startTime), args:args).Log(); + new MintLogger("ListIncompleteUpload_Test2", listIncompleteUploadsSignature, "Tests whether ListIncompleteUpload passes when qualified by prefix", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { - new MintLogger("ListIncompleteUpload_Test2",listIncompleteUploadsSignature,"Tests whether ListIncompleteUpload passes when qualified by prefix",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(), args).Log(); + new MintLogger("ListIncompleteUpload_Test2", listIncompleteUploadsSignature, "Tests whether ListIncompleteUpload passes when qualified by prefix", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } @@ -2558,11 +2589,11 @@ private async static Task ListIncompleteUpload_Test3(MinioClient minio) string prefix = "minioprefix"; string objectName = prefix + "/" + GetRandomName(10) + "/suffix"; string contentType = "gzip"; - Dictionary args = new Dictionary + var args = new Dictionary { - {"bucketName", bucketName}, - {"prefix", prefix}, - {"recursive","true"} + { "bucketName", bucketName }, + { "prefix", prefix }, + { "recursive", "true" } }; try { @@ -2579,7 +2610,7 @@ await minio.PutObjectAsync(bucketName, objectName, filestream, filestream.Length, - contentType, cancellationToken:cts.Token); + contentType, cancellationToken: cts.Token); } } catch (OperationCanceledException) @@ -2593,11 +2624,11 @@ await minio.PutObjectAsync(bucketName, await minio.RemoveIncompleteUploadAsync(bucketName, objectName); } await TearDown(minio, bucketName); - new MintLogger("ListIncompleteUpload_Test3",listIncompleteUploadsSignature,"Tests whether ListIncompleteUpload passes when qualified by prefix and recursive",TestStatus.PASS,(DateTime.Now - startTime), args:args).Log(); + new MintLogger("ListIncompleteUpload_Test3", listIncompleteUploadsSignature, "Tests whether ListIncompleteUpload passes when qualified by prefix and recursive", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { - new MintLogger("ListIncompleteUpload_Test3",listIncompleteUploadsSignature,"Tests whether ListIncompleteUpload passes when qualified by prefix and recursive",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(),args).Log(); + new MintLogger("ListIncompleteUpload_Test3", listIncompleteUploadsSignature, "Tests whether ListIncompleteUpload passes when qualified by prefix and recursive", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } @@ -2607,10 +2638,10 @@ private async static Task RemoveIncompleteUpload_Test(MinioClient minio) string bucketName = GetRandomName(15); string objectName = GetRandomName(10); string contentType = "csv"; - Dictionary args = new Dictionary + var args = new Dictionary { - {"bucketName", bucketName}, - {"objectName", objectName}, + { "bucketName", bucketName }, + { "objectName", objectName }, }; try { @@ -2627,7 +2658,7 @@ await minio.PutObjectAsync(bucketName, objectName, filestream, filestream.Length, - contentType, cancellationToken:cts.Token); + contentType, cancellationToken: cts.Token); } } catch (OperationCanceledException) @@ -2641,24 +2672,25 @@ await minio.PutObjectAsync(bucketName, ex => Assert.Fail()); } await TearDown(minio, bucketName); - new MintLogger("RemoveIncompleteUpload_Test",removeIncompleteUploadSignature,"Tests whether RemoveIncompleteUpload passes.",TestStatus.PASS,(DateTime.Now - startTime), args:args).Log(); + new MintLogger("RemoveIncompleteUpload_Test", removeIncompleteUploadSignature, "Tests whether RemoveIncompleteUpload passes.", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { - new MintLogger("RemoveIncompleteUpload_Test",removeIncompleteUploadSignature,"Tests whether RemoveIncompleteUpload passes.",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(), args).Log(); + new MintLogger("RemoveIncompleteUpload_Test", removeIncompleteUploadSignature, "Tests whether RemoveIncompleteUpload passes.", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } + // Set a policy for given bucket private async static Task SetBucketPolicy_Test1(MinioClient minio) { DateTime startTime = DateTime.Now; string bucketName = GetRandomName(15); string objectName = GetRandomName(10); - Dictionary args = new Dictionary + var args = new Dictionary { - {"bucketName", bucketName}, - {"objectPrefix", objectName.Substring(5)}, - {"policyType","readonly"} + { "bucketName", bucketName }, + { "objectPrefix", objectName.Substring(5) }, + { "policyType", "readonly" } }; try { @@ -2673,11 +2705,11 @@ await minio.SetPolicyAsync(bucketName, await minio.RemoveObjectAsync(bucketName, objectName); await TearDown(minio, bucketName); - new MintLogger("SetBucketPolicy_Test1",setBucketPolicySignature,"Tests whether SetBucketPolicy passes",TestStatus.PASS,(DateTime.Now - startTime), args:args).Log(); + new MintLogger("SetBucketPolicy_Test1", setBucketPolicySignature, "Tests whether SetBucketPolicy passes", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { - new MintLogger("SetBucketPolicy_Test1",setBucketPolicySignature,"Tests whether SetBucketPolicy passes",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(),args).Log(); + new MintLogger("SetBucketPolicy_Test1", setBucketPolicySignature, "Tests whether SetBucketPolicy passes", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } @@ -2687,9 +2719,9 @@ private async static Task GetBucketPolicy_Test1(MinioClient minio) DateTime startTime = DateTime.Now; string bucketName = GetRandomName(15); string objectName = GetRandomName(10); - Dictionary args = new Dictionary + var args = new Dictionary { - {"bucketName", bucketName}, + { "bucketName", bucketName }, }; try { @@ -2705,11 +2737,11 @@ await minio.SetPolicyAsync(bucketName, await minio.RemoveObjectAsync(bucketName, objectName); await TearDown(minio, bucketName); - new MintLogger("GetBucketPolicy_Test1",getBucketPolicySignature, "Tests whether GetBucketPolicy passes",TestStatus.PASS,(DateTime.Now - startTime), args:args).Log(); + new MintLogger("GetBucketPolicy_Test1", getBucketPolicySignature, "Tests whether GetBucketPolicy passes", TestStatus.PASS, (DateTime.Now - startTime), args:args).Log(); } catch (MinioException ex) { - new MintLogger("GetBucketPolicy_Test1",getBucketPolicySignature,"Tests whether GetBucketPolicy passes",TestStatus.FAIL,(DateTime.Now - startTime),"",ex.Message, ex.ToString(), args).Log(); + new MintLogger("GetBucketPolicy_Test1", getBucketPolicySignature, "Tests whether GetBucketPolicy passes", TestStatus.FAIL, (DateTime.Now - startTime), "", ex.Message, ex.ToString(), args).Log(); } } } diff --git a/Minio.Functional.Tests/MintLogger.cs b/Minio.Functional.Tests/MintLogger.cs index ac0ad08da..c7609f31e 100644 --- a/Minio.Functional.Tests/MintLogger.cs +++ b/Minio.Functional.Tests/MintLogger.cs @@ -51,7 +51,7 @@ internal class MintLogger public string description {get; private set;} // Key-value pair of args relevant to test - public Dictionary args {get; private set;} + public Dictionary args {get; private set;} // duration of the whole test public int duration {get; private set;} @@ -66,7 +66,7 @@ internal class MintLogger // actual low level exception/error thrown by the program public string error {get; private set;} - public MintLogger(string testName,string function, string description,TestStatus status,System.TimeSpan duration, string alert = null,string message=null, string error=null, Dictionary args=null) + public MintLogger(string testName, string function, string description, TestStatus status, System.TimeSpan duration, string alert = null, string message = null, string error = null, Dictionary args = null) { this.function = function; this.duration = (int)duration.TotalMilliseconds; diff --git a/Minio.Tests/AuthenticatorTest.cs b/Minio.Tests/AuthenticatorTest.cs index 510810803..246996132 100644 --- a/Minio.Tests/AuthenticatorTest.cs +++ b/Minio.Tests/AuthenticatorTest.cs @@ -86,7 +86,7 @@ public void TestInsecureRequestHeaders() Assert.IsTrue(hasPayloadHeader(request, "x-amz-content-sha256")); Assert.IsFalse(hasPayloadHeader(request, "Content-Md5")); } - private Tuple GetHeaderKV(IRestRequest request, string headername) + private Tuple GetHeaderKV(IRestRequest request, string headername) { var headers = request.Parameters.Where(p => p.Type.Equals(ParameterType.HttpHeader)).ToList(); List headerKeys = new List(); @@ -95,7 +95,7 @@ private Tuple GetHeaderKV(IRestRequest request, string headername string headerName = header.Name.ToLower(); if (headerName.Contains(headername.ToLower())) { - return new Tuple(headerName, header.Value); + return Tuple.Create(headerName, header.Value); } } return null; diff --git a/Minio.Tests/DictionaryExtensionMethods.cs b/Minio.Tests/DictionaryExtensionMethods.cs index 3f53780c4..8d54e295f 100644 --- a/Minio.Tests/DictionaryExtensionMethods.cs +++ b/Minio.Tests/DictionaryExtensionMethods.cs @@ -36,9 +36,8 @@ public static bool PoliciesEqual( foreach (var kvp in first) { - PolicyType secondValue; PolicyType firstValue = kvp.Value; - if (!second.TryGetValue(kvp.Key, out secondValue)) return false; + if (!second.TryGetValue(kvp.Key, out PolicyType secondValue)) return false; if (!firstValue.Equals(secondValue)) return false; } return true; diff --git a/Minio.Tests/EndpointTest.cs b/Minio.Tests/EndpointTest.cs index cb17f5c57..e1287a66d 100644 --- a/Minio.Tests/EndpointTest.cs +++ b/Minio.Tests/EndpointTest.cs @@ -33,57 +33,55 @@ public void TestGetEndpointURL() Minio.RequestUtil.GetEndpointURL("s3.amazonaws.com", true); object[] parameterValuesArray = { - new Object[]{ "s3.amazonaws.com",true,"testbucket",null,false }, - new object[] {"testbucket.s3.amazonaws.com", true} + new object[] { "s3.amazonaws.com", true, "testbucket", null, false }, + new object[] {"testbucket.s3.amazonaws.com", true } }; object[] parameterValuesArray1 = { - "s3.amazonaws.com",true,"testbucket","testobject",false - - }; + "s3.amazonaws.com", true, "testbucket", "testobject", false + }; object[][] testCases = { new Object[] { - new Object[]{ "s3.cn-north-1.amazonaws.com.cn", true}, - new Object[] { "https://s3.cn-north-1.amazonaws.com.cn", null,true} + new Object[] { "s3.cn-north-1.amazonaws.com.cn", true }, + new Object[] { "https://s3.cn-north-1.amazonaws.com.cn", null, true } }, - new Object[] { - new Object[]{ "s3.amazonaws.com:443",true }, - new Object[] {"https://s3.amazonaws.com:443",null, true} + new Object[] { + new Object[] { "s3.amazonaws.com:443", true }, + new Object[] { "https://s3.amazonaws.com:443", null, true } }, - new Object[] { - new Object[]{ "s3.amazonaws.com",true }, - new Object[] {"https://s3.amazonaws.com",null, true} + new Object[] { + new Object[] { "s3.amazonaws.com", true }, + new Object[] { "https://s3.amazonaws.com", null, true } }, - new Object[] { - new Object[]{ "s3.amazonaws.com",false }, - new Object[] {"http://s3.amazonaws.com",null, true} + new Object[] { "s3.amazonaws.com", false }, + new Object[] { "http://s3.amazonaws.com", null, true } }, - new Object[] { - new Object[]{ "192.168.1.1:9000", false}, - new object[] { "http://192.168.1.1:9000", null,true} + new Object[] { + new object[] { "192.168.1.1:9000", false}, + new object[] { "http://192.168.1.1:9000", null, true } }, - new Object[] { - new Object[]{ "192.168.1.1:9000", true}, - new object[] { "https://192.168.1.1:9000", null,true} + new Object[] { + new Object[] { "192.168.1.1:9000", true }, + new object[] { "https://192.168.1.1:9000", null, true } }, - new Object[] { - new Object[]{ "13333.123123.-", true}, - new object[] { "",new InvalidEndpointException("Endpoint: 13333.123123.- does not follow ip address or domain name standards."),false} + new Object[] { + new Object[] { "13333.123123.-", true }, + new object[] { "", new InvalidEndpointException("Endpoint: 13333.123123.- does not follow ip address or domain name standards."), false } }, - new Object[] { - new Object[]{ "s3.aamzza.-", true}, - new object[] { "",new InvalidEndpointException("Endpoint: s3.aamzza.- does not follow ip address or domain name standards."),false} + new Object[] { + new Object[] { "s3.aamzza.-", true }, + new object[] { "", new InvalidEndpointException("Endpoint: s3.aamzza.- does not follow ip address or domain name standards."), false } }, - new Object[] { - new Object[]{ "", true}, - new object[] { "",new InvalidEndpointException("Endpoint: does not follow ip address or domain name standards."),false} + new Object[] { + new Object[] { "", true }, + new object[] { "", new InvalidEndpointException("Endpoint: does not follow ip address or domain name standards."), false } }, }; for (int i = 0; i < testCases.Length; i++) @@ -109,13 +107,13 @@ public void TestIfIPIsValid() { Dictionary testIPDict = new Dictionary { - {"192.168.1",false }, - {"192.168.1.1", true}, - {"192.168.1.1.1", false}, - {"-192.168.1.1", false}, - {"260.192.1.1", false}, + { "192.168.1", false }, + { "192.168.1.1", true }, + { "192.168.1.1.1", false }, + { "-192.168.1.1", false }, + { "260.192.1.1", false }, }; - foreach (KeyValuePair testCase in testIPDict) + foreach (KeyValuePair testCase in testIPDict) { Assert.AreEqual(s3utils.IsValidIP(testCase.Key), testCase.Value); } diff --git a/Minio.Tests/RegionTest.cs b/Minio.Tests/RegionTest.cs index 32adcfc88..01db4a91f 100644 --- a/Minio.Tests/RegionTest.cs +++ b/Minio.Tests/RegionTest.cs @@ -30,11 +30,11 @@ public class TestRegion [TestMethod] public void TestGetRegion() { - Dictionary endpoint2Region = new Dictionary + var endpoint2Region = new Dictionary { {"s3.us-east-2.amazonaws.com", "us-east-2"}, - {"s3.amazonaws.com",""}, - {"testbucket.s3-ca-central-1.amazonaws.com","ca-central-1"}, + {"s3.amazonaws.com", ""}, + {"testbucket.s3-ca-central-1.amazonaws.com", "ca-central-1"}, {"mybucket-s3-us-east-2.amazonaws.com", "us-east-2"}, {"s3.us-west-1.amazonaws.com", "us-west-1"}, {"mybucket-s3-us-west-1.amazonaws.com", "us-west-1"}, diff --git a/Minio.Tests/UnitTest1.cs b/Minio.Tests/UnitTest1.cs index 5e71c8a5b..68b040ef3 100644 --- a/Minio.Tests/UnitTest1.cs +++ b/Minio.Tests/UnitTest1.cs @@ -156,7 +156,7 @@ public void TestEndpointFailure() //[ExpectedException(typeof(ArgumentException))] //public void TestPutObject() //{ - // var client = new MinioClient("localhost", 9000,); + // var client = new MinioClient("localhost", 9000); // await client.PutObjectAsync("bucket-name", "object-name", null, 5 * 1024L * 1024L * 11000, null); //} } diff --git a/Minio.Tests/UtilsTest.cs b/Minio.Tests/UtilsTest.cs index 9f4c695e2..a00f500a1 100644 --- a/Minio.Tests/UtilsTest.cs +++ b/Minio.Tests/UtilsTest.cs @@ -30,24 +30,23 @@ public class UtilsTest [TestMethod] public void TestValidBucketName() { - var testCases = new List>() + var testCases = new List> { - new KeyValuePair(".mybucket",new InvalidBucketNameException(".mybucket", "Bucket name cannot start or end with a '.' dot.")), - new KeyValuePair("mybucket.",new InvalidBucketNameException(".mybucket", "Bucket name cannot start or end with a '.' dot.")), - new KeyValuePair("",new InvalidBucketNameException("", "Bucket name cannot be empty.")), - new KeyValuePair("mk",new InvalidBucketNameException("mk", "Bucket name cannot be smaller than 3 characters.")), - new KeyValuePair("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz123456789012345",new InvalidBucketNameException("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz123456789012345", "Bucket name cannot be greater than 63 characters.")), - new KeyValuePair("my..bucket",new InvalidBucketNameException("my..bucket", "Bucket name cannot have successive periods.")), - new KeyValuePair("MyBucket",new InvalidBucketNameException("MyBucket", "Bucket name cannot have upper case characters")), + new KeyValuePair(".mybucket", new InvalidBucketNameException(".mybucket", "Bucket name cannot start or end with a '.' dot.")), + new KeyValuePair("mybucket.", new InvalidBucketNameException(".mybucket", "Bucket name cannot start or end with a '.' dot.")), + new KeyValuePair("", new InvalidBucketNameException("", "Bucket name cannot be empty.")), + new KeyValuePair("mk", new InvalidBucketNameException("mk", "Bucket name cannot be smaller than 3 characters.")), + new KeyValuePair("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz123456789012345", new InvalidBucketNameException("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz123456789012345", "Bucket name cannot be greater than 63 characters.")), + new KeyValuePair("my..bucket", new InvalidBucketNameException("my..bucket", "Bucket name cannot have successive periods.")), + new KeyValuePair("MyBucket", new InvalidBucketNameException("MyBucket", "Bucket name cannot have upper case characters")), new KeyValuePair("my!bucket", new InvalidBucketNameException("my!bucket", "Bucket name contains invalid characters.")), new KeyValuePair("mybucket", null ), - new KeyValuePair("mybucket1234dhdjkshdkshdkshdjkshdkjshfkjsfhjkshsjkhjkhfkjd",null ), + new KeyValuePair("mybucket1234dhdjkshdkshdkshdjkshdkjshfkjsfhjkshsjkhjkhfkjd", null), }; - - foreach (KeyValuePair pair in testCases) + + foreach (KeyValuePair pair in testCases) { - - string bucketName = (string)pair.Key; + string bucketName = pair.Key; InvalidBucketNameException expectedException = pair.Value; try { diff --git a/Minio/AWSS3Endpoints.cs b/Minio/AWSS3Endpoints.cs index 36a1b17cf..32a10c972 100644 --- a/Minio/AWSS3Endpoints.cs +++ b/Minio/AWSS3Endpoints.cs @@ -27,12 +27,9 @@ public sealed class AWSS3Endpoints private static readonly Lazy lazy = new Lazy(() => new AWSS3Endpoints()); - private ConcurrentDictionary endpoints; + private readonly ConcurrentDictionary endpoints; - public static AWSS3Endpoints Instance - { - get { return lazy.Value; } - } + public static AWSS3Endpoints Instance => lazy.Value; private AWSS3Endpoints() { @@ -41,7 +38,7 @@ private AWSS3Endpoints() endpoints.TryAdd("ap-northeast-1", "s3-ap-northeast-1.amazonaws.com"); // ap-northeast-2 endpoints.TryAdd("ap-northeast-2", "s3-ap-northeast-2.amazonaws.com"); - //ap-south-1 + // ap-south-1 endpoints.TryAdd("ap-south-1", "s3-ap-south-1.amazonaws.com"); // ap-southeast-1 endpoints.TryAdd("ap-southeast-1", "s3-ap-southeast-1.amazonaws.com"); @@ -63,7 +60,7 @@ private AWSS3Endpoints() endpoints.TryAdd("us-east-1", "s3.amazonaws.com"); // us-east-2 endpoints.TryAdd("us-east-2", "s3-us-east-2.amazonaws.com"); - //ca-central-1 + // ca-central-1 endpoints.TryAdd("ca-central-1", "s3.ca-central-1.amazonaws.com"); // cn-north-1 endpoints.TryAdd("cn-north-1", "s3.cn-north-1.amazonaws.com.cn"); diff --git a/Minio/ApiEndpoints/BucketOperations.cs b/Minio/ApiEndpoints/BucketOperations.cs index 0f897aae2..b229158d4 100644 --- a/Minio/ApiEndpoints/BucketOperations.cs +++ b/Minio/ApiEndpoints/BucketOperations.cs @@ -34,7 +34,6 @@ namespace Minio { public partial class MinioClient : IBucketOperations { - /// /// List all objects in a bucket /// @@ -42,7 +41,7 @@ public partial class MinioClient : IBucketOperations /// Task with an iterator lazily populated with objects public async Task ListBucketsAsync(CancellationToken cancellationToken = default(CancellationToken)) { - var request= await this.CreateRequest(Method.GET,resourcePath:"/").ConfigureAwait(false); + var request = await this.CreateRequest(Method.GET, resourcePath: "/").ConfigureAwait(false); var response = await this.ExecuteTaskAsync(this.NoErrorHandlers, request, cancellationToken).ConfigureAwait(false); ListAllMyBucketsResult bucketList = new ListAllMyBucketsResult(); @@ -50,7 +49,7 @@ public partial class MinioClient : IBucketOperations { var contentBytes = System.Text.Encoding.UTF8.GetBytes(response.Content); using (var stream = new MemoryStream(contentBytes)) - bucketList = (ListAllMyBucketsResult)(new XmlSerializer(typeof(ListAllMyBucketsResult)).Deserialize(stream)); + bucketList = (ListAllMyBucketsResult)new XmlSerializer(typeof(ListAllMyBucketsResult)).Deserialize(stream); return bucketList; } return bucketList; @@ -65,7 +64,7 @@ public partial class MinioClient : IBucketOperations /// Task public async Task MakeBucketAsync(string bucketName, string location = "us-east-1", CancellationToken cancellationToken = default(CancellationToken)) { - if (location.Equals("us-east-1")) + if (location == "us-east-1") { if (this.Region != "") { @@ -74,12 +73,14 @@ public partial class MinioClient : IBucketOperations } // Set Target URL - Uri requestUrl = RequestUtil.MakeTargetURL(this.BaseUrl, this.Secure,location); + Uri requestUrl = RequestUtil.MakeTargetURL(this.BaseUrl, this.Secure, location); SetTargetURL(requestUrl); - var request = new RestRequest("/" + bucketName, Method.PUT); - request.XmlSerializer = new RestSharp.Serializers.DotNetXmlSerializer(); - request.RequestFormat = DataFormat.Xml; + var request = new RestRequest("/" + bucketName, Method.PUT) + { + XmlSerializer = new RestSharp.Serializers.DotNetXmlSerializer(), + RequestFormat = DataFormat.Xml + }; // ``us-east-1`` is not a valid location constraint according to amazon, so we skip it. if (location != "us-east-1") { @@ -180,23 +181,21 @@ public partial class MinioClient : IBucketOperations /// marks location in the iterator sequence /// Task with a tuple populated with objects /// Optional cancellation token to cancel the operation - private async Task>> GetObjectListAsync(string bucketName, string prefix, string delimiter, string marker, CancellationToken cancellationToken = default(CancellationToken)) { var queries = new List(); // null values are treated as empty strings. - if (delimiter == null) { + if (delimiter == null) delimiter = ""; - } - if (prefix == null) { + + if (prefix == null) prefix = ""; - } - if (marker == null) { + + if (marker == null) marker = ""; - } - queries.Add("delimiter="+ Uri.EscapeDataString(delimiter)); + queries.Add("delimiter=" + Uri.EscapeDataString(delimiter)); queries.Add("prefix=" + Uri.EscapeDataString(prefix)); queries.Add("max-keys=1000"); queries.Add("marker=" + Uri.EscapeDataString(marker)); @@ -214,13 +213,13 @@ public partial class MinioClient : IBucketOperations ListBucketResult listBucketResult = null; using (var stream = new MemoryStream(contentBytes)) { - listBucketResult = (ListBucketResult)(new XmlSerializer(typeof(ListBucketResult)).Deserialize(stream)); + listBucketResult = (ListBucketResult)new XmlSerializer(typeof(ListBucketResult)).Deserialize(stream); } XDocument root = XDocument.Parse(response.Content); var items = (from c in root.Root.Descendants("{http://s3.amazonaws.com/doc/2006-03-01/}Contents") - select new Item() + select new Item { Key = c.Element("{http://s3.amazonaws.com/doc/2006-03-01/}Key").Value, LastModified = c.Element("{http://s3.amazonaws.com/doc/2006-03-01/}LastModified").Value, @@ -230,7 +229,7 @@ public partial class MinioClient : IBucketOperations }); var prefixes = (from c in root.Root.Descendants("{http://s3.amazonaws.com/doc/2006-03-01/}CommonPrefixes") - select new Item() + select new Item { Key = c.Element("{http://s3.amazonaws.com/doc/2006-03-01/}Prefix").Value, IsDir = true @@ -238,7 +237,7 @@ public partial class MinioClient : IBucketOperations items = items.Concat(prefixes); - return new Tuple>(listBucketResult, items.ToList()); + return Tuple.Create(listBucketResult, items.ToList()); } /// @@ -247,7 +246,7 @@ public partial class MinioClient : IBucketOperations /// Bucket name. /// Optional cancellation token to cancel the operation /// Task that returns the Bucket policy as a json string - public async Task GetPolicyAsync(string bucketName, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetPolicyAsync(string bucketName, CancellationToken cancellationToken = default(CancellationToken)) { IRestResponse response = null; @@ -276,7 +275,7 @@ public partial class MinioClient : IBucketOperations /// Policy json as string /// Optional cancellation token to cancel the operation /// Task to set a policy - public async Task SetPolicyAsync(String bucketName, String policyJson, CancellationToken cancellationToken = default(CancellationToken)) + public async Task SetPolicyAsync(string bucketName, string policyJson, CancellationToken cancellationToken = default(CancellationToken)) { var request = await this.CreateRequest(Method.PUT, bucketName, resourcePath: "?policy", @@ -300,16 +299,15 @@ public partial class MinioClient : IBucketOperations bucketName, resourcePath: "?notification") .ConfigureAwait(false); - BucketNotification notification = null; var response = await this.ExecuteTaskAsync(this.NoErrorHandlers, request, cancellationToken).ConfigureAwait(false); var contentBytes = System.Text.Encoding.UTF8.GetBytes(response.Content); using (var stream = new MemoryStream(contentBytes)) { - notification = (BucketNotification)(new XmlSerializer(typeof(BucketNotification)).Deserialize(stream)); - return notification; + return (BucketNotification)new XmlSerializer(typeof(BucketNotification)).Deserialize(stream); } } + /// /// Sets the notification configuration for this bucket /// diff --git a/Minio/ApiEndpoints/IBucketOperations.cs b/Minio/ApiEndpoints/IBucketOperations.cs index 9ff1a5153..f034081d3 100644 --- a/Minio/ApiEndpoints/IBucketOperations.cs +++ b/Minio/ApiEndpoints/IBucketOperations.cs @@ -72,7 +72,7 @@ public interface IBucketOperations /// Bucket name. /// Optional cancellation token to cancel the operation /// Returns Task with bucket policy json as string - Task GetPolicyAsync(String bucketName, CancellationToken cancellationToken = default(CancellationToken)); + Task GetPolicyAsync(string bucketName, CancellationToken cancellationToken = default(CancellationToken)); /// /// Sets the current bucket policy @@ -81,7 +81,7 @@ public interface IBucketOperations /// policy json /// Optional cancellation token to cancel the operation /// Returns Task that sets the current bucket policy - Task SetPolicyAsync(String bucketName, String policyJson, CancellationToken cancellationToken = default(CancellationToken)); + Task SetPolicyAsync(string bucketName, string policyJson, CancellationToken cancellationToken = default(CancellationToken)); /// /// Gets the notification configuration set for this bucket @@ -108,6 +108,6 @@ public interface IBucketOperations /// Task RemoveAllBucketNotificationsAsync(string bucketName, CancellationToken cancellationToken = default(CancellationToken)); - // Task ListenBucketNotificationsAsync(string bucketName, string prefix = "", string suffix = "", List events,CancellationToken cancellationToken = default(CancellationToken)); + // Task ListenBucketNotificationsAsync(string bucketName, string prefix = "", string suffix = "", List events, CancellationToken cancellationToken = default(CancellationToken)); } } diff --git a/Minio/ApiEndpoints/IObjectOperations.cs b/Minio/ApiEndpoints/IObjectOperations.cs index cfa40fa23..eded66967 100644 --- a/Minio/ApiEndpoints/IObjectOperations.cs +++ b/Minio/ApiEndpoints/IObjectOperations.cs @@ -93,7 +93,7 @@ public interface IObjectOperations /// /// Lists all incomplete uploads in a given bucket and prefix recursively /// - /// Bucket to list all incomplepte uploads from + /// Bucket to list all incomplete uploads from /// prefix to list all incomplete uploads /// Set to true to recursively list all incomplete uploads /// Optional cancellation token to cancel the operation @@ -144,8 +144,8 @@ public interface IObjectOperations /// Optional Server-side encryption option. Defaults to null. /// Optional cancellation token to cancel the operation /// - //Task GetObjectAsync(string bucketName, string objectName, string filePath,ServerSideEncryption sse = null, CancellationToken cancellationToken = default(CancellationToken)); - Task GetObjectAsync(string bucketName, string objectName, string filePath, ServerSideEncryption sse = null ,CancellationToken cancellationToken = default(CancellationToken)); + // Task GetObjectAsync(string bucketName, string objectName, string filePath, ServerSideEncryption sse = null, CancellationToken cancellationToken = default(CancellationToken)); + Task GetObjectAsync(string bucketName, string objectName, string filePath, ServerSideEncryption sse = null, CancellationToken cancellationToken = default(CancellationToken)); /// /// Presigned get url - returns a presigned url to access an object's data without credentials.URL can have a maximum expiry of @@ -156,7 +156,7 @@ public interface IObjectOperations /// Expiration time in seconds. /// optional override response headers /// optional request date and time in UTC - Task PresignedGetObjectAsync(string bucketName, string objectName, int expiresInt, Dictionary reqParams = null, DateTime? reqDate = null); + Task PresignedGetObjectAsync(string bucketName, string objectName, int expiresInt, Dictionary reqParams = null, DateTime? reqDate = null); /// /// Presigned Put url - returns a presigned url to upload an object without credentials.URL can have a maximum expiry of @@ -168,7 +168,7 @@ public interface IObjectOperations Task PresignedPutObjectAsync(string bucketName, string objectName, int expiresInt); /// - /// Presigned post policy + /// Presigned post policy /// Task>> PresignedPostPolicyAsync(PostPolicy policy); } diff --git a/Minio/ApiEndpoints/ObjectOperations.cs b/Minio/ApiEndpoints/ObjectOperations.cs index 6f4d4d67c..b97dacb45 100644 --- a/Minio/ApiEndpoints/ObjectOperations.cs +++ b/Minio/ApiEndpoints/ObjectOperations.cs @@ -61,7 +61,6 @@ public partial class MinioClient : IObjectOperations var response = await this.ExecuteTaskAsync(this.NoErrorHandlers, request, cancellationToken).ConfigureAwait(false); } - /// /// Get an object. The object will be streamed to the callback given by the user. /// @@ -75,13 +74,13 @@ public partial class MinioClient : IObjectOperations public async Task GetObjectAsync(string bucketName, string objectName, long offset, long length, Action cb, ServerSideEncryption sse = null, CancellationToken cancellationToken = default(CancellationToken)) { if (offset < 0) - throw new ArgumentException("Offset should be zero or greater"); + throw new ArgumentException("Offset should be zero or greater", nameof(offset)); if (length < 0) - throw new ArgumentException("Length should be greater than zero"); + throw new ArgumentException("Length should be greater than zero", nameof(length)); await StatObjectAsync(bucketName, objectName, cancellationToken: cancellationToken).ConfigureAwait(false); - Dictionary headerMap = new Dictionary(); + var headerMap = new Dictionary(); if (length > 0) headerMap.Add("Range", "bytes=" + offset.ToString() + "-" + (offset + length - 1).ToString()); @@ -148,7 +147,7 @@ public partial class MinioClient : IObjectOperations else if (fileSize > length) { throw new ArgumentException("'" + fileName + "': object size " + length + " is smaller than file size " - + fileSize); + + fileSize, nameof(fileSize)); } else if (!tempFileExists) { @@ -200,9 +199,9 @@ await GetObjectAsync(bucketName, objectName, (stream) => /// /// Bucket to create object in /// Key of the new object + /// Stream of bytes to send /// Total size of bytes to be written, must match with data's length /// Content type of the new object, null defaults to "application/octet-stream" - /// Stream of bytes to send /// Object metadata to be stored. Defaults to null. /// Server-side encryption option. Defaults to null. /// Optional cancellation token to cancel the operation @@ -234,7 +233,7 @@ await GetObjectAsync(bucketName, objectName, (stream) => } if (data == null) { - throw new ArgumentNullException("Invalid input stream,cannot be null"); + throw new ArgumentNullException(nameof(data), "Invalid input stream, cannot be null"); } // for sizes less than 5Mb , put a single object @@ -285,7 +284,7 @@ await GetObjectAsync(bucketName, objectName, (stream) => } numPartsUploaded += 1; string etag = await this.PutObjectAsync(bucketName, objectName, uploadId, partNumber, dataToCopy, metaData, sseHeaders, cancellationToken).ConfigureAwait(false); - totalParts[partNumber - 1] = new Part() { PartNumber = partNumber, ETag = etag, size = (long)expectedReadSize }; + totalParts[partNumber - 1] = new Part { PartNumber = partNumber, ETag = etag, size = (long)expectedReadSize }; } // This shouldn't happen where stream size is known. @@ -350,7 +349,6 @@ private async Task CompleteMultipartUploadAsync(string bucketName, string object /// private IObservable ListParts(string bucketName, string objectName, string uploadId, CancellationToken cancellationToken) { - return Observable.Create( async obs => { @@ -396,19 +394,19 @@ private async Task>> GetListPartsAsync(string var contentBytes = System.Text.Encoding.UTF8.GetBytes(response.Content); ListPartsResult listPartsResult = null; using (var stream = new MemoryStream(contentBytes)) - listPartsResult = (ListPartsResult)(new XmlSerializer(typeof(ListPartsResult)).Deserialize(stream)); + listPartsResult = (ListPartsResult)new XmlSerializer(typeof(ListPartsResult)).Deserialize(stream); XDocument root = XDocument.Parse(response.Content); var uploads = (from c in root.Root.Descendants("{http://s3.amazonaws.com/doc/2006-03-01/}Part") - select new Part() + select new Part { PartNumber = int.Parse(c.Element("{http://s3.amazonaws.com/doc/2006-03-01/}PartNumber").Value, CultureInfo.CurrentCulture), ETag = c.Element("{http://s3.amazonaws.com/doc/2006-03-01/}ETag").Value.Replace("\"", ""), size = long.Parse(c.Element("{http://s3.amazonaws.com/doc/2006-03-01/}Size").Value, CultureInfo.CurrentCulture) }); - return new Tuple>(listPartsResult, uploads.ToList()); + return Tuple.Create(listPartsResult, uploads.ToList()); } /// @@ -436,7 +434,7 @@ private async Task>> GetListPartsAsync(string var contentBytes = System.Text.Encoding.UTF8.GetBytes(response.Content); InitiateMultipartUploadResult newUpload = null; using (var stream = new MemoryStream(contentBytes)) - newUpload = (InitiateMultipartUploadResult)(new XmlSerializer(typeof(InitiateMultipartUploadResult)).Deserialize(stream)); + newUpload = (InitiateMultipartUploadResult)new XmlSerializer(typeof(InitiateMultipartUploadResult)).Deserialize(stream); return newUpload.UploadId; } @@ -544,25 +542,25 @@ private async Task>> GetMultipart var contentBytes = System.Text.Encoding.UTF8.GetBytes(response.Content); ListMultipartUploadsResult listBucketResult = null; using (var stream = new MemoryStream(contentBytes)) - listBucketResult = (ListMultipartUploadsResult)(new XmlSerializer(typeof(ListMultipartUploadsResult)).Deserialize(stream)); + listBucketResult = (ListMultipartUploadsResult)new XmlSerializer(typeof(ListMultipartUploadsResult)).Deserialize(stream); XDocument root = XDocument.Parse(response.Content); var uploads = (from c in root.Root.Descendants("{http://s3.amazonaws.com/doc/2006-03-01/}Upload") - select new Upload() + select new Upload { Key = c.Element("{http://s3.amazonaws.com/doc/2006-03-01/}Key").Value, UploadId = c.Element("{http://s3.amazonaws.com/doc/2006-03-01/}UploadId").Value, Initiated = c.Element("{http://s3.amazonaws.com/doc/2006-03-01/}Initiated").Value }); - return new Tuple>(listBucketResult, uploads.ToList()); + return Tuple.Create(listBucketResult, uploads.ToList()); } /// /// Lists all incomplete uploads in a given bucket and prefix recursively /// - /// Bucket to list all incomplepte uploads from + /// Bucket to list all incomplete uploads from /// Filter all incomplete uploads starting with this prefix /// Set to true to recursively list all incomplete uploads /// Optional cancellation token to cancel the operation @@ -691,7 +689,7 @@ private async Task> removeObjectsAsync(string bucketName, List var contentBytes = System.Text.Encoding.UTF8.GetBytes(response.Content); DeleteObjectsResult deleteResult = null; using (var stream = new MemoryStream(contentBytes)) - deleteResult = (DeleteObjectsResult)(new XmlSerializer(typeof(DeleteObjectsResult)).Deserialize(stream)); + deleteResult = (DeleteObjectsResult)new XmlSerializer(typeof(DeleteObjectsResult)).Deserialize(stream); if (deleteResult == null) { @@ -734,7 +732,7 @@ private async Task> removeObjectsAsync(string bucketName, List if (i % 1000 == 0) break; } - if (objectList.Count() > 0) + if (objectList.Count > 0) { var errorsList = await removeObjectsAsync(bucketName, objectList, cancellationToken).ConfigureAwait(false); foreach (DeleteError error in errorsList) @@ -773,9 +771,9 @@ private async Task> removeObjectsAsync(string bucketName, List DateTime lastModified = new DateTime(); string etag = ""; string contentType = null; - Dictionary metaData = new Dictionary(StringComparer.OrdinalIgnoreCase); + var metaData = new Dictionary(StringComparer.OrdinalIgnoreCase); - //Supported headers for object. + // Supported headers for object. List supportedHeaders = new List { "cache-control", "content-encoding", "content-type" }; foreach (Parameter parameter in response.Headers) @@ -801,7 +799,6 @@ private async Task> removeObjectsAsync(string bucketName, List { metaData[parameter.Name] = parameter.Value.ToString(); } - } return new ObjectStat(objectName, size, lastModified, etag, contentType, metaData); } @@ -860,15 +857,15 @@ internal byte[] ReadFull(Stream data, int currentPartSize) { if (bucketName == null) { - throw new ArgumentException("Source bucket name cannot be empty"); + throw new ArgumentException("Source bucket name cannot be empty", nameof(bucketName)); } if (objectName == null) { - throw new ArgumentException("Source object name cannot be empty"); + throw new ArgumentException("Source object name cannot be empty", nameof(objectName)); } if (destBucketName == null) { - throw new ArgumentException("Destination bucket name cannot be empty"); + throw new ArgumentException("Destination bucket name cannot be empty", nameof(destBucketName)); } // Escape source object path. string sourceObjectPath = bucketName + "/" + utils.UrlEncode(objectName); @@ -880,15 +877,14 @@ internal byte[] ReadFull(Stream data, int currentPartSize) } ServerSideEncryption sseGet = sseSrc; - if (sseSrc is SSECopy) + if (sseSrc is SSECopy sseCpy) { - SSECopy sseCpy = (SSECopy)sseSrc; sseGet = sseCpy.CloneToSSEC(); } // Get Stats on the source object ObjectStat srcStats = await this.StatObjectAsync(bucketName, objectName, sse: sseGet, cancellationToken: cancellationToken).ConfigureAwait(false); // Copy metadata from the source object if no metadata replace directive - Dictionary meta = new Dictionary(StringComparer.OrdinalIgnoreCase); + var meta = new Dictionary(StringComparer.OrdinalIgnoreCase); Dictionary m = metadata; if (copyConditions != null && !copyConditions.HasReplaceMetadataDirective()) { @@ -911,13 +907,13 @@ internal byte[] ReadFull(Stream data, int currentPartSize) } long copySize = (srcByteRangeSize == 0) ? srcStats.Size : srcByteRangeSize; - if ((srcByteRangeSize > srcStats.Size) || - ((srcByteRangeSize > 0) && (copyConditions.byteRangeEnd >= srcStats.Size))) + if ((srcByteRangeSize > srcStats.Size) || ((srcByteRangeSize > 0) && (copyConditions.byteRangeEnd >= srcStats.Size))) throw new ArgumentException("Specified byte range (" + copyConditions.byteRangeStart.ToString() + "-" + copyConditions.byteRangeEnd.ToString() + ") does not fit within source object (size=" + srcStats.Size.ToString() + ")"); - if ((copySize > Constants.MaxSingleCopyObjectSize) || - (srcByteRangeSize > 0 && (srcByteRangeSize != srcStats.Size))) + if ((copySize > Constants.MaxSingleCopyObjectSize) || (srcByteRangeSize > 0 && (srcByteRangeSize != srcStats.Size))) + { await MultipartCopyUploadAsync(bucketName, objectName, destBucketName, destObjectName, copyConditions, copySize, meta, sseSrc, sseDest, cancellationToken).ConfigureAwait(false); + } else { if (sseSrc != null && sseSrc is SSECopy) @@ -933,7 +929,7 @@ internal byte[] ReadFull(Stream data, int currentPartSize) } /// - /// Create the copy request,execute it and + /// Create the copy request, execute it and /// /// Bucket name where the object to be copied exists. /// Object name source to be copied. @@ -942,12 +938,11 @@ internal byte[] ReadFull(Stream data, int currentPartSize) /// optionally can take a key value CopyConditions as well for conditionally attempting copyObject. /// optional custom header to specify byte range /// optional string to specify upload id and part number - /// type of XML serialization to be applied on the server response /// Optional cancellation token to cancel the operation + /// type of XML serialization to be applied on the server response /// private async Task CopyObjectRequestAsync(string bucketName, string objectName, string destBucketName, string destObjectName, CopyConditions copyConditions, Dictionary customHeaders, string resource, CancellationToken cancellationToken, Type type) { - // Escape source object path. string sourceObjectPath = bucketName + "/" + utils.UrlEncode(objectName); @@ -983,9 +978,9 @@ private async Task CopyObjectRequestAsync(string bucketName, string obje using (var stream = new MemoryStream(contentBytes)) { if (type == typeof(CopyObjectResult)) - copyResult = (CopyObjectResult)(new XmlSerializer(typeof(CopyObjectResult)).Deserialize(stream)); + copyResult = (CopyObjectResult)new XmlSerializer(typeof(CopyObjectResult)).Deserialize(stream); if (type == typeof(CopyPartResult)) - copyResult = (CopyPartResult)(new XmlSerializer(typeof(CopyPartResult)).Deserialize(stream)); + copyResult = (CopyPartResult)new XmlSerializer(typeof(CopyPartResult)).Deserialize(stream); } return copyResult; @@ -997,7 +992,7 @@ private async Task CopyObjectRequestAsync(string bucketName, string obje /// source bucket name /// source object name /// destination bucket name - /// destiantion object name + /// destination object name /// copyconditions /// size of copy upload /// optional metadata on the destination side @@ -1041,8 +1036,10 @@ private async Task CopyObjectRequestAsync(string bucketName, string obje { resource += "?uploadId=" + uploadId + "&partNumber=" + partNumber; } - Dictionary customHeader = new Dictionary(); - customHeader.Add("x-amz-copy-source-range", "bytes=" + partCondition.byteRangeStart.ToString() + "-" + partCondition.byteRangeEnd.ToString()); + var customHeader = new Dictionary + { + { "x-amz-copy-source-range", "bytes=" + partCondition.byteRangeStart.ToString() + "-" + partCondition.byteRangeEnd.ToString() } + }; if (sseSrc != null && sseSrc is SSECopy) { sseSrc.Marshal(customHeader); @@ -1053,7 +1050,7 @@ private async Task CopyObjectRequestAsync(string bucketName, string obje } CopyPartResult cpPartResult = (CopyPartResult)await this.CopyObjectRequestAsync(bucketName, objectName, destBucketName, destObjectName, copyConditions, customHeader, resource, cancellationToken, typeof(CopyPartResult)).ConfigureAwait(false); - totalParts[partNumber - 1] = new Part() { PartNumber = partNumber, ETag = cpPartResult.ETag, size = (long)expectedReadSize }; + totalParts[partNumber - 1] = new Part { PartNumber = partNumber, ETag = cpPartResult.ETag, size = (long)expectedReadSize }; } Dictionary etags = new Dictionary(); @@ -1116,17 +1113,17 @@ public async Task>> PresignedPostPolicy if (!policy.IsBucketSet()) { - throw new ArgumentException("bucket should be set"); + throw new ArgumentException("bucket should be set", nameof(policy)); } if (!policy.IsKeySet()) { - throw new ArgumentException("key should be set"); + throw new ArgumentException("key should be set", nameof(policy)); } if (!policy.IsExpirationSet()) { - throw new ArgumentException("expiration should be set"); + throw new ArgumentException("expiration should be set", nameof(policy)); } // Initialize a new client. @@ -1153,7 +1150,7 @@ public async Task>> PresignedPostPolicy policy.SetPolicy(policyBase64); policy.SetSignature(signature); - return new Tuple>(this.restClient.BaseUrl.AbsoluteUri, policy.GetFormData()); + return Tuple.Create(this.restClient.BaseUrl.AbsoluteUri, policy.GetFormData()); } } } diff --git a/Minio/BucketRegionCache.cs b/Minio/BucketRegionCache.cs index 84f41a741..2ab5d301c 100644 --- a/Minio/BucketRegionCache.cs +++ b/Minio/BucketRegionCache.cs @@ -32,12 +32,9 @@ public sealed class BucketRegionCache private static readonly Lazy lazy = new Lazy(() => new BucketRegionCache()); - private ConcurrentDictionary regionMap; + private readonly ConcurrentDictionary regionMap; - public static BucketRegionCache Instance - { - get { return lazy.Value; } - } + public static BucketRegionCache Instance => lazy.Value; private BucketRegionCache() { this.regionMap = new ConcurrentDictionary(); @@ -50,9 +47,8 @@ private BucketRegionCache() /// public string Region(string bucketName) { - string value = null; - this.regionMap.TryGetValue(bucketName, out value); - return value != null ? value : "us-east-1"; + this.regionMap.TryGetValue(bucketName, out string value); + return value ?? "us-east-1"; } /// @@ -71,8 +67,7 @@ public void Add(string bucketName, string region) /// public void Remove(string bucketName) { - string value; - this.regionMap.TryRemove(bucketName, out value); + this.regionMap.TryRemove(bucketName, out string value); } /// @@ -80,10 +75,9 @@ public void Remove(string bucketName) /// /// /// - public bool Exists(String bucketName) + public bool Exists(string bucketName) { - string value = null; - this.regionMap.TryGetValue(bucketName, out value); + this.regionMap.TryGetValue(bucketName, out string value); return value != null; } @@ -115,7 +109,6 @@ internal async Task Update(MinioClient client, string bucketName) var stream = new MemoryStream(contentBytes); XDocument root = XDocument.Parse(response.Content); location = root.Root.Value; - } if (location == null || location == "") { @@ -124,7 +117,7 @@ internal async Task Update(MinioClient client, string bucketName) else { // eu-west-1 can be sometimes 'EU'. - if ("EU".Equals(location)) + if (location == "EU") { region = "eu-west-1"; } diff --git a/Minio/DataModel/CopyConditions.cs b/Minio/DataModel/CopyConditions.cs index b3fdc0c93..1bdbd5040 100644 --- a/Minio/DataModel/CopyConditions.cs +++ b/Minio/DataModel/CopyConditions.cs @@ -25,7 +25,7 @@ namespace Minio.DataModel /// public class CopyConditions { - private Dictionary copyConditions = new Dictionary(); + private readonly Dictionary copyConditions = new Dictionary(); internal long byteRangeStart = 0; internal long byteRangeEnd = -1; @@ -54,7 +54,7 @@ public void SetModified(DateTime date) { if (date == null) { - throw new ArgumentException("Date cannot be empty"); + throw new ArgumentException("Date cannot be empty", nameof(date)); } copyConditions.Add("x-amz-copy-source-if-modified-since", date.ToUniversalTime().ToString("r")); } @@ -68,7 +68,7 @@ public void SetUnmodified(DateTime date) { if (date == null) { - throw new ArgumentException("Date cannot be empty"); + throw new ArgumentException("Date cannot be empty", nameof(date)); } copyConditions.Add("x-amz-copy-source-if-unmodified-since", date.ToUniversalTime().ToString("r")); } @@ -83,7 +83,7 @@ public void SetMatchETag(string etag) { if (etag == null) { - throw new ArgumentException("ETag cannot be empty"); + throw new ArgumentException("ETag cannot be empty", nameof(etag)); } copyConditions.Add("x-amz-copy-source-if-match", etag); } @@ -98,13 +98,13 @@ public void SetMatchETagNone(string etag) { if (etag == null) { - throw new ArgumentException("ETag cannot be empty"); + throw new ArgumentException("ETag cannot be empty", nameof(etag)); } copyConditions.Add("x-amz-copy-source-if-none-match", etag); } /// - /// Set replace metadata directive which specifies that server side copy needs to replace metadata + /// Set replace metadata directive which specifies that server side copy needs to replace metadata /// on destination with custom metadata provided in the request. /// public void SetReplaceMetadataDirective() @@ -121,14 +121,14 @@ public bool HasReplaceMetadataDirective() foreach (var item in copyConditions) { if (item.Key.Equals("x-amz-metadata-directive", StringComparison.OrdinalIgnoreCase) && - (item.Value.ToUpper().Equals("REPLACE"))) + item.Value.ToUpper().Equals("REPLACE")) return true; } return false; } /// - /// Set Byte Range condition, copy object which falls within the + /// Set Byte Range condition, copy object which falls within the /// start and end byte range specified by user /// /// diff --git a/Minio/DataModel/CreateBucketConfiguration.cs b/Minio/DataModel/CreateBucketConfiguration.cs index fb5d854ed..968801e13 100644 --- a/Minio/DataModel/CreateBucketConfiguration.cs +++ b/Minio/DataModel/CreateBucketConfiguration.cs @@ -26,7 +26,7 @@ public CreateBucketConfiguration() this.LocationConstraint = null; } - public CreateBucketConfiguration(string location=null) + public CreateBucketConfiguration(string location = null) { this.LocationConstraint = location; } diff --git a/Minio/DataModel/DeleteObject.cs b/Minio/DataModel/DeleteObject.cs index e3d5d4414..ba49a1b4f 100644 --- a/Minio/DataModel/DeleteObject.cs +++ b/Minio/DataModel/DeleteObject.cs @@ -24,17 +24,17 @@ namespace Minio.DataModel public class DeleteObject { [XmlElement("Key")] - public string Key { get;set; } + public string Key { get; set; } [XmlElement("VersionId")] - public string VersionId { get;set;} + public string VersionId { get; set; } public DeleteObject() { this.Key = null; this.VersionId = null; } - public DeleteObject(string key,string versionId=null) + public DeleteObject(string key, string versionId = null) { this.Key = key; this.VersionId = versionId; diff --git a/Minio/DataModel/DeleteObjectsRequest.cs b/Minio/DataModel/DeleteObjectsRequest.cs index 0497794b4..d1994c3de 100644 --- a/Minio/DataModel/DeleteObjectsRequest.cs +++ b/Minio/DataModel/DeleteObjectsRequest.cs @@ -27,9 +27,9 @@ public class DeleteObjectsRequest [XmlElement("Quiet")] public bool quiet { get; set; } [XmlElement("Object")] - public List objects { get; set;} - - public DeleteObjectsRequest(List objectsList, bool quiet=true) + public List objects { get; set; } + + public DeleteObjectsRequest(List objectsList, bool quiet = true) { this.quiet = quiet; this.objects = objectsList; diff --git a/Minio/DataModel/DeleteObjectsResult.cs b/Minio/DataModel/DeleteObjectsResult.cs index f25317095..d4624a89d 100644 --- a/Minio/DataModel/DeleteObjectsResult.cs +++ b/Minio/DataModel/DeleteObjectsResult.cs @@ -31,14 +31,8 @@ public class DeleteObjectsResult [XmlElement("Error")] public List errorList; - public List ObjectsList() - { - return this.objectsList; - } + public List ObjectsList() => this.objectsList; - public List ErrorList() - { - return this.errorList; - } + public List ErrorList() => this.errorList; } } diff --git a/Minio/DataModel/DeletedObject.cs b/Minio/DataModel/DeletedObject.cs index 41aca287b..947547dd8 100644 --- a/Minio/DataModel/DeletedObject.cs +++ b/Minio/DataModel/DeletedObject.cs @@ -23,15 +23,15 @@ namespace Minio.DataModel public class DeletedObject { [XmlElement("Key")] - public string key { get;set; } + public string key { get; set; } [XmlElement("VersionId")] - public string versionId { get;set;} - + public string versionId { get; set; } + [XmlElement("DeleteMarker")] - public string deleteMarker { get;set;} + public string deleteMarker { get; set; } [XmlElement("DeleteMarkerVersionId")] - public string deleteMarkerVersionId { get;set;} + public string deleteMarkerVersionId { get; set; } } } diff --git a/Minio/DataModel/Item.cs b/Minio/DataModel/Item.cs index ace936d4c..47aa07afe 100644 --- a/Minio/DataModel/Item.cs +++ b/Minio/DataModel/Item.cs @@ -53,7 +53,7 @@ public DateTime? LastModifiedDateTime get { DateTime? dt = null; - if(!string.IsNullOrEmpty(this.LastModified)) + if (!string.IsNullOrEmpty(this.LastModified)) { dt = DateTime.Parse(this.LastModified, CultureInfo.InvariantCulture); } diff --git a/Minio/DataModel/Notification/Arn.cs b/Minio/DataModel/Notification/Arn.cs index 28d92426a..9b4aa931d 100644 --- a/Minio/DataModel/Notification/Arn.cs +++ b/Minio/DataModel/Notification/Arn.cs @@ -24,17 +24,17 @@ namespace Minio.DataModel /// public class Arn { - private string Partition { get; } - private string Service { get; } - private string Region { get; } - private string AccountID { get; } - private string Resource { get; } + private string Partition { get; } + private string Service { get; } + private string Region { get; } + private string AccountID { get; } + private string Resource { get; } [XmlText] - private string arnString; + private readonly string arnString; public Arn() - { + { } /// @@ -73,9 +73,6 @@ public Arn(string partition, string service, string region, string accountId, st this.arnString = "arn:" + this.Partition + ":" + this.Service + ":" + this.Region + ":" + this.AccountID + ":" + this.Resource; } - public override string ToString() - { - return arnString; - } + public override string ToString() => arnString; } } diff --git a/Minio/DataModel/Notification/BucketNotification.cs b/Minio/DataModel/Notification/BucketNotification.cs index 8169a023b..ed2fe8b81 100644 --- a/Minio/DataModel/Notification/BucketNotification.cs +++ b/Minio/DataModel/Notification/BucketNotification.cs @@ -65,7 +65,6 @@ public void AddTopic(TopicConfig topicConfig) /// public void AddQueue(QueueConfig queueConfig) { - bool isQueueFound = this.QueueConfigs.Exists(t => t.Equals(queueConfig)); if (!isQueueFound) { @@ -119,25 +118,13 @@ public void RemoveLambdaByArn(Arn lambdaArn) /// Helper methods to guide XMLSerializer /// /// - public bool ShouldSerializeLambdaConfigs() - { - return LambdaConfigs.Count > 0; - } + public bool ShouldSerializeLambdaConfigs() => LambdaConfigs.Count > 0; - public bool ShouldSerializeTopicConfigs() - { - return TopicConfigs.Count > 0; - } + public bool ShouldSerializeTopicConfigs() => TopicConfigs.Count > 0; - public bool ShouldSerializeQueueConfigs() - { - return QueueConfigs.Count > 0; - } + public bool ShouldSerializeQueueConfigs() => QueueConfigs.Count > 0; - public bool ShouldSerializeName() - { - return this.Name != null; - } + public bool ShouldSerializeName() => this.Name != null; /// /// Serializes the notification configuration as an XML string @@ -145,8 +132,10 @@ public bool ShouldSerializeName() /// public string ToXML() { - XmlWriterSettings settings = new XmlWriterSettings(); - settings.OmitXmlDeclaration = true; + XmlWriterSettings settings = new XmlWriterSettings + { + OmitXmlDeclaration = true + }; using (MemoryStream ms = new MemoryStream()) { using (XmlWriter writer = XmlWriter.Create(ms, settings)) diff --git a/Minio/DataModel/Notification/Filter.cs b/Minio/DataModel/Notification/Filter.cs index 03cbb2b1c..4c45823ca 100644 --- a/Minio/DataModel/Notification/Filter.cs +++ b/Minio/DataModel/Notification/Filter.cs @@ -38,9 +38,6 @@ public Filter(S3Key key) } // Helper to XMLSerializer which decides whether to serialize S3Key - public bool ShouldSerializeS3Key() - { - return S3Key.FilterRules.Count != 0; - } + public bool ShouldSerializeS3Key() => S3Key.FilterRules.Count != 0; } } \ No newline at end of file diff --git a/Minio/DataModel/Notification/FilterRule.cs b/Minio/DataModel/Notification/FilterRule.cs index 610e8fe37..f76c1a652 100644 --- a/Minio/DataModel/Notification/FilterRule.cs +++ b/Minio/DataModel/Notification/FilterRule.cs @@ -43,14 +43,8 @@ public FilterRule(string name, string value) this.Value = value; } - public bool ShouldSerializeName() - { - return this.Name != null; - } + public bool ShouldSerializeName() => this.Name != null; - public bool ShouldSerializeValue() - { - return this.Value != null; - } + public bool ShouldSerializeValue() => this.Value != null; } } diff --git a/Minio/DataModel/Notification/LambdaConfig.cs b/Minio/DataModel/Notification/LambdaConfig.cs index 74385261b..13d416865 100644 --- a/Minio/DataModel/Notification/LambdaConfig.cs +++ b/Minio/DataModel/Notification/LambdaConfig.cs @@ -42,7 +42,7 @@ public LambdaConfig(Arn arn) : base(arn) } // Implement equality for this object - public override bool Equals(Object obj) + public override bool Equals(object obj) { LambdaConfig other = (LambdaConfig)obj; // If parameter is null return false. @@ -53,9 +53,6 @@ public override bool Equals(Object obj) return other.Lambda.Equals(this.Lambda); } - public override int GetHashCode() - { - return this.Lambda.GetHashCode(); - } + public override int GetHashCode() => this.Lambda.GetHashCode(); } } diff --git a/Minio/DataModel/Notification/NotificationConfiguration.cs b/Minio/DataModel/Notification/NotificationConfiguration.cs index 4e20f257f..adb9cf485 100644 --- a/Minio/DataModel/Notification/NotificationConfiguration.cs +++ b/Minio/DataModel/Notification/NotificationConfiguration.cs @@ -93,29 +93,20 @@ public void AddFilterPrefix(string prefix) { this.Filter.S3Key.FilterRules[i] = newFilterRule; return; - } + } } this.Filter.S3Key.FilterRules.Add(newFilterRule); } - public bool ShouldSerializeFilter() - { - return this.Filter != null; - } + public bool ShouldSerializeFilter() => this.Filter != null; - public bool ShouldSerializeId() - { - return Id != null; - } + public bool ShouldSerializeId() => Id != null; public bool ShouldSerializeEvents() { return this.Events != null && this.Events.Count > 0; } - internal bool IsIdSet() - { - return this.Id != null; - } + internal bool IsIdSet() => this.Id != null; } } diff --git a/Minio/DataModel/Notification/QueueConfig.cs b/Minio/DataModel/Notification/QueueConfig.cs index 1126f4511..5d7a2545d 100644 --- a/Minio/DataModel/Notification/QueueConfig.cs +++ b/Minio/DataModel/Notification/QueueConfig.cs @@ -32,7 +32,7 @@ public QueueConfig() : base() public QueueConfig(string arn) : base(arn) { - this.Queue = arn.ToString(); + this.Queue = arn; } public QueueConfig(Arn arn) : base(arn) @@ -41,7 +41,7 @@ public QueueConfig(Arn arn) : base(arn) } // Implement equality for this object - public override bool Equals(Object obj) + public override bool Equals(object obj) { QueueConfig other = (QueueConfig)obj; // If parameter is null return false. @@ -52,9 +52,6 @@ public override bool Equals(Object obj) return other.Queue.Equals(this.Queue); } - public override int GetHashCode() - { - return this.Queue.GetHashCode(); - } + public override int GetHashCode() => this.Queue.GetHashCode(); } } diff --git a/Minio/DataModel/Notification/S3Key.cs b/Minio/DataModel/Notification/S3Key.cs index 9824212c8..16a35e1ad 100644 --- a/Minio/DataModel/Notification/S3Key.cs +++ b/Minio/DataModel/Notification/S3Key.cs @@ -49,9 +49,6 @@ internal bool IsFilterRulesSet() return this.filterRules != null && this.filterRules.Count > 0; } - public bool ShouldSerializeFilterRules() - { - return this.filterRules.Count > 0; - } + public bool ShouldSerializeFilterRules() => this.filterRules.Count > 0; } } diff --git a/Minio/DataModel/Notification/TopicConfig.cs b/Minio/DataModel/Notification/TopicConfig.cs index f84a05571..3720c14b5 100644 --- a/Minio/DataModel/Notification/TopicConfig.cs +++ b/Minio/DataModel/Notification/TopicConfig.cs @@ -47,7 +47,7 @@ public TopicConfig(Arn arn) : base(arn) /// /// /// - public override bool Equals(Object obj) + public override bool Equals(object obj) { TopicConfig other = (TopicConfig)obj; // If parameter is null return false. @@ -58,9 +58,6 @@ public override bool Equals(Object obj) return other.Topic.Equals(this.Topic); } - public override int GetHashCode() - { - return this.Topic.GetHashCode(); - } + public override int GetHashCode() => this.Topic.GetHashCode(); } } diff --git a/Minio/DataModel/ObjectStat.cs b/Minio/DataModel/ObjectStat.cs index 777bbf450..afcf73fa0 100644 --- a/Minio/DataModel/ObjectStat.cs +++ b/Minio/DataModel/ObjectStat.cs @@ -49,7 +49,7 @@ public ObjectStat(string objectName, long size, DateTime lastModified, string et public override string ToString() { - return string.Format("{0} : Size({1}) LastModified({2}) ETag({3}) Content-Type({4})",this.ObjectName, this.Size, this.LastModified, this.ETag, this.ContentType); + return string.Format("{0} : Size({1}) LastModified({2}) ETag({3}) Content-Type({4})", this.ObjectName, this.Size, this.LastModified, this.ETag, this.ContentType); } } } diff --git a/Minio/DataModel/Part.cs b/Minio/DataModel/Part.cs index 0f038402c..880efb900 100644 --- a/Minio/DataModel/Part.cs +++ b/Minio/DataModel/Part.cs @@ -24,8 +24,8 @@ public class Part private string etag; public int PartNumber { get; set; } public long size { get; set; } - public DateTime lastModified { get; set; } - + public DateTime lastModified { get; set; } + public string ETag { get @@ -45,9 +45,6 @@ public string ETag } } - public long PartSize() - { - return size; - } + public long PartSize() => size; } } diff --git a/Minio/DataModel/PostPolicy.cs b/Minio/DataModel/PostPolicy.cs index 7c26d27f7..35aa89187 100644 --- a/Minio/DataModel/PostPolicy.cs +++ b/Minio/DataModel/PostPolicy.cs @@ -23,9 +23,9 @@ namespace Minio.DataModel public class PostPolicy { private DateTime expiration; - private List> policies = + private readonly List> policies = new List>(); - private Dictionary formData = new Dictionary(); + private readonly Dictionary formData = new Dictionary(); public string Key { get; private set; } public string Bucket { get; private set; } @@ -46,9 +46,9 @@ public void SetKey(string key) { if (string.IsNullOrEmpty(key)) { - throw new ArgumentException("Object key cannot be null or empty"); + throw new ArgumentException("Object key cannot be null or empty", nameof(key)); } - this.policies.Add(new Tuple("eq", "$key", key)); + this.policies.Add(Tuple.Create("eq", "$key", key)); this.formData.Add("key", key); this.Key = key; } @@ -61,9 +61,9 @@ public void SetKeyStartsWith(string keyStartsWith) { if (string.IsNullOrEmpty(keyStartsWith)) { - throw new ArgumentException("Object key prefix cannot be null or empty"); + throw new ArgumentException("Object key prefix cannot be null or empty", nameof(keyStartsWith)); } - this.policies.Add(new Tuple("starts-with", "$key", keyStartsWith)); + this.policies.Add(Tuple.Create("starts-with", "$key", keyStartsWith)); this.formData.Add("key", keyStartsWith); } @@ -75,9 +75,9 @@ public void SetBucket(string bucket) { if (string.IsNullOrEmpty(bucket)) { - throw new ArgumentException("Bucket name cannot be null or empty"); + throw new ArgumentException("Bucket name cannot be null or empty", nameof(bucket)); } - this.policies.Add(new Tuple("eq", "$bucket", bucket)); + this.policies.Add(Tuple.Create("eq", "$bucket", bucket)); this.formData.Add("bucket", bucket); this.Bucket = bucket; } @@ -90,23 +90,23 @@ public void SetcontentType(string contentType) { if (string.IsNullOrEmpty(contentType)) { - throw new ArgumentException("Content-Type argument cannot be null or empty"); + throw new ArgumentException("Content-Type argument cannot be null or empty", nameof(contentType)); } - this.policies.Add(new Tuple("eq", "$Content-Type", contentType)); + this.policies.Add(Tuple.Create("eq", "$Content-Type", contentType)); this.formData.Add("Content-Type", contentType); } /// - /// Set content encoding + /// Set content encoding /// /// ContentEncoding for the policy public void SetContentEncoding(string contentEncoding) { if (string.IsNullOrEmpty(contentEncoding)) { - throw new ArgumentException("Content-Encoding argument cannot be null or empty"); + throw new ArgumentException("Content-Encoding argument cannot be null or empty", nameof(contentEncoding)); } - this.policies.Add(new Tuple("eq", "$Content-Encoding", contentEncoding)); + this.policies.Add(Tuple.Create("eq", "$Content-Encoding", contentEncoding)); this.formData.Add("Content-Encoding", contentEncoding); } @@ -118,13 +118,13 @@ public void SetContentLength(long contentLength) { if (contentLength <= 0) { - throw new ArgumentException("Negative Content length"); + throw new ArgumentException("Negative Content length", nameof(contentLength)); } - this.policies.Add(new Tuple("content-length-range", contentLength.ToString(), contentLength.ToString())); + this.policies.Add(Tuple.Create("content-length-range", contentLength.ToString(), contentLength.ToString())); } /// - /// Set content range + /// Set content range /// /// ContentRange for the policy /// @@ -136,11 +136,11 @@ public void SetContentRange(long startRange, long endRange) } if (startRange > endRange) { - throw new ArgumentException("Start range is greater than end range"); + throw new ArgumentException("Start range is greater than end range", nameof(startRange)); } - this.policies.Add(new Tuple("content-length-range", startRange.ToString(), endRange.ToString())); + this.policies.Add(Tuple.Create("content-length-range", startRange.ToString(), endRange.ToString())); } - + /// /// Set session token /// @@ -149,20 +149,21 @@ public void SetSessionToken(string sessionToken) { if (!string.IsNullOrEmpty(sessionToken)) { - this.policies.Add(new Tuple("eq", "$x-amz-security-token", sessionToken)); + this.policies.Add(Tuple.Create("eq", "$x-amz-security-token", sessionToken)); this.formData.Add("x-amz-security-token", sessionToken); } } + /// - /// Set the success action status of the object for this policy based upload. + /// Set the success action status of the object for this policy based upload. /// /// Success action status public void SetSuccessStatusAction(string status) { if (string.IsNullOrEmpty(status)) - throw new ArgumentException("Status is Empty"); + throw new ArgumentException("Status is Empty", nameof(status)); - this.policies.Add(new Tuple("eq", "$success_action_status", status)); + this.policies.Add(Tuple.Create("eq", "$success_action_status", status)); this.formData.Add("success_action_status", status); } @@ -174,11 +175,11 @@ public void SetSuccessStatusAction(string status) public void SetUserMetadata(string key, string value) { if (string.IsNullOrEmpty(key)) - throw new ArgumentException("Key is Empty"); + throw new ArgumentException("Key is Empty", nameof(key)); if (string.IsNullOrEmpty(value)) - throw new ArgumentException("Value is Empty"); + throw new ArgumentException("Value is Empty", nameof(value)); string headerName = "x-amz-meta-" + key; - this.policies.Add(new Tuple("eq", "$" + headerName, value)); + this.policies.Add(Tuple.Create("eq", "$" + headerName, value)); this.formData.Add(headerName, value); } @@ -190,9 +191,9 @@ public void SetAlgorithm(string algorithm) { if (string.IsNullOrEmpty(algorithm)) { - throw new ArgumentException("Algorithm argument cannot be null or empty"); + throw new ArgumentException("Algorithm argument cannot be null or empty", nameof(algorithm)); } - this.policies.Add(new Tuple("eq", "$x-amz-algorithm", algorithm)); + this.policies.Add(Tuple.Create("eq", "$x-amz-algorithm", algorithm)); this.formData.Add("x-amz-algorithm", algorithm); } @@ -204,9 +205,9 @@ public void SetCredential(string credential) { if (string.IsNullOrEmpty(credential)) { - throw new ArgumentException("credential argument cannot be null or empty"); + throw new ArgumentException("credential argument cannot be null or empty", nameof(credential)); } - this.policies.Add(new Tuple("eq", "$x-amz-credential", credential)); + this.policies.Add(Tuple.Create("eq", "$x-amz-credential", credential)); this.formData.Add("x-amz-credential", credential); } @@ -217,7 +218,7 @@ public void SetCredential(string credential) public void SetDate(DateTime date) { string dateStr = date.ToString("yyyyMMddTHHmmssZ"); - this.policies.Add(new Tuple("eq", "$x-amz-date", dateStr)); + this.policies.Add(Tuple.Create("eq", "$x-amz-date", dateStr)); this.formData.Add("x-amz-date", dateStr); } @@ -255,9 +256,9 @@ private byte[] marshalJSON() // expiration and policies will never be empty because of checks at PresignedPostPolicy() sb.Append("{"); sb.Append("\"expiration\":\"").Append(this.expiration.ToString("yyyy-MM-ddTHH:mm:ss.000Z")).Append("\"").Append(","); - sb.Append("\"conditions\":[").Append(String.Join(",", policyList)).Append("]"); + sb.Append("\"conditions\":[").Append(string.Join(",", policyList)).Append("]"); sb.Append("}"); - return System.Text.Encoding.UTF8.GetBytes(sb.ToString() as string); + return System.Text.Encoding.UTF8.GetBytes(sb.ToString()); } /// @@ -276,8 +277,7 @@ public string Base64() /// true if bucket is set public bool IsBucketSet() { - string value = ""; - if (this.formData.TryGetValue("bucket", out value)) + if (this.formData.TryGetValue("bucket", out string value)) { if (!string.IsNullOrEmpty(value)) { @@ -293,8 +293,7 @@ public bool IsBucketSet() /// true if key is set public bool IsKeySet() { - string value = ""; - if (this.formData.TryGetValue("key", out value)) + if (this.formData.TryGetValue("key", out string value)) { if (!string.IsNullOrEmpty(value)) { @@ -321,9 +320,6 @@ public bool IsExpirationSet() /// Get the populated dictionary of policy data. /// /// Dictionary of policy data - public Dictionary GetFormData() - { - return this.formData; - } + public Dictionary GetFormData() => this.formData; } } diff --git a/Minio/DataModel/ServerSideEncryption.cs b/Minio/DataModel/ServerSideEncryption.cs index 3fe2c8084..d3888bc4d 100644 --- a/Minio/DataModel/ServerSideEncryption.cs +++ b/Minio/DataModel/ServerSideEncryption.cs @@ -48,10 +48,7 @@ public class SSEC : ServerSideEncryption // secret AES-256 Key protected byte[] key; - public new EncryptionType GetType() - { - return EncryptionType.SSE_C; - } + public new EncryptionType GetType() => EncryptionType.SSE_C; public virtual void Marshal(Dictionary headers) { @@ -66,7 +63,7 @@ public SSEC(byte[] key) { if (key == null || key.Length != 32) { - throw new ArgumentException("Secret key needs to be a 256 bit AES Key"); + throw new ArgumentException("Secret key needs to be a 256 bit AES Key", nameof(key)); } this.key = key; } @@ -90,10 +87,7 @@ public SSECopy(byte[] key) : base(key) { } - public SSEC CloneToSSEC() - { - return new SSEC(this.key); - } + public SSEC CloneToSSEC() => new SSEC(this.key); } /// @@ -101,10 +95,7 @@ public SSEC CloneToSSEC() /// public class SSES3 : ServerSideEncryption { - public new EncryptionType GetType() - { - return EncryptionType.SSE_S3; - } + public new EncryptionType GetType() => EncryptionType.SSE_S3; public virtual void Marshal(Dictionary headers) { @@ -126,16 +117,13 @@ public SSEKMS(string key, Dictionary context = null) { if (key == "") { - throw new ArgumentException("KMS Key cannot be empty"); + throw new ArgumentException("KMS Key cannot be empty", nameof(key)); } this.key = key; this.context = context; } - public new EncryptionType GetType() - { - return EncryptionType.SSE_KMS; - } + public new EncryptionType GetType() => EncryptionType.SSE_KMS; public void Marshal(Dictionary headers) { @@ -171,7 +159,7 @@ private string marshalContext() } } sb.Append("}"); - byte[] contextBytes = Encoding.UTF8.GetBytes(sb.ToString() as string); + byte[] contextBytes = Encoding.UTF8.GetBytes(sb.ToString()); return Convert.ToBase64String(contextBytes); } } diff --git a/Minio/Exceptions/AccessDeniedException.cs b/Minio/Exceptions/AccessDeniedException.cs index 6ff3a7a65..55874a255 100644 --- a/Minio/Exceptions/AccessDeniedException.cs +++ b/Minio/Exceptions/AccessDeniedException.cs @@ -28,10 +28,5 @@ public AccessDeniedException() public AccessDeniedException(string message) : base(message) { } - - public override string ToString() - { - return base.ToString(); - } } } diff --git a/Minio/Exceptions/BucketNotFoundException.cs b/Minio/Exceptions/BucketNotFoundException.cs index ebc01b422..2a00f4ad2 100644 --- a/Minio/Exceptions/BucketNotFoundException.cs +++ b/Minio/Exceptions/BucketNotFoundException.cs @@ -21,11 +21,10 @@ namespace Minio.Exceptions [Serializable] public class BucketNotFoundException : MinioException { - private string bucketName; + private readonly string bucketName; public BucketNotFoundException() { - } public BucketNotFoundException(string bucketName, string message) : base(message) @@ -33,9 +32,6 @@ public BucketNotFoundException(string bucketName, string message) : base(message this.bucketName = bucketName; } - public override string ToString() - { - return this.bucketName + ": " + base.ToString(); - } + public override string ToString() => this.bucketName + ": " + base.ToString(); } } diff --git a/Minio/Exceptions/DeleteError.cs b/Minio/Exceptions/DeleteError.cs index f6d80707a..55aa2ca6f 100644 --- a/Minio/Exceptions/DeleteError.cs +++ b/Minio/Exceptions/DeleteError.cs @@ -21,7 +21,7 @@ namespace Minio.Exceptions { [Serializable] [XmlRoot(ElementName = "Error")] - public class DeleteError: ErrorResponse + public class DeleteError : ErrorResponse { } } diff --git a/Minio/Exceptions/ErrorResponse.cs b/Minio/Exceptions/ErrorResponse.cs index 2f48ffac1..deeb4e30d 100644 --- a/Minio/Exceptions/ErrorResponse.cs +++ b/Minio/Exceptions/ErrorResponse.cs @@ -20,7 +20,7 @@ namespace Minio.Exceptions { [Serializable] - [XmlRoot(ElementName="Error",Namespace = "")] + [XmlRoot(ElementName="Error", Namespace = "")] public class ErrorResponse { public string Code { get; set; } diff --git a/Minio/Exceptions/ErrorResponseException.cs b/Minio/Exceptions/ErrorResponseException.cs index fae8336f5..a6165eadc 100644 --- a/Minio/Exceptions/ErrorResponseException.cs +++ b/Minio/Exceptions/ErrorResponseException.cs @@ -20,7 +20,7 @@ namespace Minio.Exceptions { public class ErrorResponseException : MinioException { - private string ErrorCode; + private readonly string ErrorCode; public ErrorResponseException(IRestResponse response) : base($"MinIO API responded with status code={response.StatusCode}, response={response.ErrorMessage}, content={response.Content}") @@ -30,18 +30,14 @@ public ErrorResponseException(IRestResponse response) public ErrorResponseException() { - } - public ErrorResponseException(string message,string errorcode) : base($"MinIO API responded with message={message}") + public ErrorResponseException(string message, string errorcode) : base($"MinIO API responded with message={message}") { this.message = message; this.ErrorCode = errorcode; } - public override string ToString() - { - return this.message + ": " + base.ToString(); - } + public override string ToString() => this.message + ": " + base.ToString(); } } diff --git a/Minio/Exceptions/ForbiddenException.cs b/Minio/Exceptions/ForbiddenException.cs index 6196b0927..b019ae116 100644 --- a/Minio/Exceptions/ForbiddenException.cs +++ b/Minio/Exceptions/ForbiddenException.cs @@ -21,10 +21,5 @@ public class ForbiddenException : MinioException public ForbiddenException(string message) : base(message) { } - - public override string ToString() - { - return base.ToString(); - } } } diff --git a/Minio/Exceptions/InternalServerException.cs b/Minio/Exceptions/InternalServerException.cs index f3cf96db6..71168866d 100644 --- a/Minio/Exceptions/InternalServerException.cs +++ b/Minio/Exceptions/InternalServerException.cs @@ -21,10 +21,5 @@ public class InternalServerException : MinioException public InternalServerException(string message) : base(message) { } - - public override string ToString() - { - return base.ToString(); - } } } diff --git a/Minio/Exceptions/InvalidBucketNameException.cs b/Minio/Exceptions/InvalidBucketNameException.cs index 0964a20ff..5a28f1a1a 100644 --- a/Minio/Exceptions/InvalidBucketNameException.cs +++ b/Minio/Exceptions/InvalidBucketNameException.cs @@ -18,16 +18,13 @@ namespace Minio.Exceptions { public class InvalidBucketNameException : MinioException { - private string bucketName; + private readonly string bucketName; public InvalidBucketNameException(string bucketName, string message) : base(message) { this.bucketName = bucketName; } - public override string ToString() - { - return this.bucketName + ": " + base.ToString(); - } + public override string ToString() => this.bucketName + ": " + base.ToString(); } } diff --git a/Minio/Exceptions/InvalidContentLengthException.cs b/Minio/Exceptions/InvalidContentLengthException.cs index b5fd1b798..407749a1c 100644 --- a/Minio/Exceptions/InvalidContentLengthException.cs +++ b/Minio/Exceptions/InvalidContentLengthException.cs @@ -18,8 +18,8 @@ namespace Minio.Exceptions { public class InvalidContentLengthException : MinioException { - private string bucketName; - private string objectName; + private readonly string bucketName; + private readonly string objectName; public InvalidContentLengthException(string bucketName, string objectName, string message) : base(message) { diff --git a/Minio/Exceptions/InvalidEndpointException.cs b/Minio/Exceptions/InvalidEndpointException.cs index 725f557f2..f16ab698a 100644 --- a/Minio/Exceptions/InvalidEndpointException.cs +++ b/Minio/Exceptions/InvalidEndpointException.cs @@ -18,7 +18,7 @@ namespace Minio.Exceptions { public class InvalidEndpointException : MinioException { - private string endpoint; + private readonly string endpoint; public InvalidEndpointException(string endpoint, string message) : base(message) { diff --git a/Minio/Exceptions/InvalidExpiryRangeException.cs b/Minio/Exceptions/InvalidExpiryRangeException.cs index a4e4fb5f5..4aa886d61 100644 --- a/Minio/Exceptions/InvalidExpiryRangeException.cs +++ b/Minio/Exceptions/InvalidExpiryRangeException.cs @@ -21,10 +21,5 @@ public class InvalidExpiryRangeException : MinioException public InvalidExpiryRangeException(string message) : base(message) { } - - public override string ToString() - { - return base.ToString(); - } } } diff --git a/Minio/Exceptions/InvalidObjectNameException.cs b/Minio/Exceptions/InvalidObjectNameException.cs index cfef09f70..b7c0b362c 100644 --- a/Minio/Exceptions/InvalidObjectNameException.cs +++ b/Minio/Exceptions/InvalidObjectNameException.cs @@ -18,16 +18,13 @@ namespace Minio.Exceptions { public class InvalidObjectNameException : MinioException { - private string objectName; + private readonly string objectName; public InvalidObjectNameException(string objectName, string message) : base(message) { this.objectName = objectName; } - public override string ToString() - { - return this.objectName + ": " + base.ToString(); - } + public override string ToString() => this.objectName + ": " + base.ToString(); } } diff --git a/Minio/Exceptions/InvalidObjectPrefixException.cs b/Minio/Exceptions/InvalidObjectPrefixException.cs index 0310156cd..46851abd7 100644 --- a/Minio/Exceptions/InvalidObjectPrefixException.cs +++ b/Minio/Exceptions/InvalidObjectPrefixException.cs @@ -18,16 +18,13 @@ namespace Minio.Exceptions { public class InvalidObjectPrefixException : MinioException { - private string objectPrefix; + private readonly string objectPrefix; public InvalidObjectPrefixException(string objectPrefix, string message) : base(message) { this.objectPrefix = objectPrefix; } - public override string ToString() - { - return this.objectPrefix + ": " + base.ToString(); - } + public override string ToString() => this.objectPrefix + ": " + base.ToString(); } } diff --git a/Minio/Exceptions/MinioException.cs b/Minio/Exceptions/MinioException.cs index bd8fbfb57..670dcb1af 100644 --- a/Minio/Exceptions/MinioException.cs +++ b/Minio/Exceptions/MinioException.cs @@ -43,9 +43,6 @@ public MinioException(string message) : base($"MinIO API responded with message= public ErrorResponse Response { get; set; } public string XmlError { get; set; } - public override string ToString() - { - return this.message + ": " + base.ToString(); - } + public override string ToString() => this.message + ": " + base.ToString(); } } diff --git a/Minio/Exceptions/ObjectNotFoundException.cs b/Minio/Exceptions/ObjectNotFoundException.cs index e07e9a938..1f4a2a9e0 100644 --- a/Minio/Exceptions/ObjectNotFoundException.cs +++ b/Minio/Exceptions/ObjectNotFoundException.cs @@ -18,16 +18,13 @@ namespace Minio.Exceptions { public class ObjectNotFoundException : MinioException { - private string objectName; + private readonly string objectName; public ObjectNotFoundException(string objectName, string message) : base(message) { this.objectName = objectName; } - public override string ToString() - { - return this.objectName + ": " + base.ToString(); - } + public override string ToString() => this.objectName + ": " + base.ToString(); } } diff --git a/Minio/Exceptions/RedirectionException.cs b/Minio/Exceptions/RedirectionException.cs index 394e094e4..c65649caf 100644 --- a/Minio/Exceptions/RedirectionException.cs +++ b/Minio/Exceptions/RedirectionException.cs @@ -21,10 +21,5 @@ public class RedirectionException : MinioException public RedirectionException(string message) : base(message) { } - - public override string ToString() - { - return base.ToString(); - } } } diff --git a/Minio/Exceptions/UnexpectedShortReadException.cs b/Minio/Exceptions/UnexpectedShortReadException.cs index f2d461a0e..67925f381 100644 --- a/Minio/Exceptions/UnexpectedShortReadException.cs +++ b/Minio/Exceptions/UnexpectedShortReadException.cs @@ -21,10 +21,5 @@ public class UnexpectedShortReadException : MinioException public UnexpectedShortReadException(string message) : base(message) { } - - public override string ToString() - { - return base.ToString(); - } } } diff --git a/Minio/Helper/Constants.cs b/Minio/Helper/Constants.cs index 8901a849a..49a55f277 100644 --- a/Minio/Helper/Constants.cs +++ b/Minio/Helper/Constants.cs @@ -30,7 +30,7 @@ internal static class Constants // operation. public static long MaxSinglePutObjectSize = 1024L * 1024L * 1024L * 5; - // maxSingleCopyObjectSize - 5GiB + // maxSingleCopyObjectSize - 5GiB public static long MaxSingleCopyObjectSize = 1024L * 1024L * 1024L * 5; // maxMultipartPutObjectSize - maximum size 5TiB of object for // Multipart operation. @@ -41,7 +41,7 @@ internal static class Constants public static long OptimalReadBufferSize = 1024L * 1024L * 5; public static int DefaultExpiryTime = 7 * 24 * 3600; - + // SSEGenericHeader is the AWS SSE header used for SSE-S3 and SSE-KMS. public static string SSEGenericHeader = "X-Amz-Server-Side-Encryption"; diff --git a/Minio/Helper/RequestUtil.cs b/Minio/Helper/RequestUtil.cs index dbe2baf22..e8b5a67cd 100644 --- a/Minio/Helper/RequestUtil.cs +++ b/Minio/Helper/RequestUtil.cs @@ -1,5 +1,4 @@ - -/* +/* * MinIO .NET Library for Amazon S3 Compatible Cloud Storage, (C) 2017 MinIO, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -30,12 +29,12 @@ internal static Uri GetEndpointURL(string endPoint, bool secure) { string[] parts = endPoint.Split(':'); string host = parts[0]; - string port = parts[1]; + string port = parts[1]; if (!s3utils.IsValidIP(host) && !IsValidEndpoint(host)) { throw new InvalidEndpointException("Endpoint: " + endPoint + " does not follow ip address or domain name standards."); } - } + } else { if (!s3utils.IsValidIP(endPoint) && !IsValidEndpoint(endPoint)) @@ -45,10 +44,10 @@ internal static Uri GetEndpointURL(string endPoint, bool secure) } Uri uri = TryCreateUri(endPoint, secure); - RequestUtil.ValidateEndpoint(uri,endPoint); + ValidateEndpoint(uri, endPoint); return uri; } - + internal static Uri MakeTargetURL(string endPoint, bool secure, string bucketName = null, string region = null, bool usePathStyle = true) { // For Amazon S3 endpoint, try to fetch location based endpoint. @@ -63,11 +62,11 @@ internal static Uri MakeTargetURL(string endPoint, bool secure, string bucketNam host = prefix + utils.UrlEncode(host) + "/"; } } - Uri uri = TryCreateUri(host,secure); + Uri uri = TryCreateUri(host, secure); return uri; } - internal static Uri TryCreateUri(string endpoint,bool secure) + internal static Uri TryCreateUri(string endpoint, bool secure) { var scheme = secure ? utils.UrlEncode("https") : utils.UrlEncode("http"); @@ -88,7 +87,7 @@ internal static Uri TryCreateUri(string endpoint,bool secure) /// /// Validates URI to check if it is well formed. Otherwise cry foul. /// - internal static void ValidateEndpoint(Uri uri,string Endpoint) + internal static void ValidateEndpoint(Uri uri, string endpoint) { if (string.IsNullOrEmpty(uri.OriginalString)) { @@ -98,25 +97,25 @@ internal static void ValidateEndpoint(Uri uri,string Endpoint) if (!IsValidEndpoint(uri.Host)) { - throw new InvalidEndpointException(Endpoint, "Invalid endpoint."); + throw new InvalidEndpointException(endpoint, "Invalid endpoint."); } if (!uri.AbsolutePath.Equals("/", StringComparison.CurrentCultureIgnoreCase)) { - throw new InvalidEndpointException(Endpoint, "No path allowed in endpoint."); + throw new InvalidEndpointException(endpoint, "No path allowed in endpoint."); } if (!string.IsNullOrEmpty(uri.Query)) { - throw new InvalidEndpointException(Endpoint, "No query parameter allowed in endpoint."); + throw new InvalidEndpointException(endpoint, "No query parameter allowed in endpoint."); } if ((!uri.Scheme.ToLowerInvariant().Equals("https")) && (!uri.Scheme.ToLowerInvariant().Equals("http"))) { - throw new InvalidEndpointException(Endpoint, "Invalid scheme detected in endpoint."); + throw new InvalidEndpointException(endpoint, "Invalid scheme detected in endpoint."); } } - + /// - /// Validate Url endpoint + /// Validate Url endpoint /// /// /// true/false @@ -129,7 +128,7 @@ internal static bool IsValidEndpoint(string endpoint) { return false; } - + foreach (var label in endpoint.Split('.')) { if (label.Length < 1 || label.Length > 63) @@ -145,6 +144,6 @@ internal static bool IsValidEndpoint(string endpoint) } } return true; - } + } } } diff --git a/Minio/Helper/s3utils.cs b/Minio/Helper/s3utils.cs index 1b294253f..469cce16c 100644 --- a/Minio/Helper/s3utils.cs +++ b/Minio/Helper/s3utils.cs @@ -33,7 +33,7 @@ internal static bool IsAmazonEndPoint(string endpoint) } Regex rgx = new Regex("^s3[.-]?(.*?)\\.amazonaws\\.com$", RegexOptions.IgnoreCase); MatchCollection matches = rgx.Matches(endpoint); - return (matches.Count > 0); + return matches.Count > 0; } // IsAmazonChinaEndpoint - Match if it is exactly Amazon S3 China endpoint. @@ -78,7 +78,6 @@ internal static string GetPath(string p1, string p2) { throw new ArgumentException(ex.Message); } - } /// @@ -88,7 +87,7 @@ internal static string GetPath(string p1, string p2) /// internal static bool IsValidIP(string ip) { - if (String.IsNullOrEmpty(ip)) + if (string.IsNullOrEmpty(ip)) return false; string[] splitValues = ip.Split('.'); @@ -97,9 +96,7 @@ internal static bool IsValidIP(string ip) return false; } - byte tempForParsing; - - return splitValues.All(r => byte.TryParse(r, out tempForParsing)); + return splitValues.All(r => byte.TryParse(r, out var _)); } // TrimAll trims leading and trailing spaces and replace sequential spaces with one space, following Trimall() diff --git a/Minio/Helper/utils.cs b/Minio/Helper/utils.cs index 5610d0210..980b3cf78 100644 --- a/Minio/Helper/utils.cs +++ b/Minio/Helper/utils.cs @@ -30,10 +30,10 @@ internal class utils { // We support '.' with bucket names but we fallback to using path // style requests instead for such buckets. - static Regex validBucketName = new Regex("^[a-z0-9][a-z0-9\\.\\-]{1,61}[a-z0-9]$"); + private static Regex validBucketName = new Regex("^[a-z0-9][a-z0-9\\.\\-]{1,61}[a-z0-9]$"); // Invalid bucket name with double dot. - static Regex invalidDotBucketName = new Regex("`/./."); + private static Regex invalidDotBucketName = new Regex("`/./."); /// /// isValidBucketName - verify bucket name in accordance with @@ -73,13 +73,13 @@ internal static void validateBucketName(string bucketName) } // isValidObjectName - verify object name in accordance with // - http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingMetadata.html - internal static void validateObjectName(String objectName) + internal static void validateObjectName(string objectName) { if (objectName.Trim() == "") { throw new InvalidObjectNameException(objectName, "Object name cannot be empty."); } - + // c# strings are in utf16 format. they are already in unicode format when they arrive here. if (objectName.Length > 512) { @@ -114,7 +114,7 @@ internal static string UrlEncode(string input) .Replace("\\=", "%3D") .Replace("\\@", "%40") .Replace("\\[", "%5B") - .Replace("\\]", "%5D"); + .Replace("\\]", "%5D"); } // Return encoded path where extra "/" are trimmed off. internal static string EncodePath(string path) @@ -128,7 +128,7 @@ internal static string EncodePath(string path) { encodedPathBuf.Append("/"); } - encodedPathBuf.Append(utils.UrlEncode(pathSegment)); + encodedPathBuf.Append(UrlEncode(pathSegment)); } } @@ -145,14 +145,14 @@ internal static string EncodePath(string path) internal static bool isAnonymousClient(string accessKey, string secretKey) { - return (secretKey == "" || accessKey == ""); + return secretKey == "" || accessKey == ""; } internal static void ValidateFile(string filePath, string contentType = null) { if (filePath == null || filePath == "") { - throw new ArgumentException("empty file name is not allowed"); + throw new ArgumentException("empty file name is not allowed", nameof(filePath)); } string fileName = Path.GetFileName(filePath); @@ -162,7 +162,7 @@ internal static void ValidateFile(string filePath, string contentType = null) FileAttributes attr = File.GetAttributes(filePath); if (attr.HasFlag(FileAttributes.Directory)) { - throw new ArgumentException("'" + fileName + "': not a regular file"); + throw new ArgumentException("'" + fileName + "': not a regular file", nameof(filePath)); } } @@ -170,7 +170,6 @@ internal static void ValidateFile(string filePath, string contentType = null) { contentType = GetContentType(filePath); } - } internal static string GetContentType(string fileName) @@ -180,20 +179,21 @@ internal static string GetContentType(string fileName) { extension = Path.GetExtension(fileName); } - catch { } + catch + { + } - if (String.IsNullOrEmpty(extension)) + if (string.IsNullOrEmpty(extension)) return "application/octet-stream"; - return _contentTypeMap.Value.TryGetValue(extension, out string contentType) - ? contentType + return _contentTypeMap.Value.TryGetValue(extension, out string contentType) + ? contentType : "application/octet-stream"; } public static void MoveWithReplace(string sourceFileName, string destFileName) { - - //first, delete target file if exists, as File.Move() does not support overwrite + // first, delete target file if exists, as File.Move() does not support overwrite if (File.Exists(destFileName)) { File.Delete(destFileName); @@ -212,7 +212,7 @@ internal static bool isSupersetOf(IList l1, IList l2) { return false; } - return (!l2.Except(l1).Any()); + return !l2.Except(l1).Any(); } public static bool CaseInsensitiveContains(string text, string value, @@ -226,7 +226,7 @@ public static bool CaseInsensitiveContains(string text, string value, /// /// /// - public static Object CalculateMultiPartSize(long size) + public static object CalculateMultiPartSize(long size) { if (size == -1) { @@ -238,7 +238,7 @@ public static Object CalculateMultiPartSize(long size) } double partSize = (double)Math.Ceiling((decimal)size / Constants.MaxParts); partSize = (double)Math.Ceiling((decimal)partSize / Constants.MinimumPartSize) * Constants.MinimumPartSize; - double partCount = (double)Math.Ceiling(size / partSize); + double partCount = Math.Ceiling(size / partSize); double lastPartSize = size - (partCount - 1) * partSize; dynamic obj = new ExpandoObject(); obj.partSize = partSize; @@ -252,10 +252,9 @@ public static Object CalculateMultiPartSize(long size) /// /// time to expiry in seconds /// bool - public static bool IsValidExpiry(int expiryInt) { - return (expiryInt > 0) && (expiryInt <= Constants.DefaultExpiryTime); + return (expiryInt > 0) && (expiryInt <= Constants.DefaultExpiryTime); } internal static string getMD5SumStr(byte[] key) diff --git a/Minio/MinioClient.cs b/Minio/MinioClient.cs index bd3e86e91..1120c5726 100644 --- a/Minio/MinioClient.cs +++ b/Minio/MinioClient.cs @@ -83,10 +83,10 @@ private static string SystemUserAgent string release = "minio-dotnet/1.0.9"; #if NET46 string arch = Environment.Is64BitOperatingSystem ? "x86_64" : "x86"; - return String.Format("MinIO ({0};{1}) {2}", Environment.OSVersion, arch, release); + return string.Format("MinIO ({0};{1}) {2}", Environment.OSVersion, arch, release); #else string arch = RuntimeInformation.OSArchitecture.ToString(); - return String.Format("MinIO ({0};{1}) {2}", RuntimeInformation.OSDescription, arch, release); + return string.Format("MinIO ({0};{1}) {2}", RuntimeInformation.OSDescription, arch, release); #endif } } @@ -147,10 +147,10 @@ private async Task GetRegion(string bucketName) internal async Task CreateRequest(Method method, string bucketName = null, string objectName = null, Dictionary headerMap = null, string contentType = "application/octet-stream", - Object body = null, string resourcePath = null) + object body = null, string resourcePath = null) { string region = ""; - if ( bucketName != null) + if (bucketName != null) { utils.validateBucketName(bucketName); // Fetch correct region for bucket @@ -163,10 +163,10 @@ internal async Task CreateRequest(Method method, string bucketName // Start with user specified endpoint string host = this.BaseUrl; - - this.restClient.Authenticator = new V4Authenticator(this.Secure, this.AccessKey, this.SecretKey, region:this.Region, sessionToken:this.SessionToken); - // This section reconstructs the url with scheme followed by location specific endpoint( s3.region.amazonaws.com) + this.restClient.Authenticator = new V4Authenticator(this.Secure, this.AccessKey, this.SecretKey, region: this.Region, sessionToken: this.SessionToken); + + // This section reconstructs the url with scheme followed by location specific endpoint (s3.region.amazonaws.com) // or Virtual Host styled endpoint (bucketname.s3.region.amazonaws.com) for Amazon requests. string resource = ""; bool usePathStyle = false; @@ -186,7 +186,7 @@ internal async Task CreateRequest(Method method, string bucketName // use path style for location query usePathStyle = true; } - else if (bucketName != null && bucketName.Contains(".") && this.Secure) + else if (bucketName != null && bucketName.Contains(".") && this.Secure) { // use path style where '.' in bucketName causes SSL certificate validation error usePathStyle = true; @@ -204,7 +204,7 @@ internal async Task CreateRequest(Method method, string bucketName } // Set Target URL - Uri requestUrl = RequestUtil.MakeTargetURL(this.BaseUrl, this.Secure,bucketName, region, usePathStyle); + Uri requestUrl = RequestUtil.MakeTargetURL(this.BaseUrl, this.Secure, bucketName, region, usePathStyle); SetTargetURL(requestUrl); if (objectName != null) @@ -223,7 +223,6 @@ internal async Task CreateRequest(Method method, string bucketName if (body != null) { request.AddParameter(contentType, body, RestSharp.ParameterType.RequestBody); - } if (headerMap != null) @@ -254,15 +253,17 @@ internal void InitClient() // This is the actual url pointed to for all HTTP requests this.Endpoint = string.Format("{0}://{1}", scheme, host); - this.uri = RequestUtil.GetEndpointURL(this.BaseUrl,this.Secure); - RequestUtil.ValidateEndpoint(this.uri,this.Endpoint); + this.uri = RequestUtil.GetEndpointURL(this.BaseUrl, this.Secure); + RequestUtil.ValidateEndpoint(this.uri, this.Endpoint); // Initialize a new REST client. This uri will be modified if region specific endpoint/virtual style request // is decided upon while constructing a request for Amazon. - restClient = new RestSharp.RestClient(this.uri); - restClient.UserAgent = this.FullUserAgent; + restClient = new RestSharp.RestClient(this.uri) + { + UserAgent = this.FullUserAgent + }; - authenticator = new V4Authenticator(this.Secure,this.AccessKey, this.SecretKey, this.Region, this.SessionToken); + authenticator = new V4Authenticator(this.Secure, this.AccessKey, this.SecretKey, this.Region, this.SessionToken); restClient.Authenticator = authenticator; } @@ -271,16 +272,15 @@ internal void InitClient() /// /// /// - /// public void SetAppInfo(string appName, string appVersion) { if (string.IsNullOrEmpty(appName)) { - throw new ArgumentException("Appname cannot be null or empty"); + throw new ArgumentException("Appname cannot be null or empty", nameof(appName)); } if (string.IsNullOrEmpty(appVersion)) { - throw new ArgumentException("Appversion cannot be null or empty"); + throw new ArgumentException("Appversion cannot be null or empty", nameof(appVersion)); } this.CustomUserAgent = appName + "/" + appVersion; } @@ -289,12 +289,12 @@ public void SetAppInfo(string appName, string appVersion) /// Creates and returns an Cloud Storage client /// /// Location of the server, supports HTTP and HTTPS - /// Access Key for authenticated requests (Optional,can be omitted for anonymous requests) - /// Secret Key for authenticated requests (Optional,can be omitted for anonymous requests) + /// Access Key for authenticated requests (Optional, can be omitted for anonymous requests) + /// Secret Key for authenticated requests (Optional, can be omitted for anonymous requests) /// Optional custom region /// Optional session token /// Client initialized with user credentials - public MinioClient(string endpoint, string accessKey = "", string secretKey = "", string region="",string sessionToken="") + public MinioClient(string endpoint, string accessKey = "", string secretKey = "", string region = "", string sessionToken = "") { this.Secure = false; @@ -335,7 +335,6 @@ public MinioClient WithProxy(IWebProxy proxy) /// /// Sets endpoint URL on the client object that request will be made against /// - /// internal void SetTargetURL(Uri uri) { this.restClient.BaseUrl = uri; @@ -348,7 +347,7 @@ internal void SetTargetURL(Uri uri) /// request /// /// IRESTResponse - internal async Task ExecuteTaskAsync(IEnumerable errorHandlers, IRestRequest request, CancellationToken cancellationToken=default(CancellationToken)) + internal async Task ExecuteTaskAsync(IEnumerable errorHandlers, IRestRequest request, CancellationToken cancellationToken = default(CancellationToken)) { DateTime startTime = DateTime.Now; // Logs full url when HTTPtracing is enabled. @@ -358,7 +357,7 @@ internal async Task ExecuteTaskAsync(IEnumerable 1) { @@ -441,7 +440,6 @@ internal static void ParseError(IRestResponse response) BucketRegionCache.Instance.Remove(resource); e = new BucketNotFoundException(resource, "Not found."); } - } else { @@ -469,23 +467,24 @@ internal static void ParseError(IRestResponse response) var contentBytes = System.Text.Encoding.UTF8.GetBytes(response.Content); var stream = new MemoryStream(contentBytes); - ErrorResponse errResponse = (ErrorResponse)(new XmlSerializer(typeof(ErrorResponse)).Deserialize(stream)); + ErrorResponse errResponse = (ErrorResponse)new XmlSerializer(typeof(ErrorResponse)).Deserialize(stream); // Handle XML response for Bucket Policy not found case if (response.StatusCode.Equals(HttpStatusCode.NotFound) && response.Request.Resource.EndsWith("?policy") - && response.Request.Method.Equals(Method.GET) && (errResponse.Code.Equals("NoSuchBucketPolicy"))) + && response.Request.Method.Equals(Method.GET) && errResponse.Code == "NoSuchBucketPolicy") { - - ErrorResponseException ErrorException = new ErrorResponseException(errResponse.Message,errResponse.Code); - ErrorException.Response = errResponse; - ErrorException.XmlError = response.Content; - throw ErrorException; + throw new ErrorResponseException(errResponse.Message, errResponse.Code) + { + Response = errResponse, + XmlError = response.Content + }; } - MinioException MinioException = new MinioException(errResponse.Message); - MinioException.Response = errResponse; - MinioException.XmlError = response.Content; - throw MinioException; + throw new MinioException(errResponse.Message) + { + Response = errResponse, + XmlError = response.Content + }; } /// diff --git a/Minio/Regions.cs b/Minio/Regions.cs index c227a15fe..daeca6291 100644 --- a/Minio/Regions.cs +++ b/Minio/Regions.cs @@ -35,7 +35,7 @@ public static string GetRegionFromEndpoint(string endpoint) Regex endpointrgx = new Regex("^([a-z0-9][a-z0-9\\.\\-]{1,61}[a-z0-9])*?.?s3[.\\-]?(.*?)\\.amazonaws\\.com$", RegexOptions.IgnoreCase); Regex regionrgx = new Regex("^(s3[.\\-])?(.*?)$"); MatchCollection matches = endpointrgx.Matches(endpoint); - if ((matches.Count > 0) && (matches[0].Groups.Count> 1)) + if ((matches.Count > 0) && (matches[0].Groups.Count > 1)) { string regionStr = matches[0].Groups[2].Value; matches = regionrgx.Matches(regionStr); @@ -44,7 +44,7 @@ public static string GetRegionFromEndpoint(string endpoint) region = matches[0].Groups[0].Value; } } - return (region == null) ? "" : region; + return region ?? ""; } } } diff --git a/Minio/V4Authenticator.cs b/Minio/V4Authenticator.cs index 7303ca0d0..c9f3890f2 100644 --- a/Minio/V4Authenticator.cs +++ b/Minio/V4Authenticator.cs @@ -31,8 +31,8 @@ internal class V4Authenticator : IAuthenticator { private readonly string accessKey; private readonly string secretKey; - private string region; - private string sessionToken; + private readonly string region; + private readonly string sessionToken; internal bool isAnonymous { get; private set; } internal bool isSecure { get; private set; } @@ -64,7 +64,8 @@ internal class V4Authenticator : IAuthenticator // // Is skipped for obvious reasons // - private static HashSet ignoredHeaders = new HashSet() { + private static HashSet ignoredHeaders = new HashSet + { "authorization", "content-length", "content-type", @@ -84,7 +85,7 @@ public V4Authenticator(bool secure, string accessKey, string secretKey, string r this.isSecure = secure; this.accessKey = accessKey; this.secretKey = secretKey; - this.isAnonymous = String.IsNullOrEmpty(accessKey) && String.IsNullOrEmpty(secretKey); + this.isAnonymous = string.IsNullOrEmpty(accessKey) && string.IsNullOrEmpty(secretKey); this.region = region; this.sessionToken = sessionToken; } @@ -132,9 +133,9 @@ public void Authenticate(IRestClient client, IRestRequest request) } /// - /// Get credential string of form {ACCESSID}/date/region/s3/aws4_request. + /// Get credential string of form {ACCESSID}/date/region/s3/aws4_request. /// - /// Signature initated date + /// Signature initiated date /// Region for the credential string /// Credential string for the authorization header public string GetCredentialString(DateTime signingDate, string region) @@ -149,7 +150,7 @@ public string GetCredentialString(DateTime signingDate, string region) /// Hexadecimally encoded computed signature /// Date for signature to be signed /// Requested region - /// Fully formed authorization header + /// Fully formed authorization header private string GetAuthorizationHeader(string signedHeaders, string signature, DateTime signingDate, string region) { return "AWS4-HMAC-SHA256 Credential=" + this.accessKey + "/" + GetScope(region, signingDate) + @@ -235,7 +236,6 @@ private string GetScope(string region, DateTime signingDate) /// Bytes of sha256 checksum private byte[] ComputeSha256(byte[] body) { - SHA256 sha256 = System.Security.Cryptography.SHA256.Create(); return sha256.ComputeHash(body); } @@ -275,9 +275,9 @@ public string PresignPostSignature(string region, DateTime signingDate, string p /// Instantiated request /// Expiration in seconds /// Region of storage - /// Region of storage + /// Value for session token /// Optional request date and time in UTC - /// Presigned url + /// Presigned url internal string PresignURL(IRestClient client, IRestRequest request, int expires, string region = "", string sessionToken = "", DateTime? reqDate = null) { DateTime signingDate = DateTime.UtcNow; @@ -343,7 +343,7 @@ internal string GetPresignCanonicalRequest(IRestClient client, IRestRequest requ path = "/" + path; } canonicalStringList.AddLast(path); - String query = headersToSign.Aggregate(requestQuery, (pv, cv) => $"{pv}&{utils.UrlEncode(cv.Key)}={utils.UrlEncode(s3utils.TrimAll(cv.Value))}"); + string query = headersToSign.Aggregate(requestQuery, (pv, cv) => $"{pv}&{utils.UrlEncode(cv.Key)}={utils.UrlEncode(s3utils.TrimAll(cv.Value))}"); canonicalStringList.AddLast(query); if (client.BaseUrl.Port > 0 && (client.BaseUrl.Port != 80 && client.BaseUrl.Port != 443)) { @@ -470,7 +470,6 @@ private void SetHostHeader(IRestRequest request, string hostUrl) /// /// Instantiated request object /// session token - private void SetSessionTokenHeader(IRestRequest request, string sessionToken) { if (!string.IsNullOrEmpty(sessionToken)) @@ -533,7 +532,7 @@ private void SetContentMd5(IRestRequest request) { if (request.Method == Method.PUT || request.Method.Equals(Method.POST)) { - var bodyParameter = request.Parameters.Where(p => p.Type.Equals(ParameterType.RequestBody)).FirstOrDefault(); + var bodyParameter = request.Parameters.FirstOrDefault(p => p.Type.Equals(ParameterType.RequestBody)); if (bodyParameter == null) { return;