Exemple #1
0
        /// <summary>
        /// UploadProfileImageByUserAsync
        /// </summary>
        /// <param name="image"></param>
        /// <param name="appUserId"></param>
        /// <returns></returns>
        public async Task <IImage> UploadProfileImageByUserAsync(IImage image, string appUserId)
        {
            if (!await AmazonS3Util.DoesS3BucketExistAsync(_client, _s3Bucket))
            {
                throw new AmazonS3Exception("S3 Bucket does not exist");
            }

            byte[] bytes = Convert.FromBase64String(image.Body);
            var    key   = GenerateProfileImageKey(image, appUserId);

            using (var ms = new MemoryStream(bytes))
            {
                var fileTransferUtilityRequest = new TransferUtilityUploadRequest
                {
                    BucketName  = _s3Bucket,
                    CannedACL   = S3CannedACL.PublicRead,
                    Key         = key,
                    InputStream = ms
                };

                var fileTransferUtility = new TransferUtility(_client);
                await fileTransferUtility.UploadAsync(fileTransferUtilityRequest);
            }

            image.Url = GetPreSignedUrl(key);

            return(image);
        }
Exemple #2
0
        public async Task RunCode()

        {
            var client = new AmazonS3Client();

            // Bucket ismi kontrolü gerçekleştiriliyor
            // 409 hatası denebilir aynı isimde başka bir bucket var hatası olabilir.
            var response = await AmazonS3Util.DoesS3BucketExistAsync(client, "testbucket1837837837837");

            if (response)
            {
                Console.WriteLine("Bucket Already Exist");
            }
            else
            {
                var request = new PutBucketRequest {
                    BucketName      = "testbucket1837837837837",
                    UseClientRegion = true
                };

                var bucketResponse = await client.PutBucketAsync(request);

                if (bucketResponse.HttpStatusCode == System.Net.HttpStatusCode.OK)
                {
                    Console.WriteLine("Bucket Created Succesfully");
                }
            }

            Console.WriteLine("Çıkmak için lütfen bir tuşa basınız");
            Console.ReadKey();
        }
Exemple #3
0
        /// <summary>
        /// GetLinkImageByIdAsync
        /// </summary>
        /// <param name="linkId"></param>
        /// <returns></returns>
        public async Task <IImage> GetLinkImageByIdAsync(ILink link)
        {
            if (!await AmazonS3Util.DoesS3BucketExistAsync(_client, _s3Bucket))
            {
                throw new AmazonS3Exception("S3 Bucket does not exist");
            }

            var prefix = GetLinkImageKey(link);

            var listObjectsRequest = new ListObjectsV2Request
            {
                BucketName = _s3Bucket,
                Prefix     = prefix
            };
            var response = await _client.ListObjectsV2Async(listObjectsRequest);

            if (response.S3Objects.Count > 0)
            {
                IImage image = new Image();
                image.Url = GetPreSignedUrl(response.S3Objects[0].Key);
                return(image);
            }

            return(null);
        }
Exemple #4
0
        private static async Task UploadFileAsync()
        {
            try
            {
                bool bucketExists = await AmazonS3Util.DoesS3BucketExistAsync(s3Client, bucketName);

                if (!bucketExists)
                {
                    // you can implement logging if needed
                    Console.WriteLine("Bucket doesn't exist! Please verify with AWS Cloudops administrator.");
                }

                var fileTransferUtility = new TransferUtility(s3Client);
                Console.WriteLine("Uploading in progress");
                await fileTransferUtility.UploadAsync(filePath, bucketName, keyName);

                Console.WriteLine("Upload completed");
            }
            catch (AmazonS3Exception e)
            {
                Console.WriteLine("Error encountered on server.Message:'{0}' when writing an object", e.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
            }
        }
Exemple #5
0
        public async Task <bool> CreateBucket(string name)
        {
            try
            {
                if (!(await AmazonS3Util.DoesS3BucketExistAsync(s3Client, name)))
                {
                    var putBucketRequest = new PutBucketRequest
                    {
                        BucketName      = name,
                        UseClientRegion = true,
                    };

                    PutBucketResponse putBucketResponse = await s3Client.PutBucketAsync(putBucketRequest);
                }
                return(true);
            }
            catch (AmazonS3Exception e)
            {
                Console.WriteLine("Error encountered on server. Message:'{0}' when writing an object", e.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
            }
            return(false);
        }
Exemple #6
0
        public async Task CreateBucketAsync(string bucketName)
        {
            try
            {
                if (await AmazonS3Util.DoesS3BucketExistAsync(_amazonS3, bucketName) == false)
                {
                    var putBucketRequest = new PutBucketRequest
                    {
                        BucketName = bucketName
                    };
                    await _amazonS3.PutBucketAsync(putBucketRequest);
                }
            }

            // Catch specific amazon errors
            catch (AmazonS3Exception e)
            {
                throw e;
            }

            // Catch other errors
            catch (Exception e)
            {
                throw e;
            }
        }
        static async Task CreateBucketAsync()
        {
            try
            {
                if (!(await AmazonS3Util.DoesS3BucketExistAsync(s3Client, bucketName)))
                {
                    var putBucketRequest = new PutBucketRequest
                    {
                        BucketName      = bucketName,
                        UseClientRegion = true
                    };

                    PutBucketResponse putBucketResponse = await s3Client.PutBucketAsync(putBucketRequest);
                }
                // Retrieve the bucket location.
                string bucketLocation = await FindBucketLocationAsync(s3Client);
            }
            catch (AmazonS3Exception e)
            {
                Console.WriteLine("Error encountered on server. Message:'{0}' when writing an object", e.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
            }
        }
        private static async Task CreateBucketAndUploadFileAsync(IAmazonS3 s3Client, string bucketName, string path, string key)
        {
            try
            {
                if (!await AmazonS3Util.DoesS3BucketExistAsync(s3Client, bucketName))
                {
                    var putBucketRequest = new PutBucketRequest {
                        BucketName = bucketName, UseClientRegion = true
                    };

                    PutBucketResponse putBucketResponse = await s3Client.PutBucketAsync(putBucketRequest);
                }

                // Retrieve the bucket location.
                string bucketLocation = await FindBucketLocationAsync(s3Client, bucketName);

                var fileTransferUtility = new TransferUtility(s3Client);

                await fileTransferUtility.UploadAsync(path, bucketName, key);
            }
            catch (AmazonS3Exception e)
            {
                Console.WriteLine("Error encountered on server. Message:'{0}' when writing an object", e.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
            }
        }
Exemple #9
0
        /// <summary>
        /// Method verifies whenever the bucket exist in S3
        /// </summary>
        /// <param name="bucketName">Name of the bucket</param>
        /// <returns>True if bucket exist, false in other case</returns>
        public bool IsBucketExist(string bucketName)
        {
            if (string.IsNullOrEmpty(bucketName))
            {
                throw new ArgumentNullException(nameof(bucketName));
            }

            try
            {
                using (Task <bool> isBucketAlreadyExist = AmazonS3Util.DoesS3BucketExistAsync(_client, bucketName))
                {
                    if (isBucketAlreadyExist.Result == true)
                    {
                        Console.WriteLine("Bucket name already exist.");
                        return(true);
                    }

                    return(false);
                }
            }
            catch (System.AggregateException ex)
            {
                if (ex.InnerException != null)
                {
                    Console.WriteLine($"Message: {ex.InnerException.Message}");
                }

                return(false);
            }
        }
        public async Task CreateBucketAsync()
        {
            try
            {
                if (await AmazonS3Util.DoesS3BucketExistAsync(_client, BucketName) == false)
                {
                    var putBucketRequest = new PutBucketRequest
                    {
                        BucketName      = BucketName,
                        UseClientRegion = true
                    };
                    var response = await _client.PutBucketAsync(putBucketRequest);

                    _logger.LogInformation("Created Bucket - BucketName: {0}", BucketName);
                }
                else
                {
                    _logger.LogInformation("Bucket is exist - BucketName: {0}", BucketName);
                }
            }
            catch (AmazonS3Exception e)
            {
                _logger.LogInformation(e.Message);
                throw;
            }
            catch (Exception e)
            {
                _logger.LogInformation(e.Message);
            }
        }
Exemple #11
0
 private async Task EnsureBucketCreatedAsync(string bucketName)
 {
     if (!(await AmazonS3Util.DoesS3BucketExistAsync(_amazonS3Client, bucketName)))
     {
         throw new AmazonS3Exception(string.Format("Bucket is missing", bucketName));
     }
 }
        //private AmazonS3Client s3Client = new AmazonS3Client(
        //    new BasicAWSCredentials("########", "########"),
        //    RegionEndpoint.EUCentral1);

        public void Initialize()
        {
            if (AmazonS3Util.DoesS3BucketExistAsync(s3Client, BUCKET).Result)
            {
                return;
            }

            try
            {
                s3Client.PutBucketAsync(new PutBucketRequest
                {
                    BucketName      = BUCKET,
                    UseClientRegion = true
                }).RunSynchronously();
            }
            catch (AmazonS3Exception e)
            {
                if (e.ErrorCode != null &&
                    (e.ErrorCode.Equals("InvalidAccessKeyId") ||
                     e.ErrorCode.Equals("InvalidSecurity")))
                {
                    throw new DMSException("Check the provided AWS Credentials.");
                }

                throw new DMSException($"Error occurred. Message:'{e.Message}' when writing an object");
            }
        }
Exemple #13
0
        /*
         * public async Task MergeIntoBucketAsync(string repoName, string branchName, string parentBranchName)
         * {
         *  using (s3Client = new AmazonS3Client(bucketRegion))
         *  {
         *      // TODO TODO TODO TODO
         *
         *
         *
         *
         *
         *      throw new NotImplementedException();
         *  }
         * }
         */



        private async Task <PutBucketResponse> CreateBucketAsync(string bucketName)
        {
            try
            {
                if (!(await AmazonS3Util.DoesS3BucketExistAsync(s3Client, bucketName)))
                {
                    var putBucketRequest = new PutBucketRequest
                    {
                        BucketName      = bucketName,
                        UseClientRegion = true
                    };

                    PutBucketResponse putBucketResponse = await s3Client.PutBucketAsync(putBucketRequest);

                    return(putBucketResponse);
                }
                else
                {
                    return(new PutBucketResponse {
                        HttpStatusCode = HttpStatusCode.Conflict
                    });
                }
            }
            catch (Exception)
            {
                return(new PutBucketResponse {
                    HttpStatusCode = HttpStatusCode.InternalServerError
                });
            }
        }
Exemple #14
0
        /// <summary>
        ///     Uploads a stream to minio
        /// </summary>
        /// <param name="bucketName">the bucket under which to save the datastream</param>
        /// <param name="dataStream">the object to save</param>
        /// <returns>the minio id on which the item can be retrieved</returns>
        public async Task <string> UploadFile(string bucketName, Stream dataStream)
        {
            var client = GetClient();

            var bucketExist = await AmazonS3Util.DoesS3BucketExistAsync(client, bucketName);


            if (!bucketExist)
            {
                await client.PutBucketAsync(bucketName);
            }
            var fileId = Guid.NewGuid().ToString();

            var putResult = await GetClient().PutObjectAsync(new PutObjectRequest
            {
                BucketName  = bucketName,
                Key         = fileId,
                InputStream = dataStream
            });

            var code = putResult.HttpStatusCode;

            if (code == HttpStatusCode.OK)
            {
                return(fileId);
            }

            throw new AmazonS3Exception("Upload Error");
        }
        private async Task EnsureBucketExistAsync()
        {
            using (IAmazonS3 s3Client = CreateS3Client())
            {
                try
                {
                    if (await AmazonS3Util.DoesS3BucketExistAsync(s3Client, _options.BucketName))
                    {
                        return;
                    }
                }
                catch (Exception e)
                {
                    throw new RebusApplicationException(e, "Unexpected exception occured");
                }

                try
                {
                    await s3Client.PutBucketAsync(new PutBucketRequest
                    {
                        BucketName      = _options.BucketName,
                        UseClientRegion = true
                    });
                }
                catch (AmazonS3Exception e) when(e.StatusCode == HttpStatusCode.Conflict)
                {
                }
            }
        }
Exemple #16
0
        public async Task <List <S3Object> > ListAllObjectsInBucket(string name = null)
        {
            List <S3Object> objects    = new List <S3Object>();
            string          bucketName = name;

            if (bucketName == null)
            {
                bucketName = awsS3Options.Bucket;
            }
            using (AmazonS3Client client = CreateClient())
            {
                var exists = await AmazonS3Util.DoesS3BucketExistAsync(client, bucketName);

                if (exists)
                {
                    string continuationToken = null;
                    do
                    {
                        var response = await client.ListObjectsV2Async(new ListObjectsV2Request()
                        {
                            BucketName        = bucketName,
                            ContinuationToken = continuationToken
                        });

                        continuationToken = response.ContinuationToken;
                        objects.AddRange(response.S3Objects);
                    }while (continuationToken != null);
                }
            }
            return(objects);
        }
Exemple #17
0
 public void End()
 {
     if (AmazonS3Util.DoesS3BucketExistAsync(s3Client, _bucketName).Result)
     {
         _s3.DeleteFilesAsync("").Wait();
         s3Client.DeleteBucketAsync(_bucketName).Wait();
     }
 }
Exemple #18
0
 static bool DoesBucketExist(string bucketName)
 {
     if ((AmazonS3Util.DoesS3BucketExistAsync(s3Client, bucketName).Result))
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
Exemple #19
0
 private async Task DoInitialize()
 {
     if (!await AmazonS3Util.DoesS3BucketExistAsync(Client, _bucketName).ConfigureAwait(false))
     {
         var putRequest = new PutBucketRequest
         {
             BucketName = _bucketName,
         };
         await Client.PutBucketAsync(putRequest).ConfigureAwait(false);
     }
 }
Exemple #20
0
        public async Task <ObjectResult> CreateBucketAsync(string bucketName)
        {
            if (await AmazonS3Util.DoesS3BucketExistAsync(_client, bucketName) == false)
            {
                var putBucketRequest = new PutBucketRequest()
                {
                    BucketName      = bucketName,
                    UseClientRegion = true
                };
                var respose = await _client.PutBucketAsync(putBucketRequest);

                return(new OkObjectResult("Bucket created successfully"));
            }
            return(new BadRequestObjectResult("Bucket already created"));
        }
 private static void TestIfBucketExists(string bucketName)
 {
     using (var s3Client = Construction.GetAmazonS3Client())
     {
         var bucketExists = AmazonS3Util.DoesS3BucketExistAsync(s3Client, bucketName).Result;
         if (bucketExists)
         {
             Console.WriteLine($"Bucket '{bucketName}' exists!");
         }
         else
         {
             Console.WriteLine($"Bucket '{bucketName}' does NOT exist...");
         }
     }
 }
Exemple #22
0
        public async Task <bool> BucketExists(string name = null)
        {
            string bucketName = name;

            if (bucketName == null)
            {
                bucketName = awsS3Options.Bucket;
            }
            using (AmazonS3Client client = CreateClient())
            {
                var exists = await AmazonS3Util.DoesS3BucketExistAsync(client, bucketName);

                return(exists);
            }
        }
        /// <summary>
        ///     Create a bucket, sending the Bucket Name
        /// </summary>
        /// <param name="bucketName">Bucket Name (string)</param>
        /// <returns></returns>
        public async Task <S3Response> CreateBucketAsync(string bucketName)
        {
            try
            {
                // Check if bucket exists, then create it
                if (await AmazonS3Util.DoesS3BucketExistAsync(_client, bucketName) == false)
                {
                    var putBucketRequest = new PutBucketRequest
                    {
                        BucketName      = bucketName,
                        UseClientRegion = true
                    };
                    var response = await _client.PutBucketAsync(putBucketRequest);

                    return(new S3Response
                    {
                        Message = response.ResponseMetadata.RequestId,
                        Status = response.HttpStatusCode
                    });
                }
            }

            // Catch specific amazon errors
            catch (AmazonS3Exception e)
            {
                return(new S3Response
                {
                    Message = e.Message,
                    Status = e.StatusCode
                });
            }

            // Catch other errors
            catch (Exception e)
            {
                return(new S3Response
                {
                    Message = e.Message,
                    Status = HttpStatusCode.InternalServerError
                });
            }

            return(new S3Response
            {
                Message = "Something went wrong",
                Status = HttpStatusCode.InternalServerError
            });
        }
        private async Task CreateBucket()
        {
            using (var client = new AmazonS3Client(Keys.AccessKey, Keys.SecretKey, RegionEndpoint.USEast2))
            {
                if (await AmazonS3Util.DoesS3BucketExistAsync(client, Keys.BucketName) == false)
                {
                    var putBucketRequest = new PutBucketRequest
                    {
                        BucketName      = Keys.BucketName,
                        UseClientRegion = true
                    };

                    await client.PutBucketAsync(putBucketRequest);
                }
            }
        }
Exemple #25
0
        public async Task CreateBucket(string bucketName)
        {
            using (var client = new AmazonS3Client(accessKeyId, accessKey, RegionEndpoint.USEast2))
            {
                if (await AmazonS3Util.DoesS3BucketExistAsync(client, bucketName) == false)
                {
                    var putBucketRequest = new PutBucketRequest
                    {
                        BucketName      = bucketName,
                        UseClientRegion = true
                    };

                    await client.PutBucketAsync(putBucketRequest);
                }
            }
        }
Exemple #26
0
        public async Task <S3Response> CreateBucketAsync(string bucketName)
        {
            var res = new S3Response
            {
                Status  = HttpStatusCode.InternalServerError,
                Message = "Error"
            };

            try
            {
                if (await AmazonS3Util.DoesS3BucketExistAsync(_client, bucketName) == false)
                {
                    var putBucketRequest = new PutBucketRequest
                    {
                        BucketName      = bucketName,
                        UseClientRegion = true
                    };

                    //relies on credentials C:\Users\<user>\.aws (access key in file & secret key can only be seen when creating access key 1st time via AWS console)
                    var response = await _client.PutBucketAsync(putBucketRequest);

                    res.Status  = response.HttpStatusCode;
                    res.Message = response.ResponseMetadata.RequestId;
                }
                else
                {
                    res.Status  = HttpStatusCode.Conflict;
                    res.Message = string.Format("Already exists : {0}", bucketName);
                }
            }
            catch (AmazonS3Exception exaws)
            {
                Console.WriteLine(exaws);
                res.Status  = exaws.StatusCode;
                res.Message = exaws.Message;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                res.Status  = HttpStatusCode.InternalServerError;
                res.Message = ex.Message;
            }

            return(res);
        }
Exemple #27
0
        public async Task <CreateS3BucketResponce> CreateBucketAsync(string bucketName)
        {
            try
            {
                if (await AmazonS3Util.DoesS3BucketExistAsync(_client, bucketName))
                {
                    return(new CreateS3BucketResponce
                    {
                        StatusCode = HttpStatusCode.InternalServerError,
                        Message = $"Bucket {bucketName} already exists."
                    });
                }

                var putBucketRequest = new PutBucketRequest
                {
                    BucketName      = bucketName,
                    UseClientRegion = true,
                    CannedACL       = S3CannedACL.PublicRead
                };

                var response = await _client.PutBucketAsync(putBucketRequest);

                return(new CreateS3BucketResponce
                {
                    StatusCode = response.HttpStatusCode,
                    Message = response.ResponseMetadata.RequestId
                });
            }
            catch (AmazonS3Exception e)
            {
                return(new CreateS3BucketResponce
                {
                    StatusCode = e.StatusCode,
                    Message = e.Message
                });
            }
            catch (Exception e)
            {
                return(new CreateS3BucketResponce
                {
                    StatusCode = HttpStatusCode.InternalServerError,
                    Message = e.Message
                });
            }
        }
Exemple #28
0
 public static async Task CreateBucket()
 {
     using (var client = new AmazonS3Client(region))
     {
         if (!(await AmazonS3Util.DoesS3BucketExistAsync(client, bucket)))
         {
             await CreateBucket(client);
         }
         for (int x = 0; !(await AmazonS3Util.DoesS3BucketExistAsync(client, bucket)); x++)
         {
             Thread.Sleep(1);
             if (x == 30000)
             {
                 throw new Exception("Bucket " + bucket + " was successfully created but still could not be found after 30 seconds. Wait a few minutes and try again or check S3");
             }
         }
     }
 }
Exemple #29
0
        public async Task <S3Response> CreateBucketAsync(string bucketName)
        {
            try
            {
                if (await AmazonS3Util.DoesS3BucketExistAsync(_client, bucketName) == false)
                {
                    var putBucketRequest = new PutBucketRequest
                    {
                        BucketName      = bucketName,
                        UseClientRegion = true
                    };

                    var response = await _client.PutBucketAsync(putBucketRequest);

                    return(new S3Response
                    {
                        Message = response.ResponseMetadata.RequestId,
                        status = response.HttpStatusCode
                    });
                }
            }
            catch (AmazonS3Exception e)
            {
                return(new S3Response
                {
                    Message = e.Message,
                    status = e.StatusCode
                });
            }
            catch (Exception e)
            {
                return(new S3Response
                {
                    status = HttpStatusCode.InternalServerError,
                    Message = e.Message
                });
            }

            return(new S3Response
            {
                Message = "Internal error",
                status = HttpStatusCode.InternalServerError
            });
        }
Exemple #30
0
        public async Task <S3Response> DeleteBucketAsync(string bucketName)
        {
            try
            {
                if (await AmazonS3Util.DoesS3BucketExistAsync(_client, bucketName) == true)
                {
                    var deleteBucketRequest = new DeleteBucketRequest
                    {
                        BucketName      = bucketName,
                        UseClientRegion = true
                    };

                    var response = await _client.DeleteBucketAsync(deleteBucketRequest);

                    return(new S3Response
                    {
                        Message = response.ResponseMetadata.RequestId,
                        Status = response.HttpStatusCode
                    });
                }
            }
            catch (AmazonS3Exception e)
            {
                return(new S3Response
                {
                    Message = e.Message,
                    Status = e.StatusCode
                });
            }
            catch (Exception e)
            {
                return(new S3Response
                {
                    Status = HttpStatusCode.InternalServerError,
                    Message = e.Message
                });
            }

            return(new S3Response
            {
                Status = HttpStatusCode.InternalServerError,
                Message = "Bucket não existe"
            });
        }