StartAsync() public method

public StartAsync ( ) : DownloadOperation>.IAsyncOperationWithProgress
return DownloadOperation>.IAsyncOperationWithProgress
示例#1
0
 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);
     }
 }
示例#2
0
		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);
			}
		}
示例#3
0
        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);
            }

        }
示例#4
0
        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 StartDownloadAsync(DownloadOperation downloadOperation)
 {
     _activeDownload = downloadOperation;
     var progress = new Progress<DownloadOperation>(ProgressCallback);
     await downloadOperation.StartAsync().AsTask(progress);
 }
示例#6
0
        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 HandleDownloadAsync(DownloadOperation downloadOperation)
        {
            var progressCallback = new Progress<DownloadOperation>(this.DownloadProgress);

            await downloadOperation.StartAsync().AsTask(this._CancellationTokenSource.Token, progressCallback);
        }
示例#8
0
        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);
            }
        }
示例#9
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);
            }
        }
示例#10
0
        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 ManageDownloadsAsync(DownloadOperation downloadOperation, bool start)
    {
      try
      {
        _activeDownloadOperationList.Add(downloadOperation);

        Progress<DownloadOperation> downloadProgressCallback = new Progress<DownloadOperation>(ManageDownloadProgress);
        if (start)
        {
          await downloadOperation.StartAsync().AsTask(_cancellationTokenSource.Token, downloadProgressCallback);
        }
        //else
        //{
        //    // downlaod was already running on app-start
        //    await downloadOperation.AttachAsync().AsTask(_cancellationTokenSource.Token, downloadProgressCallback);
        //}
        // TODO report that download with ID: downloadOperation.Guid has finished --> fire an event
      }
      catch (TaskCanceledException)
      {
        // Download Canceled
      }
      catch (Exception ex)
      {
        // TODO add error Handling
      }
      finally
      {
        _activeDownloadOperationList.Remove(downloadOperation);
      }
    }
示例#12
0
        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)
        {
            try
            {
                Progress<DownloadOperation> progressCallback = new Progress<DownloadOperation>(DownloadProgress);
                if (start)
                {
                    await download.StartAsync().AsTask(progressCallback);
                }
                else
                {
                    await download.AttachAsync().AsTask(progressCallback);
                }

            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
                UpdateTaskCompleted();
            }
        }
示例#14
0
        private async void Start_Click(object sender, RoutedEventArgs e)
        {
            BackgroundDownloader downloader = CreateDownloader();
            try
            {
                IStorageFile file = await KnownFolders.PicturesLibrary.CreateFileAsync("downloadFile.txt", CreationCollisionOption.GenerateUniqueName);

                Uri uri = new Uri(UriBox.Text);
                slowDownload = downloader.CreateDownload(uri, file);
                downloadCancellationTokenSource = new CancellationTokenSource();

                ProgressBlock.Text = String.Empty;
                StartBlock.Text = String.Format("Guid: {0}\r\nPath: {1}", slowDownload.Guid, slowDownload.ResultFile.Path);
                HeadersBlock.Text = String.Empty;

                Progress<DownloadOperation> progressCallback = new Progress<DownloadOperation>(OnDownloadProgress);
                var task = slowDownload.StartAsync().AsTask(downloadCancellationTokenSource.Token, progressCallback);
                var notAwaited = task.ContinueWith(OnDownloadCompleted, slowDownload);
            }
            catch (Exception ex)
            {
                DisplayException(ex);
            }
        }
示例#15
0
        private async Task HandleDownloadAsync(DownloadOperation download, bool start)
        {
            // Create progress callback
            Progress<DownloadOperation> progressCallback = new Progress<DownloadOperation>(DownloadProgress);
            // Create cancellation token
            CancellationTokenSource cts = new CancellationTokenSource();

            if (start)
            {
                // Start the download and attach a progress handler.
                await download.StartAsync().AsTask(cts.Token, progressCallback);
            }
            else
            {
                // The download was scheduled in a previous session, re-attach the progress handler.
                await download.AttachAsync().AsTask(cts.Token, progressCallback);
            }
        }
示例#16
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);
            }
        }
示例#17
0
 private async Task<StorageFile> StartDownloadAsync(DownloadOperation downloadOperation)
 {
     try
     {
         Download = downloadOperation;
         await downloadOperation.StartAsync().AsTask(cts.Token, progressCallback);
         CurrentDownloadedBytes += (long)downloadOperation.Progress.BytesReceived;
         return (StorageFile)downloadOperation.ResultFile;
     }
     catch (Exception e)
     {
         Downloading = false;
         CurrentDownloadedBytes = 0;
         foreach (Playlist downloadedPlaylist in currentlyDownloadingPlaylists)
         {
             RemoveDownload(downloadedPlaylist);//may not have even started downloading this playlist when this is called
         }
         currentlyDownloadingPlaylists = new List<Playlist>();
         return null;
     }
 }
        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);
            }
        }
示例#19
0
        private async Task HandleDownloadAsync(DownloadOperation download, bool start, IProgress<int> progress = null, CancellationToken cancelToken = default(CancellationToken))
        {
            var app = Application.Current as App;

            try
            {
                // Store the download so we can pause/resume. 
                app.activeDownloads.Add(download);

                Progress<DownloadOperation> progressCallback = new Progress<DownloadOperation>((operation) =>
                {
                    if (operation.Progress.TotalBytesToReceive != 0)
                    {
                        ulong val = (ulong)(operation.Progress.BytesReceived * 100 / operation.Progress.TotalBytesToReceive);
                        progress.Report((int)val);
                    }
                });

                if (start)
                {
                    // Start the download and attach a progress handler. 
                    await download.StartAsync().AsTask(cancelToken, progressCallback);
                }
                else
                {
                    // The download was already running when the application started, re-attach the progress handler. 
                    await download.AttachAsync().AsTask(cancelToken, progressCallback);
                }
            }
            catch (TaskCanceledException)
            {
            }
            catch (Exception)
            {
            }
            finally
            {
                app.activeDownloads.Remove(download);
            }
        } 
示例#20
0
        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;
                }
            }
        }
示例#21
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);
            }
        }
示例#22
0
 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 StartDownloadAsync(DownloadOperation downloadOperation)
 {
     // backButton_Copy.IsEnabled = false;
     ConnectionProfile connections = NetworkInformation.GetInternetConnectionProfile();
     if (connections != null && connections.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess)
     {
         _activeDownload = downloadOperation;
         var progress = new Progress<DownloadOperation>(ProgressCallback);
         await downloadOperation.StartAsync().AsTask(progress);
     }
     else
     {
         ConnectionException();
     }
 }