/// <summary>
        /// すべてのバケットを取得する
        /// </summary>
        /// <param name="nameSpaceName"></param>
        /// <param name="compartmentId"></param>
        /// <returns></returns>
        public IEnumerable <BucketInfo> GetAllBuckets(string nameSpaceName, string compartmentId)
        {
            List <BucketInfo> res = new List <BucketInfo>();

            var regions = GetRegions();
            var request = new ListBucketsRequest {
                NamespaceName = nameSpaceName, CompartmentId = compartmentId, Limit = 10
            };

            Parallel.ForEach(regions, region => {
                ObjectStorageClient objectStorageClient = new ObjectStorageClient(ClientConfig);
                objectStorageClient.SetRegion(region.RegionName);
                while (true)
                {
                    var buckets = objectStorageClient.ListBuckets(request);

                    foreach (var item in buckets.Items)
                    {
                        res.Add(new BucketInfo()
                        {
                            Name = item.Name, Region = region.RegionName, Id = item.Id, ModifiedTime = item.TimeCreated
                        });
                    }

                    if (string.IsNullOrEmpty(buckets.OpcNextPage))
                    {
                        break;
                    }

                    request.Page = buckets.OpcNextPage;
                }
            });

            return(res);
        }
        /// <summary>
        /// バケットを取得する
        /// </summary>
        /// <param name="nameSpaceName"></param>
        /// <param name="compartmentId"></param>
        /// <param name="regionName"></param>
        /// <returns></returns>
        public IEnumerable <BucketInfo> GetBuckets(string nameSpaceName, string compartmentId, string regionName)
        {
            List <BucketInfo> res = new List <BucketInfo>();
            var request           = new ListBucketsRequest {
                NamespaceName = nameSpaceName, CompartmentId = compartmentId, Limit = 10
            };

            ObjectStorageClient.SetRegion(regionName);
            while (true)
            {
                var buckets = ObjectStorageClient.ListBuckets(request);

                foreach (var item in buckets.Items)
                {
                    res.Add(new BucketInfo()
                    {
                        Name = item.Name, Region = regionName, Id = item.Id
                    });
                }

                if (string.IsNullOrEmpty(buckets.OpcNextPage))
                {
                    break;
                }

                request.Page = buckets.OpcNextPage;
            }

            return(res);
        }
예제 #3
0
 // 2. List buckets by specified conditions, such as prefix/marker/max-keys.
 public static void ListBucketsByConditions()
 {
     try
     {
         var req = new ListBucketsRequest {
             Prefix = "test", MaxKeys = 3, Marker = "test2"
         };
         var result  = client.ListBuckets(req);
         var buckets = result.Buckets;
         Console.WriteLine("List buckets by page: ");
         Console.WriteLine("Prefix: {0}, MaxKeys: {1},  Marker: {2}, NextMarker:{3}",
                           result.Prefix, result.MaxKeys, result.Marker, result.NextMaker);
         foreach (var bucket in buckets)
         {
             Console.WriteLine("Name:{0}, Location:{1}, Owner:{2}", bucket.Name, bucket.Location, bucket.Owner);
         }
     }
     catch (OssException ex)
     {
         Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                           ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
     }
     catch (Exception ex)
     {
         Console.WriteLine("Failed with error info: {0}", ex.Message);
     }
 }
예제 #4
0
        private static void Populate(ListBucketsRequest request, IDictionary <string, string> parameters)
        {
            if (request.Prefix != null)
            {
                parameters[RequestParameters.PREFIX] = request.Prefix;
            }

            if (request.Marker != null)
            {
                parameters[RequestParameters.MARKER] = request.Marker;
            }

            if (request.MaxKeys.HasValue)
            {
                parameters[RequestParameters.MAX_KEYS] = request.MaxKeys.Value.ToString(CultureInfo.InvariantCulture);
            }

            if (request.Tag != null)
            {
                if (request.Tag.Key != null)
                {
                    parameters[RequestParameters.TAG_KEY] = request.Tag.Key;
                }

                if (request.Tag.Value != null)
                {
                    parameters[RequestParameters.TAG_VALUE] = request.Tag.Value;
                }
            }
        }
예제 #5
0
        public void ListBucketByTagNGTest()
        {
            //only has value
            var tag = new Tag
            {
                Value = "tag3"
            };
            var listRequest = new ListBucketsRequest();

            listRequest.Tag = tag;

            try
            {
                var result = _ossClient.ListBuckets(listRequest);
                Assert.Fail("should not here");
            }
            catch (OssException e)
            {
                Assert.AreEqual(e.ErrorCode, "InvalidArgument");
            }
            catch (Exception e)
            {
                Assert.IsTrue(false, e.Message);
            }
        }
예제 #6
0
        public void TestListBucketsResponseUnmarshallingException200OK()
        {
            Tester.Reset();

            var context = CreateTestContext();
            var request = new ListBucketsRequest();

            ((RequestContext)context.RequestContext).OriginalRequest = request;
            ((RequestContext)context.RequestContext).Request         = new ListBucketsRequestMarshaller().Marshall(request);
            ((RequestContext)context.RequestContext).Unmarshaller    = new ListBucketsResponseUnmarshaller();

            var response = MockWebResponse.CreateFromResource("MalformedResponse.txt")
                           as HttpWebResponse;

            context.ResponseContext.HttpResponse = new HttpWebRequestResponseData(response);

            try
            {
                RuntimePipeline.InvokeSync(context);
                Assert.Fail();
            }
            catch (AmazonUnmarshallingException aue)
            {
                Assert.IsTrue(aue.Message.Contains("HTTP Status Code: 200 OK"));
                Assert.AreEqual(HttpStatusCode.OK, aue.StatusCode);
                Assert.IsNotNull(aue.InnerException);
                Assert.AreEqual("Data at the root level is invalid. Line 1, position 1.", aue.InnerException.Message);
            }
        }
예제 #7
0
        /// <summary>
        /// Validates whether an account's keys are valid credentials.
        /// If successful, it sets DisplayName and Id, and marks it as validated.
        /// </summary>
        /// <param name="account">The account object to validate.</param>
        /// <returns>An account is considered validated if the keys can list its buckets.</returns>
        public static async Task <bool> ValidateAccountAsync(IAccount account, RegionEndpoint regionEndpoint, CancellationToken token)
        {
            if (account is null)
            {
                throw new ArgumentNullException(nameof(account));
            }

            bool isValidated = false;

            using (IAmazonS3 client = new AmazonS3Client(account.GetCredentials(), regionEndpoint))
            {
                try
                {
                    ListBucketsRequest request = new ListBucketsRequest();

                    var response = await RunWithoutCatchAsync <ListBucketsRequest, ListBucketsResponse>(client.ListBucketsAsync, request, token).ConfigureAwait(false);

                    isValidated = true;

                    account.DisplayName = response.Owner.DisplayName;
                    account.Id          = response.Owner.Id;
                    account.IsValidated = true;
                }
                catch (AmazonS3Exception ex)
                    when(ex.InnerException is HttpErrorResponseException inner &&
                         inner.Response.StatusCode == HttpStatusCode.Forbidden)
                    {
                    }
            }

            return(isValidated);
        }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();
            ListBucketsRequest request;

            try
            {
                request = new ListBucketsRequest
                {
                    NamespaceName      = NamespaceName,
                    CompartmentId      = CompartmentId,
                    Limit              = Limit,
                    Page               = Page,
                    Fields             = Fields,
                    OpcClientRequestId = OpcClientRequestId
                };
                IEnumerable <ListBucketsResponse> responses = GetRequestDelegate().Invoke(request);
                foreach (var item in responses)
                {
                    response = item;
                    WriteOutput(response, response.Items, true);
                }
                if (!ParameterSetName.Equals(AllPageSet) && !ParameterSetName.Equals(LimitSet) && response.OpcNextPage != null)
                {
                    WriteWarning("This operation supports pagination and not all resources were returned. Re-run using the -All option to auto paginate and list all resources.");
                }
                FinishProcessing(response);
            }
            catch (Exception ex)
            {
                TerminatingErrorDuringExecution(ex);
            }
        }
예제 #9
0
        /// <summary>
        /// 列出桶
        /// </summary>
        /// <returns></returns>
        public Task <List <Bucket> > ListBucketsAsync()
        {
            ListBucketsRequest request = new ListBucketsRequest()
            {
                IsQueryLocation = true,
            };
            ListBucketsResponse response = _client.ListBuckets(request);
            var buckets = response.Buckets;

            if (buckets == null)
            {
                return(null);
            }
            if (buckets.Count() == 0)
            {
                return(Task.FromResult(new List <Bucket>()));
            }
            var resultList = new List <Bucket>();

            foreach (var item in buckets)
            {
                resultList.Add(new Bucket()
                {
                    Location     = item.Location,
                    Name         = item.BucketName,
                    CreationDate = item.CreationDate?.ToString("yyyy-MM-dd HH:mm:ss"),
                });
            }
            return(Task.FromResult(resultList));
        }
예제 #10
0
        public void TestListBucketsResponseUnmarshallingAsync()
        {
            Tester.Reset();

            var context = CreateAsyncTestContext();
            var request = new ListBucketsRequest();

            ((RequestContext)context.RequestContext).OriginalRequest = request;
            ((RequestContext)context.RequestContext).Request         = new ListBucketsRequestMarshaller().Marshall(request);
            ((RequestContext)context.RequestContext).Unmarshaller    = ListBucketsResponseUnmarshaller.Instance;

            var response = MockWebResponse.CreateFromResource("ListBucketsResponse.txt")
                           as HttpWebResponse;

            context.ResponseContext.HttpResponse = new HttpWebRequestResponseData(response);

            var asyncResult = RuntimePipeline.InvokeAsync(context);

            asyncResult.AsyncWaitHandle.WaitOne();

            Assert.AreEqual(1, Tester.CallCount);
            Assert.IsInstanceOfType(context.ResponseContext.Response, typeof(ListBucketsResponse));

            var listBucketsResponse = context.ResponseContext.Response as ListBucketsResponse;

            Assert.AreEqual(4, listBucketsResponse.Buckets.Count);
        }
예제 #11
0
        protected override void ProcessRecord()
        {
            base.ProcessRecord();
            ListBucketsRequest request;

            try
            {
                request = new ListBucketsRequest
                {
                    NamespaceName      = NamespaceName,
                    CompartmentId      = CompartmentId,
                    Limit              = Limit,
                    Page               = Page,
                    Fields             = Fields,
                    OpcClientRequestId = OpcClientRequestId
                };
                IEnumerable <ListBucketsResponse> responses = GetRequestDelegate().Invoke(request);
                foreach (var item in responses)
                {
                    response = item;
                    WriteOutput(response, response.Items, true);
                }
                FinishProcessing(response);
            }
            catch (Exception ex)
            {
                TerminatingErrorDuringExecution(ex);
            }
        }
예제 #12
0
        public void TestListBucketsResponseUnmarshalling()
        {
            Tester.Reset();

            var context = CreateTestContext();
            var request = new ListBucketsRequest();

            ((RequestContext)context.RequestContext).OriginalRequest = request;
            ((RequestContext)context.RequestContext).Request         = new ListBucketsRequestMarshaller().Marshall(request);
            ((RequestContext)context.RequestContext).Unmarshaller    = ListBucketsResponseUnmarshaller.Instance;

            var response = MockWebResponse.CreateFromResource("ListBucketsResponse.txt")
                           as HttpWebResponse;

            context.ResponseContext.HttpResponse = new HttpWebRequestResponseData(response);

            RuntimePipeline.InvokeSync(context);

            Assert.AreEqual(1, Tester.CallCount);
            Assert.IsInstanceOfType(context.ResponseContext.Response, typeof(ListBucketsResponse));

            var listBucketsResponse = context.ResponseContext.Response as ListBucketsResponse;

            Assert.AreEqual(4, listBucketsResponse.Buckets.Count);
            Assert.AreEqual("-UUNhfhfx0J622sdKihbDfqEvIa94CkVQvcb4AGlNmRbpbInOTYXSA==", listBucketsResponse.ResponseMetadata.Metadata[HeaderKeys.XAmzCloudFrontIdHeader]);
        }
예제 #13
0
        static void Main(string[] args)
        {
            string         accessKey = "AKIAYASBUYUORND23YUN";
            string         secretKey = "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";
            RegionEndpoint region    = RegionEndpoint.APSoutheast2;
            AWSCredentials cred      = new BasicAWSCredentials(accessKey, secretKey);
            IAmazonSecurityTokenService stsClient = new AmazonSecurityTokenServiceClient(cred, region);

            AssumeRoleRequest stsRequest = new AssumeRoleRequest();

            stsRequest.DurationSeconds = 910;
            stsRequest.RoleArn         = "arn:aws:iam::550967231773:role/MyAssumeRole";
            stsRequest.RoleSessionName = "MyAssumeRolesessionFromDotNet";

            AssumeRoleResponse temporaryCred = stsClient.AssumeRoleAsync(stsRequest).Result;

            IAmazonS3 client = new AmazonS3Client(temporaryCred.Credentials, region);

            ListBucketsRequest request = new ListBucketsRequest();

            ListBucketsResponse response = client.ListBucketsAsync(request).Result;

            foreach (S3Bucket b in response.Buckets)
            {
                Console.WriteLine(b.BucketName);
            }

            Console.ReadLine();
        }
 // 2. List buckets by specified conditions, such as prefix/marker/max-keys.
 public static void ListBucketsByConditions()
 {
     try
     {
         var req = new ListBucketsRequest {Prefix = "test", MaxKeys = 3, Marker = "test2"};
         var result = client.ListBuckets(req);
         var buckets = result.Buckets;
         Console.WriteLine("List buckets by page: ");
         Console.WriteLine("Prefix: {0}, MaxKeys: {1},  Marker: {2}, NextMarker:{3}", 
                            result.Prefix, result.MaxKeys, result.Marker, result.NextMaker);
         foreach (var bucket in buckets)
         {
             Console.WriteLine("Name:{0}, Location:{1}, Owner:{2}", bucket.Name, bucket.Location, bucket.Owner);
         }
     }
     catch (OssException ex)
     {
         Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                            ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
     }
     catch (Exception ex)
     {
         Console.WriteLine("Failed with error info: {0}", ex.Message);
     }
 }
예제 #15
0
        public virtual async Task <GetOssContainersResponse> GetListAsync(GetOssContainersRequest request)
        {
            var ossClient = await CreateClientAsync();

            var aliyunRequest = new ListBucketsRequest
            {
                Marker  = request.Marker,
                Prefix  = request.Prefix,
                MaxKeys = request.MaxKeys
            };
            var bucketsResponse = ossClient.ListBuckets(aliyunRequest);

            return(new GetOssContainersResponse(
                       bucketsResponse.Prefix,
                       bucketsResponse.Marker,
                       bucketsResponse.NextMaker,
                       bucketsResponse.MaxKeys ?? 0,
                       bucketsResponse.Buckets
                       .Select(x => new OssContainer(
                                   x.Name,
                                   x.CreationDate,
                                   0L,
                                   x.CreationDate,
                                   new Dictionary <string, string>
            {
                { "Id", x.Owner?.Id },
                { "DisplayName", x.Owner?.DisplayName }
            }))
                       .ToList()));
        }
예제 #16
0
파일: S3.cs 프로젝트: uqayyum/aws_suite
        public List <string> GetAllBuckets(AWS_Credentials credentials)
        {
            if (credentials is null || credentials.AWS_AccessKey is null || credentials.AWS_SecretKey is null || credentials.Region is null)
            {
                throw new CredentialsNotProvidedException();
            }

            List <string> buckets = new List <string>();

            using (AmazonS3Client client = getS3Client(credentials))
            {
                ListBucketsRequest bucketFetchUtility = new
                                                        ListBucketsRequest();

                Task <ListBucketsResponse> bucketsResponse = client.ListBucketsAsync(bucketFetchUtility);
                bucketsResponse.Wait();

                if (bucketsResponse.IsCompleted)
                {
                    foreach (S3Bucket bucket in bucketsResponse.Result.Buckets)
                    {
                        buckets.Add(bucket.BucketName);
                    }
                }
            }
            return(buckets);
        }
 private ListBucketsCommand(IServiceClient client, Uri endpoint, ExecutionContext context,
                            IDeserializer <ServiceResponse, ListBucketsResult> deserializeMethod,
                            ListBucketsRequest request)
     : base(client, endpoint, context, deserializeMethod)
 {
     _request = request;
 }
예제 #18
0
        public void ListBuckets()
        {
            var request = new ListBucketsRequest();

            var response = _s3Client.ListBuckets(request);

            Assert.AreNotEqual(0, response.Buckets.Count);
        }
예제 #19
0
        public Task <ListBucketsResponse> ListBucketsAsync(Action <ListBucketsRequest>?config = null, CancellationToken token = default)
        {
            ListBucketsRequest request = new ListBucketsRequest();

            config?.Invoke(request);

            return(BucketOperations.ListBucketsAsync(request, token));
        }
예제 #20
0
        static async Task <ListBucketsResponse> ListBuckets(ListBucketsRequest request, string authToken, string apiUrl)
        {
            var headers = GetAuthHeaders(authToken);

            string responseString = await MakeRequest2(apiUrl + "/b2api/v1/b2_list_buckets", headers, JsonConvert.SerializeObject(request));

            return(await Task.Factory.StartNew(() => JsonConvert.DeserializeObject <ListBucketsResponse>(responseString)));
        }
예제 #21
0
        private S3Bucket GetBucket(AmazonS3 client)
        {
            ListBucketsRequest  listRequest = new ListBucketsRequest();
            ListBucketsResponse response    = client.ListBuckets(listRequest);

            return(response.Buckets
                   .Where(candidate => candidate.BucketName == this.BucketName)
                   .FirstOrDefault());
        }
        public async Task <ListBucketsResponse> GetS3Details(ListBucketsRequest listBucketsRequest)
        {
            using (var s3Client = new AmazonS3Client(awsCredentials, RegionEndpoint.GetBySystemName(Region)))
            {
                var response = await s3Client.ListBucketsAsync(listBucketsRequest);

                return(response);
            }
        }
예제 #23
0
        public async Task <List <string> > ListBucketsAsync(CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var request  = new ListBucketsRequest();
            var response = await _client.ListBucketsAsync(request, cancellationToken);

            return(response?.Buckets?.Select(x => x.BucketName).ToList() ?? new List <string>());
        }
예제 #24
0
        public void VpceEndpointTests_ListBuckets(string bucketName, string serviceUrl, Flags flags,
                                                  string expectedUri, string expectedRegion, string expectedService)
        {
            var request = new ListBucketsRequest {
            };

            RunTestRequest(request, ListBucketsRequestMarshaller.Instance,
                           isArn: false, serviceUrl, flags,
                           expectedUri, expectedRegion, expectedService);
        }
예제 #25
0
        /// <summary>
        /// Gets all buckets associated with an account in alphabetical order by bucket name. When using an authorization token
        /// that is restricted to a bucket you must include the <see cref="ListBucketsRequest.BucketId"/>
        /// or <see cref="ListBucketsRequest.BucketName"/> of that bucket in the request or the request will be denied.
        /// </summary>
        /// <param name="request">The <see cref="ListBucketsRequest"/> to send.</param>
        /// <param name="cacheTTL">An absolute cache expiration time to live (TTL) relative to now.</param>
        /// <exception cref="AuthenticationException">Thrown when authentication fails.</exception>
        /// <exception cref="ApiException">Thrown when an error occurs during client operation.</exception>
        async Task <IEnumerable <BucketItem> > IStorageBuckets.GetAsync(ListBucketsRequest request, TimeSpan cacheTTL)
        {
            var results = await _client.ListBucketsAsync(request, cacheTTL, _cancellationToken);

            if (results.IsSuccessStatusCode)
            {
                return(results.Response.Buckets);
            }

            return(default);
예제 #26
0
        public void TestListBuckets()
        {
            OssClient          ossClient = GetOssClient();
            ListBucketsRequest request   = new ListBucketsRequest();

            request.RegionId = "cn-north-1";
            var result = ossClient.ListBuckets(request).Result;

            _output.WriteLine(JsonConvert.SerializeObject(result));
        }
예제 #27
0
        private static async Task ListBuckets()
        {
            ListBucketsRequest  request  = new ListBucketsRequest();
            ListBucketsResponse response = await _s3Client.ListBucketsAsync(request);

            // Process response.
            foreach (S3Bucket bucket in response.Buckets)
            {
                Console.WriteLine($"{bucket.BucketName}");
            }
        }
예제 #28
0
                          

 static void ListBuckets(AmazonS3Client s3) 

                          {
                              
 ListBucketsRequest req = new ListBucketsRequest(); 

 Task <ListBucketsResponse> res = s3.ListBucketsAsync(req); 

 Task.WaitAll(res); 

 Console.WriteLine("List of S3 Buckets in your AWS Account"); 
            foreach (var bucket in res.Result.Buckets)

                              {
                                  
            {
                                      
 Console.WriteLine(bucket.BucketName); 

                                  }
                              }
                              

                          }
        public void ルートコンパートメント直下バケット一覧取得()
        {
            ListBucketsRequest listBucketsRequest = new ListBucketsRequest
            {
                CompartmentId = TenantOCID,
                NamespaceName = NameSpaceName
            };

            var listBucket = ObjectStorageClient.ListBuckets(listBucketsRequest);

            Assert.IsNotNull(listBucket);
        }
예제 #30
0
        protected bool BucketExists(string name)
        {
            Func <AmazonS3Client, ListBucketsResponse> command = c =>
            {
                var request = new ListBucketsRequest();
                return(c.ListBuckets(request));
            };

            var response = ClientHelper.TryCommand(command);
            var result   = response.Buckets.Any(b => b.BucketName == name);

            response.Dispose();
            return(result);
        }
        public ListBucketsResponse ListBuckets(ListBucketsRequest request)
        {
            List <S3Bucket> buckets = new List <S3Bucket>();

            foreach (var folder in Directory.EnumerateDirectories(this.BasePath))
            {
                buckets.Add(new S3Bucket {
                    BucketName = Path.GetFileName(folder)
                });
            }
            return(new ListBucketsResponse {
                Buckets = buckets
            });
        }
        public static void ListBuckets()
        {
            const string accessKeyId = "<your access key id>";
            const string accessKeySecret = "<your access key secret>";
            const string endpoint = "<valid host name>";

            OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret);

            try
            {
                // 1. Try to list all buckets.
                var buckets = client.ListBuckets();
                Console.WriteLine("List all buckets: ");
                foreach (var bucket in buckets)
                {
                    Console.WriteLine(bucket.Name + ", " + bucket.Location + ", " + bucket.Owner);
                }

                // 2. List buckets by specified conditions, such as prefix/marker/max-keys.
                var req = new ListBucketsRequest {Prefix = "test", MaxKeys = 3, Marker = "test2"};
                var res = client.ListBuckets(req);
                buckets = res.Buckets;
                Console.WriteLine("List buckets by page: ");
                Console.WriteLine("Prefix: " + res.Prefix + ", MaxKeys: " + res.MaxKeys + ", Marker: " + res.Marker
                    + ", NextMarker: " + res.NextMaker);
                foreach (var bucket in buckets)
                {
                    Console.WriteLine(bucket.Name + ", " + bucket.Location + ", " + bucket.Owner);
                }
            }
            catch (OssException ex)
            {
                Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                    ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error info: {0}", ex.Message);
            }
        }
 private S3Bucket GetBucket(AmazonS3 client)
 {
     ListBucketsRequest listRequest = new ListBucketsRequest();
     ListBucketsResponse response = client.ListBuckets(listRequest);
     return response.Buckets
         .Where(candidate => candidate.BucketName == this.BucketName)
         .FirstOrDefault();
 }
예제 #34
0
        public void BucketA_ListBucketTest()
        {
            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;
                ListBucketsResponse response = result as ListBucketsResponse;
                if (null != response)
                    actualValue = response.IsRequestSuccessful;
                hasCallbackArrived = true;
            };

            ListBucketsRequest request = new ListBucketsRequest();
            Guid id = request.Id;
            _client.OnS3Response += handler;
            _client.ListBuckets();

            EnqueueConditional(() => hasCallbackArrived);
            EnqueueCallback(() => Assert.IsTrue(expectedValue == actualValue,
                string.Format("Expected Value = {0}, Actual Value = {1}", expectedValue, actualValue)));
            EnqueueTestComplete();
        }
예제 #35
0
        /// <summary>
        /// <para>Returns a list of all buckets owned by the authenticated sender of the request.</para>
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the ListBuckets service method on AmazonS3.</param>
        /// 
        /// <returns>The response from the ListBuckets service method, as returned by AmazonS3.</returns>
		public ListBucketsResponse ListBuckets(ListBucketsRequest request)
        {
            var task = ListBucketsAsync(request);
            try
            {
                return task.Result;
            }
            catch(AggregateException e)
            {
                ExceptionDispatchInfo.Capture(e.InnerException).Throw();
                return null;
            }
        }
        public IAmazonS3 CreateClientFromIAMCredentials(IAMSecurityCredential iamCredentials) {
            Logger.Information("Creating an s3 client using IAM credentials");
            Logger.Information("AccessKeyId:{0}", iamCredentials.AccessKeyId);
            Logger.Information("SecretAccessKey:{0}", iamCredentials.SecretAccessKey);
            Logger.Information("Token:{0}", iamCredentials.Token);
            var client = new AmazonS3Client(iamCredentials.AccessKeyId, iamCredentials.SecretAccessKey, iamCredentials.Token, Amazon.RegionEndpoint.EUWest1);

            ListBucketsRequest request=new ListBucketsRequest();
            var buckets = client.ListBuckets(request);

            Logger.Information("List buckets:");
            foreach (var bucket in buckets.Buckets) {
                Logger.Information("{0}", bucket.BucketName);
            }
            return client;
        }
예제 #37
0
 IAsyncResult invokeListBuckets(ListBucketsRequest listBucketsRequest, AsyncCallback callback, object state, bool synchronized)
 {
     IRequest irequest = new ListBucketsRequestMarshaller().Marshall(listBucketsRequest);
     var unmarshaller = ListBucketsResponseUnmarshaller.GetInstance();
     AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
     Invoke(result);
     return result;
 }
예제 #38
0
        /// <summary>
        /// Initiates the asynchronous execution of the ListBuckets operation.
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the ListBuckets operation on AmazonS3Client.</param>
        /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
        /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
        ///          procedure using the AsyncState property.</param>
        /// 
        /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListBuckets
        ///         operation.</returns>
        public IAsyncResult BeginListBuckets(ListBucketsRequest request, AsyncCallback callback, object state)
        {
            var marshaller = new ListBucketsRequestMarshaller();
            var unmarshaller = ListBucketsResponseUnmarshaller.Instance;

            return BeginInvoke<ListBucketsRequest>(request, marshaller, unmarshaller,
                callback, state);
        }
예제 #39
0
 /// <summary>
 /// <para>Returns a list of all buckets owned by the authenticated sender of the request.</para>
 /// </summary>
 /// 
 /// <param name="listBucketsRequest">Container for the necessary parameters to execute the ListBuckets service method on AmazonS3.</param>
 /// 
 /// <returns>The response from the ListBuckets service method, as returned by AmazonS3.</returns>
 /// 
 public ListBucketsResponse ListBuckets(ListBucketsRequest listBucketsRequest)
 {
     IAsyncResult asyncResult = invokeListBuckets(listBucketsRequest, null, null, true);
     return EndListBuckets(asyncResult);
 }
예제 #40
0
        internal ListBucketsResponse ListBuckets(ListBucketsRequest request)
        {
            var marshaller = new ListBucketsRequestMarshaller();
            var unmarshaller = ListBucketsResponseUnmarshaller.Instance;

            return Invoke<ListBucketsRequest,ListBucketsResponse>(request, marshaller, unmarshaller);
        }
예제 #41
0
 /// <summary>
 /// Initiates the asynchronous execution of the ListBuckets operation.
 /// </summary>
 /// 
 /// <param name="request">Container for the necessary parameters to execute the ListBuckets operation on AmazonS3Client.</param>
 /// <param name="callback">An Action delegate that is invoked when the operation completes.</param>
 /// <param name="options">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
 ///          procedure using the AsyncState property.</param>
 public void ListBucketsAsync(ListBucketsRequest request, AmazonServiceCallback<ListBucketsRequest, ListBucketsResponse> callback, AsyncOptions options = null)
 {
     options = options == null?new AsyncOptions():options;
     var marshaller = new ListBucketsRequestMarshaller();
     var unmarshaller = ListBucketsResponseUnmarshaller.Instance;
     Action<AmazonWebServiceRequest, AmazonWebServiceResponse, Exception, AsyncOptions> callbackHelper = null;
     if(callback !=null )
         callbackHelper = (AmazonWebServiceRequest req, AmazonWebServiceResponse res, Exception ex, AsyncOptions ao) => { 
             AmazonServiceResult<ListBucketsRequest,ListBucketsResponse> responseObject 
                     = new AmazonServiceResult<ListBucketsRequest,ListBucketsResponse>((ListBucketsRequest)req, (ListBucketsResponse)res, ex , ao.State);    
                 callback(responseObject); 
         };
     BeginInvoke<ListBucketsRequest>(request, marshaller, unmarshaller, options, callbackHelper);
 }
예제 #42
0
        /// <summary>
        /// <para>Returns a list of all buckets owned by the authenticated sender of the request.</para>
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the ListBuckets service method on AmazonS3.</param>
        /// 
        /// <returns>The response from the ListBuckets service method, as returned by AmazonS3.</returns>
		public ListBucketsResponse ListBuckets(ListBucketsRequest request)
        {
            var task = ListBucketsAsync(request);
            try
            {
                return task.Result;
            }
            catch(AggregateException e)
            {
                throw e.InnerException;
            }
        }
 public IEnumerable<S3BucketModel> GetS3Buckets()
 {
     var request = new ListBucketsRequest();
     return S3Client.ListBuckets(request)
         .Buckets
         .Select(bucket => new S3BucketModel() { BucketName = bucket.BucketName, CreationDate = bucket.CreationDate});
 }
예제 #44
0
 /// <summary>
 /// Initiates the asynchronous execution of the ListBuckets operation.
 /// <seealso cref="Amazon.S3.IAmazonS3.ListBuckets"/>
 /// </summary>
 /// 
 /// <param name="listBucketsRequest">Container for the necessary parameters to execute the ListBuckets operation on AmazonS3.</param>
 /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
 /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
 ///          procedure using the AsyncState property.</param>
 /// 
 /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListBuckets
 ///         operation.</returns>
 public IAsyncResult BeginListBuckets(ListBucketsRequest listBucketsRequest, AsyncCallback callback, object state)
 {
     return invokeListBuckets(listBucketsRequest, callback, state, false);
 }
예제 #45
0
        /// <summary>
        /// <para>Returns a list of all buckets owned by the authenticated sender of the request.</para>
        /// </summary>
        /// 
        /// <param name="listBucketsRequest">Container for the necessary parameters to execute the ListBuckets service method on AmazonS3.</param>
        /// 
        /// <returns>The response from the ListBuckets service method, as returned by AmazonS3.</returns>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
		public async Task<ListBucketsResponse> ListBucketsAsync(ListBucketsRequest listBucketsRequest, CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new ListBucketsRequestMarshaller();
            var unmarshaller = ListBucketsResponseUnmarshaller.GetInstance();
            var response = await Invoke<IRequest, ListBucketsRequest, ListBucketsResponse>(listBucketsRequest, marshaller, unmarshaller, signer, cancellationToken)
                .ConfigureAwait(continueOnCapturedContext: false);
            return response;
        }
예제 #46
0
        /// <summary>
        /// Initiates the asynchronous execution of the ListBuckets operation.
        /// <seealso cref="Amazon.S3.IAmazonS3.ListBuckets"/>
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the ListBuckets operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
		public Task<ListBucketsResponse> ListBucketsAsync(ListBucketsRequest request, CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new ListBucketsRequestMarshaller();
            var unmarshaller = ListBucketsResponseUnmarshaller.GetInstance();
            return Invoke<IRequest, ListBucketsRequest, ListBucketsResponse>(request, marshaller, unmarshaller, signer, cancellationToken);
        }
예제 #47
0
        /// <summary>
        /// Initiates the asynchronous execution of the ListBuckets operation.
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the ListBuckets operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        public Task<ListBucketsResponse> ListBucketsAsync(ListBucketsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new ListBucketsRequestMarshaller();
            var unmarshaller = ListBucketsResponseUnmarshaller.Instance;

            return InvokeAsync<ListBucketsRequest,ListBucketsResponse>(request, marshaller, 
                unmarshaller, cancellationToken);
        }
        public void InitializeStorage()
        {
            // If these error with things like invalid credentials, now you know
            using ( AmazonS3 client = AWSClientFactory.CreateAmazonS3Client( this.amazonKey, this.amazonSecret ) ) {

                ListBucketsRequest request = new ListBucketsRequest {
                };
                ListBucketsResponse response = client.ListBuckets( request );

                List<S3Bucket> buckets = response.Buckets;
                bool exists = (
                    from b in buckets
                    where string.Equals( b.BucketName, this.amazonBucket, StringComparison.InvariantCultureIgnoreCase )
                    select b
                ).Any();

                if ( !exists ) {
                    PutBucketResponse bucketResponse = client.PutBucket( new PutBucketRequest {
                        BucketName = this.amazonBucket
                    } );
                }
            }
        }