CopyToAsync() public method

public CopyToAsync ( Stream stream ) : System.Threading.Tasks.Task
stream System.IO.Stream
return System.Threading.Tasks.Task
コード例 #1
0
        private Task ConvertStream(HttpContent httpContent, Stream outputStream)
        {
            Task convertTask = new Task(() => {

                var convertSettings = new ConvertSettings {
                    CustomOutputArgs = "-map 0",
                    CustomInputArgs = "-vcodec h264"
                };

                var ffMpeg = new FFMpegConverter();
                ffMpeg.ConvertProgress += FfMpeg_ConvertProgress;
                ffMpeg.LogReceived += FfMpeg_LogReceived;

                //var task = ffMpeg.ConvertLiveMedia(Format.h264, "C:\\Work\\Test\\converted.avi", Format.avi, convertSettings);
                var task = ffMpeg.ConvertLiveMedia(Format.h264, outputStream, Format.mpeg, convertSettings);

                task.Start();

                var ffmpegStream = new FFMPegStream(task);
                var copyTask = httpContent.CopyToAsync(ffmpegStream);
                copyTask.Wait();
                ffmpegStream.Close();

                task.Wait();

                //                ffMpeg.ConvertMedia(@"C:\Work\Test\MyHomeSecureNode\devices\test\video.h264", "C:\\Work\\Test\\converted.avi", Format.avi);

                outputStream.Close();
            });

            convertTask.Start();
            return convertTask;
        }
        private StreamContent ConvertToStreamContent(HttpContent originalContent)
        {
            if (originalContent == null)
            {
                return null;
            }

            StreamContent streamContent = originalContent as StreamContent;

            if (streamContent != null)
            {
                return streamContent;
            }

            MemoryStream ms = new MemoryStream();
            originalContent.CopyToAsync(ms).Wait();

              ms.Position = 0;

            streamContent = new StreamContent(ms);

             foreach (KeyValuePair<string, IEnumerable<string>> header in originalContent.Headers)
            {
                streamContent.Headers.TryAddWithoutValidation(header.Key, header.Value);
            }

            return streamContent;
        }
コード例 #3
0
        private async Task<StreamContent> ConvertToStreamContentAsync(HttpContent originalContent)
        {
            if (originalContent == null)
            {
                return null;
            }

            StreamContent streamContent = originalContent as StreamContent;

            if (streamContent != null)
            {
                return streamContent;
            }

            MemoryStream ms = new MemoryStream();
            await originalContent.CopyToAsync(ms);

            // Reset the stream position back to 0 as in the previous CopyToAsync() call,
            // a formatter for example, could have made the position to be at the end
            ms.Position = 0;

            streamContent = new StreamContent(ms);

            // copy headers from the original content
            foreach (KeyValuePair<string, IEnumerable<string>> header in originalContent.Headers)
            {
                streamContent.Headers.TryAddWithoutValidation(header.Key, header.Value);
            }

            return streamContent;
        }
コード例 #4
0
        private StreamContent ConvertToStreamContent(HttpContent originalContent)
        {
            if (originalContent == null)
            {
                return null;
            }

            var streamContent = originalContent as StreamContent;

            if (streamContent != null)
            {
                return streamContent;
            }

            var ms = new MemoryStream();

            // **** NOTE: ideally you should NOT be doing calling Wait() as its going to block this thread ****
            // if the original content is an ObjectContent, then this particular CopyToAsync() call would cause the MediaTypeFormatters to
            // take part in Serialization of the ObjectContent and the result of this serialization is stored in the provided target memory stream.
            originalContent.CopyToAsync(ms).Wait();

            ms.Position = 0;

            streamContent = new StreamContent(ms);

            // copy headers from the original content
            foreach (KeyValuePair<string, IEnumerable<string>> header in originalContent.Headers)
            {
                streamContent.Headers.TryAddWithoutValidation(header.Key, header.Value);
            }

            return streamContent;
        }
コード例 #5
0
        protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
        {
            // Reset stream to start position
            _content.Position = _start;

            // Copy result to output
            return(_byteRangeContent.CopyToAsync(stream));
        }
コード例 #6
0
            /// <summary>Initiate a new copy from the HttpContent to this stream. This is not thread-safe.</summary>
            internal void Run()
            {
                Debug.Assert(!Monitor.IsEntered(_syncObj), "Should not be invoked while holding the lock");
                Debug.Assert(_copyTask == null, "Should only be invoked after construction or a reset");

                // Start the copy and store the task to represent it.
                _copyTask = _content.CopyToAsync(this, _transportContext);

                // Fix up the instance when it's done
                _copyTask.ContinueWith((t, s) => ((HttpContentAsyncStream)s).EndCopyToAsync(t), this,
                                       CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
            }
コード例 #7
0
        public async Task <Image> GetImage(string name, bool min, bool save = false)
        {
            bool success = false;

            using (var client = new HttpClient())
            {
                string url = Secrets.ApiAddress + $"GetAttachment?token=" + Secrets.TenantToken + "&name=" + name + "&min=" + min;
                using (var response = await client.GetAsync(new Uri(url)))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        System.Net.Http.HttpContent content = response.Content;
                        var stream = Bitmap.FromStream(await response.Content.ReadAsStreamAsync());

                        if (save)
                        {
                            FileStream fileStream = null;
                            try
                            {
                                string path = Path.Combine(RuntimeSettings.LocalFilesPath, name);
                                fileStream = new FileStream(path, FileMode.Create, FileAccess.ReadWrite);
                                await content.CopyToAsync(fileStream).ContinueWith(
                                    (copyTask) =>
                                {
                                    fileStream.Close();
                                });

                                success = true;
                            }
                            catch
                            {
                                if (fileStream != null)
                                {
                                    fileStream.Close();
                                }

                                throw;
                            }
                        }

                        return(stream);
                    }
                    return(null);
                }
            }
        }
コード例 #8
0
            /// <summary>
            /// Initiates a new CopyToAsync from the HttpContent to this stream, and should only be called when the caller
            /// can be sure that no one else is accessing the stream or attempting to initiate a copy.
            /// </summary>
            private Task StartCopyToAsync()
            {
                Debug.Assert(!Monitor.IsEntered(_syncObj), "Should not be invoked while holding the lock");
                Debug.Assert(_copyTask == null, "Should only be invoked after construction or a reset");

                // Transfer the data from the content to this stream
                try
                {
                    VerboseTrace("Initiating new CopyToAsync");
                    return(_content.CopyToAsync(this));
                }
                catch (Exception exc)
                {
                    // CopyToAsync allows some exceptions to propagate synchronously, including exceptions
                    // indicating that a stream can't be re-copied.
                    return(Task.FromException(exc));
                }
            }
コード例 #9
0
            /// <summary>Initiate a new copy from the HttpContent to this stream. This is not thread-safe.</summary>
            internal void Run()
            {
                Debug.Assert(!Monitor.IsEntered(_syncObj), "Should not be invoked while holding the lock");
                Debug.Assert(_copyTask == null, "Should only be invoked after construction or a reset");

                // Start the copy and store the task to represent it. In the rare case that the synchronous
                // call to CopyToAsync may block writing to this stream synchronously (e.g. if the
                // SerializeToStreamAsync called by CopyToAsync did a synchronous Write on this stream) we
                // need to ensure that doesn't cause a deadlock. So, we invoke CopyToAsync asynchronously.
                // This purposefully uses Task.Run this way rather than StartNew with object state because
                // the latter would need to use a separate call to Unwrap, which is more expensive than the
                // single extra delegate allocation (no closure allocation) we'll get here along with
                // Task.Run's very efficient unwrapping implementation.
                _copyTask = Task.Run(() => _content.CopyToAsync(this));

                // Fix up the instance when it's done
                _copyTask.ContinueWith((t, s) => ((HttpContentAsyncStream)s).EndCopyToAsync(t), this,
                                       CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
            }
コード例 #10
0
ファイル: HMACHelper.cs プロジェクト: SamStrong/WebAPI.HMAC
        private static byte[] ComputeHash(HttpContent httpContent)
        {
            using (var md5 = MD5.Create())
            {
                byte[] hash = null;
                if (httpContent != null)
                {
                    var ms = new MemoryStream();
                    httpContent.CopyToAsync(ms).Wait();
                    ms.Seek(0, SeekOrigin.Begin);

                    var content = ms.ToArray();
                    if (content.Length != 0)
                    {
                        hash = md5.ComputeHash(content);
                    }
                }
                return hash;
            }
        }
コード例 #11
0
        internal static async Task WriteBufferedResponseContentAsync(HttpContextBase httpContextBase, HttpContent responseContent, HttpRequestMessage request)
        {
            Contract.Assert(httpContextBase != null);
            Contract.Assert(responseContent != null);
            Contract.Assert(request != null);

            HttpResponseBase httpResponseBase = httpContextBase.Response;

            // Return a task that writes the response body asynchronously.
            // We guarantee we will handle all error responses internally
            // and always return a non-faulted task.
            Exception exception = null;
            try
            {
                // Copy the HttpContent into the output stream asynchronously.
                await responseContent.CopyToAsync(httpResponseBase.OutputStream);
            }
            catch (Exception e)
            {
                // Can't use await inside a catch block
                exception = e;
            }

            if (exception != null)
            {
                // If we were using a buffered stream, we can still set the headers and status
                // code, and we can create an error response with the exception.
                // We create a continuation task to write an error response that will run after
                // returning from this Catch() but before other continuations the caller appends to this task.
                // The error response writing task handles errors internally and will not show as faulted.
                await CreateErrorResponseAsync(httpContextBase, responseContent, request, exception);
            }
        }
コード例 #12
0
        internal static async Task WriteStreamedResponseContentAsync(HttpResponseBase httpResponseBase, HttpContent responseContent)
        {
            Contract.Assert(httpResponseBase != null);
            Contract.Assert(responseContent != null);

            try
            {
                // Copy the HttpContent into the output stream asynchronously.
                await responseContent.CopyToAsync(httpResponseBase.OutputStream);
            }
            catch
            {
                // Streamed content may have been written and cannot be recalled.
                // Our only choice is to abort the connection.
                AbortConnection(httpResponseBase);
            }
        }
コード例 #13
0
        /// <summary>
        /// The read as file async.
        /// </summary>
        /// <param name="content">The content.</param>
        /// <param name="filename">The filename.</param>
        /// <param name="overwrite">The overwrite.</param>
        /// <returns>
        /// The <see cref="Task" />.
        /// </returns>
        /// <remarks>Taken from <see href="http://blogs.msdn.com/b/henrikn/archive/2012/02/17/downloading-a-google-map-to-local-file.aspx" />.</remarks>
        private async Task ReadAsFileAsync(HttpContent content, string filename, bool overwrite)
        {
            var pathname = Path.GetFullPath(filename);
            if (!overwrite && File.Exists(filename))
            {
                throw new InvalidOperationException(string.Format("File {0} already exists.", pathname));
            }

            FileStream fileStream = null;
            try
            {
                fileStream = new FileStream(pathname, FileMode.Create, FileAccess.Write, FileShare.None);
                await content.CopyToAsync(fileStream).ContinueWith((copyTask) => { fileStream.Close(); });
            }
            catch
            {
                if (fileStream != null)
                {
                    fileStream.Close();
                }

                throw;
            }
        }
コード例 #14
0
        internal static Task WriteBufferedResponseContentAsync(HttpContextBase httpContextBase, HttpContent responseContent, HttpRequestMessage request)
        {
            Contract.Assert(httpContextBase != null);
            Contract.Assert(responseContent != null);
            Contract.Assert(request != null);

            HttpResponseBase httpResponseBase = httpContextBase.Response;
            Task writeResponseContentTask = null;

            try
            {
                // Copy the HttpContent into the output stream asynchronously.
                writeResponseContentTask = responseContent.CopyToAsync(httpResponseBase.OutputStream);
            }
            catch (Exception ex)
            {
                // Immediate exception requires an error response.
                // Create a faulted task to share the code below
                writeResponseContentTask = TaskHelpers.FromError(ex);
            }

            // Return a task that writes the response body asynchronously.
            // We guarantee we will handle all error responses internally
            // and always return a non-faulted task.
            return writeResponseContentTask
                .Catch((info) =>
                {
                    // If we were using a buffered stream, we can still set the headers and status
                    // code, and we can create an error response with the exception.
                    // We create a continuation task to write an error response that will run after
                    // returning from this Catch() but before other continuations the caller appends to this task.
                    // The error response writing task handles errors internally and will not show as faulted.
                    Task writeErrorResponseTask = CreateErrorResponseAsync(httpContextBase, responseContent, request, info.Exception);
                    return info.Task(writeErrorResponseTask);
                });
        }
コード例 #15
0
        internal static Task WriteStreamedResponseContentAsync(HttpResponseBase httpResponseBase, HttpContent responseContent)
        {
            Contract.Assert(httpResponseBase != null);
            Contract.Assert(responseContent != null);

            Task writeResponseContentTask = null;

            try
            {
                // Copy the HttpContent into the output stream asynchronously.
                writeResponseContentTask = responseContent.CopyToAsync(httpResponseBase.OutputStream);
            }
            catch
            {
                // Streamed content may have been written and cannot be recalled.
                // Our only choice is to abort the connection.
                AbortConnection(httpResponseBase);
                return TaskHelpers.Completed();
            }

            return writeResponseContentTask
                .Catch((info) =>
                {
                    // Streamed content may have been written and cannot be recalled.
                    // Our only choice is to abort the connection.
                    AbortConnection(httpResponseBase);
                    return info.Handled();
                });
        }
コード例 #16
0
 /// <summary>
 ///     Serialize the HTTP content into a stream of bytes and copies it to the stream
 ///      object provided as the stream parameter.
 /// </summary>
 /// <param name="stream">The target stream.</param>
 public static void CopyTo(this HttpContent content, Stream stream)
 {
     Task.Run(() => content.CopyToAsync(stream)).Wait();
 }