Esempio n. 1
0
        public string SaveImageToS3(S3ConnectionProfileEntity currentConnectionProfile, S3PictureEntity picture)
        {
            try
            {
                var client = GetAmazonS3Client();

                var stream = DataAccessHelper.GetStream(picture.S3Image, ImageFormat.Jpeg);                 //We are assuming all JPG for our images

                var key = $"{currentConnectionProfile.FolderName}/{picture.FileName}";
                if (currentConnectionProfile.FolderName.Length == 0)
                {
                    key = $"{picture.FileName}";
                }

                var request = new PutObjectRequest
                {
                    BucketName      = currentConnectionProfile.BucketName,
                    InputStream     = stream,
                    ContentType     = "image/jpeg",
                    Key             = key,
                    CannedACL       = S3CannedACL.FindValue(currentConnectionProfile.CannedACL),
                    AutoCloseStream = true,
                    StorageClass    = S3StorageClass.Standard,
                };


                client.PutObject(request);
                return(key);
            }
            catch (Exception exception)
            {
                throw new Exception($"Error {exception.Message}");
            }
        }
Esempio n. 2
0
 public S3FileStorageOptionsBuilder CannedACL(string cannedAcl)
 {
     if (string.IsNullOrEmpty(cannedAcl))
     {
         throw new ArgumentNullException(nameof(cannedAcl));
     }
     Target.CannedACL = S3CannedACL.FindValue(cannedAcl);
     return(this);
 }
        public static S3CannedACL ParseCannedAcl(string aclParam)
        {
            if (string.IsNullOrEmpty(aclParam))
            {
                return(S3CannedACL.PublicRead);
            }

            return(ValidAcls.Contains(aclParam)
                ? S3CannedACL.FindValue(aclParam)
                : S3CannedACL.PublicRead);
        }
        /// <summary>
        /// Specifies the ACL to be used for S3 Buckets or S3 Objects.
        /// </summary>
        /// <param name="settings">The upload settings.</param>
        /// <param name="cannedACL">The canned ACL name.</param>
        /// <returns>The same <see cref="UploadSettings"/> instance so that multiple calls can be chained.</returns>
        public static UploadSettings SetCannedACL(this UploadSettings settings, string cannedACL)
        {
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }
            if (string.IsNullOrEmpty(cannedACL))
            {
                throw new ArgumentNullException("cannedACL");
            }

            settings.CannedACL = S3CannedACL.FindValue(cannedACL);
            return(settings);
        }
Esempio n. 5
0
        public override void OnExecute()
        {
            Client = Context.CredentialProvider.Get <S3Credential, AmazonS3Client>();

            var response = Client.PutACL(new Amazon.S3.Model.PutACLRequest()
            {
                BucketName = BucketName,
                Key        = RemoteFilePath,
                CannedACL  = S3CannedACL.FindValue(Acl)
            });

            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                throw new InvalidOperationException($"S3Response => {response.HttpStatusCode}");
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Creates an upload file request based on the s3 target properties for a given file and bucket key.
        /// </summary>
        /// <param name="path"></param>
        /// <param name="bucketKey"></param>
        /// <param name="properties"></param>
        /// <returns>PutObjectRequest with all information including metadata and tags from provided properties</returns>
        private PutObjectRequest CreateRequest(string path, Func <string> bucketKey, S3TargetPropertiesBase properties)
        {
            Guard.NotNullOrWhiteSpace(path, "The given path may not be null");
            Guard.NotNullOrWhiteSpace(bucket, "The provided bucket key may not be null");
            Guard.NotNull(properties, "Target properties may not be null");

            var request = new PutObjectRequest
            {
                FilePath     = path,
                BucketName   = bucket?.Trim(),
                Key          = bucketKey()?.Trim(),
                StorageClass = S3StorageClass.FindValue(properties.StorageClass?.Trim()),
                CannedACL    = S3CannedACL.FindValue(properties.CannedAcl?.Trim())
            }
            .WithMetadata(properties)
            .WithTags(properties);

            return(md5HashSupported ? request.WithMd5Digest(fileSystem) : request);
        }
Esempio n. 7
0
        public async Task Deliver(Uri destination, MsgNThenMessage message)
        {
            //https://s3.us-east-2.amazonaws.com/my-bucket-name/filename
            //s3://john.doe@my-bucket-name/filename[
            //s3://<credentialName>@<bucketname>/filename
            var credentials     = GetCredentials(destination);
            var bucketName      = destination.Host;
            var pathAndQuery    = Uri.UnescapeDataString(destination.PathAndQuery).TrimStart('/');
            var messageId       = message.Headers[HeaderConstants.MessageId];
            var messageGroupId  = message.Headers[HeaderConstants.MessageGroupId];
            var correlationId   = message.Headers[HeaderConstants.CorrelationId];
            var fileKey         = string.Format(pathAndQuery, messageId, messageGroupId, correlationId);
            var queryDictionary = QueryHelpers.ParseQuery(destination.Query);

            if (message.Body.CanSeek)
            {
                message.Body.Position = 0;
            }
            using (var client = new AmazonS3Client(credentials.awsAccessKeyId, credentials.awsSecretAccessKey, RegionEndpoint.USEast1))
            {
                var uploadRequest = new TransferUtilityUploadRequest
                {
                    InputStream = message.Body,
                    Key         = fileKey,
                    BucketName  = bucketName,
                    CannedACL   = S3CannedACL.BucketOwnerFullControl
                };
                if (queryDictionary.TryGetValue(QueryConstants.S3CannedACL, out var val))
                {
                    var cannedAcl = S3CannedACL.FindValue(val);
                    if (cannedAcl != null)
                    {
                        uploadRequest.CannedACL = cannedAcl;
                    }
                }

                var fileTransferUtility = new TransferUtility(client);
                await fileTransferUtility.UploadAsync(uploadRequest);
            }
        }
Esempio n. 8
0
        private InitiateMultipartUploadRequest requestFromCtrls()
        {
            InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest();

            // Set storage class from control values
            if (RadioReducedRedund.Checked)
            {
                request.StorageClass = S3StorageClass.ReducedRedundancy;
            }
            else if (RadioStandardIA.Checked)
            {
                request.StorageClass = S3StorageClass.StandardInfrequentAccess;
            }
            else
            {
                request.StorageClass = S3StorageClass.Standard;
            }

            // Set other fields from control values
            request.WebsiteRedirectLocation = TxtWebsite.Text;
            request.RequestPayer            = (ChkRequestPayer.Checked ? RequestPayer.Requester : null);

            // Set metadata from control values
            IEnumerable <DataGridViewRow> metaRows = DgvMetadata.Rows.Cast <DataGridViewRow>().Where(r => !r.IsNewRow);

            foreach (DataGridViewRow row in metaRows)
            {
                string key = row.Cells[DgvColMetadataKey.Index].Value.ToString();
                string val = row.Cells[DgvColMetadataValue.Index].Value.ToString();
                request.Metadata.Add(key, val);
            }

            // Set headers from control values
            request.Headers.ContentType        = TxtType.Text;
            request.Headers.ContentDisposition = TxtDisposition.Text;
            request.Headers.ContentEncoding    = TxtEncoding.Text;
            request.Headers.Expires            = DatePickerExpires.Value.ToUniversalTime();

            // Initialize access control
            bool useCannedAcl = ChkUseCannedACLs.Checked;

            request.CannedACL = (useCannedAcl ? S3CannedACL.FindValue(ComboAcl.Text) : null);
            if (useCannedAcl)
            {
                request.Grants = null;
            }
            else
            {
                IEnumerable <S3Grant> grants = DgvGrants.Rows.Cast <DataGridViewRow>()
                                               .Where(r => !r.IsNewRow)
                                               .SelectMany(r => grantsFromRow(r));
                request.Grants.AddRange(grants);
            }

            // Initialize server side encryption method
            bool kms    = RadioSseKms.Checked;
            bool newKey = RadioSseNewKey.Checked;

            if (kms)
            {
                request.ServerSideEncryptionMethod = ServerSideEncryptionMethod.AWSKMS;
            }
            else if (newKey)
            {
                request.ServerSideEncryptionMethod = ServerSideEncryptionMethod.AES256;
            }
            else
            {
                request.ServerSideEncryptionMethod = ServerSideEncryptionMethod.None;
            }

            // Set server side encryption from control values
            request.ServerSideEncryptionKeyManagementServiceKeyId = (kms ? TxtSseKeyId.Text : null);
            request.ServerSideEncryptionCustomerMethod            = (newKey ? ServerSideEncryptionCustomerMethod.AES256 : ServerSideEncryptionCustomerMethod.None);
            request.ServerSideEncryptionCustomerProvidedKey       = (newKey ? TxtSseCustomerKey.Text : null);
            request.ServerSideEncryptionCustomerProvidedKeyMD5    = (newKey ? TxtSseCustomerKeyMd5.Text : null);

            return(request);
        }