예제 #1
0
        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();
        }
예제 #2
0
        private static void DisplayDeleteBucketResponse(DeleteBucketResponse deleteBucketResponse)
        {
            var writer = Console.Out;

            writer.WriteLine($"{nameof(deleteBucketResponse.HttpStatusCode)}: {deleteBucketResponse.HttpStatusCode}");
            Construction.DisplayResponseMetadata(writer, deleteBucketResponse.ResponseMetadata);
        }
예제 #3
0
        public async Task DeleteBucket(String bucketName)
        {
            DeleteBucketResponse response = null;
            DeleteBucketRequest  request  = new DeleteBucketRequest
            {
                BucketName = bucketName
            };
            bool found = await IfBucketExist(bucketName);

            if (!found)
            {
                Console.WriteLine("bucket not found");
            }
            else
            {
                try
                {
                    response = await client.DeleteBucketAsync(request);

                    if (response.HttpStatusCode.ToString() == "OK")
                    {
                        Console.WriteLine("Bucket " + bucketName + " was deleted");
                    }
                }
                catch (AmazonS3Exception e)
                {
                    Console.WriteLine("Bucket is not empty.. Emptying bucket");
                    Console.WriteLine(e.ToString());
                }
            }
        }
예제 #4
0
        void DeleteBucketWebResponse(object sender, ResponseEventArgs args)
        {
            AmazonS3Exception response = args.Response as AmazonS3Exception;

            S3Common.client.OnS3Response -= DeleteBucketWebResponse;
            if (null != response)
            {
                S3ErrorResponse(response);
                return;
            }

            DeleteBucketResponse deleteBucketResult = args.Response as DeleteBucketResponse;

            if (null != deleteBucketResult)
            {
                if (!string.IsNullOrEmpty(deleteBucketResult.AmazonId2) &&
                    (!string.IsNullOrEmpty(deleteBucketResult.RequestId)))
                {
                    this.Dispatcher.BeginInvoke(() =>
                    {
                        DeleteBucketText        = string.Format(CultureInfo.InvariantCulture, "{0} bucket deleted Successfully", SelectedBucketName);
                        this.BucketNameSelected = false;
                    });
                }
            }
            else
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    DeleteBucketText        = string.Format(CultureInfo.InvariantCulture, "Unsuccessful deletetion of Bucket: {0}", SelectedBucketName);
                    this.BucketNameSelected = false;
                });
            }
        }
예제 #5
0
        public async Task <IActionResult> Remove(int InputID)
        {
            LogInput retrieved = await _logContext.LogInputs.FindAsync(InputID);

            if (retrieved == null)
            {
                return(StatusCode(404));
            }
            DeleteDeliveryStreamResponse deleteDeliveryStreamResponse = await _FirehoseClient.DeleteDeliveryStreamAsync(new DeleteDeliveryStreamRequest
            {
                DeliveryStreamName = retrieved.FirehoseStreamName
            });

            await _LambdaClient.RemovePermissionAsync(new RemovePermissionRequest
            {
                FunctionName = Environment.GetEnvironmentVariable("LAMBDA_FUNCTION_NAME"),
                StatementId  = "ID-" + retrieved.LinkedS3Bucket.ID
            });

            DeleteBucketResponse deleteBucketResponse = await _S3Client.DeleteBucketAsync(new DeleteBucketRequest
            {
                BucketName      = retrieved.LinkedS3Bucket.Name,
                UseClientRegion = true,
            });

            _logContext.LogInputs.Remove(retrieved);
            await _logContext.SaveChangesAsync();

            TempData["Alert"]   = "Success";
            TempData["Message"] = "Log Input " + retrieved.Name + " deleted successfully!";
            return(RedirectToAction("Index"));
        }
        public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context) 
        {
            DeleteBucketResponse response = new DeleteBucketResponse();
            

            return response;
        }
예제 #7
0
파일: Program.cs 프로젝트: Genbox/SimpleS3
    private static async Task Main(string[] args)
    {
        S3Provider s3Provider = UtilityHelper.SelectProvider();

        Console.WriteLine();

        string profileName = UtilityHelper.GetProfileName(s3Provider);

        Console.WriteLine("This program will delete all buckets beginning with 'testbucket-'. Are you sure? Y/N");

        ConsoleKeyInfo key = Console.ReadKey(true);

        if (key.KeyChar != 'y')
        {
            return;
        }

        using ServiceProvider provider = UtilityHelper.CreateSimpleS3(s3Provider, profileName, true);

        IProfile profile = UtilityHelper.GetOrSetupProfile(provider, s3Provider, profileName);

        ISimpleClient client = provider.GetRequiredService <ISimpleClient>();

        await foreach (S3Bucket bucket in ListAllBucketsAsync(client))
        {
            if (!UtilityHelper.IsTestBucket(bucket.BucketName, profile) && !UtilityHelper.IsTemporaryBucket(bucket.BucketName))
            {
                continue;
            }

            Console.Write(bucket.BucketName);

            int errors = await UtilityHelper.ForceDeleteBucketAsync(s3Provider, client, bucket.BucketName);

            if (errors == 0)
            {
                Console.Write(" [x] emptied ");

                DeleteBucketResponse delBucketResp = await client.DeleteBucketAsync(bucket.BucketName).ConfigureAwait(false);

                if (delBucketResp.IsSuccess)
                {
                    Console.Write("[x] deleted");
                }
                else
                {
                    Console.Write("[ ] deleted");
                }
            }
            else
            {
                Console.Write(" [ ] emptied [ ] deleted");
            }

            Console.WriteLine();
        }
    }
예제 #8
0
        /// <summary>
        /// Unmarshaller the response from the service to the response class.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
        {
            DeleteBucketResponse response = new DeleteBucketResponse();

            context.Read();
            int targetDepth = context.CurrentDepth;

            while (context.ReadAtDepth(targetDepth))
            {
                if (context.TestExpression("operations", targetDepth))
                {
                    var unmarshaller = new ListUnmarshaller <Operation, OperationUnmarshaller>(OperationUnmarshaller.Instance);
                    response.Operations = unmarshaller.Unmarshall(context);
                    continue;
                }
            }

            return(response);
        }
예제 #9
0
        public async Task DeleteBucket()
        {
            string tempBucketName = "testbucket-" + Guid.NewGuid();

            DeleteBucketResponse deleteResp1 = await BucketClient.DeleteBucketAsync(tempBucketName).ConfigureAwait(false);

            Assert.False(deleteResp1.IsSuccess);
            Assert.Equal(ErrorCode.NoSuchBucket, deleteResp1.Error?.Code);

            await BucketClient.CreateBucketAsync(tempBucketName).ConfigureAwait(false);

            DeleteBucketResponse deleteResp2 = await BucketClient.DeleteBucketAsync(tempBucketName).ConfigureAwait(false);

            Assert.True(deleteResp2.IsSuccess);
            Assert.Equal(204, deleteResp2.StatusCode);

            ListObjectsResponse listResp = await ObjectClient.ListObjectsAsync(tempBucketName).ConfigureAwait(false);

            Assert.False(listResp.IsSuccess);
            Assert.Equal(404, listResp.StatusCode);
        }
예제 #10
0
    public async Task DeleteBucket(S3Provider provider, string _, ISimpleClient client)
    {
        string tempBucketName = GetTemporaryBucket();

        DeleteBucketResponse deleteResp1 = await client.DeleteBucketAsync(tempBucketName).ConfigureAwait(false);

        Assert.False(deleteResp1.IsSuccess);
        Assert.Equal(ErrorCode.NoSuchBucket, deleteResp1.Error?.Code);

        await client.CreateBucketAsync(tempBucketName).ConfigureAwait(false);

        DeleteBucketResponse deleteResp2 = await client.DeleteBucketAsync(tempBucketName).ConfigureAwait(false);

        Assert.True(deleteResp2.IsSuccess);
        Assert.Equal(204, deleteResp2.StatusCode);

        ListObjectsResponse listResp = await client.ListObjectsAsync(tempBucketName).ConfigureAwait(false);

        Assert.False(listResp.IsSuccess);
        Assert.Equal(404, listResp.StatusCode);
    }
예제 #11
0
        public async Task DeleteBucket()
        {
            string tempBucketName = "testbucket-" + Guid.NewGuid();

            DeleteBucketResponse delete1 = await BucketClient.DeleteBucketAsync(tempBucketName).ConfigureAwait(false);

            Assert.False(delete1.IsSuccess);
            Assert.Equal(ErrorCode.NoSuchBucket, delete1.Error.Code);

            await BucketClient.PutBucketAsync(tempBucketName, request => request.Region = Config.Region).ConfigureAwait(false);

            DeleteBucketResponse delete2 = await BucketClient.DeleteBucketAsync(tempBucketName).ConfigureAwait(false);

            Assert.True(delete2.IsSuccess);
            Assert.Equal(204, delete2.StatusCode);

            GetBucketResponse resp = await BucketClient.GetBucketAsync(tempBucketName).ConfigureAwait(false);

            Assert.False(resp.IsSuccess);
            Assert.Equal(404, resp.StatusCode);
        }
예제 #12
0
        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);
            }
        }
예제 #13
0
        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 async Task <IActionResult> Delete(string bucketName)
        {
            DeleteBucketResponse result = await _s3Client.DeleteBucketAsync(bucketName);

            return(StatusCode((int)result.HttpStatusCode));
        }
예제 #15
0
        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);
            }
        }
예제 #16
0
        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();
        }
예제 #17
0
        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();
        }
예제 #18
0
        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();
        }