private async Task CheckBucketExists() { if (!_bucketExist) { _bucketExist = await _s3Client.DoesS3BucketExistAsync(_bucketName); while (_bucketExist == false) { S3Region s3region = S3Region.FindValue(_config.AmazonRegion); var putBucketRequest = new PutBucketRequest { BucketName = _bucketName, BucketRegion = s3region, }; try { EnsureValidResponse(await _s3Client.PutBucketAsync(putBucketRequest), HttpStatusCode.OK); } catch (AmazonS3Exception ex) { if (ex.ErrorCode == "BucketAlreadyOwnedByYou") { break; } throw; } _bucketExist = await _s3Client.DoesS3BucketExistAsync(_bucketName); } } }
public AmazonPictureService(IRepository <Picture> pictureRepository, ISettingService settingService, IWebHelper webHelper, ILogger logger, IEventPublisher eventPublisher, MediaSettings mediaSettings, GrandConfig config) : base(pictureRepository, settingService, webHelper, logger, eventPublisher, mediaSettings) { this._config = config; //Arguments guard if (string.IsNullOrEmpty(_config.AmazonAwsAccessKeyId)) { throw new ArgumentNullException("AmazonAwsAccessKeyId"); } if (string.IsNullOrEmpty(_config.AmazonAwsSecretAccessKey)) { throw new ArgumentNullException("AmazonAwsSecretAccessKey"); } if (string.IsNullOrEmpty(_config.AmazonBucketName)) { throw new ArgumentNullException("AmazonBucketName"); } //Region guard RegionEndpoint regionEndpoint = RegionEndpoint.GetBySystemName(_config.AmazonRegion); if (regionEndpoint.DisplayName == "Unknown") { throw new NullReferenceException("specified Region is invalid"); } //Client guard _s3Client = new AmazonS3Client(_config.AmazonAwsAccessKeyId, _config.AmazonAwsSecretAccessKey, regionEndpoint); try { EnsureValidResponse(_s3Client.ListBucketsAsync().Result, HttpStatusCode.OK); } catch (Exception ex) { throw new Exception(ex.Message); } //Bucket guard _bucketName = _config.AmazonBucketName; var bucketExists = _s3Client.DoesS3BucketExistAsync(_bucketName).Result; while (bucketExists == false) { S3Region s3region = S3Region.FindValue(_config.AmazonRegion); var putBucketRequest = new PutBucketRequest { BucketName = _bucketName, BucketRegion = s3region, }; try { EnsureValidResponse(_s3Client.PutBucketAsync(putBucketRequest).Result, HttpStatusCode.OK); } catch (AmazonS3Exception ex) { if (ex.ErrorCode == "BucketAlreadyOwnedByYou") { break; } throw; } bucketExists = _s3Client.DoesS3BucketExistAsync(_bucketName).Result; } }