Exemple #1
0
 /// <summary>
 /// Creates a new tile information instance.
 /// </summary>
 /// <param name="readCompleteHandler">Handler to call when read operations initiated by
 /// <see cref="RequestImageAync"/> are completed. Make sure that the handler calls
 /// <see cref="MarkImageRequestCompleted"/> or <see cref="MarkImageRequestCancelled"/> once it finishes
 /// handling the request.</param>
 public TileInformation(DownloadDataCompletedEventHandler readCompleteHandler)
 {
     RequestClient = new WebClient();
     RequestClient.DownloadDataCompleted += readCompleteHandler;
     IsRequestCancelled = false;
     imageBuffer        = new byte[BingMapsTiles.InitialImageBufferSize];
 }
		/// <see cref="IAsyncWebClient.DownloadDataAsync"/>
		public Task<byte[]> DownloadDataAsync(Uri address, IProgress<DownloadProgressChangedEventArgs> progress, CancellationToken cancellationToken)
		{
			cancellationToken.Register(() => _webClient.CancelAsync());

			var cookie = Guid.NewGuid();
			var tcs = new TaskCompletionSource<byte[]>();

			DownloadProgressChangedEventHandler progressHandler = CreateProgressHandler(cookie, progress);
			if (progress != null)
				_webClient.DownloadProgressChanged += progressHandler;

			DownloadDataCompletedEventHandler completedHandler = null;
			completedHandler = (o, e) =>
			{
				if (!Equals(e.UserState, cookie))
					return;

				_webClient.DownloadProgressChanged -= progressHandler;
				_webClient.DownloadDataCompleted -= completedHandler;

				tcs.TrySetFromEventArgs(e, args => args.Result);
			};
			_webClient.DownloadDataCompleted += completedHandler;

			_webClient.DownloadDataAsync(address, cookie);
			return tcs.Task;
		}
Exemple #3
0
        public Task <byte[]> DownloadDataAsync(Uri address, CancellationToken token)
        {
            var tcs = new TaskCompletionSource <byte[]>();

            token.Register(() =>
            {
                this.CancelAsync();
            });

            DownloadDataCompletedEventHandler onCompleted = null;

            onCompleted = (s, e) =>
            {
                this.DownloadDataCompleted -= onCompleted;

                if (e.Cancelled)
                {
                    tcs.TrySetCanceled();
                    return;
                }
                if (e.Error != null)
                {
                    tcs.TrySetException(e.Error);
                    return;
                }

                tcs.SetResult(e.Result);
            };

            this.DownloadDataCompleted += onCompleted;
            base.DownloadDataAsync(address);

            return(tcs.Task);
        }
Exemple #4
0
        /// <summary>Downloads the resource with the specified URI as a byte array, 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 data.</returns>
        public static Task <byte[]> DownloadDataTask(this WebClient webClient, Uri address)
        {
            // Create the task to be returned
            var tcs = new TaskCompletionSource <byte[]>(address);

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

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

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

            // Return the task that represents the async operation
            return(tcs.Task);
        }
Exemple #5
0
        /// <summary>
        /// ダウンロードを開始します。
        /// </summary>
        public void BeginDownload(Uri address,
                                  DownloadDataCompletedEventHandler callback)
        {
            if (address == null)
            {
                throw new ArgumentNullException("address");
            }

            var client = new WebClient();

            client.DownloadProgressChanged += client_DownloadProgressChanged;
            client.DownloadDataCompleted   += client_DownloadDataCompleted;

            // ダウンロード管理用オブジェクト
            var item = new DownloadItem
            {
                Client   = client,
                Callback = callback,
            };

            // ここで例外が返る可能性がある。
            Log.Debug("{0}: ダウンロードを開始します", address);
            ThreadPool.QueueUserWorkItem(_ =>
                                         client.DownloadDataAsync(address, item));

            using (LazyLock())
            {
                this.itemList.Add(item);

                this.RaisePropertyChanged("Count");
            }
        }
Exemple #6
0
        public static Task <byte[]> DownloadDataTaskAsync(this WebClient wc, Uri address)
        {
            var token = new object();
            var task  = new TaskCompletionSource <byte[]> ();
            DownloadDataCompletedEventHandler handler = null;

            handler = (s, e) =>
            {
                wc.DownloadDataCompleted -= handler;
                if (e.Error != null)
                {
                    task.TrySetException(e.Error);
                }
                else if (e.Cancelled)
                {
                    task.TrySetCanceled();
                }
                else
                {
                    task.TrySetResult(e.Result);
                }
            };
            wc.DownloadDataCompleted += handler;
            wc.DownloadDataAsync(address, token);
            return(task.Task);
        }
    /// <summary>Downloads the resource with the specified URI as a byte array, 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 data.</returns>
    public static Task <byte[]> DownloadDataTaskAsync(this WebClient webClient, Uri address)
    {
        // Create the task to be returned
        var tcs = new TaskCompletionSource <byte[]>(address);

        // Setup the callback event handler
        DownloadDataCompletedEventHandler completedHandler = null;

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

        // Start the async operation.
        try
        {
            webClient.DownloadDataAsync(address, tcs);
        }
        catch
        {
            webClient.DownloadDataCompleted -= completedHandler;
            throw;
        }

        // Return the task that represents the async operation
        return(tcs.Task);
    }
        /// <summary>
        /// Create an instance of the DatabaseAutomationRunner window
        /// </summary>
        public DatabaseAutomationRunner(ModpackSettings modpackSettings, Logfiles logfile) : base(modpackSettings, logfile)
        {
            InitializeComponent();
            DownloadProgressChanged = WebClient_DownloadProgressChanged;
            DownloadDataCompleted   = WebClient_DownloadDataComplted;
            DownloadFileCompleted   = WebClient_TransferFileCompleted;
            UploadFileCompleted     = WebClient_UploadFileCompleted;
            UploadProgressChanged   = WebClient_UploadProgressChanged;
            RelhaxProgressChanged   = RelhaxProgressReport_ProgressChanged;
            ProgressChanged         = GenericProgressChanged;
            Settings = AutomationSettings;

            //https://stackoverflow.com/questions/7712137/array-containing-methods
            settingsMethods = new Action[]
            {
                () => OpenLogWindowOnStartupSetting_Click(null, null),
                () => BigmodsUsernameSetting_TextChanged(null, null),
                () => BigmodsPasswordSetting_TextChanged(null, null),
                () => DumpParsedMacrosPerSequenceRunSetting_Click(null, null),
                () => DumpEnvironmentVariablesAtSequenceStartSetting_Click(null, null),
                () => SuppressDebugMessagesSetting_Click(null, null),
                () => AutomamtionDatabaseSelectedBranchSetting_TextChanged(null, null),
                () => SelectDBSaveLocationSetting_TextChanged(null, null),
                () => UseLocalRunnerDatabaseSetting_Click(null, null),
                () => LocalRunnerDatabaseRootSetting_TextChanged(null, null),
                () => SelectWoTInstallLocationSetting_TextChanged(null, null)
            };
        }
		public static void DownloadContextAsync(string url, DownloadDataCompletedEventHandler e) {
			using (var webClient = new WebClient {
				Encoding = Encoding.UTF8
			}) {
				webClient.DownloadDataAsync(new Uri(url));
				webClient.DownloadDataCompleted += e;
			}
		}
Exemple #10
0
 /// <summary>
 /// 内部采集方式
 /// </summary>
 /// <param name="url"></param>
 /// <param name="completed"></param>
 private void _collect(string url, DownloadDataCompletedEventHandler completed)
 {
     using (WebClient client = new WebClient())
     {
         client.DownloadDataCompleted += completed;
         client.DownloadDataAsync(new Uri(url), client);
     }
 }
Exemple #11
0
        /// <summary>
        /// Синхронная или асинхронная загрузка данных
        /// </summary>
        /// <param name="url">Адрес</param>
        /// <param name="progress">Обработчик события прогресса загрузки для асинхронной загрузки (null для синхронной</param>
        /// <param name="complete">Обработчик события завершения загрузки</param>
        /// <returns>Результат синхронной загрузки или null при неудаче, всегда null при асинхронной</returns>
        public static string DownloadPageSilent(string url, DownloadProgressChangedEventHandler progress,
                                                DownloadDataCompletedEventHandler complete)
        {
            byte[] buffer = null;
            int tries = 0;

            var client = new WebClient();
            try
            {
                if (_proxySetting.UseProxy)
                {
                    IPAddress test;
                    if (!IPAddress.TryParse(_proxySetting.Address, out test))
                        throw new ArgumentException("Некорректный адрес прокси сервера");
                    client.Proxy = _proxySetting.UseAuthentification
                                       ? new WebProxy(
                                             new Uri("http://" + _proxySetting.Address + ":" + _proxySetting.Port),
                                             false,
                                             new string[0],
                                             new NetworkCredential(_proxySetting.UserName, _proxySetting.Password))
                                       : new WebProxy(
                                             new Uri("http://" + _proxySetting.Address + ":" + _proxySetting.Port));
                }
            }
            catch (Exception ex)
            {
                _logger.Add(ex.StackTrace, false, true);
                _logger.Add(ex.Message, false, true);
                _logger.Add("Ошибка конструктора прокси", false, true);
            }

            while (tries < 3)
            {
                try
                {
                    SetHttpHeaders(client, null);
                    if (progress == null)
                        buffer = client.DownloadData(url);
                    else
                    {
                        client.DownloadProgressChanged += progress;
                        client.DownloadDataCompleted += complete;
                        client.DownloadDataAsync(new Uri(url));
                        return null;
                    }
                    break;
                }
                catch (Exception ex)
                {
                    _logger.Add(ex.StackTrace, false, true);
                    _logger.Add(ex.Message, false, true);
                    _logger.Add("Ошибка загрузки страницы", false, true);
                    tries++;
                }
            }

            return (buffer != null) ? ConvertPage(buffer) : null;
        }
Exemple #12
0
        public void DownloadFileAsync(string url, DownloadProgressChangedEventHandler downloadProgressChanged,
                                      DownloadDataCompletedEventHandler downloadCompleted)
        {
            var client = new WebClient();

            client.DownloadProgressChanged += downloadProgressChanged;
            client.DownloadDataCompleted   += downloadCompleted;
            client.DownloadDataAsync(new Uri(url));
        }
        /// <summary>
        /// Extends BeginInvoke so that when a state object is not needed, null does not need to be passed.
        /// <example>
        /// downloaddatacompletedeventhandler.BeginInvoke(sender, e, callback);
        /// </example>
        /// </summary>
        public static IAsyncResult BeginInvoke(this DownloadDataCompletedEventHandler downloaddatacompletedeventhandler, Object sender, DownloadDataCompletedEventArgs e, AsyncCallback callback)
        {
            if (downloaddatacompletedeventhandler == null)
            {
                throw new ArgumentNullException("downloaddatacompletedeventhandler");
            }

            return(downloaddatacompletedeventhandler.BeginInvoke(sender, e, callback, null));
        }
Exemple #14
0
        /// <summary>
        /// This event is raised each time an asynchronous data download operation completes
        /// </summary>
        private void Gett_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
        {
            DownloadDataCompletedEventHandler copyDownloadDataCompleted = DownloadDataCompleted;

            if (copyDownloadDataCompleted != null)
            {
                copyDownloadDataCompleted(this, e);
            }
        }
        async void GetImageBitmapFromUrl(string url, DownloadDataCompletedEventHandler eventFunc)
        {
            Bitmap img1 = null;

            using (var webClient = new System.Net.WebClient())
            {
                webClient.DownloadDataCompleted += eventFunc;
                webClient.DownloadDataAsync(new Uri(url));
            }
        }
Exemple #16
0
        public static void ByteRequestAsync(string url, DownloadDataCompletedEventHandler dataHandler)
        {
            Log.O("Downloading Async: " + url);
            var wc = new WebClient();
            if (_proxy != null)
                wc.Proxy = _proxy;

            wc.DownloadDataCompleted += dataHandler;
            wc.DownloadDataAsync(new Uri(url));
        }
        void _client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
        {
            DisconnectEvents();
            DownloadDataCompletedEventHandler handler = DownloadDataCompleted;

            if (handler != null)
            {
                handler(this, e);
            }
        }
Exemple #18
0
 public static void Download(string downloadUrl, string filename, DownloadDataCompletedEventHandler callbackDelegate)
 {
     try
     {
         URLDownloadToFile(0, downloadUrl, filename, 0, 0);
     }
     catch (Exception ex)
     {
         Trace.TraceError(ex.Message);
     }
 }
Exemple #19
0
        /// <summary>
        ///     Cancel the download
        /// </summary>
        public void Cancel()
        {
            _webc.CancelAsync();
            File.Delete(_tmplocation);
            DownloadDataCompletedEventHandler handler = DownloadCompleted;

            if (handler != null)
            {
                handler(null, null);
            }
        }
Exemple #20
0
 /// <summary>
 /// Downloads a file from the web.
 /// </summary>
 /// <param name="uri">The URI to download from.</param>
 /// <param name="downloadCompleted">The event to fire when the download completes.</param>
 /// <param name="downloadProgressChanged">The event to fire when the download progress changes.</param>
 public static async Task <byte[]> DownloadFile(Uri uri,
                                                DownloadDataCompletedEventHandler downloadCompleted         = null,
                                                DownloadProgressChangedEventHandler downloadProgressChanged = null)
 {
     // Start the modification download.
     using (WebClient client = new WebClient())
     {
         client.DownloadDataCompleted   += downloadCompleted;
         client.DownloadProgressChanged += downloadProgressChanged;
         return(await client.DownloadDataTaskAsync(uri));
     }
 }
Exemple #21
0
        public static void ByteRequestAsync(string url, DownloadDataCompletedEventHandler dataHandler)
        {
            Log.O("Downloading Async: " + url);
            var wc = new WebClient();

            if (_proxy != null)
            {
                wc.Proxy = _proxy;
            }

            wc.DownloadDataCompleted += dataHandler;
            wc.DownloadDataAsync(new Uri(url));
        }
        internal static IObservable <byte[]> DownloadAttachment(this WebClient client, Uri address, string contentType = "text/plain", string username = "", string password = "")
        {
            return(Observable.Create <byte[]>(observer =>
            {
                DownloadDataCompletedEventHandler handler = (sender, args) =>
                {
                    if (args.Cancelled)
                    {
                        observer.OnCompleted();
                    }
                    else if (args.Error != null)
                    {
                        observer.OnError(args.Error);
                    }
                    else
                    {
                        try
                        {
                            observer.OnNext(args.Result);
                            observer.OnCompleted();
                        }
                        catch (Exception ex)
                        {
                            observer.OnError(ex);
                        }
                    }
                };

                client.DownloadDataCompleted += handler;
                try
                {
                    if (!string.IsNullOrWhiteSpace(username) && !string.IsNullOrWhiteSpace(password))
                    {
                        client.SetAuthenticationHeaders(username, password);
                    }
                    client.Headers.Add(HttpRequestHeader.ContentType, contentType);
                    client.DownloadDataAsync(address);
                }
                catch (Exception ex)
                {
                    observer.OnError(ex);
                }

                return () => client.DownloadDataCompleted -= handler;
            }));
        }
Exemple #23
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>
        public static Task <byte[]> DownloadDataTask(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 <byte[]>(address);

            token.Register(webClient.CancelAsync);

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

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

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

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

            var result = tcs.Task;

            if (result.IsCompleted)
            {
                result = result.ContinueWith(antecedent => DecompressByContentEncoding(webClient, antecedent.Result),
                                             TaskContinuationOptions.ExecuteSynchronously);
            }
            return(result);
        }
Exemple #24
0
        /// <summary>
        ///     Handle finished download, move file from temporary to target location
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Finished(object sender, DownloadDataCompletedEventArgs e)
        {
            Logger.Log(LogLevel.Info, "FileDownloadProgressBar", "Download finished!", _url);
            // Move to the correct location
            if (File.Exists(_targetlocation))
            {
                File.Delete(_targetlocation);
            }
            File.Move(_tmplocation, _targetlocation);

            DownloadDataCompletedEventHandler handler = DownloadCompleted;

            if (handler != null)
            {
                handler(sender, e);
            }
        }
        public Task <byte[]> GetDataAsync(string url, CancellationToken token)
        {
            // create completion source
            var tcs = new TaskCompletionSource <byte[]>();

            // create a web client for downloading the string
            var wc = new WebClient();

            // Set up variable for referencing anonymous event handler method. We
            // need to first assign null, and then create the method so that we
            // can reference the variable within the method itself.
            DownloadDataCompletedEventHandler downloadCompletedHandler = null;

            // Set up an anonymous method that will handle the DownloadStringCompleted
            // event.
            downloadCompletedHandler = (s, e) =>
            {
                wc.DownloadDataCompleted -= downloadCompletedHandler;
                if (e.Cancelled)
                {
                    tcs.TrySetCanceled();
                }
                else if (e.Error == null)
                {
                    tcs.TrySetResult(e.Result);
                }
                else
                {
                    tcs.TrySetException(e.Error);
                }
                wc.Dispose();
            };

            // Subscribe to the completed event
            wc.DownloadDataCompleted += downloadCompletedHandler;
            try
            {
                wc.DownloadDataAsync(new Uri(url));
                token.Register(new Action(wc.CancelAsync));
            }
            catch (Exception exception)
            {
                tcs.TrySetException(exception);
            }
            return(tcs.Task);
        }
        /// <summary>Downloads the resource with the specified URI as a byte array, 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 data.</returns>
        public static Task <byte[]> DownloadDataTask(this WebClient webClient, Uri address)
        {
            TaskCompletionSource <byte[]>     tcs     = new TaskCompletionSource <byte[]>(address);
            DownloadDataCompletedEventHandler handler = null;

            handler = delegate(object sender, DownloadDataCompletedEventArgs e) {
                EAPCommon.HandleCompletion <byte[]>(tcs, e, () => e.Result, delegate {
                    webClient.DownloadDataCompleted -= handler;
                });
            };
            webClient.DownloadDataCompleted += handler;
            try
            {
                webClient.DownloadDataAsync(address, tcs);
            }
            catch (Exception exception)
            {
                webClient.DownloadDataCompleted -= handler;
                tcs.TrySetException(exception);
            }
            return(tcs.Task);
        }
    public static Task <byte[]> DownloadDataTaskAsync(this WebClient webClient, Uri address)
    {
        TaskCompletionSource <byte[]>     tcs = new TaskCompletionSource <byte[]>(address);
        DownloadDataCompletedEventHandler completedHandler = null;

        completedHandler = delegate(object sender, DownloadDataCompletedEventArgs e)
        {
            AsyncCompatLibExtensions.HandleEapCompletion <byte[]>(tcs, true, e, () => e.Result, delegate
            {
                webClient.DownloadDataCompleted -= completedHandler;
            });
        };
        webClient.DownloadDataCompleted += completedHandler;
        try
        {
            webClient.DownloadDataAsync(address, tcs);
        }
        catch
        {
            webClient.DownloadDataCompleted -= completedHandler;
            throw;
        }
        return(tcs.Task);
    }
 /// <summary>
 ///     异步抓取页面HTML代码
 /// </summary>
 private TmphDataCrawler()
 {
     onDownloadHandle = onDownload;
     onUploadHandle = onUpload;
 }
        /// <summary>
        /// Asynchronously downloads the resource with the specified URI as a Byte array limited by the specified timeout and allows cancelling the operation.
        /// </summary>
        /// <param name="webClient">The client with which to download the specified resource.</param>
        /// <param name="uri">The address of the resource to download.</param>
        /// <param name="timeout">A TimeSpan specifying the amount of time to wait for a response before aborting the request.
        /// The specify an infinite timeout, pass a TimeSpan with a TotalMillisecond value of Timeout.Infinite.
        /// When a request is aborted due to a timeout the returned task will transition to the Faulted state with a TimeoutException.</param>
        /// <param name="token">A cancellation token that can be used to cancel the pending asynchronous task.</param>
        /// <returns>A Task with the future value of the downloaded string.</returns>
        /// <exception cref="ArgumentNullException">Thrown when a null value is passed to the client or address parameters.</exception>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when the value of timeout is neither a positive value or infinite.</exception>
        public static Task <byte[]> DownloadDataTaskAsync(this WebClient webClient, Uri uri, TimeSpan timeout, CancellationToken token)
        {
            if (webClient == null)
            {
                throw new ArgumentNullException(nameof(webClient));
            }

            if (uri == null)
            {
                throw new ArgumentNullException(nameof(uri));
            }

            if (timeout.TotalMilliseconds < 0 && timeout != DefaultTimeout)
            {
                throw new ArgumentOutOfRangeException(nameof(uri), timeout, "The timeout value must be a positive or equal to InfiniteTimeout.");
            }

            if (token.IsCancellationRequested)
            {
                return(PreCancelledTask);
            }

            var taskCompletionSource    = new TaskCompletionSource <byte[]>();
            var cancellationTokenSource = new CancellationTokenSource();

            if (timeout != DefaultTimeout)
            {
                Task.Delay(timeout, cancellationTokenSource.Token).ContinueWith(x =>
                {
                    taskCompletionSource.TrySetException(new TimeoutException($"The request has exceeded the timeout limit of {timeout} and has been aborted."));
                    webClient.CancelAsync();
                }, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.NotOnCanceled);
            }

            DownloadDataCompletedEventHandler completedHandler = null;

            completedHandler = (sender, args) =>
            {
                webClient.DownloadDataCompleted -= completedHandler;
                cancellationTokenSource.Cancel();

                if (args.Cancelled)
                {
                    taskCompletionSource.TrySetCanceled();
                }
                else if (args.Error != null)
                {
                    taskCompletionSource.TrySetException(args.Error);
                }
                else
                {
                    taskCompletionSource.TrySetResult(args.Result);
                }
            };

            webClient.DownloadDataCompleted += completedHandler;

            try
            {
                webClient.DownloadDataAsync(uri);
            }
            catch
            {
                webClient.DownloadDataCompleted -= completedHandler;
                throw;
            }

            token.Register(() =>
            {
                cancellationTokenSource.Cancel();
                webClient.CancelAsync();
            });

            return(taskCompletionSource.Task);
        }
Exemple #30
0
        /// <summary>
        /// Синхронная или асинхронная загрузка данных
        /// </summary>
        /// <param name="url">Адрес</param>
        /// <param name="progress">Обработчик события прогресса загрузки для асинхронной загрузки (null для синхронной</param>
        /// <param name="complete">Обработчик события завершения загрузки</param>
        /// <returns>Результат синхронной загрузки или null при неудаче, всегда null при асинхронной</returns>
        public static string DownloadPageSilent(string url, DownloadProgressChangedEventHandler progress,
                                                DownloadDataCompletedEventHandler complete)
        {
            byte[] buffer = null;
            int    tries  = 0;

            var client = new WebClient();

            try
            {
                if (_proxySetting.UseProxy)
                {
                    IPAddress test;
                    if (!IPAddress.TryParse(_proxySetting.Address, out test))
                    {
                        throw new ArgumentException("Некорректный адрес прокси сервера");
                    }
                    client.Proxy = _proxySetting.UseAuthentification
                                       ? new WebProxy(
                        new Uri("http://" + _proxySetting.Address + ":" + _proxySetting.Port),
                        false,
                        new string[0],
                        new NetworkCredential(_proxySetting.UserName, _proxySetting.Password))
                                       : new WebProxy(
                        new Uri("http://" + _proxySetting.Address + ":" + _proxySetting.Port));
                }
            }
            catch (Exception ex)
            {
                _logger.Add(ex.StackTrace, false, true);
                _logger.Add(ex.Message, false, true);
                _logger.Add("Ошибка конструктора прокси", false, true);
            }

            while (tries < 3)
            {
                try
                {
                    SetHttpHeaders(client, null);
                    if (progress == null)
                    {
                        buffer = client.DownloadData(url);
                    }
                    else
                    {
                        client.DownloadProgressChanged += progress;
                        client.DownloadDataCompleted   += complete;
                        client.DownloadDataAsync(new Uri(url));
                        return(null);
                    }
                    break;
                }
                catch (Exception ex)
                {
                    _logger.Add(ex.StackTrace, false, true);
                    _logger.Add(ex.Message, false, true);
                    _logger.Add("Ошибка загрузки страницы", false, true);
                    tries++;
                }
            }

            return((buffer != null) ? ConvertPage(buffer) : null);
        }
Exemple #31
0
 /// <summary>
 /// Http同步Get异步请求
 /// </summary>
 /// <param name="uriString"></param>
 /// <param name="uriParameters"></param>
 /// <param name="callBackDownDataCompleted"></param>
 /// <param name="msg"></param>
 /// <param name="queryUrl"></param>
 public void GetSrcAsync(string uriString, Dictionary <string, object> uriParameters, DownloadDataCompletedEventHandler callBackDownDataCompleted, out string msg, out string queryUrl)
 {
     queryUrl = "";
     msg      = "";
     try
     {
         string parameters   = BuildingUrlParams(uriParameters);
         string cookieString = BuildCookies();
         if (!string.IsNullOrWhiteSpace(parameters))
         {
             uriString += "?" + parameters;
         }
         if (!string.IsNullOrWhiteSpace(cookieString))
         {
             this.Headers[HttpRequestHeader.Cookie] = cookieString;
         }
         // 返回页面的字节数组
         this.Headers[HttpRequestHeader.Accept] = "application/json, text/javascript, */*; q=0.01";
         if (callBackDownDataCompleted != null)
         {
             this.DownloadDataCompleted += callBackDownDataCompleted;
         }
         this.DownloadDataAsync(new Uri(uriString));
     }
     catch (WebException we)
     {
         msg = we.Message;
     }
 }
Exemple #32
0
 /// <summary>
 /// 异步抓取页面HTML代码
 /// </summary>
 private dataCrawler()
 {
     onDownloadHandle = onDownload;
     onPostFormHandle = onPostForm;
     onUploadHandle   = onUpload;
 }
        /// <summary>
        /// Asynchronously downloads the resource with the specified URI as a Byte array limited by the specified timeout and allows cancelling the operation.
        /// </summary>
        /// <param name="_client">The client with which to download the specified resource.</param>
        /// <param name="_address">The address of the resource to download.</param>
        /// <param name="_timeout">A TimeSpan specifying the amount of time to wait for a response before aborting the request.
        /// The specify an infinite timeout, pass a TimeSpan with a TotalMillisecond value of Timeout.Infinite.
        /// When a request is aborted due to a timeout the returned task will transition to the Faulted state with a TimeoutException.</param>
        /// <param name="_token">A cancellation token that can be used to cancel the pending asynchronous task.</param>
        /// <returns>A Task with the future value of the downloaded string.</returns>
        /// <exception cref="ArgumentNullException">Thrown when a null value is passed to the client or address parameters.</exception>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when the value of timeout is neither a positive value or infinite.</exception>
        public static Task <byte[]> DownloadDataTaskAsync(this WebClient _client, Uri _address, TimeSpan _timeout, CancellationToken _token)
        {
            if (_client == null)
            {
                throw new ArgumentNullException("_client");
            }
            if (_address == null)
            {
                throw new ArgumentNullException("_address");
            }
            if (_timeout.TotalMilliseconds < 0 && _timeout != _infiniteTimeout)
            {
                throw new ArgumentOutOfRangeException("_address", _timeout, "The timeout value must be a positive or equal to InfiniteTimeout.");
            }

            if (_token.IsCancellationRequested)
            {
                return(_preCancelledTask);
            }

            var _tcs = new TaskCompletionSource <byte[]>();
            var _delayTokenSource = new CancellationTokenSource();

            if (_timeout != _infiniteTimeout)
            {
                Task.Delay(_timeout, _delayTokenSource.Token).ContinueWith(_t =>
                {
                    _tcs.TrySetException(new TimeoutException(string.Format("The request has exceeded the timeout limit of {0} and has been aborted.", _timeout)));
                    _client.CancelAsync();
                }, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.NotOnCanceled);
            }

            DownloadDataCompletedEventHandler _completedHandler = null;

            _completedHandler = (_sender, _args) =>
            {
                _client.DownloadDataCompleted -= _completedHandler;
                _delayTokenSource.Cancel();

                if (_args.Cancelled)
                {
                    _tcs.TrySetCanceled();
                }
                else if (_args.Error != null)
                {
                    _tcs.TrySetException(_args.Error);
                }
                else
                {
                    _tcs.TrySetResult(_args.Result);
                }
            };

            _client.DownloadDataCompleted += _completedHandler;

            try
            {
                _client.DownloadDataAsync(_address);
            }
            catch
            {
                _client.DownloadDataCompleted -= _completedHandler;
                throw;
            }

            _token.Register(() =>
            {
                _delayTokenSource.Cancel();
                _client.CancelAsync();
            });

            return(_tcs.Task);
        }
        /// <summary>
        /// Asynchronously downloads the resource with the specified URI as a Byte array limited by the specified timeout and allows cancelling the operation.
        /// </summary>
        /// <param name="client">The client with which to download the specified resource.</param>
        /// <param name="address">The address of the resource to download.</param>
        /// <param name="timeout">A TimeSpan specifying the amount of time to wait for a response before aborting the request.
        /// The specify an infinite timeout, pass a TimeSpan with a TotalMillisecond value of Timeout.Infinite.
        /// When a request is aborted due to a timeout the returned task will transition to the Faulted state with a TimeoutException.</param>
        /// <param name="token">A cancellation token that can be used to cancel the pending asynchronous task.</param>
        /// <returns>A Task with the future value of the downloaded string.</returns>
        /// <exception cref="ArgumentNullException">Thrown when a null value is passed to the client or address parameters.</exception>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when the value of timeout is neither a positive value or infinite.</exception>
        public static Task <byte[]> DownloadDataTaskAsync(this WebClient client, Uri address, TimeSpan timeout, CancellationToken token)
        {
            if (client == null)
            {
                throw new ArgumentNullException("client");
            }
            if (address == null)
            {
                throw new ArgumentNullException("address");
            }
            if (timeout.TotalMilliseconds < 0 && timeout != InfiniteTimeout)
            {
                throw new ArgumentOutOfRangeException("address", timeout, "The timeout value must be a positive or equal to InfiniteTimeout.");
            }

            if (token.IsCancellationRequested)
            {
                return(PreCancelledTask);
            }

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

            if (timeout != InfiniteTimeout)
            {
                Task.Factory.Delay(timeout, delayTokenSource.Token).ContinueWith(t =>
                {
                    tcs.TrySetException(new TimeoutException(string.Format("The request has exceeded the timeout limit of {0} and has been aborted.", timeout)));
                    client.CancelAsync();
                }, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.NotOnCanceled);
            }

            DownloadDataCompletedEventHandler completedHandler = null;

            completedHandler = (sender, args) =>
            {
                client.DownloadDataCompleted -= completedHandler;
                delayTokenSource.Cancel();

                if (args.Cancelled)
                {
                    tcs.TrySetCanceled();
                }
                else if (args.Error != null)
                {
                    tcs.TrySetException(args.Error);
                }
                else
                {
                    tcs.TrySetResult(args.Result);
                }
            };

            client.DownloadDataCompleted += completedHandler;

            try
            {
                client.DownloadDataAsync(address);
            }
            catch
            {
                client.DownloadDataCompleted -= completedHandler;
                throw;
            }

            token.Register(() =>
            {
                delayTokenSource.Cancel();
                client.CancelAsync();
            });

            return(tcs.Task);
        }
Exemple #35
0
        // per-revision logic
        private void DownloadFileAndDisplayThumb()
        {
            XmlNode topImage = ImageInfos[SelectedRevisions[0]];
            Invoke((MethodInvoker) delegate()
            {
                if (SelectedRevisions.Length > 1)
                    lblRevision.Text = Localization.GetString("MultipleVersions_Label", SelectedRevisions.Length.ToString(),
                        ImageInfos.Count.ToString());
                else if (SelectedRevisions[0] == 0)
                    lblRevision.Text = Localization.GetString("CurrentVersion_Label") + " (" + FormatTimestamp(topImage) + ")";
                else
                    lblRevision.Text = Localization.GetString("OldVersion_Label") + " (" + FormatTimestamp(topImage) + ")";

                lblDimensions.Text = FormatDimensions(topImage);
                lblRevision.ForeColor = lblName.ForeColor = (SelectedRevisions[0] == 0 && SelectedRevisions.Length == 1 ? SystemColors.ControlText : Color.Red);

                XmlNodeList metadatas = topImage.SelectNodes("metadata/metadata");
                if (metadatas.Count > 4)
                {
                    lblViewExif.Visible = btnViewExif.Visible = true;
                    btnViewExif.Tag = metadatas;
                }
                else
                    lblViewExif.Visible = btnViewExif.Visible = false;

                pictureBox1.SizeMode = PictureBoxSizeMode.CenterImage;
                pictureBox1.Image = pictureBox1.InitialImage;
                pictureBox1.Cursor = Cursors.Default;
            });

            // decide whether PictureBox can display this image
            bool previewDownloadedFile = false;
            if (topImage.Attributes["thumburl"].Value == "")
            {
                // probably an OGG or something
                Invoke((MethodInvoker) delegate()
                {
                    pictureBox1.Image = pictureBox1.ErrorImage;
                });
            }
            else
            {
                switch (topImage.Attributes["mime"].Value)
                {
                    // GDI+ natively supports only these formats
                    case "image/gif":
                    case "image/jpeg":
                    case "image/png":
                    case "image/tiff":
                        previewDownloadedFile = true;
                        break;
                    default:
                        // try to download PNG thumb
                        // ImageLocation doesn't work, because of the useragent
                        WebClient clThumb = new WebClient();
                        clThumb.Headers.Add("User-Agent", MorebitsDotNet.UserAgent);
                        clThumb.DownloadDataCompleted += new DownloadDataCompletedEventHandler(
                            delegate(object s, DownloadDataCompletedEventArgs v)
                            {
                                pictureBox1.SizeMode = PictureBoxSizeMode.CenterImage;
                                Invoke((MethodInvoker) delegate()
                                {
                                    try
                                    {
                                        pictureBox1.Image = Image.FromStream(new MemoryStream(v.Result, false));
                                        pictureBox1.Cursor = ZoomInCursor;
                                    }
                                    catch (Exception)
                                    {
                                        pictureBox1.Image = pictureBox1.ErrorImage;
                                    }
                                });

                            });
                        clThumb.DownloadDataAsync(new Uri(topImage.Attributes["thumburl"].Value));
                        break;
                }
            }

            // download files
            SetTransferButtonDownloading(true);
            int currentIndexIndex = 0;  // the index into SelectedRevisions (an array of indexes). So meta!
            DownloadDataCompletedEventHandler displayThumbHandler = null;
            displayThumbHandler = new DownloadDataCompletedEventHandler(
                delegate(object s, DownloadDataCompletedEventArgs v)
                {
                    if (v.Cancelled)
                    {
                        SetTransferButtonDownloading(false);
                        return;
                    }
                    if (v.Error != null)
                    {
                        ErrorHandler(Localization.GetString("FailedToDownload") + "\n\n" + v.Error.Message);
                        SetTransferButtonDownloading(false);
                        return;
                    }

                    ImageDatas[SelectedRevisions[currentIndexIndex]] = v.Result;
                    if (previewDownloadedFile && currentIndexIndex == 0)
                    {
                        Invoke((MethodInvoker) delegate()
                        {
                            try
                            {
                                Image img = Image.FromStream(new MemoryStream(ImageDatas[SelectedRevisions[currentIndexIndex]], false));
                                if (img.Height > pictureBox1.Height || img.Width > pictureBox1.Width)
                                    pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
                                else
                                    pictureBox1.SizeMode = PictureBoxSizeMode.CenterImage;
                                pictureBox1.Image = img;
                                pictureBox1.Cursor = ZoomInCursor;
                            }
                            catch (Exception)
                            {
                                pictureBox1.SizeMode = PictureBoxSizeMode.CenterImage;
                                pictureBox1.Image = pictureBox1.ErrorImage;
                            }
                        });
                    }

                    if (++currentIndexIndex < SelectedRevisions.Length)
                    {
                        ImageDataDownloader = new WebClient();
                        ImageDataDownloader.Headers.Add("User-Agent", MorebitsDotNet.UserAgent);
                        ImageDataDownloader.DownloadDataCompleted += displayThumbHandler;
                        ImageDataDownloader.DownloadDataAsync(new Uri(ImageInfos[SelectedRevisions[currentIndexIndex]].Attributes["url"].Value));
                    }
                    else
                    {
                        SetTransferButtonDownloading(false);
                    }
                });
            ImageDataDownloader = new WebClient();
            ImageDataDownloader.Headers.Add("User-Agent", MorebitsDotNet.UserAgent);
            ImageDataDownloader.DownloadDataCompleted += displayThumbHandler;
            ImageDataDownloader.DownloadDataAsync(new Uri(ImageInfos[SelectedRevisions[currentIndexIndex]].Attributes["url"].Value));
        }
Exemple #36
0
 /// <summary>
 /// 下载更新文件
 /// </summary>
 void DownloadFile(string baseAddress, string file, DownloadDataCompletedEventHandler downloadCompleted, double progress)
 {
     var client = new WebClient();
     client.BaseAddress = baseAddress;
     double value = 0;
     client.DownloadProgressChanged += (sender, e) =>
     {
         var i = e.ProgressPercentage * progress / 100 - value;
         value = e.ProgressPercentage * progress / 100;
         MainWindow.UpdateProgress(i);
     };
     client.DownloadDataCompleted += (x, y) =>
     {
         if (y.Error != null)
             MainWindow.ShowError(y.Error);
         else
         {
             try
             {
                 downloadCompleted(x, y);
             }
             catch (Exception exc) { MainWindow.ShowError(exc); }
         }
     };
     client.DownloadDataAsync(new Uri(file, UriKind.Relative));
 }
Exemple #37
0
        /// <summary>
        /// ダウンロードを開始します。
        /// </summary>
        public void BeginDownload(Uri address,
                                  DownloadDataCompletedEventHandler callback)
        {
            if (address == null)
            {
                throw new ArgumentNullException("address");
            }

            var client = new WebClient();
            client.DownloadProgressChanged += client_DownloadProgressChanged;
            client.DownloadDataCompleted += client_DownloadDataCompleted;

            // ダウンロード管理用オブジェクト
            var item = new DownloadItem
            {
                Client = client,
                Callback = callback,
            };

            // ここで例外が返る可能性がある。
            Log.Debug("{0}: ダウンロードを開始します", address);
            ThreadPool.QueueUserWorkItem(_ =>
                client.DownloadDataAsync(address, item));

            using (LazyLock())
            {
                this.itemList.Add(item);

                this.RaisePropertyChanged("Count");
            }
        }