Ejemplo n.º 1
0
        public static void loggingSerial()
        {
            System.Console.WriteLine("\nhello,Logging!!");
            NameValueCollection appConfig = ConfigurationManager.AppSettings;

            AmazonS3 s3Client = AWSClientFactory.CreateAmazonS3Client(appConfig["AWSAccessKey"], appConfig["AWSSecretKey"]);
            String bucketName = "chttest1";
            String logBucketName = "chttest2";

            //PutBucket
            System.Console.WriteLine("PutBucket: {0} + {1}\n", bucketName,logBucketName);
            s3Client.PutBucket(new PutBucketRequest().WithBucketName(bucketName));
            s3Client.PutBucket(new PutBucketRequest().WithBucketName(logBucketName));

            //PutBucketACL for logDelivery user
            SetACLRequest aclRequest = new SetACLRequest();
            aclRequest.WithBucketName(logBucketName);
            aclRequest.WithCannedACL(S3CannedACL.LogDeliveryWrite);
            SetACLResponse setACLResult = s3Client.SetACL(aclRequest);
            System.Console.WriteLine("SetBucketACL, requestID:{0}\n",setACLResult.RequestId);

            //PutBucketLogging
            S3BucketLoggingConfig config = new S3BucketLoggingConfig();
            config.WithTargetBucketName(logBucketName);
            config.WithTargetPrefix("log-prefix");
            EnableBucketLoggingResponse setLoggingResult = s3Client.EnableBucketLogging(new EnableBucketLoggingRequest().WithBucketName(bucketName).WithLoggingConfig(config));
            System.Console.WriteLine("SetBucketLogging, requestID:{0}\n", setLoggingResult.RequestId);

            //GetBucketLogging
            GetBucketLoggingResponse getLoggingResult = s3Client.GetBucketLogging(new GetBucketLoggingRequest().WithBucketName(bucketName));
            System.Console.WriteLine("GetBucketLogging:\n {0}\n", getLoggingResult.ResponseXml);

            //jerry add
            S3BucketLoggingConfig config2 = new S3BucketLoggingConfig();
            config2.WithTargetBucketName(logBucketName);
            config2.WithTargetPrefix("log-prefix");

            S3Grant grant = new  S3Grant();
            S3Grantee grantee = new S3Grantee();

            grantee.WithCanonicalUser("262ab9144f28c47d5f65ad45d5a4930a6547e12c175762cb14dbae95ec7c0680", "HNJERRY");
            grant.WithGrantee(grantee);
            //grant_list.Add(grant);
            config2.AddGrant(grantee, S3Permission.FULL_CONTROL);
            //config2.WithGrants(grant_list);
            EnableBucketLoggingResponse setLoggingResult2 = s3Client.EnableBucketLogging(new EnableBucketLoggingRequest().WithBucketName(bucketName).WithLoggingConfig(config2));
            System.Console.WriteLine("SetBucketLogging, requestID:{0}\n", setLoggingResult.RequestId);

            GetBucketLoggingResponse getLoggingResult2 = s3Client.GetBucketLogging(new GetBucketLoggingRequest().WithBucketName(bucketName));
            System.Console.WriteLine("GetBucketLogging:\n {0}\n", getLoggingResult2.ResponseXml);
            //jerry add end

            //DeleteBucket
            System.Console.WriteLine("Delete Bucket!");
            s3Client.DeleteBucket(new DeleteBucketRequest().WithBucketName(bucketName));
            s3Client.DeleteBucket(new DeleteBucketRequest().WithBucketName(logBucketName));
            System.Console.WriteLine("END!");
        }
Ejemplo n.º 2
0
 protected override void ProcessRecord()
 {
     AmazonS3 client = base.GetClient();
     Amazon.S3.Model.SetACLRequest request = new Amazon.S3.Model.SetACLRequest();
     request.BucketName = this._BucketName;
     request.Key = this._Key;
     request.VersionId = this._VersionId;
     Amazon.S3.Model.SetACLResponse response = client.SetACL(request);
 }
        /// <summary>
        /// Sets the storage class for the S3 Object's Version to the value
        /// specified.
        /// </summary>
        /// <param name="bucketName">The name of the bucket in which the key is stored</param>
        /// <param name="key">The key of the S3 Object whose storage class needs changing</param>
        /// <param name="version">The version of the S3 Object whose storage class needs changing</param>
        /// <param name="sClass">The new Storage Class for the object</param>
        /// <param name="s3Client">The Amazon S3 Client to use for S3 specific operations.</param>
        /// <seealso cref="T:Amazon.S3.Model.S3StorageClass"/>
        public static void SetObjectStorageClass(string bucketName, string key, string version, S3StorageClass sClass, AmazonS3 s3Client)
        {
            if (sClass > S3StorageClass.ReducedRedundancy ||
                sClass < S3StorageClass.Standard)
            {
                throw new ArgumentException("Invalid value specified for storage class.");
            }

            if (null == s3Client)
            {
                throw new ArgumentNullException("s3Client", "Please specify an S3 Client to make service requests.");
            }

            // Get the existing ACL of the object
            GetACLRequest getACLRequest = new GetACLRequest();
            getACLRequest.BucketName = bucketName;
            getACLRequest.Key = key;
            if(version != null)
                getACLRequest.VersionId = version;
            GetACLResponse getACLResponse = s3Client.GetACL(getACLRequest);

            // Set the storage class on the object
            CopyObjectRequest copyRequest = new CopyObjectRequest();
            copyRequest.SourceBucket = copyRequest.DestinationBucket = bucketName;
            copyRequest.SourceKey = copyRequest.DestinationKey = key;
            if (version != null)
                copyRequest.SourceVersionId = version;
            copyRequest.StorageClass = sClass;
            // The copyRequest's Metadata directive is COPY by default
            CopyObjectResponse copyResponse = s3Client.CopyObject(copyRequest);

            // Set the object's original ACL back onto it because a COPY
            // operation resets the ACL on the destination object.
            SetACLRequest setACLRequest = new SetACLRequest();
            setACLRequest.BucketName = bucketName;
            setACLRequest.Key = key;
            if (version != null)
                setACLRequest.VersionId = copyResponse.VersionId;
            setACLRequest.ACL = getACLResponse.AccessControlList;
            s3Client.SetACL(setACLRequest);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Sets the ACL
        /// </summary>
        /// <param name="bucketName"></param>
        /// <param name="cannedACL">ACL to use, AuthenticatedRead, BucketOwnerFullControl, BucketOwnerRead, NoACL, Private, PublicRead, PublicReadWrite</param>
        public void SetAcl(string bucketName, string cannedACL, string key)
        {
            var request = new SetACLRequest
                              {
                                  BucketName = bucketName,
                                  CannedACL = (S3CannedACL)Enum.Parse(typeof(S3CannedACL), cannedACL),
                                  Key = key
                              };

            Client.SetACL(request);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Sets up the request needed to make an exact copy of the object leaving the parent method
        /// the ability to change just the attribute being requested to change.
        /// </summary>
        /// <param name="bucketName"></param>
        /// <param name="key"></param>
        /// <param name="version"></param>
        /// <param name="s3Client"></param>
        /// <param name="copyRequest"></param>
        /// <param name="setACLRequest"></param>
        static void SetupForObjectModification(string bucketName, string key, string version, AmazonS3 s3Client,
            out CopyObjectRequest copyRequest, out SetACLRequest setACLRequest)
        {
            // Get the existing ACL of the object
            GetACLRequest getACLRequest = new GetACLRequest();
            getACLRequest.BucketName = bucketName;
            getACLRequest.Key = key;
            if (version != null)
                getACLRequest.VersionId = version;
            GetACLResponse getACLResponse = s3Client.GetACL(getACLRequest);

            // Set the object's original ACL back onto it because a COPY
            // operation resets the ACL on the destination object.
            setACLRequest = new SetACLRequest();
            setACLRequest.BucketName = bucketName;
            setACLRequest.Key = key;
            setACLRequest.ACL = getACLResponse.AccessControlList;

            ListObjectsResponse listObjectResponse = s3Client.ListObjects(new ListObjectsRequest()
                .WithBucketName(bucketName)
                .WithPrefix(key)
                .WithMaxKeys(1));

            if (listObjectResponse.S3Objects.Count != 1)
            {
                throw new ArgumentNullException("No object exists with this bucket name and key.");
            }

            GetObjectMetadataRequest getMetaRequest = new GetObjectMetadataRequest()
            {
                BucketName = bucketName,
                Key = key
            };
            GetObjectMetadataResponse getMetaResponse = s3Client.GetObjectMetadata(getMetaRequest);

            // Set the storage class on the object
            copyRequest = new CopyObjectRequest();
            copyRequest.SourceBucket = copyRequest.DestinationBucket = bucketName;
            copyRequest.SourceKey = copyRequest.DestinationKey = key;
            copyRequest.StorageClass = listObjectResponse.S3Objects[0].StorageClass == "STANDARD" ? S3StorageClass.Standard : S3StorageClass.ReducedRedundancy;
            if (version != null)
                copyRequest.SourceVersionId = version;

            copyRequest.WebsiteRedirectLocation = getMetaResponse.WebsiteRedirectLocation;
            copyRequest.ServerSideEncryptionMethod = getMetaResponse.ServerSideEncryptionMethod;
        }
Ejemplo n.º 6
0
        public static void ACLSerial(String filePath)
        {
            System.Console.WriteLine("\nhello,ACL!!");
            NameValueCollection appConfig = ConfigurationManager.AppSettings;

            AmazonS3 s3Client = AWSClientFactory.CreateAmazonS3Client(appConfig["AWSAccessKey"], appConfig["AWSSecretKey"]);
            String bucketName = "chutest";
            String objectName = "hello";
            //versioning test
            String vbucketName = "netversion";

            //**********************************************************************************************************************************************************
            // Set Version test 環境,目前新增一專用 bucket = netversion,內有兩筆 Object 資訊(Object 已刪除,帶有 delete marker),為了測試方便,此環境不共用也不刪除
            // 若於佈板後刪除環境,請預先建立環境,執行132~150行程式
            //**********************************************************************************************************************************************************

            //PutBucket
            /*    System.Console.WriteLine("PutBucket-version: {0}\n", vbucketName);
                s3Client.PutBucket(new PutBucketRequest().WithBucketName(vbucketName));

                //PutBucketVersioning
                SetBucketVersioningResponse putVersioningResult = s3Client.SetBucketVersioning(new SetBucketVersioningRequest().WithBucketName(vbucketName).WithVersioningConfig(new S3BucketVersioningConfig().WithStatus("Enabled")));
                System.Console.WriteLine("PutBucketVersioning, requestID:{0}\n", putVersioningResult.RequestId);

                //PutObject
                System.Console.WriteLine("PutObject!");
                PutObjectRequest objectVersionRequest = new PutObjectRequest();
                objectVersionRequest.WithBucketName(vbucketName);
                objectVersionRequest.WithKey(objectName);
                objectVersionRequest.WithFilePath(filePath);
                PutObjectResponse objectVersionResult = s3Client.PutObject(objectVersionRequest);
                System.Console.WriteLine("Uploaded Object Etag: {0}\n", objectVersionResult.ETag);

                //DeleteObject
                System.Console.WriteLine("Delete Object!");
                s3Client.DeleteObject(new DeleteObjectRequest().WithBucketName(vbucketName).WithKey(objectName));
            */

            //PutBucket
            System.Console.WriteLine("PutBucket: {0}\n", bucketName);
            s3Client.PutBucket(new PutBucketRequest().WithBucketName(bucketName));

            //PutObject
            System.Console.WriteLine("PutObject!");
            PutObjectRequest request = new PutObjectRequest();
            request.WithBucketName(bucketName);
            request.WithKey(objectName);
            request.WithFilePath(filePath);
            PutObjectResponse PutResult = s3Client.PutObject(request);
            System.Console.WriteLine("Uploaded Object Etag: {0}\n", PutResult.ETag);

            //PutBucketACL
            SetACLRequest aclRequest = new SetACLRequest();
            S3AccessControlList aclConfig = new S3AccessControlList();
            aclConfig.WithOwner(new Owner().WithDisplayName("hrchu").WithId("canonicalidhrchu"));
            aclConfig.WithGrants(new S3Grant().WithGrantee(new S3Grantee().WithCanonicalUser("canonicalidhrchu","hrchu")).WithPermission(S3Permission.FULL_CONTROL));
            aclConfig.WithGrants(new S3Grant().WithGrantee(new S3Grantee().WithCanonicalUser("canonicalidannyren", "annyren")).WithPermission(S3Permission.READ_ACP));

            aclRequest.WithBucketName(bucketName);
            aclRequest.WithACL(aclConfig);

            SetACLResponse putBucketACLResult = s3Client.SetACL(aclRequest);
            System.Console.WriteLine("\nPutBucketACL, requestID:{0}",putBucketACLResult.RequestId);

            //GetBucketACL
            GetACLResponse getBucketACLResult = s3Client.GetACL(new GetACLRequest().WithBucketName(bucketName));
            System.Console.WriteLine("\nGetBucketACL Result:\n{0}\n",getBucketACLResult.ResponseXml);

            //**********************************************************************************************************************************************************

            //PutBucketACL (cannedacl)
            SetACLRequest cannedaclRequest = new SetACLRequest();
            cannedaclRequest.WithBucketName(bucketName);
            cannedaclRequest.WithCannedACL(S3CannedACL.PublicRead);

            SetACLResponse putBucketCannedACLResult = s3Client.SetACL(cannedaclRequest);
            System.Console.WriteLine("\nPutBucketCannedACL, requestID:{0}", putBucketCannedACLResult.RequestId);

            //GetBucketACL
            GetACLResponse getBucketCannedACLResult = s3Client.GetACL(new GetACLRequest().WithBucketName(bucketName));
            System.Console.WriteLine("\nGetBucketCannedACL Result:\n{0}\n", getBucketCannedACLResult.ResponseXml);

            //**********************************************************************************************************************************************************

            //PutObjectACL
            SetACLRequest objectACLRequest = new SetACLRequest();
            S3AccessControlList objectACLConfig = new S3AccessControlList();
            objectACLConfig.WithOwner(new Owner().WithDisplayName("hrchu").WithId("canonicalidhrchu"));
            objectACLConfig.WithGrants(new S3Grant().WithGrantee(new S3Grantee().WithCanonicalUser("canonicalidhrchu", "hrchu")).WithPermission(S3Permission.FULL_CONTROL));
            objectACLConfig.WithGrants(new S3Grant().WithGrantee(new S3Grantee().WithCanonicalUser("canonicalidannyren", "annyren")).WithPermission(S3Permission.WRITE_ACP));

            objectACLRequest.WithBucketName(bucketName);
            objectACLRequest.WithKey(objectName);
            objectACLRequest.WithACL(objectACLConfig);

            SetACLResponse putObjectACLResult = s3Client.SetACL(objectACLRequest);
            System.Console.WriteLine("\nPutObjectACL, requestID:{0}", putObjectACLResult.RequestId);

            //GetObjectACl
            GetACLResponse getObjectACLResult = s3Client.GetACL(new GetACLRequest().WithBucketName(bucketName).WithKey(objectName));
            System.Console.WriteLine("\nGetObjectACL Result:\n{0}\n", getObjectACLResult.ResponseXml);

            //**********************************************************************************************************************************************************

            //PutObjectACL (cannedacl)
            SetACLRequest objectCannedACLRequest = new SetACLRequest();

            objectCannedACLRequest.WithBucketName(bucketName);
            objectCannedACLRequest.WithKey(objectName);
            objectCannedACLRequest.WithCannedACL(S3CannedACL.PublicRead);

            SetACLResponse putObjectCannedACLResult = s3Client.SetACL(objectCannedACLRequest);
            System.Console.WriteLine("\nPutObjectCannedACL, requestID:{0}", putObjectCannedACLResult.RequestId);

            //GetObjectACl
            GetACLResponse getObjectCannedACLResult = s3Client.GetACL(new GetACLRequest().WithBucketName(bucketName).WithKey(objectName));
            System.Console.WriteLine("\nGetObjectCannedACL Result:\n{0}\n", getObjectCannedACLResult.ResponseXml);

            //**********************************************************************************************************************************************************

            //DeleteObject
            System.Console.WriteLine("Delete Object!");
            s3Client.DeleteObject(new DeleteObjectRequest().WithBucketName(bucketName).WithKey(objectName));
            //DeleteBucket
            System.Console.WriteLine("Delete Bucket!");
            s3Client.DeleteBucket(new DeleteBucketRequest().WithBucketName(bucketName));

            //PutObjectACL-version test*********************************************************************************************************************************
            String versionid = "784cca47e2a7423f97dedde6a72f9b3d";

            //PutObjectACL-versionid
              SetACLRequest objectVersionACLRequest = new SetACLRequest();
              S3AccessControlList objectVersionACLConfig = new S3AccessControlList();
              objectVersionACLConfig.WithOwner(new Owner().WithDisplayName("hrchu").WithId("canonicalidhrchu"));
              objectVersionACLConfig.WithGrants(new S3Grant().WithGrantee(new S3Grantee().WithCanonicalUser("canonicalidhrchu", "hrchu")).WithPermission(S3Permission.FULL_CONTROL));
              objectVersionACLConfig.WithGrants(new S3Grant().WithGrantee(new S3Grantee().WithCanonicalUser("canonicalidannyren", "annyren")).WithPermission(S3Permission.WRITE_ACP));

              objectVersionACLRequest.WithBucketName(vbucketName);
              objectVersionACLRequest.WithKey(objectName);
              objectVersionACLRequest.WithVersionId(versionid);
              objectVersionACLRequest.WithACL(objectVersionACLConfig);

              SetACLResponse putObjectVersionACLResult = s3Client.SetACL(objectVersionACLRequest);
              System.Console.WriteLine("\nPutObjectACL Version, requestID:{0}", putObjectVersionACLResult.RequestId);

              //GetObjectACl-versionid
              GetACLResponse getObjectVersionACLResult = s3Client.GetACL(new GetACLRequest().WithBucketName(vbucketName).WithKey(objectName).WithVersionId(versionid));
              System.Console.WriteLine("\nGetObjectACL Version Result:\n{0}\n", getObjectVersionACLResult.ResponseXml);

              //PutObjectACL (cannedacl)-versionid
              SetACLRequest objectVersionCannedACLRequest = new SetACLRequest();

              objectVersionCannedACLRequest.WithBucketName(vbucketName);
              objectVersionCannedACLRequest.WithKey(objectName);
              objectVersionCannedACLRequest.WithVersionId(versionid);
              objectVersionCannedACLRequest.WithCannedACL(S3CannedACL.PublicRead);

              SetACLResponse putObjectVersionCannedACLResult = s3Client.SetACL(objectVersionCannedACLRequest);
              System.Console.WriteLine("\nPutObjectCannedACL Version, requestID:{0}", putObjectVersionCannedACLResult.RequestId);

              //GetObjectACl(cannedacl)-versionid
              GetACLResponse getObjectVersionCannedACLResult = s3Client.GetACL(new GetACLRequest().WithBucketName(vbucketName).WithKey(objectName).WithVersionId(versionid));
              System.Console.WriteLine("\nGetObjectCannedACL Version Result:\n{0}\n", getObjectVersionCannedACLResult.ResponseXml);

            System.Console.WriteLine("END!");
        }
        private void setS3Permission(String bucketName, String key)
        {
            // Get the ACL for the file and retrieve the owner ID (not sure how to get it otherwise).
            GetACLRequest getAclRequest = new GetACLRequest().WithBucketName(bucketName).WithKey(key);
            GetACLResponse aclResponse = s3.GetACL(getAclRequest);
            Owner owner = aclResponse.AccessControlList.Owner;

            // Create a grantee as the MessageGears account
            S3Grantee grantee = new S3Grantee().WithCanonicalUser(properties.MessageGearsAWSCanonicalId, "MessageGears");

            // Grant MessageGears Read-only access
            S3Permission messageGearsPermission = S3Permission.READ;
            S3AccessControlList acl = new S3AccessControlList().WithOwner(owner);
            acl.AddGrant(grantee, messageGearsPermission);

            // Create a new ACL granting the owner full control.
            grantee = new S3Grantee().WithCanonicalUser(owner.Id, "MyAWSId");
            acl.AddGrant(grantee, S3Permission.FULL_CONTROL);
            SetACLRequest aclRequest = new SetACLRequest().WithACL(acl).WithBucketName(bucketName).WithKey(key);
            s3.SetACL(aclRequest);
        }
Ejemplo n.º 8
0
 private void SetAcltoObject(string key)
 {
     try
     {
         var versionsRequest = new ListVersionsRequest
                                   {
                                       BucketName = Utilities.MyConfig.BucketKey,
                                       Prefix = key
                                   };
         var result = _amazons3.ListVersions(versionsRequest);
         foreach (S3ObjectVersion s3ObjectVersion in result.Versions)
         {
             if (!s3ObjectVersion.IsDeleteMarker)
             {
                 try
                 {
                     // Get ACL.
                     var getRequest = new GetACLRequest { BucketName = Utilities.MyConfig.BucketKey, Key = key, VersionId = s3ObjectVersion.VersionId };
                     GetACLResponse getResponse = _amazons3.GetACL(getRequest);
                     if (getResponse.AccessControlList.Grants.Count < 2)
                     {
                         S3AccessControlList acl = getResponse.AccessControlList;
                         getResponse.Dispose();
                         //acl.Grants.Clear();
                         //var grantee0 = new S3Grantee();
                         //grantee0.WithCanonicalUser(acl.Owner.Id, acl.Owner.DisplayName);
                         //acl.AddGrant(grantee0, S3Permission.FULL_CONTROL);
                         var grantee1 = new S3Grantee();
                         grantee1.WithURI("http://acs.amazonaws.com/groups/global/AllUsers");
                         acl.AddGrant(grantee1, S3Permission.READ);
                         var request = new SetACLRequest
                                           {
                                               BucketName = Utilities.MyConfig.BucketKey,
                                               ACL = acl,
                                               Key = key,
                                               VersionId = s3ObjectVersion.VersionId
                                           };
                         SetACLResponse response = _amazons3.SetACL(request);
                         response.Dispose();
                     }
                 }
                 catch (Exception)
                 {
                     // Todo
                     return;
                 }
             }
         }
     }
     catch (Exception)
     {
         return;
     }
 }
Ejemplo n.º 9
0
 public void SetFileToPublic(string key)
 {
     try
     {
         var request = new SetACLRequest();
         request.WithBucketName(this._bucketName).WithKey(key);
         request.CannedACL = S3CannedACL.PublicRead;
         this._client.SetACL(request);
     }
     catch
     {
         // File not found
     }
 }
Ejemplo n.º 10
0
 public void BucketC_SetACLForBucketTest_ForException_WithoutACLList()
 {
     SetACLRequest request = new SetACLRequest { BucketName = _bucketNameForBucketAPIs };
     _client.SetACL(request);
     EnqueueTestComplete();
 }
Ejemplo n.º 11
0
        public void BucketC_SetACLForBucketTest_ForException_WithoutACLOwner()
        {
            S3AccessControlList list = new S3AccessControlList();
            list.AddGrant(new S3Grantee()
            {
                CanonicalUser = new Amazon.S3.Model.Tuple<string, string> { First = CanonicalUserID, Second = "Me" }
            }, S3Permission.FULL_CONTROL);

            SetACLRequest request = new SetACLRequest { BucketName = _bucketNameForBucketAPIs, ACL = list };

            _client.SetACL(request);
            EnqueueTestComplete();
        }
Ejemplo n.º 12
0
        public void BucketC_SetACLForBucketTest()
        {
            bool expectedValue = true;
            bool actualValue = false;
            bool hasCallbackArrived = false;

            S3ResponseEventHandler<object, ResponseEventArgs> handler = null;
            handler = delegate(object sender, ResponseEventArgs args)
            {
                IS3Response result = args.Response;
                //Unhook from event.
                _client.OnS3Response -= handler;
                SetACLResponse response = result as SetACLResponse;
                if (null != response)
                    actualValue = response.IsRequestSuccessful;
                hasCallbackArrived = true;
            };

            _client.OnS3Response += handler;

            S3AccessControlList list = new S3AccessControlList();
            list.AddGrant(new S3Grantee()
            {
                CanonicalUser = new Amazon.S3.Model.Tuple<string, string> { First = CanonicalUserID, Second = "Me" }
            }, S3Permission.FULL_CONTROL);

            list.AddGrant(new S3Grantee()
            {
                URI = "http://acs.amazonaws.com/groups/s3/LogDelivery"
            }, S3Permission.WRITE);

            list.AddGrant(new S3Grantee()
            {
                URI = "http://acs.amazonaws.com/groups/s3/LogDelivery",
            }, S3Permission.READ_ACP);

            list.Owner = new Owner { DisplayName = "Me", Id = CanonicalUserID };

            SetACLRequest request = new SetACLRequest { BucketName = _bucketNameForBucketAPIs, ACL = list };

            _client.SetACL(request);

            EnqueueConditional(() => hasCallbackArrived);
            EnqueueCallback(() => Assert.IsTrue(expectedValue == actualValue,
                string.Format("Expected Value = {0}, Actual Value = {1}", expectedValue, actualValue)));
            EnqueueTestComplete();
        }
Ejemplo n.º 13
0
        public void Test_I_SetObjectACL_With_Invalid_GranteeCanonicalUserID_And_Check_For_Error_Message()
        {
            bool hasCallbackArrived = false;
            string actualValue = string.Empty;
            string expectedValue = "InvalidArgument";
            string invalidGranteeCanonicalUserID = "09876567890"; //For more info on CanonicalUserIDs refer CanonicalUserID variable.

            S3ResponseEventHandler<object, ResponseEventArgs> handler = null;

            handler = delegate(object sender, ResponseEventArgs args)
            {
                IS3Response result = args.Response;
                //Unhook from event.
                _client.OnS3Response -= handler;
                AmazonS3Exception exceptionResponse = result as AmazonS3Exception;

                if (null != exceptionResponse)
                    actualValue = exceptionResponse.ErrorCode;

                hasCallbackArrived = true;
            };

            //Hook to event
            _client.OnS3Response += handler;

            //Create request object.
            S3AccessControlList list = new S3AccessControlList();
            list.AddGrant(new S3Grantee
            {
                CanonicalUser = new Amazon.S3.Model.Tuple<string, string> { First = invalidGranteeCanonicalUserID, Second = "Me" }
            }, S3Permission.FULL_CONTROL);

            list.Owner = new Owner { DisplayName = "Me", Id = CanonicalUserID };
            SetACLRequest request = new SetACLRequest { BucketName = _bucketName, Key = _key, ACL = list };

            _client.SetACL(request);

            EnqueueConditional(() => hasCallbackArrived);
            EnqueueCallback(() => Assert.IsTrue(expectedValue == actualValue));
            EnqueueTestComplete();
        }
Ejemplo n.º 14
0
        public void Test_G_SetObjectACL_And_Check_For_Boolean_Result()
        {
            bool hasCallbackArrived = false;
            bool actualValue = false;
            bool expectedValue = true;

            S3ResponseEventHandler<object, ResponseEventArgs> handler = null;

            handler = delegate(object sender, ResponseEventArgs args)
            {
                IS3Response result = args.Response;
                //Unhook from event.
                _client.OnS3Response -= handler;
                SetACLResponse response = result as SetACLResponse;

                if (null != response)
                    actualValue = response.IsRequestSuccessful;

                hasCallbackArrived = true;
            };

            //Hook to event
            _client.OnS3Response += handler;

            //Create request object.
            S3AccessControlList list = new S3AccessControlList();
            list.AddGrant(new S3Grantee
            {
                CanonicalUser = new Amazon.S3.Model.Tuple<string, string> { First = CanonicalUserID, Second = "Me" }
            }, S3Permission.FULL_CONTROL);

            list.Owner = new Owner { DisplayName = "Me", Id = CanonicalUserID };
            SetACLRequest request = new SetACLRequest { BucketName = _bucketName, Key = _key, ACL = list };

            _client.SetACL(request);

            EnqueueConditional(() => hasCallbackArrived);
            EnqueueCallback(() => Assert.IsTrue(expectedValue == actualValue));
            EnqueueTestComplete();
        }
Ejemplo n.º 15
0
        public static string SaveUploadedFileToAws(string accessKeyID, string secretAccessKey, string existingBucketName, string strFileName, string contentType, System.IO.Stream stream)
        {
            //try
            //{
            TransferUtility fileTransferUtility = new
                                                  TransferUtility(accessKeyID, secretAccessKey);

            //// 1. Upload a file, file name is used as the object key name.
            //fileTransferUtility.Upload(filePath, existingBucketName);
            //Console.WriteLine("Upload 1 completed");

            //// 2. Specify object key name explicitly.
            //fileTransferUtility.Upload(filePath,
            //                          existingBucketName, keyName);
            //Console.WriteLine("Upload 2 completed");

            // 3. Upload data from a type of System.IO.Stream.
            //string keyName =System.IO.Path.GetFileNameWithoutExtension(strFileName) + "_" + Guid.NewGuid() + System.IO.Path.GetExtension(strFileName);
            string keyName = strFileName;

            fileTransferUtility.Upload(stream, existingBucketName, keyName);

            Console.WriteLine("Upload 3 completed");

            //// 4.// Specify advanced settings/options.
            //TransferUtilityUploadRequest fileTransferUtilityRequest =
            //    new TransferUtilityUploadRequest()
            //    .WithBucketName(existingBucketName)
            //    .WithFilePath(filePath)
            //    .WithStorageClass(S3StorageClass.ReducedRedundancy)
            //    .WithMetadata("param1", "Value1")
            //    .WithMetadata("param2", "Value2")
            //    .WithPartSize(6291456) // This is 6 MB.
            //    .WithKey(keyName)
            //    .WithCannedACL(S3CannedACL.PublicRead);
            //fileTransferUtility.Upload(fileTransferUtilityRequest);
            //Console.WriteLine("Upload 4 completed");

            SetACLRequest request = new Amazon.S3.Model.SetACLRequest();

            request.BucketName = existingBucketName;
            request.Key        = keyName;
            request.CannedACL  = S3CannedACL.PublicRead;
            fileTransferUtility.S3Client.SetACL(request);

            //string preSignedURL = fileTransferUtility.S3Client.GetPreSignedURL(new GetPreSignedUrlRequest()
            //{
            //    BucketName = existingBucketName,
            //    Key = keyName,
            //    Expires = System.DateTime.Now.AddDays(1000)
            //});

            //return preSignedURL;

            string seperator = "/";

            existingBucketName = existingBucketName.Trim(seperator.ToCharArray()) + seperator;
            keyName            = keyName.Trim(seperator.ToCharArray());
            return(string.Format("http://s3.amazonaws.com/{0}{1}", existingBucketName, keyName));

            //}
            //catch (AmazonS3Exception s3Exception)
            //{
            //    Console.WriteLine(s3Exception.Message,
            //                      s3Exception.InnerException);
            //}
            //return string.Empty;
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Sets the server side encryption method for the S3 Object's Version to the value
        /// specified.
        /// </summary>
        /// <param name="bucketName">The name of the bucket in which the key is stored</param>
        /// <param name="key">The key of the S3 Object</param>
        /// <param name="version">The version of the S3 Object</param>
        /// <param name="method">The server side encryption method</param>
        /// <param name="s3Client">The Amazon S3 Client to use for S3 specific operations.</param>
        /// <seealso cref="T:Amazon.S3.Model.S3StorageClass"/>
        public static void SetServerSideEncryption(string bucketName, string key, string version, ServerSideEncryptionMethod method, AmazonS3 s3Client)
        {
            if (null == s3Client)
            {
                throw new ArgumentNullException("s3Client", "Please specify an S3 Client to make service requests.");
            }

            // Get the existing ACL of the object
            GetACLRequest getACLRequest = new GetACLRequest();
            getACLRequest.BucketName = bucketName;
            getACLRequest.Key = key;
            if (version != null)
                getACLRequest.VersionId = version;
            GetACLResponse getACLResponse = s3Client.GetACL(getACLRequest);

            ListObjectsResponse listObjectResponse = s3Client.ListObjects(new ListObjectsRequest()
                .WithBucketName(bucketName)
                .WithPrefix(key)
                .WithMaxKeys(1));

            if (listObjectResponse.S3Objects.Count != 1)
            {
                throw new ArgumentNullException("No object exists with this bucket name and key.");
            }

            // Set the storage class on the object
            CopyObjectRequest copyRequest = new CopyObjectRequest();
            copyRequest.SourceBucket = copyRequest.DestinationBucket = bucketName;
            copyRequest.SourceKey = copyRequest.DestinationKey = key;
            copyRequest.StorageClass = listObjectResponse.S3Objects[0].StorageClass == "STANDARD" ? S3StorageClass.Standard : S3StorageClass.ReducedRedundancy;
            if (version != null)
                copyRequest.SourceVersionId = version;

            copyRequest.ServerSideEncryptionMethod = method;
            // The copyRequest's Metadata directive is COPY by default
            CopyObjectResponse copyResponse = s3Client.CopyObject(copyRequest);

            // Set the object's original ACL back onto it because a COPY
            // operation resets the ACL on the destination object.
            SetACLRequest setACLRequest = new SetACLRequest();
            setACLRequest.BucketName = bucketName;
            setACLRequest.Key = key;
            if (version != null)
                setACLRequest.VersionId = copyResponse.VersionId;
            setACLRequest.ACL = getACLResponse.AccessControlList;
            s3Client.SetACL(setACLRequest);
        }