You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

290 lines
13 KiB

2 years ago
  1. /*
  2. * MinIO .NET Library for Amazon S3 Compatible Cloud Storage, (C) 2017, 2020 MinIO, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. using System.Diagnostics.CodeAnalysis;
  17. using System.Globalization;
  18. using System.Net;
  19. using System.Security.Cryptography;
  20. using System.Text;
  21. using Minio.DataModel;
  22. using Minio.DataModel.Encryption;
  23. using Minio.DataModel.Notification;
  24. using Minio.DataModel.ObjectLock;
  25. using Minio.Examples.Cases;
  26. using Minio.Helper;
  27. namespace Minio.Examples;
  28. public static class Program
  29. {
  30. private const int UNIT_MB = 1024 * 1024;
  31. private static readonly Random rnd = new();
  32. // Create a file of given size from random byte array
  33. private static string CreateFile(int size)
  34. {
  35. var fileName = GetRandomName();
  36. var data = new byte[size];
  37. rnd.NextBytes(data);
  38. File.WriteAllBytes(fileName, data);
  39. return fileName;
  40. }
  41. // Generate a random string
  42. public static string GetRandomName()
  43. {
  44. var characters = "0123456789abcdefghijklmnopqrstuvwxyz";
  45. var result = new StringBuilder(5);
  46. for (var i = 0; i < 5; i++) _ = result.Append(characters[rnd.Next(characters.Length)]);
  47. return "minio-dotnet-example-" + result;
  48. }
  49. [SuppressMessage("Design", "MA0051:Method is too long", Justification = "Needs to run all tests")]
  50. public static async Task Main()
  51. {
  52. string endPoint = null;
  53. string accessKey = null;
  54. string secretKey = null;
  55. var isSecure = false;
  56. var port = 80;
  57. if (Environment.GetEnvironmentVariable("SERVER_ENDPOINT") is not null)
  58. {
  59. endPoint = Environment.GetEnvironmentVariable("SERVER_ENDPOINT");
  60. var posColon = endPoint.LastIndexOf(':');
  61. if (posColon != -1)
  62. {
  63. port = int.Parse(endPoint.Substring(posColon + 1, endPoint.Length - posColon - 1), NumberStyles.Integer,
  64. CultureInfo.InvariantCulture);
  65. endPoint = endPoint[..posColon];
  66. }
  67. accessKey = Environment.GetEnvironmentVariable("ACCESS_KEY");
  68. secretKey = Environment.GetEnvironmentVariable("SECRET_KEY");
  69. if (Environment.GetEnvironmentVariable("ENABLE_HTTPS") is not null)
  70. {
  71. isSecure = Environment.GetEnvironmentVariable("ENABLE_HTTPS")
  72. .Equals("1", StringComparison.OrdinalIgnoreCase);
  73. if (isSecure && port == 80) port = 443;
  74. }
  75. }
  76. else
  77. {
  78. endPoint = "play.min.io";
  79. accessKey = "Q3AM3UQ867SPQQA43P2F";
  80. secretKey = "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG";
  81. isSecure = true;
  82. port = 443;
  83. }
  84. #pragma warning disable MA0039 // Do not write your own certificate validation method
  85. ServicePointManager.ServerCertificateValidationCallback +=
  86. (sender, certificate, chain, sslPolicyErrors) => true;
  87. #pragma warning restore MA0039 // Do not write your own certificate validation method
  88. using var minioClient = new MinioClient()
  89. .WithEndpoint(endPoint, port)
  90. .WithCredentials(accessKey, secretKey)
  91. .WithSSL(isSecure)
  92. .Build();
  93. // Assign parameters before starting the test
  94. var bucketName = GetRandomName();
  95. var smallFileName = CreateFile(1 * UNIT_MB);
  96. var bigFileName = CreateFile(6 * UNIT_MB);
  97. var objectName = GetRandomName();
  98. var destBucketName = GetRandomName();
  99. var destObjectName = GetRandomName();
  100. var lockBucketName = GetRandomName();
  101. var progress = new SyncProgress<ProgressReport>(progressReport =>
  102. {
  103. Console.WriteLine(
  104. $"Percentage: {progressReport.Percentage}% TotalBytesTransferred: {progressReport.TotalBytesTransferred} bytes");
  105. if (progressReport.Percentage != 100)
  106. Console.SetCursorPosition(0, Console.CursorTop - 1);
  107. else Console.WriteLine();
  108. });
  109. var objectsList = new List<string>();
  110. for (var i = 0; i < 10; i++) objectsList.Add(objectName + i);
  111. // Set app Info
  112. minioClient.SetAppInfo("app-name", "app-version");
  113. // Set HTTP Tracing On
  114. // minioClient.SetTraceOn();
  115. // Set HTTP Tracing Off
  116. // minioClient.SetTraceOff();
  117. // Check if bucket exists
  118. await BucketExists.Run(minioClient, bucketName).ConfigureAwait(false);
  119. // Create a new bucket
  120. await MakeBucket.Run(minioClient, bucketName).ConfigureAwait(false);
  121. await MakeBucket.Run(minioClient, destBucketName).ConfigureAwait(false);
  122. // Bucket with Lock tests
  123. await MakeBucketWithLock.Run(minioClient, lockBucketName).ConfigureAwait(false);
  124. await BucketExists.Run(minioClient, lockBucketName).ConfigureAwait(false);
  125. await RemoveBucket.Run(minioClient, lockBucketName).ConfigureAwait(false);
  126. // Versioning tests
  127. await GetVersioning.Run(minioClient, bucketName).ConfigureAwait(false);
  128. await EnableSuspendVersioning.Run(minioClient, bucketName).ConfigureAwait(false);
  129. await GetVersioning.Run(minioClient, bucketName).ConfigureAwait(false);
  130. // List all the buckets on the server
  131. await ListBuckets.Run(minioClient).ConfigureAwait(false);
  132. // Start listening for bucket notifications
  133. ListenBucketNotifications.Run(minioClient, bucketName, new List<EventType> { EventType.ObjectCreatedAll });
  134. // Start listening for global notifications
  135. ListenNotifications.Run(minioClient, new List<EventType> { EventType.BucketCreatedAll });
  136. // Put an object to the new bucket
  137. await PutObject.Run(minioClient, bucketName, objectName, smallFileName, progress).ConfigureAwait(false);
  138. // Get object metadata
  139. await StatObject.Run(minioClient, bucketName, objectName).ConfigureAwait(false);
  140. // List the objects in the new bucket
  141. await ListObjects.Run(minioClient, bucketName).ConfigureAwait(false);
  142. // Get the file and Download the object as file
  143. await GetObject.Run(minioClient, bucketName, objectName, smallFileName).ConfigureAwait(false);
  144. // Select content from object
  145. await SelectObjectContent.Run(minioClient, bucketName, objectName).ConfigureAwait(false);
  146. // Delete the file and Download partial object as file
  147. await GetPartialObject.Run(minioClient, bucketName, objectName, smallFileName).ConfigureAwait(false);
  148. // Server side copyObject
  149. await CopyObject.Run(minioClient, bucketName, objectName, destBucketName, objectName).ConfigureAwait(false);
  150. // Server side copyObject with metadata replacement
  151. await CopyObjectMetadata.Run(minioClient, bucketName, objectName, destBucketName, objectName)
  152. .ConfigureAwait(false);
  153. // Upload a File with PutObject
  154. await FPutObject.Run(minioClient, bucketName, objectName, smallFileName).ConfigureAwait(false);
  155. // Delete the file and Download the object as file
  156. await FGetObject.Run(minioClient, bucketName, objectName, smallFileName).ConfigureAwait(false);
  157. // Automatic Multipart Upload with object more than 5Mb
  158. await PutObject.Run(minioClient, bucketName, objectName, bigFileName, progress).ConfigureAwait(false);
  159. // Specify SSE-C encryption options
  160. using var aesEncryption = Aes.Create();
  161. aesEncryption.KeySize = 256;
  162. aesEncryption.GenerateKey();
  163. var ssec = new SSEC(aesEncryption.Key);
  164. // Specify SSE-C source side encryption for Copy operations
  165. var sseCpy = new SSECopy(aesEncryption.Key);
  166. // Uncomment to specify SSE-S3 encryption option
  167. var sses3 = new SSES3();
  168. // Uncomment to specify SSE-KMS encryption option
  169. var sseKms = new SSEKMS("kms-key",
  170. new Dictionary<string, string>(StringComparer.Ordinal) { { "kms-context", "somevalue" } });
  171. // Upload encrypted object
  172. var putFileName1 = CreateFile(1 * UNIT_MB);
  173. await PutObject.Run(minioClient, bucketName, objectName, putFileName1, progress, ssec).ConfigureAwait(false);
  174. // Copy SSE-C encrypted object to unencrypted object
  175. await CopyObject.Run(minioClient, bucketName, objectName, destBucketName, objectName, sseCpy, ssec)
  176. .ConfigureAwait(false);
  177. // Download SSE-C encrypted object
  178. await FGetObject.Run(minioClient, destBucketName, objectName, bigFileName, ssec).ConfigureAwait(false);
  179. // List the incomplete uploads
  180. await ListIncompleteUploads.Run(minioClient, bucketName).ConfigureAwait(false);
  181. // Remove all the incomplete uploads
  182. await RemoveIncompleteUpload.Run(minioClient, bucketName, objectName).ConfigureAwait(false);
  183. // Set a policy for given bucket
  184. await SetBucketPolicy.Run(minioClient, bucketName).ConfigureAwait(false);
  185. // Get the policy for given bucket
  186. await GetBucketPolicy.Run(minioClient, bucketName).ConfigureAwait(false);
  187. // Set bucket notifications
  188. await SetBucketNotification.Run(minioClient, bucketName).ConfigureAwait(false);
  189. // Get bucket notifications
  190. await GetBucketNotification.Run(minioClient, bucketName).ConfigureAwait(false);
  191. // Remove all bucket notifications
  192. await RemoveAllBucketNotifications.Run(minioClient, bucketName).ConfigureAwait(false);
  193. // Object Lock Configuration operations
  194. lockBucketName = GetRandomName();
  195. await MakeBucketWithLock.Run(minioClient, lockBucketName).ConfigureAwait(false);
  196. var configuration = new ObjectLockConfiguration(ObjectRetentionMode.GOVERNANCE, 35);
  197. await SetObjectLockConfiguration.Run(minioClient, lockBucketName, configuration).ConfigureAwait(false);
  198. await GetObjectLockConfiguration.Run(minioClient, lockBucketName).ConfigureAwait(false);
  199. await RemoveObjectLockConfiguration.Run(minioClient, lockBucketName).ConfigureAwait(false);
  200. await RemoveBucket.Run(minioClient, lockBucketName).ConfigureAwait(false);
  201. // Bucket Replication operations
  202. var replicationRuleID = "myreplicationID-3333";
  203. await SetBucketReplication.Run(minioClient, bucketName, destBucketName, replicationRuleID)
  204. .ConfigureAwait(false);
  205. await GetBucketReplication.Run(minioClient, bucketName, replicationRuleID).ConfigureAwait(false);
  206. // TODO: we can verify that the replication happens by checking
  207. // the content in the destination matches the source content.
  208. // We also cannot remove the replication config immediately
  209. // after running GetBucketReplication command, as
  210. // replicating the source in the destination takes some time.
  211. await RemoveBucketReplication.Run(minioClient, bucketName).ConfigureAwait(false);
  212. // Get the presigned url for a GET object request
  213. await PresignedGetObject.Run(minioClient, bucketName, objectName).ConfigureAwait(false);
  214. // Get the presigned POST policy curl url
  215. await PresignedPostPolicy.Run(minioClient, bucketName, objectName).ConfigureAwait(false);
  216. // Get the presigned url for a PUT object request
  217. await PresignedPutObject.Run(minioClient, bucketName, objectName).ConfigureAwait(false);
  218. // Delete the list of objects
  219. await RemoveObjects.Run(minioClient, bucketName, objectsList).ConfigureAwait(false);
  220. // Delete the object
  221. await RemoveObject.Run(minioClient, bucketName, objectName).ConfigureAwait(false);
  222. // Delete the object
  223. await RemoveObject.Run(minioClient, destBucketName, objectName).ConfigureAwait(false);
  224. // Retry on failure
  225. await RetryPolicyObject.Run(minioClient, destBucketName, objectName).ConfigureAwait(false);
  226. // Tracing request with custom logger
  227. await CustomRequestLogger.Run(minioClient).ConfigureAwait(false);
  228. // Remove the buckets
  229. await RemoveBucket.Run(minioClient, bucketName).ConfigureAwait(false);
  230. await RemoveBucket.Run(minioClient, destBucketName).ConfigureAwait(false);
  231. // Remove the binary files created for test
  232. File.Delete(smallFileName);
  233. File.Delete(bigFileName);
  234. if (OperatingSystem.IsWindows()) _ = Console.ReadLine();
  235. }
  236. }