Exemplo n.º 1
0
        public bool CreateBucket()
        {
            config.ServiceURL = "s3.amazonaws.com";

            AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(
                am.PublicKey,
                am.PrivateKey
                );

            ListBucketsResponse response = client.ListBuckets();

            bool found = false;

            foreach (S3Bucket bucket in response.Buckets)
            {
                if (bucket.BucketName == "Drone")
                {
                    found = true;
                    break;
                }
            }

            if (found == false)
            {
                client.PutBucket(new PutBucketRequest().WithBucketName("Drone"));
            }
            return(found);
        }
Exemplo n.º 2
0
 public static void ListBucket(string UseCase)
 {
     try
     {
         using (AmazonS3Client client = new AmazonS3Client(AccessKey, SecretKey, Amazon.RegionEndpoint.APSouth1))
         {
             ListBucketsResponse response = client.ListBuckets();
             if (UseCase == "detail")
             {
                 Console.ForegroundColor = ConsoleColor.Magenta;
                 Console.WriteLine("\tCreation Date \t\t" + "Total Objects\t\t" + "Region \t\t" + "Bucket Name");
                 Console.ForegroundColor = ConsoleColor.White;
                 Console.WriteLine();
                 foreach (S3Bucket b in response.Buckets)
                 {
                     Console.WriteLine((b.CreationDate) + " \t\t" + CountObjectsInBucket(b.BucketName) + " \t\t\t" + RegionOfTheBucketForDetailListing(b.BucketName, 1) + "\t\t" + b.BucketName);
                 }
             }
             else if (UseCase == "normal")
             {
                 Console.ForegroundColor = ConsoleColor.Magenta;
                 Console.WriteLine("\t Bucket Name");
                 Console.ForegroundColor = ConsoleColor.White;
                 foreach (S3Bucket b in response.Buckets)
                 {
                     Console.WriteLine(b.BucketName);
                 }
             }
         }
     }
     catch (Exception e)
     {
         Console.WriteLine("ERROR MESSAGE : " + e.Message);
     }
 }
Exemplo n.º 3
0
        //public bool IsFolderExists(string accessKeyID, string secretAccessKey, string bucketName, string key, bool create)
        //{
        //    AmazonS3 client = GetS3Client(accessKeyID, secretAccessKey);
        //    ListObjectsRequest listRequest = new ListObjectsRequest();
        //    listRequest.WithBucketName(bucketName)
        //    .WithPrefix(key);

        //    // get all objects inside the "folder"
        //    ListObjectsResponse objects = client.ListObjects(listRequest);
        //    foreach (S3Object s3o in objects.S3Objects)
        //    {
        //        // get the acl of the object
        //        GetACLRequest aclRequest = new GetACLRequest();
        //        aclRequest.WithBucketName("thebucket")
        //        .WithKey(s3o.Key);
        //        GetACLResponse getAclResponse = client.GetACL(aclRequest);

        //        //// copy the object without acl
        //        //string newKey = s3o.Key.Replace(oldOWnerId.ToString(), newOwnerId.ToString());
        //        //CopyObjectRequest copyRequest = new CopyObjectRequest();
        //        //copyRequest.SourceBucket = "thebucket";
        //        //copyRequest.DestinationBucket = "thebucket";
        //        //copyRequest.WithSourceKey(s3o.Key)
        //        //.WithDestinationKey(newKey);
        //        //S3Response copyResponse = client.CopyObject(copyRequest);
        //        //// set the acl of the newly made object
        //        //SetACLRequest setAclRequest = new SetACLRequest();
        //        //setAclRequest.WithBucketName("ytimusic")
        //        //.WithKey(newKey)
        //        //.WithACL(getAclResponse.AccessControlList);
        //        //SetACLResponse setAclRespone = client.SetACL(setAclRequest);
        //        //DeleteObjectRequest deleteRequest = new DeleteObjectRequest();
        //        //deleteRequest.WithBucketName("thebucket")
        //        //.WithKey(s3o.Key);
        //        //DeleteObjectResponse deleteResponse = client.DeleteObject(deleteRequest);

        //    }

        //    return false;
        //}

        /// <summary>
        /// Check Azure connection
        /// </summary>
        /// <param name="azureAccountName"></param>
        /// <param name="azureAccountKey"></param>
        /// <returns></returns>
        public bool IsBucketNameExists(string accessKeyID, string secretAccessKey, string bucketName, bool create)
        {
            try
            {
                AmazonS3            client   = GetS3Client(accessKeyID, secretAccessKey);
                ListBucketsResponse response = client.ListBuckets();
                bool found = false;
                foreach (S3Bucket bucket in response.Buckets)
                {
                    if (bucket.BucketName == bucketName)
                    {
                        found = true;
                        break;
                    }
                }
                if (found == false)
                {
                    if (create)
                    {
                        client.PutBucket(new PutBucketRequest().WithBucketName(bucketName));
                    }
                    else
                    {
                        throw new Exception("The bucket " + bucketName + " does not exists.");
                    }
                }
                return(true);
            }
            catch (Exception ex)
            {
                throw new DuradosException("AWS Connection failed, Error: " + ex.Message);
                //return false;
            }
        }
Exemplo n.º 4
0
        private static string PrintBucketName(AmazonS3Client s3Client)
        {
            ListBucketsResponse response = s3Client.ListBuckets();
            S3Bucket            bucket   = response.Buckets[0];

            return(bucket.BucketName);
        }
Exemplo n.º 5
0
        public async Task <Status> IsReadyAsync(CancellationToken cancellationToken)
        {
            var config = new AmazonS3Config();

            config.ServiceURL     = _host;
            config.ForcePathStyle = true;

            using (var s3Client = new AmazonS3Client(_accessKey, _secretKey, config))
            {
                try
                {
                    ListBucketsResponse result = await s3Client.ListBucketsAsync();

                    return(new Status
                    {
                        IsReady = true,
                        Message =
                            $"Success. Owner: {result.Owner.DisplayName}, id: {result.Owner.Id}."
                    });
                }
                catch (Exception ex)
                {
                    return(new Status
                    {
                        IsReady = false,
                        Message = ex.Message
                    });
                }
            }
        }
Exemplo n.º 6
0
 public bool CheckIfBucketExists(string bucketname)
 {
     try
     {
         ListBucketsResponse response = client.ListBuckets();
         foreach (S3Bucket bucket in response.Buckets)
         {
             if (bucketname.Equals(bucket.BucketName))
             {
                 return(true);
             }
         }
         return(false);
     }
     catch (AmazonS3Exception amazonS3Exception)
     {
         string filename = ConfigurationManager.AppSettings["LogFile"];
         using (StreamWriter writer = File.AppendText(filename))
         {
             if (amazonS3Exception.ErrorCode != null &&
                 (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") ||
                  amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
             {
                 log.WriteLog("Please check the provided AWS Credentials.", writer);
                 log.WriteLog("If you haven't signed up for Amazon S3, please visit http://aws.amazon.com/s3", writer);
                 return(false);
             }
             else
             {
                 log.WriteLog("An Error, number " + amazonS3Exception.ErrorCode + ", occurred when listing buckets with the message " + amazonS3Exception.Message, writer);
                 return(false);
             }
         }
     }
 }
Exemplo n.º 7
0
        protected Uploader_S3(Config_S3 settings)
        {
            AmazonS3Config config = new AmazonS3Config();

            config.ServiceURL     = settings.Provider;
            config.ForcePathStyle = settings.ForcePathStyle;
            if (settings.Proxy != null)
            {
                logger.Info($"Используем прокси: {settings.Proxy.Host}:{settings.Proxy.Port}");
                config.ProxyHost = settings.Proxy.Host;
                config.ProxyPort = settings.Proxy.Port;
                if (settings.Proxy.Login != null && settings.Proxy.Password != null)
                {
                    config.ProxyCredentials = new NetworkCredential(settings.Proxy.Login, settings.Proxy.Password);
                    var maskedPass = new string('#', settings.Proxy.Password.Length);
                    logger.Info($"С логином {settings.Proxy.Login} и паролем {maskedPass}");
                }
            }

            client          = new AmazonS3Client(settings.Login, settings.Password, config);
            transferUtility = new TransferUtility(client);
            ListBucketsResponse response = client.ListBuckets();

            bucket = response.Buckets.First(x => x.BucketName == settings.Container);
            if (bucket == null)
            {
                throw new InvalidOperationException($"Can't find S3 bucket: {settings.Container}");
            }

            logger.Info($"Подключены к S3 хранилищу от имени '{settings.Login}' к контейнеру '{settings.Container}'");
        }
        public async void GetS3BucketsAsync()
        {
            var             provider = new AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials());
            CognitoUserPool userPool = new CognitoUserPool("poolID", "clientID", provider);
            CognitoUser     user     = new CognitoUser("username", "clientID", userPool, provider);

            string password = "******";

            AuthFlowResponse context = await user.StartWithSrpAuthAsync(new InitiateSrpAuthRequest()
            {
                Password = password
            }).ConfigureAwait(false);

            CognitoAWSCredentials credentials =
                user.GetCognitoAWSCredentials("identityPoolID", RegionEndpoint.< YourIdentityPoolRegion >);

            using (var client = new AmazonS3Client(credentials))
            {
                ListBucketsResponse response =
                    await client.ListBucketsAsync(new ListBucketsRequest()).ConfigureAwait(false);

                foreach (S3Bucket bucket in response.Buckets)
                {
                    Console.WriteLine(bucket.BucketName);
                }
            }
        }
Exemplo n.º 9
0
    public async Task ListBuckets(S3Provider _, string bucket, ISimpleClient client)
    {
        ListBucketsResponse listResp = await client.ListBucketsAsync().ConfigureAwait(false);

        Assert.True(listResp.Buckets.Count > 0);
        Assert.Single(listResp.Buckets, x => x.BucketName == bucket);
    }
Exemplo n.º 10
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();
        }
Exemplo n.º 11
0
        public void ListBucketContents()
        {
            var andrew = "";
            var secret = "";

            //this.bucket = "stuff.tiz.digital";
            AmazonS3Client client = new AmazonS3Client(andrew, secret, RegionEndpoint.APSoutheast2);

            // Issue call
            ListBucketsResponse response = client.ListBuckets();

            // View response data
            Debug.WriteLine($"Buckets owner - {response.Owner.DisplayName}");
            foreach (S3Bucket bucket in response.Buckets)
            {
                Debug.WriteLine($"{bucket.BucketName}, Created {bucket.CreationDate}");
            }

            ListObjectsV2Request objRequest = new ListObjectsV2Request
            {
                BucketName = "rmccomb"
            };

            ListObjectsV2Response objResponse = client.ListObjectsV2(objRequest);

            foreach (S3Object obj in objResponse.S3Objects)
            {
                Debug.WriteLine($"{obj.BucketName} {obj.Key}");
            }
        }
Exemplo n.º 12
0
        public void CreateS3Bucket(String name)
        {
            NameValueCollection appConfig = ConfigurationManager.AppSettings;

            AmazonS3Client client = new AmazonS3Client(
                appConfig["AWSAccessKey"],
                appConfig["AWSSecretKey"],
                Amazon.RegionEndpoint.USWest2
                );

            PutBucketRequest request = new PutBucketRequest();

            request.BucketName = name;
            client.PutBucket(request);

            ListBucketsResponse response = client.ListBuckets();

            //create folder
            PutObjectRequest putObjectRequest = new PutObjectRequest
            {
                BucketName = name,
                Key        = "album/"
            };

            client.PutObject(putObjectRequest);

            //upload to folder in bucket
        }
Exemplo n.º 13
0
        public static void InvokeListBuckets()
        {
            NameValueCollection appConfig = ConfigurationManager.AppSettings;

            IAmazonS3 s3Client = AWSClientFactory.CreateAmazonS3Client(RegionEndpoint.USWest2);

            try
            {
                ListBucketsResponse response = s3Client.ListBuckets();
                int numBuckets = 0;
                numBuckets = response.Buckets.Count;

                Console.WriteLine("You have " + numBuckets + " Amazon S3 bucket(s).");
            }
            catch (AmazonS3Exception ex)
            {
                if (ex.ErrorCode.Equals("InvalidAccessKeyId") ||
                    ex.ErrorCode.Equals("InvalidSecurity"))
                {
                    Console.WriteLine("Please check the provided AWS access credentials.");
                    Console.WriteLine("If you haven't signed up for Amazon S3 yet, you can sign up at http://aws.amazon.com/s3.");
                }
                else
                {
                    Console.WriteLine("Caught Exception: " + ex.Message);
                    Console.WriteLine("Response Status Code: " + ex.StatusCode);
                    Console.WriteLine("Error Code: " + ex.ErrorCode);
                    Console.WriteLine("Request ID: " + ex.RequestId);
                }
            }
            Console.WriteLine();
        }
Exemplo n.º 14
0
        /// <summary>
        /// Creates bucket if it is not exists.
        /// </summary>
        /// <param name="client"></param>
        private static void CreateBucket(IAmazonS3 client)
        {
            Console.Out.WriteLine("Checking S3 bucket with name " + BUCKET_NAME);
            ListBucketsResponse response = client.ListBuckets();
            bool found = false;

            foreach (S3Bucket bucket in response.Buckets)
            {
                if (bucket.BucketName == BUCKET_NAME)
                {
                    Console.Out.WriteLine("   Bucket found will not create it.");
                    found = true;
                    break;
                }
            }

            if (found == false)
            {
                Console.Out.WriteLine("   Bucket not found will create it.");
                PutObjectRequest request = new PutObjectRequest
                {
                    BucketName = s3Bucket,
                    FilePath   = filePath,
                    Key        = S3_KEY,
                    CannedACL  = Amazon.S3.S3CannedACL.PublicRead
                };

                // Put object
                PutObjectResponse responsePut = client.PutObject(request);

                //  client.PutBucket(new PutBucketRequest().WithBucketName(BUCKET_NAME));

                Console.Out.WriteLine("Created S3 bucket with name " + BUCKET_NAME);
            }
        }
Exemplo n.º 15
0
        private static async Task <PutBucketResponse> CreateIfNotExistsAsync(
            AWSS3StorageCacheOptions options,
            S3CannedACL acl)
        {
            AmazonS3Client client = AmazonS3ClientFactory.CreateClient(options);

            bool foundBucket = false;
            ListBucketsResponse listBucketsResponse = await client.ListBucketsAsync();

            foreach (S3Bucket b in listBucketsResponse.Buckets)
            {
                if (b.BucketName == options.BucketName)
                {
                    foundBucket = true;
                    break;
                }
            }

            if (!foundBucket)
            {
                var putBucketRequest = new PutBucketRequest
                {
                    BucketName   = options.BucketName,
                    BucketRegion = options.Region,
                    CannedACL    = acl
                };

                return(await client.PutBucketAsync(putBucketRequest));
            }

            return(null);
        }
Exemplo n.º 16
0
    //取得目前該金鑰權限下的所有Bucket列表
    public static List <string> GetBucketList()
    {
        var buckets     = new List <string>();
        var credentials = new StoredProfileAWSCredentials("developer"); //若config檔裡有指定profileName屬性,則此段可省略,下面改寫為 var client = new AmazonS3Client()

        using (var client = new AmazonS3Client(credentials))
        {
            try
            {
                ListBucketsResponse response = client.ListBuckets();

                foreach (S3Bucket bucket in response.Buckets)
                {
                    buckets.Add(bucket.BucketName);
                }
            }
            catch (AmazonS3Exception amazonS3Exception)
            {
                if (amazonS3Exception.ErrorCode != null && (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") || amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
                {
                    LogTools.Error("Please check the provided AWS Credentials. If you haven't signed up for Amazon S3, please visit http://aws.amazon.com/s3");
                }
                else
                {
                    LogTools.Error(string.Format("An Error, number {0}, occurred when listing buckets with the message '{1}", amazonS3Exception.ErrorCode, amazonS3Exception.Message));
                }
            }
        }

        return(buckets);
    }
Exemplo n.º 17
0
        private static async Task CreateBucketAsync(AmazonS3Client client)
        {
            Console.Out.WriteLine("Checking S3 bucket with name " + BUCKET_NAME);

            ListBucketsResponse response = await client.ListBucketsAsync();

            bool found = false;

            foreach (S3Bucket bucket in response.Buckets)
            {
                if (bucket.BucketName == BUCKET_NAME)
                {
                    Console.Out.WriteLine("Bucket already Exists...............................");
                    found = true;
                    break;
                }
            }

            if (found == false)
            {
                Console.Out.WriteLine("Bucket is Creating...............................");

                PutBucketRequest request = new PutBucketRequest();
                request.BucketName = BUCKET_NAME;

                await client.PutBucketAsync(request);

                Console.Out.WriteLine("Bucket has been Created S3 bucket with name " + BUCKET_NAME);
            }
        }
        private static void UnmarshallResult(XmlUnmarshallerContext context, ListBucketsResponse response)
        {
            int currentDepth = context.get_CurrentDepth();
            int num          = currentDepth + 1;

            if (context.get_IsStartOfDocument())
            {
                num += 2;
            }
            while (context.Read())
            {
                if (context.get_IsStartElement() || context.get_IsAttribute())
                {
                    if (context.TestExpression("Bucket", num + 1))
                    {
                        response.Buckets.Add(BucketUnmarshaller.Instance.Unmarshall(context));
                    }
                    else if (context.TestExpression("Owner", num))
                    {
                        response.Owner = OwnerUnmarshaller.Instance.Unmarshall(context);
                    }
                }
                else if (context.get_IsEndElement() && context.get_CurrentDepth() < currentDepth)
                {
                    break;
                }
            }
        }
Exemplo n.º 19
0
 static void ListingBuckets()
 {
     try
     {
         ListBucketsResponse response = client.ListBuckets();
         foreach (S3Bucket bucket in response.Buckets)
         {
             Console.WriteLine("You own Bucket with name: {0}", bucket.BucketName);
         }
     }
     catch (AmazonS3Exception amazonS3Exception)
     {
         if (amazonS3Exception.ErrorCode != null &&
             (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") ||
              amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
         {
             Console.WriteLine("Please check the provided AWS Credentials.");
             Console.WriteLine("If you haven't signed up for Amazon S3, please visit http://aws.amazon.com/s3");
         }
         else
         {
             Console.WriteLine("An Error, number {0}, occurred when listing buckets with the message '{1}", amazonS3Exception.ErrorCode, amazonS3Exception.Message);
         }
     }
 }
Exemplo n.º 20
0
        // Parse the input request



        /// <summary>
        /// //////////////////////////////Create a new bucket//////////////////////////////
        /// </summary>
        /// <param name="client"></param>
        public static void CreateBucket(AmazonS3 client, string cmap)
        {
            Console.Out.WriteLine("Checking S3 bucket with name " + cmap);

            ListBucketsResponse response = client.ListBuckets();

            bool found = false;

            foreach (S3Bucket bucket in response.Buckets)
            {
                if (bucket.BucketName == cmap)
                {
                    Console.Out.WriteLine("   Bucket found will not create it.");
                    found = true;
                    break;
                }
            }

            if (found == false)
            {
                Console.Out.WriteLine("   Bucket not found will create it.");

                client.PutBucket(new PutBucketRequest().WithBucketName(cmap));

                Console.Out.WriteLine("Created S3 bucket with name " + cmap);
            }
        }
Exemplo n.º 21
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));
        }
Exemplo n.º 22
0
        public async Task <string> GetS3BucketsAsync(CognitoUser user)
        {
            CognitoAWSCredentials credentials =
                user.GetCognitoAWSCredentials(FED_POOL_ID, new AppConfigAWSRegion().Region);
            StringBuilder bucketlist = new StringBuilder();

            bucketlist.Append("================Cognito Credentails==================\n");
            bucketlist.Append("Access Key - " + credentials.GetCredentials().AccessKey);
            bucketlist.Append("\nSecret - " + credentials.GetCredentials().SecretKey);
            bucketlist.Append("\nSession Token - " + credentials.GetCredentials().Token);

            bucketlist.Append("\n================User Buckets==================\n");

            using (var client = new AmazonS3Client(credentials))
            {
                ListBucketsResponse response =
                    await client.ListBucketsAsync(new ListBucketsRequest()).ConfigureAwait(false);

                foreach (S3Bucket bucket in response.Buckets)
                {
                    bucketlist.Append(bucket.BucketName);

                    bucketlist.Append("\n");
                }
            }
            Console.WriteLine(bucketlist.ToString());
            return(bucketlist.ToString());
        }
Exemplo n.º 23
0
        internal async Task <List <S3Bucket> > ListBuckets()
        {
            ListBucketsResponse response = await this.amazonS3Client.ListBucketsAsync();

            this.buckets = response.Buckets;
            return(this.buckets);
        }
Exemplo n.º 24
0
        private static void Initialize()
        {
            NameValueCollection appConfig = ConfigurationManager.AppSettings;

            _amazonS3Client = new AmazonS3Client(appConfig["AWSAccessKey"], appConfig["AWSSecretKey"]);

            _folder = appConfig["SyncFolder"];

            string             password = appConfig["CryptoKey"];
            Rfc2898DeriveBytes rfcDb    = new Rfc2898DeriveBytes(password, System.Text.Encoding.UTF8.GetBytes(password));

            Rijndael rijndael = Rijndael.Create();

            byte[] key = rfcDb.GetBytes(32); //256 bits key
            byte[] iv  = rfcDb.GetBytes(16); // 128 bits key
            _aesEncryptor = rijndael.CreateEncryptor(key, iv);
            _aesDecryptor = rijndael.CreateDecryptor(key, iv);

            ListBucketsResponse listBucketsResponse = _amazonS3Client.ListBuckets();
            bool bucketIsExist = listBucketsResponse.Buckets.Any(s3Bucket => s3Bucket.BucketName == BucketName);

            if (!bucketIsExist)
            {
                _amazonS3Client.PutBucket(new PutBucketRequest().WithBucketName(BucketName));
            }

            InitializeFileSystemWatcher();
        }
        public void createBucket(string bucketName)
        {
            AmazonS3Client      client      = new AmazonS3Client("AKIAIYKAM62F6DZ2CEGA", "HmHyI439/ZdyOOxjnrpW3izOzOWcu3kS5qwpV1Kd", RegionEndpoint.USEast1);
            string              BUCKET_NAME = bucketName;
            ListBucketsResponse response    = client.ListBuckets();
            bool found = false;

            foreach (S3Bucket bucket in response.Buckets)
            {
                if (bucket.BucketName == BUCKET_NAME)
                {
                    found = true;
                    break;
                }
            }
            if (found == false)
            {
                // Create a client
                // AmazonS3Client client = new AmazonS3Client();

                // Construct request
                PutBucketRequest request = new PutBucketRequest
                {
                    BucketName   = bucketName,
                    BucketRegion = S3Region.US,           // set region to EU
                    CannedACL    = S3CannedACL.PublicRead // make bucket publicly readable
                };

                // Issue call
                client.PutBucket(request);
            }
        }
Exemplo n.º 26
0
        public async Task <string> CheckBucket(string BucketName)
        {
            string returnValue = "bucket does not exists!";

            try
            {
                s3config = new AmazonS3Config();
                string endpointUrl = config.GetEnumValue(Category.Config, Key.UseSSLObjectStorage) == "1" ? @"https://" : @"http://";
                endpointUrl         = endpointUrl + config.GetEnumValue(Category.Config, Key.ObjectEndPoint);
                s3config.ServiceURL = endpointUrl;
                using (IAmazonS3 client = new AmazonS3Client(config.GetEnumValue(Category.Config, Key.ObjectAccessKey), config.GetEnumValue(Category.Config, Key.ObjectSecretKey), s3config))
                {
                    ListBucketsResponse response = await client.ListBucketsAsync();

                    foreach (S3Bucket o in response.Buckets)
                    {
                        if (o.BucketName == BucketName)
                        {
                            returnValue = CallResult.Success.ToString();
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                nlog.Error(string.Format("Message : {0}, StackTrace : {1}", ex.Message, ex.StackTrace));
                returnValue = ex.Message;
            }
            return(returnValue);
        }
Exemplo n.º 27
0
        // Create the output bucket if it does not exist already.
        public static void CreateBucket(string bucket)
        {
            ListBucketsResponse responseBuckets = s3ForStudentBuckets.ListBuckets();
            bool found = false;

            foreach (S3Bucket s3Bucket in responseBuckets.Buckets)
            {
                if (s3Bucket.BucketName == bucket)
                {
                    found = true;
                    VerifyBucketOwnership(bucket);
                    break;
                }
                else
                {
                    found = false;
                }
            }

            if (found == false)
            {
                Debug.Write("Transformer: Creating output bucket: " + bucket);
                PutBucketRequest request = new PutBucketRequest();
                request.BucketName = bucket;
                s3ForStudentBuckets.PutBucket(request);
            }
        }
Exemplo n.º 28
0
        public bool ValidateMigrateKey(string migrateKey, AppRepository app)
        {
            bool result = false;

            using (AmazonS3Client client = GetS3Client(app))
            {
                try
                {
                    ListBucketsResponse response = client.ListBuckets();
                    foreach (S3Bucket b in response.Buckets)
                    {
                        Console.WriteLine("{0}\t{1}", b.BucketName, b.CreationDate);
                        if (b.BucketName == migrateKey)
                        {
                            result = true;
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }

            return(result);
        }
Exemplo n.º 29
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();
        }
Exemplo n.º 30
0
Arquivo: Function.cs Projeto: wse/AWS
 async Task <bool> BucketExists(string bucketName)
 {
     return(await CarryOutAWSTask <bool>(async() =>
     {
         ListBucketsResponse response = await client.ListBucketsAsync();
         return response.Buckets.Select(x => x.BucketName).Contains(bucketName);
     }, "Listing buckets"));
 }