Example #1
0
 /// <summary>
 /// Reads account properties from a HttpWebResponse.
 /// </summary>
 /// <param name="response">The HttpWebResponse from which to read the account properties.</param>
 /// <returns>The account properties stored in the headers.</returns>
 public static AccountProperties ReadAccountProperties(HttpWebResponse response)
 {
     return(HttpResponseParsers.ReadAccountProperties(response));
 }
 /// <summary>
 /// Gets the user-defined metadata.
 /// </summary>
 /// <param name="response">The response from server.</param>
 /// <returns>A <see cref="IDictionary"/> of the metadata.</returns>
 public static IDictionary <string, string> GetMetadata(HttpResponseMessage response)
 {
     return(HttpResponseParsers.GetMetadata(response));
 }
 /// <summary>
 /// Reads service properties from a stream.
 /// </summary>
 /// <param name="inputStream">The stream from which to read the service properties.</param>
 /// <returns>The service properties stored in the stream.</returns>
 public static ServiceProperties ReadServiceProperties(Stream inputStream)
 {
     return(HttpResponseParsers.ReadServiceProperties(inputStream));
 }
        /// <summary>
        /// Gets the blob's properties from the response.
        /// </summary>
        /// <param name="response">The web response.</param>
        /// <returns>The blob's properties.</returns>
        public static BlobProperties GetProperties(HttpResponseMessage response)
        {
            CommonUtility.AssertNotNull("response", response);

            BlobProperties properties = new BlobProperties();

            if (response.Content != null)
            {
                properties.LastModified = response.Content.Headers.LastModified;
                HttpContentHeaders contentHeaders = response.Content.Headers;
                properties.ContentEncoding    = HttpWebUtility.GetHeaderValues("Content-Encoding", contentHeaders);
                properties.ContentLanguage    = HttpWebUtility.GetHeaderValues("Content-Language", contentHeaders);
                properties.ContentDisposition = HttpWebUtility.GetHeaderValues("Content-Disposition", contentHeaders);
                properties.ContentType        = HttpWebUtility.GetHeaderValues("Content-Type", contentHeaders);

                if (response.Content.Headers.ContentMD5 != null && response.Content.Headers.ContentRange == null)
                {
                    properties.ContentChecksum.MD5 = HttpResponseParsers.GetContentMD5(response);
                }
                else if (!string.IsNullOrEmpty(response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.BlobContentMD5Header)))
                {
                    properties.ContentChecksum.MD5 = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.BlobContentMD5Header);
                }

                // not yet supported and tested
                if (!string.IsNullOrEmpty(response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.BlobContentCRC64Header)))
                {
                    properties.ContentChecksum.CRC64 = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.BlobContentCRC64Header);
                }

                string created = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.CreationTimeHeader);
                properties.Created = string.IsNullOrEmpty(created) ? (DateTimeOffset?)null : DateTimeOffset.Parse(created, CultureInfo.InvariantCulture).ToUniversalTime();

                string blobEncryption = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.ServerEncrypted);
                properties.IsServerEncrypted = string.Equals(blobEncryption, Constants.HeaderConstants.TrueHeader, StringComparison.OrdinalIgnoreCase);

                string encryptionScope = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.EncryptionScopeHeader);
                if (!string.IsNullOrEmpty(encryptionScope))
                {
                    properties.EncryptionScope = encryptionScope;
                }

                string incrementalCopy = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.IncrementalCopyHeader);
                properties.IsIncrementalCopy = string.Equals(incrementalCopy, Constants.HeaderConstants.TrueHeader, StringComparison.OrdinalIgnoreCase);

                // Get the content length. Prioritize range and x-ms over content length for the special cases.
                string contentLengthHeader = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.BlobContentLengthHeader);
                if ((response.Content.Headers.ContentRange != null) &&
                    response.Content.Headers.ContentRange.HasLength)
                {
                    properties.Length = response.Content.Headers.ContentRange.Length.Value;
                }
                else if (!string.IsNullOrEmpty(contentLengthHeader))
                {
                    properties.Length = long.Parse(contentLengthHeader);
                }
                else if (response.Content.Headers.ContentLength.HasValue)
                {
                    properties.Length = response.Content.Headers.ContentLength.Value;
                }
            }
            properties.CacheControl = HttpWebUtility.GetHeaderValues("Cache-Control", response.Headers);

            if (response.Headers.ETag != null)
            {
                properties.ETag = response.Headers.ETag.ToString();
            }

            // Get blob type
            string blobType = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.BlobType);

            if (!string.IsNullOrEmpty(blobType))
            {
                properties.BlobType = (BlobType)Enum.Parse(typeof(BlobType), blobType, true);
            }

            // Get lease properties
            properties.LeaseStatus   = GetLeaseStatus(response);
            properties.LeaseState    = GetLeaseState(response);
            properties.LeaseDuration = GetLeaseDuration(response);

            // Get sequence number
            string sequenceNumber = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.BlobSequenceNumber);

            if (!string.IsNullOrEmpty(sequenceNumber))
            {
                properties.PageBlobSequenceNumber = long.Parse(sequenceNumber, CultureInfo.InvariantCulture);
            }

            // Get committed block count
            string comittedBlockCount = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.BlobCommittedBlockCount);

            if (!string.IsNullOrEmpty(comittedBlockCount))
            {
                properties.AppendBlobCommittedBlockCount = int.Parse(comittedBlockCount, CultureInfo.InvariantCulture);
            }

            // Get the tier of the blob
            string premiumBlobTierInferredString = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.AccessTierInferredHeader);

            if (!string.IsNullOrEmpty(premiumBlobTierInferredString))
            {
                properties.BlobTierInferred = Convert.ToBoolean(premiumBlobTierInferredString);
            }

            string              blobTierString = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.AccessTierHeader);
            StandardBlobTier?   standardBlobTier;
            PremiumPageBlobTier?premiumPageBlobTier;

            BlobHttpResponseParsers.GetBlobTier(properties.BlobType, blobTierString, out standardBlobTier, out premiumPageBlobTier);
            properties.StandardBlobTier    = standardBlobTier;
            properties.PremiumPageBlobTier = premiumPageBlobTier;

            // Get the rehydration status
            string rehydrationStatusString = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.ArchiveStatusHeader);

            if (!string.IsNullOrEmpty(rehydrationStatusString))
            {
                if (Constants.RehydratePendingToHot.Equals(rehydrationStatusString))
                {
                    properties.RehydrationStatus = RehydrationStatus.PendingToHot;
                }
                else if (Constants.RehydratePendingToCool.Equals(rehydrationStatusString))
                {
                    properties.RehydrationStatus = RehydrationStatus.PendingToCool;
                }
                else
                {
                    properties.RehydrationStatus = RehydrationStatus.Unknown;
                }
            }

            if ((properties.PremiumPageBlobTier.HasValue || properties.StandardBlobTier.HasValue) && !properties.BlobTierInferred.HasValue)
            {
                properties.BlobTierInferred = false;
            }

            // Get the time the tier of the blob was last modified
            string accessTierChangeTimeString = response.Headers.GetHeaderSingleValueOrDefault(Constants.HeaderConstants.AccessTierChangeTimeHeader);

            if (!string.IsNullOrEmpty(accessTierChangeTimeString))
            {
                properties.BlobTierLastModifiedTime = DateTimeOffset.Parse(accessTierChangeTimeString, CultureInfo.InvariantCulture);
            }

            return(properties);
        }
Example #5
0
 /// <summary>
 /// Reads service stats from a stream.
 /// </summary>
 /// <param name="inputStream">The stream from which to read the service stats.</param>
 /// <returns>The service stats stored in the stream.</returns>
 public static ServiceStats ReadServiceStats(Stream inputStream)
 {
     return(HttpResponseParsers.ReadServiceStats(inputStream));
 }
Example #6
0
        /// <summary>
        /// Implements getting the blob.
        /// </summary>
        /// <param name="blob">The blob object that is calling this method.</param>
        /// <param name="attributes">The blob's attributes.</param>
        /// <param name="destStream">The target stream.</param>
        /// <param name="offset">The offset at which to begin downloading the blob, in bytes.</param>
        /// <param name="length">The length of the data to download from the blob, in bytes.</param>
        /// <param name="accessCondition">An object that represents the access conditions for the blob. If null, no condition is used.</param>
        /// <param name="options">An object that specifies additional options for the request.</param>
        /// <returns>A <see cref="SynchronousTask"/> that gets the stream.</returns>
        internal static RESTCommand <NullType> GetBlobImpl(ICloudBlob blob, BlobAttributes attributes, Stream destStream, long?offset, long?length, AccessCondition accessCondition, BlobRequestOptions options)
        {
            string          lockedETag            = null;
            AccessCondition lockedAccessCondition = null;

            bool   isRangeGet             = offset.HasValue;
            bool   arePropertiesPopulated = false;
            string storedMD5 = null;

            long startingOffset = offset.HasValue ? offset.Value : 0;
            long?startingLength = length;
            long?validateLength = null;

            RESTCommand <NullType> getCmd = new RESTCommand <NullType>(blob.ServiceClient.Credentials, attributes.Uri);

            getCmd.ApplyRequestOptions(options);
            getCmd.RetrieveResponseStream        = true;
            getCmd.DestinationStream             = destStream;
            getCmd.CalculateMd5ForResponseStream = !options.DisableContentMD5Validation.Value;
            getCmd.Handler        = blob.ServiceClient.AuthenticationHandler;
            getCmd.BuildClient    = HttpClientFactory.BuildHttpClient;
            getCmd.BuildRequest   = (cmd, cnt, ctx) => BlobHttpRequestMessageFactory.Get(cmd.Uri, cmd.ServerTimeoutInSeconds, attributes.SnapshotTime, offset, length, options.UseTransactionalMD5.Value, accessCondition, cnt, ctx);
            getCmd.RecoveryAction = (cmd, ex, ctx) =>
            {
                if ((lockedAccessCondition == null) && !string.IsNullOrEmpty(lockedETag))
                {
                    lockedAccessCondition = AccessCondition.GenerateIfMatchCondition(lockedETag);
                    if (accessCondition != null)
                    {
                        lockedAccessCondition.LeaseId = accessCondition.LeaseId;
                    }
                }

                if (cmd.StreamCopyState != null)
                {
                    offset = startingOffset + cmd.StreamCopyState.Length;
                    if (startingLength.HasValue)
                    {
                        length = startingLength.Value - cmd.StreamCopyState.Length;
                    }
                }

                getCmd.BuildRequest = (command, cnt, context) => BlobHttpRequestMessageFactory.Get(command.Uri, command.ServerTimeoutInSeconds, attributes.SnapshotTime, offset, length, options.UseTransactionalMD5.Value && !arePropertiesPopulated, lockedAccessCondition ?? accessCondition, cnt, context);
            };

            getCmd.PreProcessResponse = (cmd, resp, ex, ctx) =>
            {
                HttpResponseParsers.ProcessExpectedStatusCodeNoException(offset.HasValue ? HttpStatusCode.PartialContent : HttpStatusCode.OK, resp, NullType.Value, cmd, ex);

                if (!arePropertiesPopulated)
                {
                    CloudBlobSharedImpl.UpdateAfterFetchAttributes(attributes, resp, isRangeGet);

                    if (resp.Content.Headers.ContentMD5 != null)
                    {
                        storedMD5 = Convert.ToBase64String(resp.Content.Headers.ContentMD5);
                    }

                    if (!options.DisableContentMD5Validation.Value &&
                        options.UseTransactionalMD5.Value &&
                        string.IsNullOrEmpty(storedMD5))
                    {
                        throw new StorageException(
                                  cmd.CurrentResult,
                                  SR.MD5NotPresentError,
                                  null)
                              {
                                  IsRetryable = false
                              };
                    }

                    lockedETag     = attributes.Properties.ETag;
                    validateLength = resp.Content.Headers.ContentLength;

                    arePropertiesPopulated = true;
                }

                return(NullType.Value);
            };

            getCmd.PostProcessResponse = (cmd, resp, ctx) =>
            {
                HttpResponseParsers.ValidateResponseStreamMd5AndLength(validateLength, storedMD5, cmd);
                return(Task.FromResult(NullType.Value));
            };

            return(getCmd);
        }
Example #7
0
        /// <summary>
        /// Gets the blob's properties from the response.
        /// </summary>
        /// <param name="response">The web response.</param>
        /// <returns>The blob's properties.</returns>
        public static BlobProperties GetProperties(HttpWebResponse response)
        {
            CommonUtility.AssertNotNull("response", response);

            BlobProperties properties = new BlobProperties();

            properties.ETag = HttpResponseParsers.GetETag(response);

#if WINDOWS_PHONE
            properties.LastModified    = HttpResponseParsers.GetLastModified(response);
            properties.ContentLanguage = response.Headers[Constants.HeaderConstants.ContentLanguageHeader];
#else
            properties.LastModified    = response.LastModified.ToUniversalTime();
            properties.ContentLanguage = response.Headers[HttpResponseHeader.ContentLanguage];
#endif

            properties.ContentDisposition = response.Headers[Constants.HeaderConstants.ContentDispositionResponseHeader];
            properties.ContentEncoding    = response.Headers[HttpResponseHeader.ContentEncoding];

            // For range gets, only look at 'x-ms-blob-content-md5' for overall MD5
            if (response.Headers[HttpResponseHeader.ContentRange] != null)
            {
                properties.ContentMD5 = response.Headers[Constants.HeaderConstants.BlobContentMD5Header];
            }
            else
            {
                properties.ContentMD5 = response.Headers[HttpResponseHeader.ContentMd5];
            }

            properties.ContentType  = response.Headers[HttpResponseHeader.ContentType];
            properties.CacheControl = response.Headers[HttpResponseHeader.CacheControl];

            string blobEncryption = response.Headers[Constants.HeaderConstants.ServerEncrypted];
            properties.IsServerEncrypted = string.Equals(blobEncryption, Constants.HeaderConstants.TrueHeader, StringComparison.OrdinalIgnoreCase);

            string incrementalCopy = response.Headers[Constants.HeaderConstants.IncrementalCopyHeader];
            properties.IsIncrementalCopy = string.Equals(incrementalCopy, Constants.HeaderConstants.TrueHeader, StringComparison.OrdinalIgnoreCase);

            // Get blob type
            string blobType = response.Headers[Constants.HeaderConstants.BlobType];
            if (!string.IsNullOrEmpty(blobType))
            {
                properties.BlobType = (BlobType)Enum.Parse(typeof(BlobType), blobType, true);
            }

            // Get lease properties
            properties.LeaseStatus   = GetLeaseStatus(response);
            properties.LeaseState    = GetLeaseState(response);
            properties.LeaseDuration = GetLeaseDuration(response);

            // Get the content length. Prioritize range and x-ms over content length for the special cases.
            string rangeHeader             = response.Headers[HttpResponseHeader.ContentRange];
            string contentLengthHeader     = response.Headers[Constants.HeaderConstants.ContentLengthHeader];
            string blobContentLengthHeader = response.Headers[Constants.HeaderConstants.BlobContentLengthHeader];
            if (!string.IsNullOrEmpty(rangeHeader))
            {
                properties.Length = long.Parse(rangeHeader.Split('/')[1], CultureInfo.InvariantCulture);
            }
            else if (!string.IsNullOrEmpty(blobContentLengthHeader))
            {
                properties.Length = long.Parse(blobContentLengthHeader, CultureInfo.InvariantCulture);
            }
            else if (!string.IsNullOrEmpty(contentLengthHeader))
            {
                // On Windows Phone, ContentLength property is not always same as Content-Length header,
                // so we try to parse the header first.
                properties.Length = long.Parse(contentLengthHeader, CultureInfo.InvariantCulture);
            }
            else
            {
                properties.Length = response.ContentLength;
            }

            // Get sequence number
            string sequenceNumber = response.Headers[Constants.HeaderConstants.BlobSequenceNumber];
            if (!string.IsNullOrEmpty(sequenceNumber))
            {
                properties.PageBlobSequenceNumber = long.Parse(sequenceNumber, CultureInfo.InvariantCulture);
            }

            // Get committed block count
            string comittedBlockCount = response.Headers[Constants.HeaderConstants.BlobCommittedBlockCount];
            if (!string.IsNullOrEmpty(comittedBlockCount))
            {
                properties.AppendBlobCommittedBlockCount = int.Parse(comittedBlockCount, CultureInfo.InvariantCulture);
            }

            // Get the tier of the blob
            string premiumPageBlobTierInferredString = response.Headers[Constants.HeaderConstants.AccessTierInferredHeader];
            if (!string.IsNullOrEmpty(premiumPageBlobTierInferredString))
            {
                properties.BlobTierInferred = Convert.ToBoolean(premiumPageBlobTierInferredString);
            }

            string blobTierString = response.Headers[Constants.HeaderConstants.AccessTierHeader];

            StandardBlobTier?   standardBlobTier;
            PremiumPageBlobTier?premiumPageBlobTier;
            BlobHttpResponseParsers.GetBlobTier(properties.BlobType, blobTierString, out standardBlobTier, out premiumPageBlobTier);
            properties.StandardBlobTier    = standardBlobTier;
            properties.PremiumPageBlobTier = premiumPageBlobTier;

            if ((properties.PremiumPageBlobTier.HasValue || properties.StandardBlobTier.HasValue) && !properties.BlobTierInferred.HasValue)
            {
                properties.BlobTierInferred = false;
            }

            // Get the rehydration status
            string rehydrationStatusString = response.Headers[Constants.HeaderConstants.ArchiveStatusHeader];
            properties.RehydrationStatus = BlobHttpResponseParsers.GetRehydrationStatus(rehydrationStatusString);

            // Get the time the tier of the blob was last modified
            string accessTierChangeTimeString = response.Headers[Constants.HeaderConstants.AccessTierChangeTimeHeader];
            if (!string.IsNullOrEmpty(accessTierChangeTimeString))
            {
                properties.BlobTierLastModifiedTime = DateTimeOffset.Parse(accessTierChangeTimeString, CultureInfo.InvariantCulture);
            }

            return(properties);
        }
Example #8
0
        private RESTCommand <ServiceStats> GetServiceStatsImpl(TableRequestOptions requestOptions)
        {
            if (RetryPolicies.LocationMode.PrimaryOnly == requestOptions.LocationMode)
            {
                throw new InvalidOperationException(SR.GetServiceStatsInvalidOperation);
            }

            RESTCommand <ServiceStats> retCmd = new RESTCommand <ServiceStats>(this.Credentials, this.StorageUri);

            requestOptions.ApplyToStorageCommand(retCmd);
            retCmd.CommandLocationMode    = CommandLocationMode.PrimaryOrSecondary;
            retCmd.BuildRequest           = (cmd, uri, builder, cnt, serverTimeout, ctx) => TableHttpRequestMessageFactory.GetServiceStats(uri, serverTimeout, ctx, this.GetCanonicalizer(), this.Credentials);
            retCmd.RetrieveResponseStream = true;
            retCmd.ParseError             = StorageExtendedErrorInformation.ReadFromStreamUsingODataLib;
            retCmd.PreProcessResponse     = (cmd, resp, ex, ctx) => HttpResponseParsers.ProcessExpectedStatusCodeNoException(HttpStatusCode.OK, resp, null /* retVal */, cmd, ex);
            retCmd.PostProcessResponse    = (cmd, resp, ctx) => Task.Factory.StartNew(() => HttpResponseParsers.ReadServiceStats(cmd.ResponseStream));
            return(retCmd);
        }
        public async Task ListContainersScenarioTest(ListingContext listingContext, HttpStatusCode?expectedError, params string[] expectedContainers)
        {
            HttpRequestMessage request = BlobTests.ListContainersRequest(BlobContext, listingContext);

            Assert.IsTrue(request != null, "Failed to create HttpRequestMessage");
            using (HttpResponseMessage response = await BlobTestUtils.GetResponse(request, BlobContext))
            {
                BlobTests.ListContainersResponse(response, BlobContext, expectedError);
                ListContainersResponse listContainersResponse = await ListContainersResponse.ParseAsync(HttpResponseParsers.GetResponseStream(response), CancellationToken.None);

                int i = 0;
                foreach (BlobContainerEntry item in listContainersResponse.Containers)
                {
                    if (expectedContainers == null)
                    {
                        Assert.Fail("Should not have containers.");
                    }
                    Assert.IsTrue(i < expectedContainers.Length, "Unexpected container: " + item.Name);
                    Assert.AreEqual <string>(expectedContainers[i++], item.Name, "Incorrect container.");
                }
                if (expectedContainers != null && i < expectedContainers.Length)
                {
                    Assert.Fail("Missing container: " + expectedContainers[i] + "(and " + (expectedContainers.Length - i - 1) + " more).");
                }
            }
        }
 /// <summary>
 /// Reads service stats from a stream.
 /// </summary>
 /// <param name="inputStream">The stream from which to read the service stats.</param>
 /// <returns>The service stats stored in the stream.</returns>
 public static Task <ServiceStats> ReadServiceStatsAsync(Stream inputStream, CancellationToken token)
 {
     return(HttpResponseParsers.ReadServiceStatsAsync(inputStream, token));
 }
        public async Task ClearPageRangeScenarioTest(string containerName, string blobName, HttpStatusCode?expectedError)
        {
            // 1. Create Sparse Page Blob
            int blobSize = 128 * 1024;

            BlobProperties properties = new BlobProperties()
            {
                BlobType = BlobType.PageBlob
            };
            Uri uri = BlobTests.ConstructPutUri(BlobContext.Address, containerName, blobName);
            OperationContext   opContext  = new OperationContext();
            HttpRequestMessage webRequest = BlobHttpRequestMessageFactory.Put(uri, BlobContext.Timeout, properties, BlobType.PageBlob, blobSize, null, null, null, opContext, null, null);


            using (HttpResponseMessage response = await BlobTestUtils.GetResponse(webRequest, BlobContext))
            {
                BlobTests.PutBlobResponse(response, BlobContext, expectedError);
            }

            // 2. Now upload some page ranges
            for (int m = 0; m * 512 * 4 < blobSize; m++)
            {
                int startOffset = 512 * 4 * m;
                int length      = 512;

                PageRange range = new PageRange(startOffset, startOffset + length - 1);
                opContext = new OperationContext();
                HttpRequestMessage pageRequest = BlobHttpRequestMessageFactory.PutPage(uri, BlobContext.Timeout, range, PageWrite.Update, null, null, opContext, null, null);
                HttpRequestHandler.SetContentLength(pageRequest, 512);

                byte[] content = new byte[length];
                random.NextBytes(content);

                pageRequest.Content = new ByteArrayContent(content);

                using (HttpResponseMessage pageResponse = await BlobTestUtils.GetResponse(pageRequest, BlobContext))
                {
                }
            }

            // 3. Now do a Get Page Ranges
            List <PageRange> pageRanges = new List <PageRange>();

            opContext = new OperationContext();
            HttpRequestMessage pageRangeRequest = BlobHttpRequestMessageFactory.GetPageRanges(uri, BlobContext.Timeout, null, null, null, null, null, opContext, null, null);

            using (HttpResponseMessage pageRangeResponse = await BlobTestUtils.GetResponse(pageRangeRequest, BlobContext))
            {
                var ranges = await GetPageRangesResponse.ParseAsync(HttpResponseParsers.GetResponseStream(pageRangeResponse), CancellationToken.None);

                pageRanges.AddRange(ranges);
            }

            // 4. Now Clear some pages
            bool skipFlag = false;

            foreach (PageRange pRange in pageRanges)
            {
                skipFlag = !skipFlag;
                if (skipFlag)
                {
                    continue;
                }

                opContext = new OperationContext();
                HttpRequestMessage clearPageRequest = BlobHttpRequestMessageFactory.PutPage(uri, BlobContext.Timeout, pRange, PageWrite.Clear, null, null, opContext, null, null);
                HttpRequestHandler.SetContentLength(clearPageRequest, 0);
                using (HttpResponseMessage clearResponse = await BlobTestUtils.GetResponse(clearPageRequest, BlobContext))
                {
                }
            }

            // 5. Get New Page ranges and verify
            List <PageRange> newPageRanges = new List <PageRange>();

            opContext = new OperationContext();
            HttpRequestMessage newPageRangeRequest = BlobHttpRequestMessageFactory.GetPageRanges(uri, BlobContext.Timeout, null, null, null, null, null, opContext, null, null);

            using (HttpResponseMessage newPageRangeResponse = await BlobTestUtils.GetResponse(newPageRangeRequest, BlobContext))
            {
                var ranges = await GetPageRangesResponse.ParseAsync(HttpResponseParsers.GetResponseStream(newPageRangeResponse), CancellationToken.None);

                newPageRanges.AddRange(ranges);
            }

            Assert.AreEqual(pageRanges.Count(), newPageRanges.Count() * 2);
            for (int l = 0; l < newPageRanges.Count(); l++)
            {
                Assert.AreEqual(pageRanges[2 * l].StartOffset, newPageRanges[l].StartOffset);
                Assert.AreEqual(pageRanges[2 * l].EndOffset, newPageRanges[l].EndOffset);
            }
        }
Example #12
0
        /// <summary>
        /// Sets the SMB related file properties.
        /// </summary>
        /// <param name="response">The web response.</param>
        /// <param name="properties">The properties to modify.</param>
        public static void UpdateSmbProperties(HttpResponseMessage response, FileProperties properties)
        {
            properties.filePermissionKey = HttpResponseParsers.GetHeader(response, Constants.HeaderConstants.FilePermissionKey);
            properties.ntfsAttributes    = CloudFileNtfsAttributesHelper.ToAttributes(HttpResponseParsers.GetHeader(response, Constants.HeaderConstants.FileAttributes));
            properties.creationTime      = DateTimeOffset.Parse(HttpResponseParsers.GetHeader(response, Constants.HeaderConstants.FileCreationTime));
            properties.lastWriteTime     = DateTimeOffset.Parse(HttpResponseParsers.GetHeader(response, Constants.HeaderConstants.FileLastWriteTime));
            properties.ChangeTime        = DateTimeOffset.Parse(HttpResponseParsers.GetHeader(response, Constants.HeaderConstants.FileChangeTime));
            properties.FileId            = HttpResponseParsers.GetHeader(response, Constants.HeaderConstants.FileId);
            properties.ParentId          = HttpResponseParsers.GetHeader(response, Constants.HeaderConstants.FileParentId);

            properties.filePermissionKeyToSet = null;
            properties.ntfsAttributesToSet    = null;
            properties.creationTimeToSet      = null;
            properties.lastWriteTimeToSet     = null;
        }
        private RESTCommand <ServiceStats> GetServiceStatsImpl(TableRequestOptions requestOptions)
        {
            RESTCommand <ServiceStats> retCmd = new RESTCommand <ServiceStats>(this.Credentials, this.StorageUri);

            requestOptions.ApplyToStorageCommand(retCmd);
            retCmd.CommandLocationMode    = CommandLocationMode.PrimaryOrSecondary;
            retCmd.BuildRequest           = (cmd, uri, builder, cnt, serverTimeout, ctx) => TableHttpRequestMessageFactory.GetServiceStats(uri, serverTimeout, ctx);
            retCmd.RetrieveResponseStream = true;
            retCmd.ParseError             = StorageExtendedErrorInformation.ReadFromStreamUsingODataLib;
            retCmd.Handler             = this.AuthenticationHandler;
            retCmd.BuildClient         = HttpClientFactory.BuildHttpClient;
            retCmd.PreProcessResponse  = (cmd, resp, ex, ctx) => HttpResponseParsers.ProcessExpectedStatusCodeNoException(HttpStatusCode.OK, resp, null /* retVal */, cmd, ex);
            retCmd.PostProcessResponse = (cmd, resp, ctx) => Task.Factory.StartNew(() => HttpResponseParsers.ReadServiceStats(cmd.ResponseStream));
            return(retCmd);
        }
        /// <summary>
        /// Gets the blob's properties from the response.
        /// </summary>
        /// <param name="response">The web response.</param>
        /// <returns>The blob's properties.</returns>
        public static BlobProperties GetProperties(HttpWebResponse response)
        {
            CommonUtility.AssertNotNull("response", response);

            BlobProperties properties = new BlobProperties();

            properties.ETag = HttpResponseParsers.GetETag(response);

#if WINDOWS_PHONE
            properties.LastModified    = HttpResponseParsers.GetLastModified(response);
            properties.ContentLanguage = response.Headers[Constants.HeaderConstants.ContentLanguageHeader];
#else
            properties.LastModified    = response.LastModified.ToUniversalTime();
            properties.ContentLanguage = response.Headers[HttpResponseHeader.ContentLanguage];
#endif

            properties.ContentEncoding = response.Headers[HttpResponseHeader.ContentEncoding];
            properties.ContentMD5      = response.Headers[HttpResponseHeader.ContentMd5];
            properties.ContentType     = response.Headers[HttpResponseHeader.ContentType];
            properties.CacheControl    = response.Headers[HttpResponseHeader.CacheControl];

            // Get blob type
            string blobType = response.Headers[Constants.HeaderConstants.BlobType];
            if (!string.IsNullOrEmpty(blobType))
            {
                properties.BlobType = (BlobType)Enum.Parse(typeof(BlobType), blobType, true);
            }

            // Get lease properties
            properties.LeaseStatus   = GetLeaseStatus(response);
            properties.LeaseState    = GetLeaseState(response);
            properties.LeaseDuration = GetLeaseDuration(response);

            // Get the content length. Prioritize range and x-ms over content length for the special cases.
            string rangeHeader             = response.Headers[HttpResponseHeader.ContentRange];
            string contentLengthHeader     = response.Headers[Constants.HeaderConstants.ContentLengthHeader];
            string blobContentLengthHeader = response.Headers[Constants.HeaderConstants.BlobContentLengthHeader];
            if (!string.IsNullOrEmpty(rangeHeader))
            {
                properties.Length = long.Parse(rangeHeader.Split('/')[1], CultureInfo.InvariantCulture);
            }
            else if (!string.IsNullOrEmpty(blobContentLengthHeader))
            {
                properties.Length = long.Parse(blobContentLengthHeader, CultureInfo.InvariantCulture);
            }
            else if (!string.IsNullOrEmpty(contentLengthHeader))
            {
                // On Windows Phone, ContentLength property is not always same as Content-Length header,
                // so we try to parse the header first.
                properties.Length = long.Parse(contentLengthHeader, CultureInfo.InvariantCulture);
            }
            else
            {
                properties.Length = response.ContentLength;
            }

            // Get sequence number
            string sequenceNumber = response.Headers[Constants.HeaderConstants.BlobSequenceNumber];
            if (!string.IsNullOrEmpty(sequenceNumber))
            {
                properties.PageBlobSequenceNumber = long.Parse(sequenceNumber, CultureInfo.InvariantCulture);
            }

            return(properties);
        }
        /// <summary>
        /// Reads the share access policies from a stream in XML.
        /// </summary>
        /// <param name="inputStream">The stream of XML policies.</param>
        /// <param name="permissions">The permissions object to which the policies are to be written.</param>
        public static void ReadSharedAccessIdentifiers(Stream inputStream, TablePermissions permissions)
        {
            CommonUtility.AssertNotNull("permissions", permissions);

            HttpResponseParsers.ReadSharedAccessIdentifiers(permissions.SharedAccessPolicies, new TableAccessPolicyResponse(inputStream));
        }