Ejemplo n.º 1
0
        public static async Task FormatHttpContentAsync(StringBuilder sb, HttpContent content)
        {
            if (content.Headers != null)
            {
                foreach (var header in content.Headers)
                {
                    sb.AppendLine(string.Format("{0} : {1}", header.Key, header.Value.First()));
                }
            }

            await content.LoadIntoBufferAsync().ConfigureAwait(false);

            bool isMultipart = content.IsMimeMultipartContent();

            if (isMultipart)
            {
                //TODO: for some reason it hangs when trying to read the multi-part.  might have something to do with UI thread :(

                //MultipartMemoryStreamProvider provider = await content.ReadAsMultipartAsync();

                //TODO: for now format just the first part.  We will need to figure out what to do with the remain
                //parts so that it doesnt break viewer
                //content = provider.Contents.First() as StreamContent;
            }
            var sw     = new StringWriter(sb);
            var writer = new JsonTextWriter(sw)
            {
                Formatting  = Formatting.Indented,
                Indentation = 4,
                IndentChar  = ' '
            };

            string contentBody = await content.ReadAsStringAsync().ConfigureAwait(false);

            try
            {
                var jsonSerializer = new JsonSerializer();
                var reader         = new JsonTextReader(new StringReader(contentBody));

                object obj = jsonSerializer.Deserialize(reader);
                if (obj != null)
                {
                    jsonSerializer.Serialize(writer, obj);
                }
                else
                {
                    sb.AppendLine(contentBody);
                }
            }
            catch (Exception ex)
            {
                sb.AppendLine(contentBody);
                Logger.Instance.Warning("JsonWriter failed with ex: " + ex.ToString());
            }
            finally
            {
                writer.Close();
                sw.Close();
            }
        }
        private static async Task BufferRequestBodyAsync(IOwinRequest owinRequest, HttpContent content)
        {
            await content.LoadIntoBufferAsync();

            // We need to replace the request body with a buffered stream so that other
            // components can read the stream
            owinRequest.Body = await content.ReadAsStreamAsync();
        }
Ejemplo n.º 3
0
        private static async Task BufferRequestBodyAsync(IDictionary <string, object> environment, HttpContent content)
        {
            await content.LoadIntoBufferAsync();

            // We need to replace the request body with a buffered stream so that other
            // components can read the stream
            environment[OwinConstants.RequestBodyKey] = await content.ReadAsStreamAsync();
        }
Ejemplo n.º 4
0
                    protected override BodyWriter OnCreateBufferedCopy(int maxBufferSize)
                    {
                        HttpContent content = this.httpResponseMessage.Content;

                        if (content != null)
                        {
                            content.LoadIntoBufferAsync(maxBufferSize).Wait();
                        }

                        return(base.OnCreateBufferedCopy(maxBufferSize));
                    }
Ejemplo n.º 5
0
        public static async Task <Func <Stream> > WriteToStream(HttpContent content, Stream outputStream,
                                                                int maxBufferSize = int.MaxValue)
        {
            await content.LoadIntoBufferAsync(maxBufferSize);

            await content.CopyToAsync(outputStream);

            outputStream.Position = 0;

            return(() => outputStream);
        }
Ejemplo n.º 6
0
        protected static float GetContentSize(HttpContent content)
        {
            // get content size
            float contentLength = 0.0f;

            if (content != null)
            {
                content.LoadIntoBufferAsync().Wait();
                contentLength = content.Headers.ContentLength.HasValue ?
                                content.Headers.ContentLength.Value / 1024.0f : 0.0f;
            }

            return(contentLength);
        }
Ejemplo n.º 7
0
        public static async Task <HttpContent> Clone(this HttpContent source)
        {
            if (source == null)
            {
                return(null);
            }

            await source.LoadIntoBufferAsync();

            var destination = new ByteArrayContent(await source.ReadAsByteArrayAsync());

            CopyHeadersFrom(destination.Headers, source.Headers);
            return(destination);
        }
Ejemplo n.º 8
0
        private static async Task WriteContentHeadersAndBody(StringWriter sw, HttpContent content)
        {
            if (content != null)
            {
                await content.LoadIntoBufferAsync();

                WriteHeaders(sw, content.Headers);
                sw.WriteLine();
                sw.Write(await content.ReadAsStringAsync());
                sw.WriteLine();
            }
            else
            {
                sw.WriteLine();
            }
        }
        private async Task<StreamContent> GetBufferedStreamContentAsync(HttpContent httpContent)
        {
            await httpContent.LoadIntoBufferAsync();

            var buffer = new MemoryStream();
            await httpContent.CopyToAsync(buffer);
            buffer.Position = 0;

            StreamContent streamContent = new StreamContent(buffer);

            foreach (var header in httpContent.Headers)
            {
                streamContent.Headers.TryAddWithoutValidation(header.Key, header.Value);
            }

            return streamContent;
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Gets the payload size as a human readable string.
        /// </summary>
        /// <param name="content">The content.</param>
        /// <returns>The payload size as a human readable string.</returns>
        public static string SizeAsHumanReadableString(this HttpContent content)
        {
            if (content.Headers.ContentLength.HasValue)
            {
                return(content.Headers.ContentLength.Value.SizeAsHumanReadableString(LongExtensions.SIType.Byte));
            }

            var tcs = new TaskCompletionSource <byte[]>();

            Task.Run(async() =>
            {
                await content.LoadIntoBufferAsync();

                tcs.SetResult(await content.ReadAsByteArrayAsync());
            }).ConfigureAwait(false);

            return(tcs.Task.Result.SizeAsHumanReadableString());
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Deserializes the request content which is assumed to be json into a object of <typeparamref name="T"/>
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="content"></param>
        /// <returns></returns>
        public async Task <T> Deserialize <T>(HttpContent content)
        {
            await content.LoadIntoBufferAsync().ConfigureAwait(false);

            if (_knownJsonPrimitives.ContainsKey(typeof(T)))
            {
                var str = await content.ReadAsStringAsync().ConfigureAwait(false);

                return((T)_knownJsonPrimitives[typeof(T)](str));
            }
            else
            {
                using (var stream = await content.ReadAsStreamAsync().ConfigureAwait(false))
                {
                    return(await System.Text.Json.JsonSerializer.DeserializeAsync <T>(stream, _options).ConfigureAwait(false));
                }
            }
        }
Ejemplo n.º 12
0
        private async Task <string> TryGetContentAsString(HttpContent content, bool silentlyIgnoreExceptions, CancellationToken cancellationToken)
        {
            if (content == null)
            {
                return(null);
            }
            try
            {
                await content.LoadIntoBufferAsync();

                return(await content.ReadAsStringAsync().ConfigureAwait(false));
            }
            catch (Exception e)
            {
                if (!silentlyIgnoreExceptions)
                {
                    throw new FulcrumAssertionFailedException("Expected to be able to read an HttpContent.", e);
                }
            }
            return(null);
        }
Ejemplo n.º 13
0
 /// <inheritdoc />
 public Task LoadIntoBufferAsync()
 {
     return(_content.LoadIntoBufferAsync());
 }
        /// <summary>
        /// Deserializes the request content which is assumed to be MessagePack into a object of <typeparamref name="T"/>
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="content"></param>
        /// <returns></returns>
        public async Task <T> Deserialize <T>(HttpContent content)
        {
            await content.LoadIntoBufferAsync().ConfigureAwait(false);

            return(await MessagePack.MessagePackSerializer.DeserializeAsync <T>(await content.ReadAsStreamAsync().ConfigureAwait(false), ContractlessStandardResolver.Instance));
        }