public void CloudFileDirectoryAbsoluteUriAppended() { CloudFileClient client = GenerateCloudFileClient(); string name = GetRandomShareName(); CloudFileShare share = client.GetShareReference(name); CloudFileDirectory dir = share.GetRootDirectoryReference().GetDirectoryReference(share.Uri.AbsoluteUri); Assert.AreEqual(NavigationHelper.AppendPathToSingleUri(share.Uri, share.Uri.AbsoluteUri), dir.Uri); Assert.AreEqual(new Uri(share.Uri + "/" + share.Uri.AbsoluteUri), dir.Uri); dir = share.GetRootDirectoryReference().GetDirectoryReference(share.Uri.AbsoluteUri + "/TopDir1"); Assert.AreEqual(NavigationHelper.AppendPathToSingleUri(share.Uri, share.Uri.AbsoluteUri + "/TopDir1"), dir.Uri); }
/// <summary> /// Parses a queue entry in a queue listing response. /// </summary> /// <returns>Queue listing entry</returns> private static async Task <QueueEntry> ParseQueueEntryAsync(XmlReader reader, Uri baseUri, CancellationToken token) { token.ThrowIfCancellationRequested(); string name = null; IDictionary <string, string> metadata = null; 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.NameElement: name = await reader.ReadElementContentAsStringAsync().ConfigureAwait(false); break; case Constants.MetadataElement: metadata = await Response.ParseMetadataAsync(reader).ConfigureAwait(false); break; default: await reader.SkipAsync().ConfigureAwait(false); break; } } } await reader.ReadEndElementAsync().ConfigureAwait(false); return(new QueueEntry( name, NavigationHelper.AppendPathToSingleUri(baseUri, name), metadata ?? new Dictionary <string, string>() )); }
public void CloudBlobDirectoryAbsoluteUriAppended() { foreach (String delimiter in Delimiters) { CloudBlobClient client = GenerateCloudBlobClient(); client.DefaultDelimiter = delimiter; string name = GetRandomContainerName(); CloudBlobContainer container = client.GetContainerReference(name); CloudBlobDirectory dir = container.GetDirectoryReference(container.Uri.AbsoluteUri); Assert.AreEqual(NavigationHelper.AppendPathToSingleUri(container.Uri, container.Uri.AbsoluteUri + delimiter), dir.Uri); Assert.AreEqual(new Uri(container.Uri + "/" + container.Uri.AbsoluteUri + delimiter), dir.Uri); dir = container.GetDirectoryReference(container.Uri.AbsoluteUri + "/" + "TopDir1" + delimiter); Assert.AreEqual(NavigationHelper.AppendPathToSingleUri(container.Uri, container.Uri.AbsoluteUri + "/" + "TopDir1" + delimiter), dir.Uri); } }
/// <summary> /// Parses a queue entry in a queue listing response. /// </summary> /// <returns>Queue listing entry</returns> private QueueEntry ParseQueueEntry(Uri baseUri) { string name = null; IDictionary <string, string> metadata = null; this.reader.ReadStartElement(); while (this.reader.IsStartElement()) { if (this.reader.IsEmptyElement) { this.reader.Skip(); } else { switch (reader.Name) { case Constants.NameElement: name = reader.ReadElementContentAsString(); break; case Constants.MetadataElement: metadata = Response.ParseMetadata(this.reader); break; default: this.reader.Skip(); break; } } } this.reader.ReadEndElement(); if (metadata == null) { metadata = new Dictionary <string, string>(); } return(new QueueEntry(name, NavigationHelper.AppendPathToSingleUri(baseUri, name), metadata)); }
internal static Tuple <HttpWebRequest, Stream> BuildRequestForTableBatchOperation(Uri uri, UriQueryBuilder builder, IBufferManager bufferManager, int?timeout, string tableName, TableBatchOperation batch, bool useVersionHeader, OperationContext ctx, TableRequestOptions options) { HttpWebRequest msg = BuildRequestCore(NavigationHelper.AppendPathToSingleUri(uri, "$batch"), builder, "POST", timeout, useVersionHeader, ctx); TablePayloadFormat payloadFormat = options.PayloadFormat.Value; Logger.LogInformational(ctx, SR.PayloadFormat, payloadFormat); MultiBufferMemoryStream batchContentStream = new MultiBufferMemoryStream(bufferManager); using (StreamWriter contentWriter = new StreamWriter(new NonCloseableStream(batchContentStream))) { string batchID = Guid.NewGuid().ToString(); string changesetID = Guid.NewGuid().ToString(); msg.Headers.Add(Constants.HeaderConstants.DataServiceVersion, Constants.HeaderConstants.DataServiceVersionValue); msg.ContentType = Constants.BatchBoundaryMarker + batchID; string batchSeparator = Constants.BatchSeparator + batchID; string changesetSeparator = Constants.ChangesetSeparator + changesetID; string acceptHeader = "Accept: "; switch (payloadFormat) { case TablePayloadFormat.Json: acceptHeader = acceptHeader + Constants.JsonLightAcceptHeaderValue; break; case TablePayloadFormat.JsonFullMetadata: acceptHeader = acceptHeader + Constants.JsonFullMetadataAcceptHeaderValue; break; case TablePayloadFormat.JsonNoMetadata: acceptHeader = acceptHeader + Constants.JsonNoMetadataAcceptHeaderValue; break; } contentWriter.WriteLine(batchSeparator); bool isQuery = batch.Count == 1 && batch[0].OperationType == TableOperationType.Retrieve; // Query operations should not be inside changeset in payload if (!isQuery) { // Start Operation contentWriter.WriteLine(Constants.ChangesetBoundaryMarker + changesetID); contentWriter.WriteLine(); } foreach (TableOperation operation in batch) { string httpMethod = operation.HttpMethod; if (operation.OperationType == TableOperationType.Merge || operation.OperationType == TableOperationType.InsertOrMerge) { options.AssertNoEncryptionPolicyOrStrictMode(); httpMethod = "MERGE"; } if (operation.OperationType == TableOperationType.RotateEncryptionKey) { httpMethod = "MERGE"; } if (!isQuery) { contentWriter.WriteLine(changesetSeparator); } contentWriter.WriteLine(Constants.ContentTypeApplicationHttp); contentWriter.WriteLine(Constants.ContentTransferEncodingBinary); contentWriter.WriteLine(); string tableURI = Uri.EscapeUriString(operation.GenerateRequestURI(uri, tableName).ToString()); // "EscapeUriString" is almost exactly what we need, except that it contains special logic for // the percent sign, which results in an off-by-one error in the number of times "%" is encoded. // This corrects for that. tableURI = tableURI.Replace(@"%25", @"%"); contentWriter.WriteLine(httpMethod + " " + tableURI + " " + Constants.HTTP1_1); contentWriter.WriteLine(acceptHeader); contentWriter.WriteLine(Constants.ContentTypeApplicationJson); if (operation.OperationType == TableOperationType.Insert) { contentWriter.WriteLine(Constants.HeaderConstants.Prefer + @": " + (operation.EchoContent ? Constants.HeaderConstants.PreferReturnContent : Constants.HeaderConstants.PreferReturnNoContent)); } contentWriter.WriteLine(Constants.HeaderConstants.DataServiceVersion + ": " + Constants.HeaderConstants.DataServiceVersionValue); // etag if (operation.OperationType == TableOperationType.Delete || operation.OperationType == TableOperationType.Replace || operation.OperationType == TableOperationType.Merge || operation.OperationType == TableOperationType.RotateEncryptionKey) { contentWriter.WriteLine(Constants.HeaderConstants.IfMatch + @": " + operation.ETag); } contentWriter.WriteLine(); if (operation.OperationType != TableOperationType.Delete && operation.OperationType != TableOperationType.Retrieve) { using (JsonTextWriter jsonWriter = new JsonTextWriter(contentWriter)) { jsonWriter.CloseOutput = false; WriteEntityContent(operation, ctx, options, jsonWriter); } contentWriter.WriteLine(); } } if (!isQuery) { contentWriter.WriteLine(changesetSeparator + "--"); } contentWriter.WriteLine(batchSeparator + "--"); } batchContentStream.Seek(0, SeekOrigin.Begin); msg.ContentLength = batchContentStream.Length; return(new Tuple <HttpWebRequest, Stream>(msg, batchContentStream)); }
/// <summary> /// Reads a container entry completely including its properties and metadata. /// </summary> /// <returns>Container listing entry</returns> private BlobContainerEntry ParseContainerEntry(Uri baseUri) { string name = null; IDictionary <string, string> metadata = null; BlobContainerProperties containerProperties = new BlobContainerProperties(); containerProperties.PublicAccess = BlobContainerPublicAccessType.Off; this.reader.ReadStartElement(); while (this.reader.IsStartElement()) { if (this.reader.IsEmptyElement) { this.reader.Skip(); } else { switch (this.reader.Name) { case Constants.NameElement: name = this.reader.ReadElementContentAsString(); break; case Constants.PropertiesElement: this.reader.ReadStartElement(); while (this.reader.IsStartElement()) { if (this.reader.IsEmptyElement) { this.reader.Skip(); } else { switch (this.reader.Name) { case Constants.LastModifiedElement: containerProperties.LastModified = reader.ReadElementContentAsString().ToUTCTime(); break; case Constants.EtagElement: containerProperties.ETag = reader.ReadElementContentAsString(); break; case Constants.HasImmutabilityPolicyElement: containerProperties.HasImmutabilityPolicy = reader.ReadElementContentAsBoolean(); break; case Constants.HasLegalHoldElement: containerProperties.HasLegalHold = reader.ReadElementContentAsBoolean(); break; case Constants.LeaseStatusElement: containerProperties.LeaseStatus = BlobHttpResponseParsers.GetLeaseStatus(reader.ReadElementContentAsString()); break; case Constants.LeaseStateElement: containerProperties.LeaseState = BlobHttpResponseParsers.GetLeaseState(reader.ReadElementContentAsString()); break; case Constants.LeaseDurationElement: containerProperties.LeaseDuration = BlobHttpResponseParsers.GetLeaseDuration(reader.ReadElementContentAsString()); break; case Constants.PublicAccessElement: containerProperties.PublicAccess = ContainerHttpResponseParsers.GetContainerAcl(reader.ReadElementContentAsString()); break; default: reader.Skip(); break; } } } this.reader.ReadEndElement(); break; case Constants.MetadataElement: metadata = Response.ParseMetadata(this.reader); break; default: reader.Skip(); break; } } } this.reader.ReadEndElement(); if (metadata == null) { metadata = new Dictionary <string, string>(); } return(new BlobContainerEntry { Properties = containerProperties, Name = name, Uri = NavigationHelper.AppendPathToSingleUri(baseUri, name), Metadata = metadata, }); }
internal static RESTCommand <NullType> SetAclImpl(TablePermissions permissions, CloudTableClient client, CloudTable table, TableRequestOptions requestOptions) { RESTCommand <NullType> rESTCommand = new RESTCommand <NullType>(client.Credentials, client.StorageUri); RESTCommandGeneratorUtils.ApplyTableRequestOptionsToStorageCommand(requestOptions, rESTCommand); rESTCommand.HttpClient = client.HttpClient; rESTCommand.BuildRequest = ((RESTCommand <NullType> cmd, Uri uri, UriQueryBuilder uriBuilder, HttpContent httpContent, int?timeout, OperationContext ctx) => TableRequestMessageFactory.BuildStorageRequestMessageForTablePermissions(NavigationHelper.AppendPathToSingleUri(uri, table.Name), uriBuilder, timeout, HttpMethod.Put, permissions, SharedKeyCanonicalizer.Instance, client.Credentials, ctx, requestOptions)); rESTCommand.ParseErrorAsync = StorageExtendedErrorInformationRestHelper.ReadExtendedErrorInfoFromStreamAsync; rESTCommand.PreProcessResponse = ((RESTCommand <NullType> cmd, HttpResponseMessage resp, Exception ex, OperationContext ctx) => HttpResponseParsers.ProcessExpectedStatusCodeNoException(HttpStatusCode.NoContent, resp, NullType.Value, cmd, ex)); return(rESTCommand); }
/// <summary> /// Parses the response XML for a blob listing operation. /// </summary> /// <returns>An enumerable collection of objects that implement <see cref="IListBlobEntry"/>.</returns> protected override IEnumerable <IListBlobEntry> ParseXml() { if (this.reader.ReadToFollowing(Constants.EnumerationResultsElement)) { if (this.reader.IsEmptyElement) { this.reader.Skip(); } else { Uri baseUri = NavigationHelper.AppendPathToSingleUri( new Uri(this.reader.GetAttribute(Constants.ServiceEndpointElement)), this.reader.GetAttribute(Constants.ContainerNameElement)); this.reader.ReadStartElement(); while (this.reader.IsStartElement()) { if (this.reader.IsEmptyElement) { this.reader.Skip(); } else { switch (this.reader.Name) { case Constants.DelimiterElement: this.delimiter = reader.ReadElementContentAsString(); this.delimiterConsumable = true; yield return(null); break; case Constants.MarkerElement: this.marker = reader.ReadElementContentAsString(); this.markerConsumable = true; yield return(null); break; case Constants.NextMarkerElement: this.nextMarker = reader.ReadElementContentAsString(); this.nextMarkerConsumable = true; yield return(null); break; case Constants.MaxResultsElement: this.maxResults = reader.ReadElementContentAsInt(); this.maxResultsConsumable = true; yield return(null); break; case Constants.PrefixElement: this.prefix = reader.ReadElementContentAsString(); this.prefixConsumable = true; yield return(null); break; case Constants.BlobsElement: this.reader.ReadStartElement(); while (this.reader.IsStartElement()) { switch (this.reader.Name) { case Constants.BlobElement: yield return(this.ParseBlobEntry(baseUri)); break; case Constants.BlobPrefixElement: yield return(this.ParseBlobPrefixEntry()); break; } } this.reader.ReadEndElement(); this.allObjectsParsed = true; break; default: reader.Skip(); break; } } } this.reader.ReadEndElement(); } } }
/// <summary> /// Reads a container entry completely including its properties and metadata. /// </summary> /// <returns>Container listing entry</returns> private static async Task <BlobContainerEntry> ParseContainerEntryAsync(XmlReader reader, Uri baseUri, CancellationToken token) { token.ThrowIfCancellationRequested(); string name = null; IDictionary <string, string> metadata = null; BlobContainerProperties containerProperties = new BlobContainerProperties(); containerProperties.PublicAccess = BlobContainerPublicAccessType.Off; 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.NameElement: name = await reader.ReadElementContentAsStringAsync().ConfigureAwait(false); break; case Constants.PropertiesElement: 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.LastModifiedElement: containerProperties.LastModified = (await reader.ReadElementContentAsStringAsync().ConfigureAwait(false)).ToUTCTime(); break; case Constants.EtagElement: containerProperties.ETag = await reader.ReadElementContentAsStringAsync().ConfigureAwait(false); break; case Constants.HasImmutabilityPolicyElement: containerProperties.HasImmutabilityPolicy = await reader.ReadElementContentAsBooleanAsync().ConfigureAwait(false); break; case Constants.HasLegalHoldElement: containerProperties.HasLegalHold = await reader.ReadElementContentAsBooleanAsync().ConfigureAwait(false); break; case Constants.LeaseStatusElement: containerProperties.LeaseStatus = BlobHttpResponseParsers.GetLeaseStatus(await reader.ReadElementContentAsStringAsync().ConfigureAwait(false)); break; case Constants.LeaseStateElement: containerProperties.LeaseState = BlobHttpResponseParsers.GetLeaseState(await reader.ReadElementContentAsStringAsync().ConfigureAwait(false)); break; case Constants.LeaseDurationElement: containerProperties.LeaseDuration = BlobHttpResponseParsers.GetLeaseDuration(await reader.ReadElementContentAsStringAsync().ConfigureAwait(false)); break; case Constants.PublicAccessElement: containerProperties.PublicAccess = ContainerHttpResponseParsers.GetContainerAcl(await reader.ReadElementContentAsStringAsync().ConfigureAwait(false)); break; default: await reader.SkipAsync().ConfigureAwait(false); break; } } } await reader.ReadEndElementAsync().ConfigureAwait(false); break; case Constants.MetadataElement: metadata = await Response.ParseMetadataAsync(reader).ConfigureAwait(false); break; default: await reader.SkipAsync().ConfigureAwait(false); break; } } } await reader.ReadEndElementAsync().ConfigureAwait(false); if (metadata == null) { metadata = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase); } return(new BlobContainerEntry { Properties = containerProperties, Name = name, Uri = NavigationHelper.AppendPathToSingleUri(baseUri, name), Metadata = metadata, }); }
private static async Task <IListBlobEntry> ParseBlobEntryAsync(XmlReader reader, Uri baseUri, CancellationToken token) { token.ThrowIfCancellationRequested(); BlobAttributes blob = new BlobAttributes(); string name = null; // copy blob attribute strings string copyId = null; string copyStatus = null; string copyCompletionTime = null; string copyProgress = null; string copySource = null; string copyStatusDescription = null; string copyDestinationSnapshotTime = null; string blobTierString = null; bool? blobTierInferred = null; string rehydrationStatusString = null; DateTimeOffset?blobTierLastModifiedTime = null; 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.NameElement: name = await reader.ReadElementContentAsStringAsync().ConfigureAwait(false); break; case Constants.SnapshotElement: blob.SnapshotTime = (await reader.ReadElementContentAsStringAsync().ConfigureAwait(false)).ToUTCTime(); break; case Constants.DeletedElement: blob.IsDeleted = BlobHttpResponseParsers.GetDeletionStatus(await reader.ReadElementContentAsStringAsync().ConfigureAwait(false)); break; case Constants.PropertiesElement: 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.CreationTimeElement: blob.Properties.Created = (await reader.ReadElementContentAsStringAsync().ConfigureAwait(false)).ToUTCTime(); break; case Constants.LastModifiedElement: blob.Properties.LastModified = (await reader.ReadElementContentAsStringAsync().ConfigureAwait(false)).ToUTCTime(); break; case Constants.EtagElement: blob.Properties.ETag = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", await reader.ReadElementContentAsStringAsync().ConfigureAwait(false)); break; case Constants.ContentLengthElement: blob.Properties.Length = await reader.ReadElementContentAsInt64Async().ConfigureAwait(false); break; case Constants.CacheControlElement: blob.Properties.CacheControl = await reader.ReadElementContentAsStringAsync().ConfigureAwait(false); break; case Constants.ContentTypeElement: blob.Properties.ContentType = await reader.ReadElementContentAsStringAsync().ConfigureAwait(false); break; case Constants.HeaderConstants.ContentDispositionResponseHeader: blob.Properties.ContentDisposition = await reader.ReadElementContentAsStringAsync().ConfigureAwait(false); break; case Constants.ContentEncodingElement: blob.Properties.ContentEncoding = await reader.ReadElementContentAsStringAsync().ConfigureAwait(false); break; case Constants.ContentLanguageElement: blob.Properties.ContentLanguage = await reader.ReadElementContentAsStringAsync().ConfigureAwait(false); break; case Constants.ContentMD5Element: blob.Properties.ContentMD5 = await reader.ReadElementContentAsStringAsync().ConfigureAwait(false); break; case Constants.BlobTypeElement: string blobTypeString = await reader.ReadElementContentAsStringAsync().ConfigureAwait(false); switch (blobTypeString) { case Constants.BlockBlobValue: blob.Properties.BlobType = BlobType.BlockBlob; break; case Constants.PageBlobValue: blob.Properties.BlobType = BlobType.PageBlob; break; case Constants.AppendBlobValue: blob.Properties.BlobType = BlobType.AppendBlob; break; } break; case Constants.LeaseStatusElement: blob.Properties.LeaseStatus = BlobHttpResponseParsers.GetLeaseStatus(await reader.ReadElementContentAsStringAsync().ConfigureAwait(false)); break; case Constants.LeaseStateElement: blob.Properties.LeaseState = BlobHttpResponseParsers.GetLeaseState(await reader.ReadElementContentAsStringAsync().ConfigureAwait(false)); break; case Constants.LeaseDurationElement: blob.Properties.LeaseDuration = BlobHttpResponseParsers.GetLeaseDuration(await reader.ReadElementContentAsStringAsync().ConfigureAwait(false)); break; case Constants.CopyIdElement: copyId = await reader.ReadElementContentAsStringAsync().ConfigureAwait(false); break; case Constants.CopyCompletionTimeElement: copyCompletionTime = await reader.ReadElementContentAsStringAsync().ConfigureAwait(false); break; case Constants.CopyStatusElement: copyStatus = await reader.ReadElementContentAsStringAsync().ConfigureAwait(false); break; case Constants.CopyProgressElement: copyProgress = await reader.ReadElementContentAsStringAsync().ConfigureAwait(false); break; case Constants.CopySourceElement: copySource = await reader.ReadElementContentAsStringAsync().ConfigureAwait(false); break; case Constants.CopyStatusDescriptionElement: copyStatusDescription = await reader.ReadElementContentAsStringAsync().ConfigureAwait(false); break; case Constants.ServerEncryptionElement: blob.Properties.IsServerEncrypted = BlobHttpResponseParsers.GetServerEncrypted(await reader.ReadElementContentAsStringAsync().ConfigureAwait(false)); break; case Constants.IncrementalCopy: blob.Properties.IsIncrementalCopy = BlobHttpResponseParsers.GetIncrementalCopyStatus(await reader.ReadElementContentAsStringAsync().ConfigureAwait(false)); break; case Constants.CopyDestinationSnapshotElement: copyDestinationSnapshotTime = await reader.ReadElementContentAsStringAsync().ConfigureAwait(false); break; case Constants.AccessTierElement: blobTierString = await reader.ReadElementContentAsStringAsync().ConfigureAwait(false); break; case Constants.ArchiveStatusElement: rehydrationStatusString = await reader.ReadElementContentAsStringAsync().ConfigureAwait(false); break; case Constants.AccessTierInferred: blobTierInferred = await reader.ReadElementContentAsBooleanAsync().ConfigureAwait(false); break; case Constants.AccessTierChangeTimeElement: string t = await reader.ReadElementContentAsStringAsync().ConfigureAwait(false); blobTierLastModifiedTime = DateTimeOffset.Parse(t, CultureInfo.InvariantCulture); break; case Constants.DeletedTimeElement: blob.Properties.DeletedTime = (await reader.ReadElementContentAsStringAsync().ConfigureAwait(false)).ToUTCTime(); break; case Constants.RemainingRetentionDaysElement: blob.Properties.RemainingDaysBeforePermanentDelete = int.Parse(await reader.ReadElementContentAsStringAsync().ConfigureAwait(false)); break; default: await reader.SkipAsync().ConfigureAwait(false); break; } } } await reader.ReadEndElementAsync().ConfigureAwait(false); break; case Constants.MetadataElement: blob.Metadata = await Response.ParseMetadataAsync(reader).ConfigureAwait(false); break; default: await reader.SkipAsync().ConfigureAwait(false); break; } } } await reader.ReadEndElementAsync().ConfigureAwait(false); Uri uri = NavigationHelper.AppendPathToSingleUri(baseUri, name); if (blob.SnapshotTime.HasValue) { UriQueryBuilder builder = new UriQueryBuilder(); builder.Add("snapshot", Request.ConvertDateTimeToSnapshotString(blob.SnapshotTime.Value)); uri = builder.AddToUri(uri); } blob.StorageUri = new StorageUri(uri); if (!string.IsNullOrEmpty(copyStatus)) { blob.CopyState = BlobHttpResponseParsers.GetCopyAttributes( copyStatus, copyId, copySource, copyProgress, copyCompletionTime, copyStatusDescription, copyDestinationSnapshotTime); } if (!string.IsNullOrEmpty(blobTierString)) { StandardBlobTier? standardBlobTier; PremiumPageBlobTier?premiumPageBlobTier; BlobHttpResponseParsers.GetBlobTier(blob.Properties.BlobType, blobTierString, out standardBlobTier, out premiumPageBlobTier); blob.Properties.StandardBlobTier = standardBlobTier; blob.Properties.PremiumPageBlobTier = premiumPageBlobTier; } blob.Properties.RehydrationStatus = BlobHttpResponseParsers.GetRehydrationStatus(rehydrationStatusString); blob.Properties.BlobTierLastModifiedTime = blobTierLastModifiedTime; blob.Properties.BlobTierInferred = blobTierInferred; return(new ListBlobEntry(name, blob)); }
internal static StorageRequestMessage BuildRequestForTableBatchOperation <T>(RESTCommand <T> cmd, Uri uri, UriQueryBuilder builder, int?timeout, string tableName, TableBatchOperation batch, CloudTableClient client, HttpContent content, OperationContext ctx, TablePayloadFormat payloadFormat, ICanonicalizer canonicalizer, StorageCredentials credentials) { StorageRequestMessage msg = BuildRequestCore(NavigationHelper.AppendPathToSingleUri(uri, "$batch"), builder, HttpMethod.Post, timeout, content, ctx, canonicalizer, credentials); Logger.LogInformational(ctx, SR.PayloadFormat, payloadFormat); // create the writer, indent for readability of the examples. ODataMessageWriterSettings writerSettings = new ODataMessageWriterSettings() { CheckCharacters = false, // sets this flag on the XmlWriter for ATOM Version = TableConstants.ODataProtocolVersion // set the Odata version to use when writing the entry }; HttpRequestAdapterMessage adapterMsg = new HttpRequestAdapterMessage(msg, client.BufferManager, 64 * (int)Constants.KB); cmd.StreamToDispose = adapterMsg.GetStream(); // Start Batch ODataMessageWriter odataWriter = new ODataMessageWriter(adapterMsg, writerSettings); ODataBatchWriter batchWriter = odataWriter.CreateODataBatchWriter(); batchWriter.WriteStartBatch(); bool isQuery = batch.Count == 1 && batch[0].OperationType == TableOperationType.Retrieve; // Query operations should not be inside changeset in payload if (!isQuery) { // Start Operation batchWriter.WriteStartChangeset(); batchWriter.Flush(); } foreach (TableOperation operation in batch) { string httpMethod = operation.OperationType == TableOperationType.Merge || operation.OperationType == TableOperationType.InsertOrMerge ? "MERGE" : operation.HttpMethod.Method; ODataBatchOperationRequestMessage mimePartMsg = batchWriter.CreateOperationRequestMessage(httpMethod, operation.GenerateRequestURI(uri, tableName)); SetAcceptAndContentTypeForODataBatchMessage(mimePartMsg, payloadFormat); // etag if (operation.OperationType == TableOperationType.Delete || operation.OperationType == TableOperationType.Replace || operation.OperationType == TableOperationType.Merge) { mimePartMsg.SetHeader("If-Match", operation.Entity.ETag); } // Prefer header if (operation.OperationType == TableOperationType.Insert) { mimePartMsg.SetHeader("Prefer", operation.EchoContent ? "return-content" : "return-no-content"); } if (operation.OperationType != TableOperationType.Delete && operation.OperationType != TableOperationType.Retrieve) { using (ODataMessageWriter batchEntryWriter = new ODataMessageWriter(mimePartMsg, writerSettings, new TableStorageModel(client.AccountName))) { // Write entity ODataWriter entryWriter = batchEntryWriter.CreateODataEntryWriter(); WriteOdataEntity(operation.Entity, operation.OperationType, ctx, entryWriter); } } } if (!isQuery) { // End Operation batchWriter.WriteEndChangeset(); } // End Batch batchWriter.WriteEndBatch(); batchWriter.Flush(); return(adapterMsg.GetPopulatedMessage()); }
/// <summary> /// Parses a file directory entry in a file listing response. /// </summary> /// <returns>File listing entry</returns> private IListFileEntry ParseFileDirectoryEntry(Uri baseUri) { FileDirectoryProperties properties = new FileDirectoryProperties(); string name = null; this.reader.ReadStartElement(); while (this.reader.IsStartElement()) { if (this.reader.IsEmptyElement) { this.reader.Skip(); } else { switch (this.reader.Name) { case Constants.NameElement: name = reader.ReadElementContentAsString(); break; case Constants.PropertiesElement: this.reader.ReadStartElement(); while (this.reader.IsStartElement()) { if (this.reader.IsEmptyElement) { this.reader.Skip(); } else { switch (this.reader.Name) { case Constants.LastModifiedElement: properties.LastModified = reader.ReadElementContentAsString().ToUTCTime(); break; case Constants.EtagElement: properties.ETag = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", reader.ReadElementContentAsString()); break; default: this.reader.Skip(); break; } } } this.reader.ReadEndElement(); break; default: this.reader.Skip(); break; } } } this.reader.ReadEndElement(); Uri uri = NavigationHelper.AppendPathToSingleUri(baseUri, name); return(new ListFileDirectoryEntry(name, uri, properties)); }
/// <summary> /// Parses a file entry in a file listing response. /// </summary> /// <returns>File listing entry</returns> private IListFileEntry ParseFileEntry(Uri baseUri) { CloudFileAttributes file = new CloudFileAttributes(); string name = null; this.reader.ReadStartElement(); while (this.reader.IsStartElement()) { if (this.reader.IsEmptyElement) { this.reader.Skip(); } else { switch (this.reader.Name) { case Constants.NameElement: name = reader.ReadElementContentAsString(); break; case Constants.PropertiesElement: this.reader.ReadStartElement(); while (this.reader.IsStartElement()) { if (this.reader.IsEmptyElement) { this.reader.Skip(); } else { switch (this.reader.Name) { case Constants.ContentLengthElement: file.Properties.Length = reader.ReadElementContentAsLong(); break; default: this.reader.Skip(); break; } } } this.reader.ReadEndElement(); break; default: this.reader.Skip(); break; } } } this.reader.ReadEndElement(); Uri uri = NavigationHelper.AppendPathToSingleUri(baseUri, name); file.StorageUri = new StorageUri(uri); return(new ListFileEntry(name, file)); }
internal static StorageRequestMessage BuildStorageRequestMessageForTableBatchOperation(Uri uri, TableBatchOperation batch, ICanonicalizer canonicalizer, string tableName, StorageCredentials cred, OperationContext ctx, TableRequestOptions options) { StorageRequestMessage storageRequestMessage = new StorageRequestMessage(HttpMethod.Post, NavigationHelper.AppendPathToSingleUri(uri, "$batch"), canonicalizer, cred, cred.AccountName); storageRequestMessage.Headers.AcceptCharset.ParseAdd("UTF-8"); storageRequestMessage.Headers.Add("MaxDataServiceVersion", "3.0;NetFx"); TablePayloadFormat value = options.PayloadFormat.Value; Logger.LogInformational(ctx, "Setting payload format for the request to '{0}'.", value); SetAcceptHeaderValueForStorageRequestMessage(storageRequestMessage, value); storageRequestMessage.Headers.Add("DataServiceVersion", "3.0;"); MultiBufferMemoryStream multiBufferMemoryStream = new MultiBufferMemoryStream(); string str = Guid.NewGuid().ToString(); using (StreamWriter streamWriter = new StreamWriter(new NonCloseableStream(multiBufferMemoryStream))) { string str2 = Guid.NewGuid().ToString(); string text = "--batch_" + str; string text2 = "--changeset_" + str2; string text3 = "Accept: "; switch (value) { case TablePayloadFormat.Json: text3 += "application/json;odata=minimalmetadata"; break; case TablePayloadFormat.JsonFullMetadata: text3 += "application/json;odata=fullmetadata"; break; case TablePayloadFormat.JsonNoMetadata: text3 += "application/json;odata=nometadata"; break; } streamWriter.WriteLine(text); bool flag = batch.Count == 1 && batch[0].OperationType == TableOperationType.Retrieve; if (!flag) { streamWriter.WriteLine("Content-Type: multipart/mixed; boundary=changeset_" + str2); streamWriter.WriteLine(); } foreach (TableOperation item in batch) { HttpMethod httpMethod = RESTCommandGeneratorUtils.ExtractHttpMethod(item); if (item.OperationType == TableOperationType.Merge || item.OperationType == TableOperationType.InsertOrMerge) { httpMethod = new HttpMethod("MERGE"); } if (!flag) { streamWriter.WriteLine(text2); } streamWriter.WriteLine("Content-Type: application/http"); streamWriter.WriteLine("Content-Transfer-Encoding: binary"); streamWriter.WriteLine(); string text4 = Uri.EscapeUriString(RESTCommandGeneratorUtils.GenerateRequestURI(item, uri, tableName).ToString()); text4 = text4.Replace("%25", "%"); streamWriter.WriteLine(httpMethod + " " + text4 + " HTTP/1.1"); streamWriter.WriteLine(text3); streamWriter.WriteLine("Content-Type: application/json"); if (item.OperationType == TableOperationType.Insert) { streamWriter.WriteLine("Prefer: " + (item.EchoContent ? "return-content" : "return-no-content")); } streamWriter.WriteLine("DataServiceVersion: 3.0;"); if (item.OperationType == TableOperationType.Delete || item.OperationType == TableOperationType.Replace || item.OperationType == TableOperationType.Merge) { streamWriter.WriteLine("If-Match: " + item.ETag); } streamWriter.WriteLine(); if (item.OperationType != TableOperationType.Delete && item.OperationType != TableOperationType.Retrieve) { using (JsonTextWriter jsonTextWriter = new JsonTextWriter(streamWriter)) { jsonTextWriter.CloseOutput = false; WriteEntityContent(item, ctx, options, jsonTextWriter); } streamWriter.WriteLine(); } } if (!flag) { streamWriter.WriteLine(text2 + "--"); } streamWriter.WriteLine(text + "--"); } multiBufferMemoryStream.Seek(0L, SeekOrigin.Begin); storageRequestMessage.Content = new StreamContent(multiBufferMemoryStream); storageRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("multipart/mixed"); storageRequestMessage.Content.Headers.ContentType.Parameters.Add(NameValueHeaderValue.Parse("boundary=batch_" + str)); return(storageRequestMessage); }
internal static StorageRequestMessage BuildRequestForTableBatchOperation <T>(RESTCommand <T> cmd, Uri uri, UriQueryBuilder builder, int?timeout, string tableName, TableBatchOperation batch, CloudTableClient client, HttpContent content, OperationContext ctx, TablePayloadFormat payloadFormat, ICanonicalizer canonicalizer, StorageCredentials credentials) { StorageRequestMessage msg = BuildRequestCore(NavigationHelper.AppendPathToSingleUri(uri, "$batch"), builder, HttpMethod.Post, timeout, content, ctx, canonicalizer, credentials); Logger.LogInformational(ctx, SR.PayloadFormat, payloadFormat); MultiBufferMemoryStream batchContentStream = new MultiBufferMemoryStream(client.BufferManager); string batchID = Guid.NewGuid().ToString(); string changesetID = Guid.NewGuid().ToString(); using (StreamWriter contentWriter = new StreamWriter(new NonCloseableStream(batchContentStream))) { msg.Headers.Add(Constants.HeaderConstants.DataServiceVersion, Constants.HeaderConstants.DataServiceVersionValue); string batchSeparator = Constants.BatchSeparator + batchID; string changesetSeparator = Constants.ChangesetSeparator + changesetID; string acceptHeader = "Accept: "; switch (payloadFormat) { case TablePayloadFormat.Json: acceptHeader = acceptHeader + Constants.JsonLightAcceptHeaderValue; break; case TablePayloadFormat.JsonFullMetadata: acceptHeader = acceptHeader + Constants.JsonFullMetadataAcceptHeaderValue; break; case TablePayloadFormat.JsonNoMetadata: acceptHeader = acceptHeader + Constants.JsonNoMetadataAcceptHeaderValue; break; } contentWriter.WriteLine(batchSeparator); bool isQuery = batch.Count == 1 && batch[0].OperationType == TableOperationType.Retrieve; // Query operations should not be inside changeset in payload if (!isQuery) { // Start Operation contentWriter.WriteLine(Constants.ChangesetBoundaryMarker + changesetID); contentWriter.WriteLine(); } foreach (TableOperation operation in batch) { string httpMethod = operation.OperationType == TableOperationType.Merge || operation.OperationType == TableOperationType.InsertOrMerge ? "MERGE" : operation.HttpMethod.Method; if (!isQuery) { contentWriter.WriteLine(changesetSeparator); } contentWriter.WriteLine(Constants.ContentTypeApplicationHttp); contentWriter.WriteLine(Constants.ContentTransferEncodingBinary); contentWriter.WriteLine(); string tableURI = Uri.EscapeUriString(operation.GenerateRequestURI(uri, tableName).ToString()); // "EscapeUriString" is almost exactly what we need, except that it contains special logic for // the percent sign, which results in an off-by-one error in the number of times "%" is encoded. // This corrects for that. tableURI = tableURI.Replace(@"%25", @"%"); contentWriter.WriteLine(httpMethod + " " + tableURI + " " + Constants.HTTP1_1); contentWriter.WriteLine(acceptHeader); contentWriter.WriteLine(Constants.ContentTypeApplicationJson); if (operation.OperationType == TableOperationType.Insert) { contentWriter.WriteLine(Constants.HeaderConstants.Prefer + @": " + (operation.EchoContent ? Constants.HeaderConstants.PreferReturnContent : Constants.HeaderConstants.PreferReturnNoContent)); } contentWriter.WriteLine(Constants.HeaderConstants.DataServiceVersion + ": " + Constants.HeaderConstants.DataServiceVersionValue); // etag if (operation.OperationType == TableOperationType.Delete || operation.OperationType == TableOperationType.Replace || operation.OperationType == TableOperationType.Merge) { contentWriter.WriteLine(Constants.HeaderConstants.IfMatch + @": " + operation.ETag); } contentWriter.WriteLine(); if (operation.OperationType != TableOperationType.Delete && operation.OperationType != TableOperationType.Retrieve) { using (JsonTextWriter jsonWriter = new JsonTextWriter(contentWriter)) { jsonWriter.CloseOutput = false; WriteEntityContent(operation, ctx, jsonWriter); } contentWriter.WriteLine(); } } if (!isQuery) { contentWriter.WriteLine(changesetSeparator + "--"); } contentWriter.WriteLine(batchSeparator + "--"); } batchContentStream.Seek(0, SeekOrigin.Begin); msg.Content = new StreamContent(batchContentStream); msg.Content.Headers.ContentLength = batchContentStream.Length; msg.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(Constants.BatchBoundaryMarker + batchID);//new System.Net.Http.Headers.MediaTypeHeaderValue(Constants.BatchBoundaryMarker + batchID); return(msg); }
/// <summary> /// Reads a share entry completely including its properties and metadata. /// </summary> /// <returns>Share listing entry</returns> private FileShareEntry ParseShareEntry(Uri baseUri) { string name = null; IDictionary <string, string> metadata = null; FileShareProperties shareProperties = new FileShareProperties(); this.reader.ReadStartElement(); while (this.reader.IsStartElement()) { if (this.reader.IsEmptyElement) { this.reader.Skip(); } else { switch (this.reader.Name) { case Constants.NameElement: name = this.reader.ReadElementContentAsString(); break; case Constants.PropertiesElement: this.reader.ReadStartElement(); while (this.reader.IsStartElement()) { if (this.reader.IsEmptyElement) { this.reader.Skip(); } else { switch (this.reader.Name) { case Constants.LastModifiedElement: shareProperties.LastModified = reader.ReadElementContentAsString().ToUTCTime(); break; case Constants.EtagElement: shareProperties.ETag = reader.ReadElementContentAsString(); break; case Constants.QuotaElement: shareProperties.Quota = reader.ReadElementContentAsInt(); break; default: reader.Skip(); break; } } } this.reader.ReadEndElement(); break; case Constants.MetadataElement: metadata = Response.ParseMetadata(this.reader); break; default: reader.Skip(); break; } } } this.reader.ReadEndElement(); if (metadata == null) { metadata = new Dictionary <string, string>(); } return(new FileShareEntry { Properties = shareProperties, Name = name, Uri = NavigationHelper.AppendPathToSingleUri(baseUri, name), Metadata = metadata, }); }
/// <summary> /// Parses a file directory entry in a file listing response. /// </summary> /// <returns>File listing entry</returns> private static async Task <IListFileEntry> ParseFileDirectoryEntryAsync(XmlReader reader, Uri baseUri, CancellationToken token) { token.ThrowIfCancellationRequested(); FileDirectoryProperties properties = new FileDirectoryProperties(); string name = null; 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.NameElement: name = await reader.ReadElementContentAsStringAsync().ConfigureAwait(false); break; case Constants.PropertiesElement: 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.LastModifiedElement: properties.LastModified = (await reader.ReadElementContentAsStringAsync().ConfigureAwait(false)).ToUTCTime(); break; case Constants.EtagElement: properties.ETag = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", await reader.ReadElementContentAsStringAsync().ConfigureAwait(false)); break; default: await reader.SkipAsync().ConfigureAwait(false); break; } } } await reader.ReadEndElementAsync().ConfigureAwait(false); break; default: await reader.SkipAsync().ConfigureAwait(false); break; } } } await reader.ReadEndElementAsync().ConfigureAwait(false); Uri uri = NavigationHelper.AppendPathToSingleUri(baseUri, name); return(new ListFileDirectoryEntry(name, uri, properties)); }
/// <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 }); } }
/// <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> /// Reads a share entry completely including its properties and metadata. /// </summary> /// <returns>Share listing entry</returns> private static async Task <FileShareEntry> ParseShareEntryAsync(XmlReader reader, Uri baseUri, CancellationToken token) { token.ThrowIfCancellationRequested(); string name = null; DateTimeOffset?snapshotTime = null; IDictionary <string, string> metadata = null; FileShareProperties shareProperties = new FileShareProperties(); 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.NameElement: name = await reader.ReadElementContentAsStringAsync().ConfigureAwait(false); break; case Constants.SnapshotElement: snapshotTime = (await reader.ReadElementContentAsStringAsync().ConfigureAwait(false)).ToUTCTime(); break; case Constants.PropertiesElement: 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.LastModifiedElement: shareProperties.LastModified = (await reader.ReadElementContentAsStringAsync().ConfigureAwait(false)).ToUTCTime(); break; case Constants.EtagElement: shareProperties.ETag = await reader.ReadElementContentAsStringAsync().ConfigureAwait(false); break; case Constants.QuotaElement: shareProperties.Quota = await reader.ReadElementContentAsInt32Async().ConfigureAwait(false); break; default: await reader.SkipAsync().ConfigureAwait(false); break; } } } await reader.ReadEndElementAsync().ConfigureAwait(false); break; case Constants.MetadataElement: metadata = await Response.ParseMetadataAsync(reader).ConfigureAwait(false); break; default: await reader.SkipAsync().ConfigureAwait(false); break; } } } await reader.ReadEndElementAsync().ConfigureAwait(false); return(new FileShareEntry { Properties = shareProperties, Name = name, Uri = NavigationHelper.AppendPathToSingleUri(baseUri, name), Metadata = metadata ?? new Dictionary <string, string>(), SnapshotTime = snapshotTime, }); }
/// <summary> /// Parses a file entry in a file listing response. /// </summary> /// <returns>File listing entry</returns> private static async Task <IListFileEntry> ParseFileEntryAsync(XmlReader reader, Uri baseUri, CancellationToken token) { token.ThrowIfCancellationRequested(); CloudFileAttributes file = new CloudFileAttributes(); string name = null; 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.NameElement: name = await reader.ReadElementContentAsStringAsync().ConfigureAwait(false); break; case Constants.PropertiesElement: 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.ContentLengthElement: file.Properties.Length = await reader.ReadElementContentAsInt64Async().ConfigureAwait(false); break; default: await reader.SkipAsync().ConfigureAwait(false); break; } } } await reader.ReadEndElementAsync().ConfigureAwait(false); break; default: await reader.SkipAsync().ConfigureAwait(false); break; } } } await reader.ReadEndElementAsync().ConfigureAwait(false); Uri uri = NavigationHelper.AppendPathToSingleUri(baseUri, name); file.StorageUri = new StorageUri(uri); return(new ListFileEntry(name, file)); }
private IListBlobEntry ParseBlobEntry(Uri baseUri) { BlobAttributes blob = new BlobAttributes(); string name = null; // copy blob attribute strings string copyId = null; string copyStatus = null; string copyCompletionTime = null; string copyProgress = null; string copySource = null; string copyStatusDescription = null; this.reader.ReadStartElement(); while (this.reader.IsStartElement()) { if (this.reader.IsEmptyElement) { this.reader.Skip(); } else { switch (this.reader.Name) { case Constants.NameElement: name = reader.ReadElementContentAsString(); break; case Constants.SnapshotElement: blob.SnapshotTime = reader.ReadElementContentAsString().ToUTCTime(); break; case Constants.PropertiesElement: this.reader.ReadStartElement(); while (this.reader.IsStartElement()) { if (this.reader.IsEmptyElement) { this.reader.Skip(); } else { switch (this.reader.Name) { case Constants.LastModifiedElement: blob.Properties.LastModified = reader.ReadElementContentAsString().ToUTCTime(); break; case Constants.EtagElement: blob.Properties.ETag = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", reader.ReadElementContentAsString()); break; case Constants.ContentLengthElement: blob.Properties.Length = reader.ReadElementContentAsLong(); break; case Constants.CacheControlElement: blob.Properties.CacheControl = reader.ReadElementContentAsString(); break; case Constants.ContentTypeElement: blob.Properties.ContentType = reader.ReadElementContentAsString(); break; case Constants.HeaderConstants.ContentDispositionResponseHeader: blob.Properties.ContentDisposition = reader.ReadElementContentAsString(); break; case Constants.ContentEncodingElement: blob.Properties.ContentEncoding = reader.ReadElementContentAsString(); break; case Constants.ContentLanguageElement: blob.Properties.ContentLanguage = reader.ReadElementContentAsString(); break; case Constants.ContentMD5Element: blob.Properties.ContentMD5 = reader.ReadElementContentAsString(); break; case Constants.BlobTypeElement: string blobTypeString = reader.ReadElementContentAsString(); switch (blobTypeString) { case Constants.BlockBlobValue: blob.Properties.BlobType = BlobType.BlockBlob; break; case Constants.PageBlobValue: blob.Properties.BlobType = BlobType.PageBlob; break; } break; case Constants.LeaseStatusElement: blob.Properties.LeaseStatus = BlobHttpResponseParsers.GetLeaseStatus(reader.ReadElementContentAsString()); break; case Constants.LeaseStateElement: blob.Properties.LeaseState = BlobHttpResponseParsers.GetLeaseState(reader.ReadElementContentAsString()); break; case Constants.LeaseDurationElement: blob.Properties.LeaseDuration = BlobHttpResponseParsers.GetLeaseDuration(reader.ReadElementContentAsString()); break; case Constants.CopyIdElement: copyId = reader.ReadElementContentAsString(); break; case Constants.CopyCompletionTimeElement: copyCompletionTime = reader.ReadElementContentAsString(); break; case Constants.CopyStatusElement: copyStatus = reader.ReadElementContentAsString(); break; case Constants.CopyProgressElement: copyProgress = reader.ReadElementContentAsString(); break; case Constants.CopySourceElement: copySource = reader.ReadElementContentAsString(); break; case Constants.CopyStatusDescriptionElement: copyStatusDescription = reader.ReadElementContentAsString(); break; default: reader.Skip(); break; } } } this.reader.ReadEndElement(); break; case Constants.MetadataElement: blob.Metadata = Response.ParseMetadata(this.reader); break; default: this.reader.Skip(); break; } } } this.reader.ReadEndElement(); Uri uri = NavigationHelper.AppendPathToSingleUri(baseUri, name); if (blob.SnapshotTime.HasValue) { UriQueryBuilder builder = new UriQueryBuilder(); builder.Add("snapshot", BlobRequest.ConvertDateTimeToSnapshotString(blob.SnapshotTime.Value)); uri = builder.AddToUri(uri); } blob.StorageUri = new StorageUri(uri); if (!string.IsNullOrEmpty(copyStatus)) { blob.CopyState = BlobHttpResponseParsers.GetCopyAttributes( copyStatus, copyId, copySource, copyProgress, copyCompletionTime, copyStatusDescription); } return(new ListBlobEntry(name, blob)); }
private IListBlobEntry ParseBlobEntry(Uri baseUri) { BlobAttributes blob = new BlobAttributes(); string name = null; // copy blob attribute strings string copyId = null; string copyStatus = null; string copyCompletionTime = null; string copyProgress = null; string copySource = null; string copyStatusDescription = null; string copyDestinationSnapshotTime = null; string blobTierString = null; bool? blobTierInferred = null; string rehydrationStatusString = null; DateTimeOffset?blobTierLastModifiedTime = null; this.reader.ReadStartElement(); while (this.reader.IsStartElement()) { if (this.reader.IsEmptyElement) { this.reader.Skip(); } else { switch (this.reader.Name) { case Constants.NameElement: name = reader.ReadElementContentAsString(); break; case Constants.SnapshotElement: blob.SnapshotTime = reader.ReadElementContentAsString().ToUTCTime(); break; case Constants.PropertiesElement: this.reader.ReadStartElement(); while (this.reader.IsStartElement()) { if (this.reader.IsEmptyElement) { this.reader.Skip(); } else { switch (this.reader.Name) { case Constants.LastModifiedElement: blob.Properties.LastModified = reader.ReadElementContentAsString().ToUTCTime(); break; case Constants.EtagElement: blob.Properties.ETag = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", reader.ReadElementContentAsString()); break; case Constants.ContentLengthElement: blob.Properties.Length = reader.ReadElementContentAsLong(); break; case Constants.CacheControlElement: blob.Properties.CacheControl = reader.ReadElementContentAsString(); break; case Constants.ContentTypeElement: blob.Properties.ContentType = reader.ReadElementContentAsString(); break; case Constants.HeaderConstants.ContentDispositionResponseHeader: blob.Properties.ContentDisposition = reader.ReadElementContentAsString(); break; case Constants.ContentEncodingElement: blob.Properties.ContentEncoding = reader.ReadElementContentAsString(); break; case Constants.ContentLanguageElement: blob.Properties.ContentLanguage = reader.ReadElementContentAsString(); break; case Constants.ContentMD5Element: blob.Properties.ContentMD5 = reader.ReadElementContentAsString(); break; case Constants.BlobTypeElement: string blobTypeString = reader.ReadElementContentAsString(); switch (blobTypeString) { case Constants.BlockBlobValue: blob.Properties.BlobType = BlobType.BlockBlob; break; case Constants.PageBlobValue: blob.Properties.BlobType = BlobType.PageBlob; break; case Constants.AppendBlobValue: blob.Properties.BlobType = BlobType.AppendBlob; break; } break; case Constants.LeaseStatusElement: blob.Properties.LeaseStatus = BlobHttpResponseParsers.GetLeaseStatus(reader.ReadElementContentAsString()); break; case Constants.LeaseStateElement: blob.Properties.LeaseState = BlobHttpResponseParsers.GetLeaseState(reader.ReadElementContentAsString()); break; case Constants.LeaseDurationElement: blob.Properties.LeaseDuration = BlobHttpResponseParsers.GetLeaseDuration(reader.ReadElementContentAsString()); break; case Constants.CopyIdElement: copyId = reader.ReadElementContentAsString(); break; case Constants.CopyCompletionTimeElement: copyCompletionTime = reader.ReadElementContentAsString(); break; case Constants.CopyStatusElement: copyStatus = reader.ReadElementContentAsString(); break; case Constants.CopyProgressElement: copyProgress = reader.ReadElementContentAsString(); break; case Constants.CopySourceElement: copySource = reader.ReadElementContentAsString(); break; case Constants.CopyStatusDescriptionElement: copyStatusDescription = reader.ReadElementContentAsString(); break; case Constants.ServerEncryptionElement: blob.Properties.IsServerEncrypted = BlobHttpResponseParsers.GetServerEncrypted(reader.ReadElementContentAsString()); break; case Constants.IncrementalCopy: blob.Properties.IsIncrementalCopy = BlobHttpResponseParsers.GetIncrementalCopyStatus(reader.ReadElementContentAsString()); break; case Constants.CopyDestinationSnapshotElement: copyDestinationSnapshotTime = reader.ReadElementContentAsString(); break; case Constants.AccessTierElement: blobTierString = reader.ReadElementContentAsString(); break; case Constants.ArchiveStatusElement: rehydrationStatusString = reader.ReadElementContentAsString(); break; case Constants.AccessTierInferred: blobTierInferred = reader.ReadElementContentAsBoolean(); break; case Constants.AccessTierChangeTimeElement: string t = reader.ReadElementContentAsString(); blobTierLastModifiedTime = DateTimeOffset.Parse(t, CultureInfo.InvariantCulture); break; default: reader.Skip(); break; } } } this.reader.ReadEndElement(); break; case Constants.MetadataElement: blob.Metadata = Response.ParseMetadata(this.reader); break; default: this.reader.Skip(); break; } } } this.reader.ReadEndElement(); Uri uri = NavigationHelper.AppendPathToSingleUri(baseUri, name); if (blob.SnapshotTime.HasValue) { UriQueryBuilder builder = new UriQueryBuilder(); builder.Add("snapshot", Request.ConvertDateTimeToSnapshotString(blob.SnapshotTime.Value)); uri = builder.AddToUri(uri); } blob.StorageUri = new StorageUri(uri); if (!string.IsNullOrEmpty(copyStatus)) { blob.CopyState = BlobHttpResponseParsers.GetCopyAttributes( copyStatus, copyId, copySource, copyProgress, copyCompletionTime, copyStatusDescription, copyDestinationSnapshotTime); } if (!string.IsNullOrEmpty(blobTierString)) { StandardBlobTier? standardBlobTier; PremiumPageBlobTier?premiumPageBlobTier; BlobHttpResponseParsers.GetBlobTier(blob.Properties.BlobType, blobTierString, out standardBlobTier, out premiumPageBlobTier); blob.Properties.StandardBlobTier = standardBlobTier; blob.Properties.PremiumPageBlobTier = premiumPageBlobTier; } blob.Properties.RehydrationStatus = BlobHttpResponseParsers.GetRehydrationStatus(rehydrationStatusString); blob.Properties.BlobTierLastModifiedTime = blobTierLastModifiedTime; blob.Properties.BlobTierInferred = blobTierInferred; return(new ListBlobEntry(name, blob)); }
internal static Tuple <HttpWebRequest, Stream> BuildRequestForTableBatchOperation(Uri uri, UriQueryBuilder builder, IBufferManager bufferManager, int?timeout, string tableName, TableBatchOperation batch, bool useVersionHeader, OperationContext ctx, TableRequestOptions options, string accountName) { HttpWebRequest msg = BuildRequestCore(NavigationHelper.AppendPathToSingleUri(uri, "$batch"), builder, "POST", timeout, useVersionHeader, ctx); TablePayloadFormat payloadFormat = options.PayloadFormat.Value; Logger.LogInformational(ctx, SR.PayloadFormat, payloadFormat); // create the writer, indent for readability of the examples. ODataMessageWriterSettings writerSettings = new ODataMessageWriterSettings() { CheckCharacters = false, // sets this flag on the XmlWriter for ATOM Version = TableConstants.ODataProtocolVersion // set the Odata version to use when writing the entry }; HttpWebRequestAdapterMessage adapterMsg = new HttpWebRequestAdapterMessage(msg, bufferManager); // Start Batch ODataMessageWriter odataWriter = new ODataMessageWriter(adapterMsg, writerSettings); ODataBatchWriter batchWriter = odataWriter.CreateODataBatchWriter(); batchWriter.WriteStartBatch(); bool isQuery = batch.Count == 1 && batch[0].OperationType == TableOperationType.Retrieve; // Query operations should not be inside changeset in payload if (!isQuery) { // Start Operation batchWriter.WriteStartChangeset(); batchWriter.Flush(); } foreach (TableOperation operation in batch) { string httpMethod = operation.HttpMethod; if (operation.OperationType == TableOperationType.Merge || operation.OperationType == TableOperationType.InsertOrMerge) { options.AssertNoEncryptionPolicyOrStrictMode(); httpMethod = "MERGE"; } ODataBatchOperationRequestMessage mimePartMsg = batchWriter.CreateOperationRequestMessage(httpMethod, operation.GenerateRequestURI(uri, tableName)); SetAcceptAndContentTypeForODataBatchMessage(mimePartMsg, payloadFormat); // etag if (operation.OperationType == TableOperationType.Delete || operation.OperationType == TableOperationType.Replace || operation.OperationType == TableOperationType.Merge) { mimePartMsg.SetHeader("If-Match", operation.Entity.ETag); } // Prefer header if (operation.OperationType == TableOperationType.Insert) { mimePartMsg.SetHeader("Prefer", operation.EchoContent ? "return-content" : "return-no-content"); } if (operation.OperationType != TableOperationType.Delete && operation.OperationType != TableOperationType.Retrieve) { using (ODataMessageWriter batchEntryWriter = new ODataMessageWriter(mimePartMsg, writerSettings, new TableStorageModel(accountName))) { // Write entity ODataWriter entryWriter = batchEntryWriter.CreateODataEntryWriter(); WriteOdataEntity(operation.Entity, operation.OperationType, ctx, entryWriter, options); } } } if (!isQuery) { // End Operation batchWriter.WriteEndChangeset(); } // End Batch batchWriter.WriteEndBatch(); batchWriter.Flush(); return(new Tuple <HttpWebRequest, Stream>(adapterMsg.GetPopulatedMessage(), adapterMsg.GetStream())); }
internal static RESTCommand <TablePermissions> GetAclImpl(CloudTableClient client, CloudTable table, TableRequestOptions requestOptions) { RESTCommand <TablePermissions> rESTCommand = new RESTCommand <TablePermissions>(client.Credentials, client.StorageUri); RESTCommandGeneratorUtils.ApplyTableRequestOptionsToStorageCommand(requestOptions, rESTCommand); rESTCommand.HttpClient = client.HttpClient; rESTCommand.CommandLocationMode = CommandLocationMode.PrimaryOrSecondary; rESTCommand.BuildRequest = ((RESTCommand <TablePermissions> cmd, Uri uri, UriQueryBuilder uriBuilder, HttpContent httpContent, int?timeout, OperationContext ctx) => TableRequestMessageFactory.BuildStorageRequestMessageForTablePermissions(NavigationHelper.AppendPathToSingleUri(uri, table.Name), uriBuilder, timeout, HttpMethod.Get, null, SharedKeyCanonicalizer.Instance, client.Credentials, ctx, requestOptions)); rESTCommand.ParseErrorAsync = StorageExtendedErrorInformationRestHelper.ReadExtendedErrorInfoFromStreamAsync; rESTCommand.PreProcessResponse = ((RESTCommand <TablePermissions> cmd, HttpResponseMessage resp, Exception ex, OperationContext ctx) => HttpResponseParsers.ProcessExpectedStatusCodeNoException(HttpStatusCode.OK, resp, null, cmd, ex)); rESTCommand.PostProcessResponseAsync = ((RESTCommand <TablePermissions> cmd, HttpResponseMessage resp, OperationContext ctx, CancellationToken token) => TableOperationHttpResponseParsers.ParseGetAclAsync(cmd, resp, ctx)); return(rESTCommand); }