public bool DeleteBucket() { try { ListObjectsRequest request = new ListObjectsRequest(); request.BucketName = this.bucketName; ListObjectsResponse response = amazonS3Client.ListObjects(request); foreach (S3Object o in response.S3Objects) { DeleteObjectRequest delrequest = new DeleteObjectRequest(); delrequest.BucketName = this.bucketName; delrequest.Key = o.Key; amazonS3Client.DeleteObject(delrequest); } DeleteBucketRequest delbucketrequest = new DeleteBucketRequest(); delbucketrequest.BucketName = this.bucketName; amazonS3Client.DeleteBucket(delbucketrequest); return(true); } catch (Exception e) { structuredLog("E", "Exception in DeleteBucket: " + e); return(false); } }
virtual public void RemoveLabBuckets(AmazonS3Client s3Client, List <string> bucketNames) { foreach (var bucketName in bucketNames) { try { ListObjectsResponse listObjectsResponse = s3Client.ListObjects(new ListObjectsRequest { BucketName = bucketName }); foreach (var s3Object in listObjectsResponse.S3Objects) { var deleteObjectRequest = new DeleteObjectRequest { BucketName = bucketName, Key = s3Object.Key }; s3Client.DeleteObject(deleteObjectRequest); } s3Client.DeleteBucket(new DeleteBucketRequest { BucketName = bucketName }); } catch (AmazonS3Exception s3E) { if (!s3E.ErrorCode.Equals("NoSuchBucket")) { // This error wasn't expected, so rethrow. throw; } } } }
static void Main(string[] args) { SharedCredentialsFile sharedCredentialsFile = new SharedCredentialsFile(); CredentialProfile defaultProfile = GetDefaultProfile(sharedCredentialsFile); if (defaultProfile != null) { AWSCredentials credentials = AWSCredentialsFactory.GetAWSCredentials(defaultProfile, new SharedCredentialsFile()); AmazonS3Client s3Client = new AmazonS3Client(credentials, RegionEndpoint.USEast1); DeleteBucketRequest request = new DeleteBucketRequest { //How to get this name programatically without hard coding? bucket.name? BucketName = "20411141-0e46-4b95-8074-1e28cb421306" }; if (request.Equals(null)) { DeleteBucketResponse dResponse = s3Client.DeleteBucket(request); } ListBucketsResponse response = s3Client.ListBuckets(); foreach (S3Bucket r in response.Buckets) { Console.WriteLine(r.BucketName + " created at " + r.CreationDate + " type = " + r.GetType()); } } Console.ReadLine(); }
public static void DeleteBucket(string bucketName) { using (var client = new AmazonS3Client(Settings.AccessKey, Settings.Secret)) { client.DeleteBucket(bucketName); } }
private void DeleteRolesAndPolicies() { try { _s3Client.DeleteBucket(_awsConfiguration.Bucket); } catch (AmazonS3Exception) { } try { _iamClient.DeleteRolePolicy(new DeleteRolePolicyRequest { RoleName = _awsConfiguration.RoleName, PolicyName = "s3-releases" }); } catch (NoSuchEntityException) { } try { _iamClient.DeleteRole(new DeleteRoleRequest { RoleName = _awsConfiguration.RoleName }); } catch (NoSuchEntityException) { } }
private void deleteBucket() { s3.DeleteBucket(new DeleteBucketRequest() { BucketName = bucketName }); }
public static void Main(string[] args) { // create the AWS S3 client AmazonS3Client s3 = AWSS3Factory.getS3Client(); bool moreRecords = true; string nextMarker = string.Empty; while (moreRecords) { ListVersionsRequest request = new ListVersionsRequest() { BucketName = AWSS3Factory.S3_BUCKET, }; if (nextMarker.Length > 0) { request.KeyMarker = nextMarker; } ListVersionsResponse response = new ListVersionsResponse(); response = s3.ListVersions(request); foreach (S3ObjectVersion theObject in response.Versions) { s3.DeleteObject(new DeleteObjectRequest() { BucketName = AWSS3Factory.S3_BUCKET, Key = theObject.Key, VersionId = theObject.VersionId }); Console.WriteLine("Deleted {0}/{1}", AWSS3Factory.S3_BUCKET, theObject.Key); } Console.WriteLine(string.Format("Next Marker: {0} Version Count: {1}", response.NextKeyMarker, response.Versions.Count.ToString())); if (response.IsTruncated) { nextMarker = response.NextKeyMarker; } else { moreRecords = false; } } s3.DeleteBucket(new DeleteBucketRequest() { BucketName = AWSS3Factory.S3_BUCKET }); // print bucket name for validation Console.WriteLine(string.Format("Deleted bucket {0}", AWSS3Factory.S3_BUCKET)); Console.ReadLine(); }
/// <summary> /// Delete a bucket and its content. /// </summary> /// <param name="bucketName">The name of the bucket.</param> public void DeleteBucket(string bucketName) { var request = new DeleteBucketRequest { BucketName = bucketName }; _amazonS3Client.DeleteBucket(request); }
public virtual void DeleteBucket(AmazonS3Client s3Client, string bucketName) { // First, try to delete the bucket. var deleteBucketRequest = new DeleteBucketRequest { BucketName = bucketName }; try { s3Client.DeleteBucket(deleteBucketRequest); // If we get here, no error was generated so we'll assume the bucket was deleted and return. return; } catch (AmazonS3Exception ex) { if (!ex.ErrorCode.Equals("BucketNotEmpty")) { // We got an unanticipated error. Just rethrow. throw; } } // If we got here, then our bucket isn't empty so we need to delete the items in it first. DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest { BucketName = bucketName }; foreach (S3Object obj in s3Client.ListObjects(new ListObjectsRequest { BucketName = bucketName }).S3Objects) { // Add keys for the objects to the delete request deleteObjectsRequest.AddKey(obj.Key, null); } // Submit the request s3Client.DeleteObjects(deleteObjectsRequest); // The bucket is empty now, so delete the bucket. s3Client.DeleteBucket(deleteBucketRequest); }
private void DeletePreviousTestStack() { _iamClient.DeleteRole("some_role_that_is_no_good_test"); _iamClient.DeleteUser(_userName); StackHelper.DeleteStack(_awsConfiguration.AwsEndpoint, "SimpleBucketTestStack"); if (_s3Client.ListBuckets().Buckets.Any(x => x.BucketName == _bucketName)) { _s3Client.DeleteBucket(_bucketName); } }
public ICustomActivityResult Execute() { var message = string.Empty; var credentials = new BasicAWSCredentials(AccessKey, SecretKey); using (var result = new AmazonS3Client(credentials, RegionEndpoint.USWest2)) { result.DeleteBucket(bucketName); message = "Success"; } return(this.GenerateActivityResult(message)); }
public static void DeleteAllBuckets() { using (var client = new AmazonS3Client(Settings.AccessKey, Settings.Secret)) { var response = client.ListBuckets(); foreach (var bucket in response.Buckets) { DeleteAllBucketItems(bucket.BucketName); client.DeleteBucket(bucket.BucketName); } } }
public void rmdir(string bucket) { try { DeleteBucketRequest deletebucketrequest = new DeleteBucketRequest(); deletebucketrequest.BucketName = bucket; s3Client.DeleteBucket(deletebucketrequest); Console.WriteLine("Bucket '" + bucket + "' has been deleted"); } catch (Exception e) { Console.WriteLine("Error deleting bucket '" + bucket + "': " + e.Message); } }
static void Main(string[] args) { string AccessKey = " *** Enter Access Key Here *** "; string SecretKey = " *** Enter Secret Key Here *** "; string NameOfTheBucket = " *** Name Of The Bucket *** "; string RegionOfTheBucket = " *** Enter The Region Of The Bucket (Eg: mumbai) ***"; RegionOfTheBucket = RegionOfTheBucket.ToLower(); try { AmazonS3Client client = new AmazonS3Client(AccessKey, SecretKey, Amazon.RegionEndpoint.GetBySystemName(ClientRegion(RegionOfTheBucket))); ListObjectsRequest ObjectRequest = new ListObjectsRequest { BucketName = NameOfTheBucket }; ListObjectsResponse ListResponse; do { ListResponse = client.ListObjects(ObjectRequest); foreach (S3Object obj in ListResponse.S3Objects) { DeleteObjectRequest DeleteObject = new DeleteObjectRequest { BucketName = NameOfTheBucket, Key = obj.Key }; client.DeleteObject(DeleteObject); } ObjectRequest.Marker = ListResponse.NextMarker; } while (ListResponse.IsTruncated); DeleteBucketRequest DeleteRequest = new DeleteBucketRequest { BucketName = NameOfTheBucket, UseClientRegion = true }; client.DeleteBucket(DeleteRequest); Console.WriteLine("Bucket Deleted"); } catch (Exception e) { Console.WriteLine("ERROR MESSAGE : " + e.Message); } Console.ReadLine(); }
/// <summary> /// delete bucket from s3 /// </summary> /// <param name="PathName"></param> /// <returns></returns> public bool DeleteDirectory(string PathName) { try { //amazon client using (var client = new AmazonS3Client()) { //delete bucket request using (var response = client.DeleteBucket(new DeleteBucketRequest() .WithBucketName(PathName))) { return(true); } } } catch (Exception ex) { Trace.WriteLine(ex.ToString()); } return(false); }
// Delete bucket functionality public static void DeleteBucketFunctionality(string NameOfTheBucket, string RegionOfTheBucket) { RegionOfTheBucket = RegionOfTheBucket.ToLower(); try { AmazonS3Client client = new AmazonS3Client(AccessKey, SecretKey, Amazon.RegionEndpoint.GetBySystemName(ClientRegion(RegionOfTheBucket))); ListObjectsRequest ObjectRequest = new ListObjectsRequest { BucketName = NameOfTheBucket }; ListObjectsResponse ListResponse; do { ListResponse = client.ListObjects(ObjectRequest); foreach (S3Object obj in ListResponse.S3Objects) { DeleteObjectRequest DeleteObject = new DeleteObjectRequest { BucketName = NameOfTheBucket, Key = obj.Key }; client.DeleteObject(DeleteObject); } ObjectRequest.Marker = ListResponse.NextMarker; } while (ListResponse.IsTruncated); DeleteBucketRequest DeleteRequest = new DeleteBucketRequest { BucketName = NameOfTheBucket, UseClientRegion = true }; client.DeleteBucket(DeleteRequest); Console.WriteLine("Bucket Deleted"); } catch (Exception e) { Console.WriteLine("ERROR MESSAGE : " + e.Message); } }
public static void Main(string[] args) { System.Net.ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true); // create the AWS S3 client AmazonS3Client s3 = AWSS3Factory.getS3Client(); String bucketName = String.Join("-", AWSS3Factory.S3_BUCKET, DateTime.Now.ToString("yyyyMMddHHmmss")); //********************// // 1. Create a bucket // //********************// Console.Write(string.Format(" [*] Creating bucket '{0}'... ", bucketName)); PutBucketResponse pbRes = s3.PutBucket(bucketName); if (pbRes.HttpStatusCode != System.Net.HttpStatusCode.OK) { Console.WriteLine("fail"); Console.ReadLine(); System.Environment.Exit(1); } Console.WriteLine("done"); //************************************// // 2. Create and upload object // //************************************// String objectKey = "object-" + DateTime.Now.ToString("yyyyMMddHHmmssffff"); Console.Write(string.Format(" [*] Creating a new object with key '{0}'... ", objectKey)); PutObjectRequest poRequest = new PutObjectRequest() { BucketName = bucketName, ContentBody = "Lorem ipsum dolor sit amet, consectetur adipiscing elit...", Key = objectKey }; PutObjectResponse poResponse = s3.PutObject(poRequest); if (poResponse.HttpStatusCode != System.Net.HttpStatusCode.OK) { Console.WriteLine("fail"); Console.ReadLine(); System.Environment.Exit(1); } Console.WriteLine("done"); //****************************************// // 3. Obtain object metadata // //****************************************// Console.Write(string.Format(" [*] Obtaining object size and other metadata for object '{0}'... ", objectKey)); GetObjectMetadataRequest request = new GetObjectMetadataRequest() { BucketName = bucketName, Key = objectKey }; // get object metadata - not actual content (HEAD request not GET). GetObjectMetadataResponse gomResponse = s3.GetObjectMetadata(request); if (gomResponse.HttpStatusCode != System.Net.HttpStatusCode.OK) { Console.WriteLine("fail"); Console.ReadLine(); System.Environment.Exit(1); } Console.WriteLine("done"); // Obtain the object size in Bytes long objectSize = gomResponse.Headers.ContentLength; Console.WriteLine(string.Format(" [x] Object size is: {0} bytes", objectSize)); Console.WriteLine(" [x] Other headers and metadata:"); ICollection <string> headers = gomResponse.Headers.Keys; foreach (string header in headers) { Console.WriteLine("[x] {0}: {1}", header, gomResponse.Headers[header]); } ICollection <string> metaKeys = gomResponse.Metadata.Keys; foreach (string metaKey in metaKeys) { Console.WriteLine("[x] {0}: {1}", metaKey, gomResponse.Metadata[metaKey]); } //*******************************************// // 4. Delete the object // //*******************************************// Console.Write(string.Format(" [*] Deleting object '{0}'... ", objectKey)); // create the request object DeleteObjectRequest doRequest = new DeleteObjectRequest() { BucketName = bucketName, Key = objectKey }; // delete the object in the demo bucket DeleteObjectResponse doResponse = s3.DeleteObject(doRequest); if (doResponse.HttpStatusCode != System.Net.HttpStatusCode.NoContent) { Console.WriteLine("fail"); Console.ReadLine(); System.Environment.Exit(1); } Console.WriteLine("done"); //***********************// // 5. Delete the bucket // //***********************// Console.Write(String.Format(" [*] Deleting bucket '{0}' (sleeping 5 seconds)... ", bucketName)); System.Threading.Thread.Sleep(5000); DeleteBucketResponse dbRes = s3.DeleteBucket(bucketName); if (dbRes.HttpStatusCode != System.Net.HttpStatusCode.NoContent) { Console.WriteLine("fail"); Console.ReadLine(); System.Environment.Exit(1); } Console.WriteLine("done"); Console.WriteLine(" [*] Example is completed. Press any key to exit..."); Console.ReadLine(); }
public void BucketSamples() { { #region ListBuckets Sample // Create a client AmazonS3Client client = new AmazonS3Client(); // Issue call ListBucketsResponse response = client.ListBuckets(); // View response data Console.WriteLine("Buckets owner - {0}", response.Owner.DisplayName); foreach (S3Bucket bucket in response.Buckets) { Console.WriteLine("Bucket {0}, Created on {1}", bucket.BucketName, bucket.CreationDate); } #endregion } { #region BucketPolicy Sample // Create a client AmazonS3Client client = new AmazonS3Client(); // Put sample bucket policy (overwrite an existing policy) string newPolicy = @"{ ""Statement"":[{ ""Sid"":""BasicPerms"", ""Effect"":""Allow"", ""Principal"": ""*"", ""Action"":[""s3:PutObject"",""s3:GetObject""], ""Resource"":[""arn:aws:s3:::samplebucketname/*""] }]}"; PutBucketPolicyRequest putRequest = new PutBucketPolicyRequest { BucketName = "SampleBucket", Policy = newPolicy }; client.PutBucketPolicy(putRequest); // Retrieve current policy GetBucketPolicyRequest getRequest = new GetBucketPolicyRequest { BucketName = "SampleBucket" }; string policy = client.GetBucketPolicy(getRequest).Policy; Console.WriteLine(policy); Debug.Assert(policy.Contains("BasicPerms")); // Delete current policy DeleteBucketPolicyRequest deleteRequest = new DeleteBucketPolicyRequest { BucketName = "SampleBucket" }; client.DeleteBucketPolicy(deleteRequest); // Retrieve current policy and verify that it is null policy = client.GetBucketPolicy(getRequest).Policy; Debug.Assert(policy == null); #endregion } { #region GetBucketLocation Sample // Create a client AmazonS3Client client = new AmazonS3Client(); // Construct request GetBucketLocationRequest request = new GetBucketLocationRequest { BucketName = "SampleBucket" }; // Issue call GetBucketLocationResponse response = client.GetBucketLocation(request); // View response data Console.WriteLine("Bucket location - {0}", response.Location); #endregion } { #region PutBucket Sample // Create a client AmazonS3Client client = new AmazonS3Client(); // Construct request PutBucketRequest request = new PutBucketRequest { BucketName = "SampleBucket", BucketRegion = S3Region.EU, // set region to EU CannedACL = S3CannedACL.PublicRead // make bucket publicly readable }; // Issue call PutBucketResponse response = client.PutBucket(request); #endregion } { #region DeleteBucket Sample 1 // Create a client AmazonS3Client client = new AmazonS3Client(); // Construct request DeleteBucketRequest request = new DeleteBucketRequest { BucketName = "SampleBucket" }; // Issue call DeleteBucketResponse response = client.DeleteBucket(request); #endregion } { #region DeleteBucket Sample 2 // Create a client AmazonS3Client client = new AmazonS3Client(); // List and delete all objects ListObjectsRequest listRequest = new ListObjectsRequest { BucketName = "SampleBucket" }; ListObjectsResponse listResponse; do { // Get a list of objects listResponse = client.ListObjects(listRequest); foreach (S3Object obj in listResponse.S3Objects) { // Delete each object client.DeleteObject(new DeleteObjectRequest { BucketName = "SampleBucket", Key = obj.Key }); } // Set the marker property listRequest.Marker = listResponse.NextMarker; } while (listResponse.IsTruncated); // Construct DeleteBucket request DeleteBucketRequest request = new DeleteBucketRequest { BucketName = "SampleBucket" }; // Issue call DeleteBucketResponse response = client.DeleteBucket(request); #endregion } { #region LifecycleConfiguration Sample // Create a client AmazonS3Client client = new AmazonS3Client(); // Put sample lifecycle configuration (overwrite an existing configuration) LifecycleConfiguration newConfiguration = new LifecycleConfiguration { Rules = new List <LifecycleRule> { // Rule to delete keys with prefix "Test-" after 5 days new LifecycleRule { Prefix = "Test-", Expiration = new LifecycleRuleExpiration { Days = 5 } }, // Rule to delete keys in subdirectory "Logs" after 2 days new LifecycleRule { Prefix = "Logs/", Expiration = new LifecycleRuleExpiration { Days = 2 }, Id = "log-file-removal" } } }; PutLifecycleConfigurationRequest putRequest = new PutLifecycleConfigurationRequest { BucketName = "SampleBucket", Configuration = newConfiguration }; client.PutLifecycleConfiguration(putRequest); // Retrieve current configuration GetLifecycleConfigurationRequest getRequest = new GetLifecycleConfigurationRequest { BucketName = "SampleBucket" }; LifecycleConfiguration configuration = client.GetLifecycleConfiguration(getRequest).Configuration; Console.WriteLine("Configuration contains {0} rules", configuration.Rules.Count); foreach (LifecycleRule rule in configuration.Rules) { Console.WriteLine("Rule"); Console.WriteLine(" Prefix = " + rule.Prefix); Console.WriteLine(" Expiration (days) = " + rule.Expiration.Days); Console.WriteLine(" Id = " + rule.Id); Console.WriteLine(" Status = " + rule.Status); } // Put a new configuration and overwrite the existing configuration configuration.Rules.RemoveAt(0); // remove first rule client.PutLifecycleConfiguration(putRequest); // Delete current configuration DeleteLifecycleConfigurationRequest deleteRequest = new DeleteLifecycleConfigurationRequest { BucketName = "SampleBucket" }; client.DeleteLifecycleConfiguration(deleteRequest); // Retrieve current configuration and verify that it is null configuration = client.GetLifecycleConfiguration(getRequest).Configuration; Debug.Assert(configuration == null); #endregion } }
public void GenerateDatasetTest() { var iamClient = new AmazonIdentityManagementServiceClient(); var snsClient = new AmazonSimpleNotificationServiceClient(); var s3Client = new AmazonS3Client(); string bucketName = null; string topicArn = null; Role role = null; try { bucketName = UtilityMethods.GenerateName("GenerateDatasetTestBucket"); s3Client.PutBucket(bucketName); var roleName = UtilityMethods.GenerateName("GenerateDatasetTestRole"); var policyName = "MarketplacePolicy"; // Create a role with trust policy role = iamClient.CreateRole(new CreateRoleRequest { RoleName = roleName, AssumeRolePolicyDocument = TrustPolicy }).Role; // Set access policy iamClient.PutRolePolicy(new PutRolePolicyRequest { RoleName = roleName, PolicyDocument = AccessPolicy, PolicyName = policyName }); var snsTopicName = UtilityMethods.GenerateName("GenerateDatasetTestTopic"); topicArn = snsClient.CreateTopic(snsTopicName).TopicArn; // Throws an error as this account does not have any reports Utils.AssertExtensions.ExpectException <AmazonAWSMarketplaceCommerceAnalyticsException> (() => Client.GenerateDataSet(new GenerateDataSetRequest { DataSetPublicationDate = DateTime.Now, DataSetType = DataSetType.DailyBusinessFees, DestinationS3BucketName = bucketName, SnsTopicArn = topicArn, RoleNameArn = role.Arn }) ); } finally { s3Client.DeleteBucket(bucketName); if (role != null) { iamClient.DeleteRolePolicy(new DeleteRolePolicyRequest { PolicyName = "MarketplacePolicy", RoleName = role.RoleName }); iamClient.DeleteRole(new DeleteRoleRequest { RoleName = role.RoleName }); } if (topicArn != null) { snsClient.DeleteTopic(topicArn); } } }
public static void Main(string[] args) { System.Net.ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true); // create the AWS S3 client AmazonS3Client s3 = AWSS3Factory.getS3Client(); String bucketName = String.Join("-", AWSS3Factory.S3_BUCKET, DateTime.Now.ToString("yyyyMMddHHmmss")); //********************// // 1. Create a bucket // //********************// Console.Write(string.Format(" [*] Creating bucket '{0}'... ", bucketName)); PutBucketResponse pbRes = s3.PutBucket(bucketName); if (pbRes.HttpStatusCode != System.Net.HttpStatusCode.OK) { Console.WriteLine("fail"); Console.ReadLine(); System.Environment.Exit(1); } Console.WriteLine("done"); //*******************************************// // 2. Enable object versioning on the bucket // //*******************************************// Console.Write(string.Format(" [*] Enabling bucket versioning for bucket '{0}'... ", bucketName)); PutBucketVersioningRequest pvr = new PutBucketVersioningRequest() { BucketName = bucketName, VersioningConfig = new S3BucketVersioningConfig() { Status = VersionStatus.Enabled } }; PutBucketVersioningResponse pvrResponse = s3.PutBucketVersioning(pvr); if (pvrResponse.HttpStatusCode != System.Net.HttpStatusCode.OK) { Console.WriteLine("fail"); Console.ReadLine(); System.Environment.Exit(1); } Console.WriteLine("done"); //************************************// // 3. Create a new object (version 1) // //************************************// String objectKey = "object-" + DateTime.Now.ToString("yyyyMMddHHmmssffff"); Console.Write(string.Format(" [*] Creating a new object with key '{0}'... ", objectKey)); PutObjectRequest poRequest = new PutObjectRequest() { BucketName = bucketName, ContentBody = "Lorem ipsum dolor sit amet, consectetur adipiscing elit...", Key = objectKey }; PutObjectResponse poResponse = s3.PutObject(poRequest); if (poResponse.HttpStatusCode != System.Net.HttpStatusCode.OK) { Console.WriteLine("fail"); Console.ReadLine(); System.Environment.Exit(1); } Console.WriteLine("done"); Console.WriteLine(string.Format(" [x] Object content: '{0}'", poRequest.ContentBody)); //****************************************// // 4. Delete the object (deletion marker) // //****************************************// Console.Write(string.Format(" [*] Deleting object with key '{0}' (adding a deletion marker)... ", objectKey)); DeleteObjectRequest doRequest = new DeleteObjectRequest() { BucketName = bucketName, Key = objectKey }; DeleteObjectResponse doResponse = s3.DeleteObject(doRequest); if (doResponse.HttpStatusCode != System.Net.HttpStatusCode.NoContent || doResponse.DeleteMarker != "true") { Console.WriteLine("fail"); Console.ReadLine(); System.Environment.Exit(1); } Console.WriteLine("done"); //*************************************************// // 5. Try to get the object (expect 404 Not Found) // //*************************************************// Console.Write(string.Format(" [*] Trying to read object with key '{0}' (expecting 404 Not Found)... ", objectKey)); GetObjectRequest goRequest = new GetObjectRequest() { BucketName = bucketName, Key = objectKey, }; try { // should throw an exception as the object is marked as deleted s3.GetObject(goRequest); Console.WriteLine("fail"); Console.ReadLine(); System.Environment.Exit(1); } catch (AmazonS3Exception e) { if (e.StatusCode != System.Net.HttpStatusCode.NotFound) { Console.WriteLine("fail"); Console.ReadLine(); System.Environment.Exit(1); } } Console.WriteLine("done (404 Not Found)"); //*************************************************************************// // 6. List the object versions and get the version ID of the first version // //*************************************************************************// Console.WriteLine(string.Format(" [*] Listing object versions for bucket '{0}' and getting version ID to restore... ", bucketName)); ListVersionsResponse lvResponse = s3.ListVersions(bucketName); if (lvResponse.HttpStatusCode != System.Net.HttpStatusCode.OK) { Console.WriteLine("fail"); Console.ReadLine(); System.Environment.Exit(1); } String restoreVersion = String.Empty; foreach (S3ObjectVersion version in lvResponse.Versions) { if (version.Key != objectKey) { // filtering out other objects continue; } Console.WriteLine(string.Format(" [x] -> Object key: {0}", version.Key)); Console.WriteLine(string.Format(" [x] VersionId: {0}", version.VersionId)); Console.WriteLine(string.Format(" [x] IsDeleteMarker: {0}", version.IsDeleteMarker)); Console.WriteLine(string.Format(" [x] LastModified: {0}", version.LastModified)); if (!version.IsDeleteMarker) { restoreVersion = version.VersionId; } } if (restoreVersion.Length == 0) { Console.WriteLine(" [*] Could not find a version to restore, exiting..."); Console.ReadLine(); System.Environment.Exit(1); } //******************************************************************// // 7. Restore the first version using a server-side copy operation. // //******************************************************************// Console.Write(string.Format(" [*] Restoring object version ID '{0}' (server-side copy)... ", restoreVersion)); CopyObjectRequest coRequest = new CopyObjectRequest() { SourceBucket = bucketName, SourceKey = objectKey, SourceVersionId = restoreVersion, DestinationBucket = bucketName, DestinationKey = objectKey }; CopyObjectResponse coResponse = s3.CopyObject(coRequest); if (coResponse.HttpStatusCode != System.Net.HttpStatusCode.OK) { Console.WriteLine("fail"); Console.ReadLine(); System.Environment.Exit(1); } Console.WriteLine("done"); //************************************************************// // 8. Verify that the object can now be successfully obtained // //************************************************************// Console.Write(string.Format(" [*] Trying to read object '{0}'... ", objectKey)); GetObjectResponse goResponse = s3.GetObject(goRequest); if (goResponse.HttpStatusCode != System.Net.HttpStatusCode.OK || goResponse.ContentLength != poRequest.ContentBody.Length) { Console.WriteLine("fail"); Console.ReadLine(); System.Environment.Exit(1); } Console.WriteLine("done"); String responseBody = ""; using (Stream responseStream = goResponse.ResponseStream) using (StreamReader reader = new StreamReader(responseStream)) { responseBody = reader.ReadToEnd(); } Console.WriteLine(string.Format(" [x] Object '{0}' successfully restored. New VersionId: '{1}'. Content: '{2}'", goResponse.Key, goResponse.VersionId, responseBody)); //*******************************************// // 9. Permanently delete the object versions // //*******************************************// Console.Write(" [*] Permanently deleting all object versions... "); ListVersionsResponse lv2Response = s3.ListVersions(bucketName); if (lv2Response.HttpStatusCode != System.Net.HttpStatusCode.OK) { Console.WriteLine("fail"); Console.ReadLine(); System.Environment.Exit(1); } foreach (S3ObjectVersion version in lv2Response.Versions) { DeleteObjectRequest do2Request = new DeleteObjectRequest() { BucketName = bucketName, Key = version.Key, VersionId = version.VersionId }; DeleteObjectResponse do2Response = s3.DeleteObject(do2Request); if (do2Response.HttpStatusCode != System.Net.HttpStatusCode.NoContent) { Console.WriteLine("fail"); Console.ReadLine(); System.Environment.Exit(1); } } Console.WriteLine("done"); //***********************// // 10. Delete the bucket // //***********************// Console.Write(String.Format(" [*] Deleting bucket '{0}' (sleeping 5 seconds)... ", bucketName)); System.Threading.Thread.Sleep(5000); DeleteBucketResponse dbRes = s3.DeleteBucket(bucketName); if (dbRes.HttpStatusCode != System.Net.HttpStatusCode.NoContent) { Console.WriteLine("fail"); Console.ReadLine(); System.Environment.Exit(1); } Console.WriteLine("done"); Console.WriteLine(" [*] Example is completed. Press any key to exit..."); Console.ReadLine(); }
public void DeleteBucket(string bucketName) { client.DeleteBucket(bucketName); }
public static void Main(string[] args) { // create the AWS S3 client AmazonS3Client s3 = AWSS3Factory.getS3Client(); String bucketName = String.Join("-", AWSS3Factory.S3_BUCKET, DateTime.Now.ToString("yyyyMMddHHmmss")); //********************// // 1. Create a bucket // //********************// Console.Write(string.Format(" [*] Creating bucket '{0}'... ", bucketName)); PutBucketResponse pbRes = s3.PutBucket(bucketName); if (pbRes.HttpStatusCode != System.Net.HttpStatusCode.OK) { Console.WriteLine("fail"); Console.ReadLine(); System.Environment.Exit(1); } Console.WriteLine("done"); //*******************************************// // 2. Get current bucket versioning status // //*******************************************// Console.Write(string.Format(" [*] Getting bucket versioning status for bucket '{0}'... ", bucketName)); GetBucketVersioningRequest gvr = new GetBucketVersioningRequest() { BucketName = bucketName }; GetBucketVersioningResponse gvrResponse = s3.GetBucketVersioning(gvr); Console.Write(string.Format("status: {0}", gvrResponse.VersioningConfig.Status)); //*******************************************// // 3. Enable object versioning on the bucket // //*******************************************// // enabled versioning if not yet enabled if (gvrResponse.VersioningConfig.Status != VersionStatus.Enabled) { Console.Write(string.Format(" [*] Enabling bucket versioning for bucket '{0}'... ", bucketName)); PutBucketVersioningRequest pvr = new PutBucketVersioningRequest() { BucketName = bucketName, VersioningConfig = new S3BucketVersioningConfig() { Status = VersionStatus.Enabled } }; PutBucketVersioningResponse pvrResponse = s3.PutBucketVersioning(pvr); if (pvrResponse.HttpStatusCode != System.Net.HttpStatusCode.OK) { Console.WriteLine("fail"); Console.ReadLine(); System.Environment.Exit(1); } Console.WriteLine("done"); } //***********************************************************************// // 4. Upload three object with three versions each (Total of 9 versions) // //***********************************************************************// Console.Write(string.Format(" [*] Uploading 3 objects with 3 versions each to bucket '{0}'... ", bucketName)); for (int i = 0; i < 3; i++) { string objectKey = String.Format("object-{0}", i); for (int j = 0; j < 3; j++) { string objectContent = String.Format("This is object {0}, revision {1}", i, j); PutObjectRequest poRequest = new PutObjectRequest() { BucketName = bucketName, Key = objectKey, ContentBody = objectContent }; PutObjectResponse poResponse = s3.PutObject(poRequest); if (poResponse.HttpStatusCode != System.Net.HttpStatusCode.OK) { Console.WriteLine("fail"); Console.ReadLine(); System.Environment.Exit(1); } Console.Write("."); } } Console.WriteLine("done"); //*******************************************// // 5. List the object versions in the bucket // //*******************************************// Console.WriteLine(" [*] Listing object versions..."); ListVersionsRequest request = new ListVersionsRequest() { BucketName = bucketName, // You can optionally specify key name prefix in the request // if you want list of object versions of a specific object. // For this example we limit response to return list of 2 versions. MaxKeys = 2 }; bool moreRecords = true; while (moreRecords) { ListVersionsResponse response = s3.ListVersions(request); foreach (S3ObjectVersion version in response.Versions) { Console.WriteLine(string.Format(" [x] -> Object key: {0}", version.Key)); Console.WriteLine(string.Format(" [x] VersionId: {0}", version.VersionId)); Console.WriteLine(string.Format(" [x] IsDeleteMarker: {0}", version.IsDeleteMarker)); Console.WriteLine(string.Format(" [x] LastModified: {0}", version.LastModified)); } // If response is truncated, set the marker to get the next // set of keys. if (response.IsTruncated) { request.KeyMarker = response.NextKeyMarker; request.VersionIdMarker = response.NextVersionIdMarker; } else { moreRecords = false; } Console.WriteLine(string.Format(" [x] More records? {0}", moreRecords)); } //*******************************************// // 6. Permanently delete the object versions // //*******************************************// Console.Write(" [*] Permanently deleting all object versions... "); ListVersionsResponse lv2Response = s3.ListVersions(bucketName); if (lv2Response.HttpStatusCode != System.Net.HttpStatusCode.OK) { Console.WriteLine("fail"); Console.ReadLine(); System.Environment.Exit(1); } foreach (S3ObjectVersion version in lv2Response.Versions) { DeleteObjectRequest do2Request = new DeleteObjectRequest() { BucketName = bucketName, Key = version.Key, VersionId = version.VersionId }; DeleteObjectResponse do2Response = s3.DeleteObject(do2Request); if (do2Response.HttpStatusCode != System.Net.HttpStatusCode.NoContent) { Console.WriteLine("fail"); Console.ReadLine(); System.Environment.Exit(1); } } Console.WriteLine("done"); //***********************// // 7. Delete the bucket // //***********************// Console.Write(String.Format(" [*] Deleting bucket '{0}' (sleeping 5 seconds)... ", bucketName)); System.Threading.Thread.Sleep(5000); DeleteBucketResponse dbRes = s3.DeleteBucket(bucketName); if (dbRes.HttpStatusCode != System.Net.HttpStatusCode.NoContent) { Console.WriteLine("fail"); Console.ReadLine(); System.Environment.Exit(1); } Console.WriteLine("done"); Console.WriteLine(" [*] Example is completed. Press any key to exit..."); Console.ReadLine(); }
public static void Main(string[] args) { // create the AWS S3 client AmazonS3Client s3 = AWSS3Factory.getS3Client(); String bucketName = String.Join("-", AWSS3Factory.S3_BUCKET, DateTime.Now.ToString("yyyyMMddHHmmss")); //************************// // 1. Create a bucket // //************************// Console.Write(string.Format(" [*] Creating bucket '{0}'... ", bucketName)); PutBucketResponse pbRes = s3.PutBucket(bucketName); if (pbRes.HttpStatusCode != System.Net.HttpStatusCode.OK) { Console.WriteLine("fail"); Console.ReadLine(); System.Environment.Exit(1); } Console.WriteLine("done"); //*************************************// // 2. Configure bucket lifecycle rules // //*************************************// Console.Write(string.Format(" [*] Updating lifecycle configuration for bucket '{0}'... ", bucketName)); LifecycleConfiguration newConfiguration = new LifecycleConfiguration { Rules = new List <LifecycleRule> { // Rule to delete keys with prefix "Test-" after 5 days new LifecycleRule { Prefix = "Test-", Expiration = new LifecycleRuleExpiration { Days = 5 }, Status = LifecycleRuleStatus.Enabled }, // Rule to delete keys in subdirectory "Logs" after 2 days new LifecycleRule { Prefix = "Logs/", Expiration = new LifecycleRuleExpiration { Days = 2 }, Id = "log-file-removal", Status = LifecycleRuleStatus.Enabled } } }; PutLifecycleConfigurationRequest plcReq = new PutLifecycleConfigurationRequest { BucketName = bucketName, Configuration = newConfiguration }; PutLifecycleConfigurationResponse plcRes = s3.PutLifecycleConfiguration(plcReq); if (plcRes.HttpStatusCode != System.Net.HttpStatusCode.OK) { Console.WriteLine("fail"); Console.ReadLine(); System.Environment.Exit(1); } Console.WriteLine("done"); //************************************************// // 3. Retrieve the bucket lifecycle configuration // //************************************************// Console.Write(string.Format(" [*] Retrieving current lifecycle configuration for bucket '{0}'... ", bucketName)); GetLifecycleConfigurationResponse glcRes = s3.GetLifecycleConfiguration(bucketName); if (glcRes.HttpStatusCode != System.Net.HttpStatusCode.OK) { Console.WriteLine("fail"); Console.ReadLine(); System.Environment.Exit(1); } Console.WriteLine("done"); Console.WriteLine(String.Format(" [x] Configuration contains {0} rules", glcRes.Configuration.Rules.Count)); foreach (LifecycleRule rule in glcRes.Configuration.Rules) { Console.WriteLine(" [x] Rule:"); Console.WriteLine(" [x] Prefix = " + rule.Prefix); Console.WriteLine(" [x] Expiration (days) = " + rule.Expiration.Days); Console.WriteLine(" [x] Id = " + rule.Id); Console.WriteLine(" [x] Status = " + rule.Status); } //**********************************************// // 4. Delete the bucket lifecycle configuration // //**********************************************// Console.Write(String.Format(" [*] Deleting current lifecycle configuration for bucket '{0}'... ", bucketName)); DeleteLifecycleConfigurationResponse dlcRes = s3.DeleteLifecycleConfiguration(bucketName); if (dlcRes.HttpStatusCode != System.Net.HttpStatusCode.NoContent) { Console.WriteLine("fail"); Console.ReadLine(); System.Environment.Exit(1); } Console.WriteLine("done"); Console.Write(String.Format(" [*] Verifying current lifecycle rules for bucket '{0}' are empty... ", bucketName)); LifecycleConfiguration configuration = s3.GetLifecycleConfiguration(bucketName).Configuration; if (configuration.Rules.Count != 0) { Console.WriteLine("fail"); Console.ReadLine(); System.Environment.Exit(1); } Console.WriteLine("done"); //************************// // 5. Delete the bucket // //************************// Console.Write(String.Format(" [*] Deleting bucket '{0}'... ", bucketName)); DeleteBucketResponse dbRes = s3.DeleteBucket(bucketName); if (dbRes.HttpStatusCode != System.Net.HttpStatusCode.NoContent) { Console.WriteLine("fail"); Console.ReadLine(); System.Environment.Exit(1); } Console.WriteLine("done"); Console.WriteLine(" [*] Example is completed. Press any key to exit..."); Console.ReadLine(); }