/// <inheritdoc /> public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger) { if (type == null) { throw Error.ArgumentNull("type"); } if (readStream == null) { throw Error.ArgumentNull("readStream"); } if (type == typeof(DBNull) && content != null && content.Headers != null && content.Headers.ContentLength == 0) { // Lower-level Json.Net deserialization can convert null to DBNull.Value. However this formatter treats // DBNull.Value like null and serializes no content. Json.Net code won't be invoked at all (for read or // write). Override BaseJsonMediaTypeFormatter.ReadFromStream()'s call to GetDefaultValueForType() // (which would return null in this case) and instead return expected DBNull.Value. Special case exists // primarily for parity with JsonMediaTypeFormatter. return Task.FromResult((object)DBNull.Value); } else { return base.ReadFromStreamAsync(type, readStream, content, formatterLogger); } }
private static void ValidateContentHeader(HttpContent content) { IEnumerable<string> values; bool headerResult = content.Headers.TryGetValues(TestHeader, out values); Assert.True(headerResult); Assert.Equal(TestValue, values.First()); }
public ProgressContent(HttpContent innerContent, ProgressMessageHandler handler, HttpRequestMessage request) { Contract.Assert(innerContent != null); Contract.Assert(handler != null); Contract.Assert(request != null); _innerContent = innerContent; _handler = handler; _request = request; innerContent.Headers.CopyTo(Headers); }
public static bool IsMimeMultipartContent(HttpContent content) { Contract.Assert(content != null, "content cannot be null."); try { string boundary = ValidateArguments(content, DefaultMaxMessageSize, false); return boundary != null ? true : false; } catch (Exception) { return false; } }
/// <summary> /// Initializes a new instance of the <see cref="MimeMultipartBodyPartParser"/> class. /// </summary> /// <param name="content">An existing <see cref="HttpContent"/> instance to use for the object's content.</param> /// <param name="streamProvider">A stream provider providing output streams for where to write body parts as they are parsed.</param> /// <param name="maxMessageSize">The max length of the entire MIME multipart message.</param> /// <param name="maxBodyPartHeaderSize">The max length of the MIME header within each MIME body part.</param> public MimeMultipartBodyPartParser( HttpContent content, IMultipartStreamProvider streamProvider, long maxMessageSize, int maxBodyPartHeaderSize) { Contract.Assert(content != null, "content cannot be null."); Contract.Assert(streamProvider != null, "streamProvider cannot be null."); string boundary = ValidateArguments(content, maxMessageSize, true); _mimeParser = new MimeMultipartParser(boundary, maxMessageSize); _currentBodyPart = new MimeBodyPart(streamProvider, maxBodyPartHeaderSize); _maxBodyPartHeaderSize = maxBodyPartHeaderSize; _streamProvider = streamProvider; }
// Sealed because derived classes shouldn't override the async version. Override sync version instead. public sealed override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext) { if (type == null) { throw Error.ArgumentNull("type"); } if (writeStream == null) { throw Error.ArgumentNull("writeStream"); } return TaskHelpers.RunSynchronously( () => { using (Stream bufferedStream = GetBufferStream(writeStream, _bufferSizeInBytes)) { WriteToStream(type, value, bufferedStream, content); } }); }
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext) { if (type == null) { throw Error.ArgumentNull("type"); } if (writeStream == null) { throw Error.ArgumentNull("writeStream"); } #if !NETFX_CORE // No DataContractJsonSerializer in portable library version if (UseDataContractJsonSerializer && Indent) { throw Error.NotSupported(Properties.Resources.UnsupportedIndent, typeof(DataContractJsonSerializer)); } #endif try { WriteToStream(type, value, writeStream, content); return TaskHelpers.Completed(); } catch (Exception e) { return TaskHelpers.FromError(e); } }
/// <summary> /// Writes synchronously to the buffered stream. /// </summary> /// <remarks> /// An implementation of this method should close <paramref name="writeStream"/> upon completion. /// </remarks> /// <param name="type">The type of the object to write.</param> /// <param name="value">The object value to write. It may be <c>null</c>.</param> /// <param name="writeStream">The <see cref="Stream"/> to which to write.</param> /// <param name="content">The <see cref="HttpContent"/> if available. Note that /// modifying the headers of the content will have no effect on the generated HTTP message; they should only be used to guide the writing.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> public virtual void WriteToStream(Type type, object value, Stream writeStream, HttpContent content, CancellationToken cancellationToken) { WriteToStream(type, value, writeStream, content); }
public sealed override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger) { return ReadFromStreamAsync(type, readStream, content, formatterLogger, CancellationToken.None); }
/// <summary> /// Constructs a web request to set user-defined metadata for the blob. /// </summary> /// <param name="uri">The absolute URI to the blob.</param> /// <param name="timeout">The server timeout interval.</param> /// <param name="accessCondition">The access condition to apply to the request.</param> /// <returns>A web request for performing the operation.</returns> public static StorageRequestMessage SetMetadata(Uri uri, int?timeout, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials) { StorageRequestMessage request = HttpRequestMessageFactory.SetMetadata(uri, timeout, null /* builder */, content, operationContext, canonicalizer, credentials); request.ApplyAccessCondition(accessCondition); return(request); }
/// <summary> /// Initializes a new instance of the <see cref="MimeMultipartBodyPartParser"/> class. /// </summary> /// <param name="content">An existing <see cref="HttpContent"/> instance to use for the object's content.</param> /// <param name="streamProvider">A stream provider providing output streams for where to write body parts as they are parsed.</param> public MimeMultipartBodyPartParser(HttpContent content, IMultipartStreamProvider streamProvider) : this(content, streamProvider, DefaultMaxMessageSize, DefaultMaxBodyPartHeaderSize) { }
/// <summary> /// Constructs a web request to return the list of blocks for a block blob. /// </summary> /// <param name="uri">The absolute URI to the blob.</param> /// <param name="timeout">The server timeout interval.</param> /// <param name="snapshot">The snapshot timestamp, if the blob is a snapshot.</param> /// <param name="typesOfBlocks">The types of blocks to include in the list: committed, uncommitted, or both.</param> /// <param name="accessCondition">The access condition to apply to the request.</param> /// <returns>A web request to use to perform the operation.</returns> public static StorageRequestMessage GetBlockList(Uri uri, int?timeout, DateTimeOffset?snapshot, BlockListingFilter typesOfBlocks, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials) { UriQueryBuilder builder = new UriQueryBuilder(); builder.Add(Constants.QueryConstants.Component, "blocklist"); builder.Add("blocklisttype", typesOfBlocks.ToString()); BlobHttpRequestMessageFactory.AddSnapshot(builder, snapshot); StorageRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Get, uri, timeout, builder, content, operationContext, canonicalizer, credentials); request.ApplyAccessCondition(accessCondition); return(request); }
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken) { if (type == null) { throw Error.ArgumentNull("type"); } if (writeStream == null) { throw Error.ArgumentNull("writeStream"); } if (cancellationToken.IsCancellationRequested) { return TaskHelpers.Canceled(); } try { WriteToStream(type, value, writeStream, content); return TaskHelpers.Completed(); } catch (Exception e) { return TaskHelpers.FromError(e); } }
/// <summary> /// Constructs a web request to write a block to a block blob. /// </summary> /// <param name="uri">The absolute URI to the blob.</param> /// <param name="timeout">The server timeout interval.</param> /// <param name="blockId">The block ID for this block.</param> /// <param name="accessCondition">The access condition to apply to the request.</param> /// <returns>A web request to use to perform the operation.</returns> public static StorageRequestMessage PutBlock(Uri uri, int?timeout, string blockId, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials) { UriQueryBuilder builder = new UriQueryBuilder(); builder.Add(Constants.QueryConstants.Component, "block"); builder.Add("blockid", blockId); StorageRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Put, uri, timeout, builder, content, operationContext, canonicalizer, credentials); request.ApplyLeaseId(accessCondition); return(request); }
/// <summary> /// Constructs a web request to create or update a blob by committing a block list. /// </summary> /// <param name="uri">The absolute URI to the blob.</param> /// <param name="timeout">The server timeout interval.</param> /// <param name="properties">The properties to set for the blob.</param> /// <param name="accessCondition">The access condition to apply to the request.</param> /// <returns>A web request for performing the operation.</returns> public static StorageRequestMessage PutBlockList(Uri uri, int?timeout, BlobProperties properties, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials) { UriQueryBuilder builder = new UriQueryBuilder(); builder.Add(Constants.QueryConstants.Component, "blocklist"); StorageRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Put, uri, timeout, builder, content, operationContext, canonicalizer, credentials); if (properties != null) { request.AddOptionalHeader(Constants.HeaderConstants.BlobCacheControlHeader, properties.CacheControl); request.AddOptionalHeader(Constants.HeaderConstants.BlobContentTypeHeader, properties.ContentType); request.AddOptionalHeader(Constants.HeaderConstants.BlobContentMD5Header, properties.ContentMD5); request.AddOptionalHeader(Constants.HeaderConstants.BlobContentLanguageHeader, properties.ContentLanguage); request.AddOptionalHeader(Constants.HeaderConstants.BlobContentEncodingHeader, properties.ContentEncoding); request.AddOptionalHeader(Constants.HeaderConstants.BlobContentDispositionRequestHeader, properties.ContentDisposition); } request.ApplyAccessCondition(accessCondition); return(request); }
/// <summary> /// Generates a web request to use to acquire, renew, change, release or break the lease for the blob. /// </summary> /// <param name="uri">The absolute URI to the blob.</param> /// <param name="timeout">The server timeout interval, in seconds.</param> /// <param name="action">The lease action to perform.</param> /// <param name="proposedLeaseId">A lease ID to propose for the result of an acquire or change operation, /// or null if no ID is proposed for an acquire operation. This should be null for renew, release, and break operations.</param> /// <param name="leaseDuration">The lease duration, in seconds, for acquire operations. /// If this is -1 then an infinite duration is specified. This should be null for renew, change, release, and break operations.</param> /// <param name="leaseBreakPeriod">The amount of time to wait, in seconds, after a break operation before the lease is broken. /// If this is null then the default time is used. This should be null for acquire, renew, change, and release operations.</param> /// <param name="accessCondition">The access condition to apply to the request.</param> /// <returns>A web request to use to perform the operation.</returns> public static StorageRequestMessage Lease(Uri uri, int?timeout, LeaseAction action, string proposedLeaseId, int?leaseDuration, int?leaseBreakPeriod, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials) { UriQueryBuilder builder = new UriQueryBuilder(); builder.Add(Constants.QueryConstants.Component, "lease"); StorageRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Put, uri, timeout, builder, content, operationContext, canonicalizer, credentials); request.ApplyAccessCondition(accessCondition); // Add lease headers BlobHttpRequestMessageFactory.AddLeaseAction(request, action); BlobHttpRequestMessageFactory.AddLeaseDuration(request, leaseDuration); BlobHttpRequestMessageFactory.AddProposedLeaseId(request, proposedLeaseId); BlobHttpRequestMessageFactory.AddLeaseBreakPeriod(request, leaseBreakPeriod); return(request); }
/// <summary> /// Constructs a web request to create a snapshot of a blob. /// </summary> /// <param name="uri">The absolute URI to the blob.</param> /// <param name="timeout">The server timeout interval.</param> /// <param name="accessCondition">The access condition to apply to the request.</param> /// <returns>A web request to use to perform the operation.</returns> public static StorageRequestMessage Snapshot(Uri uri, int?timeout, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials) { UriQueryBuilder builder = new UriQueryBuilder(); builder.Add(Constants.QueryConstants.Component, "snapshot"); StorageRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Put, uri, timeout, builder, content, operationContext, canonicalizer, credentials); request.ApplyAccessCondition(accessCondition); return(request); }
/// <summary> /// Constructs a web request to delete a blob. /// </summary> /// <param name="uri">The absolute URI to the blob.</param> /// <param name="timeout">The server timeout interval.</param> /// <param name="snapshot">The snapshot timestamp, if the blob is a snapshot.</param> /// <param name="deleteSnapshotsOption">A set of options indicating whether to delete only blobs, only snapshots, or both.</param> /// <param name="accessCondition">The access condition to apply to the request.</param> /// <returns>A web request to use to perform the operation.</returns> public static StorageRequestMessage Delete(Uri uri, int?timeout, DateTimeOffset?snapshot, DeleteSnapshotsOption deleteSnapshotsOption, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials) { if ((snapshot != null) && (deleteSnapshotsOption != DeleteSnapshotsOption.None)) { throw new InvalidOperationException(string.Format(SR.DeleteSnapshotsNotValidError, "deleteSnapshotsOption", "snapshot")); } UriQueryBuilder builder = new UriQueryBuilder(); BlobHttpRequestMessageFactory.AddSnapshot(builder, snapshot); StorageRequestMessage request = HttpRequestMessageFactory.Delete(uri, timeout, builder, content, operationContext, canonicalizer, credentials); switch (deleteSnapshotsOption) { case DeleteSnapshotsOption.None: break; // nop case DeleteSnapshotsOption.IncludeSnapshots: request.Headers.Add( Constants.HeaderConstants.DeleteSnapshotHeader, Constants.HeaderConstants.IncludeSnapshotsValue); break; case DeleteSnapshotsOption.DeleteSnapshotsOnly: request.Headers.Add( Constants.HeaderConstants.DeleteSnapshotHeader, Constants.HeaderConstants.SnapshotsOnlyValue); break; } request.ApplyAccessCondition(accessCondition); return(request); }
internal HttpContentHeaders (HttpContent content) : base (HttpHeaderKind.Content) { this.content = content; }
/// <summary> /// Constructs a web request to write or clear a range of pages in a page blob. /// </summary> /// <param name="uri">The absolute URI to the blob.</param> /// <param name="timeout">The server timeout interval.</param> /// <param name="properties">The blob's properties.</param> /// <param name="accessCondition">The access condition to apply to the request.</param> /// <returns>A web request to use to perform the operation.</returns> public static StorageRequestMessage PutPage(Uri uri, int?timeout, PageRange pageRange, PageWrite pageWrite, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials) { UriQueryBuilder builder = new UriQueryBuilder(); builder.Add(Constants.QueryConstants.Component, "page"); StorageRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Put, uri, timeout, builder, content, operationContext, canonicalizer, credentials); request.Headers.Add(Constants.HeaderConstants.RangeHeader, pageRange.ToString()); request.Headers.Add(Constants.HeaderConstants.PageWrite, pageWrite.ToString()); request.ApplyAccessCondition(accessCondition); request.ApplySequenceNumberCondition(accessCondition); return(request); }
public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger) { if (type == null) { throw Error.ArgumentNull("type"); } if (readStream == null) { throw Error.ArgumentNull("readStream"); } try { return Task.FromResult(ReadFromStream(type, readStream, content, formatterLogger)); } catch (Exception e) { return TaskHelpers.FromError<object>(e); } }
/// <summary> /// Generates a web request to copy a blob. /// </summary> /// <param name="uri">The absolute URI to the destination blob.</param> /// <param name="timeout">The server timeout interval.</param> /// <param name="source">The absolute URI to the source blob, including any necessary authentication parameters.</param> /// <param name="sourceAccessCondition">The access condition to apply to the source blob.</param> /// <param name="destAccessCondition">The access condition to apply to the destination blob.</param> /// <returns>A web request to use to perform the operation.</returns> public static StorageRequestMessage CopyFrom(Uri uri, int?timeout, Uri source, AccessCondition sourceAccessCondition, AccessCondition destAccessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials) { StorageRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Put, uri, timeout, null /* builder */, content, operationContext, canonicalizer, credentials); request.Headers.Add(Constants.HeaderConstants.CopySourceHeader, source.AbsoluteUri); request.ApplyAccessCondition(destAccessCondition); request.ApplyAccessConditionToSource(sourceAccessCondition); return(request); }
/// <summary> /// Writes synchronously to the buffered stream. /// </summary> /// <remarks> /// An implementation of this method should close <paramref name="writeStream"/> upon completion. /// </remarks> /// <param name="type">The type of the object to write.</param> /// <param name="value">The object value to write. It may be <c>null</c>.</param> /// <param name="writeStream">The <see cref="Stream"/> to which to write.</param> /// <param name="content">The <see cref="HttpContent"/> if available. Note that /// modifying the headers of the content will have no effect on the generated HTTP message; they should only be used to guide the writing.</param> public virtual void WriteToStream(Type type, object value, Stream writeStream, HttpContent content) { throw Error.NotSupported(Properties.Resources.MediaTypeFormatterCannotWriteSync, GetType().Name); }
/// <summary> /// Called during serialization to write an object of the specified <paramref name="type"/> /// to the specified <paramref name="writeStream"/>. /// </summary> /// <param name="type">The type of object to write.</param> /// <param name="value">The object to write.</param> /// <param name="writeStream">The <see cref="Stream"/> to which to write.</param> /// <param name="content">The <see cref="HttpContent"/> for the content being written.</param> /// <param name="transportContext">The <see cref="TransportContext"/>.</param> /// <returns>A <see cref="Task"/> that will write the value to the stream.</returns> public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext) { if (type == null) { throw Error.ArgumentNull("type"); } if (writeStream == null) { throw Error.ArgumentNull("writeStream"); } #if !NETFX_CORE if (UseDataContractJsonSerializer && Indent) { throw Error.NotSupported(Properties.Resources.UnsupportedIndent, typeof(DataContractJsonSerializer)); } #endif return TaskHelpers.RunSynchronously(() => { Encoding effectiveEncoding = SelectCharacterEncoding(content == null ? null : content.Headers); #if !NETFX_CORE if (UseDataContractJsonSerializer) { if (MediaTypeFormatter.TryGetDelegatingTypeForIQueryableGenericOrSame(ref type)) { if (value != null) { value = MediaTypeFormatter.GetTypeRemappingConstructor(type).Invoke(new object[] { value }); } } DataContractJsonSerializer dataContractSerializer = GetDataContractSerializer(type); using (XmlWriter writer = JsonReaderWriterFactory.CreateJsonWriter(writeStream, effectiveEncoding, ownsStream: false)) { dataContractSerializer.WriteObject(writer, value); } } else #endif { using (JsonTextWriter jsonTextWriter = new JsonTextWriter(new StreamWriter(writeStream, effectiveEncoding)) { CloseOutput = false }) { if (Indent) { jsonTextWriter.Formatting = Newtonsoft.Json.Formatting.Indented; } JsonSerializer jsonSerializer = JsonSerializer.Create(_jsonSerializerSettings); jsonSerializer.Serialize(jsonTextWriter, value); jsonTextWriter.Flush(); } } }); }
/// <summary> /// Called during deserialization to read an object of the specified <paramref name="type"/> /// from the specified <paramref name="readStream"/>. /// </summary> /// <param name="type">The type of object to read.</param> /// <param name="readStream">The <see cref="Stream"/> from which to read.</param> /// <param name="content">The <see cref="HttpContent"/> for the content being read.</param> /// <param name="formatterLogger">The <see cref="IFormatterLogger"/> to log events to.</param> /// <returns>A <see cref="Task"/> whose result will be the object instance that has been read.</returns> public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger) { if (type == null) { throw Error.ArgumentNull("type"); } if (readStream == null) { throw Error.ArgumentNull("readStream"); } return TaskHelpers.RunSynchronously<object>(() => { IEnumerable<KeyValuePair<string, string>> nameValuePairs = ReadFormUrlEncoded(readStream, ReadBufferSize); if (type == typeof(FormDataCollection)) { return new FormDataCollection(nameValuePairs); } if (FormattingUtilities.IsJTokenType(type)) { return FormUrlEncodedJson.Parse(nameValuePairs, _maxDepth); } // Passed us an unsupported type. Should have called CanReadType() first. throw Error.InvalidOperation(Properties.Resources.SerializerCannotSerializeType, GetType().Name, type.Name); }); }
public async Task PostAsync_CallMethod_StreamContent(Uri remoteServer, HttpContent content, byte[] expectedData) { using (var client = new HttpClient()) { content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(expectedData); using (HttpResponseMessage response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } }
/// <summary> /// Constructs a web request to create a new block blob or page blob, or to update the content /// of an existing block blob. /// </summary> /// <param name="uri">The absolute URI to the blob.</param> /// <param name="timeout">The server timeout interval.</param> /// <param name="properties">The properties to set for the blob.</param> /// <param name="blobType">The type of the blob.</param> /// <param name="pageBlobSize">For a page blob, the size of the blob. This parameter is ignored /// for block blobs.</param> /// <param name="accessCondition">The access condition to apply to the request.</param> /// <returns>A web request to use to perform the operation.</returns> public static StorageRequestMessage Put(Uri uri, int?timeout, BlobProperties properties, BlobType blobType, long pageBlobSize, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials) { if (blobType == BlobType.Unspecified) { throw new InvalidOperationException(SR.UndefinedBlobType); } StorageRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Put, uri, timeout, null /* builder */, content, operationContext, canonicalizer, credentials); if (properties.CacheControl != null) { request.Headers.CacheControl = CacheControlHeaderValue.Parse(properties.CacheControl); } if (content != null) { if (properties.ContentType != null) { content.Headers.ContentType = MediaTypeHeaderValue.Parse(properties.ContentType); } if (properties.ContentMD5 != null) { content.Headers.ContentMD5 = Convert.FromBase64String(properties.ContentMD5); } if (properties.ContentLanguage != null) { content.Headers.ContentLanguage.Add(properties.ContentLanguage); } if (properties.ContentEncoding != null) { content.Headers.ContentEncoding.Add(properties.ContentEncoding); } if (properties.ContentDisposition != null) { content.Headers.ContentDisposition = ContentDispositionHeaderValue.Parse(properties.ContentDisposition); } } if (blobType == BlobType.PageBlob) { request.Headers.Add(Constants.HeaderConstants.BlobType, Constants.HeaderConstants.PageBlob); request.Headers.Add(Constants.HeaderConstants.BlobContentLengthHeader, pageBlobSize.ToString(NumberFormatInfo.InvariantInfo)); properties.Length = pageBlobSize; } else if (blobType == BlobType.BlockBlob) { request.Headers.Add(Constants.HeaderConstants.BlobType, Constants.HeaderConstants.BlockBlob); } else { request.Headers.Add(Constants.HeaderConstants.BlobType, Constants.HeaderConstants.AppendBlob); } request.ApplyAccessCondition(accessCondition); return(request); }
/// <summary> /// Constructs a web request to return the user-defined metadata for the blob. /// </summary> /// <param name="uri">The absolute URI to the blob.</param> /// <param name="timeout">The server timeout interval.</param> /// <param name="snapshot">The snapshot timestamp, if the blob is a snapshot.</param> /// <param name="accessCondition">The access condition to apply to the request.</param> /// <returns>A web request for performing the operation.</returns> public static StorageRequestMessage GetMetadata(Uri uri, int?timeout, DateTimeOffset?snapshot, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials) { UriQueryBuilder builder = new UriQueryBuilder(); BlobHttpRequestMessageFactory.AddSnapshot(builder, snapshot); StorageRequestMessage request = HttpRequestMessageFactory.GetMetadata(uri, timeout, builder, content, operationContext, canonicalizer, credentials); request.ApplyAccessCondition(accessCondition); return(request); }
private async Task PostUsingAuthHelper( Uri serverUri, string requestBody, HttpContent requestContent, NetworkCredential credential, bool preAuthenticate) { var handler = new HttpClientHandler(); handler.PreAuthenticate = preAuthenticate; handler.Credentials = credential; using (var client = new HttpClient(handler)) { // Send HEAD request to help bypass the 401 auth challenge for the latter POST assuming // that the authentication will be cached and re-used later when PreAuthenticate is true. var request = new HttpRequestMessage(HttpMethod.Head, serverUri); HttpResponseMessage response; using (response = await client.SendAsync(request)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } // Now send POST request. request = new HttpRequestMessage(HttpMethod.Post, serverUri); request.Content = requestContent; requestContent.Headers.ContentLength = null; request.Headers.TransferEncodingChunked = true; using (response = await client.PostAsync(serverUri, requestContent)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, true, requestBody); } } }
/// <summary> /// Generates a web request to abort a copy operation. /// </summary> /// <param name="uri">The absolute URI to the blob.</param> /// <param name="timeout">The server timeout interval.</param> /// <param name="copyId">The ID string of the copy operation to be aborted.</param> /// <param name="accessCondition">The access condition to apply to the request. /// Only lease conditions are supported for this operation.</param> /// <returns>A web request for performing the operation.</returns> public static StorageRequestMessage AbortCopy(Uri uri, int?timeout, string copyId, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials) { UriQueryBuilder builder = new UriQueryBuilder(); builder.Add(Constants.QueryConstants.Component, "copy"); builder.Add(Constants.QueryConstants.CopyId, copyId); StorageRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Put, uri, timeout, builder, content, operationContext, canonicalizer, credentials); request.Headers.Add(Constants.HeaderConstants.CopyActionHeader, Constants.HeaderConstants.CopyActionAbort); request.ApplyAccessCondition(accessCondition); return(request); }
/// <summary> /// Constructs a web request to set a page blob's sequence number. /// </summary> /// <param name="uri">The absolute URI to the blob.</param> /// <param name="timeout">The server timeout interval.</param> /// <param name="sequenceNumberAction">A value of type <see cref="SequenceNumberAction"/>, indicating the operation to perform on the sequence number.</param> /// <param name="sequenceNumber">The sequence number. Set this parameter to <c>null</c> if this operation is an increment action.</param> /// <param name="accessCondition">The access condition to apply to the request.</param> /// <returns>A web request to use to perform the operation.</returns> public static StorageRequestMessage SetSequenceNumber(Uri uri, int?timeout, SequenceNumberAction sequenceNumberAction, long?sequenceNumber, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials) { CommonUtility.AssertInBounds("sequenceNumberAction", sequenceNumberAction, SequenceNumberAction.Max, SequenceNumberAction.Increment); if (sequenceNumberAction == SequenceNumberAction.Increment) { if (sequenceNumber.HasValue) { throw new ArgumentException(SR.BlobInvalidSequenceNumber, "sequenceNumber"); } } else { CommonUtility.AssertNotNull("sequenceNumber", sequenceNumber); CommonUtility.AssertInBounds("sequenceNumber", sequenceNumber.Value, 0); } UriQueryBuilder builder = new UriQueryBuilder(); builder.Add(Constants.QueryConstants.Component, "properties"); StorageRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Put, uri, timeout, builder, content, operationContext, canonicalizer, credentials); request.Headers.Add(Constants.HeaderConstants.SequenceNumberAction, sequenceNumberAction.ToString()); if (sequenceNumberAction != SequenceNumberAction.Increment) { request.Headers.Add(Constants.HeaderConstants.BlobSequenceNumber, sequenceNumber.Value.ToString()); } request.ApplyAccessCondition(accessCondition); return(request); }
/// <summary> /// Constructs a web request to get the blob's content, properties, and metadata. /// </summary> /// <param name="uri">The absolute URI to the blob.</param> /// <param name="timeout">The server timeout interval.</param> /// <param name="snapshot">The snapshot version, if the blob is a snapshot.</param> /// <param name="accessCondition">The access condition to apply to the request.</param> /// <returns>A web request for performing the operation.</returns> public static StorageRequestMessage Get(Uri uri, int?timeout, DateTimeOffset?snapshot, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials) { UriQueryBuilder builder = new UriQueryBuilder(); if (snapshot.HasValue) { builder.Add("snapshot", Request.ConvertDateTimeToSnapshotString(snapshot.Value)); } StorageRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Get, uri, timeout, builder, content, operationContext, canonicalizer, credentials); request.ApplyAccessCondition(accessCondition); return(request); }
private object ReadFromStreamSync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger, CancellationToken cancellationToken) { object result; HttpContentHeaders contentHeaders = content == null ? null : content.Headers; if (contentHeaders != null && contentHeaders.ContentLength == 0) { result = GetDefaultValueForType(type); } else { using (Stream bufferedStream = GetBufferStream(readStream, _bufferSizeInBytes)) { result = ReadFromStream(type, bufferedStream, content, formatterLogger, cancellationToken); } } return result; }
/// <summary> /// Constructs a web request to return a specified range of the blob's content, together with its properties and metadata. /// </summary> /// <param name="uri">The absolute URI to the blob.</param> /// <param name="timeout">The server timeout interval, in seconds.</param> /// <param name="snapshot">The snapshot version, if the blob is a snapshot.</param> /// <param name="offset">The byte offset at which to begin returning content.</param> /// <param name="count">The number of bytes to return, or null to return all bytes through the end of the blob.</param> /// <param name="accessCondition">The access condition to apply to the request.</param> /// <returns>A web request to use to perform the operation.</returns> public static StorageRequestMessage Get(Uri uri, int?timeout, DateTimeOffset?snapshot, long?offset, long?count, bool rangeContentMD5, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials) { if (offset.HasValue && offset.Value < 0) { CommonUtility.ArgumentOutOfRange("offset", offset); } if (offset.HasValue && rangeContentMD5) { CommonUtility.AssertNotNull("count", count); CommonUtility.AssertInBounds("count", count.Value, 1, Constants.MaxBlockSize); } StorageRequestMessage request = Get(uri, timeout, snapshot, accessCondition, content, operationContext, canonicalizer, credentials); AddRange(request, offset, count); if (offset.HasValue && rangeContentMD5) { request.Headers.Add(Constants.HeaderConstants.RangeContentMD5Header, Constants.HeaderConstants.TrueHeader); } return(request); }
public MockHttpContent(HttpContent innerContent) { InnerContent = innerContent; Headers.ContentType = innerContent.Headers.ContentType; }
/// <summary> /// Creates a web request to set the properties of the service. /// </summary> /// <param name="uri">The absolute URI to the service.</param> /// <param name="timeout">The server timeout interval.</param> /// <returns>A web request to set the service properties.</returns> internal static StorageRequestMessage SetServiceProperties(Uri uri, int?timeout, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials) { return(HttpRequestMessageFactory.SetServiceProperties(uri, timeout, content, operationContext, canonicalizer, credentials)); }
private void WriteToStream(Type type, object value, Stream writeStream, HttpContent content) { Encoding effectiveEncoding = SelectCharacterEncoding(content == null ? null : content.Headers); #if !NETFX_CORE // No DataContractJsonSerializer in portable library version if (UseDataContractJsonSerializer) { if (MediaTypeFormatter.TryGetDelegatingTypeForIQueryableGenericOrSame(ref type)) { if (value != null) { value = MediaTypeFormatter.GetTypeRemappingConstructor(type).Invoke(new object[] { value }); } } DataContractJsonSerializer dataContractSerializer = GetDataContractSerializer(type); using (XmlWriter writer = JsonReaderWriterFactory.CreateJsonWriter(writeStream, effectiveEncoding, ownsStream: false)) { dataContractSerializer.WriteObject(writer, value); } } else #endif { using (JsonTextWriter jsonTextWriter = new JsonTextWriter(new StreamWriter(writeStream, effectiveEncoding)) { CloseOutput = false }) { if (Indent) { jsonTextWriter.Formatting = Newtonsoft.Json.Formatting.Indented; } JsonSerializer jsonSerializer = JsonSerializer.Create(_jsonSerializerSettings); jsonSerializer.Serialize(jsonTextWriter, value); jsonTextWriter.Flush(); } } }
public async Task <T> DeserializeAsync <T>(HttpContent responseContent) { var responseContentString = await responseContent.ReadAsStringAsync(); return(JsonConvert.DeserializeObject <T>(responseContentString)); }
/// <inheritdoc /> public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken) { if (type == null) { throw Error.ArgumentNull("type"); } if (writeStream == null) { throw Error.ArgumentNull("writeStream"); } if (UseDataContractJsonSerializer && Indent) { throw Error.NotSupported(Properties.Resources.UnsupportedIndent, typeof(DataContractJsonSerializer)); } return base.WriteToStreamAsync(type, value, writeStream, content, transportContext, cancellationToken); }
/// <summary> /// Prepares a request to the path and appends the shop's access token header if applicable. /// </summary> protected CloneableRequestMessage PrepareRequestMessage(RequestUri uri, HttpMethod method, HttpContent content = null) { var msg = new CloneableRequestMessage(uri.ToUri(), method, content); msg.Headers.Add("Accept", "application/json"); return(msg); }
private object ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger) { Contract.Assert(type != null); Contract.Assert(readStream != null); HttpContentHeaders contentHeaders = content == null ? null : content.Headers; // If content length is 0 then return default value for this type if (contentHeaders != null && contentHeaders.ContentLength == 0) { return GetDefaultValueForType(type); } // Get the character encoding for the content // Never non-null since SelectCharacterEncoding() throws in error / not found scenarios Encoding effectiveEncoding = SelectCharacterEncoding(contentHeaders); try { return ReadFromStream(type, readStream, effectiveEncoding, formatterLogger); } catch (Exception e) { if (formatterLogger == null) { throw; } formatterLogger.LogError(String.Empty, e); return GetDefaultValueForType(type); } }
/// <summary> /// Executes a request and returns the given type. Throws an exception when the response is invalid. /// Use this method when the expected response is a single line or simple object that doesn't warrant its own class. /// </summary> protected async Task <T> ExecuteRequestAsync <T>(RequestUri uri, HttpMethod method, HttpContent content = null, string rootElement = null) { using (var baseRequestMessage = PrepareRequestMessage(uri, method, content)) { var policyResult = await _ExecutionPolicy.Run(baseRequestMessage, async requestMessage => { // update client for basic authentication var byteArray = Encoding.ASCII.GetBytes($"{_userName}:{_apiKey}"); _Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray)); var request = _Client.SendAsync(requestMessage); using (var response = await request) { var rawResult = await response.Content.ReadAsStringAsync(); //Check for and throw exception when necessary. if (!string.IsNullOrEmpty(rawResult)) { CheckResponseExceptions(response, rawResult); } // This method may fail when the method was Delete, which is intendend. // Delete methods should not be parsing the response JSON and should instead // be using the non-generic ExecuteRequestAsync. var result = JsonConvert.DeserializeObject <T>(rawResult); return(new RequestResult <T>(response, result, rawResult)); } }); return(policyResult); } }
private void WriteToStream(Type type, object value, Stream writeStream, HttpContent content) { Contract.Assert(type != null); Contract.Assert(writeStream != null); Encoding effectiveEncoding = SelectCharacterEncoding(content == null ? null : content.Headers); WriteToStream(type, value, writeStream, effectiveEncoding); }
internal HttpResponseWithExpectedStatusCode(IEnumerable <HttpHeader> headers, HttpContent content, TimeSpan requestDuration) { Headers = headers.ToArray(); Content = content; RequestDuration = requestDuration; }
/// <summary> /// Reads synchronously from the buffered stream. /// </summary> /// <remarks> /// An implementation of this method should close <paramref name="readStream"/> upon completion. /// </remarks> /// <param name="type">The type of the object to deserialize.</param> /// <param name="readStream">The <see cref="Stream"/> to read.</param> /// <param name="content">The <see cref="HttpContent"/> if available.</param> /// <param name="formatterLogger">The <see cref="IFormatterLogger"/> to log events to.</param> /// <returns>An object of the given type.</returns> public virtual object ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger) { throw Error.NotSupported(Properties.Resources.MediaTypeFormatterCannotReadSync, GetType().Name); }
public Task <HttpResponseMessage> PostAsync(string url, HttpContent content) { return(Task.Run(() => new HttpResponseMessage(System.Net.HttpStatusCode.InternalServerError))); }
public sealed override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger) { if (type == null) { throw Error.ArgumentNull("type"); } if (readStream == null) { throw Error.ArgumentNull("readStream"); } return TaskHelpers.RunSynchronously<object>( () => { HttpContentHeaders contentHeaders = content == null ? null : content.Headers; if (contentHeaders != null && contentHeaders.ContentLength == 0) { return GetDefaultValueForType(type); } using (Stream bufferedStream = GetBufferStream(readStream, _bufferSizeInBytes)) { return ReadFromStream(type, bufferedStream, content, formatterLogger); } }); }
public static Task <HttpResponseMessage> PatchAsync(Guid requestId, string url, HttpContent content, HttpRequest originRequest) { var request = new HttpRequestMessage { Method = new HttpMethod("PATCH"), RequestUri = new Uri(url), Content = content }; return(SendAndLogAsync(requestId, request, originRequest)); }
private static string ValidateArguments(HttpContent content, long maxMessageSize, bool throwOnError) { Contract.Assert(content != null, "content cannot be null."); if (maxMessageSize < MimeMultipartParser.MinMessageSize) { if (throwOnError) { throw new ArgumentOutOfRangeException("maxMessageSize", maxMessageSize, RS.Format(Properties.Resources.ArgumentMustBeGreaterThanOrEqualTo, MimeMultipartParser.MinMessageSize)); } else { return null; } } MediaTypeHeaderValue contentType = content.Headers.ContentType; if (contentType == null) { if (throwOnError) { throw new ArgumentException(RS.Format(Properties.Resources.ReadAsMimeMultipartArgumentNoContentType, typeof(HttpContent).Name, "multipart/"), "content"); } else { return null; } } if (!contentType.MediaType.StartsWith("multipart", StringComparison.OrdinalIgnoreCase)) { if (throwOnError) { throw new ArgumentException(RS.Format(Properties.Resources.ReadAsMimeMultipartArgumentNoMultipart, typeof(HttpContent).Name, "multipart/"), "content"); } else { return null; } } string boundary = null; foreach (NameValueHeaderValue p in contentType.Parameters) { if (p.Name.Equals("boundary", StringComparison.OrdinalIgnoreCase)) { boundary = FormattingUtilities.UnquoteToken(p.Value); break; } } if (boundary == null) { if (throwOnError) { throw new ArgumentException(RS.Format(Properties.Resources.ReadAsMimeMultipartArgumentNoBoundary, typeof(HttpContent).Name, "multipart", "boundary"), "content"); } else { return null; } } return boundary; }
public static async Task <HttpResponseMessage> CRMWebAPIRequest(string apiRequest, HttpContent requestContent, string requestType) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; AuthenticationContext authContext = new AuthenticationContext(WebConfigurationManager.AppSettings["adOath2AuthEndpoint"], false); UserCredential credentials = new UserCredential(WebConfigurationManager.AppSettings["crmUsername"], WebConfigurationManager.AppSettings["crmPassword"]); AuthenticationResult tokenResult = authContext.AcquireToken(WebConfigurationManager.AppSettings["crmUri"], WebConfigurationManager.AppSettings["adClientId"], credentials); HttpResponseMessage apiResponse; using (HttpClient httpClient = new HttpClient()) { httpClient.BaseAddress = new Uri(WebConfigurationManager.AppSettings["crmUri"]); httpClient.Timeout = new TimeSpan(0, 2, 0); httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0"); httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0"); httpClient.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.AccessToken); if (requestType == "retrieve") { apiResponse = await httpClient.GetAsync(apiRequest); } else if (requestType == "create") { apiResponse = await httpClient.PostAsync(apiRequest, requestContent); } else { apiResponse = null; } } return(apiResponse); }
protected async Task <ResultServiceModel <T> > Post <T>(string url, object model) where T : class { StartMethod: ResultServiceModel <T> resultService = new ResultServiceModel <T>(); try { HttpClient client = new HttpClient(); string token = ""; try { token = await SecureStorage.GetAsync("Token"); } catch (Exception e) { throw e; } client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token); HttpContent content = GetHttpContent(model); var result = await client.PostAsync(url, content); if (result.IsSuccessStatusCode) { var json_result = await result.Content.ReadAsStringAsync(); T obj = GetModelFormResult <T>(json_result); resultService.IsError = false; resultService.Model = obj; return(resultService); } else if (result.StatusCode == System.Net.HttpStatusCode.Unauthorized) { try { var tokenData = await _tokenService.GetAccessToken(); if (tokenData != null || !tokenData.IsError) { if (tokenData.Model == null || tokenData.Model.Token == null) { CloseApp(); } await SecureStorage.SetAsync("Token", tokenData.Model.Token); goto StartMethod; } else { CloseApp(); } } catch (Exception e) { CloseApp(); } } else { client.Dispose(); resultService.IsError = true; } } catch (Exception e) { resultService.IsError = true; } return(resultService); }
public async Task <T> DeserializeAsync <T>(HttpContent content) { using Stream utf8Json = await content.ReadAsStreamAsync(); return(await JsonSerializer.DeserializeAsync <T>(utf8Json, this.serializerOptions)); }
/// <summary> /// Called during deserialization to read an object of the specified <paramref name="type"/> /// from the specified <paramref name="readStream"/>. /// </summary> /// <param name="type">The type of object to read.</param> /// <param name="readStream">The <see cref="Stream"/> from which to read.</param> /// <param name="content">The <see cref="HttpContent"/> for the content being written.</param> /// <param name="formatterLogger">The <see cref="IFormatterLogger"/> to log events to.</param> /// <returns>A <see cref="Task"/> whose result will be the object instance that has been read.</returns> public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger) { if (type == null) { throw Error.ArgumentNull("type"); } if (readStream == null) { throw Error.ArgumentNull("readStream"); } return TaskHelpers.RunSynchronously<object>(() => { HttpContentHeaders contentHeaders = content == null ? null : content.Headers; // If content length is 0 then return default value for this type if (contentHeaders != null && contentHeaders.ContentLength == 0) { return GetDefaultValueForType(type); } // Get the character encoding for the content Encoding effectiveEncoding = SelectCharacterEncoding(contentHeaders); try { #if !NETFX_CORE if (UseDataContractJsonSerializer) { DataContractJsonSerializer dataContractSerializer = GetDataContractSerializer(type); using (XmlReader reader = JsonReaderWriterFactory.CreateJsonReader(new NonClosingDelegatingStream(readStream), effectiveEncoding, _readerQuotas, null)) { return dataContractSerializer.ReadObject(reader); } } else #endif { using (JsonTextReader jsonTextReader = new JsonTextReader(new StreamReader(readStream, effectiveEncoding)) { CloseInput = false, MaxDepth = _maxDepth }) { JsonSerializer jsonSerializer = JsonSerializer.Create(_jsonSerializerSettings); if (formatterLogger != null) { // Error must always be marked as handled // Failure to do so can cause the exception to be rethrown at every recursive level and overflow the stack for x64 CLR processes jsonSerializer.Error += (sender, e) => { Exception exception = e.ErrorContext.Error; formatterLogger.LogError(e.ErrorContext.Path, exception); e.ErrorContext.Handled = true; }; } return jsonSerializer.Deserialize(jsonTextReader, type); } } } catch (Exception e) { if (formatterLogger == null) { throw; } formatterLogger.LogError(String.Empty, e); return GetDefaultValueForType(type); } }); }
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return(sample); }
private async Task PostHelper( Uri serverUri, string requestBody, HttpContent requestContent, bool useContentLengthUpload, bool useChunkedEncodingUpload) { using (var client = new HttpClient()) { if (!useContentLengthUpload && requestContent != null) { requestContent.Headers.ContentLength = null; } if (useChunkedEncodingUpload) { client.DefaultRequestHeaders.TransferEncodingChunked = true; } using (HttpResponseMessage response = await client.PostAsync(serverUri, requestContent)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); if (!useContentLengthUpload && !useChunkedEncodingUpload) { useChunkedEncodingUpload = true; } TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, useChunkedEncodingUpload, requestBody); } } }
internal async Task <TResponse> ExecuteAsync <TResponse>(HttpContent httpContent, CancellationToken cancellationToken = default) where TResponse : class { using var response = await Api.SendAsync(Config, httpContent, cancellationToken).ConfigureAwait(false); return(await ReadAsync <TResponse>(response, cancellationToken).ConfigureAwait(false)); }
/// <summary> /// Constructs a web request to return the list of page ranges that differ between a specified snapshot and this object. /// </summary> /// <param name="uri">The absolute URI to the blob.</param> /// <param name="timeout">The server timeout interval.</param> /// <param name="snapshot">The snapshot timestamp, if the blob is a snapshot.</param> /// <param name="previousSnapshotTime">A <see cref="DateTimeOffset"/> representing the snapshot timestamp to use as the starting point for the diff. If this CloudPageBlob represents a snapshot, the previousSnapshotTime parameter must be prior to the current snapshot timestamp.</param> /// <param name="offset">The starting offset of the data range over which to list page ranges, in bytes. Must be a multiple of 512.</param> /// <param name="count">The length of the data range over which to list page ranges, in bytes. Must be a multiple of 512.</param> /// <param name="accessCondition">The access condition to apply to the request.</param> /// <param name="operationContext">An <see cref="OperationContext"/> object that represents the context for the current operation.</param> /// <returns>A web request to use to perform the operation.</returns> public static StorageRequestMessage GetPageRangesDiff(Uri uri, int?timeout, DateTimeOffset?snapshot, DateTimeOffset previousSnapshotTime, long?offset, long?count, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials) { if (offset.HasValue) { CommonUtility.AssertNotNull("count", count); } UriQueryBuilder builder = new UriQueryBuilder(); builder.Add(Constants.QueryConstants.Component, "pagelist"); BlobHttpRequestMessageFactory.AddSnapshot(builder, snapshot); builder.Add("prevsnapshot", Request.ConvertDateTimeToSnapshotString(previousSnapshotTime)); StorageRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Get, uri, timeout, builder, content, operationContext, canonicalizer, credentials); AddRange(request, offset, count); request.ApplyAccessCondition(accessCondition); return(request); }
private void WriteToStreamSync(Type type, object value, Stream writeStream, HttpContent content, CancellationToken cancellationToken) { using (Stream bufferedStream = GetBufferStream(writeStream, _bufferSizeInBytes)) { WriteToStream(type, value, bufferedStream, content, cancellationToken); } }
/// <summary> /// Initializes a new instance of the CrmHttpResponseException class. /// </summary> /// <param name="content">The populated HTTP content in Json format.</param> /// <param name="innerexception">The exception that is the cause of the current exception, or a null reference /// if no inner exception is specified.</param> public CrmHttpResponseException(HttpContent content, Exception innerexception) : base(ExtractMessageFromContent(content), innerexception) { }
/// <summary> /// Constructs a web request to resize a page blob. /// </summary> /// <param name="uri">The absolute URI to the blob.</param> /// <param name="timeout">The server timeout interval.</param> /// <param name="newBlobSize">The new blob size, if the blob is a page blob. Set this parameter to <c>null</c> to keep the existing blob size.</param> /// <param name="accessCondition">The access condition to apply to the request.</param> /// <returns>A web request to use to perform the operation.</returns> public static StorageRequestMessage Resize(Uri uri, int?timeout, long newBlobSize, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials) { UriQueryBuilder builder = new UriQueryBuilder(); builder.Add(Constants.QueryConstants.Component, "properties"); StorageRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Put, uri, timeout, builder, content, operationContext, canonicalizer, credentials); request.Headers.Add(Constants.HeaderConstants.BlobContentLengthHeader, newBlobSize.ToString(NumberFormatInfo.InvariantInfo)); request.ApplyAccessCondition(accessCondition); return(request); }