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(); // GetResponseInformation() returns null for non-HTTP transfers (e.g., FTP). string statusCode = response != null ? response.StatusCode.ToString() : String.Empty; //LogStatus( // String.Format( // CultureInfo.CurrentCulture, // "Completed: {0}, Status Code: {1}", // download.Guid, // statusCode), // NotifyType.StatusMessage); } catch(TaskCanceledException) { //LogStatus("Canceled: " + download.Guid,NotifyType.StatusMessage); } catch{ //if(!IsExceptionHandled("Execution error",ex,download)) { //throw; //} } finally { activeDownloads.Remove(download); } }
private async Task HandleDownloadAsync(DownloadOperation download) { try { activeDownloads.Add(download); await download.StartAsync().AsTask(); Debug.WriteLine("------------------------" + Environment.NewLine + "Download Started" + Environment.NewLine + "Filename : " + download.ResultFile.Name + Environment.NewLine + "Folder : " + download.ResultFile.Path + Environment.NewLine + "------------------------"); ResponseInformation response = download.GetResponseInformation(); } finally { activeDownloads.Remove(download); Debug.WriteLine("------------------------" + Environment.NewLine + "Download Finished" + Environment.NewLine + "Filename : " + download.ResultFile.Name + Environment.NewLine + "Folder : " + download.ResultFile.Path + Environment.NewLine + "------------------------"); } }
// 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 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 = 100; if (currentProgress.TotalBytesToReceive > 0) { percent = currentProgress.BytesReceived * 100 / currentProgress.TotalBytesToReceive; } MarshalLog(String.Format( CultureInfo.CurrentCulture, " - Transfered bytes: {0} of {1}, {2}%", currentProgress.BytesReceived, currentProgress.TotalBytesToReceive, percent)); 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> /// 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 bool IsFailed(DownloadOperation download) { BackgroundTransferStatus status = download.Progress.Status; if (status == BackgroundTransferStatus.Error || status == BackgroundTransferStatus.Canceled) { return true; } ResponseInformation response = download.GetResponseInformation(); if (response.StatusCode != 200) { return true; } return false; }
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); } }
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 e) { //LogStatus("Canceled: " + download.Guid, NotifyType.StatusMessage); } catch (Exception ex) { ShowMessageDialog("Execution error!12"); //if (!IsExceptionHandled("Execution error", ex, download)) //{ // throw; //} } finally { //activeDownloads.Remove(download); } }
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); } }
// 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(CultureInfo.CurrentCulture, "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(CultureInfo.CurrentCulture, " - 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 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); } }
// 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(CultureInfo.CurrentCulture, "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; } var match = _viewModel.DownloadItems.FirstOrDefault(di => di.Uri == download.RequestedUri); var ignore = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { //Progress.Value = percent; if (match != null) { match.Progress = percent; match.Status = download.Progress.Status.ToString(); } }); MarshalLog(String.Format(CultureInfo.CurrentCulture, " - 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); } }
/// <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 static async Task HandleDownloadAsync(DownloadOperation download, bool start, Action<DownloadOperation> downloadProgress) { CancellationTokenSource cts = new CancellationTokenSource(); DownloadCancelOperation opration = new DownloadCancelOperation() { DownloadKey=download.ResultFile.Name, DownLoad = download, CancelToken = cts }; try { Debug.WriteLine("Running: " + download.Guid); // Store the download so we can pause/resume. ActiveDownloads.Add(opration); if (downloadProgress!=null) { 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); } } else { if (start) { await download.StartAsync().AsTask(cts.Token); } else { await download.AttachAsync().AsTask(cts.Token); } } ResponseInformation response = download.GetResponseInformation(); // GetResponseInformation() returns null for non-HTTP transfers (e.g., FTP). string statusCode = response != null ? response.StatusCode.ToString() : String.Empty; Debug.WriteLine( String.Format( CultureInfo.CurrentCulture, "Completed: {0}, Status Code: {1}", download.Guid, statusCode )); } catch (TaskCanceledException) { Debug.WriteLine("Canceled: " + download.Guid); } catch (Exception ex) { if (!IsExceptionHandled("Execution error", ex, download)) { throw; } } finally { opration.CancelToken.Dispose(); ActiveDownloads.Remove(opration); } }
private async void handleDownloadAsync(DownloadOperation download, Episode episode, DownloadState downloadState) { try { logger.LogMessage($"EpisodesViewModel: Registering download of file {download.ResultFile.Name}.", LoggingLevel.Information); activeDownloadsByDownload.Add(download, episode); if (activeDownloadsByEpisode.Keys.Contains(episode)) { activeDownloadsByEpisode[episode].Add(download); } else { activeDownloadsByEpisode.Add(episode, new List<DownloadOperation> { download }); } Progress<DownloadOperation> progressCallback = new Progress<DownloadOperation>(downloadProgress); #if DEBUG download.CostPolicy = BackgroundTransferCostPolicy.Always; #endif if (downloadState == DownloadState.NotStarted) { logger.LogMessage($"EpisodesViewModel: Download hasn't been started yet. Starting it."); await download.StartAsync().AsTask(progressCallback).ConfigureAwait(false); } if (downloadState == DownloadState.AlreadyRunning) { logger.LogMessage($"EpisodesViewModel: Download has been already started. Attaching progress handler to it."); await download.AttachAsync().AsTask(progressCallback); } ResponseInformation response = download.GetResponseInformation(); logger.LogMessage($"EpisodesViewModel: Download of {download.ResultFile.Name} completed. Status Code: {response.StatusCode}", LoggingLevel.Information); await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => episode.Status = Loaded); } catch (TaskCanceledException) { logger.LogMessage("Download cancelled."); await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => episode.Status = CanBeLoaded); await fileUtils.TryDeleteFile(download.ResultFile.Name); } catch (Exception ex) { logger.LogMessage($"EpisodesViewModel: Download error. {ex.Message}", LoggingLevel.Error); await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => episode.Status = CanBeLoaded); await fileUtils.TryDeleteFile(download.ResultFile.Name); } finally { unregisterDownlod(download, episode); } }
private async Task HandleDownloadAsync(DownloadOperation download, bool start, Func<IStorageFile, Task> finish, Action<string> callBack, Action<double> progressHandler) { _progressCall = progressHandler; string notifica = ""; 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) { notifica = "Download Cancelado, tente novamente mais tarde"; //LogStatus("Canceled: " + download.Guid, NotifyType.StatusMessage); } catch (Exception ex) { notifica = "-- Erro desconhecido --"; notifica = string.Format("{0}\n{1}", notifica, ex.ToString()); } finally { _downloadOp = null; } if (notifica == "") { await finish(download.ResultFile); } else { await download.ResultFile.DeleteAsync(); callBack(notifica); } }