/// <summary>
        /// Constructs a web request to create a new share.
        /// </summary>
        /// <param name="uri">The absolute URI to the share.</param>
        /// <param name="properties">Properties to set on the share.</param>
        /// <param name="timeout">The server timeout interval.</param>
        /// <returns>A web request to use to perform the operation.</returns>
        public static StorageRequestMessage Create(Uri uri, FileShareProperties properties, int?timeout, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials)
        {
            UriQueryBuilder shareBuilder = GetShareUriQueryBuilder();

            StorageRequestMessage request = HttpRequestMessageFactory.Create(uri, timeout, shareBuilder, content, operationContext, canonicalizer, credentials);

            if (properties != null && properties.Quota.HasValue)
            {
                request.AddOptionalHeader(Constants.HeaderConstants.ShareQuota, properties.Quota.Value);
            }

            return(request);
        }
        /// <summary>
        /// Constructs a web request to get the blob's content, properties, and metadata.
        /// </summary>
        /// <param name="uri">The absolute URI to the blob.</param>
        /// <param name="timeout">The server timeout interval.</param>
        /// <param name="snapshot">The snapshot version, if the blob is a snapshot.</param>
        /// <param name="accessCondition">The access condition to apply to the request.</param>
        /// <returns>A web request for performing the operation.</returns>
        public static StorageRequestMessage Get(Uri uri, int?timeout, DateTimeOffset?snapshot, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials)
        {
            UriQueryBuilder builder = new UriQueryBuilder();

            if (snapshot.HasValue)
            {
                builder.Add("snapshot", Request.ConvertDateTimeToSnapshotString(snapshot.Value));
            }

            StorageRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Get, uri, timeout, builder, content, operationContext, canonicalizer, credentials);

            request.ApplyAccessCondition(accessCondition);
            return(request);
        }
Example #3
0
 /// <summary>
 /// Adds the File Last Write Time to the <see cref="StorageRequestMessage"/>
 /// </summary>
 /// <param name="request">The <see cref="StorageRequestMessage"/></param>
 /// <param name="properties">The <see cref="FileProperties"/></param>
 /// <param name="defaultValue">The default value to set if properties.lastWriteTimeToSet is null</param>
 private static void AddLastWriteTime(
     StorageRequestMessage request,
     FileProperties properties,
     string defaultValue)
 {
     if (properties?.lastWriteTimeToSet != null)
     {
         request.AddOptionalHeader(Constants.HeaderConstants.FileLastWriteTime, Request.ConvertDateTimeToSnapshotString(properties.lastWriteTimeToSet.Value));
     }
     else
     {
         request.AddOptionalHeader(Constants.HeaderConstants.FileLastWriteTime, defaultValue);
     }
 }
        internal static void ApplyCustomerProvidedKeyOrEncryptionScope(StorageRequestMessage request, BlobRequestOptions options, bool isSource)
        {
            var customerProvidedKey = options?.CustomerProvidedKey;
            var encryptionScope     = options?.EncryptionScope;

            if (null != customerProvidedKey)
            {
                ApplyCustomerProvidedKey(request, customerProvidedKey, isSource);
            }
            else if (null != encryptionScope)
            {
                request.Headers.Add(Constants.HeaderConstants.EncryptionScopeHeader, encryptionScope);
            }
        }
Example #5
0
 /// <summary>
 /// Adds the <see cref="CloudFileNtfsAttributes"/> to the <see cref="StorageRequestMessage"/>
 /// </summary>
 /// <param name="request">The <see cref="StorageRequestMessage"/></param>
 /// <param name="properties">The <see cref="FileProperties"/></param>
 /// <param name="defaultValue">The default value to set if properties.ntfsAttributesToSet is null</param>
 private static void AddNtfsFileAttributes(
     StorageRequestMessage request,
     FileProperties properties,
     string defaultValue)
 {
     if (properties?.ntfsAttributesToSet != null)
     {
         request.AddOptionalHeader(Constants.HeaderConstants.FileAttributes, CloudFileNtfsAttributesHelper.ToString(properties.ntfsAttributesToSet.Value));
     }
     else
     {
         request.AddOptionalHeader(Constants.HeaderConstants.FileAttributes, defaultValue);
     }
 }
        /// <summary>
        /// Constructs a web request to return a listing of all shares in this storage account.
        /// </summary>
        /// <param name="uri">The absolute URI for the account.</param>
        /// <param name="timeout">The server timeout interval.</param>
        /// <param name="listingContext">A set of parameters for the listing operation.</param>
        /// <param name="detailsIncluded">Additional details to return with the listing.</param>
        /// <returns>A web request for the specified operation.</returns>
        public static StorageRequestMessage List(Uri uri, int?timeout, ListingContext listingContext, ShareListingDetails detailsIncluded, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials)
        {
            UriQueryBuilder builder = new UriQueryBuilder();

            builder.Add(Constants.QueryConstants.Component, "list");

            if (listingContext != null)
            {
                if (listingContext.Prefix != null)
                {
                    builder.Add("prefix", listingContext.Prefix);
                }

                if (listingContext.Marker != null)
                {
                    builder.Add("marker", listingContext.Marker);
                }

                if (listingContext.MaxResults.HasValue)
                {
                    builder.Add("maxresults", listingContext.MaxResults.ToString());
                }
            }

            if (detailsIncluded != ShareListingDetails.None)
            {
                StringBuilder sb      = new StringBuilder();
                bool          started = false;

                if ((detailsIncluded & ShareListingDetails.Metadata) == ShareListingDetails.Metadata)
                {
                    if (!started)
                    {
                        started = true;
                    }
                    else
                    {
                        sb.Append(",");
                    }

                    sb.Append("metadata");
                }

                builder.Add("include", sb.ToString());
            }

            StorageRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Get, uri, timeout, builder, content, operationContext, canonicalizer, credentials);

            return(request);
        }
        /// <summary>
        /// Constructs a web request to write or clear a range of pages in a file.
        /// </summary>
        /// <param name="uri">The absolute URI to the file.</param>
        /// <param name="timeout">The server timeout interval.</param>
        /// <param name="fileRange">The beginning and ending offsets.</param>
        /// <param name="fileRangeWrite">Action describing whether we are writing to a file or clearing a set of ranges.</param>
        /// <param name="accessCondition">The access condition to apply to the request.</param>
        /// <param name="content">The corresponding Http content.</param>
        /// <param name="operationContext">An object that represents the context for the current operation.</param>
        /// <returns>A web request to use to perform the operation.</returns>
        public static StorageRequestMessage PutRange(Uri uri, int?timeout, FileRange fileRange, FileRangeWrite fileRangeWrite, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials)
        {
            UriQueryBuilder builder = new UriQueryBuilder();

            builder.Add(Constants.QueryConstants.Component, "range");

            StorageRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Put, uri, timeout, builder, content, operationContext, canonicalizer, credentials);

            request.AddOptionalHeader(Constants.HeaderConstants.RangeHeader, fileRange.ToString());
            request.Headers.Add(Constants.HeaderConstants.FileRangeWrite, fileRangeWrite.ToString());

            request.ApplyAccessCondition(accessCondition);
            return(request);
        }
        /// <summary>
        /// Creates a web request to get the properties of the account.
        /// </summary>
        /// <param name="uri">The absolute URI to the service.</param>
        /// <param name="builder">A <see cref="UriQueryBuilder"/> object specifying additional parameters to add to the URI query string.</param>
        /// <param name="timeout">The server timeout interval.</param>
        /// <param name="useVersionHeader">A boolean value indicating whether to set the <i>x-ms-version</i> HTTP header.</param>
        /// <param name="operationContext">An <see cref="OperationContext"/> object that represents the context for the current operation.</param>
        /// <returns>
        /// A web request to get the service properties.
        /// </returns>
        internal static StorageRequestMessage GetAccountProperties(Uri uri, UriQueryBuilder builder, int?timeout, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials)
        {
            if (builder == null)
            {
                builder = new UriQueryBuilder();
            }

            builder.Add(Constants.QueryConstants.Component, "properties");
            builder.Add(Constants.QueryConstants.ResourceType, "account");

            StorageRequestMessage request = CreateRequestMessage(HttpMethod.Head, uri, timeout, builder, content, operationContext, canonicalizer, credentials);

            return(request);
        }
        /// <summary>
        /// Generates a web request to abort a copy operation.
        /// </summary>
        /// <param name="uri">The absolute URI to the file.</param>
        /// <param name="timeout">The server timeout interval.</param>
        /// <param name="copyId">The ID string of the copy operation to be aborted.</param>
        /// <param name="accessCondition">The access condition to apply to the request.
        ///     Only lease conditions are supported for this operation.</param>
        /// <returns>A web request for performing the operation.</returns>
        public static StorageRequestMessage AbortCopy(Uri uri, int?timeout, string copyId, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials)
        {
            UriQueryBuilder builder = new UriQueryBuilder();

            builder.Add(Constants.QueryConstants.Component, "copy");
            builder.Add(Constants.QueryConstants.CopyId, copyId);

            StorageRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Put, uri, timeout, builder, content, operationContext, canonicalizer, credentials);

            request.Headers.Add(Constants.HeaderConstants.CopyActionHeader, Constants.HeaderConstants.CopyActionAbort);
            request.ApplyAccessCondition(accessCondition);

            return(request);
        }
        /// <summary>
        /// Constructs a web request to get messages for a queue.
        /// </summary>
        /// <param name="uri">A <see cref="System.Uri"/> specifying the absolute URI to the queue.</param>
        /// <param name="timeout">An integer specifying the server timeout interval.</param>
        /// <param name="numberOfMessages">An integer specifying the number of messages to get. The maximum number of messages that may be retrieved at one time is 32.</param>
        /// <param name="visibilityTimeout">A <see cref="TimeSpan"/> value specifying the visibility timeout.</param>
        /// <param name="content">The contents of the HTTP request message.</param>
        /// <param name="operationContext">An <see cref="OperationContext"/> object that represents the context for the current operation.</param>
        /// <returns>A web request to use to perform the operation.</returns>
        public static StorageRequestMessage GetMessages(Uri uri, int?timeout, int numberOfMessages, TimeSpan?visibilityTimeout, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials)
        {
            UriQueryBuilder builder = new UriQueryBuilder();

            builder.Add(Constants.QueryConstants.NumOfMessages, numberOfMessages.ToString());

            if (visibilityTimeout != null)
            {
                builder.Add(Constants.QueryConstants.VisibilityTimeout, visibilityTimeout.Value.RoundUpToSeconds().ToString());
            }

            StorageRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Get, uri, timeout, builder, content, operationContext, canonicalizer, credentials);

            return(request);
        }
 private static void SetAcceptHeaderForHttpWebRequest(StorageRequestMessage msg, TablePayloadFormat payloadFormat)
 {
     if (payloadFormat == TablePayloadFormat.JsonFullMetadata)
     {
         msg.Headers.Add(Constants.HeaderConstants.PayloadAcceptHeader, Constants.JsonFullMetadataAcceptHeaderValue);
     }
     else if (payloadFormat == TablePayloadFormat.Json)
     {
         msg.Headers.Add(Constants.HeaderConstants.PayloadAcceptHeader, Constants.JsonLightAcceptHeaderValue);
     }
     else if (payloadFormat == TablePayloadFormat.JsonNoMetadata)
     {
         msg.Headers.Add(Constants.HeaderConstants.PayloadAcceptHeader, Constants.JsonNoMetadataAcceptHeaderValue);
     }
 }
Example #12
0
        /// <summary>
        /// Generates a web request to use to acquire, renew, change, release or break the lease for the container.
        /// </summary>
        /// <param name="uri">The absolute URI to the container.</param>
        /// <param name="timeout">The server timeout interval, in seconds.</param>
        /// <param name="action">The lease action to perform.</param>
        /// <param name="proposedLeaseId">A lease ID to propose for the result of an acquire or change operation,
        /// or null if no ID is proposed for an acquire operation. This should be null for renew, release, and break operations.</param>
        /// <param name="leaseDuration">The lease duration, in seconds, for acquire operations.
        /// If this is -1 then an infinite duration is specified. This should be null for renew, change, release, and break operations.</param>
        /// <param name="leaseBreakPeriod">The amount of time to wait, in seconds, after a break operation before the lease is broken.
        /// If this is null then the default time is used. This should be null for acquire, renew, change, and release operations.</param>
        /// <param name="accessCondition">The access condition to apply to the request.</param>
        /// <returns>A web request to use to perform the operation.</returns>
        public static StorageRequestMessage Lease(Uri uri, int? timeout, LeaseAction action, string proposedLeaseId, int? leaseDuration, int? leaseBreakPeriod, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials)
        {
            UriQueryBuilder builder = GetContainerUriQueryBuilder();
            builder.Add(Constants.QueryConstants.Component, "lease");

            StorageRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Put, uri, timeout, builder, content, operationContext, canonicalizer, credentials);

            // Add Headers
            BlobHttpRequestMessageFactory.AddLeaseAction(request, action);
            BlobHttpRequestMessageFactory.AddLeaseDuration(request, leaseDuration);
            BlobHttpRequestMessageFactory.AddProposedLeaseId(request, proposedLeaseId);
            BlobHttpRequestMessageFactory.AddLeaseBreakPeriod(request, leaseBreakPeriod);

            request.ApplyAccessCondition(accessCondition);
            return request;
        }
Example #13
0
        /// <summary>
        /// Constructs a web request to return a specified range of the file's content, together with its properties and metadata.
        /// </summary>
        /// <param name="uri">The absolute URI to the file.</param>
        /// <param name="timeout">The server timeout interval, in seconds.</param>
        /// <param name="offset">The byte offset at which to begin returning content.</param>
        /// <param name="count">The number of bytes to return, or null to return all bytes through the end of the file.</param>
        /// <param name="shareSnapshot">A <see cref="DateTimeOffset"/> specifying the share snapshot timestamp, if the share is a snapshot.</param>
        /// <param name="accessCondition">The access condition to apply to the request.</param>
        /// <returns>A web request to use to perform the operation.</returns>
        public static StorageRequestMessage Get(Uri uri, int?timeout, long?offset, long?count, ChecksumRequested rangeContentChecksumRequested, DateTimeOffset?shareSnapshot, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials)
        {
            if (offset.HasValue && offset.Value < 0)
            {
                CommonUtility.ArgumentOutOfRange("offset", offset);
            }

            rangeContentChecksumRequested.AssertInBounds(offset, count, Constants.MaxRangeGetContentMD5Size, Constants.MaxRangeGetContentCRC64Size);

            StorageRequestMessage request = Get(uri, timeout, shareSnapshot, accessCondition, content, operationContext, canonicalizer, credentials);

            AddRange(request, offset, count);

            request.ApplyRangeContentChecksumRequested(offset, rangeContentChecksumRequested);

            return(request);
        }
        /// <summary>
        /// Constructs a web request to create a new file.
        /// </summary>
        /// <param name="uri">The absolute URI to the file.</param>
        /// <param name="timeout">The server timeout interval.</param>
        /// <param name="properties">The properties to set for the file.</param>
        /// <param name="fileSize">For a file, the size of the file. This parameter is ignored
        /// for block files.</param>
        /// <param name="accessCondition">The access condition to apply to the request.</param>
        /// <returns>A web request to use to perform the operation.</returns>
        public static StorageRequestMessage Create(Uri uri, int?timeout, FileProperties properties, long fileSize, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials)
        {
            CommonUtility.AssertNotNull("properties", properties);

            StorageRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Put, uri, timeout, null /* builder */, content, operationContext, canonicalizer, credentials);

            if (properties.CacheControl != null)
            {
                request.Headers.CacheControl = CacheControlHeaderValue.Parse(properties.CacheControl);
            }

            if (content != null)
            {
                if (properties.ContentType != null)
                {
                    content.Headers.ContentType = MediaTypeHeaderValue.Parse(properties.ContentType);
                }

                if (properties.ContentMD5 != null)
                {
                    content.Headers.ContentMD5 = Convert.FromBase64String(properties.ContentMD5);
                }

                if (properties.ContentLanguage != null)
                {
                    content.Headers.ContentLanguage.Add(properties.ContentLanguage);
                }

                if (properties.ContentEncoding != null)
                {
                    content.Headers.ContentEncoding.Add(properties.ContentEncoding);
                }

                if (properties.ContentDisposition != null)
                {
                    content.Headers.ContentDisposition = ContentDispositionHeaderValue.Parse(properties.ContentDisposition);
                }
            }

            request.Headers.Add(Constants.HeaderConstants.FileType, Constants.HeaderConstants.File);
            request.Headers.Add(Constants.HeaderConstants.FileContentLengthHeader, fileSize.ToString(NumberFormatInfo.InvariantInfo));
            properties.Length = fileSize;

            request.ApplyAccessCondition(accessCondition);
            return(request);
        }
        /// <summary>
        /// Constructs a web request to return the ACL for a cloud resource.
        /// </summary>
        /// <param name="uri">The absolute URI to the resource.</param>
        /// <param name="timeout">The server timeout interval.</param>
        /// <param name="builder">An optional query builder to use.</param>
        /// <returns><returns>A web request to use to perform the operation.</returns></returns>
        internal static StorageRequestMessage GetAcl(Uri uri, int?timeout, UriQueryBuilder builder, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials)
        {
            if (builder == null)
            {
                builder = new UriQueryBuilder();
            }

            builder.Add(Constants.QueryConstants.Component, "acl");

            StorageRequestMessage request = CreateRequestMessage(HttpMethod.Get, uri, timeout, builder, content, operationContext, canonicalizer, credentials);

#if WINDOWS_PHONE
            // Windows phone adds */* as the Accept type when we don't set one explicitly.
            request.Headers.Add(Constants.HeaderConstants.PayloadAcceptHeader, Constants.XMLAcceptHeaderValue);
#endif
            return(request);
        }
Example #16
0
        /// <summary>
        /// Constructs a web request to return the list of valid ranges for a file.
        /// </summary>
        /// <param name="uri">The absolute URI to the file.</param>
        /// <param name="timeout">The server timeout interval.</param>
        /// <param name="offset">The starting offset of the data range over which to list file ranges, in bytes.</param>
        /// <param name="count">The length of the data range over which to list file ranges, in bytes.</param>
        /// <param name="accessCondition">The access condition to apply to the request.</param>
        /// <returns>A web request to use to perform the operation.</returns>
        public static StorageRequestMessage ListRanges(Uri uri, int?timeout, long?offset, long?count, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials)
        {
            if (offset.HasValue)
            {
                CommonUtility.AssertNotNull("count", count);
            }

            UriQueryBuilder builder = new UriQueryBuilder();

            builder.Add(Constants.QueryConstants.Component, "rangelist");

            StorageRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Get, uri, timeout, builder, content, operationContext, canonicalizer, credentials);

            AddRange(request, offset, count);
            request.ApplyAccessCondition(accessCondition);
            return(request);
        }
        /// <summary>
        /// Constructs a web request to add a message for a queue.
        /// </summary>
        /// <param name="uri">The absolute URI to the queue.</param>
        /// <param name="timeout">The server timeout interval.</param>
        /// <param name="timeToLiveInSeconds">The message time-to-live, in seconds.</param>
        /// <param name="visibilityTimeoutInSeconds">The length of time during which the message will be invisible, in seconds.</param>
        /// <param name="content">The contents of the HTTP request message.</param>
        /// <param name="operationContext">An <see cref="OperationContext"/> object that represents the context for the current operation.</param>
        /// <returns>A web request to use to perform the operation.</returns>
        public static StorageRequestMessage AddMessage(Uri uri, int?timeout, long?timeToLiveInSeconds, int?visibilityTimeoutInSeconds, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials)
        {
            UriQueryBuilder builder = new UriQueryBuilder();

            if (timeToLiveInSeconds != null)
            {
                builder.Add(Constants.QueryConstants.MessageTimeToLive, timeToLiveInSeconds.Value.ToString());
            }

            if (visibilityTimeoutInSeconds != null)
            {
                builder.Add(Constants.QueryConstants.VisibilityTimeout, visibilityTimeoutInSeconds.Value.ToString());
            }

            StorageRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Post, uri, timeout, builder, content, operationContext, canonicalizer, credentials);

            return(request);
        }
        /// <summary>
        /// Constructs a web request to set system properties for a share.
        /// </summary>
        /// <param name="uri">The absolute URI to the share.</param>
        /// <param name="timeout">The server timeout interval.</param>
        /// <param name="properties">The share's properties.</param>
        /// <param name="accessCondition">The access condition to apply to the request.</param>
        /// <returns>A web request to use to perform the operation.</returns>
        public static StorageRequestMessage SetProperties(Uri uri, int?timeout, FileShareProperties properties, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials)
        {
            CommonUtility.AssertNotNull("properties", properties);

            UriQueryBuilder shareBuilder = GetShareUriQueryBuilder();

            shareBuilder.Add(Constants.QueryConstants.Component, "properties");

            StorageRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Put, uri, timeout, shareBuilder, content, operationContext, canonicalizer, credentials);

            if (properties.Quota.HasValue)
            {
                request.AddOptionalHeader(Constants.HeaderConstants.ShareQuota, properties.Quota.Value);
            }

            request.ApplyAccessCondition(accessCondition);
            return(request);
        }
        /// <summary>
        /// Constructs a web request to update a message for a queue.
        /// </summary>
        /// <param name="uri">The absolute URI to the queue.</param>
        /// <param name="timeout">The server timeout interval.</param>
        /// <returns>A web request to use to perform the operation.</returns>
        public static StorageRequestMessage UpdateMessage(Uri uri, int?timeout, string popReceipt, TimeSpan?visibilityTimeout, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials)
        {
            UriQueryBuilder builder = new UriQueryBuilder();

            builder.Add(Constants.QueryConstants.PopReceipt, popReceipt);
            if (visibilityTimeout != null)
            {
                builder.Add(Constants.QueryConstants.VisibilityTimeout, visibilityTimeout.Value.TotalSeconds.ToString());
            }
            else
            {
                builder.Add(Constants.QueryConstants.VisibilityTimeout, "0");
            }

            StorageRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Put, uri, timeout, builder, content, operationContext, canonicalizer, credentials);

            return(request);
        }
        /// <summary>
        /// Gets the close handles implementation.
        /// </summary>
        /// <param name="token">Continuation token for closing many files.</param>
        /// <param name="handleId">Id of the handle, "*" if all handles on the file.</param>
        /// <param name="recursive">Whether to recurse through this directory's files and subfolders.</param>
        /// <param name="accessCondition">An <see cref="AccessCondition"/> object that represents the access conditions for the file. If <c>null</c>, no condition is used.</param>
        /// <param name="options">An <see cref="FileRequestOptions"/> object that specifies additional options for the request.</param>
        /// <returns>A <see cref="RESTCommand{T}"/> for closing the handles.</returns>
        private RESTCommand <CloseFileHandleResultSegment> CloseHandleImpl(FileContinuationToken token, string handleId, bool?recursive, AccessCondition accessCondition, FileRequestOptions options)
        {
            RESTCommand <CloseFileHandleResultSegment> putCmd = new RESTCommand <CloseFileHandleResultSegment>(this.ServiceClient.Credentials, this.StorageUri, this.ServiceClient.HttpClient);

            options.ApplyToStorageCommand(putCmd);

            putCmd.CommandLocationMode    = CommandLocationMode.PrimaryOrSecondary;
            putCmd.RetrieveResponseStream = true;
            putCmd.BuildRequest           = (cmd, uri, builder, cnt, serverTimeout, ctx) =>
            {
                StorageRequestMessage msg = FileHttpRequestMessageFactory.CloseHandle(uri, serverTimeout, handleId, recursive, token, accessCondition, cnt, ctx, this.ServiceClient.GetCanonicalizer(), this.ServiceClient.Credentials);
                FileHttpRequestMessageFactory.AddMetadata(msg, this.Metadata);
                return(msg);
            };
            putCmd.PreProcessResponse = (cmd, resp, ex, ctx) =>
            {
                CloseFileHandleResultSegment res = HttpResponseParsers.ProcessExpectedStatusCodeNoException(HttpStatusCode.OK, resp, null /* retVal */, cmd, ex);
                int handlesClosed;

                if (!int.TryParse(resp.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.NumHandlesClosed), out handlesClosed))
                {
                    handlesClosed = -1;
                }

                FileContinuationToken continuation = null;
                string marker;

                if ((marker = resp.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.Marker)) != "")
                {
                    continuation = new FileContinuationToken()
                    {
                        NextMarker = marker
                    };
                }

                return(new CloseFileHandleResultSegment()
                {
                    NumHandlesClosed = handlesClosed,
                    ContinuationToken = continuation
                });
            };

            return(putCmd);
        }
        /// <summary>
        /// Applies the condition for a source blob to the web request.
        /// </summary>
        /// <param name="request">The request to be modified.</param>
        /// <param name="accessCondition">Access condition to be added to the request.</param>
        internal static void ApplyAccessConditionToSource(this StorageRequestMessage request, AccessCondition accessCondition)
        {
            if (accessCondition != null)
            {
                if (!string.IsNullOrEmpty(accessCondition.IfMatchETag))
                {
                    request.Headers.Add(Constants.HeaderConstants.SourceIfMatchHeader, accessCondition.IfMatchETag);
                }

                if (!string.IsNullOrEmpty(accessCondition.IfNoneMatchETag))
                {
                    request.Headers.Add(Constants.HeaderConstants.SourceIfNoneMatchHeader, accessCondition.IfNoneMatchETag);
                }

                if (!string.IsNullOrEmpty(accessCondition.IfMatchContentCrc))
                {
                    request.Headers.Add(Constants.HeaderConstants.SourceIfMatchCrcHeader, accessCondition.IfMatchContentCrc);
                }

                if (!string.IsNullOrEmpty(accessCondition.IfNoneMatchContentCrc))
                {
                    request.Headers.Add(Constants.HeaderConstants.SourceIfNoneMatchCrcHeader, accessCondition.IfNoneMatchContentCrc);
                }

                if (accessCondition.IfModifiedSinceTime.HasValue)
                {
                    request.Headers.Add(
                        Constants.HeaderConstants.SourceIfModifiedSinceHeader,
                        HttpWebUtility.ConvertDateTimeToHttpString(accessCondition.IfModifiedSinceTime.Value));
                }

                if (accessCondition.IfNotModifiedSinceTime.HasValue)
                {
                    request.Headers.Add(
                        Constants.HeaderConstants.SourceIfUnmodifiedSinceHeader,
                        HttpWebUtility.ConvertDateTimeToHttpString(accessCondition.IfNotModifiedSinceTime.Value));
                }

                if (!string.IsNullOrEmpty(accessCondition.LeaseId))
                {
                    throw new InvalidOperationException(SR.LeaseConditionOnSource);
                }
            }
        }
Example #22
0
 /// <summary>
 /// Adds the File Permission or File Permission Key to a StorageRequest.
 /// </summary>
 /// <param name="request">The <see cref="StorageRequestMessage"/></param>
 /// <param name="filePermissionToSet">The File Permission</param>
 /// <param name="properties">The <see cref="FileProperties"/></param>
 /// <param name="defaultValue">The default value to set if fileermissionToSet and properties.filePermissionKeyToSet are null</param>
 private static void AddFilePermissionOrFilePermissionKey(
     StorageRequestMessage request,
     string filePermissionToSet,
     FileProperties properties,
     string defaultValue)
 {
     if (filePermissionToSet == null && properties?.filePermissionKeyToSet == null)
     {
         request.AddOptionalHeader(Constants.HeaderConstants.FilePermission, defaultValue);
     }
     else if (filePermissionToSet != null)
     {
         request.AddOptionalHeader(Constants.HeaderConstants.FilePermission, filePermissionToSet);
     }
     else
     {
         request.AddOptionalHeader(Constants.HeaderConstants.FilePermissionKey, properties.filePermissionKeyToSet);
     }
 }
        /// <summary>
        /// Constructs a web request to return the list of page ranges that differ between a specified snapshot and this object.
        /// </summary>
        /// <param name="uri">The absolute URI to the blob.</param>
        /// <param name="timeout">The server timeout interval.</param>
        /// <param name="snapshot">The snapshot timestamp, if the blob is a snapshot.</param>
        /// <param name="previousSnapshotTime">A <see cref="DateTimeOffset"/> representing the snapshot timestamp to use as the starting point for the diff. If this CloudPageBlob represents a snapshot, the previousSnapshotTime parameter must be prior to the current snapshot timestamp.</param>
        /// <param name="offset">The starting offset of the data range over which to list page ranges, in bytes. Must be a multiple of 512.</param>
        /// <param name="count">The length of the data range over which to list page ranges, in bytes. Must be a multiple of 512.</param>
        /// <param name="accessCondition">The access condition to apply to the request.</param>
        /// <param name="operationContext">An <see cref="OperationContext"/> object that represents the context for the current operation.</param>
        /// <returns>A web request to use to perform the operation.</returns>
        public static StorageRequestMessage GetPageRangesDiff(Uri uri, int?timeout, DateTimeOffset?snapshot, DateTimeOffset previousSnapshotTime, long?offset, long?count, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials)
        {
            if (offset.HasValue)
            {
                CommonUtility.AssertNotNull("count", count);
            }

            UriQueryBuilder builder = new UriQueryBuilder();

            builder.Add(Constants.QueryConstants.Component, "pagelist");
            BlobHttpRequestMessageFactory.AddSnapshot(builder, snapshot);
            builder.Add("prevsnapshot", Request.ConvertDateTimeToSnapshotString(previousSnapshotTime));

            StorageRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Get, uri, timeout, builder, content, operationContext, canonicalizer, credentials);

            AddRange(request, offset, count);
            request.ApplyAccessCondition(accessCondition);
            return(request);
        }
        private Task <HttpResponseMessage> GetSharedKeyAuthenticationTask(StorageRequestMessage request, CancellationToken cancellationToken)
        {
            ICanonicalizer     canonicalizer = request.Canonicalizer;
            StorageCredentials credentials   = request.Credentials;
            string             accountName   = request.AccountName;

            if (!request.Headers.Contains("x-ms-date"))
            {
                string value = HttpWebUtility.ConvertDateTimeToHttpString(DateTimeOffset.UtcNow);
                request.Headers.Add("x-ms-date", value);
            }
            if (credentials.IsSharedKey)
            {
                string key     = credentials.Key;
                string message = canonicalizer.CanonicalizeHttpRequest(request, accountName);
                string arg     = CryptoUtility.ComputeHmac256(key, message);
                request.Headers.Authorization = new AuthenticationHeaderValue(canonicalizer.AuthorizationScheme, string.Format(CultureInfo.InvariantCulture, "{0}:{1}", credentials.AccountName, arg));
            }
            return(base.SendAsync((HttpRequestMessage)request, cancellationToken));
        }
Example #25
0
        /// <summary>
        /// Constructs a web request to create a new directory.
        /// </summary>
        /// <param name="uri">The absolute URI to the directory.</param>
        /// <param name="timeout">The server timeout interval.</param>
        /// <param name="properties">The properties to set for the directory.</param>
        /// <param name="filePermissionToSet">The file permissions to set for the directory.</param>
        /// <param name="content">HttpContent for the request</param>
        /// <param name="operationContext">An <see cref="OperationContext"/> object that represents the context for the current operation.</param>
        /// <param name="canonicalizer">A canonicalizer that converts HTTP request data into a standard form appropriate for signing.</param>
        /// <param name="credentials">A <see cref="StorageCredentials"/> object providing credentials for the request.</param>
        /// <returns>A web request to use to perform the operation.</returns>
        public static StorageRequestMessage Create(
            Uri uri,
            int?timeout,
            FileDirectoryProperties properties,
            string filePermissionToSet,
            HttpContent content,
            OperationContext operationContext,
            ICanonicalizer canonicalizer,
            StorageCredentials credentials)
        {
            UriQueryBuilder       directoryBuilder = GetDirectoryUriQueryBuilder();
            StorageRequestMessage request          = HttpRequestMessageFactory.Create(uri, timeout, directoryBuilder, content, operationContext, canonicalizer, credentials);

            AddFilePermissionOrFilePermissionKey(request, filePermissionToSet, properties, Constants.HeaderConstants.FilePermissionInherit);
            AddNtfsFileAttributes(request, properties, Constants.HeaderConstants.FileAttributesNone);
            AddCreationTime(request, properties, Constants.HeaderConstants.FileTimeNow);
            AddLastWriteTime(request, properties, Constants.HeaderConstants.FileTimeNow);

            return(request);
        }
Example #26
0
        /// <summary>
        /// Constructs a web request to create a new container.
        /// </summary>
        /// <param name="uri">The absolute URI to the container.</param>
        /// <param name="timeout">The server timeout interval.</param>
        /// <param name="accessType">An <see cref="BlobContainerPublicAccessType"/> object that specifies whether data in the container may be accessed publicly and what level of access is to be allowed.</param>
        /// <returns>A web request to use to perform the operation.</returns>
        public static StorageRequestMessage Create(Uri uri, int?timeout, HttpContent content, OperationContext operationContext, BlobContainerPublicAccessType accessType, BlobContainerEncryptionScopeOptions encryptionScopeOptions, ICanonicalizer canonicalizer, StorageCredentials credentials)
        {
            UriQueryBuilder       containerBuilder = GetContainerUriQueryBuilder();
            StorageRequestMessage request          = HttpRequestMessageFactory.Create(uri, timeout, containerBuilder, content, operationContext, canonicalizer, credentials);

            if (accessType != BlobContainerPublicAccessType.Off)
            {
                request.Headers.Add(Constants.HeaderConstants.ContainerPublicAccessType, accessType.ToString().ToLower());
            }

            if (null != encryptionScopeOptions)
            {
                request.Headers.Add(Constants.HeaderConstants.DefaultEncryptionScopeHeader, encryptionScopeOptions.DefaultEncryptionScope);

                request.Headers.Add(Constants.HeaderConstants.PreventEncryptionScopeOverrideHeader,
                                    encryptionScopeOptions.PreventEncryptionScopeOverride ? Constants.HeaderConstants.TrueHeader : Constants.HeaderConstants.FalseHeader);
            }

            return(request);
        }
Example #27
0
        /// <summary>
        /// Implementation for the SetMetadata method.
        /// </summary>
        /// <param name="accessCondition">An object that represents the access conditions for the directory. If null, no condition is used.</param>
        /// <param name="options">An object that specifies additional options for the request.</param>
        /// <returns>A <see cref="RESTCommand"/> that sets the metadata.</returns>
        private RESTCommand <NullType> SetMetadataImpl(AccessCondition accessCondition, FileRequestOptions options)
        {
            RESTCommand <NullType> putCmd = new RESTCommand <NullType>(this.ServiceClient.Credentials, this.StorageUri);

            options.ApplyToStorageCommand(putCmd);
            putCmd.BuildRequest = (cmd, uri, builder, cnt, serverTimeout, ctx) =>
            {
                StorageRequestMessage msg = DirectoryHttpRequestMessageFactory.SetMetadata(uri, serverTimeout, accessCondition, cnt, ctx, this.ServiceClient.GetCanonicalizer(), this.ServiceClient.Credentials);
                DirectoryHttpRequestMessageFactory.AddMetadata(msg, this.Metadata);
                return(msg);
            };
            putCmd.PreProcessResponse = (cmd, resp, ex, ctx) =>
            {
                HttpResponseParsers.ProcessExpectedStatusCodeNoException(HttpStatusCode.OK, resp, NullType.Value, cmd, ex);
                this.UpdateETagAndLastModified(resp);
                return(NullType.Value);
            };

            return(putCmd);
        }
Example #28
0
        internal static void ApplyCustomerProvidedKey(StorageRequestMessage request, BlobCustomerProvidedKey customerProvidedKey, bool isSource)
        {
            if ((null == customerProvidedKey))
            {
                return;
            }

            if (isSource)
            {
                request.Headers.Add(Constants.HeaderConstants.ClientProvidedEncyptionKeySource, customerProvidedKey.Key);
                request.Headers.Add(Constants.HeaderConstants.ClientProvidedEncyptionKeyHashSource, customerProvidedKey.KeySHA256);
                request.Headers.Add(Constants.HeaderConstants.ClientProvidedEncyptionKeyAlgorithmSource, customerProvidedKey.EncryptionAlgorithm);
            }
            else
            {
                request.Headers.Add(Constants.HeaderConstants.ClientProvidedEncyptionKey, customerProvidedKey.Key);
                request.Headers.Add(Constants.HeaderConstants.ClientProvidedEncyptionKeyHash, customerProvidedKey.KeySHA256);
                request.Headers.Add(Constants.HeaderConstants.ClientProvidedEncyptionAlgorithm, customerProvidedKey.EncryptionAlgorithm);
            }
        }
        /// <summary>
        /// Constructs a web request to create a new file.
        /// </summary>
        /// <param name="uri">The absolute URI to the file.</param>
        /// <param name="timeout">The server timeout interval.</param>
        /// <param name="properties">The properties to set for the file.</param>
        /// <param name="fileSize">For a file, the size of the file. This parameter is ignored
        /// for block files.</param>
        /// <param name="accessCondition">The access condition to apply to the request.</param>
        /// <returns>A web request to use to perform the operation.</returns>
        public static StorageRequestMessage Create(Uri uri, int?timeout, FileProperties properties, long fileSize, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials)
        {
            StorageRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Put, uri, timeout, null /* builder */, content, operationContext, canonicalizer, credentials);

            if (properties.CacheControl != null)
            {
                request.AddOptionalHeader(Constants.HeaderConstants.FileCacheControlHeader, properties.CacheControl);
            }

            if (properties.ContentType != null)
            {
                request.AddOptionalHeader(Constants.HeaderConstants.FileContentTypeHeader, properties.ContentType);
            }

            if (properties.ContentMD5 != null)
            {
                request.AddOptionalHeader(Constants.HeaderConstants.FileContentMD5Header, properties.ContentMD5);
            }

            if (properties.ContentLanguage != null)
            {
                request.AddOptionalHeader(Constants.HeaderConstants.FileContentLanguageHeader, properties.ContentLanguage);
            }

            if (properties.ContentEncoding != null)
            {
                request.AddOptionalHeader(Constants.HeaderConstants.FileContentEncodingHeader, properties.ContentEncoding);
            }

            if (properties.ContentDisposition != null)
            {
                request.AddOptionalHeader(Constants.HeaderConstants.FileContentDispositionRequestHeader, properties.ContentDisposition);
            }

            request.Headers.Add(Constants.HeaderConstants.FileType, Constants.HeaderConstants.File);
            request.Headers.Add(Constants.HeaderConstants.FileContentLengthHeader, fileSize.ToString(NumberFormatInfo.InvariantInfo));
            properties.Length = fileSize;

            request.ApplyAccessCondition(accessCondition);
            return(request);
        }
        /// <summary>
        /// Constructs a web request to set system properties for a file.
        /// </summary>
        /// <param name="uri">The absolute URI to the file.</param>
        /// <param name="timeout">The server timeout interval.</param>
        /// <param name="properties">The file's properties.</param>
        /// <param name="accessCondition">The access condition to apply to the request.</param>
        /// <returns>A web request to use to perform the operation.</returns>
        public static StorageRequestMessage SetProperties(Uri uri, int?timeout, FileProperties properties, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials)
        {
            UriQueryBuilder builder = new UriQueryBuilder();

            builder.Add(Constants.QueryConstants.Component, "properties");

            StorageRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Put, uri, timeout, builder, content, operationContext, canonicalizer, credentials);

            if (properties != null)
            {
                request.AddOptionalHeader(Constants.HeaderConstants.FileCacheControlHeader, properties.CacheControl);
                request.AddOptionalHeader(Constants.HeaderConstants.FileContentDispositionRequestHeader, properties.ContentDisposition);
                request.AddOptionalHeader(Constants.HeaderConstants.FileContentEncodingHeader, properties.ContentEncoding);
                request.AddOptionalHeader(Constants.HeaderConstants.FileContentLanguageHeader, properties.ContentLanguage);
                request.AddOptionalHeader(Constants.HeaderConstants.FileContentMD5Header, properties.ContentMD5);
                request.AddOptionalHeader(Constants.HeaderConstants.FileContentTypeHeader, properties.ContentType);
            }

            request.ApplyAccessCondition(accessCondition);
            return(request);
        }