Example #1
0
        /// <summary>Uploads data in a string to the specified resource, asynchronously.</summary>
        /// <param name="webClient">The WebClient.</param>
        /// <param name="address">The URI to which the data should be uploaded.</param>
        /// <param name="method">The HTTP method that should be used to upload the data.</param>
        /// <param name="data">The data to upload.</param>
        /// <returns>A Task containing the data in the response from the upload.</returns>
        public static Task <string> UploadStringTask(
            this WebClient webClient, Uri address, string method, string data)
        {
            // Create the task to be returned
            var tcs = new TaskCompletionSource <string>(address);

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

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

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

            // Return the task that represents the async operation
            return(tcs.Task);
        }
Example #2
0
        /// <summary>Downloads the resource with the specified URI to a local file, asynchronously.</summary>
        /// <param name="webClient">The WebClient.</param>
        /// <param name="address">The URI from which to download data.</param>
        /// <param name="fileName">The name of the local file that is to receive the data.</param>
        /// <returns>A Task that contains the downloaded data.</returns>
        public static Task DownloadFileTask(this WebClient webClient, Uri address, string fileName)
        {
            // Create the task to be returned
            var tcs = new TaskCompletionSource <object>(address);

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

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

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

            // Return the task that represents the async operation
            return(tcs.Task);
        }
Example #3
0
        private static Task <Stream> OpenReadTaskInternal(WebClient webClient, CancellationToken token, Uri address)
        {
            var tcs = new TaskCompletionSource <Stream>(address);

            token.Register(webClient.CancelAsync);

            OpenReadCompletedEventHandler handler = null;

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

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

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

            return(tcs.Task);
        }
        /// <summary>The core implementation of SendTask.</summary>
        /// <param name="smtpClient">The client.</param>
        /// <param name="userToken">The user-supplied state.</param>
        /// <param name="sendAsync">
        /// A delegate that initiates the asynchronous send.
        /// The provided TaskCompletionSource must be passed as the user-supplied state to the actual SmtpClient.SendAsync method.
        /// </param>
        /// <returns></returns>
        private static Task SendTaskCore(
            SmtpClient smtpClient, object userToken, Action <TaskCompletionSource <object> > sendAsync)
        {
            // Validate we're being used with a real smtpClient.  The rest of the arg validation
            // will happen in the call to sendAsync.
            if (smtpClient == null)
            {
                throw new ArgumentNullException(nameof(smtpClient));
            }

            // Create a TaskCompletionSource to represent the operation
            var tcs = new TaskCompletionSource <object>(userToken);

            // Register a handler that will transfer completion results to the TCS Task
            SendCompletedEventHandler handler = null;

            handler = (sender, e) => EAPCommon.HandleCompletion(tcs, e, () => null, () => smtpClient.SendCompleted -= handler);
            smtpClient.SendCompleted += handler;

            // Try to start the async operation.  If starting it fails (due to parameter validation)
            // unregister the handler before allowing the exception to propagate.
            try
            {
                sendAsync(tcs);
            }
            catch (Exception exc)
            {
                smtpClient.SendCompleted -= handler;
                tcs.TrySetException(exc);
            }

            // Return the task to represent the asynchronous operation
            return(tcs.Task);
        }
Example #5
0
        public static Task <string> PingTask(this DataService client, TaskCompletionSource <string> tcs)
        {
            PingCompletedEventHandler handler = null;

            try {
                handler = (sender, e) => EAPCommon.HandleCompletion(tcs, e, () => e.Result, () => client.PingCompleted -= handler);
                client.PingCompleted += handler;

                client.PingAsync(tcs);
            }
            catch (Exception ex) {
                if (log.IsErrorEnabled)
                {
                    log.ErrorException("웹서비스 비동기 호출에 예외가 발생했습니다.", ex);
                }

                if (handler != null)
                {
                    client.PingCompleted -= handler;
                }

                tcs.TrySetException(ex);
            }
            return(tcs.Task);
        }
Example #6
0
        public static Task <ResponseMessage> ExecuteTask(this DataService client,
                                                         RequestMessage requestMessage,
                                                         string productName,
                                                         TaskCompletionSource <byte[]> tcs)
        {
            client.ShouldNotBeNull("client");
            requestMessage.ShouldNotBeNull("requestMessage");

            try {
                var requestBytes = ResolveRequestSerializer(productName).Serialize(requestMessage);

                ExecuteCompletedEventHandler handler = null;
                handler = (sender, e) => EAPCommon.HandleCompletion(tcs, e, () => e.Result, () => client.ExecuteCompleted -= handler);
                client.ExecuteCompleted += handler;

                client.ExecuteAsync(requestBytes, productName, tcs);


                return
                    (tcs.Task
                     .ContinueWith(task => ResolveResponseSerializer(productName).Deserialize(task.Result)));
            }
            catch (Exception ex) {
                if (log.IsErrorEnabled)
                {
                    log.ErrorException("웹서비스를 통한 요청이 실패했습니다.", ex);
                }

                throw;
            }
        }
        /// <summary>The core implementation of SendTask.</summary>
        /// <param name="smtpClient">The client.</param>
        /// <param name="userToken">The user-supplied state.</param>
        /// <param name="sendAsync">
        /// A delegate that initiates the asynchronous send.
        /// The provided TaskCompletionSource must be passed as the user-supplied state to the actual SmtpClient.SendAsync method.
        /// </param>
        /// <returns></returns>
        private static Task SendTaskCore(SmtpClient smtpClient, object userToken, Action <TaskCompletionSource <object> > sendAsync)
        {
            if (smtpClient == null)
            {
                throw new ArgumentNullException("smtpClient");
            }
            TaskCompletionSource <object> tcs     = new TaskCompletionSource <object>(userToken);
            SendCompletedEventHandler     handler = null;

            handler = delegate(object sender, AsyncCompletedEventArgs e) {
                EAPCommon.HandleCompletion <object>(tcs, e, () => null, delegate {
                    smtpClient.SendCompleted -= handler;
                });
            };
            smtpClient.SendCompleted += handler;
            try
            {
                sendAsync(tcs);
            }
            catch (Exception exception)
            {
                smtpClient.SendCompleted -= handler;
                tcs.TrySetException(exception);
            }
            return(tcs.Task);
        }
Example #8
0
        /// <summary>The core implementation of SendTask.</summary>
        /// <param name="ping">The Ping.</param>
        /// <param name="userToken">A user-defined object stored in the resulting Task.</param>
        /// <param name="sendAsync">
        /// A delegate that initiates the asynchronous send.
        /// The provided TaskCompletionSource must be passed as the user-supplied state to the actual Ping.SendAsync method.
        /// </param>
        /// <returns></returns>
        private static Task <PingReply> SendTaskCore(Ping ping, object userToken, Action <TaskCompletionSource <PingReply> > sendAsync)
        {
            if (ping == null)
            {
                throw new ArgumentNullException("ping");
            }
            TaskCompletionSource <PingReply> tcs     = new TaskCompletionSource <PingReply>(userToken);
            PingCompletedEventHandler        handler = null;

            handler = delegate(object sender, PingCompletedEventArgs e) {
                EAPCommon.HandleCompletion <PingReply>(tcs, e, () => e.Reply, delegate {
                    ping.PingCompleted -= handler;
                });
            };
            ping.PingCompleted += handler;
            try
            {
                sendAsync(tcs);
            }
            catch (Exception exception)
            {
                ping.PingCompleted -= handler;
                tcs.TrySetException(exception);
            }
            return(tcs.Task);
        }
Example #9
0
        /// <summary>
        /// <paramref name="address"/>의 리소스를 비동기적으로 다운받아 byte array로 반환하는 Task{byte[]}를 빌드합니다.
        /// </summary>
        /// <param name="webClient"><see cref="WebClient"/> 인스턴스</param>
        /// <param name="token">작업 취소를 위한 Token</param>
        /// <param name="address">리소스 위치</param>
        /// <returns></returns>
        private static Task <string> DownloadStringTaskInternal(this WebClient webClient, CancellationToken token, Uri address)
        {
            webClient.ShouldNotBeNull("webClient");
            token.ShouldNotBeNull("token");
            address.ShouldNotBeNull("address");

            if (IsDebugEnabled)
            {
                log.Debug("WebClient를 이용하여 지정된 주소로부터 리소스를 비동기 방식으로 다운받습니다... address=[{0}]", address.AbsoluteUri);
            }

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

            token.Register(webClient.CancelAsync);

            // 비동기 완료 시의 처리를 정의합니다.
            DownloadStringCompletedEventHandler handler = null;

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

            try
            {
                webClient.DownloadStringAsync(address, tcs);
            }
            catch (Exception ex)
            {
                if (log.IsWarnEnabled)
                {
                    log.Warn("WebClient를 이용하여 리소스 Data를 비동기적으로 다운받는데 실패했습니다. address=[{0}]", address.AbsoluteUri);
                    log.Warn(ex);
                }

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

            var result = tcs.Task;

            //if(result.IsCompleted)
            //    result = result.ContinueWith(antecedent => DecompressByContentEncoding(webClient, antecedent.Result),
            //                                 TaskContinuationOptions.ExecuteSynchronously);
            return(result);
        }
Example #10
0
        /// <summary>Downloads the resource with the specified URI as a string, asynchronously.</summary>
        /// <param name="webClient">The WebClient.</param>
        /// <param name="address">The URI from which to download data.</param>
        /// <returns>A Task that contains the downloaded string.</returns>
        public static Task <string> DownloadStringTask(this WebClient webClient, Uri address)
        {
            TaskCompletionSource <string>       tcs     = new TaskCompletionSource <string>(address);
            DownloadStringCompletedEventHandler handler = null;

            handler = delegate(object sender, DownloadStringCompletedEventArgs e) {
                EAPCommon.HandleCompletion <string>(tcs, e, () => e.Result, delegate {
                    webClient.DownloadStringCompleted -= handler;
                });
            };
            webClient.DownloadStringCompleted += handler;
            try
            {
                webClient.DownloadStringAsync(address, tcs);
            }
            catch (Exception exception)
            {
                webClient.DownloadStringCompleted -= handler;
                tcs.TrySetException(exception);
            }
            return(tcs.Task);
        }
Example #11
0
        /// <summary>Downloads the resource with the specified URI to a local file, asynchronously.</summary>
        /// <param name="webClient">The WebClient.</param>
        /// <param name="address">The URI from which to download data.</param>
        /// <param name="fileName">The name of the local file that is to receive the data.</param>
        /// <returns>A Task that contains the downloaded data.</returns>
        public static Task DownloadFileTask(this WebClient webClient, Uri address, string fileName)
        {
            TaskCompletionSource <object> tcs     = new TaskCompletionSource <object>(address);
            AsyncCompletedEventHandler    handler = null;

            handler = delegate(object sender, AsyncCompletedEventArgs e) {
                EAPCommon.HandleCompletion <object>(tcs, e, () => null, delegate {
                    webClient.DownloadFileCompleted -= handler;
                });
            };
            webClient.DownloadFileCompleted += handler;
            try
            {
                webClient.DownloadFileAsync(address, fileName, tcs);
            }
            catch (Exception exception)
            {
                webClient.DownloadFileCompleted -= handler;
                tcs.TrySetException(exception);
            }
            return(tcs.Task);
        }
Example #12
0
        /// <summary>Uploads a file to the specified resource, asynchronously.</summary>
        /// <param name="webClient">The WebClient.</param>
        /// <param name="address">The URI to which the file should be uploaded.</param>
        /// <param name="method">The HTTP method that should be used to upload the file.</param>
        /// <param name="fileName">A path to the file to upload.</param>
        /// <returns>A Task containing the data in the response from the upload.</returns>
        public static Task <byte[]> UploadFileTask(this WebClient webClient, Uri address, string method, string fileName)
        {
            TaskCompletionSource <byte[]>   tcs     = new TaskCompletionSource <byte[]>(address);
            UploadFileCompletedEventHandler handler = null;

            handler = delegate(object sender, UploadFileCompletedEventArgs e) {
                EAPCommon.HandleCompletion <byte[]>(tcs, e, () => e.Result, delegate {
                    webClient.UploadFileCompleted -= handler;
                });
            };
            webClient.UploadFileCompleted += handler;
            try
            {
                webClient.UploadFileAsync(address, method, fileName, tcs);
            }
            catch (Exception exception)
            {
                webClient.UploadFileCompleted -= handler;
                tcs.TrySetException(exception);
            }
            return(tcs.Task);
        }
Example #13
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);
        }