public async void Download(string uri, string filename) { Uri source; if (!Uri.TryCreate(uri, UriKind.Absolute, out source)) { return; } string destination = filename.Trim(); if (string.IsNullOrWhiteSpace(destination)) { return; } StorageFile destinationFile; try { destinationFile = await KnownFolders.PicturesLibrary.CreateFileAsync( destination, CreationCollisionOption.GenerateUniqueName); } catch (FileNotFoundException ex) { return; } BackgroundDownloader downloader = new BackgroundDownloader(); DownloadOperation download = downloader.CreateDownload(source, destinationFile); download.Priority = BackgroundTransferPriority.Default; List <DownloadOperation> requestOperations = new List <DownloadOperation>(); requestOperations.Add(download); // If the app isn't actively being used, at some point the system may slow down or pause long running // downloads. The purpose of this behavior is to increase the device's battery life. // By requesting unconstrained downloads, the app can request the system to not suspend any of the // downloads in the list for power saving reasons. // Use this API with caution since it not only may reduce battery life, but it may show a prompt to // the user. UnconstrainedTransferRequestResult result; try { result = await BackgroundDownloader.RequestUnconstrainedDownloadsAsync(requestOperations); } catch (NotImplementedException) { return; } await HandleDownloadAsync(download, true); }
private async Task <bool> HandleDownloadsAsync(List <DownloadOperation> downloads, bool start) { UnconstrainedTransferRequestResult result; try { result = await BackgroundDownloader.RequestUnconstrainedDownloadsAsync(downloads); } catch (NotImplementedException ex) { telemetry.TrackException(ex); } try { List <DownloadOperation> successfullyAddedDownloads = new List <DownloadOperation>(); foreach (var download in downloads) { if (_activeDownloads.TryAdd(download.RequestedUri.ToString(), download)) { successfullyAddedDownloads.Add(download); _totalDownloads++; } } // Store the download so we can pause/resume. foreach (var download in successfullyAddedDownloads) { 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); } } return(true); } catch (TaskCanceledException) { InstallationStep = "Cancelled"; return(false); } catch (Exception ex) { WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult); telemetry.TrackException(ex, new Dictionary <string, string> { { "Scenario", "GettingActiveDownloads" } }); await QuranApp.NativeProvider.ShowErrorMessageBox("Error getting active downloads: " + error.ToString()); return(false); } finally { try { await FinishActiveDownloads(); } catch (Exception ex) { telemetry.TrackException(ex, new Dictionary <string, string> { { "Scenario", "GettingActiveDownloads" } }); } } }
async void StartDownload() { try { //file = await folder.CreateFileAsync(video.Title+video.VideoExtension, CreationCollisionOption.GenerateUniqueName); file = await folder.CreateFileAsync(youtubeVideo.VideoTitle + "." + youtubeVideo.Extension, CreationCollisionOption.GenerateUniqueName); } catch (Exception ex) { } //BackgroundTransferGroup videoGroup = BackgroundTransferGroup.CreateGroup("video"); BackgroundDownloader downloader = new BackgroundDownloader(); //downloader.TransferGroup = videoGroup; string successToastText = "One of your VIDEO downloads has completed"; string failureToastText = "One of your VIDEO downloads has failed"; XmlDocument successToastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01); successToastXml.GetElementsByTagName("text").Item(0).InnerText = successToastText; ToastNotification successToast = new ToastNotification(successToastXml); downloader.SuccessToastNotification = successToast; XmlDocument failureToastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01); failureToastXml.GetElementsByTagName("text").Item(0).InnerText = failureToastText; ToastNotification failureToast = new ToastNotification(failureToastXml); downloader.FailureToastNotification = failureToast; DownloadOperation download = downloader.CreateDownload(source, file); download.CostPolicy = BackgroundTransferCostPolicy.Always; List <DownloadOperation> requestOperations = new List <DownloadOperation>(); requestOperations.Add(download); UnconstrainedTransferRequestResult result; try { result = await BackgroundDownloader.RequestUnconstrainedDownloadsAsync(requestOperations); } catch (NotImplementedException) { return; } //await HandleDownloadAsync(download, true); await Helper.HelperMethods.MessageUser("Your download has been started..."); //gridView = null; //Frame.Navigate((typeof(MainPage))); await HandleDownloadAsync(download, true); //await Task.WhenAll(t); }
private async void StartDownload(BackgroundTransferPriority priority, bool requestUnconstrainedDownload) { // 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. Uri source; if (!Uri.TryCreate(serverAddressField.Text.Trim(), UriKind.Absolute, out source)) { rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage); return; } string destination = fileNameField.Text.Trim(); if (string.IsNullOrWhiteSpace(destination)) { rootPage.NotifyUser("A local file name is required.", NotifyType.ErrorMessage); return; } StorageFile destinationFile; try { destinationFile = await KnownFolders.PicturesLibrary.CreateFileAsync( destination, CreationCollisionOption.GenerateUniqueName); } catch (FileNotFoundException ex) { rootPage.NotifyUser("Error while creating file: " + ex.Message, NotifyType.ErrorMessage); return; } BackgroundDownloader downloader = new BackgroundDownloader(); DownloadOperation download = downloader.CreateDownload(source, destinationFile); Log(String.Format(CultureInfo.CurrentCulture, "Downloading {0} to {1} with {2} priority, {3}", source.AbsoluteUri, destinationFile.Name, priority, download.Guid)); download.Priority = priority; if (!requestUnconstrainedDownload) { // Attach progress and completion handlers. await HandleDownloadAsync(download, true); return; } List <DownloadOperation> requestOperations = new List <DownloadOperation>(); requestOperations.Add(download); // If the app isn't actively being used, at some point the system may slow down or pause long running // downloads. The purpose of this behavior is to increase the device's battery life. // By requesting unconstrained downloads, the app can request the system to not suspend any of the // downloads in the list for power saving reasons. // Use this API with caution since it not only may reduce battery life, but it may show a prompt to // the user. UnconstrainedTransferRequestResult result; try { result = await BackgroundDownloader.RequestUnconstrainedDownloadsAsync(requestOperations); } catch (NotImplementedException) { rootPage.NotifyUser( "BackgroundDownloader.RequestUnconstrainedDownloadsAsync is not supported in Windows Phone.", NotifyType.ErrorMessage); return; } Log(String.Format(CultureInfo.CurrentCulture, "Request for unconstrained downloads has been {0}", (result.IsUnconstrained ? "granted" : "denied"))); await HandleDownloadAsync(download, true); }
public async void Download(string DownloadURL, string DestinationFileName, StorageFile destinationFile, AudioEncodingQuality AudioQuality, bool IsVideo, bool IsM4A) { try { // Temporary destination folder StorageFile tempDestinationFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(DestinationFileName, CreationCollisionOption.GenerateUniqueName); // Add the place where the user wants to save to a dictionary first. Our file will first be saved to a temp folder if (StorageFileDictionary.ContainsKey(tempDestinationFile.Name)) { StorageFileDictionary.Remove(tempDestinationFile.Name); } StorageFileDictionary.Add(tempDestinationFile.Name, destinationFile); // Add to audio encoding quality if (!IsVideo) { if (AudioQualityDictionary.ContainsKey(tempDestinationFile.Name)) { AudioQualityDictionary.Remove(tempDestinationFile.Name); } AudioQualityDictionary.Add(tempDestinationFile.Name, AudioQuality); } // Add to isMusicDictionary if (IsMusicDictionary.ContainsKey(tempDestinationFile.Name)) { IsMusicDictionary.Remove(tempDestinationFile.Name); } IsMusicDictionary.Add(tempDestinationFile.Name, !IsVideo); // Add to M4A dictionary, since Windows Phone doesnt support mp3 if (IsisM4ADictionary.ContainsKey(tempDestinationFile.Name)) { IsisM4ADictionary.Remove(tempDestinationFile.Name); } IsisM4ADictionary.Add(tempDestinationFile.Name, IsM4A); // Create a new instance of background downloader BackgroundDownloader downloader = new BackgroundDownloader(); Uri fileDownloadUri = new Uri(DownloadURL, UriKind.Absolute); DownloadOperation download = downloader.CreateDownload(fileDownloadUri, tempDestinationFile); download.Priority = BackgroundTransferPriority.High; Debug.WriteLine(String.Format(CultureInfo.CurrentCulture, "Downloading {0} to {1} with {2} priority, {3}", fileDownloadUri.AbsoluteUri, DestinationFileName, download.Priority, download.Guid)); List <DownloadOperation> requestOperations = new List <DownloadOperation>(); requestOperations.Add(download); // If the app isn't actively being used, at some point the system may slow down or pause long running // downloads. The purpose of this behavior is to increase the device's battery life. // By requesting unconstrained downloads, the app can request the system to not suspend any of the // downloads in the list for power saving reasons. // Use this API with caution since it not only may reduce battery life, but it may show a prompt to // the user. UnconstrainedTransferRequestResult result; try { result = await BackgroundDownloader.RequestUnconstrainedDownloadsAsync(requestOperations); } catch (NotImplementedException) { Debug.WriteLine("BackgroundDownloader.RequestUnconstrainedDownloadsAsync is not supported in Windows Phone."); return; } Debug.WriteLine(String.Format(CultureInfo.CurrentCulture, "Request for unconstrained downloads has been {0}", (result.IsUnconstrained ? "granted" : "denied"))); await HandleDownloadAsync(download, true); } catch (Exception ex) { IsExceptionHandled("Download Error", ex); } }