public async Task GetPutBucketLockConfiguration(LockMode mode) { string tempBucketName = "testbucket-" + Guid.NewGuid(); CreateBucketResponse createResp = await BucketClient.CreateBucketAsync(tempBucketName, req => req.EnableObjectLocking = true).ConfigureAwait(false); Assert.True(createResp.IsSuccess); PutBucketLockConfigurationResponse putResp = await BucketClient.PutBucketLockConfigurationAsync(tempBucketName, true, x => { x.LockMode = mode; x.LockRetainUntil = DateTimeOffset.UtcNow.AddDays(2); }).ConfigureAwait(false); Assert.True(putResp.IsSuccess); GetBucketLockConfigurationResponse getResp = await BucketClient.GetBucketLockConfigurationAsync(tempBucketName).ConfigureAwait(false); Assert.True(getResp.IsSuccess); Assert.Equal(mode, getResp.LockMode); Assert.Equal(DateTimeOffset.UtcNow.AddDays(2 - 1).DateTime, getResp.LockRetainUntil !.Value.DateTime, TimeSpan.FromMinutes(1)); //Delete again to cleanup await BucketClient.DeleteBucketAsync(tempBucketName).ConfigureAwait(false); }
/// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { CreateBucketResponse response = new CreateBucketResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("bucket", targetDepth)) { var unmarshaller = BucketUnmarshaller.Instance; response.Bucket = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("operations", targetDepth)) { var unmarshaller = new ListUnmarshaller <Operation, OperationUnmarshaller>(OperationUnmarshaller.Instance); response.Operations = unmarshaller.Unmarshall(context); continue; } } return(response); }
private static void UnmarshallResult(XmlUnmarshallerContext context, CreateBucketResponse response) { int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; if (context.IsStartOfDocument) { targetDepth += 1; } while (context.Read()) { if (context.IsStartElement || context.IsAttribute) { if (context.TestExpression("BucketArn", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.BucketArn = unmarshaller.Unmarshall(context); continue; } } else if (context.IsEndElement && context.CurrentDepth < originalDepth) { return; } } return; }
public async Task CreateBucket(S3Provider _, string __, ISimpleClient client) { string tempBucketName = GetTemporaryBucket(); CreateBucketResponse resp = await client.CreateBucketAsync(tempBucketName).ConfigureAwait(false); Assert.True(resp.IsSuccess); //Delete again to cleanup await client.DeleteBucketAsync(tempBucketName).ConfigureAwait(false); }
public async Task CreateBucket() { string tempBucketName = "testbucket-" + Guid.NewGuid(); CreateBucketResponse resp = await BucketClient.CreateBucketAsync(tempBucketName).ConfigureAwait(false); Assert.True(resp.IsSuccess); //Delete again to cleanup await BucketClient.DeleteBucketAsync(tempBucketName).ConfigureAwait(false); }
/// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context) { CreateBucketResponse response = new CreateBucketResponse(); UnmarshallResult(context, response); if (context.ResponseData.IsHeaderPresent("Location")) { response.Location = context.ResponseData.GetHeaderValue("Location"); } return(response); }
public async Task CreateBucketObjectLocking() { string tempBucketName = "testbucket-" + Guid.NewGuid(); CreateBucketResponse resp = await BucketClient.CreateBucketAsync(tempBucketName, req => req.EnableObjectLocking = true).ConfigureAwait(false); Assert.True(resp.IsSuccess); //TODO: Check locking is enabled once we have that functionality //Delete again to cleanup await BucketClient.DeleteBucketAsync(tempBucketName).ConfigureAwait(false); }
public async Task CreateBucketCannedAcl() { string tempBucketName = "testbucket-" + Guid.NewGuid(); CreateBucketResponse resp = await BucketClient.CreateBucketAsync(tempBucketName, req => req.Acl = BucketCannedAcl.PublicReadWrite).ConfigureAwait(false); Assert.True(resp.IsSuccess); //TODO: Check ACL once we have that functionality //Delete again to cleanup await BucketClient.DeleteBucketAsync(tempBucketName).ConfigureAwait(false); }
static void CreateBucket() { try { CreateBucketRequest request = new CreateBucketRequest() { BucketName = bucketName }; CreateBucketResponse response = client.CreateBucket(request); Console.WriteLine("Create bucket response: {0}", response.StatusCode); } catch (ObsException ex) { Console.WriteLine("Exception errorcode: {0}, when create a bucket.", ex.ErrorCode); Console.WriteLine("Exception errormessage: {0}", ex.ErrorMessage); } }
public async Task GetEmptyBucketLock() { string tempBucketName = "testbucket-" + Guid.NewGuid(); CreateBucketResponse createResp = await BucketClient.CreateBucketAsync(tempBucketName, req => req.EnableObjectLocking = true).ConfigureAwait(false); Assert.True(createResp.IsSuccess); GetBucketLockConfigurationResponse getResp = await BucketClient.GetBucketLockConfigurationAsync(tempBucketName).ConfigureAwait(false); Assert.True(getResp.IsSuccess); Assert.Equal(LockMode.Unknown, getResp.LockMode); Assert.Null(getResp.LockRetainUntil); //Delete again to cleanup await BucketClient.DeleteBucketAsync(tempBucketName).ConfigureAwait(false); }
protected async Task CreateTempBucketAsync(S3Provider provider, ISimpleClient client, Func <string, Task> action, Action <CreateBucketRequest>?config = null) { string tempBucket = GetTemporaryBucket(); CreateBucketResponse createResponse = await client.CreateBucketAsync(tempBucket, config).ConfigureAwait(false); Assert.Equal(200, createResponse.StatusCode); try { await action(tempBucket).ConfigureAwait(false); } finally { int errors = await UtilityHelper.ForceDeleteBucketAsync(provider, client, tempBucket); Assert.Equal(0, errors); } }
/// <summary> /// 创建桶 /// </summary> /// <param name="bucketName"></param> /// <returns></returns> public async Task <bool> CreateBucketAsync(string bucketName) { if (string.IsNullOrEmpty(bucketName)) { throw new ArgumentNullException(nameof(bucketName)); } if (await BucketExistsAsync(bucketName)) { throw new BucketExistException($"Bucket '{bucketName}' already exists."); } CreateBucketRequest request = new CreateBucketRequest { Location = Options.Region, BucketName = bucketName, }; CreateBucketResponse response = _client.CreateBucket(request); return(response != null && response.StatusCode == HttpStatusCode.OK); }
public async Task CreateBucketCustomAcl() { string tempBucketName = "testbucket-" + Guid.NewGuid(); CreateBucketResponse resp = await BucketClient.CreateBucketAsync(tempBucketName, req => { req.AclGrantReadAcp.AddEmail(TestConstants.TestEmail); req.AclGrantWriteAcp.AddEmail(TestConstants.TestEmail); req.AclGrantRead.AddEmail(TestConstants.TestEmail); req.AclGrantWrite.AddEmail(TestConstants.TestEmail); req.AclGrantFullControl.AddEmail(TestConstants.TestEmail); }).ConfigureAwait(false); Assert.True(resp.IsSuccess); //TODO: Check ACL once we have that functionality //Delete again to cleanup await BucketClient.DeleteBucketAsync(tempBucketName).ConfigureAwait(false); }
private static async Task <bool> TryCreateBucketAsync(IBucketClient bucketClient, string bucketName) { HeadBucketResponse headResp = await bucketClient.HeadBucketAsync(bucketName); //Bucket already exist - we return true to apply post-configuration if (headResp.StatusCode == 200) { return(true); } CreateBucketResponse createResp = await bucketClient.CreateBucketAsync(bucketName, r => r.EnableObjectLocking = true).ConfigureAwait(false); if (createResp.IsSuccess) { Console.WriteLine($"Successfully created '{bucketName}'."); return(true); } Console.Error.WriteLine($"Failed to create '{bucketName}'. Error: " + createResp.Error?.Message); return(false); }
protected async Task CreateTempBucketAsync(Func <string, Task> action) { string tempBucketName = "testbucket-" + Guid.NewGuid(); CreateBucketResponse createResponse = await BucketClient.CreateBucketAsync(tempBucketName).ConfigureAwait(false); Assert.True(createResponse.IsSuccess); try { await action(tempBucketName).ConfigureAwait(false); } finally { DeleteAllObjectsStatus delResp = await ObjectClient.DeleteAllObjectsAsync(tempBucketName).ConfigureAwait(false); Assert.Equal(DeleteAllObjectsStatus.Ok, delResp); DeleteBucketResponse del2Resp = await BucketClient.DeleteBucketAsync(tempBucketName).ConfigureAwait(false); Assert.True(del2Resp.IsSuccess); } }
public static async Task MainOSBucketTagging() { string compartmentId = Environment.GetEnvironmentVariable("OCI_COMPARTMENT_ID"); string bucketName = Environment.GetEnvironmentVariable("BUCKET_NAME"); string tagNamespace = Environment.GetEnvironmentVariable("TAG_NAMESPACE"); string tagName = Environment.GetEnvironmentVariable("TAG_NAME"); logger.Info("Starting example"); // Create Object Storage Client var provider = new ConfigFileAuthenticationDetailsProvider("DEFAULT"); var osClient = new ObjectStorageClient(provider, new ClientConfiguration()); logger.Info("Object Storage client created."); GetNamespaceRequest getNamespaceRequest = new GetNamespaceRequest { CompartmentId = compartmentId }; GetNamespaceResponse getNamespaceResponse = await osClient.GetNamespace(getNamespaceRequest); string nSpace = getNamespaceResponse.Value.Trim('"'); logger.Info($"namespace is {nSpace}"); /* * We can assign tags to a bucket at creation time. Like other taggable resources, we can * assign freeform and defined tags to a bucket. Freeform tags are a dictionary of * string-to-string, where the key is the tag name and the value is the tag value. * * Defined tags are a dictionary where the key is the tag namespace (string) and the value is another dictionary. In * this second dictionary, the key is the tag name (string) and the value is the tag value. The tag names have to * correspond to the name of a tag within the specified namespace (and the namespace must exist). */ try { Dictionary <string, string> freeformTags = new Dictionary <string, string>() { { "free", "form" }, { "another", "item" } }; Dictionary <string, object> definedTagsMap = new Dictionary <string, object>() { { tagName, "original value" } }; Dictionary <string, Dictionary <string, object> > definedTags = new Dictionary <string, Dictionary <string, object> >() { { tagNamespace, definedTagsMap } }; CreateBucketDetails createBucketDetails = new CreateBucketDetails { Name = bucketName, CompartmentId = compartmentId, FreeformTags = freeformTags, DefinedTags = definedTags, ObjectEventsEnabled = false }; CreateBucketRequest createBucketRequest = new CreateBucketRequest { CreateBucketDetails = createBucketDetails, NamespaceName = nSpace }; CreateBucketResponse createBucketResponse = await osClient.CreateBucket(createBucketRequest); logger.Info($"Created a bucket with tags Bucket name: {createBucketResponse.Bucket.Name}"); logger.Info("========================================"); definedTags = createBucketResponse.Bucket.DefinedTags; foreach (KeyValuePair <string, Dictionary <string, object> > kvp in definedTags) { foreach (KeyValuePair <string, object> tags in kvp.Value) { logger.Info($"tag key name: {tags.Key} and tag value is {tags.Value}"); } } // Tags come back when retrieving the bucket GetBucketRequest getBucketRequest = new GetBucketRequest { NamespaceName = nSpace, BucketName = bucketName }; GetBucketResponse getBucketResponse = await osClient.GetBucket(getBucketRequest); logger.Info($"Retrieved a bucket with tags Bucket name: {getBucketResponse.Bucket.Name}"); logger.Info("=========================================="); definedTags = getBucketResponse.Bucket.DefinedTags; foreach (KeyValuePair <string, Dictionary <string, object> > kvp in definedTags) { foreach (KeyValuePair <string, object> tags in kvp.Value) { logger.Info($"tag key name: {tags.Key} and tag value is {tags.Value}"); } } /* * Unlike other resources (e.g. instances, VCNs, and block volumes), when listing buckets * tags are not returned by default. Instead, you need to provide a value to the fields * parameter when listing buckets in order to have those tags returned. * * Here we can see the result of providing and not providing that parameter. */ ListBucketsRequest listBucketsRequest = new ListBucketsRequest { CompartmentId = compartmentId, NamespaceName = nSpace }; IEnumerable <BucketSummary> bucketSummaries = osClient.Paginators.ListBucketsRecordEnumerator(listBucketsRequest); foreach (BucketSummary bucketSummary in bucketSummaries) { if (bucketSummary.Name.Equals(bucketName)) { logger.Info($"Bucket summary without tags: Bucket Name: {bucketSummary.Name}"); logger.Info("========================================="); if (bucketSummary.DefinedTags != null) { logger.Error($"expected tags to be zero but got: {bucketSummary.DefinedTags.Count}"); } break; } } List <ListBucketsRequest.FieldsEnum> fields = new List <ListBucketsRequest.FieldsEnum>() { ListBucketsRequest.FieldsEnum.Tags }; listBucketsRequest = new ListBucketsRequest { CompartmentId = compartmentId, NamespaceName = nSpace, Fields = fields }; bucketSummaries = osClient.Paginators.ListBucketsRecordEnumerator(listBucketsRequest); foreach (BucketSummary bucketSummary in bucketSummaries) { if (bucketSummary.Name.Equals(bucketName)) { logger.Info($"Bucket summary with tags: Bucket Name: {bucketSummary.Name}"); logger.Info("======================================"); definedTags = bucketSummary.DefinedTags; foreach (KeyValuePair <string, Dictionary <string, object> > kvp in definedTags) { foreach (KeyValuePair <string, object> tags in kvp.Value) { logger.Info($"tag key name: {tags.Key} and tag value is {tags.Value}"); } } } } /* * We can also update tags on a bucket. Note that this is a total replacement for any * previously set freeform or defined tags. */ Dictionary <string, string> updateFreeformTags = new Dictionary <string, string>() { { "new", "freeform" } }; Dictionary <string, object> updateDefinedTagsMap = new Dictionary <string, object>() { { tagName, "replaced" } }; Dictionary <string, Dictionary <string, object> > updateDefinedTags = new Dictionary <string, Dictionary <string, object> >() { { tagNamespace, updateDefinedTagsMap } }; UpdateBucketDetails updateBucketDetails = new UpdateBucketDetails { Name = bucketName, FreeformTags = updateFreeformTags, DefinedTags = updateDefinedTags }; UpdateBucketRequest updateBucketRequest = new UpdateBucketRequest { NamespaceName = nSpace, BucketName = bucketName, UpdateBucketDetails = updateBucketDetails }; UpdateBucketResponse updateBucketResponse = await osClient.UpdateBucket(updateBucketRequest); logger.Info($"Updated the bucket with new tags Bucket name: {updateBucketResponse.Bucket.Name}"); logger.Info("=============================================="); definedTags = updateBucketResponse.Bucket.DefinedTags; foreach (KeyValuePair <string, Dictionary <string, object> > kvp in definedTags) { foreach (KeyValuePair <string, object> tags in kvp.Value) { logger.Info($"tag key name: {tags.Key} and tag value is {tags.Value}"); } } updateBucketDetails = new UpdateBucketDetails { Name = bucketName, FreeformTags = new Dictionary <string, string>(), DefinedTags = new Dictionary <string, Dictionary <string, object> >() }; updateBucketRequest = new UpdateBucketRequest { NamespaceName = nSpace, BucketName = bucketName, UpdateBucketDetails = updateBucketDetails }; updateBucketResponse = await osClient.UpdateBucket(updateBucketRequest); logger.Info($"cleared the tags for the bucket: {updateBucketResponse.Bucket.Name}"); logger.Info("================================="); // Clean up DeleteBucketRequest deleteBucketRequest = new DeleteBucketRequest { NamespaceName = nSpace, BucketName = bucketName }; await osClient.DeleteBucket(deleteBucketRequest); logger.Info("Deleted the bucket"); logger.Info("Ending example."); } catch (Exception e) { logger.Error($"Failed Object Storage example: {e.Message}"); } finally { osClient.Dispose(); } }
private static async Task Main(string[] args) { IConfigurationRoot root = new ConfigurationBuilder() .AddJsonFile("Config.json", false) .Build(); ServiceCollection services = new ServiceCollection(); services.Configure <S3Config>(root); IS3ClientBuilder clientBuilder = services.AddSimpleS3(); clientBuilder.CoreBuilder.UseProfileManager() .BindConfigToDefaultProfile() .UseDataProtection(); IConfigurationSection proxySection = root.GetSection("Proxy"); if (proxySection != null && proxySection["UseProxy"].Equals("true", StringComparison.OrdinalIgnoreCase)) { clientBuilder.HttpBuilder.WithProxy(proxySection["ProxyAddress"]); } using (ServiceProvider provider = services.BuildServiceProvider()) { IProfileManager manager = provider.GetRequiredService <IProfileManager>(); IProfile? profile = manager.GetDefaultProfile(); //If profile is null, then we do not yet have a profile stored on disk. We use ConsoleSetup as an easy and secure way of asking for credentials if (profile == null) { Console.WriteLine("No profile found. Starting setup."); ConsoleSetup.SetupDefaultProfile(manager); } IBucketClient bucketClient = provider.GetRequiredService <IBucketClient>(); string bucketName = root["BucketName"]; Console.WriteLine($"Setting up bucket '{bucketName}'"); HeadBucketResponse headResp = await bucketClient.HeadBucketAsync(bucketName).ConfigureAwait(false); if (headResp.IsSuccess) { Console.WriteLine($"'{bucketName}' already exist."); } else { Console.WriteLine($"'{bucketName}' does not exist - creating."); CreateBucketResponse createResp = await bucketClient.CreateBucketAsync(bucketName, x => x.EnableObjectLocking = true).ConfigureAwait(false); if (createResp.IsSuccess) { Console.WriteLine($"Successfully created '{bucketName}'."); } else { Console.Error.WriteLine($"Failed to create '{bucketName}'. Exiting."); return; } } Console.WriteLine("Adding lock configuration"); PutBucketLockConfigurationResponse putLockResp = await bucketClient.PutBucketLockConfigurationAsync(bucketName, true).ConfigureAwait(false); if (putLockResp.IsSuccess) { Console.WriteLine("Successfully applied lock configuration."); } else { Console.Error.WriteLine("Failed to apply lock configuration."); } List <S3Rule> rules = new List <S3Rule> { new S3Rule("ExpireAll", true) { AbortIncompleteMultipartUploadDays = 1, NonCurrentVersionExpirationDays = 1, Expiration = new S3Expiration(1), Filter = new S3Filter { Prefix = "" } } }; Console.WriteLine("Adding lifecycle configuration"); PutBucketLifecycleConfigurationResponse putLifecycleResp = await bucketClient.PutBucketLifecycleConfigurationAsync(bucketName, rules).ConfigureAwait(false); if (putLifecycleResp.IsSuccess) { Console.WriteLine("Successfully applied lifecycle configuration."); } else { Console.Error.WriteLine("Failed to apply lifecycle configuration."); } } }
private static async Task Main(string[] args) { // This example uses BackBlaze B2. Go here to create a key: https://secure.backblaze.com/app_keys.htm ISimpleClient client = BuildClient(); string bucketName = "test-" + Guid.NewGuid(); Console.WriteLine("# Listing buckets"); await foreach (S3Bucket bucket in client.ListAllBucketsAsync()) //This is a commercial feature { Console.WriteLine($" - {bucket.BucketName}"); } Console.WriteLine("# Creating a temporary bucket"); CreateBucketResponse putBucket = await client.CreateBucketAsync(bucketName); if (putBucket.IsSuccess) { Console.WriteLine($" - Successfully created {bucketName}"); Console.WriteLine("# Creating 10 objects"); for (int i = 0; i < 10; i++) { string objectName = Guid.NewGuid().ToString(); PutObjectResponse putReq = await client.PutObjectStringAsync(bucketName, objectName, "This is a test"); //This is a commercial feature if (putReq.IsSuccess) { Console.WriteLine($" - Successfully created {objectName}"); } else { Console.WriteLine($" - Failed to create {objectName}"); } } Console.WriteLine("# Deleting all objects in temporary bucket"); await foreach (S3DeleteError obj in client.DeleteAllObjectVersionsAsync(bucketName)) //This is a commercial feature { Console.WriteLine("Deleted " + obj.ObjectKey); } DeleteBucketResponse delResp = await client.DeleteBucketAsync(bucketName); if (delResp.IsSuccess) { Console.WriteLine($" - Successfully deleted {bucketName}"); } else { Console.WriteLine($" - Failed to delete {bucketName}"); } } else { Console.WriteLine("Failed to create " + bucketName); } }