public static async Task<DownloadItem> Create(DownloadOperation op) { DownloadItem item = new DownloadItem(); item.Downloader = new BackgroundDownloader(); item.Url = op.RequestedUri.OriginalString; await item.Construct(op); return item; }
public UniversalTransferRequest(DownloadOperation request, Progress<DownloadOperation> callback) { this.request = request; this.callback = callback; if (this.callback != null) { this.callback.ProgressChanged += Request_ProgressChanged; } }
private void DownloadProgress(DownloadOperation download) { double percent = 100; if (download.Progress.TotalBytesToReceive > 0) { percent = download.Progress.BytesReceived*100/download.Progress.TotalBytesToReceive; } PercenTextBlock.Text = string.Format("Concluído: {0}%", percent); }
/// <summary> /// Overrides the base execute logic to use the background downloader to download the file. /// </summary> protected async override void OnExecute() { BT.BackgroundDownloader downloader; if (this.Url.OriginalString.StartsWith(this.LiveClient.ApiEndpoint, StringComparison.OrdinalIgnoreCase)) { if (base.RefreshTokenIfNeeded()) { return; } downloader = new BT.BackgroundDownloader(); if (this.LiveClient.Session != null) { downloader.SetRequestHeader( ApiOperation.AuthorizationHeader, AuthConstants.BearerTokenType + " " + this.LiveClient.Session.AccessToken); } downloader.SetRequestHeader(ApiOperation.LibraryHeader, Platform.GetLibraryHeaderValue()); } else { downloader = new BT.BackgroundDownloader(); } downloader.Group = LiveConnectClient.LiveSDKDownloadGroup; this.cts = new CancellationTokenSource(); this.downloadOp = downloader.CreateDownload(this.Url, this.OutputFile); var progressHandler = new Progress <BT.DownloadOperation>(this.OnDownloadProgress); LiveDownloadOperationResult result = null; Exception webError = null; try { this.downloadOp = await this.downloadOp.StartAsync().AsTask(this.cts.Token, progressHandler); result = this.OutputFile != null ? new LiveDownloadOperationResult(this.OutputFile) : new LiveDownloadOperationResult(this.downloadOp.GetResultStreamAt(0)); } catch (TaskCanceledException) { result = new LiveDownloadOperationResult(null, true); } catch (Exception error) { webError = error; } if (webError != null) { result = await this.ProcessDownloadErrorResponse(webError); } this.OnOperationCompleted(result); }
private void ProgressCallback(DownloadOperation obj) { double progress = ((double)obj.Progress.BytesReceived / obj.Progress.TotalBytesToReceive); DownloadProgress.Value = progress * 100; if (progress >= 1.0) { _activeDownload = null; DownloadButton.IsEnabled = true; } }
private async Task Construct(DownloadOperation op = null) { var folder = KnownFolders.SavedPictures; var fileName = Url.Split('/').Last(); var file = await folder.CreateFileAsync(fileName, CreationCollisionOption.OpenIfExists); if ((await file.GetBasicPropertiesAsync()).Size > 0) file = await folder.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName); File = file; Name = file.Name; Operation = op ?? Downloader.CreateDownload(new Uri(Url), file); Progress = new Progress<DownloadOperation>(HandleProgress); CancellationToken = new CancellationTokenSource(); }
private async Task StartDownloadAsync(DownloadOperation downloadOperation) { try { DownloadButton.IsEnabled = false; _activeDownload.Add(downloadOperation); var progress = new Progress<DownloadOperation>(ProgressCallback); await downloadOperation.StartAsync().AsTask(progress); //await downloadOperation.StartAsync(); } catch(Exception ex) { Debug.WriteLine(ex.Message); } }
private void DownloadProgress(DownloadOperation download) { BackgroundDownloadProgress currentProgress = download.Progress; double percent = 100; if (currentProgress.TotalBytesToReceive > 0) { percent = currentProgress.BytesReceived * 100 / currentProgress.TotalBytesToReceive; } Status.Text = (String.Format( CultureInfo.CurrentCulture, " - Transfered bytes: {0} of {1}, {2}%", currentProgress.BytesReceived, currentProgress.TotalBytesToReceive, percent)); }
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); } }
/// <summary> /// Called from the BTS.DownloadOperation progress event and raise this's download progress. /// </summary> private void OnDownloadProgress(BT.DownloadOperation downloadOp) { Debug.Assert(downloadOp != null); if (downloadOp.Progress.Status != BT.BackgroundTransferStatus.Error && downloadOp.Progress.Status != BT.BackgroundTransferStatus.Canceled) { if (!this.isAttach) { if (this.Progress != null) { this.Progress.Report( new LiveOperationProgress( (long)downloadOp.Progress.BytesReceived, (long)downloadOp.Progress.TotalBytesToReceive)); } } } }
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); } }
/// <summary> /// Attach to a pending download operation. /// </summary> public async void Attach(BT.DownloadOperation downloadOp) { Debug.Assert(downloadOp != null); this.downloadOp = downloadOp; this.isAttach = true; this.cts = new CancellationTokenSource(); var progressHandler = new Progress<BT.DownloadOperation>(this.OnDownloadProgress); try { // Since we don't provide API for apps to attach to pending download operations, we have no // way to invoke the app event handler to provide any feedback. We would just ignore the result here. this.downloadOp = await this.downloadOp.AttachAsync().AsTask(this.cts.Token, progressHandler); } catch { // Ignore errors as well. } }
/// <summary> /// Attach to a pending download operation. /// </summary> public async void Attach(BT.DownloadOperation downloadOp) { Debug.Assert(downloadOp != null); this.downloadOp = downloadOp; this.isAttach = true; this.cts = new CancellationTokenSource(); var progressHandler = new Progress <BT.DownloadOperation>(this.OnDownloadProgress); try { // Since we don't provide API for apps to attach to pending download operations, we have no // way to invoke the app event handler to provide any feedback. We would just ignore the result here. this.downloadOp = await this.downloadOp.AttachAsync().AsTask(this.cts.Token, progressHandler); } catch { // Ignore errors as well. } }
/// <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 void HandleProgress(DownloadOperation op) { BackgroundDownloadProgress currentProgress = op.Progress; TotalSize = currentProgress.TotalBytesToReceive; CurrentSize = currentProgress.BytesReceived; switch (currentProgress.Status) { case BackgroundTransferStatus.Canceled: State = DownloadStates.CANCELED; break; case BackgroundTransferStatus.Completed: State = DownloadStates.SUCCESSFUL; break; case BackgroundTransferStatus.Running: State = DownloadStates.DOWNLOADING; break; case BackgroundTransferStatus.Error: State = DownloadStates.ERROR; break; default: State = DownloadStates.PAUSED; break; } if (TotalSize == CurrentSize) State = DownloadStates.SUCCESSFUL; }
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, bool start) { try { // Store the download so we can pause/resume. activeDownloads.Add(download); if (start) { // Start the download and attach a progress handler. await download.StartAsync(); } else { // The download was already running when the application started, re-attach the progress handler. await download.AttachAsync(); } } catch (TaskCanceledException) { } catch (Exception ex) { } finally { activeDownloads.Remove(download); } }
private async Task<DownloadOperation> GetExistingDownloadAsync() { if (_download != null) { return this._download; } var pendingDownloads = await BackgroundDownloader.GetCurrentDownloadsAsync(); if (pendingDownloads != null) { foreach (var pendingD in pendingDownloads) { if (pendingD.Guid == this.Id) { _download = pendingD; return _download; } } var existing = pendingDownloads.FirstOrDefault(x => x.Guid == Id); _download = existing; return _download; } return null; }
private bool IsExceptionHandled(string title, Exception ex, DownloadOperation download = null) { WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult); if (error == WebErrorStatus.Unknown) { return false; } if (download == null) { LogStatus(String.Format(CultureInfo.CurrentCulture, "Error: {0}: {1}", title, error), NotifyType.ErrorMessage); } else { LogStatus(String.Format(CultureInfo.CurrentCulture, "Error: {0} - {1}: {2}", download.Guid, title, error), NotifyType.ErrorMessage); } return true; }
public async Task StartDownlodAsync() { try { _cts = new CancellationTokenSource(); var source = DownloadUrl; var fileName = GetFileName(); await EnsureRootFolderExistsAsync(); var destinationFile = await _rootFolder.CreateFileAsync( fileName, CreationCollisionOption.OpenIfExists); LocalFileUrl = new Uri(destinationFile.Path); var downloader = new BackgroundDownloader(); //downloader.SuccessToastNotification =this.GetSuccessToastTemplate(); //downloader.FailureToastNotification = new ToastNotification(new XmlDocument()); _download = downloader.CreateDownload(source, destinationFile); Id = _download.Guid; // Attach progress and completion handlers. await HandleDownloadAsync(true); } catch (Exception ex) { var a = 5; } }
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); } }
// Note that this event is invoked on a background thread, so we cannot access the UI directly. private void DownloadProgress(DownloadOperation download) { if (download.Progress.TotalBytesToReceive > 0) { ProgressBarHandler.Instance.ProgressBar.Value = download.Progress.BytesReceived * 100 / download.Progress.TotalBytesToReceive; } }
/// <summary> /// Use as callback of every downloads progress /// </summary> private void DownloadProgress(DownloadOperation download) { //Thread safety comes first! _dispatcherUtility.RunAsync(() => { //Get the associated song BackgroundDownload var songDownload = ActiveDownloads.FirstOrDefault( p => ((DownloadOperation)p.BackgroundDownload.DownloadOperation).Guid == download.Guid); if (songDownload == null) { return; } Debug.WriteLine("Updating song BackgroundDownload progress for {0}", songDownload); songDownload.BackgroundDownload.Status = download.Progress.Status.ToString().ToSentenceCase().Replace("Running", "Downloading"); if (download.Progress.TotalBytesToReceive > 0) { songDownload.BackgroundDownload.BytesToReceive = download.Progress.TotalBytesToReceive; songDownload.BackgroundDownload.BytesReceived = download.Progress.BytesReceived; } else { songDownload.BackgroundDownload.Status = "Waiting"; } }); }
public void ProgressCallback(DownloadOperation obj) { DownloadProgress = 100.0 * (((long)obj.Progress.BytesReceived + DownloadAccessor.Instance.CurrentDownloadedBytes) / (double)DownloadAccessor.Instance.TotalBytes); DownloadProgressText = DownloadAccessor.Instance.ClipsComplete + " / " + DownloadAccessor.Instance.TotalClips + " File(s)"; if (DownloadProgress == 100) { ProgressGridVisibility = Visibility.Collapsed; DownloadAccessor.Instance.currentlyDownloadingPlaylists = new List<Playlist>(); DownloadProgress = 0; DownloadedVisibility = Visibility.Visible; } }
/// <summary> /// 设置下载进度的信息 /// </summary> /// <param name="download"></param> private static void DownloadProgress(DownloadOperation download) { try { TransferModel transfer = transfers.First(p => p.DownloadOperation == download); transfer.Progress = (int)((download.Progress.BytesReceived * 100) / download.Progress.TotalBytesToReceive); transfer.BytesReceived = download.Progress.BytesReceived; transfer.TotalBytesToReceive = download.Progress.TotalBytesToReceive; } catch { } }
private async Task DownloadAsync(DownloadOperation download) { Log(String.Format(CultureInfo.CurrentCulture, "Downloading {0}", download.ResultFile.Name)); try { await download.StartAsync(); LogStatus(String.Format(CultureInfo.CurrentCulture, "Downloading {0} completed.", download.ResultFile.Name), NotifyType.StatusMessage); } catch (TaskCanceledException) { } catch (Exception ex) { if (!IsExceptionHandled("Execution error", ex, download)) { throw; } } }
private void DownloadProgress(DownloadOperation download) { //var task = Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync( // CoreDispatcherPriority.Normal, // () => // { double percent = 100; if (download.Progress.TotalBytesToReceive > 0) { percent = download.Progress.BytesReceived * 100 / download.Progress.TotalBytesToReceive; } Percentage = percent; Status = Math.Abs(Percentage - 100) < 0.1 ? DownloadStatus.Completed : DownloadStatus.Downloading; if (Status == DownloadStatus.Completed) { OnDownloadCompleted(); } // }).AsTask(); //task.FireAndForget(); }
/// <summary> /// Constructor. /// </summary> /// <param name="downloadOperation"></param> internal LiveDownloadOperation(DownloadOperation downloadOperation) { Debug.Assert(downloadOperation != null); this.downloadOperation = downloadOperation; }
// 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); } }
private void Request_ProgressChanged(object sender, DownloadOperation e) { if (TransferProgressChanged != null) TransferProgressChanged(sender, new TransferEventArgs(this)); }
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 + "------------------------"); } }
private async Task RunDownloadsAsync(BackgroundDownloader downloader, ScenarioType type) { // Validating the URI is required since it was received from an untrusted source (user input). // The URI is validated by calling Uri.TryCreate() that will return 'false' for strings that are not valid URIs. // Note that when enabling the text box users may provide URIs to machines on the intrAnet that require // the "Home or Work Networking" capability. if (!Uri.TryCreate(serverAddressField.Text.Trim(), UriKind.Absolute, out baseUri)) { rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage); return; } // Use a unique ID for every button click, to help the user associate downloads of the same run // in the logs. runId++; DownloadOperation[] downloads = new DownloadOperation[3]; try { // First we create three download operations: Note that we don't start downloads immediately. It is // important to first create all operations that should participate in the toast/tile update. Once all // operations have been created, we can start them. // If we start a download and create a second one afterwards, there is a race where the first download // may complete before we were able to create the second one. This would result in the toast/tile being // shown before we even create the second download. downloads[0] = await CreateDownload(downloader, 1, String.Format(CultureInfo.InvariantCulture, "{0}.{1}.FastDownload.txt", type, runId)); downloads[1] = await CreateDownload(downloader, 5, String.Format(CultureInfo.InvariantCulture, "{0}.{1}.MediumDownload.txt", type, runId)); downloads[2] = await CreateDownload(downloader, 10, String.Format(CultureInfo.InvariantCulture, "{0}.{1}.SlowDownload.txt", type, runId)); } catch (FileNotFoundException) { // We were unable to create the destination file. return; } // Once all downloads participating in the toast/tile update have been created, start them. Task[] downloadTasks = new Task[downloads.Length]; for (int i = 0; i < downloads.Length; i++) { downloadTasks[i] = DownloadAsync(downloads[i]); } await Task.WhenAll(downloadTasks); }