private static void EditorUpdate() { if (!DLError) { if (FinishedDL) { DownloadFinished(); } else if (EditorUtility.DisplayCancelableProgressBar("Downloading latest Fuse SDK", "Downloaded: " + KBytes + "kB / " + TotalKBytes + "kB", DownloadProgress)) { Downloader.CancelAsync(); } else { return; } } EditorApplication.update -= EditorUpdate; EditorUtility.ClearProgressBar(); if (Downloader != null) { Downloader.Dispose(); Downloader = null; } }
private void DownloadFile() { WebClient client = new WebClient(); //register download events client.DownloadProgressChanged += client_DownloadProgressChanged; client.DownloadFileCompleted += client_DownloadFileCompleted; //start the download client.DownloadFileAsync(address, outFileName); patchDownloadState = DownloadState.InProgress; bool patchDownloadCancelling = false; //wait for the file to be downloaded while (patchDownloadState == DownloadState.InProgress) { if (!patchDownloadCancelling && (Cancelling || Cancelled)) { Description = Messages.DOWNLOAD_AND_EXTRACT_ACTION_DOWNLOAD_CANCELLED_DESC; client.CancelAsync(); patchDownloadCancelling = true; } Thread.Sleep(SLEEP_TIME); } //deregister download events client.DownloadProgressChanged -= client_DownloadProgressChanged; client.DownloadFileCompleted -= client_DownloadFileCompleted; if (patchDownloadState == DownloadState.Cancelled) throw new CancelledException(); if (patchDownloadState == DownloadState.Error) MarkCompleted(patchDownloadError ?? new Exception(Messages.ERROR_UNKNOWN)); }
public void CancelDownload() { if (_client != null) { _client.CancelAsync(); } }
public Task<Stream> DownloadFile(Uri url) { var tcs = new TaskCompletionSource<Stream>(); var wc = new WebClient(); wc.OpenReadCompleted += (s, e) => { if (e.Error != null) { tcs.TrySetException(e.Error); return; } else if (e.Cancelled) { tcs.TrySetCanceled(); return; } else tcs.TrySetResult(e.Result); }; wc.OpenReadAsync(url); MessageBoxResult result = MessageBox.Show("Started downloading media. Do you like to stop the download ?", "Purpose Color", MessageBoxButton.OKCancel); if( result == MessageBoxResult.OK ) { progress.HideProgressbar(); wc.CancelAsync(); return null; } return tcs.Task; }
private void ExecuteWebRequest(string url, Action<string> callback, Action<Exception> error) { WebClient webClient = new WebClient(); // create a timeout timer Timer timer = null; TimerCallback timerCallback = state => { timer.Dispose(); webClient.CancelAsync(); error(new TimeoutException()); }; timer = new Timer(timerCallback, null, 5000, 5000); // create a web client webClient.DownloadStringCompleted += (s, e) => { timer.Dispose(); try { string result = e.Result; _marshal.Invoke(() => callback(result)); } catch (Exception ex) { _marshal.Invoke(() => error(ex)); } }; webClient.DownloadStringAsync(new Uri(url)); }
public void Defaults () { WebClient wc = new WebClient (); CheckDefaults (wc); // does nothing if no async operation is in progress wc.CancelAsync (); }
private void ExecuteWebRequest(string url, Action<string> callback, Action<Exception> error) { DispatcherTimer timer = new DispatcherTimer(); // create a web client to fetch the URL results WebClient webClient = new WebClient(); webClient.DownloadStringCompleted += (s, e) => { timer.Stop(); try { string result = e.Result; callback(result); } catch (Exception ex) { error(ex); } }; // initiate the download webClient.DownloadStringAsync(new Uri(url)); // create a timeout timer timer.Interval = TimeSpan.FromSeconds(5); timer.Start(); timer.Tick += (s, e) => { timer.Stop(); webClient.CancelAsync(); error(new TimeoutException()); }; }
//Button2のClickイベントハンドラ private void Button2_Click(object sender, EventArgs e) { //非同期ダウンロードをキャンセルする if (downloadClient != null) { downloadClient.CancelAsync(); } }
public async Task<IEnumerable<VersionDescription>> DownloadVersionInfoTaskAsync( Uri source, CancellationToken cancel_token) { var client = new WebClient(); cancel_token.Register(() => client.CancelAsync()); return ParseAppCast( System.Text.Encoding.UTF8.GetString( await this.client.DownloadDataTaskAsync(source))); }
public void Update(Product product) { string url = product.DownloadLink; string filePath = Path.Combine(Path.GetTempPath(), Path.GetFileName(url)); if (webClient.IsBusy) { webClient.CancelAsync(); } webClient.DownloadFileAsync(new Uri(url), filePath); }
public static void WebClientAsync(WebClient client, string url) { if (client.IsBusy) client.CancelAsync(); try { client.DownloadStringAsync(new Uri(url, UriKind.Absolute)); } catch (Exception) { } }
private void PerformExtractPHP(Action onComplete) { SetProgress("Detecting PHP..."); if (Directory.Exists("C:\\PHP")) { SetProgress("C:\\PHP already exists. Assuming PHP is installed (continuing in 2 seconds)."); Thread.Sleep(2000); onComplete(); return; } else { SetProgress("Downloading PHP package..."); var client = new WebClient(); client.DownloadProgressChanged += (sender, e) => { if (_installThread == null) client.CancelAsync(); SetProgress("Downloading PHP package (" + e.ProgressPercentage + "% complete)..."); }; client.DownloadFileCompleted += (sender, e) => { if (_installThread == null) return; SetProgress("Extracting PHP package..."); var zip = new ZipFile(Path.Combine(Path.GetTempPath(), "PHP.zip")); Directory.CreateDirectory("C:\\PHP"); foreach (ZipEntry entry in zip) { if (!entry.IsFile) continue; var entryFileName = entry.Name; var buffer = new byte[4096]; var zipStream = zip.GetInputStream(entry); String fullZipToPath = Path.Combine("C:\\PHP", entryFileName); string directoryName = Path.GetDirectoryName(fullZipToPath); if (directoryName.Length > 0) Directory.CreateDirectory(directoryName); using (var streamWriter = File.Create(fullZipToPath)) StreamUtils.Copy(zipStream, streamWriter, buffer); } if (_installThread != null) onComplete(); }; client.DownloadFileAsync( new Uri("http://windows.php.net/downloads/releases/php-5.4.14-nts-Win32-VC9-x86.zip"), Path.Combine(Path.GetTempPath(), "PHP.zip")); } }
public void PostToImgur(string filename) { changeValueEnabled(); Bitmap bitmap = new Bitmap(filename); MemoryStream memoryStream = new MemoryStream(); bitmap.Save(memoryStream, ImageFormat.Jpeg); using (var w = new WebClient()) { w.UploadProgressChanged += new UploadProgressChangedEventHandler(delegate(object send, UploadProgressChangedEventArgs arg) { int percent = arg.ProgressPercentage; progressBar.Value = percent > 0 ? (percent < 45 ? percent * 2 : (percent >= 90 ? percent : 90)) : 0; }); this.FormClosing += new FormClosingEventHandler(delegate(object send, FormClosingEventArgs arg) { w.CancelAsync(); }); var values = new NameValueCollection { { "key", IMGUR_API_KEY }, { "image", Convert.ToBase64String(memoryStream.ToArray()) } }; string debug = values.ToString(); byte[] response = new byte[0]; w.UploadValuesCompleted += new UploadValuesCompletedEventHandler(delegate(object send, UploadValuesCompletedEventArgs arg) { if (arg.Cancelled) return; response = arg.Result; XDocument xDocument = XDocument.Load(new MemoryStream(response).ToString()); bitmap.Dispose(); _address = (string)xDocument.Root.Element("original_image"); this.Close(); }); w.UploadValuesAsync(new Uri("http://imgur.com/api/upload.xml"), values); buttonClose.Click -= buttonClose_Click; buttonClose.Click += new EventHandler(delegate(object send, EventArgs arg) { w.CancelAsync(); changeValueEnabled(); buttonClose.Click += buttonClose_Click; }); } }
/// <summary> /// Starts the video download. /// </summary> /// <exception cref="IOException">The video file could not be saved.</exception> /// <exception cref="WebException">An error occured while downloading the video.</exception> public override void Execute() { // We need a handle to keep the method synchronously var handle = new ManualResetEvent(false); var client = new WebClient(); bool isCanceled = false; client.DownloadFileCompleted += (sender, args) => { handle.Close(); client.Dispose(); // DownloadFileAsync passes the exception to the DownloadFileCompleted event, if one occurs if (args.Error != null && !args.Cancelled) { throw args.Error; } handle.Set(); }; client.DownloadProgressChanged += (sender, args) => { var progressArgs = new ProgressEventArgs(args.ProgressPercentage); // Backwards compatibility this.OnProgressChanged(progressArgs); if (this.DownloadProgressChanged != null) { this.DownloadProgressChanged(this, progressArgs); if (progressArgs.Cancel && !isCanceled) { isCanceled = true; client.CancelAsync(); } } }; this.OnDownloadStarted(EventArgs.Empty); client.DownloadFileAsync(new Uri(this.Video.DownloadUrl), this.SavePath); handle.WaitOne(); this.OnDownloadFinished(EventArgs.Empty); }
static async void Example11() { System.Net.WebClient wc = new System.Net.WebClient(); wc.DownloadProgressChanged += (sender, args) => { Console.WriteLine(args.ProgressPercentage + "% complete"); }; await Task.Delay(5000).ContinueWith(ant => wc.CancelAsync()); try { await wc.DownloadFileTaskAsync("https://www.oreilly.com/", "code.html"); } catch (WebException we) { Console.WriteLine(we.Status == WebExceptionStatus.RequestCanceled); } }
private void OnApplicationExit(object sender, FormClosingEventArgs e) { if (g_updating) { var res = MessageBox.Show("Stop program update and Exit?\n\nTo resume update click Cancel\nTo continue without the patch update click OK", "Annihilus Launcher", MessageBoxButtons.OKCancel); if (res == DialogResult.OK) { g_webClient.CancelAsync(); //try { // System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + "AnnihilusUpdater(temp).exe"); //} //catch (Exception ex) { // MessageBox.Show(ex.ToString(), "error"); //} } e.Cancel = res == DialogResult.Cancel; } }
private void progressTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { try { if (!wc.IsBusy) { // TODO: how to get the error cause here? GuiLogMessage("AutoUpdate: Download failed.", NotificationLevel.Warning); wc.CancelAsync(); progressTimer.Stop(); CurrentState = State.UpdateAvailable; } } catch (Exception ex) { GuiLogMessage("AutoUpdate: Error during download: " + ex.Message, NotificationLevel.Error); } }
public string DownloadInstaller(Control aOwner, Version aVersion) { WebClient Client = new WebClient(); Client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(Client_DownloadProgressChanged); Client.DownloadFileCompleted += new AsyncCompletedEventHandler(Client_DownloadFileCompleted); string destinationPath = Path.Combine(Path.GetTempPath(), string.Format("FlySightViewer-{0}-setup.exe", aVersion)); Uri downloadUrl = new Uri(string.Format("http://tomvandijck.com/flysight/FlySightViewer-{0}-setup.exe", aVersion)); Client.DownloadFileAsync(downloadUrl, destinationPath); if (ShowDialog(aOwner) == System.Windows.Forms.DialogResult.OK) { return destinationPath; } Client.CancelAsync(); return null; }
private WebClient GetWebClient(CancellationToken cancelToken, IProgress<DownloadProgressChangedEventArgs> progress) { var wc = new WebClient { BaseAddress = BaseAddress, CachePolicy = CachePolicy, UseDefaultCredentials = UseDefaultCredentials, Credentials = Credentials, Headers = Headers, Proxy = Proxy }; if (!string.IsNullOrEmpty(ApiKey)) wc.QueryString["key"] = ApiKey; if (cancelToken != CancellationToken.None) cancelToken.Register(() => wc.CancelAsync()); if (progress != null) wc.DownloadProgressChanged += (sender, args) => progress.Report(args); return wc; }
public Form1() { InitializeComponent(); client = new WebClient(); client.Disposed += (s, e) => { DownloadBar.Value = 0; client.CancelAsync(); while (client.IsBusy) ; try { if (File.Exists(this.tbFile.Text)) File.Delete(this.tbFile.Text); } catch(Exception ex) { /*FAIL!*/ } this.btBrowse.Enabled = true; this.btDownload.Enabled = true; this.btCancel.Enabled = false; }; client.DownloadDataCompleted += (s, e) => { DownloadBar.Value = 0; this.btBrowse.Enabled = true; this.btDownload.Enabled = true; this.btCancel.Enabled = false; this.Refresh(); }; client.DownloadProgressChanged += (s, e) => { DownloadBar.Value = e.ProgressPercentage; this.Refresh(); }; }
protected virtual void Dispose(bool disposing) { if (!disposing) { return; } if (webClient != null) { if (entry != null) { webClient.CancelAsync(); } webClient.Dispose(); webClient = null; } if (entry != null) { entry.Dispose(); entry = null; } }
public async Task<string> GetDocumentAsync(string address, CancellationToken cancel) { if (string.IsNullOrWhiteSpace(address)) { throw new ArgumentNullException("address"); } try { using (WebClient client = new WebClient()) { using (CancellationTokenRegistration registration = cancel.Register(() => client.CancelAsync())) { return await client.DownloadStringTaskAsync(address); } } } catch (Exception ex) { throw new IOException("Unable to get document from: " + address, ex); } }
public static bool WGet(string URL, string destFileName) { DateTime EndTime = DateTime.Now.AddSeconds(30); try { WebClient Client = new WebClient(); Client.DownloadFileAsync(new Uri(URL), destFileName); while ((Client.IsBusy) && (DateTime.Now < EndTime)) { System.Threading.Thread.Sleep(200); } if (Client.IsBusy) Client.CancelAsync(); Client.Dispose(); } catch { if (File.Exists(destFileName)) File.Delete(destFileName); return false; } return true; }
public Task<byte[]> Download(string uri, IDownloadNotifier notifier, CancellationToken cancellationToken) { //var req = (HttpWebRequest)WebRequest.Create(uri); //var res = (HttpWebResponse)req.GetResponse(); //return StreamUtil.ReadFully(res.GetResponseStream()); var tcs = new TaskCompletionSource<byte[]>(); var wc = new WebClient(); if (notifier != null) { notifier.ReportStart(); wc.DownloadProgressChanged += (s, ea) => { notifier.ReportProgress(ea.BytesReceived, ea.TotalBytesToReceive); if (cancellationToken.IsCancellationRequested) wc.CancelAsync(); }; } wc.DownloadDataCompleted += (s, ea) => { var d = uri; if (notifier != null) notifier.ReportFinish(); if (ea.Error != null) tcs.SetException(ea.Error); else if (ea.Cancelled) tcs.SetCanceled(); else tcs.SetResult(ea.Result); }; wc.DownloadDataAsync(new Uri(uri)); return tcs.Task; }
#pragma warning disable 1998 /// <summary> /// Downloads the new version to a temporary folder and provides the generated filename. /// The progress delegate returns, if the download process should be canceled. Return false, if not. /// </summary> /// <param name="this">The this.</param> /// <param name="progress">The progress.</param> /// <param name="completed">callbakc when download is completed.</param> /// <returns> /// Filename of the msi-file /// </returns> public static async Task<string> DownloadMsi(this IAppVersion @this, Func<DownloadProgressInformation, bool> progress = null, Action completed = null) { var tmpFilenameWithPath = Path.GetTempFileName(); var msiFilenameWithPath = Path.GetFileNameWithoutExtension(tmpFilenameWithPath); msiFilenameWithPath += ".msi"; msiFilenameWithPath = Path.Combine(Path.GetDirectoryName(tmpFilenameWithPath), msiFilenameWithPath); File.Move(tmpFilenameWithPath, msiFilenameWithPath); var uri = new Uri(HockeyClient.Current.AsInternal().ApiBaseVersion2 + "apps/" + HockeyClient.Current.AsInternal().AppIdentifier + "/app_versions/" + @this.Id + ".msi"); WebClient wc = new WebClient(); if (progress != null) { wc.DownloadProgressChanged += (a, b) => { if (progress(new DownloadProgressInformation(b.ProgressPercentage, b.BytesReceived, b.TotalBytesToReceive))) { wc.CancelAsync(); }; }; } if(completed != null){ wc.DownloadFileCompleted += (a,b) => completed(); } wc.DownloadFileAsync(uri, msiFilenameWithPath); if (_downloadFilesnames.ContainsKey(@this.AppId)) { _downloadFilesnames[@this.AppId] = msiFilenameWithPath; } else { _downloadFilesnames.Add(@this.AppId, msiFilenameWithPath); } return msiFilenameWithPath; }
public string Send(int timeoutSec = 10) { var wc = new WebClient(); wc.UploadValuesCompleted += wc_UploadValuesCompleted; wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); wc.Headers.Add("Origin", "http://elpis.adamhaile.net"); if (PRequest.Proxy != null) wc.Proxy = PRequest.Proxy; wc.UploadValuesAsync(new Uri(_url), "POST", _params); DateTime start = DateTime.Now; while (!_uploadComplete && ((DateTime.Now - start).TotalMilliseconds < (timeoutSec * 1000))) Thread.Sleep(25); if (_uploadComplete) return _uploadResult; wc.CancelAsync(); throw new Exception("Timeout waiting for POST to " + _url); }
public void Cancelation () { WebClient wc = new WebClient (); var progress = new ManualResetEvent (false); wc.DownloadProgressChanged += delegate { progress.Set (); }; // Try downloading some large file, so we don't finish early. var url = "http://download.mono-project.com/archive/2.10.9/macos-10-x86/11/MonoFramework-MDK-2.10.9_11.macos10.xamarin.x86.dmg"; var task = wc.DownloadDataTaskAsync (url); Assert.IsTrue (progress.WaitOne (10000), "#1"); wc.CancelAsync (); try { task.Wait (); Assert.Fail ("#2"); } catch (Exception ex) { if (ex is AggregateException) ex = ((AggregateException)ex).InnerException; Assert.IsInstanceOfType (typeof (OperationCanceledException), ex, "#3"); Assert.IsTrue (task.IsCanceled, "#4"); } }
/// <summary> /// Downloads a file from the specified Uri to a specified destination /// </summary> /// <param name="urlString">The Uri containing the web addres of the file to be downloaded.</param> /// <param name="destination">The destination of the file to be downloaded. Includes the filename.</param> /// <returns></returns> private bool DownloadFile(string url, string destination) { bool SkipDownload = false; //bool SkipCopy = false; int RemoteFileSize = 0; int iRunningByteTotal = 0; //DateTime previousTickTime; //TimeSpan tickDuration; //int previousPercentage = 0; //Int64 TickRunningByte = 0; bool returnValue = true; string MethodProgress = ""; Uri validUrl = null; string tmpDestination = ""; //double dProgressPercentage = 0; //int iProgressPercentage = 0; try { SkipDownload = !Uri.TryCreate(url, UriKind.Absolute, out validUrl); tmpDestination = _globalPackDir + "\\" + FileNameFromUri(url); SetDownloadLabelTextMain("Downloading"); SetDownloadLabelTextSub("Preparing download"); SetDownloadProgressbarProgress(0); SetDownloadProgressbarMarqueueStyle(ProgressBarStyle.Continuous); SetDownloadPanelVisibility(true); if (validUrl != null) { System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); SetAllowUnsafeHeaderParsing20(); System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); response.Close(); RemoteFileSize = (int)response.ContentLength; // gets the size of the file in bytes iRunningByteTotal = 0; // keeps track of the total bytes downloaded so we can update the progress bar //check if pack has already been downloaded if (File.Exists(tmpDestination)) { if (new FileInfo(tmpDestination).Length == RemoteFileSize) //file exists, but what about the size ? (to filter out incomplete downloads) { if (MessageBox.Show("The file " + new FileInfo(tmpDestination).Name + " with matching size was found on the disk." + Environment.NewLine + "Do you want to use that file instead of downloading it again?", "Existing file found", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes) { SkipDownload = true; } } } } else { if (!File.Exists(tmpDestination)) throw new Exception("The file " + new FileInfo(tmpDestination).Name + " could not be downloaded and was not found on the disk. If you downloaded it manually, then please make sure you placed it in the " + _globalPackDir + " folder"); } if (!SkipDownload) { //download the pack SetDownloadPanelVisibility(true); //SetDownloadLabelTextMain("Downloading"); //SetDownloadProgressbarProgress(0); using (System.Net.WebClient client = new System.Net.WebClient()) { // open the file at the remote URL for reading MethodProgress = "Using streamRemote"; client.DownloadProgressChanged += client_DownloadProgressChanged; client.DownloadFileCompleted += client_DownloadFileCompleted; LastDownloadTickTime = DateTime.Now; DownloadingFile = true; client.DownloadFileAsync(validUrl, tmpDestination); SetDownloadLabelTextSub(new FileInfo(tmpDestination).Name); SetDownloadCancelButtonVisibility(true); while (client.IsBusy)//(DownloadingFile) { Thread.Sleep(100); if (CloseAllThreads || _abortDownload) client.CancelAsync(); } //if (CloseAllThreads) // break; if (_abortDownload) { MessageBox.Show("The download has been cancelled by the user.", "Download Cancelled!"); returnValue = false; //client.CancelAsync(); DownloadingFile = false; //break; } //using (System.IO.Stream streamRemote = client.OpenRead(urlString)) //{ // // using the FileStream object, we can write the downloaded bytes to the file system // MethodProgress = "Using streamLocal"; // using (Stream streamLocal = new FileStream(destination, FileMode.Create, FileAccess.Write, FileShare.None)) // { // // loop the stream and get the file into the byte buffer // int iByteSize = 0; // //byte[] byteBuffer = new byte[RemoteFileSize]; // byte[] byteBuffer = new byte[4096]; // previousTickTime = DateTime.Now; // SetDownloadLabelTextSub(new FileInfo(destination).Name); // SetDownloadCancelButtonVisibility(true); // MethodProgress = "While... streamRemote.read "; // while ((iByteSize = streamRemote.Read(byteBuffer, 0, byteBuffer.Length)) > 0) //...ngByteTotal, byteBuffer.Length)) // { // //aborts the download if a cancel request have been made // if (CloseAllThreads) // break; // if (_abortDownload) // { // MessageBox.Show("The download has been cancelled by the user.", "Download Cancelled!"); // returnValue = false; // break; // } // // write the bytes to the file system at the file path specified // MethodProgress = "streamLocal.Write"; // streamLocal.Write(byteBuffer, 0, iByteSize); // iRunningByteTotal += iByteSize; // // calculate the progress out of a base "100" // //double dIndex = (double)(iRunningByteTotal); // //double dTotal = RemoteFileSize; //(double)byteBuffer.Length; // //dProgressPercentage = ((double)iRunningByteTotal / (double)RemoteFileSize); // iProgressPercentage = (int)(((double)iRunningByteTotal / (double)RemoteFileSize) * 100); // // update the progress bar // //backgroundWorker1.ReportProgress(iProgressPercentage); // if (previousPercentage < iProgressPercentage) // { // tickDuration = DateTime.Now - previousTickTime; // double speed = (1 / tickDuration.TotalSeconds) * (iRunningByteTotal - TickRunningByte); // previousTickTime = DateTime.Now; // TickRunningByte = iRunningByteTotal; // SetDownloadLabelSpeedAndProgressText(string.Format("{0} KB/s", Math.Floor(speed / 1024)), string.Format("{0} / {1} MB", iRunningByteTotal / 1048576, RemoteFileSize / 1048576)); // SetDownloadProgressbarProgress(iProgressPercentage); // previousPercentage = iProgressPercentage; // } // } // // clean up the file stream // streamLocal.Close(); // } // // close the connection to the remote server // streamRemote.Close(); //} } if (!_abortDownload) { SetDownloadProgressbarProgress(100); SetDownloadLabelTextMain("Download Complete"); } } if (_abortDownload && !CloseAllThreads) { File.Delete(tmpDestination); _abortDownload = false; SetDownloadPanelVisibility(false); } if (String.Compare(Path.GetFullPath(tmpDestination).TrimEnd('\\'), Path.GetFullPath(destination).TrimEnd('\\'), StringComparison.InvariantCultureIgnoreCase) != 0) { if (File.Exists(tmpDestination)) { File.Copy(tmpDestination,destination,true); File.Delete(tmpDestination); } else { throw new Exception("The tmpDestination (" + tmpDestination + ") did not exsist when trying to copy it to the correct destination"); } } SetDownloadCancelButtonVisibility(false); } catch (Exception ex) { //ex.Data.Add("DownloadFile() - Url", urlString.OriginalString); ex.Data.Add("DownloadFile() - methodProgress", MethodProgress); ex.Data.Add("DownloadFile() - destination", destination); ex.Data.Add("DownloadFile() - SkipDownload", SkipDownload.ToString()); ex.Data.Add("DownloadFile() - RemoteFileSize", RemoteFileSize.ToString()); ex.Data.Add("DownloadFile() - iRunningByteTotal", iRunningByteTotal.ToString()); throw ex; } return returnValue; }
public void Cancel() { wc.CancelAsync(); }
private void loadSmiles() { using (var wc = new WebClient()) { wc.DownloadStringCompleted += (o, a) => { if (a.Error == null) { JObject stream = (JObject)JsonConvert.DeserializeObject(a.Result.ToString()); if (stream["emoticons"].HasValues) { foreach (JObject jobj in stream["emoticons"]) { if (isStopped) { wc.CancelAsync(); } TwitchSmile smile = new TwitchSmile(); smile.regex = jobj["regex"].ToString(); JArray imgopt = (JArray)JsonConvert.DeserializeObject(jobj["images"].ToString()); smile.width = int.Parse(imgopt[0]["width"].ToString()); smile.height = int.Parse(imgopt[0]["height"].ToString()); smile.uri = new Uri(imgopt[0]["url"].ToString()); if(imgopt[0]["emoticon_set"]!=null) smile.emoticon_set = imgopt[0]["emoticon_set"].ToString(); smile.key = smile.regex; smiles.Add(smile.regex, smile); } } if (smilesLoaded != null) smilesLoaded(this, new EventArgs()); } }; wc.DownloadStringAsync(new Uri(@"https://api.twitch.tv/kraken/chat/emoticons")); } }
// 下载数据文件 // parameters: // strDataFileName 数据文件名。纯粹的文件名。 // strLocalFilePath 本地文件名 // return: // -1 出错 // 0 正常结束 // 1 被用户中断 int DownloadDataFile(string strDataFileName, string strLocalFilePath, out string strError) { strError = ""; string strServerUrl = ""; string strUserName = ""; string strPassword = ""; // 获得数据中心配置参数 int nRet = GetDataCenterParam( out strServerUrl, out strUserName, out strPassword, out strError); if (nRet == -1) return -1; string strPath = strServerUrl + "/" + strDataFileName; Uri serverUri = new Uri(strPath); /* // The serverUri parameter should start with the ftp:// scheme. if (serverUri.Scheme != Uri.UriSchemeFtp) { } * */ // Get the object used to communicate with the server. WebClient request = new WebClient(); this.DownloadException = null; this.DownloadCancelled = false; this.eventDownloadFinished.Reset(); request.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(request_DownloadFileCompleted); request.DownloadProgressChanged += new DownloadProgressChangedEventHandler(request_DownloadProgressChanged); request.Credentials = new NetworkCredential(strUserName, strPassword); try { File.Delete(strLocalFilePath); request.DownloadFileAsync(serverUri, strLocalFilePath); } catch (WebException ex) { strError = "下载数据文件 " + strPath+ " 失败: " + ex.ToString(); return -1; } // 等待下载结束 WaitHandle[] events = new WaitHandle[2]; events[0] = this.eventClose; events[1] = this.eventDownloadFinished; while (true) { if (this.Stopped == true) { request.CancelAsync(); } int index = WaitHandle.WaitAny(events, 1000, false); // 每秒超时一次 if (index == WaitHandle.WaitTimeout) { // 超时 } else if (index == 0) { strError = "下载被关闭信号提前中断"; return -1; } else { // 得到结束信号 break; } } if (this.DownloadCancelled == true) return 1; // 被用户中断 if (this.DownloadException != null) { strError = this.DownloadException.Message; if (this.DownloadException is WebException) { WebException webex = (WebException)this.DownloadException; if (webex.Response is FtpWebResponse) { FtpWebResponse ftpr = (FtpWebResponse)webex.Response; if (ftpr.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable) { return -1; } } } return -1; } return 0; }
public string DownloadFile(Uri remoteLocation, string localFilename, int timeoutMilliseconds, bool showProgress, Request request) { if (request == null) { throw new ArgumentNullException("request"); } if (remoteLocation == null) { throw new ArgumentNullException("remoteLocation"); } request.Debug("Calling 'WebDownloader::DownloadFile' '{0}','{1}','{2}','{3}'", remoteLocation, localFilename, timeoutMilliseconds, showProgress); if (remoteLocation.Scheme.ToLowerInvariant() != "http" && remoteLocation.Scheme.ToLowerInvariant() != "https" && remoteLocation.Scheme.ToLowerInvariant() != "ftp") { request.Error(ErrorCategory.InvalidResult, remoteLocation.ToString(), Constants.Messages.SchemeNotSupported, remoteLocation.Scheme); return null; } if (localFilename == null) { localFilename = "downloadedFile.tmp".GenerateTemporaryFilename(); } localFilename = Path.GetFullPath(localFilename); // did the caller pass us a directory name? if (Directory.Exists(localFilename)) { localFilename = Path.Combine(localFilename, "downloadedFile.tmp"); } // make sure that the parent folder is created first. var folder = Path.GetDirectoryName(localFilename); if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } // clobber an existing file if it's already there. // todo: in the future, we could check the md5 of the file and if the remote server supports it // todo: we could skip the download. if (File.Exists(localFilename)) { localFilename.TryHardToDelete(); } // setup the progress tracker if the caller wanted one. int pid = 0; if (showProgress) { pid = request.StartProgress(0, "Downloading '{0}'", remoteLocation); } #if CORECLR var task = Download(remoteLocation, localFilename, showProgress, request, pid); task.Wait(timeoutMilliseconds); if (!task.IsCompleted) { request.Warning(Constants.Status.TimedOut); request.Debug("Timed out downloading '{0}'", remoteLocation.AbsoluteUri); } #else var webClient = new WebClient(); webClient.Headers.Add("user-agent", "chocolatey command line"); var done = new ManualResetEvent(false); webClient.DownloadFileCompleted += (sender, args) => { if (args.Cancelled || args.Error != null) { localFilename = null; } done.Set(); }; var lastPercent = 0; if (showProgress) { webClient.DownloadProgressChanged += (sender, args) => { // Progress(requestObject, 2, (int)percent, "Downloading {0} of {1} bytes", args.BytesReceived, args.TotalBytesToReceive); var percent = (int)((args.BytesReceived*100)/args.TotalBytesToReceive); if (percent > lastPercent) { lastPercent = percent; request.Progress(pid, (int)((args.BytesReceived*100)/args.TotalBytesToReceive), "To {0}", localFilename); } }; } // start the download webClient.DownloadFileAsync(remoteLocation, localFilename); // wait for the completion if (timeoutMilliseconds > 0) { if (!done.WaitOne(timeoutMilliseconds)) { webClient.CancelAsync(); request.Warning(Constants.Status.TimedOut); request.Debug("Timed out downloading '{0}'", remoteLocation.AbsoluteUri); return null; } } else { // wait until it completes or fails on it's own done.WaitOne(); } #endif // if we don't have the file by this point, we've failed. if (localFilename == null || !File.Exists(localFilename)) { request.CompleteProgress(pid, false); request.Error(ErrorCategory.InvalidResult, remoteLocation.ToString(), Constants.Messages.UnableToDownload, remoteLocation.ToString(), localFilename); return null; } if (showProgress) { request.CompleteProgress(pid, true); } return localFilename; }
private string DownloadQueryResults(string sourceUrl) { if (!string.IsNullOrEmpty(sourceUrl)) { string tempZipDir = Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetRandomFileName())); string tempZipFile = tempZipDir + ".zip"; WebClient webClient = null; bool canceled = false; try { webClient = new WebClient(); bool downloadCompleted = false; webClient.DownloadProgressChanged += delegate(object sender, DownloadProgressChangedEventArgs e) { string msg; if (IsCancelRequested()) { OnCancelRequested(); if (!canceled) { webClient.CancelAsync(); } canceled = true; return; } if (e.BytesReceived < 1000*1024) msg = string.Format("Retrieving images ({0:0.00}KB)", ((float) e.BytesReceived)/1024); else msg = string.Format("Retrieving images ({0:0.00}MB)", ((float) e.BytesReceived)/1000/1024); OnProgressUpdated(msg); //OnResultUpdated(Result); }; webClient.DownloadFileCompleted += delegate(object sender, System.ComponentModel.AsyncCompletedEventArgs e) { downloadCompleted = true; }; webClient.DownloadFileAsync(new Uri(sourceUrl), tempZipFile); //webClient.DownloadFile(sourceUrl, tempZipFile); while (!downloadCompleted) System.Threading.Thread.Sleep(500); if (IsCancelRequested()) { OnCancelRequested(); canceled = true; } if (!canceled) { OnProgressUpdated("Processing received images"); //Result.ProgressMessage = "Processing received images"; //OnResultUpdated(Result); try { ZipUtil.UnZipFiles(tempZipFile, tempZipDir, "", false, true); File.Delete(tempZipFile); } catch (Exception ex) { Platform.Log(LogLevel.Error, "Error processing received images", ex); OnError("Error processing received images"); return null; } return tempZipDir; } } finally { if (webClient != null) { webClient.Dispose(); } } } return null; }
public static void Update() { if (updating) return; updating = true; if (updateTimer != null) updateTimer.Dispose(); updateTimer = new System.Timers.Timer(settings.OnlineRulesUpdateInterval * 1000); updateTimer.Elapsed += (sender, e) => { Update(); }; updateTimer.Start(); UpdateStarted(); var client = new WebClient(); var timer = new Timer((arg) => { client.CancelAsync(); Updated(false); }, null, settings.RuleUpdateTimeout, Timeout.Infinite); //client.Proxy = null; client.DownloadStringCompleted += (sender, e) => { timer.Dispose(); if (e.Error != null) Updated(false); else { File.WriteAllText(App.AppDataDirectory + settings.OnlineRulesFileName, e.Result); settings.OnlineRulesLastUpdateTime = DateTime.Now; Updated(true); } updating = false; }; client.DownloadStringAsync(new Uri(settings.OnlineRulesUrl)); }
/// <summary> /// Executes a HTTP GET request and if succesful returns up to the first 1024 bytes read from the /// response to the caller. /// </summary> /// <param name="url">The URL of the server to call.</param> /// <returns>The first 1024 bytes read from the response.</returns> public string WebGet(string url, int timeout) { Timer cancelTimer = null; try { if (!url.IsNullOrBlank()) { using (WebClient webClient = new WebClient()) { if (timeout > 0) { timeout = (timeout > WEBGET_MAXIMUM_TIMEOUT) ? timeout = WEBGET_MAXIMUM_TIMEOUT : timeout; cancelTimer = new Timer(delegate { Log("WebGet to " + url + " timed out after " + timeout + " seconds."); webClient.CancelAsync(); }, null, timeout * 1000, Timeout.Infinite); } Log("WebGet attempting to read from " + url + "."); System.IO.Stream responseStream = webClient.OpenRead(url); if (responseStream != null) { byte[] buffer = new byte[MAX_BYTES_WEB_GET]; int bytesRead = responseStream.Read(buffer, 0, MAX_BYTES_WEB_GET); responseStream.Close(); return Encoding.UTF8.GetString(buffer, 0, bytesRead); } } } return null; } catch (Exception excp) { logger.Error("Exception WebGet. " + excp.Message); Log("Error in WebGet for " + url + "."); return null; } finally { if (cancelTimer != null) { cancelTimer.Dispose(); } } }
static DateTime get(string url) { try { data_received = false; WebClient w = new WebClient(); w.DownloadProgressChanged += new DownloadProgressChangedEventHandler(w_DownloadProgressChanged); Uri uri = new Uri(url); w.DownloadStringAsync(uri); while (w.IsBusy && !data_received) { Application.DoEvents(); } if (w.ResponseHeaders == null) throw(new Exception("This version of the application requires access to the internet to check its validity.\nPlease connect your computer to the internet and restart the application.")); string dts = w.ResponseHeaders["Date"]; w.CancelAsync(); w.Dispose(); if (dts == null || dts.Length <= 0) throw(new Exception("Could not find Date header in the response.")); DateTime dt; if (!DateTime.TryParse(dts, out dt)) throw (new Exception("Could not convert Date header to DateTime.")); return dt; } catch (Exception e) { LogMessage.Exit("Test period validation failed.\n\n" + e.Message); //Environment.Exit(0); } return new DateTime(2100, 1, 1); }
// Retrieve latest version of WhatsApp public async Task GetLatestWhatsAppVersion (string pageUrl) { var getVersion = new WebClient(); string htmlAndroid = getVersion.DownloadString (new Uri(pageUrl)); // Get WhatsApp latest version string[] split = htmlAndroid.Split (new char[] { '>' }); int i = 0; while (i < split.Length) { if (split.GetValue (i).ToString ().StartsWith ("Version")) { split = split.GetValue (i).ToString ().Split (new char[] { ' ', '<' }); latestWhatsAppVersion = split.GetValue (1).ToString ().Trim (); break; } i++; } // Display WhatsApp installed and latest version TextView whatsapp_installed_version = FindViewById<TextView> (Resource.Id.whatsapp_installed_version); TextView whatsapp_latest_version = FindViewById<TextView> (Resource.Id.whatsapp_latest_version); installedWhatsAppVersion = PackageManager.GetPackageInfo ("com.whatsapp", 0).VersionName.Trim (); whatsapp_installed_version.Text = installedWhatsAppVersion; whatsapp_latest_version.Text = latestWhatsAppVersion; fullLatestWhatsAppFilename = filename + "WhatsApp_" + latestWhatsAppVersion + ".apk"; // Load Floating Button var fab = FindViewById<FloatingActionButton> (Resource.Id.fab); // Compare installed and latest WhatsApp version if (CompareVersionReceiver.VersionCompare(installedWhatsAppVersion, latestWhatsAppVersion) < 0) { // There is a new version fab.SetImageDrawable(Resources.GetDrawable(Resource.Drawable.ic_download)); // Preference: Autodownload if (prefAutoDownload) { SetDownloadDialog (); var webClient = new WebClient (); webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler (downloadProgressChanged); webClient.DownloadFileCompleted += new AsyncCompletedEventHandler (downloadWhatsAppFileCompleted); webClient.DownloadFileAsync (new Uri (whatsAppApk), fullLatestWhatsAppFilename); progressDialog.SetTitle (string.Format(Resources.GetString(Resource.String.downloading), "WhatsApp " + latestWhatsAppVersion + "...")); progressDialog.SetButton (Resources.GetString(Resource.String.cancel_button), (object senderCancel, DialogClickEventArgs eCancel) => {webClient.CancelAsync (); progressDialog.Dismiss ();}); progressDialog.Show (); } else { fab.Click += delegate { SetDownloadDialog (); var webClient = new WebClient (); webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler (downloadProgressChanged); webClient.DownloadFileCompleted += new AsyncCompletedEventHandler (downloadWhatsAppFileCompleted); webClient.DownloadFileAsync (new Uri (whatsAppApk), fullLatestWhatsAppFilename); progressDialog.SetTitle (string.Format(Resources.GetString(Resource.String.downloading), "WhatsApp " + latestWhatsAppVersion + "...")); progressDialog.SetButton (Resources.GetString(Resource.String.cancel_button), (object senderCancel, DialogClickEventArgs eCancel) => {webClient.CancelAsync (); progressDialog.Dismiss ();}); progressDialog.Show (); }; } // There is not a new version } else { fab.SetImageDrawable(Resources.GetDrawable(Resource.Drawable.ic_menu_about)); fab.Click += delegate { AlertDialog errorInstalled = new AlertDialog.Builder (this).Create (); errorInstalled.SetTitle (Resources.GetString(Resource.String.latest_installed)); errorInstalled.SetMessage (string.Format(Resources.GetString(Resource.String.latest_installed_description), "WhatsApp " + installedWhatsAppVersion)); errorInstalled.SetButton ((int)DialogButtonType.Positive, Resources.GetString(Resource.String.ok), (object senderClose, DialogClickEventArgs eClose) => errorInstalled.Dismiss ()); errorInstalled.Show (); }; } }
// Retrieve latest version of Beta Updater public async Task GetLatestAppVersion (string pageUrl) { var getVersion = new WebClient(); string htmlAndroid = getVersion.DownloadString (new Uri(pageUrl)); // Get WhatsApp latest version string[] split = htmlAndroid.Split (new char[] { '>' }); int i = 0; while (i < split.Length) { if (split.GetValue (i).ToString ().StartsWith ("v")) { split = split.GetValue (i).ToString ().Split (new char[] { 'v', '<' }); latestAppVersion = split.GetValue (1).ToString ().Trim (); break; } i++; } installedAppVersion = PackageManager.GetPackageInfo ("com.javiersantos.whatsappbetaupdater", 0).VersionName.Trim (); if (CompareVersionReceiver.VersionCompare (installedAppVersion, latestAppVersion) < 0) { appApk = appApk + "v" + latestAppVersion + "/com.javiersantos.whatsappbetaupdater.apk"; AlertDialog appUpdateDialog = new AlertDialog.Builder (this).Create (); appUpdateDialog.SetTitle (string.Format(Resources.GetString(Resource.String.app_update), latestAppVersion)); appUpdateDialog.SetMessage (string.Format(Resources.GetString(Resource.String.app_update_description), Resources.GetString(Resource.String.app_name))); appUpdateDialog.SetButton ((int)DialogButtonType.Positive, Resources.GetString (Resource.String.update_button), (object senderUpdateAppOK, DialogClickEventArgs eUpdateAppOK) => { SetDownloadDialog (); var webClient = new WebClient (); webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler (downloadProgressChanged); webClient.DownloadFileCompleted += new AsyncCompletedEventHandler (downloadAppFileCompleted); webClient.DownloadFileAsync (new Uri (appApk), fullLatestAppFilename); progressDialog.SetTitle (string.Format(Resources.GetString(Resource.String.downloading), Resources.GetString(Resource.String.app_name) + " " + latestAppVersion + "...")); progressDialog.SetButton (Resources.GetString(Resource.String.cancel_button), (object senderCancel, DialogClickEventArgs eCancel) => {webClient.CancelAsync (); progressDialog.Dismiss ();}); progressDialog.Show (); }); appUpdateDialog.SetButton ((int)DialogButtonType.Negative, Resources.GetString(Resource.String.cancel_button), (object senderUpdateAppCancel, DialogClickEventArgs eUpdateAppCancel) => appUpdateDialog.Dismiss ()); appUpdateDialog.SetButton ((int)DialogButtonType.Neutral, Resources.GetString(Resource.String.never_button), (object senderUpdateAppNever, DialogClickEventArgs eUpdateAppNever) => {prefs.Edit().PutBoolean("prefShowAppUpdates", false).Commit(); appUpdateDialog.Dismiss (); }); appUpdateDialog.SetCancelable (false); appUpdateDialog.Show (); } }
public void DownloadAppleDocs (AppleDocInformation infos, CancellationToken token) { if (token.IsCancellationRequested) return; var tempPath = Path.GetTempFileName (); var evt = new ManualResetEvent (false); var evtArgs = new AppleDocEventArgs () { Stage = ProcessStage.Downloading }; WebClient client = new WebClient (); client.DownloadFileCompleted += (sender, e) => HandleAppleDocDownloadFinished (e, tempPath, evt, token); client.DownloadProgressChanged += (sender, e) => { evtArgs.Percentage = e.ProgressPercentage; FireAppleDocEvent (evtArgs); }; FireAppleDocEvent (new AppleDocEventArgs () { Stage = ProcessStage.Downloading, Percentage = -1 }); client.DownloadFileAsync (new Uri (infos.DownloadUrl), tempPath); token.Register (() => client.CancelAsync ()); evt.WaitOne (); }
public static void AmazonUploadContent(string virtuelpath) { if (context.Cache[virtuelpath + _bucketServerName + "-content"] == null) { Uri path = new Uri(GetSiteRoot() + "/" + virtuelpath); string q = path.Query; string qp = HttpUtility.ParseQueryString(q).Get("p"); string qpageId = "-" + qp; string source = null; // Create a request using a URL WebClient wrGETURL = new System.Net.WebClient(); wrGETURL.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore); wrGETURL.UseDefaultCredentials = false; wrGETURL.Encoding = Encoding.UTF8; source = wrGETURL.DownloadString(path); wrGETURL.Dispose(); wrGETURL.CancelAsync(); string contentType = "text/javascript"; // Create a signature for this operation PutObjectRequest putObjReq = new PutObjectRequest(); putObjReq.WithBucketName(_bucketServerName); putObjReq.WithContentType(contentType); putObjReq.WithContentBody(source); putObjReq.WithKey(virtuelpath.Remove(0).GetHashCode() + "-" + qp + ".js"); putObjReq.WithCannedACL(S3CannedACL.PublicRead); var headers = new System.Collections.Specialized.NameValueCollection(); headers.Add("Expires", TimeZoneManager.DateTimeNow.AddMonths(6).ToString("ddd, dd MMM yyyy HH:mm:ss K")); putObjReq.AddHeaders(headers); // COMPRESS file MemoryStream ms = new MemoryStream(); using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true)) { byte[] buffer = Encoding.UTF8.GetBytes(source); zip.Write(buffer, 0, buffer.Length); zip.Flush(); } ms.Position = 0; // Create a signature for this operation PutObjectRequest putObjReqGZ = new PutObjectRequest(); putObjReqGZ.WithBucketName(_bucketServerName); putObjReqGZ.WithContentType(contentType); putObjReqGZ.WithInputStream(ms); putObjReqGZ.WithKey(virtuelpath.Remove(0).GetHashCode() + "-" + qp + ".js.gz"); putObjReqGZ.WithCannedACL(S3CannedACL.PublicRead); var headersGZ = new System.Collections.Specialized.NameValueCollection(); headersGZ.Add("Content-Encoding", "gzip"); headersGZ.Add("Expires", TimeZoneManager.DateTimeNow.AddMonths(6).ToString("ddd, dd MMM yyyy HH:mm:ss K")); putObjReqGZ.AddHeaders(headersGZ); // connect client AmazonS3 s3Client = AWSClientFactory.CreateAmazonS3Client(_amazonID, _amazonSecretKey); s3Client.PutObject(putObjReq); // upload file s3Client.PutObject(putObjReqGZ); // upload file context.Cache.Add(virtuelpath + _bucketServerName + "-content", "isUploaded", null, TimeZoneManager.DateTimeNow.AddDays(30), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null); // clean amazon s3Client.Dispose(); ms.Close(); ms.Flush(); ms.Dispose(); } }