From 72239bb553f92c495d6e0a6ae5c73e2e42194684 Mon Sep 17 00:00:00 2001 From: Martijn van Dijk Date: Mon, 24 Apr 2023 11:51:37 +0200 Subject: [PATCH 01/13] Fix --- Minio.Functional.Tests/FunctionalTest.cs | 4 +- Minio/DataModel/ObjectStat.cs | 1 + Minio/DataModel/Replication/Metrics.cs | 4 +- .../Replication/SseKmsEncryptedObjects.cs | 4 +- Minio/Helper/Utils.cs | 8 +++- Minio/MinioClientExtensions.cs | 38 +++++++++++++++++++ 6 files changed, 53 insertions(+), 6 deletions(-) diff --git a/Minio.Functional.Tests/FunctionalTest.cs b/Minio.Functional.Tests/FunctionalTest.cs index be5816524..59d04127d 100644 --- a/Minio.Functional.Tests/FunctionalTest.cs +++ b/Minio.Functional.Tests/FunctionalTest.cs @@ -2752,8 +2752,8 @@ await PutObject_Tester(minio, bucketName, objectName, null, contentType, } catch (Exception ex) { - if (ex.Message == "Listening for bucket notification is specific" + - " only to `minio` server endpoints") + if (string.Equals(ex.Message, "Listening for bucket notification is specific" + + " only to `minio` server endpoints", StringComparison.OrdinalIgnoreCase)) { // This is expected when bucket notification // is requested against AWS. diff --git a/Minio/DataModel/ObjectStat.cs b/Minio/DataModel/ObjectStat.cs index 3d51a7f72..d2c802f4d 100644 --- a/Minio/DataModel/ObjectStat.cs +++ b/Minio/DataModel/ObjectStat.cs @@ -49,6 +49,7 @@ public static ObjectStat FromResponseHeaders(string objectName, IDictionary(Stream stream) where T : class { var ns = GetNamespace(); if (!string.IsNullOrWhiteSpace(ns) && ns is "http://s3.amazonaws.com/doc/2006-03-01/") - return (T)new XmlSerializer(typeof(T)).Deserialize(new AmazonAwsS3XmlReader(stream)); + { + using var amazonAwsS3XmlReader = new AmazonAwsS3XmlReader(stream); + return (T)new XmlSerializer(typeof(T)).Deserialize(amazonAwsS3XmlReader); + } return (T)new XmlSerializer(typeof(T)).Deserialize(stream); } @@ -1002,7 +1005,8 @@ public static T DeserializeXml(string xml) where T : class try { var serializer = new XmlSerializer(typeof(T)); - return (T)serializer.Deserialize(new StringReader(xml)); + using var stringReader = new StringReader(xml); + return (T)serializer.Deserialize(stringReader); } catch (Exception) { diff --git a/Minio/MinioClientExtensions.cs b/Minio/MinioClientExtensions.cs index 1291dade6..37e0ebdd6 100644 --- a/Minio/MinioClientExtensions.cs +++ b/Minio/MinioClientExtensions.cs @@ -8,6 +8,11 @@ public static class MinioClientExtensions { public static MinioClient WithEndpoint(this MinioClient minioClient, string endpoint) { + if (minioClient is null) + { + throw new ArgumentNullException(nameof(minioClient)); + } + minioClient.BaseUrl = endpoint; minioClient.SetBaseURL(GetBaseUrl(endpoint)); return minioClient; @@ -15,6 +20,11 @@ public static MinioClient WithEndpoint(this MinioClient minioClient, string endp public static MinioClient WithEndpoint(this MinioClient minioClient, string endpoint, int port) { + if (minioClient is null) + { + throw new ArgumentNullException(nameof(minioClient)); + } + if (port < 1 || port > 65535) throw new ArgumentException(string.Format("Port {0} is not a number between 1 and 65535", port), nameof(port)); @@ -23,12 +33,22 @@ public static MinioClient WithEndpoint(this MinioClient minioClient, string endp public static MinioClient WithEndpoint(this MinioClient minioClient, Uri url) { + if (minioClient is null) + { + throw new ArgumentNullException(nameof(minioClient)); + } + if (url == null) throw new ArgumentException("URL is null. Can't create endpoint."); return minioClient.WithEndpoint(url.AbsoluteUri); } public static MinioClient WithRegion(this MinioClient minioClient, string region) { + if (minioClient is null) + { + throw new ArgumentNullException(nameof(minioClient)); + } + if (string.IsNullOrEmpty(region)) throw new ArgumentException(string.Format("{0} the region value can't be null or empty.", region), nameof(region)); @@ -39,6 +59,10 @@ public static MinioClient WithRegion(this MinioClient minioClient, string region public static MinioClient WithRegion(this MinioClient minioClient) { + if (minioClient is null) + { + throw new ArgumentNullException(nameof(minioClient)); + } // Set region to its default value if empty or null minioClient.Region = "us-east-1"; return minioClient; @@ -46,6 +70,11 @@ public static MinioClient WithRegion(this MinioClient minioClient) public static MinioClient WithCredentials(this MinioClient minioClient, string accessKey, string secretKey) { + if (minioClient is null) + { + throw new ArgumentNullException(nameof(minioClient)); + } + minioClient.AccessKey = accessKey; minioClient.SecretKey = secretKey; return minioClient; @@ -53,12 +82,21 @@ public static MinioClient WithCredentials(this MinioClient minioClient, string a public static MinioClient WithSessionToken(this MinioClient minioClient, string st) { + if (minioClient is null) + { + throw new ArgumentNullException(nameof(minioClient)); + } + minioClient.SessionToken = st; return minioClient; } public static MinioClient Build(this MinioClient minioClient) { + if (minioClient is null) + { + throw new ArgumentNullException(nameof(minioClient)); + } // Instantiate a region cache minioClient.regionCache = BucketRegionCache.Instance; if (string.IsNullOrEmpty(minioClient.BaseUrl)) throw new MinioException("Endpoint not initialized."); From d344017b38bd4a07185062ca2568fc9dc1e86990 Mon Sep 17 00:00:00 2001 From: Martijn van Dijk Date: Mon, 24 Apr 2023 14:20:53 +0200 Subject: [PATCH 02/13] Null checks --- Minio.Functional.Tests/FunctionalTest.cs | 2 +- Minio/DataModel/AccessCredentials.cs | 11 +++-- Minio/DataModel/ILM/Transition.cs | 5 ++- Minio/DataModel/ObjectOperationsArgs.cs | 6 +-- .../Replication/AccessControlTranslation.cs | 5 ++- .../Replication/DeleteMarkerReplication.cs | 5 ++- .../Replication/DeleteReplication.cs | 5 ++- .../Replication/EncryptionConfiguration.cs | 6 ++- .../Replication/ExistingObjectReplication.cs | 3 +- Minio/DataModel/Replication/Metrics.cs | 2 - .../DataModel/Replication/ReplicationTime.cs | 7 +-- .../Replication/SseKmsEncryptedObjects.cs | 2 - .../ServerSideEncryptionConfigurationApply.cs | 3 +- Minio/MinioClientExtensions.cs | 43 +++++-------------- 14 files changed, 45 insertions(+), 60 deletions(-) diff --git a/Minio.Functional.Tests/FunctionalTest.cs b/Minio.Functional.Tests/FunctionalTest.cs index 59d04127d..e875d63ec 100644 --- a/Minio.Functional.Tests/FunctionalTest.cs +++ b/Minio.Functional.Tests/FunctionalTest.cs @@ -2753,7 +2753,7 @@ await PutObject_Tester(minio, bucketName, objectName, null, contentType, catch (Exception ex) { if (string.Equals(ex.Message, "Listening for bucket notification is specific" + - " only to `minio` server endpoints", StringComparison.OrdinalIgnoreCase)) + " only to `minio` server endpoints", StringComparison.OrdinalIgnoreCase)) { // This is expected when bucket notification // is requested against AWS. diff --git a/Minio/DataModel/AccessCredentials.cs b/Minio/DataModel/AccessCredentials.cs index f514cf64a..f4035b68a 100644 --- a/Minio/DataModel/AccessCredentials.cs +++ b/Minio/DataModel/AccessCredentials.cs @@ -26,9 +26,14 @@ public class AccessCredentials public AccessCredentials(string accessKey, string secretKey, string sessionToken, DateTime expiration) { - if (string.IsNullOrWhiteSpace(accessKey) || string.IsNullOrWhiteSpace(secretKey)) - throw new ArgumentNullException(nameof(accessKey) + " and " + nameof(secretKey) + - " cannot be null or empty."); + if (string.IsNullOrEmpty(accessKey)) + throw new ArgumentException($"'{nameof(accessKey)}' cannot be null or empty.", nameof(accessKey)); + + if (string.IsNullOrEmpty(secretKey)) + throw new ArgumentException($"'{nameof(secretKey)}' cannot be null or empty.", nameof(secretKey)); + + if (string.IsNullOrEmpty(sessionToken)) + throw new ArgumentException($"'{nameof(sessionToken)}' cannot be null or empty.", nameof(sessionToken)); AccessKey = accessKey; SecretKey = secretKey; diff --git a/Minio/DataModel/ILM/Transition.cs b/Minio/DataModel/ILM/Transition.cs index d6fbff1db..ae1083d65 100644 --- a/Minio/DataModel/ILM/Transition.cs +++ b/Minio/DataModel/ILM/Transition.cs @@ -44,7 +44,8 @@ public Transition(DateTime date, string storageClass) : base(date) internal static void CheckStorageClass(string storageClass) { - if (string.IsNullOrEmpty(storageClass) || string.IsNullOrWhiteSpace(storageClass)) - throw new ArgumentNullException(nameof(storageClass) + " cannot be empty."); + if (string.IsNullOrWhiteSpace(storageClass)) + throw new ArgumentException($"'{nameof(storageClass)}' cannot be null or whitespace.", + nameof(storageClass)); } } \ No newline at end of file diff --git a/Minio/DataModel/ObjectOperationsArgs.cs b/Minio/DataModel/ObjectOperationsArgs.cs index 6be8464b4..88c6d2e6d 100644 --- a/Minio/DataModel/ObjectOperationsArgs.cs +++ b/Minio/DataModel/ObjectOperationsArgs.cs @@ -1893,11 +1893,11 @@ internal override HttpRequestMessageBuilder BuildRequest(HttpRequestMessageBuild return requestMessageBuilder; } - public override PutObjectArgs WithHeaders(IDictionary metaData) + public override PutObjectArgs WithHeaders(IDictionary headers) { Headers ??= new Dictionary(StringComparer.OrdinalIgnoreCase); - if (metaData != null) - foreach (var p in metaData) + if (headers != null) + foreach (var p in headers) { var key = p.Key; if (!OperationsUtil.IsSupportedHeader(p.Key) && diff --git a/Minio/DataModel/Replication/AccessControlTranslation.cs b/Minio/DataModel/Replication/AccessControlTranslation.cs index 3b13f37e0..4be0752ec 100644 --- a/Minio/DataModel/Replication/AccessControlTranslation.cs +++ b/Minio/DataModel/Replication/AccessControlTranslation.cs @@ -32,8 +32,9 @@ public class AccessControlTranslation { public AccessControlTranslation(string owner) { - if (string.IsNullOrEmpty(owner) || string.IsNullOrWhiteSpace(owner)) - throw new ArgumentNullException(nameof(Owner) + " cannot be empty."); + if (string.IsNullOrWhiteSpace(owner)) + throw new ArgumentException($"'{nameof(owner)}' cannot be null or whitespace.", nameof(owner)); + Owner = owner; } diff --git a/Minio/DataModel/Replication/DeleteMarkerReplication.cs b/Minio/DataModel/Replication/DeleteMarkerReplication.cs index 9ff4c9f02..96bf2aaa9 100644 --- a/Minio/DataModel/Replication/DeleteMarkerReplication.cs +++ b/Minio/DataModel/Replication/DeleteMarkerReplication.cs @@ -35,8 +35,9 @@ public class DeleteMarkerReplication public DeleteMarkerReplication(string status) { - if (string.IsNullOrWhiteSpace(status)) - throw new ArgumentNullException(nameof(status) + " cannot be null or empty."); + if (string.IsNullOrEmpty(status)) + throw new ArgumentException($"'{nameof(status)}' cannot be null or empty.", nameof(status)); + Status = status; } diff --git a/Minio/DataModel/Replication/DeleteReplication.cs b/Minio/DataModel/Replication/DeleteReplication.cs index f7b3e6af8..2b73aa386 100644 --- a/Minio/DataModel/Replication/DeleteReplication.cs +++ b/Minio/DataModel/Replication/DeleteReplication.cs @@ -35,8 +35,9 @@ public class DeleteReplication public DeleteReplication(string status) { - if (string.IsNullOrWhiteSpace(status)) - throw new ArgumentNullException(nameof(status) + " cannot be null or empty."); + if (string.IsNullOrEmpty(status)) + throw new ArgumentException($"'{nameof(status)}' cannot be null or empty.", nameof(status)); + Status = status; } diff --git a/Minio/DataModel/Replication/EncryptionConfiguration.cs b/Minio/DataModel/Replication/EncryptionConfiguration.cs index 7d7f6eb98..d958b73bc 100644 --- a/Minio/DataModel/Replication/EncryptionConfiguration.cs +++ b/Minio/DataModel/Replication/EncryptionConfiguration.cs @@ -31,8 +31,10 @@ public class EncryptionConfiguration { public EncryptionConfiguration(string replicaKmsKeyID) { - if (string.IsNullOrEmpty(replicaKmsKeyID) || string.IsNullOrWhiteSpace(replicaKmsKeyID)) - throw new ArgumentNullException(nameof(ReplicaKmsKeyID) + " cannot be null or empty."); + if (string.IsNullOrWhiteSpace(replicaKmsKeyID)) + throw new ArgumentException($"'{nameof(replicaKmsKeyID)}' cannot be null or whitespace.", + nameof(replicaKmsKeyID)); + ReplicaKmsKeyID = replicaKmsKeyID; } diff --git a/Minio/DataModel/Replication/ExistingObjectReplication.cs b/Minio/DataModel/Replication/ExistingObjectReplication.cs index aa88f56db..98736cf0f 100644 --- a/Minio/DataModel/Replication/ExistingObjectReplication.cs +++ b/Minio/DataModel/Replication/ExistingObjectReplication.cs @@ -41,7 +41,8 @@ public ExistingObjectReplication() public ExistingObjectReplication(string status) { if (string.IsNullOrWhiteSpace(status)) - throw new ArgumentNullException(nameof(status) + " cannot be null or empty."); + throw new ArgumentException($"'{nameof(status)}' cannot be null or whitespace.", nameof(status)); + Status = status; } diff --git a/Minio/DataModel/Replication/Metrics.cs b/Minio/DataModel/Replication/Metrics.cs index a07bab669..df1ccb4f6 100644 --- a/Minio/DataModel/Replication/Metrics.cs +++ b/Minio/DataModel/Replication/Metrics.cs @@ -33,9 +33,7 @@ public class Metrics public Metrics(string status, ReplicationTimeValue eventThreshold) { if (string.IsNullOrWhiteSpace(status)) - { throw new ArgumentException($"'{nameof(status)}' member cannot be empty.", nameof(status)); - } Status = status; EventThreshold = eventThreshold; } diff --git a/Minio/DataModel/Replication/ReplicationTime.cs b/Minio/DataModel/Replication/ReplicationTime.cs index e6a0e092f..f2971912d 100644 --- a/Minio/DataModel/Replication/ReplicationTime.cs +++ b/Minio/DataModel/Replication/ReplicationTime.cs @@ -36,9 +36,10 @@ public ReplicationTime() public ReplicationTime(ReplicationTimeValue time, string status) { - if (string.IsNullOrWhiteSpace(status)) - throw new ArgumentNullException(nameof(status) + " cannot be null or empty."); - Time = time ?? throw new ArgumentNullException(nameof(Time), " object cannot be null."); + if (string.IsNullOrEmpty(status)) + throw new ArgumentException($"'{nameof(status)}' cannot be null or empty.", nameof(status)); + + Time = time ?? throw new ArgumentNullException(nameof(time)); Status = status; } diff --git a/Minio/DataModel/Replication/SseKmsEncryptedObjects.cs b/Minio/DataModel/Replication/SseKmsEncryptedObjects.cs index ec9bbce4b..e331bfcbb 100644 --- a/Minio/DataModel/Replication/SseKmsEncryptedObjects.cs +++ b/Minio/DataModel/Replication/SseKmsEncryptedObjects.cs @@ -40,9 +40,7 @@ public SseKmsEncryptedObjects() public SseKmsEncryptedObjects(string status) { if (string.IsNullOrWhiteSpace(status)) - { throw new ArgumentException($"'{nameof(status)}' cannot be null or whitespace.", nameof(status)); - } Status = status; } diff --git a/Minio/DataModel/ServerSideEncryptionConfigurationApply.cs b/Minio/DataModel/ServerSideEncryptionConfigurationApply.cs index cac6b4d22..f195f548b 100644 --- a/Minio/DataModel/ServerSideEncryptionConfigurationApply.cs +++ b/Minio/DataModel/ServerSideEncryptionConfigurationApply.cs @@ -31,8 +31,7 @@ public ServerSideEncryptionConfigurationApply(string algorithm = ServerSideEncry string keyId = null) { if (string.IsNullOrEmpty(algorithm)) - throw new ArgumentNullException( - "The SSE Algorithm " + nameof(SSEAlgorithm) + " cannot be null or empty"); + throw new ArgumentException($"'{nameof(algorithm)}' cannot be null or empty.", nameof(algorithm)); SSEAlgorithm = algorithm; KMSMasterKeyId = keyId; diff --git a/Minio/MinioClientExtensions.cs b/Minio/MinioClientExtensions.cs index 37e0ebdd6..ea11e3e50 100644 --- a/Minio/MinioClientExtensions.cs +++ b/Minio/MinioClientExtensions.cs @@ -8,10 +8,7 @@ public static class MinioClientExtensions { public static MinioClient WithEndpoint(this MinioClient minioClient, string endpoint) { - if (minioClient is null) - { - throw new ArgumentNullException(nameof(minioClient)); - } + if (minioClient is null) throw new ArgumentNullException(nameof(minioClient)); minioClient.BaseUrl = endpoint; minioClient.SetBaseURL(GetBaseUrl(endpoint)); @@ -20,10 +17,7 @@ public static MinioClient WithEndpoint(this MinioClient minioClient, string endp public static MinioClient WithEndpoint(this MinioClient minioClient, string endpoint, int port) { - if (minioClient is null) - { - throw new ArgumentNullException(nameof(minioClient)); - } + if (minioClient is null) throw new ArgumentNullException(nameof(minioClient)); if (port < 1 || port > 65535) throw new ArgumentException(string.Format("Port {0} is not a number between 1 and 65535", port), @@ -33,21 +27,16 @@ public static MinioClient WithEndpoint(this MinioClient minioClient, string endp public static MinioClient WithEndpoint(this MinioClient minioClient, Uri url) { - if (minioClient is null) - { - throw new ArgumentNullException(nameof(minioClient)); - } + if (minioClient is null) throw new ArgumentNullException(nameof(minioClient)); + + if (url is null) throw new ArgumentNullException(nameof(url)); - if (url == null) throw new ArgumentException("URL is null. Can't create endpoint."); return minioClient.WithEndpoint(url.AbsoluteUri); } public static MinioClient WithRegion(this MinioClient minioClient, string region) { - if (minioClient is null) - { - throw new ArgumentNullException(nameof(minioClient)); - } + if (minioClient is null) throw new ArgumentNullException(nameof(minioClient)); if (string.IsNullOrEmpty(region)) throw new ArgumentException(string.Format("{0} the region value can't be null or empty.", region), @@ -59,10 +48,7 @@ public static MinioClient WithRegion(this MinioClient minioClient, string region public static MinioClient WithRegion(this MinioClient minioClient) { - if (minioClient is null) - { - throw new ArgumentNullException(nameof(minioClient)); - } + if (minioClient is null) throw new ArgumentNullException(nameof(minioClient)); // Set region to its default value if empty or null minioClient.Region = "us-east-1"; return minioClient; @@ -70,10 +56,7 @@ public static MinioClient WithRegion(this MinioClient minioClient) public static MinioClient WithCredentials(this MinioClient minioClient, string accessKey, string secretKey) { - if (minioClient is null) - { - throw new ArgumentNullException(nameof(minioClient)); - } + if (minioClient is null) throw new ArgumentNullException(nameof(minioClient)); minioClient.AccessKey = accessKey; minioClient.SecretKey = secretKey; @@ -82,10 +65,7 @@ public static MinioClient WithCredentials(this MinioClient minioClient, string a public static MinioClient WithSessionToken(this MinioClient minioClient, string st) { - if (minioClient is null) - { - throw new ArgumentNullException(nameof(minioClient)); - } + if (minioClient is null) throw new ArgumentNullException(nameof(minioClient)); minioClient.SessionToken = st; return minioClient; @@ -93,10 +73,7 @@ public static MinioClient WithSessionToken(this MinioClient minioClient, string public static MinioClient Build(this MinioClient minioClient) { - if (minioClient is null) - { - throw new ArgumentNullException(nameof(minioClient)); - } + if (minioClient is null) throw new ArgumentNullException(nameof(minioClient)); // Instantiate a region cache minioClient.regionCache = BucketRegionCache.Instance; if (string.IsNullOrEmpty(minioClient.BaseUrl)) throw new MinioException("Endpoint not initialized."); From 81dcaccea0e5fb386d307465d7f1fc125135578a Mon Sep 17 00:00:00 2001 From: Martijn van Dijk Date: Mon, 24 Apr 2023 14:44:46 +0200 Subject: [PATCH 03/13] Cleanup --- Minio/DataModel/ILM/LifecycleRule.cs | 2 +- Minio/DataModel/Notification/BucketNotification.cs | 7 +++---- Minio/DataModel/ObjectOperationsArgs.cs | 7 ++----- Minio/Helper/RequestUtil.cs | 3 +-- Minio/MinioClient.cs | 2 +- 5 files changed, 8 insertions(+), 13 deletions(-) diff --git a/Minio/DataModel/ILM/LifecycleRule.cs b/Minio/DataModel/ILM/LifecycleRule.cs index 8dee7cc9c..1ce94122b 100644 --- a/Minio/DataModel/ILM/LifecycleRule.cs +++ b/Minio/DataModel/ILM/LifecycleRule.cs @@ -79,7 +79,7 @@ public RuleFilter Filter set { // The filter must not be missing, even if it is empty. - if (value == null) + if (value is null) _ruleFilter = new RuleFilter(); else _ruleFilter = value; diff --git a/Minio/DataModel/Notification/BucketNotification.cs b/Minio/DataModel/Notification/BucketNotification.cs index b2dd9968c..bb845707d 100644 --- a/Minio/DataModel/Notification/BucketNotification.cs +++ b/Minio/DataModel/Notification/BucketNotification.cs @@ -32,7 +32,6 @@ public class BucketNotification [XmlElement("TopicConfiguration")] public List TopicConfigs; [XmlElement("QueueConfiguration")] public List QueueConfigs; - public BucketNotification() { LambdaConfigs = new List(); @@ -48,7 +47,7 @@ public BucketNotification() /// public void AddTopic(TopicConfig topicConfig) { - var isTopicFound = TopicConfigs.Any(t => t.Topic.Equals(topicConfig)); + var isTopicFound = TopicConfigs.Exists(t => t.Topic.Equals(topicConfig)); if (!isTopicFound) TopicConfigs.Add(topicConfig); } @@ -58,7 +57,7 @@ public void AddTopic(TopicConfig topicConfig) /// public void AddQueue(QueueConfig queueConfig) { - var isQueueFound = QueueConfigs.Any(t => t.Equals(queueConfig)); + var isQueueFound = QueueConfigs.Exists(t => t.Equals(queueConfig)); if (!isQueueFound) QueueConfigs.Add(queueConfig); } @@ -68,7 +67,7 @@ public void AddQueue(QueueConfig queueConfig) /// public void AddLambda(LambdaConfig lambdaConfig) { - var isLambdaFound = LambdaConfigs.Any(t => t.Lambda.Equals(lambdaConfig)); + var isLambdaFound = LambdaConfigs.Exists(t => t.Lambda.Equals(lambdaConfig)); if (!isLambdaFound) LambdaConfigs.Add(lambdaConfig); } diff --git a/Minio/DataModel/ObjectOperationsArgs.cs b/Minio/DataModel/ObjectOperationsArgs.cs index 88c6d2e6d..042345ebb 100644 --- a/Minio/DataModel/ObjectOperationsArgs.cs +++ b/Minio/DataModel/ObjectOperationsArgs.cs @@ -305,12 +305,9 @@ public class PresignedPostPolicyArgs : ObjectArgs Utils.ValidateBucketName(BucketName); Utils.ValidateObjectName(ObjectName); } - catch (Exception ex) + catch (Exception ex) when (ex is InvalidBucketNameException || ex is InvalidObjectNameException) { - if (ex is InvalidBucketNameException || ex is InvalidObjectNameException) - checkPolicy = true; - else - throw; + checkPolicy = true; } if (checkPolicy) diff --git a/Minio/Helper/RequestUtil.cs b/Minio/Helper/RequestUtil.cs index 3377b6e69..b62a293ef 100644 --- a/Minio/Helper/RequestUtil.cs +++ b/Minio/Helper/RequestUtil.cs @@ -63,8 +63,7 @@ internal static Uri MakeTargetURL(string endPoint, bool secure, string bucketNam var scheme = secure ? "https" : "http"; var endpointURL = string.Format("{0}://{1}", scheme, host); - var uri = new Uri(endpointURL, UriKind.Absolute); - return uri; + return new Uri(endpointURL, UriKind.Absolute); } internal static Uri TryCreateUri(string endpoint, bool secure) diff --git a/Minio/MinioClient.cs b/Minio/MinioClient.cs index 2026422ed..54d917bff 100644 --- a/Minio/MinioClient.cs +++ b/Minio/MinioClient.cs @@ -448,7 +448,7 @@ public MinioClient WithCredentialsProvider(ClientProvider provider) { Provider = provider; AccessCredentials credentials; - if (Provider is IAMAWSProvider iAMAWSProvider) + if (Provider is IAMAWSProvider) // Empty object, we need the Minio client completely credentials = new AccessCredentials(); else From 590bb6a7dd6607ce84e0bffa98226dc4c1e57c3a Mon Sep 17 00:00:00 2001 From: Martijn van Dijk Date: Tue, 25 Apr 2023 13:14:42 +0200 Subject: [PATCH 04/13] Is or is not null checks --- Docs/API.md | 2 +- Minio.Examples/Cases/GetBucketEncryption.cs | 2 +- Minio.Examples/Cases/GetBucketLifecycle.cs | 2 +- Minio.Examples/Cases/GetBucketReplication.cs | 2 +- Minio.Examples/Cases/GetBucketTags.cs | 2 +- .../Cases/GetObjectLockConfiguration.cs | 4 +- Minio.Examples/Cases/GetObjectTags.cs | 2 +- Minio.Examples/Cases/GetVersioning.cs | 2 +- Minio.Examples/Cases/RemoveObjects.cs | 2 +- Minio.Examples/Cases/RetryPolicyObject.cs | 2 +- Minio.Examples/Cases/SelectObjectContent.cs | 2 +- Minio.Examples/Cases/SetBucketReplication.cs | 4 +- Minio.Examples/Program.cs | 4 +- Minio.Functional.Tests/FunctionalTest.cs | 28 ++++----- Minio.Functional.Tests/Program.cs | 8 +-- Minio.Tests/AuthenticatorTest.cs | 4 +- Minio.Tests/DictionaryExtensionMethods.cs | 2 +- Minio/AWSS3Endpoints.cs | 2 +- Minio/ApiEndpoints/BucketOperations.cs | 4 +- Minio/ApiEndpoints/ObjectOperations.cs | 16 ++--- Minio/BucketRegionCache.cs | 6 +- Minio/Credentials/AssumeRoleBaseProvider.cs | 4 +- Minio/Credentials/AssumeRoleProvider.cs | 8 +-- .../CertificateIdentityProvider.cs | 6 +- Minio/Credentials/ChainedProvider.cs | 2 +- Minio/Credentials/IAMAWSProvider.cs | 14 ++--- .../WebIdentityClientGrantsProvider.cs | 6 +- Minio/DataModel/BucketArgs.cs | 2 +- Minio/DataModel/BucketOperationsArgs.cs | 8 +-- Minio/DataModel/BucketOperationsReponse.cs | 8 +-- Minio/DataModel/CopyConditions.cs | 4 +- Minio/DataModel/ILM/AndOperator.cs | 2 +- Minio/DataModel/ILM/LifecycleConfiguration.cs | 2 +- Minio/DataModel/Item.cs | 2 +- .../Notification/BucketNotification.cs | 2 +- Minio/DataModel/Notification/FilterRule.cs | 4 +- Minio/DataModel/Notification/LambdaConfig.cs | 2 +- .../Notification/NotificationConfiguration.cs | 6 +- Minio/DataModel/Notification/QueueConfig.cs | 2 +- Minio/DataModel/Notification/TopicConfig.cs | 2 +- Minio/DataModel/ObjectOperationsArgs.cs | 60 +++++++++---------- Minio/DataModel/ObjectOperationsResponse.cs | 4 +- Minio/DataModel/ObjectStat.cs | 8 +-- Minio/DataModel/Part.cs | 2 +- .../Replication/ReplicationConfiguration.cs | 2 +- .../DataModel/Select/SelectResponseStream.cs | 2 +- Minio/DataModel/ServerSideEncryption.cs | 4 +- Minio/DataModel/Tags/TagSet.cs | 2 +- Minio/DataModel/Tags/Tagging.cs | 8 +-- Minio/Exceptions/MinioException.cs | 6 +- Minio/Helper/OperationsHelper.cs | 2 +- Minio/Helper/RequestUtil.cs | 2 +- Minio/Helper/Utils.cs | 6 +- Minio/Helper/s3utils.cs | 2 +- Minio/HttpRequestMessageBuilder.cs | 6 +- Minio/MinioClient.cs | 32 +++++----- Minio/MinioClientExtensions.cs | 6 +- Minio/ResponseResult.cs | 10 ++-- Minio/V4Authenticator.cs | 6 +- 59 files changed, 179 insertions(+), 179 deletions(-) diff --git a/Docs/API.md b/Docs/API.md index ad0c59c32..293a1689e 100644 --- a/Docs/API.md +++ b/Docs/API.md @@ -2247,7 +2247,7 @@ try Console.WriteLine("Bytes scanned:" + resp.Stats.BytesScanned); Console.WriteLine("Bytes returned:" + resp.Stats.BytesReturned); Console.WriteLine("Bytes processed:" + resp.Stats.BytesProcessed); - if (resp.Progress != null) + if (resp.Progress is not null) { Console.WriteLine("Progress :" + resp.Progress.BytesProcessed); } diff --git a/Minio.Examples/Cases/GetBucketEncryption.cs b/Minio.Examples/Cases/GetBucketEncryption.cs index 14652e924..fd16a0ce3 100644 --- a/Minio.Examples/Cases/GetBucketEncryption.cs +++ b/Minio.Examples/Cases/GetBucketEncryption.cs @@ -30,7 +30,7 @@ public static async Task Run(IMinioClient minio, .WithBucket(bucketName) ).ConfigureAwait(false); Console.WriteLine($"Got encryption configuration for bucket {bucketName}."); - if (config != null && config.Rule?.Apply != null) + if (config is not null && config.Rule?.Apply is not null) Console.WriteLine("Server Side Encryption Algorithm: " + config.Rule.Apply.SSEAlgorithm); Console.WriteLine(); } diff --git a/Minio.Examples/Cases/GetBucketLifecycle.cs b/Minio.Examples/Cases/GetBucketLifecycle.cs index 0f46c4092..5eb339ada 100644 --- a/Minio.Examples/Cases/GetBucketLifecycle.cs +++ b/Minio.Examples/Cases/GetBucketLifecycle.cs @@ -29,7 +29,7 @@ public static async Task Run(IMinioClient minio, new GetBucketLifecycleArgs() .WithBucket(bucketName) ).ConfigureAwait(false); - if (lfc != null && lfc.Rules?.Count > 0) + if (lfc is not null && lfc.Rules?.Count > 0) { Console.WriteLine($"Got Bucket Lifecycle set for bucket {bucketName}."); Console.WriteLine(lfc.MarshalXML()); diff --git a/Minio.Examples/Cases/GetBucketReplication.cs b/Minio.Examples/Cases/GetBucketReplication.cs index 639ae8460..4417751a1 100644 --- a/Minio.Examples/Cases/GetBucketReplication.cs +++ b/Minio.Examples/Cases/GetBucketReplication.cs @@ -32,7 +32,7 @@ public static async Task Run(IMinioClient minio, new GetBucketReplicationArgs() .WithBucket(bucketName) ).ConfigureAwait(false); - if (repl != null && repl.Rules?.Count > 0) + if (repl is not null && repl.Rules?.Count > 0) { Console.WriteLine($"Got Bucket Replication Configuration set for bucket {bucketName}."); foreach (var rule in repl.Rules) diff --git a/Minio.Examples/Cases/GetBucketTags.cs b/Minio.Examples/Cases/GetBucketTags.cs index f52f022c1..3ae91b928 100644 --- a/Minio.Examples/Cases/GetBucketTags.cs +++ b/Minio.Examples/Cases/GetBucketTags.cs @@ -29,7 +29,7 @@ public static async Task Run(IMinioClient minio, new GetBucketTagsArgs() .WithBucket(bucketName) ).ConfigureAwait(false); - if (tags != null && tags.Tags?.Count > 0) + if (tags is not null && tags.Tags?.Count > 0) { Console.WriteLine($"Got Bucket Tags set for bucket {bucketName}."); foreach (var tag in tags.Tags) Console.WriteLine(tag.Key + " : " + tag.Value); diff --git a/Minio.Examples/Cases/GetObjectLockConfiguration.cs b/Minio.Examples/Cases/GetObjectLockConfiguration.cs index 64a5b5c8f..6c415938b 100644 --- a/Minio.Examples/Cases/GetObjectLockConfiguration.cs +++ b/Minio.Examples/Cases/GetObjectLockConfiguration.cs @@ -31,10 +31,10 @@ public static async Task Run(IMinioClient minio, new GetObjectLockConfigurationArgs() .WithBucket(bucketName) ).ConfigureAwait(false); - if (config != null) + if (config is not null) { Console.WriteLine($"Object lock configuration on bucket {bucketName} is : " + config.ObjectLockEnabled); - if (config.Rule?.DefaultRetention != null) + if (config.Rule?.DefaultRetention is not null) { var mode = config.Rule.DefaultRetention.Mode == RetentionMode.GOVERNANCE ? "GOVERNANCE" diff --git a/Minio.Examples/Cases/GetObjectTags.cs b/Minio.Examples/Cases/GetObjectTags.cs index 473d024d8..cab77481e 100644 --- a/Minio.Examples/Cases/GetObjectTags.cs +++ b/Minio.Examples/Cases/GetObjectTags.cs @@ -33,7 +33,7 @@ public static async Task Run(IMinioClient minio, .WithObject(objectName) .WithVersionId(versionId) ).ConfigureAwait(false); - if (tags != null && tags.Tags?.Count > 0) + if (tags is not null && tags.Tags?.Count > 0) { Console.WriteLine($"Got tags set for object {bucketName}/{objectName}."); foreach (var tag in tags.Tags) Console.WriteLine(tag.Key + " : " + tag.Value); diff --git a/Minio.Examples/Cases/GetVersioning.cs b/Minio.Examples/Cases/GetVersioning.cs index 00111abc1..773092109 100644 --- a/Minio.Examples/Cases/GetVersioning.cs +++ b/Minio.Examples/Cases/GetVersioning.cs @@ -29,7 +29,7 @@ public static async Task Run(IMinioClient minio, { Console.WriteLine("Running example for API: GetVersioning, "); var config = await minio.GetVersioningAsync(args).ConfigureAwait(false); - if (config == null) + if (config is null) { Console.WriteLine("Versioning Configuration not available for bucket " + bucketName); Console.WriteLine(); diff --git a/Minio.Examples/Cases/RemoveObjects.cs b/Minio.Examples/Cases/RemoveObjects.cs index 07e564d42..1ee19f805 100644 --- a/Minio.Examples/Cases/RemoveObjects.cs +++ b/Minio.Examples/Cases/RemoveObjects.cs @@ -27,7 +27,7 @@ public static async Task Run(IMinioClient minio, try { Console.WriteLine("Running example for API: RemoveObjectsAsync"); - if (objectsList != null) + if (objectsList is not null) { var objArgs = new RemoveObjectsArgs() .WithBucket(bucketName) diff --git a/Minio.Examples/Cases/RetryPolicyObject.cs b/Minio.Examples/Cases/RetryPolicyObject.cs index 1a4ead01e..511d4c343 100644 --- a/Minio.Examples/Cases/RetryPolicyObject.cs +++ b/Minio.Examples/Cases/RetryPolicyObject.cs @@ -64,7 +64,7 @@ public static AsyncPolicy GetDefaultRetryPolicy( public static RetryPolicyHandlingDelegate AsRetryDelegate(this AsyncPolicy policy) { - return policy == null + return policy is null ? null : async executeCallback => await policy.ExecuteAsync(executeCallback).ConfigureAwait(false); } diff --git a/Minio.Examples/Cases/SelectObjectContent.cs b/Minio.Examples/Cases/SelectObjectContent.cs index 09813e87e..128a77c8e 100644 --- a/Minio.Examples/Cases/SelectObjectContent.cs +++ b/Minio.Examples/Cases/SelectObjectContent.cs @@ -81,7 +81,7 @@ public static async Task Run(IMinioClient minio, Console.WriteLine("Bytes scanned:" + resp.Stats.BytesScanned); Console.WriteLine("Bytes returned:" + resp.Stats.BytesReturned); Console.WriteLine("Bytes processed:" + resp.Stats.BytesProcessed); - if (resp.Progress != null) Console.WriteLine("Progress :" + resp.Progress.BytesProcessed); + if (resp.Progress is not null) Console.WriteLine("Progress :" + resp.Progress.BytesProcessed); } catch (Exception e) { diff --git a/Minio.Examples/Cases/SetBucketReplication.cs b/Minio.Examples/Cases/SetBucketReplication.cs index d63b1677d..d29ae9346 100644 --- a/Minio.Examples/Cases/SetBucketReplication.cs +++ b/Minio.Examples/Cases/SetBucketReplication.cs @@ -65,12 +65,12 @@ public static async Task Run(IMinioClient minio, string serverEndPoint; string accessKey; string secretKey; - if (Environment.GetEnvironmentVariable("SERVER_ENDPOINT") != null) + if (Environment.GetEnvironmentVariable("SERVER_ENDPOINT") is not null) { serverEndPoint = Environment.GetEnvironmentVariable("SERVER_ENDPOINT"); accessKey = Environment.GetEnvironmentVariable("ACCESS_KEY"); secretKey = Environment.GetEnvironmentVariable("SECRET_KEY"); - if (Environment.GetEnvironmentVariable("ENABLE_HTTPS") != null) + if (Environment.GetEnvironmentVariable("ENABLE_HTTPS") is not null) if (Environment.GetEnvironmentVariable("ENABLE_HTTPS").Equals("1", StringComparison.OrdinalIgnoreCase)) schema = "https://"; } diff --git a/Minio.Examples/Program.cs b/Minio.Examples/Program.cs index 7c3192510..31e9960ef 100644 --- a/Minio.Examples/Program.cs +++ b/Minio.Examples/Program.cs @@ -58,7 +58,7 @@ public static async Task Main(string[] args) var isSecure = false; var port = 80; - if (Environment.GetEnvironmentVariable("SERVER_ENDPOINT") != null) + if (Environment.GetEnvironmentVariable("SERVER_ENDPOINT") is not null) { endPoint = Environment.GetEnvironmentVariable("SERVER_ENDPOINT"); var posColon = endPoint.LastIndexOf(':'); @@ -70,7 +70,7 @@ public static async Task Main(string[] args) accessKey = Environment.GetEnvironmentVariable("ACCESS_KEY"); secretKey = Environment.GetEnvironmentVariable("SECRET_KEY"); - if (Environment.GetEnvironmentVariable("ENABLE_HTTPS") != null) + if (Environment.GetEnvironmentVariable("ENABLE_HTTPS") is not null) { isSecure = Environment.GetEnvironmentVariable("ENABLE_HTTPS") .Equals("1", StringComparison.OrdinalIgnoreCase); diff --git a/Minio.Functional.Tests/FunctionalTest.cs b/Minio.Functional.Tests/FunctionalTest.cs index e875d63ec..13fec61e4 100644 --- a/Minio.Functional.Tests/FunctionalTest.cs +++ b/Minio.Functional.Tests/FunctionalTest.cs @@ -496,8 +496,8 @@ internal static async Task ListBuckets_Test(MinioClient minio) bucketList.ToList().Sort((x, y) => { if (string.Equals(x.Name, y.Name, StringComparison.Ordinal)) return 0; - if (x.Name == null) return -1; - if (y.Name == null) return 1; + if (x.Name is null) return -1; + if (y.Name is null) return 1; return x.Name.CompareTo(y.Name); }); var indx = 0; @@ -571,7 +571,7 @@ internal static async Task TearDown(MinioClient minio, string bucketName) { versioningConfig = await minio.GetVersioningAsync(new GetVersioningArgs() .WithBucket(bucketName)).ConfigureAwait(false); - if (versioningConfig != null && (versioningConfig.Status.Contains("Enabled") || + if (versioningConfig is not null && (versioningConfig.Status.Contains("Enabled") || versioningConfig.Status.Contains("Suspended"))) getVersions = true; @@ -938,7 +938,7 @@ internal static async Task PutObject_Task(MinioClient minio, string bucketName, var startTime = DateTime.Now; var filestream = mstream; - if (filestream == null) + if (filestream is null) { #if NETFRAMEWORK ReadOnlyMemory bs = File.ReadAllBytes(fileName); @@ -976,7 +976,7 @@ internal static async Task PutObject_Tester(MinioClient minio, var startTime = DateTime.Now; var filestream = mstream; - if (filestream == null) + if (filestream is null) { #if NETFRAMEWORK Memory bs = File.ReadAllBytes(fileName); @@ -1009,7 +1009,7 @@ internal static async Task PutObject_Tester(MinioClient minio, Assert.IsTrue(statObject.ObjectName.Equals(objectName, StringComparison.Ordinal)); Assert.AreEqual(statObject.Size, size); - if (contentType != null) + if (contentType is not null) { Assert.IsNotNull(statObject.ContentType); Assert.IsTrue(statObject.ContentType.Equals(contentType, StringComparison.OrdinalIgnoreCase)); @@ -1366,7 +1366,7 @@ internal static async Task PresignedPostPolicy_Test1(MinioClient minio) Assert.IsNotNull(statObject); Assert.IsTrue(statObject.ObjectName.Equals(objectName, StringComparison.Ordinal)); Assert.AreEqual(statObject.Size, sizeExpected); - Assert.IsTrue(statObject.MetaData["Content-Type"] != null); + Assert.IsTrue(statObject.MetaData["Content-Type"] is not null); Assert.IsTrue(statObject.ContentType.Equals(contentType, StringComparison.OrdinalIgnoreCase)); Assert.IsTrue(statObject.MetaData[metadataKey].Equals(metadataValue, StringComparison.Ordinal)); @@ -2721,7 +2721,7 @@ await PutObject_Tester(minio, bucketName, objectName, null, contentType, var notification = JsonSerializer.Deserialize(received[0].json); - if (notification.Records != null) + if (notification.Records is not null) { Assert.AreEqual(1, notification.Records.Count); Assert.IsTrue(notification.Records[0].EventName.Contains("s3:ObjectCreated:Put")); @@ -2765,7 +2765,7 @@ static bool isAWS(string endPoint) return matches.Count > 0; } - if (Environment.GetEnvironmentVariable("AWS_ENDPOINT") != null || + if (Environment.GetEnvironmentVariable("AWS_ENDPOINT") is not null || isAWS(Environment.GetEnvironmentVariable("SERVER_ENDPOINT"))) // This is a PASS new MintLogger(nameof(ListenBucketNotificationsAsync_Test1), @@ -3353,8 +3353,8 @@ internal static async Task PutObject_Test4(MinioClient minio) var statObject = await PutObject_Tester(minio, bucketName, objectName, fileName, contentType, metaData: metaData) .ConfigureAwait(false); - Assert.IsTrue(statObject != null); - Assert.IsTrue(statObject.MetaData != null); + Assert.IsTrue(statObject is not null); + Assert.IsTrue(statObject.MetaData is not null); var statMeta = new Dictionary(statObject.MetaData, StringComparer.OrdinalIgnoreCase); Assert.IsTrue(statMeta.ContainsKey("Customheader")); Assert.IsTrue(statObject.MetaData.ContainsKey("Content-Type") && @@ -4103,7 +4103,7 @@ internal static async Task CopyObject_Test8(MinioClient minio) .WithObject(objectName); var stats = await minio.StatObjectAsync(statObjectArgs).ConfigureAwait(false); - Assert.IsTrue(stats.MetaData["Orig"] != null); + Assert.IsTrue(stats.MetaData["Orig"] is not null); var copyCond = new CopyConditions(); copyCond.SetReplaceMetadataDirective(); @@ -4131,8 +4131,8 @@ internal static async Task CopyObject_Test8(MinioClient minio) .WithBucket(destBucketName) .WithObject(destObjectName); var dstats = await minio.StatObjectAsync(statObjectArgs).ConfigureAwait(false); - Assert.IsTrue(dstats.MetaData["Content-Type"] != null); - Assert.IsTrue(dstats.MetaData["Mynewkey"] != null); + Assert.IsTrue(dstats.MetaData["Content-Type"] is not null); + Assert.IsTrue(dstats.MetaData["Mynewkey"] is not null); Assert.IsTrue(dstats.MetaData["Content-Type"].Contains("application/css")); Assert.IsTrue(dstats.MetaData["Mynewkey"].Contains("test test")); new MintLogger("CopyObject_Test8", copyObjectSignature, diff --git a/Minio.Functional.Tests/Program.cs b/Minio.Functional.Tests/Program.cs index 7a0da16a6..ce1442d65 100644 --- a/Minio.Functional.Tests/Program.cs +++ b/Minio.Functional.Tests/Program.cs @@ -30,8 +30,8 @@ public static async Task Main(string[] args) var kmsEnabled = "0"; var port = 80; - var useAWS = Environment.GetEnvironmentVariable("AWS_ENDPOINT") != null; - if (Environment.GetEnvironmentVariable("SERVER_ENDPOINT") != null) + var useAWS = Environment.GetEnvironmentVariable("AWS_ENDPOINT") is not null; + if (Environment.GetEnvironmentVariable("SERVER_ENDPOINT") is not null) { endPoint = Environment.GetEnvironmentVariable("SERVER_ENDPOINT"); var posColon = endPoint.LastIndexOf(':'); @@ -43,7 +43,7 @@ public static async Task Main(string[] args) accessKey = Environment.GetEnvironmentVariable("ACCESS_KEY"); secretKey = Environment.GetEnvironmentVariable("SECRET_KEY"); - if (Environment.GetEnvironmentVariable("ENABLE_HTTPS") != null) + if (Environment.GetEnvironmentVariable("ENABLE_HTTPS") is not null) { isSecure = Environment.GetEnvironmentVariable("ENABLE_HTTPS") .Equals("1", StringComparison.OrdinalIgnoreCase); @@ -230,7 +230,7 @@ public static async Task Main(string[] args) await FunctionalTest.EncryptedCopyObject_Test2(minioClient).ConfigureAwait(false); } - if (kmsEnabled != null && string.Equals(kmsEnabled, "1", StringComparison.OrdinalIgnoreCase)) + if (kmsEnabled is not null && string.Equals(kmsEnabled, "1", StringComparison.OrdinalIgnoreCase)) { await FunctionalTest.PutGetStatEncryptedObject_Test3(minioClient).ConfigureAwait(false); await FunctionalTest.EncryptedCopyObject_Test3(minioClient).ConfigureAwait(false); diff --git a/Minio.Tests/AuthenticatorTest.cs b/Minio.Tests/AuthenticatorTest.cs index fa365eb4a..bc01d93c5 100644 --- a/Minio.Tests/AuthenticatorTest.cs +++ b/Minio.Tests/AuthenticatorTest.cs @@ -166,13 +166,13 @@ private Tuple GetHeaderKV(HttpRequestMessageBuilder request, str { var key = request.HeaderParameters.Keys.FirstOrDefault(o => string.Equals(o, headername, StringComparison.OrdinalIgnoreCase)); - if (key != null) return Tuple.Create(key, request.HeaderParameters[key]); + if (key is not null) return Tuple.Create(key, request.HeaderParameters[key]); return null; } private bool HasPayloadHeader(HttpRequestMessageBuilder request, string headerName) { var match = GetHeaderKV(request, headerName); - return match != null; + return match is not null; } } \ No newline at end of file diff --git a/Minio.Tests/DictionaryExtensionMethods.cs b/Minio.Tests/DictionaryExtensionMethods.cs index dd40599f5..1bd4aa584 100644 --- a/Minio.Tests/DictionaryExtensionMethods.cs +++ b/Minio.Tests/DictionaryExtensionMethods.cs @@ -26,7 +26,7 @@ public static bool PoliciesEqual(this IDictionary ListIncompleteUploads(ListIncompleteUploadsArgs args, .WithKeyMarker(nextKeyMarker) .WithUploadIdMarker(nextUploadIdMarker); var uploads = await GetMultipartUploadsListAsync(getArgs, cancellationToken).ConfigureAwait(false); - if (uploads == null) + if (uploads is null) { isRunning = false; continue; @@ -153,7 +153,7 @@ public async Task RemoveIncompleteUploadAsync(RemoveIncompleteUploadArgs args, throw; } - if (uploads == null) return; + if (uploads is null) return; foreach (var upload in uploads) if (upload.Key.Equals(args.ObjectName, StringComparison.OrdinalIgnoreCase)) { @@ -562,7 +562,7 @@ public async Task PutObjectAsync(PutObjectArgs args, args.SSE?.Marshal(args.Headers); // Upload object in single part if size falls under restricted part size. - if (args.ObjectSize < Constants.MinimumPartSize && args.ObjectSize >= 0 && args.ObjectStreamData != null) + if (args.ObjectSize < Constants.MinimumPartSize && args.ObjectSize >= 0 && args.ObjectStreamData is not null) { var bytes = await ReadFullAsync(args.ObjectStreamData, (int)args.ObjectSize).ConfigureAwait(false); var bytesRead = bytes.Length; @@ -715,7 +715,7 @@ public async Task CopyObjectAsync(CopyObjectArgs args, CancellationToken cancell newMeta = new Dictionary(args.Headers); else newMeta = new Dictionary(args.SourceObjectInfo.MetaData); - if (args.SourceObject.SSE != null && args.SourceObject.SSE is SSECopy) + if (args.SourceObject.SSE is not null && args.SourceObject.SSE is SSECopy) args.SourceObject.SSE.Marshal(newMeta); args.SSE?.Marshal(newMeta); cpReqArgs.WithHeaders(newMeta); @@ -939,7 +939,7 @@ private async Task MultipartCopyUploadAsync(MultipartCopyUploadArgs args, queryMap.Add("partNumber", partNumber.ToString()); } - if (args.SourceObject.SSE != null && args.SourceObject.SSE is SSECopy) + if (args.SourceObject.SSE is not null && args.SourceObject.SSE is SSECopy) args.SourceObject.SSE.Marshal(args.Headers); args.SSE?.Marshal(args.Headers); var cpPartArgs = new CopyObjectRequestArgs() @@ -1261,14 +1261,14 @@ private async Task CopyObjectRequestAsync(string bucketName, string obje destObjectName, customHeaders) .ConfigureAwait(false); - if (queryMap != null) + if (queryMap is not null) foreach (var query in queryMap) requestMessageBuilder.AddQueryParameter(query.Key, query.Value); // Set the object source requestMessageBuilder.AddOrUpdateHeaderParameter("x-amz-copy-source", sourceObjectPath); // If no conditions available, skip addition else add the conditions to the header - if (copyConditions != null) + if (copyConditions is not null) foreach (var item in copyConditions.Conditions) requestMessageBuilder.AddOrUpdateHeaderParameter(item.Key, item.Value); @@ -1355,7 +1355,7 @@ private async Task MultipartCopyUploadAsync(string bucketName, string objectName } }; - if (sseSrc != null && sseSrc is SSECopy) sseSrc.Marshal(customHeader); + if (sseSrc is not null && sseSrc is SSECopy) sseSrc.Marshal(customHeader); sseDest?.Marshal(customHeader); var cpPartResult = (CopyPartResult)await CopyObjectRequestAsync(bucketName, objectName, diff --git a/Minio/BucketRegionCache.cs b/Minio/BucketRegionCache.cs index c46a7783e..2dc347670 100644 --- a/Minio/BucketRegionCache.cs +++ b/Minio/BucketRegionCache.cs @@ -86,8 +86,8 @@ internal static async Task Update(MinioClient client, string bucketName) { string region = null; - if (!string.Equals(bucketName, null, StringComparison.OrdinalIgnoreCase) && client.AccessKey != null - && client.SecretKey != null && !Instance.Exists(bucketName)) + if (!string.Equals(bucketName, null, StringComparison.OrdinalIgnoreCase) && client.AccessKey is not null + && client.SecretKey is not null && !Instance.Exists(bucketName)) { string location = null; var path = Utils.UrlEncode(bucketName); @@ -99,7 +99,7 @@ internal static async Task Update(MinioClient client, string bucketName) using var response = await client.ExecuteTaskAsync(client.NoErrorHandlers, requestBuilder).ConfigureAwait(false); - if (response != null && HttpStatusCode.OK.Equals(response.StatusCode)) + if (response is not null && HttpStatusCode.OK.Equals(response.StatusCode)) { var root = XDocument.Parse(response.Content); location = root.Root.Value; diff --git a/Minio/Credentials/AssumeRoleBaseProvider.cs b/Minio/Credentials/AssumeRoleBaseProvider.cs index 923000926..1cc57fc4a 100644 --- a/Minio/Credentials/AssumeRoleBaseProvider.cs +++ b/Minio/Credentials/AssumeRoleBaseProvider.cs @@ -97,7 +97,7 @@ public T WithRoleAction(string action) internal virtual async Task BuildRequest() { - if (Client == null) throw new InvalidOperationException("MinioClient is not set in AssumeRoleBaseProvider"); + if (Client is null) throw new InvalidOperationException("MinioClient is not set in AssumeRoleBaseProvider"); var reqBuilder = await Client.CreateRequest(HttpMethod.Post).ConfigureAwait(false); reqBuilder.AddQueryParameter("Action", Action); reqBuilder.AddQueryParameter("Version", "2011-06-15"); @@ -113,7 +113,7 @@ public override async Task GetCredentialsAsync() if (Credentials?.AreExpired() == false) return Credentials; var requestBuilder = await BuildRequest().ConfigureAwait(false); - if (Client != null) + if (Client is not null) { ResponseResult responseMessage = null; try diff --git a/Minio/Credentials/AssumeRoleProvider.cs b/Minio/Credentials/AssumeRoleProvider.cs index f539886d4..97bdf2e08 100644 --- a/Minio/Credentials/AssumeRoleProvider.cs +++ b/Minio/Credentials/AssumeRoleProvider.cs @@ -98,7 +98,7 @@ public override async Task GetCredentialsAsync() if (Credentials?.AreExpired() == false) return Credentials; var requestBuilder = await BuildRequest().ConfigureAwait(false); - if (Client != null) + if (Client is not null) { ResponseResult responseResult = null; try @@ -113,8 +113,8 @@ public override async Task GetCredentialsAsync() assumeRoleResp = Utils.DeserializeXml(stream); } - if (Credentials == null && - assumeRoleResp?.AssumeRole != null) + if (Credentials is null && + assumeRoleResp?.AssumeRole is not null) Credentials = assumeRoleResp.AssumeRole.Credentials; return Credentials; @@ -131,7 +131,7 @@ public override async Task GetCredentialsAsync() internal override async Task BuildRequest() { Action = AssumeRole; - if (DurationInSeconds == null || DurationInSeconds.Value == 0) + if (DurationInSeconds is null || DurationInSeconds.Value == 0) DurationInSeconds = DefaultDurationInSeconds; var requestMessageBuilder = await Client.CreateRequest(HttpMethod.Post).ConfigureAwait(false); diff --git a/Minio/Credentials/CertificateIdentityProvider.cs b/Minio/Credentials/CertificateIdentityProvider.cs index 0b26682e8..3651946c6 100644 --- a/Minio/Credentials/CertificateIdentityProvider.cs +++ b/Minio/Credentials/CertificateIdentityProvider.cs @@ -120,10 +120,10 @@ public override async Task GetCredentialsAsync() if (Credentials?.AreExpired() == false) return Credentials; - if (HttpClient == null) + if (HttpClient is null) throw new ArgumentException("httpClient cannot be null or empty"); - if (ClientCertificate == null) throw new ArgumentException("clientCertificate cannot be null or empty"); + if (ClientCertificate is null) throw new ArgumentException("clientCertificate cannot be null or empty"); using var response = await HttpClient.PostAsync(PostEndpoint, null).ConfigureAwait(false); @@ -136,7 +136,7 @@ public override async Task GetCredentialsAsync() Utils.DeserializeXml(stream); } - if (Credentials == null && certResponse?.Cr != null) + if (Credentials is null && certResponse?.Cr is not null) Credentials = certResponse.Cr.Credentials; return Credentials; diff --git a/Minio/Credentials/ChainedProvider.cs b/Minio/Credentials/ChainedProvider.cs index 322c1213e..ddecba5c5 100644 --- a/Minio/Credentials/ChainedProvider.cs +++ b/Minio/Credentials/ChainedProvider.cs @@ -45,7 +45,7 @@ public ChainedProvider AddProviders(ClientProvider[] providers) public override AccessCredentials GetCredentials() { if (Credentials?.AreExpired() == false) return Credentials; - if (CurrentProvider != null && !Credentials.AreExpired()) + if (CurrentProvider is not null && !Credentials.AreExpired()) { Credentials = CurrentProvider.GetCredentials(); return CurrentProvider.GetCredentials(); diff --git a/Minio/Credentials/IAMAWSProvider.cs b/Minio/Credentials/IAMAWSProvider.cs index 760b64929..da997f687 100644 --- a/Minio/Credentials/IAMAWSProvider.cs +++ b/Minio/Credentials/IAMAWSProvider.cs @@ -58,7 +58,7 @@ public override AccessCredentials GetCredentials() { Validate(); var url = CustomEndPoint; - if (CustomEndPoint == null) + if (CustomEndPoint is null) { var region = Environment.GetEnvironmentVariable("AWS_REGION"); if (string.IsNullOrWhiteSpace(region)) @@ -83,10 +83,10 @@ internal AccessCredentials GetAccessCredentials(string tokenFile) Validate(); var url = CustomEndPoint; var urlStr = url.Authority; - if (url == null || string.IsNullOrWhiteSpace(urlStr)) + if (url is null || string.IsNullOrWhiteSpace(urlStr)) { var region = Environment.GetEnvironmentVariable("AWS_REGION"); - urlStr = region == null ? "https://sts.amazonaws.com" : "https://sts." + region + ".amazonaws.com"; + urlStr = region is null ? "https://sts.amazonaws.com" : "https://sts." + region + ".amazonaws.com"; url = new Uri(urlStr); } @@ -155,7 +155,7 @@ public override async Task GetCredentialsAsync() var containerRelativeUri = Environment.GetEnvironmentVariable("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"); var containerFullUri = Environment.GetEnvironmentVariable("AWS_CONTAINER_CREDENTIALS_FULL_URI"); - var isURLEmpty = url == null; + var isURLEmpty = url is null; if (!string.IsNullOrWhiteSpace(containerRelativeUri) && isURLEmpty) { url = RequestUtil.MakeTargetURL("169.254.170.2" + "/" + containerRelativeUri, false); @@ -205,7 +205,7 @@ public async Task GetIamRoleNamedURL() Validate(); var url = CustomEndPoint; string newUrlStr; - if (url == null || string.IsNullOrWhiteSpace(url.Authority)) + if (url is null || string.IsNullOrWhiteSpace(url.Authority)) { url = new Uri("http://169.254.169.254/latest/meta-data/iam/security-credentials/"); newUrlStr = "http://169.254.169.254/latest/meta-data/iam/security-credentials/"; @@ -225,7 +225,7 @@ public async Task GetIamRoleNamedURL() public IAMAWSProvider WithMinioClient(MinioClient minio) { Minio_Client = minio; - if (Credentials == null || + if (Credentials is null || string.IsNullOrWhiteSpace(Credentials.AccessKey) || string.IsNullOrWhiteSpace(Credentials.SecretKey)) Credentials = GetCredentialsAsync().GetAwaiter().GetResult(); @@ -246,7 +246,7 @@ public IAMAWSProvider WithEndpoint(string endpoint) public void Validate() { - if (Minio_Client == null) + if (Minio_Client is null) throw new ArgumentNullException(nameof(Minio_Client) + " should be assigned for the operation to continue."); } diff --git a/Minio/Credentials/WebIdentityClientGrantsProvider.cs b/Minio/Credentials/WebIdentityClientGrantsProvider.cs index 122a8297b..6cd0d1570 100644 --- a/Minio/Credentials/WebIdentityClientGrantsProvider.cs +++ b/Minio/Credentials/WebIdentityClientGrantsProvider.cs @@ -33,7 +33,7 @@ public abstract class WebIdentityClientGrantsProvider : AssumeRoleBaseProvide internal uint GetDurationInSeconds(uint expiry) { - if (DurationInSeconds != null && DurationInSeconds.Value > 0) expiry = DurationInSeconds.Value; + if (DurationInSeconds is not null && DurationInSeconds.Value > 0) expiry = DurationInSeconds.Value; if (expiry > MAX_DURATION_SECONDS) return MAX_DURATION_SECONDS; return expiry < MIN_DURATION_SECONDS ? MIN_DURATION_SECONDS : expiry; } @@ -72,9 +72,9 @@ internal override AccessCredentials ParseResponse(HttpResponseMessage response) protected void Validate() { - if (JWTSupplier == null) + if (JWTSupplier is null) throw new ArgumentNullException(nameof(JWTSupplier) + " JWT Token supplier cannot be null."); - if (STSEndpoint == null || string.IsNullOrWhiteSpace(STSEndpoint.AbsoluteUri)) + if (STSEndpoint is null || string.IsNullOrWhiteSpace(STSEndpoint.AbsoluteUri)) throw new InvalidOperationException(nameof(STSEndpoint) + " value is invalid."); } } \ No newline at end of file diff --git a/Minio/DataModel/BucketArgs.cs b/Minio/DataModel/BucketArgs.cs index 9d008cfd4..50a897bad 100644 --- a/Minio/DataModel/BucketArgs.cs +++ b/Minio/DataModel/BucketArgs.cs @@ -35,7 +35,7 @@ public T WithBucket(string bucket) public virtual T WithHeaders(IDictionary headers) { - if (headers == null || headers.Count <= 0) return (T)this; + if (headers is null || headers.Count <= 0) return (T)this; Headers ??= new Dictionary(); foreach (var key in headers.Keys) { diff --git a/Minio/DataModel/BucketOperationsArgs.cs b/Minio/DataModel/BucketOperationsArgs.cs index 8da756e40..5213732ad 100644 --- a/Minio/DataModel/BucketOperationsArgs.cs +++ b/Minio/DataModel/BucketOperationsArgs.cs @@ -303,7 +303,7 @@ public SetBucketNotificationsArgs() internal override HttpRequestMessageBuilder BuildRequest(HttpRequestMessageBuilder requestMessageBuilder) { - if (BucketNotificationConfiguration == null) + if (BucketNotificationConfiguration is null) throw new UnexpectedMinioException( "Cannot BuildRequest for SetBucketNotificationsArgs. BucketNotification configuration not assigned"); @@ -556,7 +556,7 @@ internal override HttpRequestMessageBuilder BuildRequest(HttpRequestMessageBuild internal override void Validate() { base.Validate(); - if (BucketTags == null || BucketTags.Tags.Count == 0) + if (BucketTags is null || BucketTags.Tags.Count == 0) throw new InvalidOperationException("Unable to set empty tags."); } } @@ -607,7 +607,7 @@ public SetObjectLockConfigurationArgs WithLockConfiguration(ObjectLockConfigurat internal override void Validate() { base.Validate(); - if (LockConfiguration == null) + if (LockConfiguration is null) throw new InvalidOperationException("The lock configuration object " + nameof(LockConfiguration) + " is not set. Please use " + nameof(WithLockConfiguration) + " to set."); @@ -696,7 +696,7 @@ internal override HttpRequestMessageBuilder BuildRequest(HttpRequestMessageBuild internal override void Validate() { base.Validate(); - if (BucketLifecycle == null || BucketLifecycle.Rules.Count == 0) + if (BucketLifecycle is null || BucketLifecycle.Rules.Count == 0) throw new InvalidOperationException("Unable to set empty Lifecycle configuration."); } } diff --git a/Minio/DataModel/BucketOperationsReponse.cs b/Minio/DataModel/BucketOperationsReponse.cs index af9ca8c7e..47b32854f 100644 --- a/Minio/DataModel/BucketOperationsReponse.cs +++ b/Minio/DataModel/BucketOperationsReponse.cs @@ -77,14 +77,14 @@ internal ListObjectsItemResponse(ListObjectsArgs args, TupleWhen etag is null public void SetMatchETag(string etag) { - if (etag == null) throw new ArgumentException("ETag cannot be empty", nameof(etag)); + if (etag is null) throw new ArgumentException("ETag cannot be empty", nameof(etag)); copyConditions.Add("x-amz-copy-source-if-match", etag); } @@ -92,7 +92,7 @@ public void SetMatchETag(string etag) /// When etag is null public void SetMatchETagNone(string etag) { - if (etag == null) throw new ArgumentException("ETag cannot be empty", nameof(etag)); + if (etag is null) throw new ArgumentException("ETag cannot be empty", nameof(etag)); copyConditions.Add("x-amz-copy-source-if-none-match", etag); } diff --git a/Minio/DataModel/ILM/AndOperator.cs b/Minio/DataModel/ILM/AndOperator.cs index 48785851e..f0c9b1512 100644 --- a/Minio/DataModel/ILM/AndOperator.cs +++ b/Minio/DataModel/ILM/AndOperator.cs @@ -44,7 +44,7 @@ public AndOperator(string prefix, IList tag) public AndOperator(string prefix, IDictionary tags) { Prefix = prefix; - if (tags == null || tags.Count == 0) + if (tags is null || tags.Count == 0) return; foreach (var item in tags) Tags.Add(new Tag(item.Key, item.Value)); } diff --git a/Minio/DataModel/ILM/LifecycleConfiguration.cs b/Minio/DataModel/ILM/LifecycleConfiguration.cs index 6a8e35479..6d92d4c90 100644 --- a/Minio/DataModel/ILM/LifecycleConfiguration.cs +++ b/Minio/DataModel/ILM/LifecycleConfiguration.cs @@ -38,7 +38,7 @@ public LifecycleConfiguration() public LifecycleConfiguration(IList rules) { - if (rules == null || rules.Count <= 0) + if (rules is null || rules.Count <= 0) throw new ArgumentNullException(nameof(rules), "Rules object cannot be empty. A finite set of Lifecycle Rules are needed for LifecycleConfiguration."); diff --git a/Minio/DataModel/Item.cs b/Minio/DataModel/Item.cs index cfac1d95c..53d234799 100644 --- a/Minio/DataModel/Item.cs +++ b/Minio/DataModel/Item.cs @@ -31,7 +31,7 @@ public string ETag get => etag; set { - if (value != null) + if (value is not null) etag = value.Replace("\"", string.Empty); else etag = null; diff --git a/Minio/DataModel/Notification/BucketNotification.cs b/Minio/DataModel/Notification/BucketNotification.cs index bb845707d..7c44b0d5b 100644 --- a/Minio/DataModel/Notification/BucketNotification.cs +++ b/Minio/DataModel/Notification/BucketNotification.cs @@ -119,7 +119,7 @@ public bool ShouldSerializeQueueConfigs() public bool ShouldSerializeName() { - return Name != null; + return Name is not null; } /// diff --git a/Minio/DataModel/Notification/FilterRule.cs b/Minio/DataModel/Notification/FilterRule.cs index 91253bd87..a189f9eee 100644 --- a/Minio/DataModel/Notification/FilterRule.cs +++ b/Minio/DataModel/Notification/FilterRule.cs @@ -43,11 +43,11 @@ public FilterRule(string name, string value) public bool ShouldSerializeName() { - return Name != null; + return Name is not null; } public bool ShouldSerializeValue() { - return Value != null; + return Value is not null; } } \ No newline at end of file diff --git a/Minio/DataModel/Notification/LambdaConfig.cs b/Minio/DataModel/Notification/LambdaConfig.cs index 369b54bc2..961952714 100644 --- a/Minio/DataModel/Notification/LambdaConfig.cs +++ b/Minio/DataModel/Notification/LambdaConfig.cs @@ -45,7 +45,7 @@ public override bool Equals(object obj) { var other = (LambdaConfig)obj; // If parameter is null return false. - if (obj == null) + if (obj is null) return false; return other.Lambda.Equals(Lambda, StringComparison.Ordinal); } diff --git a/Minio/DataModel/Notification/NotificationConfiguration.cs b/Minio/DataModel/Notification/NotificationConfiguration.cs index 8cac23cb9..bb4e1a629 100644 --- a/Minio/DataModel/Notification/NotificationConfiguration.cs +++ b/Minio/DataModel/Notification/NotificationConfiguration.cs @@ -96,12 +96,12 @@ public void AddFilterPrefix(string prefix) public bool ShouldSerializeFilter() { - return Filter != null; + return Filter is not null; } public bool ShouldSerializeId() { - return Id != null; + return Id is not null; } public bool ShouldSerializeEvents() @@ -111,6 +111,6 @@ public bool ShouldSerializeEvents() internal bool IsIdSet() { - return Id != null; + return Id is not null; } } \ No newline at end of file diff --git a/Minio/DataModel/Notification/QueueConfig.cs b/Minio/DataModel/Notification/QueueConfig.cs index 49d3a539f..8a989d1be 100644 --- a/Minio/DataModel/Notification/QueueConfig.cs +++ b/Minio/DataModel/Notification/QueueConfig.cs @@ -43,7 +43,7 @@ public override bool Equals(object obj) { var other = (QueueConfig)obj; // If parameter is null return false. - if (other == null) return false; + if (other is null) return false; return other.Queue.Equals(Queue, StringComparison.Ordinal); } diff --git a/Minio/DataModel/Notification/TopicConfig.cs b/Minio/DataModel/Notification/TopicConfig.cs index 8b714a8e9..7712e9972 100644 --- a/Minio/DataModel/Notification/TopicConfig.cs +++ b/Minio/DataModel/Notification/TopicConfig.cs @@ -49,7 +49,7 @@ public override bool Equals(object obj) { var other = (TopicConfig)obj; // If parameter is null return false. - if (other == null) return false; + if (other is null) return false; return other.Topic.Equals(Topic, StringComparison.OrdinalIgnoreCase); } diff --git a/Minio/DataModel/ObjectOperationsArgs.cs b/Minio/DataModel/ObjectOperationsArgs.cs index 042345ebb..17a03b10d 100644 --- a/Minio/DataModel/ObjectOperationsArgs.cs +++ b/Minio/DataModel/ObjectOperationsArgs.cs @@ -44,7 +44,7 @@ internal override void Validate() throw new InvalidOperationException("The Expression " + nameof(SelectOptions.Expression) + " for Select Object Content cannot be empty."); - if (SelectOptions.InputSerialization == null || SelectOptions.OutputSerialization == null) + if (SelectOptions.InputSerialization is null || SelectOptions.OutputSerialization is null) throw new InvalidOperationException( "The Input/Output serialization members for SelectObjectContentArgs should be initialized " + nameof(SelectOptions.InputSerialization) + " " + nameof(SelectOptions.OutputSerialization)); @@ -518,7 +518,7 @@ public GetObjectArgs() internal override void Validate() { base.Validate(); - if (CallBack == null && FuncCallBack == null && string.IsNullOrEmpty(FileName)) + if (CallBack is null && FuncCallBack is null && string.IsNullOrEmpty(FileName)) throw new MinioException("Atleast one of " + nameof(CallBack) + ", CallBack method or " + nameof(FileName) + " file path to save need to be set for GetObject operation."); @@ -530,7 +530,7 @@ internal override void Validate() throw new ArgumentException("Length should be greater than or equal to zero", nameof(ObjectLength)); } - if (FileName != null) Utils.ValidateFile(FileName); + if (FileName is not null) Utils.ValidateFile(FileName); Populate(); } @@ -694,7 +694,7 @@ internal override void Validate() "or " + nameof(WithObjectsVersions) + " method to set objects to be deleted."); - if ((ObjectNames == null && ObjectNamesVersions == null) || + if ((ObjectNames is null && ObjectNamesVersions is null) || (ObjectNames.Count == 0 && ObjectNamesVersions.Count == 0)) throw new InvalidOperationException( "Please assign list of object names or object names and version IDs to remove using method(s) " + @@ -768,7 +768,7 @@ internal override HttpRequestMessageBuilder BuildRequest(HttpRequestMessageBuild internal override void Validate() { base.Validate(); - if (ObjectTags == null || ObjectTags.Tags.Count == 0) + if (ObjectTags is null || ObjectTags.Tags.Count == 0) throw new InvalidOperationException("Unable to set empty tags."); } } @@ -927,7 +927,7 @@ public CopySourceObjectArgs() public CopySourceObjectArgs WithCopyConditions(CopyConditions cp) { - CopyOperationConditions = cp != null ? cp.Clone() : new CopyConditions(); + CopyOperationConditions = cp is not null ? cp.Clone() : new CopyConditions(); return this; } @@ -987,7 +987,7 @@ internal CopyObjectRequestArgs WithReplaceTagsDirective(bool replace) public CopyObjectRequestArgs WithCopyObjectSource(CopySourceObjectArgs cs) { - if (cs == null) + if (cs is null) throw new InvalidOperationException("The copy source object needed for copy operation is not initialized."); SourceObject ??= new CopySourceObjectArgs(); @@ -1019,11 +1019,11 @@ internal override HttpRequestMessageBuilder BuildRequest(HttpRequestMessageBuild // Set the object source requestMessageBuilder.AddOrUpdateHeaderParameter("x-amz-copy-source", sourceObjectPath); - if (QueryMap != null) + if (QueryMap is not null) foreach (var query in QueryMap) requestMessageBuilder.AddQueryParameter(query.Key, query.Value); - if (SourceObject.CopyOperationConditions != null) + if (SourceObject.CopyOperationConditions is not null) foreach (var item in SourceObject.CopyOperationConditions.Conditions) requestMessageBuilder.AddOrUpdateHeaderParameter(item.Key, item.Value); @@ -1090,7 +1090,7 @@ public CopyObjectRequestArgs WithObjectLockRetentionDate(DateTime untilDate) internal override void Validate() { Utils.ValidateBucketName(BucketName); //Object name can be same as that of source. - if (SourceObject == null) throw new InvalidOperationException(nameof(SourceObject) + " has not been assigned."); + if (SourceObject is null) throw new InvalidOperationException(nameof(SourceObject) + " has not been assigned."); Populate(); } @@ -1098,7 +1098,7 @@ internal void Populate() { ObjectName = string.IsNullOrEmpty(ObjectName) ? SourceObject.ObjectName : ObjectName; // Opting for concat as Headers may have byte range info .etc. - if (!ReplaceMetadataDirective && SourceObjectInfo.MetaData != null) + if (!ReplaceMetadataDirective && SourceObjectInfo.MetaData is not null) Headers = SourceObjectInfo.MetaData.Concat(Headers).GroupBy(item => item.Key) .ToDictionary(item => item.Key, item => item.First().Value); else if (ReplaceMetadataDirective) Headers ??= new Dictionary(); @@ -1129,11 +1129,11 @@ public CopyObjectArgs() internal override void Validate() { Utils.ValidateBucketName(BucketName); - if (SourceObject == null) + if (SourceObject is null) throw new InvalidOperationException(nameof(SourceObject) + " has not been assigned. Please use " + nameof(WithCopyObjectSource)); - if (SourceObjectInfo == null) + if (SourceObjectInfo is null) throw new InvalidOperationException( "StatObject result for the copy source object needed to continue copy operation. Use " + nameof(WithCopyObjectSourceStats) + " to initialize StatObject result."); @@ -1169,7 +1169,7 @@ private void Populate() Headers ??= new Dictionary(); if (ReplaceMetadataDirective) { - if (Headers != null) + if (Headers is not null) foreach (var pair in SourceObjectInfo.MetaData) { var comparer = StringComparer.OrdinalIgnoreCase; @@ -1185,7 +1185,7 @@ private void Populate() item.Last().Value); } - if (Headers != null) + if (Headers is not null) { var newKVList = new List>(); foreach (var item in Headers) @@ -1210,7 +1210,7 @@ private void Populate() public CopyObjectArgs WithCopyObjectSource(CopySourceObjectArgs cs) { - if (cs == null) + if (cs is null) throw new InvalidOperationException("The copy source object needed for copy operation is not initialized."); SourceObject.RequestMethod = HttpMethod.Put; @@ -1259,7 +1259,7 @@ public CopyObjectArgs WithObjectLockRetentionDate(DateTime untilDate) internal CopyObjectArgs WithCopyObjectSourceStats(ObjectStat info) { SourceObjectInfo = info; - if (info.MetaData != null && !ReplaceMetadataDirective) + if (info.MetaData is not null && !ReplaceMetadataDirective) { SourceObject.Headers ??= new Dictionary(); SourceObject.Headers = SourceObject.Headers.Concat(info.MetaData).GroupBy(item => item.Key) @@ -1392,9 +1392,9 @@ internal class MultipartCopyUploadArgs : ObjectWriteArgs(args.SourceObjectInfo.MetaData); else if (args.ReplaceMetadataDirective) Headers ??= new Dictionary(); - if (Headers != null) + if (Headers is not null) { var newKVList = new List>(); foreach (var item in Headers) @@ -1534,7 +1534,7 @@ internal class NewMultipartUploadCopyArgs : NewMultipartUploadArgs item.Key) .ToDictionary(item => item.Key, item => item.First().Value); else if (ReplaceMetadataDirective) Headers ??= new Dictionary(); - if (Headers != null) + if (Headers is not null) { var newKVList = new List>(); foreach (var item in Headers) @@ -1608,7 +1608,7 @@ public NewMultipartUploadCopyArgs WithSourceObjectInfo(ObjectStat stat) public NewMultipartUploadCopyArgs WithCopyObjectSource(CopySourceObjectArgs cs) { - if (cs == null) + if (cs is null) throw new InvalidOperationException("The copy source object needed for copy operation is not initialized."); SourceObject ??= new CopySourceObjectArgs(); @@ -1684,7 +1684,7 @@ internal override void Validate() base.Validate(); if (string.IsNullOrWhiteSpace(UploadId)) throw new ArgumentNullException(nameof(UploadId) + " cannot be empty."); - if (ETags == null || ETags.Count <= 0) + if (ETags is null || ETags.Count <= 0) throw new InvalidOperationException(nameof(ETags) + " dictionary cannot be empty."); } @@ -1816,7 +1816,7 @@ internal override void Validate() { base.Validate(); // Check atleast one of filename or stream are initialized - if (string.IsNullOrWhiteSpace(FileName) && ObjectStreamData == null) + if (string.IsNullOrWhiteSpace(FileName) && ObjectStreamData is null) throw new ArgumentException("One of " + nameof(FileName) + " or " + nameof(ObjectStreamData) + " must be set."); @@ -1824,13 +1824,13 @@ internal override void Validate() throw new ArgumentOutOfRangeException(nameof(PartNumber), PartNumber, "Invalid Part number value. Cannot be less than 0"); // Check if only one of filename or stream are initialized - if (!string.IsNullOrWhiteSpace(FileName) && ObjectStreamData != null) + if (!string.IsNullOrWhiteSpace(FileName) && ObjectStreamData is not null) throw new ArgumentException("Only one of " + nameof(FileName) + " or " + nameof(ObjectStreamData) + " should be set."); if (!string.IsNullOrWhiteSpace(FileName)) Utils.ValidateFile(FileName); // Check object size when using stream data - if (ObjectStreamData != null && ObjectSize == 0) + if (ObjectStreamData is not null && ObjectSize == 0) throw new ArgumentException($"{nameof(ObjectSize)} must be set"); Populate(); } @@ -1861,7 +1861,7 @@ internal override HttpRequestMessageBuilder BuildRequest(HttpRequestMessageBuild if (ObjectTags?.TaggingSet?.Tag.Count > 0) requestMessageBuilder.AddOrUpdateHeaderParameter("x-amz-tagging", ObjectTags.GetTagString()); - if (Retention != null) + if (Retention is not null) { requestMessageBuilder.AddOrUpdateHeaderParameter("x-amz-object-lock-retain-until-date", Retention.RetainUntilDate); @@ -1870,7 +1870,7 @@ internal override HttpRequestMessageBuilder BuildRequest(HttpRequestMessageBuild Utils.GetMD5SumStr(RequestBody.Span)); } - if (LegalHoldEnabled != null) + if (LegalHoldEnabled is not null) requestMessageBuilder.AddOrUpdateHeaderParameter("x-amz-object-lock-legal-hold", LegalHoldEnabled == true ? "ON" : "OFF"); @@ -1893,7 +1893,7 @@ internal override HttpRequestMessageBuilder BuildRequest(HttpRequestMessageBuild public override PutObjectArgs WithHeaders(IDictionary headers) { Headers ??= new Dictionary(StringComparer.OrdinalIgnoreCase); - if (headers != null) + if (headers is not null) foreach (var p in headers) { var key = p.Key; diff --git a/Minio/DataModel/ObjectOperationsResponse.cs b/Minio/DataModel/ObjectOperationsResponse.cs index 7403d4239..a8c719af5 100644 --- a/Minio/DataModel/ObjectOperationsResponse.cs +++ b/Minio/DataModel/ObjectOperationsResponse.cs @@ -73,7 +73,7 @@ internal GetMultipartUploadsListResponse(HttpStatusCode statusCode, string respo XNamespace ns = Utils.DetermineNamespace(root); var itemCheck = root.Root.Descendants(ns + "Upload").FirstOrDefault(); - if (uploadsResult == null || itemCheck?.HasElements != true) return; + if (uploadsResult is null || itemCheck?.HasElements != true) return; var uploads = from c in root.Root.Descendants(ns + "Upload") select new Upload { @@ -112,7 +112,7 @@ public GetLegalHoldResponse(HttpStatusCode statusCode, string responseContent) CurrentLegalHoldConfiguration = Utils.DeserializeXml(stream); - if (CurrentLegalHoldConfiguration == null + if (CurrentLegalHoldConfiguration is null || string.IsNullOrEmpty(CurrentLegalHoldConfiguration.Status)) Status = "OFF"; else diff --git a/Minio/DataModel/ObjectStat.cs b/Minio/DataModel/ObjectStat.cs index d2c802f4d..f7603209b 100644 --- a/Minio/DataModel/ObjectStat.cs +++ b/Minio/DataModel/ObjectStat.cs @@ -146,16 +146,16 @@ public override string ToString() if (DeleteMarker) versionInfo = $"Version ID({VersionId}, deleted)"; } - if (Expires != null) expires = "Expiry(" + Utils.To8601String(Expires.Value) + ")"; - if (ObjectLockMode != null) + if (Expires is not null) expires = "Expiry(" + Utils.To8601String(Expires.Value) + ")"; + if (ObjectLockMode is not null) { objectLockInfo = "ObjectLock Mode(" + (ObjectLockMode == RetentionMode.GOVERNANCE ? "GOVERNANCE" : "COMPLIANCE") + ")"; objectLockInfo += " Retain Until Date(" + Utils.To8601String(ObjectLockRetainUntilDate.Value) + ")"; } - if (TaggingCount != null) taggingCount = "Tagging-Count(" + TaggingCount.Value + ")"; - if (LegalHoldEnabled != null) + if (TaggingCount is not null) taggingCount = "Tagging-Count(" + TaggingCount.Value + ")"; + if (LegalHoldEnabled is not null) legalHold = "LegalHold(" + (LegalHoldEnabled.Value ? "Enabled" : "Disabled") + ")"; if (!string.IsNullOrWhiteSpace(ReplicationStatus)) replicationStatus = "Replication Status(" + ReplicationStatus + ")"; diff --git a/Minio/DataModel/Part.cs b/Minio/DataModel/Part.cs index f679b06c2..ad11d3368 100644 --- a/Minio/DataModel/Part.cs +++ b/Minio/DataModel/Part.cs @@ -30,7 +30,7 @@ public string ETag get => etag; set { - if (value != null) + if (value is not null) etag = value.Replace("\"", string.Empty); else etag = null; diff --git a/Minio/DataModel/Replication/ReplicationConfiguration.cs b/Minio/DataModel/Replication/ReplicationConfiguration.cs index 86ce770b1..8add463b3 100644 --- a/Minio/DataModel/Replication/ReplicationConfiguration.cs +++ b/Minio/DataModel/Replication/ReplicationConfiguration.cs @@ -41,7 +41,7 @@ public ReplicationConfiguration(string role, Collection rules) { if (string.IsNullOrEmpty(role) || string.IsNullOrWhiteSpace(role)) throw new ArgumentNullException(nameof(role) + " member cannot be empty."); - if (rules == null || rules.Count == 0) + if (rules is null || rules.Count == 0) throw new ArgumentNullException(nameof(rules) + " member cannot be an empty list."); if (rules.Count >= 1000) throw new ArgumentOutOfRangeException( diff --git a/Minio/DataModel/Select/SelectResponseStream.cs b/Minio/DataModel/Select/SelectResponseStream.cs index c51e47630..699e28e31 100644 --- a/Minio/DataModel/Select/SelectResponseStream.cs +++ b/Minio/DataModel/Select/SelectResponseStream.cs @@ -39,7 +39,7 @@ public SelectResponseStream() // SelectResponseStream is a struct for selectobjectcontent response. public SelectResponseStream(Stream stream) { - if (stream != null) + if (stream is not null) { var _ms = new MemoryStream(); stream.CopyTo(_ms); diff --git a/Minio/DataModel/ServerSideEncryption.cs b/Minio/DataModel/ServerSideEncryption.cs index 2d1920f3b..425af6652 100644 --- a/Minio/DataModel/ServerSideEncryption.cs +++ b/Minio/DataModel/ServerSideEncryption.cs @@ -49,7 +49,7 @@ public class SSEC : IServerSideEncryption public SSEC(byte[] key) { - if (key == null || key.Length != 32) + if (key is null || key.Length != 32) throw new ArgumentException("Secret key needs to be a 256 bit AES Key", nameof(key)); this.key = key; } @@ -142,7 +142,7 @@ public void Marshal(IDictionary headers) headers.Add(Constants.SSEKMSKeyId, key); headers.Add(Constants.SSEGenericHeader, "aws:kms"); - if (context != null) headers.Add(Constants.SSEKMSContext, MarshalContext()); + if (context is not null) headers.Add(Constants.SSEKMSContext, MarshalContext()); } /// diff --git a/Minio/DataModel/Tags/TagSet.cs b/Minio/DataModel/Tags/TagSet.cs index 3c411a083..c59610c3e 100644 --- a/Minio/DataModel/Tags/TagSet.cs +++ b/Minio/DataModel/Tags/TagSet.cs @@ -30,7 +30,7 @@ public TagSet() public TagSet(IDictionary tags) { - if (tags == null || tags.Count == 0) return; + if (tags is null || tags.Count == 0) return; Tag = new Collection(); foreach (var item in tags) Tag.Add(new Tag(item.Key, item.Value)); } diff --git a/Minio/DataModel/Tags/Tagging.cs b/Minio/DataModel/Tags/Tagging.cs index 706134bd8..ee99db29a 100644 --- a/Minio/DataModel/Tags/Tagging.cs +++ b/Minio/DataModel/Tags/Tagging.cs @@ -41,7 +41,7 @@ public Tagging() public Tagging(IDictionary tags, bool isObjects) { - if (tags == null) + if (tags is null) { TaggingSet = null; return; @@ -68,7 +68,7 @@ public IDictionary Tags { get { - if (TaggingSet == null || TaggingSet.Tag.Count == 0) return null; + if (TaggingSet is null || TaggingSet.Tag.Count == 0) return null; var tagMap = new Dictionary(); foreach (var tag in TaggingSet.Tag) tagMap[tag.Key] = tag.Value; return tagMap; @@ -88,7 +88,7 @@ internal bool ValidateTagKey(string key) internal bool ValidateTagValue(string value) { - if (value == null || // Empty or whitespace is allowed + if (value is null || // Empty or whitespace is allowed value.Length > MAX_TAG_VALUE_LENGTH || value.Contains('&')) return false; @@ -145,7 +145,7 @@ public static Tagging GetObjectTags(IDictionary tags) internal string GetTagString() { - if (TaggingSet == null || (TaggingSet.Tag == null && TaggingSet.Tag.Count == 0)) return null; + if (TaggingSet is null || (TaggingSet.Tag is null && TaggingSet.Tag.Count == 0)) return null; var tagStr = ""; var i = 0; foreach (var tag in TaggingSet.Tag) diff --git a/Minio/Exceptions/MinioException.cs b/Minio/Exceptions/MinioException.cs index d7229bfc7..fdb5bc133 100644 --- a/Minio/Exceptions/MinioException.cs +++ b/Minio/Exceptions/MinioException.cs @@ -53,15 +53,15 @@ public MinioException(string message, ResponseResult serverResponse) private static string GetMessage(string message, ResponseResult serverResponse) { - if (serverResponse == null && string.IsNullOrEmpty(message)) + if (serverResponse is null && string.IsNullOrEmpty(message)) throw new ArgumentNullException(nameof(message)); - if (serverResponse == null) + if (serverResponse is null) return $"MinIO API responded with message={message}"; var contentString = serverResponse.Content; - if (message == null) + if (message is null) return $"MinIO API responded with status code={serverResponse.StatusCode}, response={serverResponse.ErrorMessage}, content={contentString}"; diff --git a/Minio/Helper/OperationsHelper.cs b/Minio/Helper/OperationsHelper.cs index f583cf882..a060bea23 100644 --- a/Minio/Helper/OperationsHelper.cs +++ b/Minio/Helper/OperationsHelper.cs @@ -45,7 +45,7 @@ private async Task GetObjectHelper(GetObjectArgs args, CancellationT if (args.OffsetLengthSet) statArgs.WithOffsetAndLength(args.ObjectOffset, args.ObjectLength); var objStat = await StatObjectAsync(statArgs, cancellationToken).ConfigureAwait(false); args?.Validate(); - if (args.FileName != null) + if (args.FileName is not null) await GetObjectFileAsync(args, objStat, cancellationToken).ConfigureAwait(false); else if (args.CallBack is not null) await GetObjectStreamAsync(args, objStat, args.CallBack, cancellationToken).ConfigureAwait(false); diff --git a/Minio/Helper/RequestUtil.cs b/Minio/Helper/RequestUtil.cs index b62a293ef..6f8916ade 100644 --- a/Minio/Helper/RequestUtil.cs +++ b/Minio/Helper/RequestUtil.cs @@ -57,7 +57,7 @@ internal static Uri MakeTargetURL(string endPoint, bool secure, string bucketNam if (!usePathStyle) { - var suffix = bucketName != null ? bucketName + "/" : ""; + var suffix = bucketName is not null ? bucketName + "/" : ""; host = host + "/" + suffix; } diff --git a/Minio/Helper/Utils.cs b/Minio/Helper/Utils.cs index f6ab37678..19ed032d5 100644 --- a/Minio/Helper/Utils.cs +++ b/Minio/Helper/Utils.cs @@ -189,9 +189,9 @@ public static void MoveWithReplace(string sourceFileName, string destFileName) internal static bool IsSupersetOf(IList l1, IList l2) { - if (l2 == null) return true; + if (l2 is null) return true; - if (l1 == null) return false; + if (l1 is null) return false; return !l2.Except(l1).Any(); } @@ -952,7 +952,7 @@ public static void Print(object obj) public static void PrintDict(IDictionary d) { - if (d != null) + if (d is not null) foreach (var kv in d) Console.WriteLine("DEBUG >> {0} = {1}", kv.Key, kv.Value); diff --git a/Minio/Helper/s3utils.cs b/Minio/Helper/s3utils.cs index 490d3cb15..0386153f1 100644 --- a/Minio/Helper/s3utils.cs +++ b/Minio/Helper/s3utils.cs @@ -46,7 +46,7 @@ internal static bool IsAmazonChinaEndPoint(string endpoint) // would support this. internal static bool IsVirtualHostSupported(Uri endpointURL, string bucketName) { - if (endpointURL == null) return false; + if (endpointURL is null) return false; // bucketName can be valid but '.' in the hostname will fail SSL // certificate validation. So do not use host-style for such buckets. if (string.Equals(endpointURL.Scheme, "https", StringComparison.OrdinalIgnoreCase) && diff --git a/Minio/HttpRequestMessageBuilder.cs b/Minio/HttpRequestMessageBuilder.cs index 5e32e95ee..62eb4258e 100644 --- a/Minio/HttpRequestMessageBuilder.cs +++ b/Minio/HttpRequestMessageBuilder.cs @@ -110,14 +110,14 @@ public HttpRequestMessage Request } } - if (request.Content != null) + if (request.Content is not null) { var isMultiDeleteRequest = false; if (Method == HttpMethod.Post) isMultiDeleteRequest = QueryParameters.ContainsKey("delete"); var isSecure = RequestUri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase); if (!isSecure && !isMultiDeleteRequest && - BodyParameters.TryGetValue("Content-Md5", out var value) && value != null) + BodyParameters.TryGetValue("Content-Md5", out var value) && value is not null) { BodyParameters.TryGetValue("Content-Md5", out var returnValue); request.Content.Headers.ContentMD5 = Convert.FromBase64String(returnValue); @@ -151,7 +151,7 @@ public void AddHeaderParameter(string key, string value) public void AddOrUpdateHeaderParameter(string key, string value) { - if (HeaderParameters.GetType().GetProperty(key) != null) + if (HeaderParameters.GetType().GetProperty(key) is not null) HeaderParameters.Remove(key); HeaderParameters[key] = value; } diff --git a/Minio/MinioClient.cs b/Minio/MinioClient.cs index 54d917bff..aab3b62d0 100644 --- a/Minio/MinioClient.cs +++ b/Minio/MinioClient.cs @@ -284,7 +284,7 @@ internal async Task CreateRequest( bool isBucketCreationRequest = false) { var region = string.Empty; - if (bucketName != null) + if (bucketName is not null) { Utils.ValidateBucketName(bucketName); // Fetch correct region for bucket if this is not a bucket creation @@ -292,9 +292,9 @@ internal async Task CreateRequest( region = await GetRegion(bucketName).ConfigureAwait(false); } - if (objectName != null) Utils.ValidateObjectName(objectName); + if (objectName is not null) Utils.ValidateObjectName(objectName); - if (Provider != null) + if (Provider is not null) { var isAWSEnvProvider = Provider is AWSEnvironmentProvider || (Provider is ChainedProvider ch && @@ -320,7 +320,7 @@ internal async Task CreateRequest( creds = await Provider.GetCredentialsAsync().ConfigureAwait(false); } - if (creds != null) + if (creds is not null) { AccessKey = creds.AccessKey; SecretKey = creds.SecretKey; @@ -332,9 +332,9 @@ internal async Task CreateRequest( var resource = string.Empty; var usePathStyle = false; - if (bucketName != null && S3utils.IsAmazonEndPoint(BaseUrl)) + if (bucketName is not null && S3utils.IsAmazonEndPoint(BaseUrl)) { - if (method == HttpMethod.Put && objectName == null && resourcePath == null) + if (method == HttpMethod.Put && objectName is null && resourcePath is null) // use path style for make bucket to workaround "AuthorizationHeaderMalformed" error from s3.amazonaws.com usePathStyle = true; else if (resourcePath?.Contains("location") == true) @@ -350,10 +350,10 @@ internal async Task CreateRequest( // Set Target URL var requestUrl = RequestUtil.MakeTargetURL(BaseUrl, Secure, bucketName, region, usePathStyle); - if (objectName != null) resource += Utils.EncodePath(objectName); + if (objectName is not null) resource += Utils.EncodePath(objectName); // Append query string passed in - if (resourcePath != null) resource += resourcePath; + if (resourcePath is not null) resource += resourcePath; HttpRequestMessageBuilder messageBuilder; if (!string.IsNullOrEmpty(resource)) @@ -366,7 +366,7 @@ internal async Task CreateRequest( messageBuilder.AddOrUpdateHeaderParameter("Content-Type", contentType); } - if (headerMap != null) + if (headerMap is not null) { if (headerMap.TryGetValue(messageBuilder.ContentTypeKey, out var value) && !string.IsNullOrEmpty(value)) headerMap[messageBuilder.ContentTypeKey] = contentType; @@ -435,7 +435,7 @@ public MinioClient WithRetryPolicy(RetryPolicyHandlingDelegate retryPolicyHandle /// public MinioClient WithHttpClient(HttpClient httpClient, bool disposeHttpClient = false) { - if (httpClient != null) HttpClient = httpClient; + if (httpClient is not null) HttpClient = httpClient; this.disposeHttpClient = disposeHttpClient; return this; } @@ -454,7 +454,7 @@ public MinioClient WithCredentialsProvider(ClientProvider provider) else credentials = Provider.GetCredentials(); - if (credentials == null) + if (credentials is null) // Unable to fetch credentials. return this; @@ -527,9 +527,9 @@ private async Task ExecuteTaskCoreAsync( HttpCompletionOption.ResponseHeadersRead, cancellationToken) .ConfigureAwait(false); responseResult = new ResponseResult(request, response); - if (requestMessageBuilder.ResponseWriter != null) + if (requestMessageBuilder.ResponseWriter is not null) requestMessageBuilder.ResponseWriter(responseResult.ContentStream); - if (requestMessageBuilder.FunctionResponseWriter != null) + if (requestMessageBuilder.FunctionResponseWriter is not null) await requestMessageBuilder.FunctionResponseWriter(responseResult.ContentStream, cancellationToken) .ConfigureAwait(false); } @@ -553,7 +553,7 @@ await requestMessageBuilder.FunctionResponseWriter(responseResult.ContentStream, /// internal static void ParseError(ResponseResult response) { - if (response == null) + if (response is null) throw new ConnectionException( "Response is nil. Please report this issue https://github.com/minio/minio-dotnet/issues", response); @@ -756,7 +756,7 @@ private void HandleIfErrorResponse(ResponseResult response, IEnumerable ExecuteWithRetry( Func> executeRequestCallback) { - return retryPolicyHandler == null + return retryPolicyHandler is null ? executeRequestCallback() : retryPolicyHandler(executeRequestCallback); } diff --git a/Minio/MinioClientExtensions.cs b/Minio/MinioClientExtensions.cs index ea11e3e50..1a3fd1501 100644 --- a/Minio/MinioClientExtensions.cs +++ b/Minio/MinioClientExtensions.cs @@ -77,10 +77,10 @@ public static MinioClient Build(this MinioClient minioClient) // Instantiate a region cache minioClient.regionCache = BucketRegionCache.Instance; if (string.IsNullOrEmpty(minioClient.BaseUrl)) throw new MinioException("Endpoint not initialized."); - if (minioClient.Provider != null && minioClient.Provider.GetType() != typeof(ChainedProvider) && - minioClient.SessionToken == null) + if (minioClient.Provider is not null && minioClient.Provider.GetType() != typeof(ChainedProvider) && + minioClient.SessionToken is null) throw new MinioException("User Access Credentials Provider not initialized correctly."); - if (minioClient.Provider == null && + if (minioClient.Provider is null && (string.IsNullOrEmpty(minioClient.AccessKey) || string.IsNullOrEmpty(minioClient.SecretKey))) throw new MinioException("User Access Credentials not initialized."); diff --git a/Minio/ResponseResult.cs b/Minio/ResponseResult.cs index 7c3b4005e..70157a1d5 100644 --- a/Minio/ResponseResult.cs +++ b/Minio/ResponseResult.cs @@ -49,7 +49,7 @@ public HttpStatusCode StatusCode { get { - if (Response == null) return 0; + if (Response is null) return 0; return Response.StatusCode; } @@ -59,7 +59,7 @@ public Stream ContentStream { get { - if (Response == null) return null; + if (Response is null) return null; #if NETSTANDARD return _stream ??= Response.Content.ReadAsStreamAsync().GetAwaiter().GetResult(); #else @@ -72,7 +72,7 @@ public ReadOnlyMemory ContentBytes { get { - if (ContentStream == null) + if (ContentStream is null) return ReadOnlyMemory.Empty; if (_contentBytes.IsEmpty) @@ -104,11 +104,11 @@ public IDictionary Headers { get { - if (Response == null) return new Dictionary(); + if (Response is null) return new Dictionary(); if (!_headers.Any()) { - if (Response.Content != null) + if (Response.Content is not null) foreach (var item in Response.Content.Headers) _headers.Add(item.Key, item.Value.FirstOrDefault()); diff --git a/Minio/V4Authenticator.cs b/Minio/V4Authenticator.cs index ab1067cd0..1e9ef367c 100644 --- a/Minio/V4Authenticator.cs +++ b/Minio/V4Authenticator.cs @@ -396,7 +396,7 @@ private string GetCanonicalRequest(HttpRequestMessageBuilder requestBuilder, canonicalStringList.AddLast(requestBuilder.Method.ToString()); var queryParamsDict = new Dictionary(); - if (requestBuilder.QueryParameters != null) + if (requestBuilder.QueryParameters is not null) foreach (var kvp in requestBuilder.QueryParameters) queryParamsDict[kvp.Key] = Uri.EscapeDataString(kvp.Value); @@ -417,7 +417,7 @@ private string GetCanonicalRequest(HttpRequestMessageBuilder requestBuilder, } var isFormData = false; - if (requestBuilder.Request.Content != null && requestBuilder.Request.Content.Headers?.ContentType != null) + if (requestBuilder.Request.Content is not null && requestBuilder.Request.Content.Headers?.ContentType is not null) isFormData = string.Equals(requestBuilder.Request.Content.Headers.ContentType.ToString(), "application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase); @@ -425,7 +425,7 @@ private string GetCanonicalRequest(HttpRequestMessageBuilder requestBuilder, { // Convert stream content to byte[] var cntntByteData = Span.Empty; - if (requestBuilder.Request.Content != null) + if (requestBuilder.Request.Content is not null) cntntByteData = requestBuilder.Request.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult(); // UTF conversion - String from bytes From d56ff900ecfababe6143020ad35de16a3cf7c4ef Mon Sep 17 00:00:00 2001 From: Martijn van Dijk Date: Tue, 25 Apr 2023 13:25:55 +0200 Subject: [PATCH 05/13] Update nuget --- Directory.Build.props | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index acad565f1..e093dc527 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -63,8 +63,8 @@ - + \ No newline at end of file From 74344e35f4cf9fd9e7ecca7721b13a5a7e4d7003 Mon Sep 17 00:00:00 2001 From: Martijn van Dijk Date: Tue, 25 Apr 2023 13:57:10 +0200 Subject: [PATCH 06/13] Fix concurency bug in older dotnet --- Minio/DataModel/ObjectOperationsArgs.cs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Minio/DataModel/ObjectOperationsArgs.cs b/Minio/DataModel/ObjectOperationsArgs.cs index 17a03b10d..1e7dd87c3 100644 --- a/Minio/DataModel/ObjectOperationsArgs.cs +++ b/Minio/DataModel/ObjectOperationsArgs.cs @@ -1170,7 +1170,11 @@ private void Populate() if (ReplaceMetadataDirective) { if (Headers is not null) +#if NETSTANDARD + foreach (var pair in SourceObjectInfo.MetaData.ToList()) +#else foreach (var pair in SourceObjectInfo.MetaData) +#endif { var comparer = StringComparer.OrdinalIgnoreCase; var newDictionary = new Dictionary(Headers, comparer); @@ -1188,7 +1192,11 @@ private void Populate() if (Headers is not null) { var newKVList = new List>(); +#if NETSTANDARD + foreach (var item in Headers.ToList()) +#else foreach (var item in Headers) +#endif { var key = item.Key; if (!OperationsUtil.IsSupportedHeader(item.Key) && From 459d6fe25f45e8b625f160f7624b5aefb02b7f19 Mon Sep 17 00:00:00 2001 From: Martijn van Dijk Date: Tue, 25 Apr 2023 14:23:24 +0200 Subject: [PATCH 07/13] Fix buffer bug in older dotnet --- Minio/DataModel/Select/SelectResponseStream.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Minio/DataModel/Select/SelectResponseStream.cs b/Minio/DataModel/Select/SelectResponseStream.cs index 699e28e31..5e886a279 100644 --- a/Minio/DataModel/Select/SelectResponseStream.cs +++ b/Minio/DataModel/Select/SelectResponseStream.cs @@ -66,7 +66,9 @@ protected int ReadFromStream(Span buffer) if (!_isProcessing) return read; #if NETSTANDARD - read = payloadStream.Read(buffer.ToArray(), 0, buffer.Length); + var bytes = new byte[buffer.Length]; + read = payloadStream.Read(bytes, 0, buffer.Length); + bytes.CopyTo(buffer); #else read = payloadStream.Read(buffer); #endif From 39397f93867cc6eaa96bb9ed665bd704cede481b Mon Sep 17 00:00:00 2001 From: Martijn van Dijk Date: Tue, 25 Apr 2023 14:58:58 +0200 Subject: [PATCH 08/13] More null checks --- Minio.Examples/Cases/ClearObjectRetention.cs | 2 ++ Minio.Examples/Cases/CustomRequestLogger.cs | 2 ++ Minio.Examples/Cases/GetBucketEncryption.cs | 2 ++ Minio.Examples/Cases/GetBucketLifecycle.cs | 2 ++ Minio.Examples/Cases/GetBucketReplication.cs | 2 ++ Minio.Examples/Cases/GetBucketTags.cs | 2 ++ Minio.Examples/Cases/GetObjectLockConfiguration.cs | 2 ++ Minio.Examples/Cases/GetObjectRetention.cs | 2 ++ Minio.Examples/Cases/GetObjectTags.cs | 2 ++ Minio.Examples/Cases/MakeBucket.cs | 2 ++ Minio.Examples/Cases/MakeBucketWithLock.cs | 2 ++ Minio.Examples/Cases/PresignedGetObject.cs | 2 ++ Minio.Examples/Cases/PresignedPostPolicy.cs | 1 + Minio.Examples/Cases/PresignedPutObject.cs | 2 ++ Minio.Examples/Cases/PutObjectWithTags.cs | 2 ++ Minio.Examples/Cases/RemoveAllBucketNotifications.cs | 2 ++ Minio.Examples/Cases/RemoveBucketEncryption.cs | 2 ++ Minio.Examples/Cases/RemoveBucketLifecycle.cs | 2 ++ Minio.Examples/Cases/RemoveBucketReplication.cs | 2 ++ Minio.Examples/Cases/RemoveBucketTags.cs | 2 ++ Minio.Examples/Cases/RemoveObject.cs | 2 ++ Minio.Examples/Cases/RemoveObjectLockConfiguration.cs | 2 ++ Minio.Examples/Cases/RemoveObjectTags.cs | 2 ++ Minio.Examples/Cases/RetryPolicyObject.cs | 2 ++ Minio.Examples/Cases/SelectObjectContent.cs | 2 ++ Minio.Examples/Cases/SetBucketEncryption.cs | 2 ++ Minio.Examples/Cases/SetBucketLifecycle.cs | 2 ++ Minio.Examples/Cases/SetBucketNotification.cs | 2 ++ Minio.Examples/Cases/SetBucketPolicy.cs | 2 ++ Minio.Examples/Cases/SetBucketReplication.cs | 2 ++ Minio.Examples/Cases/SetBucketTags.cs | 2 ++ Minio.Examples/Cases/SetLegalHold.cs | 2 ++ Minio.Examples/Cases/SetObjectLockConfiguration.cs | 2 ++ Minio.Examples/Cases/SetObjectRetention.cs | 2 ++ Minio.Examples/Cases/SetObjectTags.cs | 2 ++ Minio.Examples/Cases/StatObject.cs | 2 ++ Minio.Examples/Cases/StatObjectQuery.cs | 2 ++ Minio.Functional.Tests/FunctionalTest.cs | 4 ++-- Minio/DataModel/Notification/BucketNotification.cs | 1 + Minio/DataModel/Notification/LambdaConfig.cs | 2 ++ Minio/DataModel/Notification/QueueConfig.cs | 2 ++ Minio/DataModel/Notification/TopicConfig.cs | 2 ++ Minio/DataModel/ObjectOperationsResponse.cs | 6 ++++++ Minio/DataModel/ObjectStat.cs | 1 + Minio/DataModel/Replication/AndOperator.cs | 2 ++ Minio/DataModel/VersioningConfiguration.cs | 2 ++ Minio/DefaultRequestLogger.cs | 4 ++++ Minio/Helper/Utils.cs | 4 ++++ Minio/V4Authenticator.cs | 10 +++------- 49 files changed, 104 insertions(+), 9 deletions(-) diff --git a/Minio.Examples/Cases/ClearObjectRetention.cs b/Minio.Examples/Cases/ClearObjectRetention.cs index 00d19322b..8c9b0b49c 100644 --- a/Minio.Examples/Cases/ClearObjectRetention.cs +++ b/Minio.Examples/Cases/ClearObjectRetention.cs @@ -24,6 +24,8 @@ public static async Task Run(IMinioClient minio, string objectName = "my-object-name", string versionId = null) { + if (minio is null) throw new ArgumentNullException(nameof(minio)); + try { Console.WriteLine("Running example for API: ClearObjectRetention"); diff --git a/Minio.Examples/Cases/CustomRequestLogger.cs b/Minio.Examples/Cases/CustomRequestLogger.cs index b476d1bd6..917a2bd39 100644 --- a/Minio.Examples/Cases/CustomRequestLogger.cs +++ b/Minio.Examples/Cases/CustomRequestLogger.cs @@ -24,6 +24,8 @@ public static class CustomRequestLogger // Check if a bucket exists public static async Task Run(IMinioClient minio) { + if (minio is null) throw new ArgumentNullException(nameof(minio)); + try { Console.WriteLine("Running example for: set custom request logger"); diff --git a/Minio.Examples/Cases/GetBucketEncryption.cs b/Minio.Examples/Cases/GetBucketEncryption.cs index fd16a0ce3..7993ebea6 100644 --- a/Minio.Examples/Cases/GetBucketEncryption.cs +++ b/Minio.Examples/Cases/GetBucketEncryption.cs @@ -22,6 +22,8 @@ public static class GetBucketEncryption public static async Task Run(IMinioClient minio, string bucketName = "my-bucket-name") { + if (minio is null) throw new ArgumentNullException(nameof(minio)); + try { Console.WriteLine("Running example for API: GetBucketEncryptionAsync"); diff --git a/Minio.Examples/Cases/GetBucketLifecycle.cs b/Minio.Examples/Cases/GetBucketLifecycle.cs index 5eb339ada..1497eafd7 100644 --- a/Minio.Examples/Cases/GetBucketLifecycle.cs +++ b/Minio.Examples/Cases/GetBucketLifecycle.cs @@ -22,6 +22,8 @@ public static class GetBucketLifecycle public static async Task Run(IMinioClient minio, string bucketName = "my-bucket-name") { + if (minio is null) throw new ArgumentNullException(nameof(minio)); + try { Console.WriteLine("Running example for API: GetBucketLifecycle"); diff --git a/Minio.Examples/Cases/GetBucketReplication.cs b/Minio.Examples/Cases/GetBucketReplication.cs index 4417751a1..9b008e399 100644 --- a/Minio.Examples/Cases/GetBucketReplication.cs +++ b/Minio.Examples/Cases/GetBucketReplication.cs @@ -25,6 +25,8 @@ public static async Task Run(IMinioClient minio, string bucketName = "my-bucket-name", string replicationRuleID = "my-replication-rule-ID") { + if (minio is null) throw new ArgumentNullException(nameof(minio)); + try { Console.WriteLine("Running example for API: GetBucketReplicationConfiguration"); diff --git a/Minio.Examples/Cases/GetBucketTags.cs b/Minio.Examples/Cases/GetBucketTags.cs index 3ae91b928..353ccfa96 100644 --- a/Minio.Examples/Cases/GetBucketTags.cs +++ b/Minio.Examples/Cases/GetBucketTags.cs @@ -22,6 +22,8 @@ public static class GetBucketTags public static async Task Run(IMinioClient minio, string bucketName = "my-bucket-name") { + if (minio is null) throw new ArgumentNullException(nameof(minio)); + try { Console.WriteLine("Running example for API: GetBucketTags"); diff --git a/Minio.Examples/Cases/GetObjectLockConfiguration.cs b/Minio.Examples/Cases/GetObjectLockConfiguration.cs index 6c415938b..a230fc0bb 100644 --- a/Minio.Examples/Cases/GetObjectLockConfiguration.cs +++ b/Minio.Examples/Cases/GetObjectLockConfiguration.cs @@ -24,6 +24,8 @@ public static class GetObjectLockConfiguration public static async Task Run(IMinioClient minio, string bucketName = "my-bucket-name") { + if (minio is null) throw new ArgumentNullException(nameof(minio)); + try { Console.WriteLine("Running example for API: GetObjectLockConfiguration"); diff --git a/Minio.Examples/Cases/GetObjectRetention.cs b/Minio.Examples/Cases/GetObjectRetention.cs index 99d247d34..036c21d62 100644 --- a/Minio.Examples/Cases/GetObjectRetention.cs +++ b/Minio.Examples/Cases/GetObjectRetention.cs @@ -26,6 +26,8 @@ public static async Task Run(IMinioClient minio, string objectName = "my-object-name", string versionId = null) { + if (minio is null) throw new ArgumentNullException(nameof(minio)); + try { Console.WriteLine("Running example for API: GetObjectRetentionAsync"); diff --git a/Minio.Examples/Cases/GetObjectTags.cs b/Minio.Examples/Cases/GetObjectTags.cs index cab77481e..f5464f5c0 100644 --- a/Minio.Examples/Cases/GetObjectTags.cs +++ b/Minio.Examples/Cases/GetObjectTags.cs @@ -24,6 +24,8 @@ public static async Task Run(IMinioClient minio, string objectName = "my-object-name", string versionId = null) { + if (minio is null) throw new ArgumentNullException(nameof(minio)); + try { Console.WriteLine("Running example for API: GetObjectTags"); diff --git a/Minio.Examples/Cases/MakeBucket.cs b/Minio.Examples/Cases/MakeBucket.cs index 75abe0976..396e22079 100644 --- a/Minio.Examples/Cases/MakeBucket.cs +++ b/Minio.Examples/Cases/MakeBucket.cs @@ -22,6 +22,8 @@ public static class MakeBucket public static async Task Run(IMinioClient minio, string bucketName = "my-bucket-name", string loc = "us-east-1") { + if (minio is null) throw new ArgumentNullException(nameof(minio)); + try { Console.WriteLine("Running example for API: MakeBucketAsync"); diff --git a/Minio.Examples/Cases/MakeBucketWithLock.cs b/Minio.Examples/Cases/MakeBucketWithLock.cs index 96d63d9b7..3c8c61f00 100644 --- a/Minio.Examples/Cases/MakeBucketWithLock.cs +++ b/Minio.Examples/Cases/MakeBucketWithLock.cs @@ -22,6 +22,8 @@ public static class MakeBucketWithLock public static async Task Run(IMinioClient minio, string bucketName = "my-bucket-name", string loc = "us-east-1") { + if (minio is null) throw new ArgumentNullException(nameof(minio)); + try { Console.WriteLine("Running example for API: MakeBucketAsync"); diff --git a/Minio.Examples/Cases/PresignedGetObject.cs b/Minio.Examples/Cases/PresignedGetObject.cs index 114c7ebfb..888c2a95a 100644 --- a/Minio.Examples/Cases/PresignedGetObject.cs +++ b/Minio.Examples/Cases/PresignedGetObject.cs @@ -22,6 +22,8 @@ public static async Task Run(IMinioClient client, string bucketName = "my-bucket-name", string objectName = "my-object-name") { + if (client is null) throw new ArgumentNullException(nameof(client)); + var reqParams = new Dictionary { { "response-content-type", "application/json" } }; var args = new PresignedGetObjectArgs() .WithBucket(bucketName) diff --git a/Minio.Examples/Cases/PresignedPostPolicy.cs b/Minio.Examples/Cases/PresignedPostPolicy.cs index bd7d29ad0..3c6afb2d0 100644 --- a/Minio.Examples/Cases/PresignedPostPolicy.cs +++ b/Minio.Examples/Cases/PresignedPostPolicy.cs @@ -28,6 +28,7 @@ public static async Task Run(IMinioClient client, string bucketName = "my-bucketname", string objectName = "my-objectname") { + if (client is null) throw new ArgumentNullException(nameof(client)); // default value for expiration is 2 minutes var expiration = DateTime.UtcNow.AddMinutes(2); diff --git a/Minio.Examples/Cases/PresignedPutObject.cs b/Minio.Examples/Cases/PresignedPutObject.cs index b4952fbfe..2dd201f10 100644 --- a/Minio.Examples/Cases/PresignedPutObject.cs +++ b/Minio.Examples/Cases/PresignedPutObject.cs @@ -22,6 +22,8 @@ public static async Task Run(IMinioClient client, string bucketName = "my-bucket-name", string objectName = "my-object-name") { + if (client is null) throw new ArgumentNullException(nameof(client)); + try { var args = new PresignedPutObjectArgs() diff --git a/Minio.Examples/Cases/PutObjectWithTags.cs b/Minio.Examples/Cases/PutObjectWithTags.cs index 5f0c9dc43..4e97a9d80 100644 --- a/Minio.Examples/Cases/PutObjectWithTags.cs +++ b/Minio.Examples/Cases/PutObjectWithTags.cs @@ -28,6 +28,8 @@ public static async Task Run(IMinioClient minio, string objectName = "my-object-name", string fileName = "location-of-file") { + if (minio is null) throw new ArgumentNullException(nameof(minio)); + try { Console.WriteLine("Running example for API: PutObjectAsync with Tags"); diff --git a/Minio.Examples/Cases/RemoveAllBucketNotifications.cs b/Minio.Examples/Cases/RemoveAllBucketNotifications.cs index 7aaf5a107..71d12f3ec 100644 --- a/Minio.Examples/Cases/RemoveAllBucketNotifications.cs +++ b/Minio.Examples/Cases/RemoveAllBucketNotifications.cs @@ -22,6 +22,8 @@ internal static class RemoveAllBucketNotifications public static async Task Run(IMinioClient minio, string bucketName = "my-bucket-name") { + if (minio is null) throw new ArgumentNullException(nameof(minio)); + try { Console.WriteLine("Running example for API: RemoveAllBucketNotificationAsync"); diff --git a/Minio.Examples/Cases/RemoveBucketEncryption.cs b/Minio.Examples/Cases/RemoveBucketEncryption.cs index cd91eeba9..1b2041019 100644 --- a/Minio.Examples/Cases/RemoveBucketEncryption.cs +++ b/Minio.Examples/Cases/RemoveBucketEncryption.cs @@ -22,6 +22,8 @@ public static class RemoveBucketEncryption public static async Task Run(IMinioClient minio, string bucketName = "my-bucket-name") { + if (minio is null) throw new ArgumentNullException(nameof(minio)); + try { Console.WriteLine("Running example for API: RemoveBucketEncryptionAsync"); diff --git a/Minio.Examples/Cases/RemoveBucketLifecycle.cs b/Minio.Examples/Cases/RemoveBucketLifecycle.cs index dc83d87a2..61f308f3b 100644 --- a/Minio.Examples/Cases/RemoveBucketLifecycle.cs +++ b/Minio.Examples/Cases/RemoveBucketLifecycle.cs @@ -22,6 +22,8 @@ public static class RemoveBucketLifecycle public static async Task Run(IMinioClient minio, string bucketName = "my-bucket-name") { + if (minio is null) throw new ArgumentNullException(nameof(minio)); + try { Console.WriteLine("Running example for API: RemoveBucketLifecycle"); diff --git a/Minio.Examples/Cases/RemoveBucketReplication.cs b/Minio.Examples/Cases/RemoveBucketReplication.cs index 32e3e27f6..0501edebc 100644 --- a/Minio.Examples/Cases/RemoveBucketReplication.cs +++ b/Minio.Examples/Cases/RemoveBucketReplication.cs @@ -22,6 +22,8 @@ public static class RemoveBucketReplication public static async Task Run(IMinioClient minio, string bucketName = "my-bucket-name") { + if (minio is null) throw new ArgumentNullException(nameof(minio)); + try { Console.WriteLine("Running example for API: RemoveBucketReplication"); diff --git a/Minio.Examples/Cases/RemoveBucketTags.cs b/Minio.Examples/Cases/RemoveBucketTags.cs index 63ccb097c..b97137e27 100644 --- a/Minio.Examples/Cases/RemoveBucketTags.cs +++ b/Minio.Examples/Cases/RemoveBucketTags.cs @@ -22,6 +22,8 @@ public static class RemoveBucketTags public static async Task Run(IMinioClient minio, string bucketName = "my-bucket-name") { + if (minio is null) throw new ArgumentNullException(nameof(minio)); + try { Console.WriteLine("Running example for API: RemoveBucketTags"); diff --git a/Minio.Examples/Cases/RemoveObject.cs b/Minio.Examples/Cases/RemoveObject.cs index 8f2dcf79d..f916398f2 100644 --- a/Minio.Examples/Cases/RemoveObject.cs +++ b/Minio.Examples/Cases/RemoveObject.cs @@ -24,6 +24,8 @@ public static async Task Run(IMinioClient minio, string objectName = "my-object-name", string versionId = null) { + if (minio is null) throw new ArgumentNullException(nameof(minio)); + try { var args = new RemoveObjectArgs() diff --git a/Minio.Examples/Cases/RemoveObjectLockConfiguration.cs b/Minio.Examples/Cases/RemoveObjectLockConfiguration.cs index 1795e5fba..1cb072e83 100644 --- a/Minio.Examples/Cases/RemoveObjectLockConfiguration.cs +++ b/Minio.Examples/Cases/RemoveObjectLockConfiguration.cs @@ -22,6 +22,8 @@ public static class RemoveObjectLockConfiguration public static async Task Run(IMinioClient minio, string bucketName = "my-bucket-name") { + if (minio is null) throw new ArgumentNullException(nameof(minio)); + try { Console.WriteLine("Running example for API: RemoveObjectLockConfiguration"); diff --git a/Minio.Examples/Cases/RemoveObjectTags.cs b/Minio.Examples/Cases/RemoveObjectTags.cs index a7999fe54..d630e43c5 100644 --- a/Minio.Examples/Cases/RemoveObjectTags.cs +++ b/Minio.Examples/Cases/RemoveObjectTags.cs @@ -24,6 +24,8 @@ public static async Task Run(IMinioClient minio, string objectName = "my-object-name", string versionId = null) { + if (minio is null) throw new ArgumentNullException(nameof(minio)); + try { Console.WriteLine("Running example for API: RemoveObjectTags"); diff --git a/Minio.Examples/Cases/RetryPolicyObject.cs b/Minio.Examples/Cases/RetryPolicyObject.cs index 511d4c343..34c627e93 100644 --- a/Minio.Examples/Cases/RetryPolicyObject.cs +++ b/Minio.Examples/Cases/RetryPolicyObject.cs @@ -82,6 +82,8 @@ public static async Task Run(MinioClient minio, string bucketName = "my-bucket-name", string bucketObject = "my-object-name") { + if (minio is null) throw new ArgumentNullException(nameof(minio)); + try { var customPolicy = RetryPolicyHelper diff --git a/Minio.Examples/Cases/SelectObjectContent.cs b/Minio.Examples/Cases/SelectObjectContent.cs index 128a77c8e..17f8b8020 100644 --- a/Minio.Examples/Cases/SelectObjectContent.cs +++ b/Minio.Examples/Cases/SelectObjectContent.cs @@ -28,6 +28,8 @@ public static async Task Run(IMinioClient minio, string objectName = "my-object-name", string fileName = "my-file-name") { + if (minio is null) throw new ArgumentNullException(nameof(minio)); + var newObjectName = "new" + objectName; try { diff --git a/Minio.Examples/Cases/SetBucketEncryption.cs b/Minio.Examples/Cases/SetBucketEncryption.cs index d04c6dad1..552b8723e 100644 --- a/Minio.Examples/Cases/SetBucketEncryption.cs +++ b/Minio.Examples/Cases/SetBucketEncryption.cs @@ -23,6 +23,8 @@ public static async Task Run(IMinioClient minio, string bucketName = "my-bucket-name", ServerSideEncryptionConfiguration config = null) { + if (minio is null) throw new ArgumentNullException(nameof(minio)); + try { Console.WriteLine("Running example for API: SetBucketEncryptionAsync"); diff --git a/Minio.Examples/Cases/SetBucketLifecycle.cs b/Minio.Examples/Cases/SetBucketLifecycle.cs index e82fd53b4..fae0eb447 100644 --- a/Minio.Examples/Cases/SetBucketLifecycle.cs +++ b/Minio.Examples/Cases/SetBucketLifecycle.cs @@ -25,6 +25,8 @@ public static async Task Run(IMinioClient minio, string bucketName = "my-bucket-name", LifecycleConfiguration lfc = null) { + if (minio is null) throw new ArgumentNullException(nameof(minio)); + try { Console.WriteLine("Running example for API: SetBucketLifecycle"); diff --git a/Minio.Examples/Cases/SetBucketNotification.cs b/Minio.Examples/Cases/SetBucketNotification.cs index 10813f8c4..3d0235ff0 100644 --- a/Minio.Examples/Cases/SetBucketNotification.cs +++ b/Minio.Examples/Cases/SetBucketNotification.cs @@ -25,6 +25,8 @@ internal static class SetBucketNotification public static async Task Run(IMinioClient minio, string bucketName = "my-bucket-name") { + if (minio is null) throw new ArgumentNullException(nameof(minio)); + try { Console.WriteLine("Running example for API: SetBucketNotificationAsync"); diff --git a/Minio.Examples/Cases/SetBucketPolicy.cs b/Minio.Examples/Cases/SetBucketPolicy.cs index f48aa5fc3..098982a14 100644 --- a/Minio.Examples/Cases/SetBucketPolicy.cs +++ b/Minio.Examples/Cases/SetBucketPolicy.cs @@ -22,6 +22,8 @@ internal static class SetBucketPolicy public static async Task Run(IMinioClient minio, string bucketName = "my-bucket-name") { + if (minio is null) throw new ArgumentNullException(nameof(minio)); + try { Console.WriteLine("Running example for API: SetPolicyAsync"); diff --git a/Minio.Examples/Cases/SetBucketReplication.cs b/Minio.Examples/Cases/SetBucketReplication.cs index d29ae9346..e09a628a3 100644 --- a/Minio.Examples/Cases/SetBucketReplication.cs +++ b/Minio.Examples/Cases/SetBucketReplication.cs @@ -53,6 +53,8 @@ public static async Task Run(IMinioClient minio, string destBucketName = "dest-bucket-name", string replicationRuleID = "my-replication-ID") { + if (minio is null) throw new ArgumentNullException(nameof(minio)); + var setArgs = new SetVersioningArgs() .WithBucket(bucketName) .WithVersioningEnabled(); diff --git a/Minio.Examples/Cases/SetBucketTags.cs b/Minio.Examples/Cases/SetBucketTags.cs index 810b5a380..a6f827449 100644 --- a/Minio.Examples/Cases/SetBucketTags.cs +++ b/Minio.Examples/Cases/SetBucketTags.cs @@ -25,6 +25,8 @@ public static async Task Run(IMinioClient minio, string bucketName = "my-bucket-name", IDictionary tags = null) { + if (minio is null) throw new ArgumentNullException(nameof(minio)); + try { Console.WriteLine("Running example for API: SetBucketTags"); diff --git a/Minio.Examples/Cases/SetLegalHold.cs b/Minio.Examples/Cases/SetLegalHold.cs index c0a1b328f..c539a8ff2 100644 --- a/Minio.Examples/Cases/SetLegalHold.cs +++ b/Minio.Examples/Cases/SetLegalHold.cs @@ -24,6 +24,8 @@ public static async Task Run(IMinioClient minio, string objectName = "my-object-name", string versionId = null) { + if (minio is null) throw new ArgumentNullException(nameof(minio)); + try { Console.WriteLine("Running example for API: SetLegalHold, enable legal hold"); diff --git a/Minio.Examples/Cases/SetObjectLockConfiguration.cs b/Minio.Examples/Cases/SetObjectLockConfiguration.cs index 2586c8eec..6c9b25f61 100644 --- a/Minio.Examples/Cases/SetObjectLockConfiguration.cs +++ b/Minio.Examples/Cases/SetObjectLockConfiguration.cs @@ -25,6 +25,8 @@ public static async Task Run(IMinioClient minio, string bucketName = "my-bucket-name", ObjectLockConfiguration config = null) { + if (minio is null) throw new ArgumentNullException(nameof(minio)); + try { Console.WriteLine("Running example for API: SetObjectLockConfiguration"); diff --git a/Minio.Examples/Cases/SetObjectRetention.cs b/Minio.Examples/Cases/SetObjectRetention.cs index 3d768d7de..2f2643626 100644 --- a/Minio.Examples/Cases/SetObjectRetention.cs +++ b/Minio.Examples/Cases/SetObjectRetention.cs @@ -28,6 +28,8 @@ public static async Task Run(IMinioClient minio, RetentionMode mode = RetentionMode.GOVERNANCE, DateTime retentionValidDate = default) { + if (minio is null) throw new ArgumentNullException(nameof(minio)); + try { if (retentionValidDate.Equals(default)) diff --git a/Minio.Examples/Cases/SetObjectTags.cs b/Minio.Examples/Cases/SetObjectTags.cs index c52c1b231..b8e137135 100644 --- a/Minio.Examples/Cases/SetObjectTags.cs +++ b/Minio.Examples/Cases/SetObjectTags.cs @@ -27,6 +27,8 @@ public static async Task Run(IMinioClient minio, IDictionary tags = null, string versionId = null) { + if (minio is null) throw new ArgumentNullException(nameof(minio)); + try { Console.WriteLine("Running example for API: SetObjectTags"); diff --git a/Minio.Examples/Cases/StatObject.cs b/Minio.Examples/Cases/StatObject.cs index 3c9f03ffb..bf2d83f87 100644 --- a/Minio.Examples/Cases/StatObject.cs +++ b/Minio.Examples/Cases/StatObject.cs @@ -37,6 +37,8 @@ public static async Task Run(IMinioClient minio, string bucketObject = "my-object-name", string versionID = null) { + if (minio is null) throw new ArgumentNullException(nameof(minio)); + try { Console.WriteLine("Running example for API: StatObjectAsync"); diff --git a/Minio.Examples/Cases/StatObjectQuery.cs b/Minio.Examples/Cases/StatObjectQuery.cs index f0700b3f9..da6f2f99b 100644 --- a/Minio.Examples/Cases/StatObjectQuery.cs +++ b/Minio.Examples/Cases/StatObjectQuery.cs @@ -39,6 +39,8 @@ public static async Task Run(IMinioClient minio, string matchEtag = null, DateTime modifiedSince = default) { + if (minio is null) throw new ArgumentNullException(nameof(minio)); + try { Console.WriteLine("Running example for API: StatObjectAsync [with ObjectQuery]"); diff --git a/Minio.Functional.Tests/FunctionalTest.cs b/Minio.Functional.Tests/FunctionalTest.cs index 13fec61e4..7c0b9c89d 100644 --- a/Minio.Functional.Tests/FunctionalTest.cs +++ b/Minio.Functional.Tests/FunctionalTest.cs @@ -572,7 +572,7 @@ internal static async Task TearDown(MinioClient minio, string bucketName) versioningConfig = await minio.GetVersioningAsync(new GetVersioningArgs() .WithBucket(bucketName)).ConfigureAwait(false); if (versioningConfig is not null && (versioningConfig.Status.Contains("Enabled") || - versioningConfig.Status.Contains("Suspended"))) + versioningConfig.Status.Contains("Suspended"))) getVersions = true; lockConfig = await minio.GetObjectLockConfigurationAsync(lockConfigurationArgs).ConfigureAwait(false); @@ -4867,7 +4867,7 @@ internal static async Task GetObject_AsyncCallback_Test1(MinioClient minio) .WithBucket(bucketName) .WithObject(objectName) .WithCallbackStream(async (stream, cancellationToken) => - await callbackAsync(stream, default).ConfigureAwait(false)); + await callbackAsync(stream, cancellationToken).ConfigureAwait(false)); await minio.GetObjectAsync(getObjectArgs).ConfigureAwait(false); var writtenInfo = new FileInfo(destFileName); diff --git a/Minio/DataModel/Notification/BucketNotification.cs b/Minio/DataModel/Notification/BucketNotification.cs index 7c44b0d5b..f74d851a6 100644 --- a/Minio/DataModel/Notification/BucketNotification.cs +++ b/Minio/DataModel/Notification/BucketNotification.cs @@ -32,6 +32,7 @@ public class BucketNotification [XmlElement("TopicConfiguration")] public List TopicConfigs; [XmlElement("QueueConfiguration")] public List QueueConfigs; + public BucketNotification() { LambdaConfigs = new List(); diff --git a/Minio/DataModel/Notification/LambdaConfig.cs b/Minio/DataModel/Notification/LambdaConfig.cs index 961952714..c05c01b4d 100644 --- a/Minio/DataModel/Notification/LambdaConfig.cs +++ b/Minio/DataModel/Notification/LambdaConfig.cs @@ -35,6 +35,8 @@ public LambdaConfig(string arn) : base(arn) public LambdaConfig(Arn arn) : base(arn) { + if (arn is null) throw new ArgumentNullException(nameof(arn)); + Lambda = arn.ToString(); } diff --git a/Minio/DataModel/Notification/QueueConfig.cs b/Minio/DataModel/Notification/QueueConfig.cs index 8a989d1be..a7820d9a9 100644 --- a/Minio/DataModel/Notification/QueueConfig.cs +++ b/Minio/DataModel/Notification/QueueConfig.cs @@ -33,6 +33,8 @@ public QueueConfig(string arn) : base(arn) public QueueConfig(Arn arn) : base(arn) { + if (arn is null) throw new ArgumentNullException(nameof(arn)); + Queue = arn.ToString(); } diff --git a/Minio/DataModel/Notification/TopicConfig.cs b/Minio/DataModel/Notification/TopicConfig.cs index 7712e9972..d9eb05efb 100644 --- a/Minio/DataModel/Notification/TopicConfig.cs +++ b/Minio/DataModel/Notification/TopicConfig.cs @@ -35,6 +35,8 @@ public TopicConfig(string arn) : base(arn) public TopicConfig(Arn arn) : base(arn) { + if (arn is null) throw new ArgumentNullException(nameof(arn)); + Topic = arn.ToString(); } diff --git a/Minio/DataModel/ObjectOperationsResponse.cs b/Minio/DataModel/ObjectOperationsResponse.cs index a8c719af5..38ce7cb32 100644 --- a/Minio/DataModel/ObjectOperationsResponse.cs +++ b/Minio/DataModel/ObjectOperationsResponse.cs @@ -91,6 +91,10 @@ public class PresignedPostPolicyResponse { public PresignedPostPolicyResponse(PresignedPostPolicyArgs args, Uri URI) { + if (args is null) throw new ArgumentNullException(nameof(args)); + + if (URI is null) throw new ArgumentNullException(nameof(URI)); + URIPolicyTuple = Tuple.Create(URI.AbsolutePath, args.Policy.FormData); } @@ -202,6 +206,8 @@ public PutObjectResponse(HttpStatusCode statusCode, string responseContent, IDictionary responseHeaders, long size, string name) : base(statusCode, responseContent) { + if (responseHeaders is null) throw new ArgumentNullException(nameof(responseHeaders)); + foreach (var parameter in responseHeaders) if (parameter.Key.Equals("ETag", StringComparison.OrdinalIgnoreCase)) { diff --git a/Minio/DataModel/ObjectStat.cs b/Minio/DataModel/ObjectStat.cs index f7603209b..2c6c89b02 100644 --- a/Minio/DataModel/ObjectStat.cs +++ b/Minio/DataModel/ObjectStat.cs @@ -49,6 +49,7 @@ public static ObjectStat FromResponseHeaders(string objectName, IDictionary tag) public AndOperator(string prefix, IDictionary tags) { + if (tags is null) throw new ArgumentNullException(nameof(tags)); + Prefix = prefix; foreach (var item in tags) Tags.Add(new Tag(item.Key, item.Value)); } diff --git a/Minio/DataModel/VersioningConfiguration.cs b/Minio/DataModel/VersioningConfiguration.cs index 3dfc91b20..74b328536 100644 --- a/Minio/DataModel/VersioningConfiguration.cs +++ b/Minio/DataModel/VersioningConfiguration.cs @@ -38,6 +38,8 @@ public VersioningConfiguration(bool enableVersioning = true) public VersioningConfiguration(VersioningConfiguration vc) { + if (vc is null) throw new ArgumentNullException(nameof(vc)); + Status = vc.Status; MfaDelete = vc.MfaDelete; } diff --git a/Minio/DefaultRequestLogger.cs b/Minio/DefaultRequestLogger.cs index c9c5d8934..1ef1a4e0b 100644 --- a/Minio/DefaultRequestLogger.cs +++ b/Minio/DefaultRequestLogger.cs @@ -23,6 +23,10 @@ public sealed class DefaultRequestLogger : IRequestLogger { public void LogRequest(RequestToLog requestToLog, ResponseToLog responseToLog, double durationMs) { + if (requestToLog is null) throw new ArgumentNullException(nameof(requestToLog)); + + if (responseToLog is null) throw new ArgumentNullException(nameof(responseToLog)); + var sb = new StringBuilder("Request completed in "); sb.Append(durationMs); diff --git a/Minio/Helper/Utils.cs b/Minio/Helper/Utils.cs index 19ed032d5..805e6fd73 100644 --- a/Minio/Helper/Utils.cs +++ b/Minio/Helper/Utils.cs @@ -199,6 +199,8 @@ internal static bool IsSupersetOf(IList l1, IList l2) public static bool CaseInsensitiveContains(string text, string value, StringComparison stringComparison = StringComparison.CurrentCultureIgnoreCase) { + if (string.IsNullOrEmpty(text)) + throw new ArgumentException($"'{nameof(text)}' cannot be null or empty.", nameof(text)); #if NETSTANDARD return text.IndexOf(value, stringComparison) >= 0; #else @@ -811,6 +813,8 @@ private static IDictionary AddContentTypeMappings() public static string MarshalXML(object obj, string nmspc) { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + XmlWriter xw = null; var str = string.Empty; diff --git a/Minio/V4Authenticator.cs b/Minio/V4Authenticator.cs index 1e9ef367c..6e66008cc 100644 --- a/Minio/V4Authenticator.cs +++ b/Minio/V4Authenticator.cs @@ -373,13 +373,9 @@ internal string GetPresignCanonicalRequest(HttpMethod requestMethod, Uri uri, private static string GetCanonicalHost(Uri url) { - string canonicalHost; if (url.Port > 0 && url.Port != 80 && url.Port != 443) - canonicalHost = $"{url.Host}:{url.Port}"; - else - canonicalHost = url.Host; - - return canonicalHost; + return $"{url.Host}:{url.Port}"; + return url.Host; } /// @@ -417,7 +413,7 @@ private string GetCanonicalRequest(HttpRequestMessageBuilder requestBuilder, } var isFormData = false; - if (requestBuilder.Request.Content is not null && requestBuilder.Request.Content.Headers?.ContentType is not null) + if (requestBuilder.Request.Content?.Headers?.ContentType is not null) isFormData = string.Equals(requestBuilder.Request.Content.Headers.ContentType.ToString(), "application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase); From a9dcae14b08410fb1e69b2d033af907edb848eda Mon Sep 17 00:00:00 2001 From: Martijn van Dijk Date: Tue, 25 Apr 2023 15:33:53 +0200 Subject: [PATCH 09/13] New name --- Minio/V4Authenticator.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Minio/V4Authenticator.cs b/Minio/V4Authenticator.cs index 6e66008cc..f549e7966 100644 --- a/Minio/V4Authenticator.cs +++ b/Minio/V4Authenticator.cs @@ -110,13 +110,13 @@ public string Authenticate(HttpRequestMessageBuilder requestBuilder, bool isSts ReadOnlySpan canonicalRequestBytes = Encoding.UTF8.GetBytes(canonicalRequest); var hash = ComputeSha256(canonicalRequestBytes); var canonicalRequestHash = BytesToHex(hash); - var region = GetRegion(requestUri.Host); - var stringToSign = GetStringToSign(region, signingDate, canonicalRequestHash, isSts); - var signingKey = GenerateSigningKey(region, signingDate, isSts); + var endpointRegion = GetRegion(requestUri.Host); + var stringToSign = GetStringToSign(endpointRegion, signingDate, canonicalRequestHash, isSts); + var signingKey = GenerateSigningKey(endpointRegion, signingDate, isSts); ReadOnlySpan stringToSignBytes = Encoding.UTF8.GetBytes(stringToSign); var signatureBytes = SignHmac(signingKey, stringToSignBytes); var signature = BytesToHex(signatureBytes); - var authorization = GetAuthorizationHeader(signedHeaders, signature, signingDate, region, isSts); + var authorization = GetAuthorizationHeader(signedHeaders, signature, signingDate, endpointRegion, isSts); return authorization; } From a6fd42f641550459d9eb53eb877ceb34f5606121 Mon Sep 17 00:00:00 2001 From: Martijn van Dijk Date: Tue, 25 Apr 2023 16:31:37 +0200 Subject: [PATCH 10/13] Disable analyzer again --- Directory.Build.props | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index e093dc527..82c44c093 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -63,7 +63,7 @@ - + \ No newline at end of file From 451f972f74d31ebe02b3736049cfea3a7c3d2842 Mon Sep 17 00:00:00 2001 From: Martijn van Dijk Date: Wed, 26 Apr 2023 11:49:39 +0200 Subject: [PATCH 11/13] Move more to extensions --- Minio.Examples/Cases/SelectObjectContent.cs | 3 +- Minio/MinioClient.cs | 115 ++------------------ Minio/MinioClientExtensions.cs | 114 ++++++++++++++++++- 3 files changed, 125 insertions(+), 107 deletions(-) diff --git a/Minio.Examples/Cases/SelectObjectContent.cs b/Minio.Examples/Cases/SelectObjectContent.cs index 17f8b8020..d98372756 100644 --- a/Minio.Examples/Cases/SelectObjectContent.cs +++ b/Minio.Examples/Cases/SelectObjectContent.cs @@ -79,7 +79,8 @@ public static async Task Run(IMinioClient minio, .WithInputSerialization(inputSerialization) .WithOutputSerialization(outputSerialization); var resp = await minio.SelectObjectContentAsync(args).ConfigureAwait(false); - await resp.Payload.CopyToAsync(Console.OpenStandardOutput()).ConfigureAwait(false); + using var standardOutput = Console.OpenStandardOutput(); + await resp.Payload.CopyToAsync(standardOutput).ConfigureAwait(false); Console.WriteLine("Bytes scanned:" + resp.Stats.BytesScanned); Console.WriteLine("Bytes returned:" + resp.Stats.BytesReturned); Console.WriteLine("Bytes processed:" + resp.Stats.BytesProcessed); diff --git a/Minio/MinioClient.cs b/Minio/MinioClient.cs index aab3b62d0..172dd54aa 100644 --- a/Minio/MinioClient.cs +++ b/Minio/MinioClient.cs @@ -53,7 +53,7 @@ public partial class MinioClient : IMinioClient private string CustomUserAgent = string.Empty; private bool disposedValue; - private bool disposeHttpClient = true; + internal bool DisposeHttpClient = true; private IRequestLogger logger; @@ -63,10 +63,10 @@ public partial class MinioClient : IMinioClient // Cache holding bucket to region mapping for buckets seen so far. internal BucketRegionCache regionCache; - private int requestTimeout; + internal int RequestTimeout; // Handler for task retry policy - internal RetryPolicyHandlingDelegate retryPolicyHandler; + internal RetryPolicyHandlingDelegate RetryPolicyHandler; // Enables HTTP tracing if set to true private bool trace; @@ -100,7 +100,7 @@ public MinioClient() internal HttpClient HttpClient { get; set; } - internal IWebProxy Proxy { get; private set; } + internal IWebProxy Proxy { get; set; } private static string SystemUserAgent { @@ -129,8 +129,7 @@ private static string SystemUserAgent /// public async Task WrapperGetAsync(string url) { - var response = await HttpClient.GetAsync(url).ConfigureAwait(false); - return response; + return await HttpClient.GetAsync(url).ConfigureAwait(false); } /// @@ -377,100 +376,6 @@ internal async Task CreateRequest( return messageBuilder; } - /// - /// Connects to Cloud Storage with HTTPS if this method is invoked on client object - /// - /// - public MinioClient WithSSL(bool secure = true) - { - if (secure) - { - Secure = true; - if (string.IsNullOrEmpty(BaseUrl)) - return this; - var secureUrl = RequestUtil.MakeTargetURL(BaseUrl, Secure); - } - - return this; - } - - /// - /// Uses webproxy for all requests if this method is invoked on client object. - /// - /// Information on the proxy server in the setup. - /// - public MinioClient WithProxy(IWebProxy proxy) - { - Proxy = proxy; - return this; - } - - /// - /// Uses the set timeout for all requests if this method is invoked on client object - /// - /// Timeout in milliseconds. - /// - public MinioClient WithTimeout(int timeout) - { - requestTimeout = timeout; - return this; - } - - /// - /// Allows to add retry policy handler - /// - /// Delegate that will wrap execution of http client requests. - /// - public MinioClient WithRetryPolicy(RetryPolicyHandlingDelegate retryPolicyHandler) - { - this.retryPolicyHandler = retryPolicyHandler; - return this; - } - - /// - /// Allows end user to define the Http server and pass it as a parameter - /// - /// Instance of HttpClient - /// Dispose the HttpClient when leaving - /// - public MinioClient WithHttpClient(HttpClient httpClient, bool disposeHttpClient = false) - { - if (httpClient is not null) HttpClient = httpClient; - this.disposeHttpClient = disposeHttpClient; - return this; - } - - /// - /// With provider for credentials and session token if being used - /// - /// - public MinioClient WithCredentialsProvider(ClientProvider provider) - { - Provider = provider; - AccessCredentials credentials; - if (Provider is IAMAWSProvider) - // Empty object, we need the Minio client completely - credentials = new AccessCredentials(); - else - credentials = Provider.GetCredentials(); - - if (credentials is null) - // Unable to fetch credentials. - return this; - - AccessKey = credentials.AccessKey; - SecretKey = credentials.SecretKey; - var isSessionTokenAvailable = !string.IsNullOrEmpty(credentials.SessionToken); - if ((Provider is AWSEnvironmentProvider || - Provider is IAMAWSProvider || - Provider is CertificateIdentityProvider || - (Provider is ChainedProvider chainedProvider && chainedProvider.CurrentProvider is AWSEnvironmentProvider)) - && isSessionTokenAvailable) - SessionToken = credentials.SessionToken; - - return this; - } - /// /// Actual doer that executes the request on the server /// @@ -485,9 +390,9 @@ internal Task ExecuteTaskAsync( bool isSts = false, CancellationToken cancellationToken = default) { - if (requestTimeout > 0) + if (RequestTimeout > 0) { - using var internalTokenSource = new CancellationTokenSource(new TimeSpan(0, 0, 0, 0, requestTimeout)); + using var internalTokenSource = new CancellationTokenSource(new TimeSpan(0, 0, 0, 0, RequestTimeout)); using var timeoutTokenSource = CancellationTokenSource.CreateLinkedTokenSource(internalTokenSource.Token, cancellationToken); cancellationToken = timeoutTokenSource.Token; @@ -807,9 +712,9 @@ private void LogRequest(HttpRequestMessage request, ResponseResult response, dou private Task ExecuteWithRetry( Func> executeRequestCallback) { - return retryPolicyHandler is null + return RetryPolicyHandler is null ? executeRequestCallback() - : retryPolicyHandler(executeRequestCallback); + : RetryPolicyHandler(executeRequestCallback); } protected virtual void Dispose(bool disposing) @@ -817,7 +722,7 @@ protected virtual void Dispose(bool disposing) if (!disposedValue) { if (disposing) - if (disposeHttpClient) + if (DisposeHttpClient) HttpClient?.Dispose(); disposedValue = true; } diff --git a/Minio/MinioClientExtensions.cs b/Minio/MinioClientExtensions.cs index 1a3fd1501..f39be2614 100644 --- a/Minio/MinioClientExtensions.cs +++ b/Minio/MinioClientExtensions.cs @@ -1,4 +1,6 @@ -using Minio.Credentials; +using System.Net; +using Minio.Credentials; +using Minio.DataModel; using Minio.Exceptions; using Minio.Helper; @@ -71,9 +73,119 @@ public static MinioClient WithSessionToken(this MinioClient minioClient, string return minioClient; } + /// + /// Connects to Cloud Storage with HTTPS if this method is invoked on client object + /// + /// + public static MinioClient WithSSL(this MinioClient minioClient, bool secure = true) + { + if (minioClient is null) throw new ArgumentNullException(nameof(minioClient)); + + if (secure) + { + minioClient.Secure = true; + if (string.IsNullOrEmpty(minioClient.BaseUrl)) + return minioClient; + var secureUrl = RequestUtil.MakeTargetURL(minioClient.BaseUrl, minioClient.Secure); + } + + return minioClient; + } + + /// + /// Uses webproxy for all requests if this method is invoked on client object. + /// + /// Information on the proxy server in the setup. + /// + public static MinioClient WithProxy(this MinioClient minioClient, IWebProxy proxy) + { + if (minioClient is null) throw new ArgumentNullException(nameof(minioClient)); + + minioClient.Proxy = proxy; + return minioClient; + } + + /// + /// Uses the set timeout for all requests if this method is invoked on client object + /// + /// Timeout in milliseconds. + /// + public static MinioClient WithTimeout(this MinioClient minioClient, int timeout) + { + if (minioClient is null) throw new ArgumentNullException(nameof(minioClient)); + + minioClient.RequestTimeout = timeout; + return minioClient; + } + + /// + /// Allows to add retry policy handler + /// + /// Delegate that will wrap execution of http client requests. + /// + public static MinioClient WithRetryPolicy(this MinioClient minioClient, + RetryPolicyHandlingDelegate retryPolicyHandler) + { + if (minioClient is null) throw new ArgumentNullException(nameof(minioClient)); + + minioClient.RetryPolicyHandler = retryPolicyHandler; + return minioClient; + } + + /// + /// Allows end user to define the Http server and pass it as a parameter + /// + /// Instance of HttpClient + /// Dispose the HttpClient when leaving + /// + public static MinioClient WithHttpClient(this MinioClient minioClient, HttpClient httpClient, + bool disposeHttpClient = false) + { + if (minioClient is null) throw new ArgumentNullException(nameof(minioClient)); + + if (httpClient is not null) minioClient.HttpClient = httpClient; + minioClient.DisposeHttpClient = disposeHttpClient; + return minioClient; + } + + /// + /// With provider for credentials and session token if being used + /// + /// + public static MinioClient WithCredentialsProvider(this MinioClient minioClient, ClientProvider provider) + { + if (minioClient is null) throw new ArgumentNullException(nameof(minioClient)); + + minioClient.Provider = provider; + AccessCredentials credentials; + if (minioClient.Provider is IAMAWSProvider) + // Empty object, we need the Minio client completely + credentials = new AccessCredentials(); + else + credentials = minioClient.Provider.GetCredentials(); + + if (credentials is null) + // Unable to fetch credentials. + return minioClient; + + minioClient.AccessKey = credentials.AccessKey; + minioClient.SecretKey = credentials.SecretKey; + var isSessionTokenAvailable = !string.IsNullOrEmpty(credentials.SessionToken); + if ((minioClient.Provider is AWSEnvironmentProvider || + minioClient.Provider is IAMAWSProvider || + minioClient.Provider is CertificateIdentityProvider || + (minioClient.Provider is ChainedProvider chainedProvider && + chainedProvider.CurrentProvider is AWSEnvironmentProvider)) + && isSessionTokenAvailable) + minioClient.SessionToken = credentials.SessionToken; + + return minioClient; + } + public static MinioClient Build(this MinioClient minioClient) { if (minioClient is null) throw new ArgumentNullException(nameof(minioClient)); + // Instantiate a region cache minioClient.regionCache = BucketRegionCache.Instance; if (string.IsNullOrEmpty(minioClient.BaseUrl)) throw new MinioException("Endpoint not initialized."); From ea4f2388566fef24c4e1b0b88d1fc8daf0bba157 Mon Sep 17 00:00:00 2001 From: Martijn van Dijk Date: Wed, 26 Apr 2023 11:55:26 +0200 Subject: [PATCH 12/13] Invert checks --- Minio/DataModel/AccessCredentials.cs | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/Minio/DataModel/AccessCredentials.cs b/Minio/DataModel/AccessCredentials.cs index f4035b68a..045a7e468 100644 --- a/Minio/DataModel/AccessCredentials.cs +++ b/Minio/DataModel/AccessCredentials.cs @@ -26,19 +26,24 @@ public class AccessCredentials public AccessCredentials(string accessKey, string secretKey, string sessionToken, DateTime expiration) { - if (string.IsNullOrEmpty(accessKey)) - throw new ArgumentException($"'{nameof(accessKey)}' cannot be null or empty.", nameof(accessKey)); + if (!string.IsNullOrEmpty(accessKey) || !string.IsNullOrEmpty(secretKey) || !string.IsNullOrEmpty(sessionToken)) + { + AccessKey = accessKey; + SecretKey = secretKey; + SessionToken = sessionToken; + Expiration = expiration.Equals(default) ? null : Utils.To8601String(expiration); + } + else + { + if (string.IsNullOrEmpty(secretKey)) + throw new ArgumentException($"'{nameof(accessKey)}' cannot be null or empty.", nameof(accessKey)); - if (string.IsNullOrEmpty(secretKey)) - throw new ArgumentException($"'{nameof(secretKey)}' cannot be null or empty.", nameof(secretKey)); + if (string.IsNullOrEmpty(secretKey)) + throw new ArgumentException($"'{nameof(secretKey)}' cannot be null or empty.", nameof(secretKey)); - if (string.IsNullOrEmpty(sessionToken)) - throw new ArgumentException($"'{nameof(sessionToken)}' cannot be null or empty.", nameof(sessionToken)); - - AccessKey = accessKey; - SecretKey = secretKey; - SessionToken = sessionToken; - Expiration = expiration.Equals(default) ? null : Utils.To8601String(expiration); + if (string.IsNullOrEmpty(sessionToken)) + throw new ArgumentException($"'{nameof(sessionToken)}' cannot be null or empty.", nameof(sessionToken)); + } } public AccessCredentials() From 8aceacd2dce07061008d89b3a18fd3496c21203e Mon Sep 17 00:00:00 2001 From: Martijn van Dijk Date: Wed, 26 Apr 2023 12:15:11 +0200 Subject: [PATCH 13/13] Fix --- Minio/DataModel/AccessCredentials.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Minio/DataModel/AccessCredentials.cs b/Minio/DataModel/AccessCredentials.cs index 045a7e468..e2a7c612d 100644 --- a/Minio/DataModel/AccessCredentials.cs +++ b/Minio/DataModel/AccessCredentials.cs @@ -35,7 +35,7 @@ public AccessCredentials(string accessKey, string secretKey, } else { - if (string.IsNullOrEmpty(secretKey)) + if (string.IsNullOrEmpty(accessKey)) throw new ArgumentException($"'{nameof(accessKey)}' cannot be null or empty.", nameof(accessKey)); if (string.IsNullOrEmpty(secretKey))