public static async Task <StorageExtendedErrorInformation> ReadFromStreamAsync(Stream inputStream, CancellationToken cancellationToken)
        {
            CommonUtility.AssertNotNull("inputStream", inputStream);
            if (inputStream.CanSeek && inputStream.Length < 1)
            {
                return(null);
            }
            try
            {
                using (XmlReader reader = XMLReaderExtensions.CreateAsAsync(inputStream))
                {
                    await reader.ReadAsync().ConfigureAwait(continueOnCapturedContext: false);

                    cancellationToken.ThrowIfCancellationRequested();
                    StorageExtendedErrorInformation result = await ReadXmlAsync(reader, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);

                    cancellationToken.ThrowIfCancellationRequested();
                    return(result);
                }
            }
            catch (XmlException)
            {
                return(null);
            }
        }
        /// <summary>
        /// Parses the XML response for an operation to get a range for a file.
        /// </summary>
        /// <returns>An enumerable collection of <see cref="FileRange"/> objects.</returns>
        internal static async Task <IEnumerable <FileRange> > ParseAsync(Stream stream, CancellationToken token)
        {
            using (XmlReader reader = XMLReaderExtensions.CreateAsAsync(stream))
            {
                token.ThrowIfCancellationRequested();

                List <FileRange> ranges = new List <FileRange>();

                if (await reader.ReadToFollowingAsync(Constants.FileRangeListElement).ConfigureAwait(false))
                {
                    if (reader.IsEmptyElement)
                    {
                        await reader.SkipAsync().ConfigureAwait(false);
                    }
                    else
                    {
                        await reader.ReadStartElementAsync().ConfigureAwait(false);

                        while (await reader.IsStartElementAsync(Constants.FileRangeElement).ConfigureAwait(false))
                        {
                            ranges.Add(await ParseRangeAsync(reader, token).ConfigureAwait(false));
                        }

                        await reader.ReadEndElementAsync().ConfigureAwait(false);
                    }
                }

                return(ranges);
            }
        }
示例#3
0
        /// <summary>
        /// Gets the error details from an XML-formatted error stream.
        /// </summary>
        /// <param name="inputStream">The input stream.</param>
        /// <returns>The error details.</returns>
        public static async Task <StorageExtendedErrorInformation> ReadFromStreamAsync(Stream inputStream)
        {
            CommonUtility.AssertNotNull("inputStream", inputStream);

            if (inputStream.CanSeek && inputStream.Length < 1)
            {
                return(null);
            }

            StorageExtendedErrorInformation extendedErrorInfo = new StorageExtendedErrorInformation();

            try
            {
                using (XmlReader reader = XMLReaderExtensions.CreateAsAsync(inputStream))
                {
                    await reader.ReadAsync().ConfigureAwait(false);

                    await extendedErrorInfo.ReadXmlAsync(reader, CancellationToken.None).ConfigureAwait(false);
                }

                return(extendedErrorInfo);
            }
            catch (XmlException)
            {
                // If there is a parsing error we cannot return extended error information
                return(null);
            }
        }
        public async Task ExtendedErrorInfoVerifyXmlWithAdditionalDetails()
        {
            Uri                baseAddressUri = new Uri(TestBase.TargetTenantConfig.BlobServiceEndpoint);
            CloudBlobClient    client         = new CloudBlobClient(baseAddressUri, TestBase.StorageCredentials);
            CloudBlobContainer container      = client.GetContainerReference(Guid.NewGuid().ToString("N"));

            byte[] buffer     = TestBase.GetRandomBuffer(4 * 1024 * 1024);
            MD5    md5        = MD5.Create();
            string contentMD5 = Convert.ToBase64String(md5.ComputeHash(buffer));

            try
            {
                container.Create();
                CloudBlockBlob blob   = container.GetBlockBlobReference("blob1");
                List <string>  blocks = new List <string>();
                for (int i = 0; i < 2; i++)
                {
                    blocks.Add(Convert.ToBase64String(Guid.NewGuid().ToByteArray()));
                }

                using (MemoryStream memoryStream = new MemoryStream(buffer))
                {
                    memoryStream.Seek(0, SeekOrigin.Begin);
                    blob.PutBlock(blocks[0], memoryStream, contentMD5);

                    int offset = buffer.Length - 1024;
                    memoryStream.Seek(offset, SeekOrigin.Begin);
                    StorageException e = TestHelper.ExpectedException <StorageException>(
                        () => blob.PutBlock(blocks[1], memoryStream, contentMD5),
                        "Invalid MD5 should fail with mismatch");

                    Assert.IsNotNull(e.RequestInformation.ExtendedErrorInformation);

                    StorageExtendedErrorInformation retrErrorInfo = new StorageExtendedErrorInformation();
                    XmlWriterSettings settings = new XmlWriterSettings();
                    settings.Indent = true;
                    StringBuilder sb = new StringBuilder();
                    using (XmlWriter writer = XmlWriter.Create(sb, settings))
                    {
                        e.RequestInformation.ExtendedErrorInformation.WriteXml(writer);
                    }

                    using (XmlReader reader = XMLReaderExtensions.CreateAsAsync(new MemoryStream(Encoding.Unicode.GetBytes(sb.ToString()))))
                    {
                        await retrErrorInfo.ReadXmlAsync(reader, CancellationToken.None);
                    }

                    Assert.AreEqual(e.RequestInformation.ExtendedErrorInformation.ErrorCode, retrErrorInfo.ErrorCode);
                    Assert.AreEqual(e.RequestInformation.ExtendedErrorInformation.ErrorMessage, retrErrorInfo.ErrorMessage);
                    Assert.AreNotEqual(0, retrErrorInfo.AdditionalDetails.Count);
                    Assert.AreEqual(e.RequestInformation.ExtendedErrorInformation.AdditionalDetails.Count, retrErrorInfo.AdditionalDetails.Count);
                }
            }
            finally
            {
                container.DeleteIfExists();
            }
        }
        public async Task QueueContinuationTokenVerifyXmlFunctions()
        {
            CloudQueueClient client     = GenerateCloudQueueClient();
            string           prefix     = "dotnetqueuetest" + Guid.NewGuid().ToString("N");
            List <string>    queueNames = new List <string>();
            int count = 30;

            for (int i = 0; i < count; i++)
            {
                queueNames.Add(prefix + i);
                client.GetQueueReference(prefix + i).Create();
            }

            QueueContinuationToken token   = null;
            List <CloudQueue>      results = new List <CloudQueue>();

            do
            {
                QueueResultSegment segment = client.ListQueuesSegmented(prefix, QueueListingDetails.None, 5, token, null, null);
                token = segment.ContinuationToken;
                results.AddRange(segment.Results);
                if (token != null)
                {
                    Assert.AreEqual(null, token.GetSchema());

                    XmlWriterSettings settings = new XmlWriterSettings();
                    settings.Indent = true;
                    StringBuilder sb = new StringBuilder();
                    using (XmlWriter writer = XmlWriter.Create(sb, settings))
                    {
                        token.WriteXml(writer);
                    }

                    using (XmlReader reader = XMLReaderExtensions.CreateAsAsync(new MemoryStream(Encoding.Unicode.GetBytes(sb.ToString()))))
                    {
                        token = new QueueContinuationToken();
                        await token.ReadXmlAsync(reader);
                    }
                }
            }while (token != null);

            foreach (CloudQueue queue in results)
            {
                if (queueNames.Remove(queue.Name))
                {
                    queue.Delete();
                }
                else
                {
                    Assert.Fail();
                }
            }

            Assert.AreEqual <int>(0, queueNames.Count);
        }
示例#6
0
        /// <summary>
        /// Parses the XML response returned by an operation to get messages from a queue.
        /// </summary>
        /// <returns>An enumerable collection of <see cref="QueueMessage"/> objects.</returns>
        internal static async Task <IEnumerable <QueueMessage> > ParseAsync(Stream stream, CancellationToken token)
        {
            using (XmlReader reader = XMLReaderExtensions.CreateAsAsync(stream))
            {
                token.ThrowIfCancellationRequested();

                List <QueueMessage> messages = new List <QueueMessage>();

                if (await reader.ReadToFollowingAsync(Constants.MessagesElement).ConfigureAwait(false))
                {
                    if (reader.IsEmptyElement)
                    {
                        await reader.SkipAsync().ConfigureAwait(false);
                    }
                    else
                    {
                        await reader.ReadStartElementAsync().ConfigureAwait(false);

                        while (await reader.IsStartElementAsync().ConfigureAwait(false))
                        {
                            token.ThrowIfCancellationRequested();

                            if (reader.IsEmptyElement)
                            {
                                await reader.SkipAsync().ConfigureAwait(false);
                            }
                            else
                            {
                                switch (reader.Name)
                                {
                                case Constants.MessageElement:
                                    while (await reader.IsStartElementAsync().ConfigureAwait(false))
                                    {
                                        messages.Add(await ParseMessageEntryAsync(reader, token).ConfigureAwait(false));
                                    }

                                    break;

                                default:
                                    await reader.SkipAsync().ConfigureAwait(false);

                                    break;
                                }
                            }
                        }

                        await reader.ReadEndElementAsync().ConfigureAwait(false);
                    }
                }

                return(messages);
            }
        }
        public async Task QueueContinuationTokenVerifyEmptyTargetDeserializer()
        {
            QueueContinuationToken queueContinuationToken = new QueueContinuationToken {
                TargetLocation = null
            };
            StringBuilder stringBuilder = new StringBuilder();

            using (XmlWriter writer = XmlWriter.Create(stringBuilder))
            {
                queueContinuationToken.WriteXml(writer);
            }

            string stringToken = stringBuilder.ToString();
            QueueContinuationToken parsedToken = new QueueContinuationToken();
            await parsedToken.ReadXmlAsync(XMLReaderExtensions.CreateAsAsync(new MemoryStream(Encoding.Unicode.GetBytes(stringToken))));

            Assert.AreEqual(parsedToken.TargetLocation, null);
        }
示例#8
0
        internal static async Task <UserDelegationKey> ParseAsync(Stream stream, CancellationToken token)
        {
            UserDelegationKey key = null;

            using (XmlReader reader = XMLReaderExtensions.CreateAsAsync(stream))
            {
                token.ThrowIfCancellationRequested();

                if (await reader.ReadToFollowingAsync(Constants.UserDelegationKey).ConfigureAwait(false))
                {
                    if (reader.IsEmptyElement)
                    {
                        await reader.SkipAsync().ConfigureAwait(false);
                    }
                    else
                    {
                        key = await ParseKey(reader, token);
                    }
                }
            }

            return(key);
        }
        public async Task ExtendedErrorInfoVerifyXml()
        {
            Uri                baseAddressUri = new Uri(TestBase.TargetTenantConfig.BlobServiceEndpoint);
            CloudBlobClient    client         = new CloudBlobClient(baseAddressUri, TestBase.StorageCredentials);
            CloudBlobContainer container      = client.GetContainerReference(Guid.NewGuid().ToString("N"));

            try
            {
                StorageException e = TestHelper.ExpectedException <StorageException>(
                    () => container.GetPermissions(),
                    "Try to get permissions on a non-existent container");

                Assert.IsNotNull(e.RequestInformation.ExtendedErrorInformation);

                StorageExtendedErrorInformation retrErrorInfo = new StorageExtendedErrorInformation();
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent = true;
                StringBuilder sb = new StringBuilder();
                using (XmlWriter writer = XmlWriter.Create(sb, settings))
                {
                    e.RequestInformation.ExtendedErrorInformation.WriteXml(writer);
                }

                using (XmlReader reader = XMLReaderExtensions.CreateAsAsync(new MemoryStream(Encoding.Unicode.GetBytes(sb.ToString()))))
                {
                    await retrErrorInfo.ReadXmlAsync(reader, CancellationToken.None);
                }

                Assert.AreEqual(e.RequestInformation.ExtendedErrorInformation.ErrorCode, retrErrorInfo.ErrorCode);
                Assert.AreEqual(e.RequestInformation.ExtendedErrorInformation.ErrorMessage, retrErrorInfo.ErrorMessage);
            }
            finally
            {
                container.DeleteIfExists();
            }
        }
        /// <summary>
        /// Parses the response XML for a container listing operation.
        /// </summary>
        /// <returns>An enumerable collection of <see cref="BlobContainerEntry"/> objects.</returns>
        internal static async Task <ListContainersResponse> ParseAsync(Stream stream, CancellationToken token)
        {
            using (XmlReader reader = XMLReaderExtensions.CreateAsAsync(stream))
            {
                token.ThrowIfCancellationRequested();

                List <BlobContainerEntry> entries = new List <BlobContainerEntry>();

                string nextMarker = default(string);

                if (await reader.ReadToFollowingAsync(Constants.EnumerationResultsElement).ConfigureAwait(false))
                {
                    if (reader.IsEmptyElement)
                    {
                        await reader.SkipAsync().ConfigureAwait(false);
                    }
                    else
                    {
                        Uri baseUri = new Uri(reader.GetAttribute(Constants.ServiceEndpointElement));

                        await reader.ReadStartElementAsync().ConfigureAwait(false);

                        while (await reader.IsStartElementAsync().ConfigureAwait(false))
                        {
                            token.ThrowIfCancellationRequested();

                            if (reader.IsEmptyElement)
                            {
                                await reader.SkipAsync().ConfigureAwait(false);
                            }
                            else
                            {
                                switch (reader.Name)
                                {
                                case Constants.MarkerElement:
                                    await reader.ReadElementContentAsStringAsync().ConfigureAwait(false);

                                    break;

                                case Constants.NextMarkerElement:
                                    nextMarker = await reader.ReadElementContentAsStringAsync().ConfigureAwait(false);

                                    break;

                                case Constants.MaxResultsElement:
                                    await reader.ReadElementContentAsInt32Async().ConfigureAwait(false);

                                    break;

                                case Constants.PrefixElement:
                                    await reader.ReadElementContentAsStringAsync().ConfigureAwait(false);

                                    break;

                                case Constants.ContainersElement:
                                    await reader.ReadStartElementAsync().ConfigureAwait(false);

                                    while (await reader.IsStartElementAsync(Constants.ContainerElement).ConfigureAwait(false))
                                    {
                                        entries.Add(await ParseContainerEntryAsync(reader, baseUri, token).ConfigureAwait(false));
                                    }

                                    await reader.ReadEndElementAsync().ConfigureAwait(false);

                                    break;

                                default:
                                    await reader.SkipAsync().ConfigureAwait(false);

                                    break;
                                }
                            }
                        }

                        await reader.ReadEndElementAsync().ConfigureAwait(false);
                    }
                }

                return(new ListContainersResponse {
                    Containers = entries, NextMarker = nextMarker
                });
            }
        }
        /// <summary>
        /// Parses the response XML for a blob listing operation.
        /// </summary>
        /// <returns>An enumerable collection of objects that implement <see cref="IListBlobEntry"/>.</returns>
        internal static async Task <ListBlobsResponse> ParseAsync(Stream stream, CancellationToken token)
        {
            using (XmlReader reader = XMLReaderExtensions.CreateAsAsync(stream))
            {
                token.ThrowIfCancellationRequested();

                List <IListBlobEntry> entries = new List <IListBlobEntry>();
                string nextMarker             = default(string);

                if (await reader.ReadToFollowingAsync(Constants.EnumerationResultsElement).ConfigureAwait(false))
                {
                    if (reader.IsEmptyElement)
                    {
                        await reader.SkipAsync().ConfigureAwait(false);
                    }
                    else
                    {
                        Uri    baseUri;
                        string serviceEndpoint = reader.GetAttribute(Constants.ServiceEndpointElement);
                        if (!string.IsNullOrEmpty(serviceEndpoint))
                        {
                            baseUri = NavigationHelper.AppendPathToSingleUri(
                                new Uri(serviceEndpoint),
                                reader.GetAttribute(Constants.ContainerNameElement));
                        }
                        else
                        {
                            baseUri = new Uri(reader.GetAttribute(Constants.ContainerNameElement));
                        }

                        await reader.ReadStartElementAsync().ConfigureAwait(false);

                        while (await reader.IsStartElementAsync().ConfigureAwait(false))
                        {
                            token.ThrowIfCancellationRequested();

                            if (reader.IsEmptyElement)
                            {
                                await reader.SkipAsync().ConfigureAwait(false);
                            }
                            else
                            {
                                switch (reader.Name)
                                {
                                case Constants.DelimiterElement:
                                    await reader.ReadElementContentAsStringAsync().ConfigureAwait(false);

                                    break;

                                case Constants.MarkerElement:
                                    await reader.ReadElementContentAsStringAsync().ConfigureAwait(false);

                                    break;

                                case Constants.NextMarkerElement:
                                    nextMarker = await reader.ReadElementContentAsStringAsync().ConfigureAwait(false);

                                    break;

                                case Constants.MaxResultsElement:
                                    await reader.ReadElementContentAsInt32Async().ConfigureAwait(false);

                                    break;

                                case Constants.PrefixElement:
                                    await reader.ReadElementContentAsStringAsync().ConfigureAwait(false);

                                    break;

                                case Constants.BlobsElement:
                                    await reader.ReadStartElementAsync().ConfigureAwait(false);

                                    while (await reader.IsStartElementAsync().ConfigureAwait(false))
                                    {
                                        switch (reader.Name)
                                        {
                                        case Constants.BlobElement:
                                            entries.Add(await ParseBlobEntryAsync(reader, baseUri, token).ConfigureAwait(false));
                                            break;

                                        case Constants.BlobPrefixElement:
                                            entries.Add(await ParseBlobPrefixEntryAsync(reader, token).ConfigureAwait(false));
                                            break;
                                        }
                                    }

                                    await reader.ReadEndElementAsync().ConfigureAwait(false);

                                    break;

                                default:
                                    await reader.SkipAsync().ConfigureAwait(false);

                                    break;
                                }
                            }
                        }

                        await reader.ReadEndElementAsync().ConfigureAwait(false);
                    }
                }

                return(new ListBlobsResponse {
                    Blobs = entries, NextMarker = nextMarker
                });
            }
        }
        public async Task RequestResultErrorCode()
        {
            Uri                baseAddressUri = new Uri(TestBase.TargetTenantConfig.BlobServiceEndpoint);
            CloudBlobClient    client         = new CloudBlobClient(baseAddressUri, TestBase.StorageCredentials);
            CloudBlobContainer container      = client.GetContainerReference(Guid.NewGuid().ToString("N"));

            byte[] buffer     = TestBase.GetRandomBuffer(4 * 1024 * 1024);
            MD5    md5        = MD5.Create();
            string contentMD5 = Convert.ToBase64String(md5.ComputeHash(buffer));

            try
            {
                RequestResult     requestResult;
                XmlWriterSettings settings;
                StringBuilder     sb;
                container.Create();
                CloudBlockBlob blob   = container.GetBlockBlobReference("blob1");
                List <string>  blocks = new List <string>();
                for (int i = 0; i < 2; i++)
                {
                    blocks.Add(Convert.ToBase64String(Guid.NewGuid().ToByteArray()));
                }

                // Verify the ErrorCode property is set and that it is serialized correctly
                using (MemoryStream memoryStream = new MemoryStream(buffer))
                {
                    memoryStream.Seek(0, SeekOrigin.Begin);
                    blob.PutBlock(blocks[0], memoryStream, contentMD5);

                    int offset = buffer.Length - 1024;
                    memoryStream.Seek(offset, SeekOrigin.Begin);
                    StorageException e = TestHelper.ExpectedException <StorageException>(
                        () => blob.PutBlock(blocks[1], memoryStream, contentMD5),
                        "Invalid MD5 should fail with mismatch");

                    Assert.AreEqual(e.RequestInformation.ErrorCode, StorageErrorCodeStrings.Md5Mismatch);

                    requestResult   = new RequestResult();
                    settings        = new XmlWriterSettings();
                    settings.Indent = true;
                    sb = new StringBuilder();
                    using (XmlWriter writer = XmlWriter.Create(sb, settings))
                    {
                        e.RequestInformation.WriteXml(writer);
                    }

                    using (XmlReader reader = XMLReaderExtensions.CreateAsAsync(new MemoryStream(Encoding.Unicode.GetBytes(sb.ToString()))))
                    {
                        await requestResult.ReadXmlAsync(reader);
                    }

                    // ExtendedErrorInformation.ErrorCode will be depricated, but it should still match on a non HEAD request
                    Assert.AreEqual(e.RequestInformation.ErrorCode, requestResult.ErrorCode);
                    Assert.AreEqual(e.RequestInformation.ExtendedErrorInformation.ErrorCode, requestResult.ErrorCode);
                }

                // Verify the ErrorCode property is set on a HEAD request
                CloudAppendBlob blob2 = container.GetAppendBlobReference("blob2");
                blob2.CreateOrReplace();
                StorageException e2 = TestHelper.ExpectedException <StorageException>(
                    () => blob2.FetchAttributes(AccessCondition.GenerateIfMatchCondition("\"garbage\"")), // must supply our own quotes for a valid etag
                    "Mismatched etag should fail");
                Assert.AreEqual(e2.RequestInformation.ErrorCode, StorageErrorCodeStrings.ConditionNotMet);

                // Verify the ErrorCode property is not set on a successful request and that it is serialized correctly
                OperationContext ctx = new OperationContext();
                blob2.FetchAttributes(operationContext: ctx);
                Assert.AreEqual(ctx.RequestResults[0].ErrorCode, null);
                requestResult   = new RequestResult();
                settings        = new XmlWriterSettings();
                settings.Indent = true;
                sb = new StringBuilder();
                using (XmlWriter writer = XmlWriter.Create(sb, settings))
                {
                    ctx.RequestResults[0].WriteXml(writer);
                }

                using (XmlReader reader = XMLReaderExtensions.CreateAsAsync(new MemoryStream(Encoding.Unicode.GetBytes(sb.ToString()))))
                {
                    await requestResult.ReadXmlAsync(reader);
                }

                Assert.AreEqual(ctx.RequestResults[0].ErrorCode, requestResult.ErrorCode);
            }
            finally
            {
                container.DeleteIfExists();
            }
        }
        public async Task QueueContinuationTokenVerifySerializer()
        {
            XmlSerializer serializer = new XmlSerializer(typeof(QueueContinuationToken));

            XmlWriterSettings settings = new XmlWriterSettings();

            settings.Indent = true;

            StringReader reader;
            string       tokenxml;

            QueueContinuationToken writeToken = new QueueContinuationToken
            {
                NextMarker     = Guid.NewGuid().ToString(),
                TargetLocation = StorageLocation.Primary
            };

            QueueContinuationToken readToken = null;

            // Write with XmlSerializer
            using (StringWriter writer = new StringWriter())
            {
                serializer.Serialize(writer, writeToken);
                tokenxml = writer.ToString();
            }

            // Read with XmlSerializer
            reader    = new StringReader(tokenxml);
            readToken = (QueueContinuationToken)serializer.Deserialize(reader);
            Assert.AreEqual(writeToken.NextMarker, readToken.NextMarker);

            // Read with token.ReadXml()
            using (XmlReader xmlReader = XMLReaderExtensions.CreateAsAsync(new MemoryStream(Encoding.Unicode.GetBytes(tokenxml))))
            {
                readToken = new QueueContinuationToken();
                await readToken.ReadXmlAsync(xmlReader);
            }
            Assert.AreEqual(writeToken.NextMarker, readToken.NextMarker);

            // Read with token.ReadXml()
            using (XmlReader xmlReader = XMLReaderExtensions.CreateAsAsync(new MemoryStream(Encoding.Unicode.GetBytes(tokenxml))))
            {
                readToken = new QueueContinuationToken();
                await readToken.ReadXmlAsync(xmlReader);
            }

            // Write with token.WriteXml
            StringBuilder sb = new StringBuilder();

            using (XmlWriter writer = XmlWriter.Create(sb, settings))
            {
                writeToken.WriteXml(writer);
            }

            // Read with XmlSerializer
            reader    = new StringReader(sb.ToString());
            readToken = (QueueContinuationToken)serializer.Deserialize(reader);
            Assert.AreEqual(writeToken.NextMarker, readToken.NextMarker);

            // Read with token.ReadXml()
            using (XmlReader xmlReader = XMLReaderExtensions.CreateAsAsync(new MemoryStream(Encoding.Unicode.GetBytes(sb.ToString()))))
            {
                readToken = new QueueContinuationToken();
                await readToken.ReadXmlAsync(xmlReader);
            }
            Assert.AreEqual(writeToken.NextMarker, readToken.NextMarker);
        }
        /// <summary>
        /// Parses the response XML for a file listing operation.
        /// </summary>
        /// <returns>An enumerable collection of objects that implement <see cref="IListFileEntry"/>.</returns>
        internal static async Task <ListFilesAndDirectoriesResponse> ParseAsync(Stream stream, CancellationToken token)
        {
            using (XmlReader reader = XMLReaderExtensions.CreateAsAsync(stream))
            {
                token.ThrowIfCancellationRequested();

                List <IListFileEntry> entries = new List <IListFileEntry>();
                string nextMarker             = default(string);

                if (await reader.ReadToFollowingAsync(Constants.EnumerationResultsElement).ConfigureAwait(false))
                {
                    if (reader.IsEmptyElement)
                    {
                        await reader.SkipAsync().ConfigureAwait(false);
                    }
                    else
                    {
                        Uri baseUri = new Uri(reader.GetAttribute(Constants.ServiceEndpointElement));
                        baseUri = NavigationHelper.AppendPathToSingleUri(baseUri, reader.GetAttribute(Constants.ShareNameElement));
                        baseUri = NavigationHelper.AppendPathToSingleUri(baseUri, reader.GetAttribute(Constants.DirectoryPathElement));

                        await reader.ReadStartElementAsync().ConfigureAwait(false);

                        while (await reader.IsStartElementAsync().ConfigureAwait(false))
                        {
                            token.ThrowIfCancellationRequested();

                            if (reader.IsEmptyElement)
                            {
                                await reader.SkipAsync().ConfigureAwait(false);
                            }
                            else
                            {
                                switch (reader.Name)
                                {
                                case Constants.MarkerElement:
                                    await reader.ReadElementContentAsStringAsync().ConfigureAwait(false);

                                    break;

                                case Constants.NextMarkerElement:
                                    nextMarker = await reader.ReadElementContentAsStringAsync().ConfigureAwait(false);

                                    break;

                                case Constants.MaxResultsElement:
                                    await reader.ReadElementContentAsInt32Async().ConfigureAwait(false);

                                    break;

                                case Constants.EntriesElement:
                                    await reader.ReadStartElementAsync().ConfigureAwait(false);

                                    while (await reader.IsStartElementAsync().ConfigureAwait(false))
                                    {
                                        switch (reader.Name)
                                        {
                                        case Constants.FileElement:
                                            entries.Add(await ParseFileEntryAsync(reader, baseUri, token).ConfigureAwait(false));
                                            break;

                                        case Constants.FileDirectoryElement:
                                            entries.Add(await ParseFileDirectoryEntryAsync(reader, baseUri, token).ConfigureAwait(false));
                                            break;
                                        }
                                    }

                                    await reader.ReadEndElementAsync().ConfigureAwait(false);

                                    break;

                                default:
                                    await reader.SkipAsync().ConfigureAwait(false);

                                    break;
                                }
                            }
                        }

                        await reader.ReadEndElementAsync().ConfigureAwait(false);
                    }
                }

                return(new ListFilesAndDirectoriesResponse {
                    Files = entries, NextMarker = nextMarker
                });
            }
        }
 /// <summary>
 /// Initializes a new instance of the AccessPolicyResponseBase class.
 /// </summary>
 /// <param name="stream">The stream to be parsed.</param>
 protected AccessPolicyResponseBase(Stream stream)
 {
     this.reader            = XMLReaderExtensions.CreateAsAsync(stream);
     this.AccessIdentifiers = this.ParseAsync();
 }
示例#16
0
        /// <summary>
        /// Asynchronously parses the XML response returned by an operation to retrieve a list of blocks.
        /// </summary>
        /// <param name="stream">The stream containing the XML response.</param>
        /// <param name="token">The cancellation token.</param>
        /// <returns>The list of <see cref="ListBlockItem"/> objects.</returns>
        internal static async Task <IEnumerable <ListBlockItem> > ParseAsync(Stream stream, CancellationToken token)
        {
            token.ThrowIfCancellationRequested();
            List <ListBlockItem> blocks = new List <ListBlockItem>();

            using (XmlReader reader = XMLReaderExtensions.CreateAsAsync(stream))
            {
                token.ThrowIfCancellationRequested();
                if (await reader.ReadToFollowingAsync(Constants.BlockListElement).ConfigureAwait(false))
                {
                    if (reader.IsEmptyElement)
                    {
                        await reader.SkipAsync().ConfigureAwait(false);
                    }
                    else
                    {
                        await reader.ReadStartElementAsync().ConfigureAwait(false);

                        while (await reader.IsStartElementAsync().ConfigureAwait(false))
                        {
                            token.ThrowIfCancellationRequested();
                            if (reader.IsEmptyElement)
                            {
                                await reader.SkipAsync().ConfigureAwait(false);
                            }
                            else
                            {
                                switch (reader.Name)
                                {
                                case Constants.CommittedBlocksElement:
                                    await reader.ReadStartElementAsync().ConfigureAwait(false);

                                    while (await reader.IsStartElementAsync(Constants.BlockElement).ConfigureAwait(false))
                                    {
                                        token.ThrowIfCancellationRequested();
                                        blocks.Add(await ParseBlockItemAsync(true, reader, token).ConfigureAwait(false));
                                    }

                                    await reader.ReadEndElementAsync().ConfigureAwait(false);

                                    break;

                                case Constants.UncommittedBlocksElement:
                                    await reader.ReadStartElementAsync().ConfigureAwait(false);

                                    while (await reader.IsStartElementAsync(Constants.BlockElement).ConfigureAwait(false))
                                    {
                                        token.ThrowIfCancellationRequested();
                                        blocks.Add(await ParseBlockItemAsync(false, reader, token).ConfigureAwait(false));
                                    }

                                    await reader.ReadEndElementAsync().ConfigureAwait(false);

                                    break;

                                default:
                                    await reader.SkipAsync().ConfigureAwait(false);

                                    break;
                                }
                            }
                        }

                        await reader.ReadEndElementAsync().ConfigureAwait(false);
                    }
                }
                return(blocks);
            }
        }
        public async Task RequestResultVerifyXml()
        {
            Uri                baseAddressUri = new Uri(TestBase.TargetTenantConfig.BlobServiceEndpoint);
            CloudBlobClient    blobClient     = new CloudBlobClient(baseAddressUri, TestBase.StorageCredentials);
            CloudBlobContainer container      = blobClient.GetContainerReference(Guid.NewGuid().ToString("N"));

            OperationContext opContext = new OperationContext();

            Assert.IsNull(opContext.LastResult);
            container.Exists(null, opContext);
            Assert.IsNotNull(opContext.LastResult);

            // We do not have precision at milliseconds level. Hence, we need
            // to recreate the start DateTime to be able to compare it later.
            DateTime start = opContext.LastResult.StartTime;

            start = new DateTime(start.Year, start.Month, start.Day, start.Hour, start.Minute, start.Second);

            DateTime end = opContext.LastResult.EndTime;

            end = new DateTime(end.Year, end.Month, end.Day, end.Hour, end.Minute, end.Second);

            XmlWriterSettings settings = new XmlWriterSettings();

            settings.Indent = true;
            StringBuilder sb = new StringBuilder();

            using (XmlWriter writer = XmlWriter.Create(sb, settings))
            {
                opContext.LastResult.WriteXml(writer);
            }

            RequestResult retrResult = new RequestResult();

            using (XmlReader reader = XMLReaderExtensions.CreateAsAsync(new MemoryStream(Encoding.Unicode.GetBytes(sb.ToString()))))
            {
                await retrResult.ReadXmlAsync(reader);
            }

            Assert.AreEqual(opContext.LastResult.RequestDate, retrResult.RequestDate);
            Assert.AreEqual(opContext.LastResult.ServiceRequestID, retrResult.ServiceRequestID);
            Assert.AreEqual(start, retrResult.StartTime);
            Assert.AreEqual(end, retrResult.EndTime);
            Assert.AreEqual(opContext.LastResult.HttpStatusCode, retrResult.HttpStatusCode);
            Assert.AreEqual(opContext.LastResult.HttpStatusMessage, retrResult.HttpStatusMessage);
            Assert.AreEqual(opContext.LastResult.ContentMd5, retrResult.ContentMd5);
            Assert.AreEqual(opContext.LastResult.Etag, retrResult.Etag);

            // Now test with no indentation
            sb = new StringBuilder();
            using (XmlWriter writer = XmlWriter.Create(sb))
            {
                opContext.LastResult.WriteXml(writer);
            }

            retrResult = new RequestResult();
            using (XmlReader reader = XMLReaderExtensions.CreateAsAsync(new MemoryStream(Encoding.Unicode.GetBytes(sb.ToString()))))
            {
                await retrResult.ReadXmlAsync(reader);
            }

            Assert.AreEqual(opContext.LastResult.RequestDate, retrResult.RequestDate);
            Assert.AreEqual(opContext.LastResult.ServiceRequestID, retrResult.ServiceRequestID);
            Assert.AreEqual(start, retrResult.StartTime);
            Assert.AreEqual(end, retrResult.EndTime);
            Assert.AreEqual(opContext.LastResult.HttpStatusCode, retrResult.HttpStatusCode);
            Assert.AreEqual(opContext.LastResult.HttpStatusMessage, retrResult.HttpStatusMessage);
            Assert.AreEqual(opContext.LastResult.ContentMd5, retrResult.ContentMd5);
            Assert.AreEqual(opContext.LastResult.Etag, retrResult.Etag);
        }