Пример #1
0
        /// <summary>Opens a writeable stream for uploading data to a resource, asynchronously.</summary>
        /// <param name="webClient">The WebClient.</param>
        /// <param name="address">The URI for which the stream should be opened.</param>
        /// <param name="method">The HTTP method that should be used to open the stream.</param>
        /// <returns>A Task that contains the opened stream.</returns>
        public static Task <Stream> OpenWriteTask(this WebClient webClient, Uri address, string method)
        {
            // Create the task to be returned
            var tcs = new TaskCompletionSource <Stream>(address);

            // Setup the callback event handler
            OpenWriteCompletedEventHandler handler = null;

            handler = (sender, e) => EAPCommon.HandleCompletion(tcs, e, () => e.Result, () => webClient.OpenWriteCompleted -= handler);
            webClient.OpenWriteCompleted += handler;

            // Start the async work
            try
            {
                webClient.OpenWriteAsync(address, method, tcs);
            }
            catch (Exception exc)
            {
                // If something goes wrong kicking off the async work,
                // unregister the callback and cancel the created task
                webClient.OpenWriteCompleted -= handler;
                tcs.TrySetException(exc);
            }

            // Return the task that represents the async operation
            return(tcs.Task);
        }
Пример #2
0
        /// <summary>
        /// Extends BeginInvoke so that when a state object is not needed, null does not need to be passed.
        /// <example>
        /// openwritecompletedeventhandler.BeginInvoke(sender, e, callback);
        /// </example>
        /// </summary>
        public static IAsyncResult BeginInvoke(this OpenWriteCompletedEventHandler openwritecompletedeventhandler, Object sender, OpenWriteCompletedEventArgs e, AsyncCallback callback)
        {
            if (openwritecompletedeventhandler == null)
            {
                throw new ArgumentNullException("openwritecompletedeventhandler");
            }

            return(openwritecompletedeventhandler.BeginInvoke(sender, e, callback, null));
        }
Пример #3
0
        protected virtual void OnOpenWriteCompleted(OpenWriteCompletedEventArgs args)
        {
            CompleteAsync();
            OpenWriteCompletedEventHandler handler = OpenWriteCompleted;

            if (handler != null)
            {
                handler(this, args);
            }
        }
        public static Task UploadDataAsync(this WebClient client, string address, string method, byte[] data)
        {
            var source = new TaskCompletionSource <bool>();

            client.AllowWriteStreamBuffering = true;
            OpenWriteCompletedEventHandler openWriteCompletedHandler = (s, args) =>
            {
                using (var stream = new MemoryStream(data))
                {
                    using (BinaryReader br = new BinaryReader(stream))
                    {
                        using (BinaryWriter bw = new BinaryWriter(args.Result))
                        {
                            long   bCount   = 0;
                            long   fileSize = stream.Length;
                            byte[] bytes    = new byte[BLOCK_SIZE];
                            do
                            {
                                bytes   = br.ReadBytes(BLOCK_SIZE);
                                bCount += bytes.Length;
                                bw.Write(bytes);
                            } while (bCount < fileSize);
                        }
                    }
                }
            };

            WriteStreamClosedEventHandler streamClosedHandler = null;

            streamClosedHandler = (s, args) =>
            {
                if (args.Error != null)
                {
                    source.TrySetException(args.Error);
                }
                else
                {
                    source.TrySetResult(true);
                }

                // Unsubscribe the handlers
                client.OpenWriteCompleted -= openWriteCompletedHandler;
                client.WriteStreamClosed  -= streamClosedHandler;
            };

            client.OpenWriteCompleted += openWriteCompletedHandler;
            client.WriteStreamClosed  += streamClosedHandler;
            client.OpenWriteAsync(new Uri(address), method);
            return(source.Task);
        }
    /// <summary>Opens a writeable stream for uploading data to a resource, asynchronously.</summary>
    /// <param name="webClient">The WebClient.</param>
    /// <param name="address">The URI for which the stream should be opened.</param>
    /// <param name="method">The HTTP method that should be used to open the stream.</param>
    /// <returns>A Task that contains the opened stream.</returns>
    public static Task <Stream> OpenWriteTaskAsync(this WebClient webClient, Uri address, string method)
    {
        // Create the task to be returned
        var tcs = new TaskCompletionSource <Stream>(address);

        // Setup the callback event handler
        OpenWriteCompletedEventHandler handler = null;

        handler = (sender, e) => TaskServices.HandleEapCompletion(tcs, true, e, () => e.Result, () => webClient.OpenWriteCompleted -= handler);
        webClient.OpenWriteCompleted += handler;

        // Start the async operation.
        try { webClient.OpenWriteAsync(address, method, tcs); }
        catch
        {
            webClient.OpenWriteCompleted -= handler;
            throw;
        }

        // Return the task that represents the async operation
        return(tcs.Task);
    }
Пример #6
0
        /// <summary>Opens a writeable stream for uploading data to a resource, asynchronously.</summary>
        /// <param name="webClient">The WebClient.</param>
        /// <param name="address">The URI for which the stream should be opened.</param>
        /// <param name="method">The HTTP method that should be used to open the stream.</param>
        /// <returns>A Task that contains the opened stream.</returns>
        public static Task <Stream> OpenWriteTask(this WebClient webClient, Uri address, string method)
        {
            TaskCompletionSource <Stream>  tcs     = new TaskCompletionSource <Stream>(address);
            OpenWriteCompletedEventHandler handler = null;

            handler = delegate(object sender, OpenWriteCompletedEventArgs e) {
                EAPCommon.HandleCompletion <Stream>(tcs, e, () => e.Result, delegate {
                    webClient.OpenWriteCompleted -= handler;
                });
            };
            webClient.OpenWriteCompleted += handler;
            try
            {
                webClient.OpenWriteAsync(address, method, tcs);
            }
            catch (Exception exception)
            {
                webClient.OpenWriteCompleted -= handler;
                tcs.TrySetException(exception);
            }
            return(tcs.Task);
        }
Пример #7
0
        /// <summary>
        /// <paramref name="address"/>에 비동기적으로 data를 전송하기 위한 쓰기용 Stream을 반환합니다.
        /// </summary>
        /// <param name="webClient">WebClient 인스턴스</param>
        /// <param name="token">작업 취소를 위한 Token</param>
        /// <param name="address">리소스의 주소</param>
        /// <param name="method">전송 방법 : Http인 경우는 POST, FTP인 경우는 STOR입니다.</param>
        /// <returns></returns>
        public static Task <Stream> OpenWriteTask(this WebClient webClient, CancellationToken token, Uri address, string method)
        {
            webClient.ShouldNotBeNull("webClient");
            token.ShouldNotBeNull("token");
            address.ShouldNotBeNull("address");

            if (IsDebugEnabled)
            {
                log.Debug("지정된 주소에 데이타 쓰기용 Stream을 엽니다... address=[{0}], method=[{1}]", address.AbsoluteUri, method);
            }


            var tcs = new TaskCompletionSource <Stream>(address);

            token.Register(webClient.CancelAsync);

            OpenWriteCompletedEventHandler handler = null;

            handler =
                (s, e) => EventAsyncPattern.HandleCompletion(tcs, e, () => e.Result, () => webClient.OpenWriteCompleted -= handler);
            webClient.OpenWriteCompleted += handler;

            try {
                webClient.OpenWriteAsync(address, method, tcs);
            }
            catch (Exception ex) {
                if (log.IsWarnEnabled)
                {
                    log.Warn("WebClient를 이용하여 데이타를 전송하기 위해 쓰기용 Stream을 오픈하는데 실패했습니다. address=[{0}]", address.AbsoluteUri);
                    log.Warn(ex);
                }

                webClient.OpenWriteCompleted -= handler;
                tcs.TrySetException(ex);
            }

            return(tcs.Task);
        }
    public static Task <Stream> OpenWriteTaskAsync(this WebClient webClient, Uri address, string method)
    {
        TaskCompletionSource <Stream>  tcs     = new TaskCompletionSource <Stream>(address);
        OpenWriteCompletedEventHandler handler = null;

        handler = delegate(object sender, OpenWriteCompletedEventArgs e)
        {
            AsyncCompatLibExtensions.HandleEapCompletion <Stream>(tcs, true, e, () => e.Result, delegate
            {
                webClient.OpenWriteCompleted -= handler;
            });
        };
        webClient.OpenWriteCompleted += handler;
        try
        {
            webClient.OpenWriteAsync(address, method, tcs);
        }
        catch
        {
            webClient.OpenWriteCompleted -= handler;
            throw;
        }
        return(tcs.Task);
    }