private async Task HandleDownloadAsync(DownloadOperation download, bool start) { try { Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress); if (start) { // Start the download and attach a progress handler. await download.StartAsync().AsTask(cts.Token, progressCallback); } else { // The download was already running when the application started, re-attach the progress handler. await download.AttachAsync().AsTask(cts.Token, progressCallback); } ResponseInformation response = download.GetResponseInformation(); string statusCode = response != null?response.StatusCode.ToString() : String.Empty; } catch (TaskCanceledException) { //LogStatus("Canceled: " + download.Guid, NotifyType.StatusMessage); } catch (Exception ex) { /* * if (!IsExceptionHandled("Execution error", ex, download)) * { * throw; * } */ } }
private async Task HandleDownloadAsync(DownloadOperation download, bool start) { try { Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress); if (start) { // Start the upload and attach a progress handler. await download.StartAsync().AsTask(cts.Token, progressCallback); } else { // The upload was already running when the application started, re-attach the progress handler. await download.AttachAsync().AsTask(cts.Token, progressCallback); } ResponseInformation response = download.GetResponseInformation(); } catch (TaskCanceledException) { XmlDocument toastXML = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02); XmlNodeList texts = toastXML.GetElementsByTagName("text"); texts[0].AppendChild(toastXML.CreateTextNode("HAP+ - Download Canceled")); texts[1].AppendChild(toastXML.CreateTextNode("The download of " + download.ResultFile.Name + " has been Canceled.")); ((XmlElement)toastXML.SelectSingleNode("/toast")).SetAttribute("launch", "{\"type\":\"toast\"}"); ToastNotification toast = new ToastNotification(toastXML); ToastNotificationManager.CreateToastNotifier().Show(toast); } }
private async Task HandleDownloadAsync(DownloadOperation download, bool start) { try { Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress); if (start) { // Start the download and attach a progress handler. await download.StartAsync().AsTask(cts.Token, progressCallback); } else { // The download was already running when the application started, re-attach the progress handler. await download.AttachAsync().AsTask(cts.Token, progressCallback); } ResponseInformation response = download.GetResponseInformation(); } catch (TaskCanceledException) { } catch (Exception ex) { } finally { } }
private async Task HandleDownloadAsync(DownloadOperation download, bool start) { try { //LogStatus("Running: " + download.Guid, NotifyType.StatusMessage); // Store the download so we can pause/resume. activeDownloads.Add(download); Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress); if (start) { // Start the download and attach a progress handler. await download.StartAsync().AsTask(cts.Token, progressCallback); } else { // The download was already running when the application started, re-attach the progress handler. await download.AttachAsync().AsTask(cts.Token, progressCallback); } ResponseInformation response = download.GetResponseInformation(); //LogStatus(String.Format(CultureInfo.CurrentCulture, "Completed: {0}, Status Code: {1}", // download.Guid, response.StatusCode), NotifyType.StatusMessage); } catch (TaskCanceledException) { //LogStatus("Canceled: " + download.Guid, NotifyType.StatusMessage); } catch (Exception ex) { if (!IsExceptionHandled("Execution error", ex, download)) { throw; } } finally { activeDownloads.Remove(download); } }
private async Task HandleDownloadAsync(DownloadOperation download) { try { // For more advanced Background Transfer features, please take a look at the // BackgroundTransfer sample. if (download.Progress.Status == BackgroundTransferStatus.Idle) { await download.StartAsync(); } else { await download.AttachAsync(); } ResponseInformation response = download.GetResponseInformation(); // GetResponseInformation() returns null for non-HTTP transfers (e.g., FTP). string statusCode = response != null?response.StatusCode.ToString() : String.Empty; rootPage.NotifyUser(String.Format(CultureInfo.CurrentCulture, "Successfully completed background download: {0}, Status Code: {1}", download.Guid, statusCode), NotifyType.StatusMessage); } catch (Exception ex) { rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage); } }
/// <summary> /// Handle the Background download operation /// </summary> private async Task HandleDownloadAsync(DownloadOperation download, bool start) { try { Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress); if (start) { ModelDownloadStarted?.Invoke(this, null); await download.StartAsync().AsTask(_cts.Token, progressCallback); } else { await download.AttachAsync().AsTask(_cts.Token, progressCallback); } var response = download.GetResponseInformation(); } catch (TaskCanceledException ex) { } catch (Exception ex) { ModelDownloadError?.Invoke(this, null); } }
private async Task HandleDownloadAsync(DownloadOperation download, DownloadInfo info, bool start) { try { _activeDownloads[info.ChannelId] = download; _cts[info.ChannelId] = new CancellationTokenSource(); var progressCallback = new Progress <DownloadOperation>(downOperation => { DownloadProgress(downOperation, info); }); if (start) { await download.StartAsync().AsTask(_cts[info.ChannelId].Token, progressCallback); } else { await download.AttachAsync().AsTask(_cts[info.ChannelId].Token, progressCallback); } _activeDownloads.Remove(info.ChannelId); _cts.Remove(info.ChannelId); var response = download.GetResponseInformation(); _isDownloading = false; DownloadCompleted(info); } catch (System.Threading.Tasks.TaskCanceledException) { } catch (Exception ex) { _isDownloading = false; DownloadFailture(info, ex.Message); } }
private async Task HandleDownloadAsync(DownloadOperation download, bool start) { try { TransferModel transfer = new TransferModel(); transfer.DownloadOperation = download; transfer.Source = download.RequestedUri.ToString(); transfer.Destination = download.ResultFile.Path; transfer.BytesReceived = download.Progress.BytesReceived; transfer.TotalBytesToReceive = download.Progress.TotalBytesToReceive; transfer.Progress = 0; transfer.Title = download.ResultFile.Name.Replace(".mp4", ""); transfer.PhanTram = "0 %"; App.ViewModel.transfers.Add(transfer); Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress); await download.AttachAsync().AsTask(cancelToken.Token, progressCallback); ResponseInformation response = download.GetResponseInformation(); Debug.WriteLine(String.Format(CultureInfo.CurrentCulture, "Completed: {0}, Status Code: {1}", download.Guid, response.StatusCode)); } catch (TaskCanceledException) { Debug.WriteLine("Canceled: " + download.Guid); } catch (Exception ex) { Debug.WriteLine(ex.ToString()); } finally { App.ViewModel.transfers.Remove(App.ViewModel.transfers.First(p => p.DownloadOperation == download)); activeDownloads.Remove(download); } }
// Note that this event is invoked on a background thread, so we cannot access the UI directly. private void DownloadProgress(DownloadOperation download) { MarshalLog(String.Format("Progress: {0}, Status: {1}", download.Guid, download.Progress.Status)); double percent = 100; if (download.Progress.TotalBytesToReceive > 0) { percent = download.Progress.BytesReceived * 100 / download.Progress.TotalBytesToReceive; } MarshalLog(String.Format(" - Transfered bytes: {0} of {1}, {2}%", download.Progress.BytesReceived, download.Progress.TotalBytesToReceive, percent)); if (download.Progress.HasRestarted) { MarshalLog(" - Download restarted"); } if (download.Progress.HasResponseChanged) { // We've received new response headers from the server. MarshalLog(" - Response updated; Header count: " + download.GetResponseInformation().Headers.Count); // If you want to stream the response data this is a good time to start. // download.GetResultStreamAt(0); } }
private ulong GetTotalBytesToReceive(DownloadOperation downloadOperation) { try { //TotalBytesToReceive有时会抽风返回0 if (downloadOperation.Progress.TotalBytesToReceive != 0) { return(downloadOperation.Progress.TotalBytesToReceive); } else { var response = downloadOperation.GetResponseInformation(); if (response != null && response.Headers.ContainsKey("Content-Length") && ulong.TryParse(response.Headers["Content-Length"], out var total)) { return(total); } return(0); } } catch (Exception) { return(0); } }
private async Task HandleDownload(DownloadOperation download, bool start) { try { activeDownloads.Add(download); Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress); if (start) { await download.StartAsync().AsTask(cts.Token, progressCallback); } else { await download.AttachAsync().AsTask(cts.Token, progressCallback); } ResponseInformation response = download.GetResponseInformation(); string statusCode = response != null?response.StatusCode.ToString() : string.Empty; } catch (Exception ex) { } finally { activeDownloads.Remove(download); } }
//处理正在下载的任务 private async Task HandleDownloadAsync(DownloadOperation download, bool v) { try { TransferModel transfer = new TransferModel(); transfer.DownloadOperation = download; transfer.Source = download.RequestedUri.ToString(); transfer.Destination = download.ResultFile.Path; transfer.BytesReceived = download.Progress.BytesReceived; transfer.TotalBytesToReceive = download.Progress.TotalBytesToReceive; transfer.Progress = 0; transfers.Add(transfer); //当下载进度发生变化时的回调函数 Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(downloadprogressAsync); //监听已存在的后台下载任务 await download.AttachAsync().AsTask(cancelToken.Token, progressCallback); ResponseInformation response = download.GetResponseInformation(); } catch (TaskCanceledException) { await new MessageDialog("任务取消:").ShowAsync(); } catch (Exception ex) { await new MessageDialog("处理下载任务失败:" + ex).ShowAsync(); } finally { transfers.Remove(transfers.First(p => p.DownloadOperation == download)); DownloadList.Remove(download); NoTask.Visibility = Visibility.Visible; } }
/// <summary> /// Hanbdles a single BackgroundDownload for a song. /// </summary> private async void HandleDownload(Track track, DownloadOperation download, bool start) { track.BackgroundDownload = new BackgroundDownload(download); ActiveDownloads.Add(track); Debug.WriteLine("Added {0} to active downloads", track); try { var progressCallback = new Progress <DownloadOperation>(DownloadProgress); if (start) { // Start the BackgroundDownload and attach a progress handler. await download.StartAsync() .AsTask(track.BackgroundDownload.CancellationTokenSrc.Token, progressCallback); } else { // The BackgroundDownload was already running when the application started, re-attach the progress handler. await download.AttachAsync() .AsTask(track.BackgroundDownload.CancellationTokenSrc.Token, progressCallback); } //Download Completed var response = download.GetResponseInformation(); //Make sure it is success if (response.StatusCode < 400) { await DownloadFinishedForAsync(track); } else { Debug.WriteLine("Download status code for {0} is bad :/", track); track.Status = TrackStatus.None; await _libraryService.UpdateTrackAsync(track); await((DownloadOperation)track.BackgroundDownload.DownloadOperation).ResultFile.DeleteAsync(); } } catch { Debug.WriteLine("Download cancelled {0}", track); track.AudioLocalUri = null; track.Status = TrackStatus.None; await _libraryService.UpdateTrackAsync(track); await((DownloadOperation)track.BackgroundDownload.DownloadOperation).ResultFile.DeleteAsync(); } finally { ActiveDownloads.Remove(track); } }
private async Task HandleDownloadAsync(DownloadOperation download, bool start) { DownloadViewModel Selected = Downloads.FirstOrDefault(p => p.Address == download.RequestedUri.ToString()); try { // LogStatus("Running: " + download.Guid, NotifyType.StatusMessage); // Store the download so we can pause/resume. // activeDownloads.Add(download); Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress); if (start) { // Start the download and attach a progress handler. await download.StartAsync().AsTask(cts.Token, progressCallback); } else { // The download was already running when the application started, re-attach the progress handler. await download.AttachAsync().AsTask(cts.Token, progressCallback); } ResponseInformation response = download.GetResponseInformation(); // GetResponseInformation() returns null for non-HTTP transfers (e.g., FTP). string statusCode = response != null?response.StatusCode.ToString() : String.Empty; // download completed Selected.Status = "decompressing..."; Selected.IsDownloadVisible = false; // Unzip var zipFile = await ApplicationData.Current.LocalFolder.GetFileAsync(Selected.FullFileName); var unzipFolder = await FileHelper.GetFolderNotNullAsync( ApplicationData.Current.LocalFolder, "cards"); await ZipHelper.UnZipFileAsync(zipFile, unzipFolder); // end Selected.Complete(); } catch (TaskCanceledException) { // LogStatus("Canceled: " + download.Guid, NotifyType.StatusMessage); } catch (Exception) { if (Selected != null) { await Selected.Delete(); } } finally { // activeDownloads.Remove(download); } }
/// <summary> /// Hanbdles a single BackgroundDownload for a song. /// </summary> /// <param name="song"> /// The song to be downloaded /// </param> /// <param name="download"> /// The download operation /// </param> /// <param name="start"> /// Either the download is started or just handled /// </param> private async void HandleDownload(Song song, DownloadOperation download, bool start) { if (song == null || download == null) { return; } song.Download = new BackgroundDownload(download); ActiveDownloads.Add(song); try { var progressCallback = new Progress <DownloadOperation>(DownloadProgress); if (start) { // Start the BackgroundDownload and attach a progress handler. await download.StartAsync().AsTask(song.Download.CancellationTokenSrc.Token, progressCallback); } else { // The BackgroundDownload was already running when the application started, re-attach the progress handler. await download.AttachAsync().AsTask(song.Download.CancellationTokenSrc.Token, progressCallback); } // Download Completed var response = download.GetResponseInformation(); // Make sure it is success if (response.StatusCode < 400) { await DownloadFinishedForAsync(song); } else { song.SongState = SongState.None; sqlService.UpdateItem(song); download.ResultFile.DeleteAsync(); } } catch { song.SongState = SongState.None; sqlService.UpdateItem(song); download.ResultFile.DeleteAsync(); } finally { ActiveDownloads.Remove(song); } }
private async Task <string> HandleDownloadAsync(DownloadOperation download, bool start) { try { //LogStatus("Running: " + download.Guid, NotifyType.StatusMessage); // Store the download so we can pause/resume. activeDownloads.Add(download); Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress); if (start) { // Start the download and attach a progress handler. await download.StartAsync().AsTask(cts.Token, progressCallback); } else { // The download was already running when the application started, re-attach the progress handler. await download.AttachAsync().AsTask(cts.Token, progressCallback); } ResponseInformation response = download.GetResponseInformation(); // GetResponseInformation() returns null for non-HTTP transfers (e.g., FTP). string statusCode = response != null?response.StatusCode.ToString() : String.Empty; return(statusCode); //LogStatus( // String.Format( // CultureInfo.CurrentCulture, // "Completed: {0}, Status Code: {1}", // download.Guid, // statusCode), // NotifyType.StatusMessage); } catch (TaskCanceledException et) { //LogStatus("Canceled: " + download.Guid, NotifyType.StatusMessage); return(et.Message); } catch (Exception ex) { return(ex.Message); } finally { activeDownloads.Remove(download); } }
private static async Task StartDownload(Uri target, BackgroundTransferPriority priority, string localFilename) { var result = await BackgroundExecutionManager.RequestAccessAsync(); StorageFile destinationFile; destinationFile = await GetLocalFileFromName(localFilename); var group = BackgroundTransferGroup.CreateGroup(Guid.NewGuid().ToString()); group.TransferBehavior = BackgroundTransferBehavior.Serialized; BackgroundTransferCompletionGroup completionGroup = new BackgroundTransferCompletionGroup(); // this will cause the app to be activated when the download completes and // CheckCompletionResult will be called for the final download state RegisterBackgroundTask(completionGroup.Trigger); BackgroundDownloader downloader = new BackgroundDownloader(completionGroup); downloader.TransferGroup = group; group.TransferBehavior = BackgroundTransferBehavior.Serialized; CreateNotifications(downloader); DownloadOperation download = downloader.CreateDownload(target, destinationFile); download.Priority = priority; completionGroup.Enable(); Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress); var downloadTask = download.StartAsync().AsTask(progressCallback); string tag = GetFileNameFromUri(target); CreateToast(tag, localFilename); try { await downloadTask; // Will occur after download completes ResponseInformation response = download.GetResponseInformation(); } catch (Exception) { Debug.WriteLine("Download exception"); } }
private async Task HandleDownloadAsync(DownloadOperation download, bool start) { if (_cts is null) { _cts = new CancellationTokenSource(); } if (_activeDownloads is null) { _activeDownloads = new Dictionary <string, DownloadOperation>(); } try { // Store the download so we can pause/resume. _activeDownloads.TryAdd(download.ResultFile.Path, download); Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress); if (start) { // Start the download and attach a progress handler. await download.StartAsync().AsTask(_cts.Token, progressCallback); } else { // The download was already running when the application started, re-attach the progress handler. await download.AttachAsync().AsTask(_cts.Token, progressCallback); } ResponseInformation response = download.GetResponseInformation(); } catch (TaskCanceledException) { } catch (Exception ex) { if (!IsExceptionHandled(ex)) { throw; } } finally { _activeDownloads.Remove(download.ResultFile.Path); _activeProgress.Remove(download.ResultFile.Path); } }
private async Task HandleDownloadAsync(DownloadOperation download, bool start) { try { // Store the download so we can pause/resume. activeDownloads.Add(download); Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress); if (start) { // Start the download and attach a progress handler. await download.StartAsync().AsTask(cts.Token, progressCallback); } else { // The download was already running when the application started, re-attach the progress handler. await download.AttachAsync().AsTask(cts.Token, progressCallback); } ResponseInformation response = download.GetResponseInformation(); // GetResponseInformation() returns null for non-HTTP transfers (e.g., FTP). string statusCode = response != null?response.StatusCode.ToString() : String.Empty; LogHelper.WriteLine( String.Format( CultureInfo.CurrentCulture, "Completed: {0}, Status Code: {1}", download.Guid, statusCode)); } catch (TaskCanceledException) { LogHelper.WriteLine("Canceled: " + download.Guid); } catch (Exception ex) { if (!IsExceptionHandled("Execution error", ex, download)) { throw; } } finally { activeDownloads.Remove(download); } }
// Note that this event is invoked on a background thread, so we cannot access the UI directly. private void DownloadProgress(DownloadOperation download) { var Selected = Downloads.First(p => p.guid == download.Guid); // DownloadOperation.Progress is updated in real-time while the operation is ongoing. Therefore, // we must make a local copy at the beginning of the progress handler, so that we can have a consistent // view of that ever-changing state throughout the handler's lifetime. BackgroundDownloadProgress currentProgress = download.Progress; // MarshalLog(String.Format(CultureInfo.CurrentCulture, "Progress: {0}, Status: {1}", download.Guid, // currentProgress.Status)); double percent = 0; if (currentProgress.TotalBytesToReceive > 0) { percent = currentProgress.BytesReceived * 100 / currentProgress.TotalBytesToReceive; } Selected.Progress = percent; // MarshalLog(String.Format( // CultureInfo.CurrentCulture, // " - Transfered bytes: {0} of {1}, {2}%", // currentProgress.BytesReceived, // currentProgress.TotalBytesToReceive, // percent)); Selected.Size = currentProgress.TotalBytesToReceive / 1024 / 1024; if (currentProgress.HasRestarted) { // MarshalLog(" - Download restarted"); } if (currentProgress.HasResponseChanged) { // We have received new response headers from the server. // Be aware that GetResponseInformation() returns null for non-HTTP transfers (e.g., FTP). ResponseInformation response = download.GetResponseInformation(); int headersCount = response != null ? response.Headers.Count : 0; // MarshalLog(" - Response updated; Header count: " + headersCount); // If you want to stream the response data this is a good time to start. // download.GetResultStreamAt(0); } }
/// <summary> /// 处理并监视指定的后台下载任务 /// </summary> /// <param name="download">后台下载任务</param> /// <param name="isNew">是否是新增的任务</param> private async Task HandleDownloadAsync(DownloadOperation download, bool isNew) { try { // 构造显示用的相关数据 TransferModel transfer = new TransferModel(); transfer.DownloadOperation = download; transfer.Source = download.RequestedUri.ToString(); transfer.Destination = download.ResultFile.Path; transfer.Progress = download.Progress.Status.ToString() + ": 0 / 0"; _transfers.Add(transfer); WriteLine("Task Count: " + _transfers.Count.ToString()); // 当下载进度发生变化时的回调函数 Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress); if (isNew) { await download.StartAsync().AsTask(_cancelToken.Token, progressCallback); // 启动一个后台下载任务 } else { await download.AttachAsync().AsTask(_cancelToken.Token, progressCallback); // 监视已存在的后台下载任务 } // 下载完成后获取服务端的响应信息 ResponseInformation response = download.GetResponseInformation(); WriteLine("Completed: " + response.ActualUri + ", HttpStatusCode: " + response.StatusCode.ToString()); } catch (TaskCanceledException) // 调用 CancellationTokenSource.Cancel() 后会抛出此异常 { WriteLine("Canceled: " + download.Guid); } catch (Exception ex) { // 将异常转换为 WebErrorStatus 枚举,如果获取到的是 WebErrorStatus.Unknown 则说明此次异常不是涉及 web 的异常 WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult); WriteLine(ex.ToString()); } finally { _transfers.Remove(_transfers.First(p => p.DownloadOperation == download)); } }
private static void DownloadProgress(DownloadOperation download) { BackgroundDownloadProgress currentProgress = download.Progress; double percent = 100; if (currentProgress.TotalBytesToReceive > 0) { percent = currentProgress.BytesReceived * 100 / currentProgress.TotalBytesToReceive; } if (currentProgress.HasResponseChanged) { ResponseInformation response = download.GetResponseInformation(); int headersCount = response != null ? response.Headers.Count : 0; } }
/// <summary> /// Handles the download asynchronous. /// </summary> /// <param name="download">The download.</param> /// <param name="start">if set to <c>true</c> [start].</param> /// <returns></returns> private async Task HandleDownloadAsync(DownloadOperation download, bool start) { try { //LogStatus("Running: " + download.Guid, NotifyType.StatusMessage); // Store the download so we can pause/resume. //activeDownloads.Add(download); cts = new CancellationTokenSource(); //Progress<DownloadOperation> progressCallback = new Progress<DownloadOperation>(DownloadProgress); if (start) { // Start the download and attach a progress handler. await download.StartAsync().AsTask(cts.Token, null); } else { // The download was already running when the application started, re-attach the progress handler. await download.AttachAsync().AsTask(cts.Token, null); } ShowMessageDialog("Download Complete!"); ResponseInformation response = download.GetResponseInformation(); //LogStatus(String.Format("Completed: {0}, Status Code: {1}", download.Guid, response.StatusCode), //NotifyType.StatusMessage); } catch (TaskCanceledException) { //LogStatus("Canceled: " + download.Guid, NotifyType.StatusMessage); } catch (Exception) { ShowMessageDialog("Execution error!12"); //if (!IsExceptionHandled("Execution error", ex, download)) //{ // throw; //} } finally { //activeDownloads.Remove(download); } }
private bool IsFailed(DownloadOperation download) { BackgroundTransferStatus status = download.Progress.Status; if (status == BackgroundTransferStatus.Error || status == BackgroundTransferStatus.Canceled) { return(true); } ResponseInformation response = download.GetResponseInformation(); if (response == null || response.StatusCode != 200) { return(true); } return(false); }
public async void StartAsync() { var progress = DownloadOperation.StartAsync(); progress.Progress = (_, op) => OnProgress(op); await progress .AsTask() .ContinueWith(OnDownloadCompleted); #if DEBUG Debug.WriteLine("DL Operation Headers."); var info = DownloadOperation.GetResponseInformation(); foreach (var header in info.Headers) { Debug.WriteLine(header.Key + ":" + header.Value); } Debug.WriteLine("DL Operation Headers end."); #endif }
private static void DownloadProgress(DownloadOperation download) { // DownloadOperation.Progress is updated in real-time while the operation is ongoing. Therefore, // we must make a local copy so that we can have a consistent view of that ever-changing state // throughout this method's lifetime. BackgroundDownloadProgress currentProgress = download.Progress; (string.Format(CultureInfo.CurrentCulture, "Progress: {0}, Status: {1}", download.Guid, currentProgress.Status)).PrintDebug(); double percent = 100; if (currentProgress.TotalBytesToReceive > 0) { percent = currentProgress.BytesReceived * 100 / currentProgress.TotalBytesToReceive; } (string.Format( CultureInfo.CurrentCulture, " - Transferred bytes: {0} of {1}, {2}%", currentProgress.BytesReceived, currentProgress.TotalBytesToReceive, percent)).PrintDebug(); if (currentProgress.HasRestarted) { (" - Download restarted").PrintDebug(); } if (currentProgress.HasResponseChanged) { // We have received new response headers from the server. // Be aware that GetResponseInformation() returns null for non-HTTP transfers (e.g., FTP). ResponseInformation response = download.GetResponseInformation(); int headersCount = response != null ? response.Headers.Count : 0; (" - Response updated; Header count: " + headersCount).PrintDebug(); // If you want to stream the response data this is a good time to start. // download.GetResultStreamAt(0); } }
public async void StartDownload(string serverAddress) { if (string.IsNullOrWhiteSpace(serverAddress)) { return; } //Select the location for file FileSavePicker picker = new FileSavePicker(); picker.FileTypeChoices.Add("xml文件", new string[] { ".xml" }); StorageFile file = await picker.PickSaveFileAsync(); if (file != null) { BackgroundDownloader downloader = new BackgroundDownloader(); DownloadOperation operation = downloader.CreateDownload(new Uri(serverAddress), file); Progress <DownloadOperation> progressDown = new Progress <DownloadOperation>(new ViewLibrary().ProgressChanged); var opresult = await operation.StartAsync().AsTask(progressDown); try { ResponseInformation response = operation.GetResponseInformation(); Trace.LogStatus(rootPage, String.Format(CultureInfo.CurrentCulture, "Completed: {0}, Status Code: {1}", operation.Guid, response.StatusCode), NotifyType.StatusMessage); } catch (TaskCanceledException) { Trace.LogStatus(rootPage, "Canceled: " + operation.Guid, NotifyType.StatusMessage); } catch (Exception ex) { if (!IsExceptionHandled("Error", ex, operation)) { throw; } } } }
// Note that this event is invoked on a background thread, so we cannot access the UI directly. private void DownloadProgress(DownloadOperation download) { // DownloadOperation.Progress is updated in real-time while the operation is ongoing. Therefore, // we must make a local copy so that we can have a consistent view of that ever-changing state // throughout this method's lifetime. BackgroundDownloadProgress currentProgress = download.Progress; double percent = 100; if (currentProgress.TotalBytesToReceive > 0) { percent = currentProgress.BytesReceived * 100 / currentProgress.TotalBytesToReceive; } var payload = new DownloadProgressChangedEvent(); payload.Identifier = download.Guid; payload.Percent = percent; var transfer = this.TransferHistory.Where(f => f.Identifier == download.Guid).FirstOrDefault(); if (transfer != null) { transfer.PercentComplete = percent; } Messenger.Default.Send <DownloadProgressChangedEvent>(payload); if (currentProgress.HasRestarted) { } if (currentProgress.HasResponseChanged) { // We have received new response headers from the server. // Be aware that GetResponseInformation() returns null for non-HTTP transfers (e.g., FTP). ResponseInformation response = download.GetResponseInformation(); int headersCount = response != null ? response.Headers.Count : 0; } }
private async Task HandleDownloadAsync(DownloadOperation download, bool start) { try { // Store the download so we can pause/resume. activeDownloads.Add(download); Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress); var cts = new CancellationTokenSource(); cancellationTokens.Add(download.Guid, cts); if (start) { // Start the download and attach a progress handler. await download.StartAsync().AsTask(cts.Token, progressCallback); } else { // The download was already running when the application started, re-attach the progress handler. await download.AttachAsync().AsTask(cts.Token, progressCallback); } ResponseInformation response = download.GetResponseInformation(); // GetResponseInformation() returns null for non-HTTP transfers (e.g., FTP). string statusCode = response != null?response.StatusCode.ToString() : String.Empty; } catch (TaskCanceledException) { } catch (Exception ex) { } finally { activeDownloads.Remove(download); } }
private void OnDownloadCompleted(Task <DownloadOperation> task, object arg) { DownloadOperation slowDownload = arg as DownloadOperation; // Append headers. StringBuilder builder = new StringBuilder(); ResponseInformation response = slowDownload.GetResponseInformation(); // Append Task.Status. builder.Append(String.Format("Status: {0}\r\n", task.Status)); // If server never replied, 'response' is null. if (response != null) { builder.Append(String.Format("ActualUri: {0}\r\n", response.ActualUri)); builder.Append(String.Format("StatusCode: {0}\r\n", response.StatusCode)); builder.Append(String.Format("IsResumable: {0}\r\n", response.IsResumable)); foreach (var headerPair in response.Headers) { builder.Append(String.Format("{0}: {1}\r\n", headerPair.Key, headerPair.Value)); } } // Format excpetion info. string exceptionInfo = String.Empty; if (task.Exception != null) { builder.Append(String.Format( "Exception: 0x{0:X8} {1}\r\n", task.Exception.HResult, task.Exception.Message)); } var notAwaited = Dispatcher.RunAsync(CoreDispatcherPriority.High, () => { HeadersBlock.Text = builder.ToString().Trim(); }); }