The parameters to request metadata for an object.
상속: Amazon.S3.Model.S3Request
예제 #1
48
 public DateTime LastWriteTime(string id)
 {
     using (var client = SetupClient())
     {
         try {
             var request = new GetObjectMetadataRequest().WithBucketName(BucketName).WithKey(id);
             var response = client.GetObjectMetadata(request);
             var date = response.LastModified;
             var lastwrite = response.Metadata[LastWriteTimeKey];
             return DateTime.Parse(lastwrite);
         }
         catch
         {
             return DateTime.MinValue;
         }
     }
 }
        public async Task <MetadataCollection> GetObjectMetadataAsync(string bucket,
                                                                      string key,
                                                                      CancellationToken cancellationToken = default)
        {
            this.Logger.LogDebug($"[{nameof(this.GetObjectMetadataAsync)}]");

            this.Logger.LogTrace(JsonConvert.SerializeObject(new { bucket, key }));

            if (string.IsNullOrWhiteSpace(bucket))
            {
                throw new ArgumentNullException(nameof(bucket));
            }
            if (string.IsNullOrWhiteSpace(key))
            {
                throw new ArgumentNullException(nameof(key));
            }

            var request = new Amazon.S3.Model.GetObjectMetadataRequest
            {
                BucketName = bucket,
                Key        = key,
            };

            this.Logger.LogTrace(JsonConvert.SerializeObject(value: request));

            var response = await this.Repository.GetObjectMetadataAsync(request : request,
                                                                        cancellationToken : cancellationToken == default?this.CancellationToken.Token : cancellationToken);

            this.Logger.LogTrace(JsonConvert.SerializeObject(value: response));

            return(response.Metadata);
        }
예제 #3
0
        /// <summary>
        /// Executes the task.
        /// </summary>
        /// <returns>True if the task executed successfully, false otherwise.</returns>
        public override bool Execute()
        {
            bool exists = false;

            GetObjectMetadataRequest request = new GetObjectMetadataRequest()
                .WithBucketName(BucketName)
                .WithKey(this.Key);

            try
            {
                using (GetObjectMetadataResponse response = Client.GetObjectMetadata(request))
                {
                    exists = true;
                }
            }
            catch (AmazonS3Exception ex)
            {
                if (ex.StatusCode != HttpStatusCode.NotFound || !"NoSuchKey".Equals(ex.ErrorCode, StringComparison.OrdinalIgnoreCase))
                {
                    throw;
                }
            }

            Exists = exists;
            return true;
        }
예제 #4
0
        public BucketRegionTestRunner(bool useSigV4, bool useSigV4SetExplicitly = false)
        {
            originalUseSignatureVersion4 = AWSConfigsS3.UseSignatureVersion4;
            originalUseSigV4SetExplicitly = GetAWSConfigsS3InternalProperty();
            AWSConfigsS3.UseSignatureVersion4 = useSigV4;
            SetAWSConfigsS3InternalProperty(useSigV4SetExplicitly);

            CreateAndCheckTestBucket();
            if (TestBucketIsReady)
            {
                GetObjectMetadataRequest = new GetObjectMetadataRequest()
                {
                    BucketName = TestBucket.BucketName,
                    Key = TestObjectKey
                };
                PutObjectRequest = new PutObjectRequest()
                {
                    BucketName = TestBucket.BucketName,
                    Key = TestObjectKey,
                    ContentBody = TestContent
                };
                PreSignedUrlRequest = new GetPreSignedUrlRequest
                {
                    BucketName = BucketName,
                    Key = BucketRegionTestRunner.TestObjectKey,
                    Expires = DateTime.Now.AddHours(1)
                };
            }
        }
예제 #5
0
파일: S3Client.cs 프로젝트: jrolstad/Motore
        protected internal virtual GetObjectMetadataRequest CreateGetObjectMetadataRequest(string bucket, string path)
        {
            var request = new GetObjectMetadataRequest
                              {
                                  BucketName = bucket,
                                  Key = path,
                              };

            return request;
        }
예제 #6
0
        /// <summary>
        /// Invoked when the publisher has published a file.
        /// </summary>
        /// <param name="path">The local path of the file that was published.</param>
        /// <param name="objectKey">The object key the file was published to.</param>
        /// <param name="withGzip">A value indicating whether the file was GZipped prior to publishing.</param>
        public void OnFilePublished(string path, string objectKey, bool withGzip)
        {
            if (this.assertPublished)
            {
                GetObjectMetadataRequest request = new GetObjectMetadataRequest()
                    .WithBucketName(BucketName)
                    .WithKey(objectKey);

                using (GetObjectMetadataResponse response = Client.GetObjectMetadata(request))
                {
                    Assert.AreEqual(MimeType.FromCommon(objectKey).ContentType, response.ContentType);

                    if (withGzip)
                    {
                        Assert.AreEqual("gzip", response.Headers["Content-Encoding"]);
                    }
                }
            }
        }
예제 #7
0
        bool FileExists(string key)
        {
            try
            {
                var request = new GetObjectMetadataRequest()
                    .WithBucketName(bucket)
                    .WithKey(key);

                var response = s3client.GetObjectMetadata(request);

                return true;
            }
            catch(AmazonS3Exception ex)
            {
                if(ex.StatusCode == HttpStatusCode.NotFound)
                {
                    return false;
                }
                throw;
            }
        }
        public async void Test_Blob_Properties_Updated_Async()
        {
            var container = GetRandomContainerName();
            var blobName = GenerateRandomName();
            var contentType = "image/jpg";
            var newContentType = "image/png";
            var data = GenerateRandomBlobStream();

            await CreateNewObjectAsync(container, blobName, data, false, contentType);

            await _provider.UpdateBlobPropertiesAsync(container, blobName, new BlobProperties
            {
                ContentType = newContentType,
                Security = BlobSecurity.Public
            });

            var objectMetaRequest = new GetObjectMetadataRequest()
            {
                BucketName = Bucket,
                Key = container + "/" + blobName
            };

            var props = await _client.GetObjectMetadataAsync(objectMetaRequest);

            Assert.Equal(props.Headers.ContentType, newContentType);

            var objectAclRequest = new GetACLRequest()
            {
                BucketName = Bucket,
                Key = container + "/" + blobName
            };

            var acl = await _client.GetACLAsync(objectAclRequest);

            var isPublic = acl.AccessControlList.Grants
                .Where(x => x.Grantee.URI == "http://acs.amazonaws.com/groups/global/AllUsers").Count() > 0;

            Assert.True(isPublic);
        }
예제 #9
0
        public async Task<FileSpec> GetFileInfoAsync(string path) {
            using (var client = CreateClient()) {
                var req = new GetObjectMetadataRequest {
                    BucketName = _bucket,
                    Key = path.Replace('\\', '/')
                };

                try {
                    var res = await client.GetObjectMetadataAsync(req).AnyContext();

                    if (!res.HttpStatusCode.IsSuccessful())
                        return null;

                    return new FileSpec {
                        Size = res.ContentLength,
                        Created = res.LastModified,
                        Modified = res.LastModified,
                        Path = path
                    };
                } catch (AmazonS3Exception) {
                    return null;
                }
            }
        }
        public virtual async Task<QueryResult<bool>> Exists(string namePath)
        {
            bool exists = false;
            bool hasExceptions = false;

            try
            {
                IAmazonS3 client = GetS3Client();

                GetObjectMetadataRequest request = new GetObjectMetadataRequest()
                {
                    BucketName = Settings.BucketName,
                    Key = namePath
                };

                GetObjectMetadataResponse response
                    = await client.GetObjectMetadataAsync(request);

                exists = true;
            }
            catch (AmazonS3Exception ex)
            {
                if(ex.StatusCode == System.Net.HttpStatusCode.NotFound)
                {
                    exists = false;
                }
                else
                {
                    _logger.Exception(ex);
                    hasExceptions = true;
                }
            }

            return new QueryResult<bool>(exists, hasExceptions);
        }
예제 #11
0
    public bool FileExists(string virtualPath) {
      var request = new GetObjectMetadataRequest()
        .WithBucketName(this.bucketName)
        .WithKey(FixPathForS3(virtualPath));

      try {
        using (this.s3.GetObjectMetadata(request)) { }
      } catch (AmazonS3Exception) {
        return false;
      }
      return true;
    }
예제 #12
0
    public bool DirectoryExists(string virtualPath) { // ~/upload/28/
      virtualPath = FixPathForS3(virtualPath) + EmptyFilename;

      var request = new GetObjectMetadataRequest()
        .WithBucketName(this.bucketName)
        .WithKey(virtualPath);

      try {
        using (this.s3.GetObjectMetadata(request)) { }
      } catch (AmazonS3Exception) {
        return false;
      }
      return true;
    }
예제 #13
0
        /// <summary>
        /// Initiates the asynchronous execution of the GetObjectMetadata operation.
        /// <seealso cref="Amazon.S3.IAmazonS3.GetObjectMetadata"/>
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the GetObjectMetadata 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<GetObjectMetadataResponse> GetObjectMetadataAsync(GetObjectMetadataRequest request, CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new GetObjectMetadataRequestMarshaller();
            var unmarshaller = GetObjectMetadataResponseUnmarshaller.GetInstance();
            return Invoke<IRequest, GetObjectMetadataRequest, GetObjectMetadataResponse>(request, marshaller, unmarshaller, signer, cancellationToken);
        }
예제 #14
0
        /// <summary>
        /// Returns information about a specified object.
        /// </summary>
        /// <remarks>
        /// Retrieves information about a specific object or object size, without actually fetching the object itself.
        /// This is useful if you're only interested in the object metadata, and don't want to waste bandwidth on the object data.
        /// The response is identical to the GetObject response, except that there is no response body.
        /// </remarks>
        /// <param name="request">Container for the necessary parameters to execute the GetObjectMetadata service method on AmazonS3.</param>
        /// <returns>The response from the HeadObject service method, as returned by AmazonS3.</returns>
		public GetObjectMetadataResponse GetObjectMetadata(GetObjectMetadataRequest request)
        {
            var task = GetObjectMetadataAsync(request);
            try
            {
                return task.Result;
            }
            catch(AggregateException e)
            {
                throw e.InnerException;
            }
        }
예제 #15
0
        /// <summary>
        /// Initiates the asynchronous execution of the GetObjectMetadata operation.
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the GetObjectMetadata 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 EndGetObjectMetadata
        ///         operation.</returns>
        public IAsyncResult BeginGetObjectMetadata(GetObjectMetadataRequest request, AsyncCallback callback, object state)
        {
            var marshaller = new GetObjectMetadataRequestMarshaller();
            var unmarshaller = GetObjectMetadataResponseUnmarshaller.Instance;

            return BeginInvoke<GetObjectMetadataRequest>(request, marshaller, unmarshaller,
                callback, state);
        }
예제 #16
0
        /// <summary>
        /// Initiates the asynchronous execution of the GetObjectMetadata operation.
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the GetObjectMetadata 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<GetObjectMetadataResponse> GetObjectMetadataAsync(GetObjectMetadataRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new GetObjectMetadataRequestMarshaller();
            var unmarshaller = GetObjectMetadataResponseUnmarshaller.Instance;

            return InvokeAsync<GetObjectMetadataRequest,GetObjectMetadataResponse>(request, marshaller, 
                unmarshaller, cancellationToken);
        }
예제 #17
0
        public bool ObjectExists(Uri uri)
        {
            CheckUri(uri);

            try
            {
                using (var client = CreateAmazonS3Client())
                {
                    try
                    {
                        var absolutePath = HttpUtility.UrlDecode(uri.AbsolutePath);
                        var key = absolutePath.TrimStart('/');
                        var request = new GetObjectMetadataRequest();

                        request.WithBucketName(bucketName)
                            .WithKey(key);

                        using (client.GetObjectMetadata(request))
                        {
                            return true;
                        }
                    }
                    catch (AmazonS3Exception ex)
                    {
                        if (ex.StatusCode == HttpStatusCode.NotFound)
                        {
                            return false;
                        }

                        // Status not found - throw the exception.
                        throw;
                    }
                }
            }
            catch (Exception e)
            {
                throw new StorageException(string.Format("Failed to check if object exists {0}.", uri), e);
            }
        }
예제 #18
0
        internal bool ExistsWithBucketCheck(out bool bucketExists)
        {
            bucketExists = true;
            try
            {
                var request = new GetObjectMetadataRequest
                {
                    BucketName = bucket,
                    Key = S3Helper.EncodeKey(key)
                };
                request.BeforeRequestEvent += S3Helper.FileIORequestEventHandler;

                // If the object doesn't exist then a "NotFound" will be thrown
                s3Client.GetObjectMetadata(request);
                return true;
            }
            catch (AmazonS3Exception e)
            {
                if (string.Equals(e.ErrorCode, "NoSuchBucket"))
                {
                    bucketExists = false;
                    return false;
                }
                else if (string.Equals(e.ErrorCode, "NotFound"))
                {
                    return false;
                }
                throw;
            }
        }
예제 #19
0
 /// <summary>
 /// Initiates the asynchronous execution of the GetObjectMetadata operation.
 /// <seealso cref="Amazon.S3.IAmazonS3.GetObjectMetadata"/>
 /// </summary>
 /// 
 /// <param name="getObjectMetadataRequest">Container for the necessary parameters to execute the GetObjectMetadata 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 EndGetObjectMetadata
 ///         operation.</returns>
 public IAsyncResult BeginGetObjectMetadata(GetObjectMetadataRequest getObjectMetadataRequest, AsyncCallback callback, object state)
 {
     return invokeGetObjectMetadata(getObjectMetadataRequest, callback, state, false);
 }
예제 #20
0
 IAsyncResult invokeGetObjectMetadata(GetObjectMetadataRequest getObjectMetadataRequest, AsyncCallback callback, object state, bool synchronized)
 {
     IRequest irequest = new GetObjectMetadataRequestMarshaller().Marshall(getObjectMetadataRequest);
     var unmarshaller = GetObjectMetadataResponseUnmarshaller.GetInstance();
     AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
     Invoke(result);
     return result;
 }
예제 #21
0
        public bool Exists(string key)
        {
            GetObjectMetadataRequest request = new GetObjectMetadataRequest
            {
                BucketName = Bucket,
                Key = key
            };

            var response = S3Client.GetObjectMetadata(request);

            return response.HttpStatusCode == HttpStatusCode.OK;
        }
예제 #22
0
 /// <summary>
 /// Returns information about a specified object.
 /// </summary>
 /// <remarks>
 /// Retrieves information about a specific object or object size, without actually fetching the object itself. 
 /// This is useful if you're only interested in the object metadata, and don't want to waste bandwidth on the object data.
 /// The response is identical to the GetObject response, except that there is no response body.
 /// </remarks>
 /// <param name="getObjectMetadataRequest">Container for the necessary parameters to execute the GetObjectMetadata service method on AmazonS3.</param>
 /// <returns>The response from the HeadObject service method, as returned by AmazonS3.</returns>
 public GetObjectMetadataResponse GetObjectMetadata(GetObjectMetadataRequest getObjectMetadataRequest)
 {
     IAsyncResult asyncResult = invokeGetObjectMetadata(getObjectMetadataRequest, null, null, true);
     return EndGetObjectMetadata(asyncResult);
 }
예제 #23
0
 /// <summary>
 /// Initiates the asynchronous execution of the GetObjectMetadata operation.
 /// This API is supported only when AWSConfigs.HttpClient is set to AWSConfigs.HttpClientOption.UnityWebRequest, the default value for this configuration option is AWSConfigs.HttpClientOption.UnityWWW
 /// </summary>
 /// 
 /// <param name="request">Container for the necessary parameters to execute the GetObjectMetadata 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 GetObjectMetadataAsync(GetObjectMetadataRequest request, AmazonServiceCallback<GetObjectMetadataRequest, GetObjectMetadataResponse> callback, AsyncOptions options = null)
 {
     if (AWSConfigs.HttpClient == AWSConfigs.HttpClientOption.UnityWWW)
     {
         throw new InvalidOperationException("GetObjectMetadata is only allowed with AWSConfigs.HttpClientOption.UnityWebRequest API option");
     }
     options = options == null?new AsyncOptions():options;
     var marshaller = new GetObjectMetadataRequestMarshaller();
     var unmarshaller = GetObjectMetadataResponseUnmarshaller.Instance;
     Action<AmazonWebServiceRequest, AmazonWebServiceResponse, Exception, AsyncOptions> callbackHelper = null;
     if(callback !=null )
         callbackHelper = (AmazonWebServiceRequest req, AmazonWebServiceResponse res, Exception ex, AsyncOptions ao) => { 
             AmazonServiceResult<GetObjectMetadataRequest,GetObjectMetadataResponse> responseObject 
                     = new AmazonServiceResult<GetObjectMetadataRequest,GetObjectMetadataResponse>((GetObjectMetadataRequest)req, (GetObjectMetadataResponse)res, ex , ao.State);    
                 callback(responseObject); 
         };
     BeginInvoke<GetObjectMetadataRequest>(request, marshaller, unmarshaller, options, callbackHelper);
 }
 private Amazon.S3.Model.GetObjectMetadataResponse CallAWSServiceOperation(IAmazonS3 client, Amazon.S3.Model.GetObjectMetadataRequest request)
 {
     Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon Simple Storage Service (S3)", "GetObjectMetadata");
     try
     {
         #if DESKTOP
         return(client.GetObjectMetadata(request));
         #elif CORECLR
         return(client.GetObjectMetadataAsync(request).GetAwaiter().GetResult());
         #else
                 #error "Unknown build edition"
         #endif
     }
     catch (AmazonServiceException exc)
     {
         var webException = exc.InnerException as System.Net.WebException;
         if (webException != null)
         {
             throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException);
         }
         throw;
     }
 }
예제 #25
0
        public override bool FileExists(string bin, string fileName)
        {
            GetObjectMetadataRequest request = new GetObjectMetadataRequest();
            request.BucketName = bin;
            request.Key = fileName;

            try
            {
                GetObjectMetadataResponse response = client.GetObjectMetadata(request);
            }
            catch (Amazon.S3.AmazonS3Exception ex)
            {
                if (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
                {
                    return false;
                }
                else
                {
                    throw;
                }
            }
            catch (System.Xml.XmlException)
            {
                return false;
            }

            return true;
        }
예제 #26
0
 /// <summary>
 /// The HEAD operation retrieves metadata from an object without returning the object
 /// itself. This operation is useful if you're only interested in an object's metadata.
 /// To use HEAD, you must have READ access to the object.
 /// This API is supported only when AWSConfigs.HttpClient is set to AWSConfigs.HttpClientOption.UnityWebRequest, the default value of this configuration option is AWSConfigs.HttpClientOption.UnityWWW
 /// </summary>
 /// <param name="bucketName">A property of GetObjectMetadataRequest used to execute the GetObjectMetadata service method.</param>
 /// <param name="key">A property of GetObjectMetadataRequest used to execute the GetObjectMetadata service method.</param>
 /// <param name="versionId">VersionId used to reference a specific version of the object.</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>
 /// 
 /// <returns>The response from the GetObjectMetadata service method, as returned by S3.</returns>
 public void GetObjectMetadataAsync(string bucketName, string key, string versionId,  AmazonServiceCallback<GetObjectMetadataRequest, GetObjectMetadataResponse> callback, AsyncOptions options = null)
 {
     var request = new GetObjectMetadataRequest();
     request.BucketName = bucketName;
     request.Key = key;
     request.VersionId = versionId;
     GetObjectMetadataAsync(request, callback, options);
 }
예제 #27
0
        public bool Exists(string key)
        {
            VerifyKey(key);
            key = ConvertKey(key);

            var request = new GetObjectMetadataRequest
            {
                BucketName = BucketName,
                Key = key,
            };

            var exists = false;

            try
            {
                S3.GetObjectMetadata(request);
                exists = true;
            }
            catch (AmazonS3Exception e)
            {
                if (e.ErrorCode != "NotFound")
                {
                    throw;
                }
            }

            return exists;
        }
예제 #28
0
 /// <summary>
 /// The HEAD operation retrieves metadata from an object without returning the object
 /// itself. This operation is useful if you're only interested in an object's metadata.
 /// To use HEAD, you must have READ access to the object.
 /// </summary>
 /// <param name="bucketName">A property of GetObjectMetadataRequest used to execute the GetObjectMetadata service method.</param>
 /// <param name="key">A property of GetObjectMetadataRequest used to execute the GetObjectMetadata service method.</param>
 /// <param name="versionId">VersionId used to reference a specific version of the object.</param>
 /// <param name="cancellationToken">
 ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
 /// </param>
 /// 
 /// <returns>The response from the GetObjectMetadata service method, as returned by S3.</returns>
 public Task<GetObjectMetadataResponse> GetObjectMetadataAsync(string bucketName, string key, string versionId, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
 {
     var request = new GetObjectMetadataRequest();
     request.BucketName = bucketName;
     request.Key = key;
     request.VersionId = versionId;
     return GetObjectMetadataAsync(request, cancellationToken);
 }
예제 #29
0
 /// <summary>
 /// The HEAD operation retrieves metadata from an object without returning the object
 /// itself. This operation is useful if you're only interested in an object's metadata.
 /// To use HEAD, you must have READ access to the object.
 /// </summary>
 /// <param name="bucketName">A property of GetObjectMetadataRequest used to execute the GetObjectMetadata service method.</param>
 /// <param name="key">A property of GetObjectMetadataRequest used to execute the GetObjectMetadata service method.</param>
 /// <param name="versionId">VersionId used to reference a specific version of the object.</param>
 /// 
 /// <returns>The response from the GetObjectMetadata service method, as returned by S3.</returns>
 public GetObjectMetadataResponse GetObjectMetadata(string bucketName, string key, string versionId)
 {
     var request = new GetObjectMetadataRequest();
     request.BucketName = bucketName;
     request.Key = key;
     request.VersionId = versionId;
     return GetObjectMetadata(request);
 }
예제 #30
0
        internal GetObjectMetadataResponse GetObjectMetadata(GetObjectMetadataRequest request)
        {
            var marshaller = new GetObjectMetadataRequestMarshaller();
            var unmarshaller = GetObjectMetadataResponseUnmarshaller.Instance;

            return Invoke<GetObjectMetadataRequest,GetObjectMetadataResponse>(request, marshaller, unmarshaller);
        }
예제 #31
0
        /// <summary>
        /// Sets up the request needed to make an exact copy of the object leaving the parent method
        /// the ability to change just the attribute being requested to change.
        /// </summary>
        /// <param name="bucketName"></param>
        /// <param name="key"></param>
        /// <param name="version"></param>
        /// <param name="s3Client"></param>
        /// <param name="copyRequest"></param>
        /// <param name="setACLRequest"></param>
        static void SetupForObjectModification(string bucketName, string key, string version, AmazonS3 s3Client,
            out CopyObjectRequest copyRequest, out SetACLRequest setACLRequest)
        {
            // Get the existing ACL of the object
            GetACLRequest getACLRequest = new GetACLRequest();
            getACLRequest.BucketName = bucketName;
            getACLRequest.Key = key;
            if (version != null)
                getACLRequest.VersionId = version;
            GetACLResponse getACLResponse = s3Client.GetACL(getACLRequest);

            // Set the object's original ACL back onto it because a COPY
            // operation resets the ACL on the destination object.
            setACLRequest = new SetACLRequest();
            setACLRequest.BucketName = bucketName;
            setACLRequest.Key = key;
            setACLRequest.ACL = getACLResponse.AccessControlList;

            ListObjectsResponse listObjectResponse = s3Client.ListObjects(new ListObjectsRequest()
                .WithBucketName(bucketName)
                .WithPrefix(key)
                .WithMaxKeys(1));

            if (listObjectResponse.S3Objects.Count != 1)
            {
                throw new ArgumentNullException("No object exists with this bucket name and key.");
            }

            GetObjectMetadataRequest getMetaRequest = new GetObjectMetadataRequest()
            {
                BucketName = bucketName,
                Key = key
            };
            GetObjectMetadataResponse getMetaResponse = s3Client.GetObjectMetadata(getMetaRequest);

            // Set the storage class on the object
            copyRequest = new CopyObjectRequest();
            copyRequest.SourceBucket = copyRequest.DestinationBucket = bucketName;
            copyRequest.SourceKey = copyRequest.DestinationKey = key;
            copyRequest.StorageClass = listObjectResponse.S3Objects[0].StorageClass == "STANDARD" ? S3StorageClass.Standard : S3StorageClass.ReducedRedundancy;
            if (version != null)
                copyRequest.SourceVersionId = version;

            copyRequest.WebsiteRedirectLocation = getMetaResponse.WebsiteRedirectLocation;
            copyRequest.ServerSideEncryptionMethod = getMetaResponse.ServerSideEncryptionMethod;
        }
        public object Execute(ExecutorContext context)
        {
            var cmdletContext = context as CmdletContext;
            // create request
            var request = new Amazon.S3.Model.GetObjectMetadataRequest();

            if (cmdletContext.BucketName != null)
            {
                request.BucketName = cmdletContext.BucketName;
            }
            if (cmdletContext.EtagToMatch != null)
            {
                request.EtagToMatch = cmdletContext.EtagToMatch;
            }
            #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute
            if (cmdletContext.ModifiedSinceDate != null)
            {
                if (cmdletContext.UtcModifiedSinceDate != null)
                {
                    throw new System.ArgumentException("Parameters ModifiedSinceDate and UtcModifiedSinceDate are mutually exclusive.", nameof(this.ModifiedSinceDate));
                }
                request.ModifiedSinceDate = cmdletContext.ModifiedSinceDate.Value;
            }
            #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute
            if (cmdletContext.UtcModifiedSinceDate != null)
            {
                request.ModifiedSinceDateUtc = cmdletContext.UtcModifiedSinceDate.Value;
            }
            if (cmdletContext.EtagToNotMatch != null)
            {
                request.EtagToNotMatch = cmdletContext.EtagToNotMatch;
            }
            #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute
            if (cmdletContext.UnmodifiedSinceDate != null)
            {
                if (cmdletContext.UtcUnmodifiedSinceDate != null)
                {
                    throw new System.ArgumentException("Parameters UnmodifiedSinceDate and UtcUnmodifiedSinceDate are mutually exclusive.", nameof(this.UnmodifiedSinceDate));
                }
                request.UnmodifiedSinceDate = cmdletContext.UnmodifiedSinceDate.Value;
            }
            #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute
            if (cmdletContext.UtcUnmodifiedSinceDate != null)
            {
                request.UnmodifiedSinceDateUtc = cmdletContext.UtcUnmodifiedSinceDate.Value;
            }
            if (cmdletContext.Key != null)
            {
                request.Key = cmdletContext.Key;
            }
            if (cmdletContext.VersionId != null)
            {
                request.VersionId = cmdletContext.VersionId;
            }
            if (cmdletContext.ServerSideEncryptionCustomerMethod != null)
            {
                request.ServerSideEncryptionCustomerMethod = cmdletContext.ServerSideEncryptionCustomerMethod;
            }
            if (cmdletContext.ServerSideEncryptionCustomerProvidedKey != null)
            {
                request.ServerSideEncryptionCustomerProvidedKey = cmdletContext.ServerSideEncryptionCustomerProvidedKey;
            }
            if (cmdletContext.ServerSideEncryptionCustomerProvidedKeyMD5 != null)
            {
                request.ServerSideEncryptionCustomerProvidedKeyMD5 = cmdletContext.ServerSideEncryptionCustomerProvidedKeyMD5;
            }
            if (cmdletContext.PartNumber != null)
            {
                request.PartNumber = cmdletContext.PartNumber.Value;
            }
            if (cmdletContext.RequestPayer != null)
            {
                request.RequestPayer = cmdletContext.RequestPayer;
            }
            if (cmdletContext.ExpectedBucketOwner != null)
            {
                request.ExpectedBucketOwner = cmdletContext.ExpectedBucketOwner;
            }

            CmdletOutput output;

            // issue call
            var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);
            try
            {
                var    response       = CallAWSServiceOperation(client, request);
                object pipelineOutput = null;
                pipelineOutput = cmdletContext.Select(response, this);
                output         = new CmdletOutput
                {
                    PipelineOutput  = pipelineOutput,
                    ServiceResponse = response
                };
            }
            catch (Exception e)
            {
                output = new CmdletOutput {
                    ErrorResponse = e
                };
            }

            return(output);
        }
예제 #33
-1
        public AmazonFilesStatus(S3Object s3File,string bucket,string prefix)
        {
            var filename = s3File.Key.Replace(prefix,"");
            var fileExt = filename.Remove(0,filename.LastIndexOf('.'));
            type =  getContentTypeByExtension(fileExt);
            isimage =  Regex.Match(filename.ToLower(),AmazonHelper.ImgExtensions()).Success;
            var client = AmazonHelper.GetS3Client();
            var metareq = new GetObjectMetadataRequest().WithBucketName(bucket).WithKey(s3File.Key);
            var meta = client.GetObjectMetadata(metareq);
            var height = 0;
            var width = 0;
            if(isimage){
                height = String.IsNullOrWhiteSpace(meta.Headers["x-amz-meta-height"])? 0 : Int32.Parse(meta.Headers["x-amz-meta-height"]);
                 width = String.IsNullOrWhiteSpace(meta.Headers["x-amz-meta-width"])? 0 : Int32.Parse(meta.Headers["x-amz-meta-width"]);

            }

            var size = Convert.ToInt32(s3File.Size);

            SetValues(filename,bucket,prefix,size,height,width);
        }