예제 #1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="App"/> class.
 /// </summary>
 /// <param name="repositories">The repositories.</param>
 /// <param name="downloader">The downloader.</param>
 /// <param name="episodeSaver">The episode saver.</param>
 public App(
     IRepositoryFactory repositories,
     IPodCastDownloader downloader,
     IEpisodeSaver episodeSaver)
 {
     this.backgroundDownloader =
         new BackgroundDownloader(
             repositories,
             downloader,
             episodeSaver);
     this.Startup +=
         this.App_Startup;
     this.DispatcherUnhandledException +=
         App_DispatcherUnhandledException;
 }
예제 #2
0
        public async static Task SaveAsync(
            Uri fileUri,
            StorageFolder folder,
            string fileName)
        {
            // Hitting System.UnauthorizedAccessException when the file already exists.
            // If they already have it, keep what is there.
            var file = await folder.CreateFileAsync(fileName, CreationCollisionOption.OpenIfExists);

            var downloader = new BackgroundDownloader();
            var download   = downloader.CreateDownload(
                fileUri,
                file);

            await download.StartAsync();
        }
예제 #3
0
        private async void btn_PauseAll_Click(object sender, RoutedEventArgs e)
        {
            var ls = await BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(DownloadHelper2.group);

            foreach (var item in ls)
            {
                try
                {
                    item.Pause();
                }
                catch (Exception)
                {
                }
            }
            // LoadDowning();
        }
예제 #4
0
        private async void btn_D_Pause_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var ls = await BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(DownloadHelper2.group);

                var data = (sender as Button).DataContext as DisplayModel;
                var item = ls.First(x => x.Guid.ToString() == data.guid);

                item.Pause();
                data.backgroundTransferStatus = item.Progress.Status;
            }
            catch (Exception)
            {
            }
        }
예제 #5
0
        public override async Task <bool> OpenFileAsync(ICloudFile fileToDownload, bool forceDownload = false, bool showOpenWith = false)
        {
            var          sourceObject = new Uri(fileToDownload.DownloadSourceLocation);
            IStorageFile file         = null;

            if (fileToDownload.IsQualifiedAsSmallDownload() && !forceDownload)
            {
                file = await StorageFile.CreateStreamedFileFromUriAsync(fileToDownload.Name,
                                                                        sourceObject,
                                                                        null);
            }
            else
            {
                //TODO: Add feature to send as attachment. :D
                //TODO: Verify the code waits till the background download is complete before launching the file.
                var downloader = new BackgroundDownloader();
                file = await DownloadManager.DownloadStorageFileAsync(fileToDownload);

                DownloadOperation operation = downloader.CreateDownload(sourceObject, file);
                var result = await operation.StartAsync();

                file = result.ResultFile;
            }

            //SAD: the following did not work somehow
            //var result = await _liveClient.BackgroundDownloadAsync(objectToDownload.DownloadSourceLocation,);
            //var options = new LauncherOptions();
            //options.DisplayApplicationPicker = true;
            //var result2 = await _liveClient.GetAsync(objectToDownload.Id);

            bool launchResult;

            //Consider LaunchUriAsync(...) for else part?
            if (showOpenWith)
            {
                var options = new LauncherOptions {
                    DisplayApplicationPicker = true
                };
                launchResult = await Launcher.LaunchFileAsync(file, options);
            }
            else
            {
                launchResult = await Launcher.LaunchFileAsync(file);
            }

            return(launchResult);
        }
        private async void start_Click(object sender, RoutedEventArgs e)
        {
            Uri source;

            if (!Uri.TryCreate(sourceUrl.Text.Trim(), UriKind.Absolute, out source))
            {
                status.Log(LocalizableStrings.BACKGROUND_TRANSFER_INVALID_URI);
                return;
            }

            string destination = localFile.Text.Trim();

            if (string.IsNullOrWhiteSpace(destination))
            {
                status.Log(LocalizableStrings.BACKGROUND_TRANSFER_INVALID_FILENAME);
                return;
            }

            StorageFile destinationFile = null;

            try
            {
                destinationFile = await KnownFolders.PicturesLibrary.CreateFileAsync(
                    destination, CreationCollisionOption.GenerateUniqueName);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("BackgroundTransferPage.start_Click: " + ex.ToString());
                status.Log(ex.Message);
                return;
            }

            try
            {
                BackgroundDownloader downloader = new BackgroundDownloader();
                if (downloader != null)
                {
                    DownloadOperation download = downloader.CreateDownload(source, destinationFile);
                    download.Priority = BackgroundTransferPriority.Default;
                    await HandleDownloadAsync(download, true);
                }
            }
            catch (Exception ex)
            {
                status.Log(ex.Message);
            }
        }
예제 #7
0
        private async void StartDownload(BackgroundTransferPriority priority)
        {
            // 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 "Private Networks (Client and Server)" 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;

            // Attach progress and completion handlers.
            await HandleDownloadAsync(download, true);
        }
        internal static async Task InitializeAsync()
        {
            Uri source = new Uri($"http://api.iuwp.top:9000/{Services.SQLiteService.DBNAME}");

            var localFolder = ApplicationData.Current.LocalFolder;
            var file        = await localFolder.TryGetItemAsync(SQLiteService.DBNAME);

            var property = await file.GetBasicPropertiesAsync();

            if (file == null || property.Size < 51200)
            {
                Helpers.NotifyPopup notify;
                if (NetworkHelper.Instance.ConnectionInformation.IsInternetAvailable == false)
                {
                    notify = new Helpers.NotifyPopup("第一次需要连接网络,下载数据库,请连接网络后重新打开应用", TimeSpan.FromSeconds(60));
                    notify.Show();
                    return;
                }
                notify = new Helpers.NotifyPopup("首次启动,正在下载数据库...", TimeSpan.FromSeconds(5));
                notify.Show();

                var destinationFile = await localFolder.CreateFileAsync(
                    SQLiteService.DBNAME, CreationCollisionOption.ReplaceExisting);

                var downloaded = new BackgroundDownloader();
                var download   = downloaded.CreateDownload(source, destinationFile);
                var operation  = await download.StartAsync();

                if (operation.Progress.Status != BackgroundTransferStatus.Completed)
                {
                    notify = new Helpers.NotifyPopup("数据库下载失败,请检查网络状况后,重新开启应用", TimeSpan.FromSeconds(60));
                    notify.Show();
                }
                else
                {
                    notify = new Helpers.NotifyPopup("数据库下载完成,即将自动重启应用", TimeSpan.FromSeconds(5));
                    notify.Show();
                    await Task.Delay(TimeSpan.FromSeconds(5));

                    await CoreApplication.RequestRestartAsync(string.Empty);
                }
            }
            else
            {
                return;
            }
        }
예제 #9
0
        // Click on find-adress button
        // Forming omniBox
        private async void button5_Click(object sender, RoutedEventArgs e)
        {
            string      address = "http://geocode-maps.yandex.ru/1.x/?geocode=" + textBox.Text;
            StorageFile myDB;

            try
            {
                listBox.Visibility     = Visibility.Visible;
                controlsBG2.Visibility = Visibility.Visible;
                controlsBG.Visibility  = Visibility.Collapsed;
                listBox.Items.Clear();
                StorageFile tempFile2 = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("multi", CreationCollisionOption.ReplaceExisting);

                BackgroundDownloader manager2 = new BackgroundDownloader();
                var operation = manager2.CreateDownload(new Uri(address), tempFile2);
                IProgress <DownloadOperation> progressH = new Progress <DownloadOperation>((p) =>
                                                                                           { /*Debug.WriteLine("Transferred: {0}, Total: {1}", p.Progress.BytesReceived, p.Progress.TotalBytesToReceive);*/ });
                await operation.StartAsync().AsTask(progressH);

                //Debug.WriteLine("BacgroundTransfer created");

                // Read the data
                myDB = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync("multi");

                var alldata = await Windows.Storage.FileIO.ReadLinesAsync(myDB);

                datalines = new string[alldata.Count];
                int ko = 0; // counter
                int start;  // first no-hashtag sybol in string
                foreach (var line in alldata)
                {
                    datalines[ko] = line.ToString();
                    ko++;
                    if ((start = datalines[ko - 1].IndexOf("<text>")) != -1)
                    {
                        // forming omniBox
                        int nameLeng = datalines[ko - 1].Length;
                        listBox.Items.Add(datalines[ko - 1].Substring(start + 6, nameLeng - 6 - start - 7));
                    }
                }
                await myDB.DeleteAsync();
            }
            catch (Exception)
            {
                MessageDialog dialog = new MessageDialog("Ошибка при поиске Вашего запроса. Очистите карту и попробуйте построить маршрут снова.", "Ошибка поиска #007101");
            }
        }
예제 #10
0
        // Take Picture
        private async Task TakePicture()
        {
            try
            {
                PictureProgress.Value = 0;
                Uri         uri         = new Uri("http://" + IP + ":8080");
                StorageFile storageFile = await KnownFolders.PicturesLibrary.CreateFileAsync("robot.jpg", CreationCollisionOption.GenerateUniqueName);

                BackgroundDownloader downloader = new BackgroundDownloader();
                DownloadOperation    download   = downloader.CreateDownload(uri, storageFile);
                await PerformDownload(download);
            }
            catch (Exception ex)
            {
                LogMessage(string.Format("Take New Image Error: {0}", ex.Message));
            }
        }
예제 #11
0
        public static async Task preloadMp3SingleAsync(string mp3RemoteUrl)
        {
            var    url      = new Uri(mp3RemoteUrl);
            string filename = System.IO.Path.GetFileName(url.LocalPath);

            if (await isFilePresent(filename))
            {
                // do nothing
            }
            else
            {
                var destinationFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);

                var download = new BackgroundDownloader().CreateDownload(url, destinationFile);
                await download.StartAsync().AsTask();
            }
        }
예제 #12
0
        private async void CreateButDoNotStartDownload_Click(object sender, RoutedEventArgs e)
        {
            BackgroundDownloader downloader = CreateDownloader();

            downloader.ProxyCredential = new Windows.Security.Credentials.PasswordCredential();
            //downloader.ProxyCredential.UserName = "******";
            Debug.WriteLine(downloader.ProxyCredential.UserName.Length);
            Debug.WriteLine(downloader.ProxyCredential.UserName);
            Debug.WriteLine(downloader.ProxyCredential.Password.Length);
            Debug.WriteLine(downloader.ProxyCredential.Password);

            IStorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("neverStarted.txt", CreationCollisionOption.GenerateUniqueName);

            var aDownload = downloader.CreateDownload(new Uri("http://example.com"), file);

            Debug.WriteLine(aDownload.Guid);
        }
예제 #13
0
        public static async Task StartGalleryDownloadAsync(ExGallery gallery, StorageFolder galleryFolder)
        {
            // Download image list
            await gallery.LoadAllItemsAsync();


            BackgroundTransferCompletionGroup completionGroup = new BackgroundTransferCompletionGroup();

            BackgroundTaskBuilder builder = new BackgroundTaskBuilder()
            {
                Name = "DownloadFinished"
            };

            builder.SetTrigger(completionGroup.Trigger);
            BackgroundTaskRegistration taskRegistration = builder.Register();

            BackgroundDownloader downloader = new BackgroundDownloader(completionGroup)
            {
                TransferGroup = BackgroundTransferGroup.CreateGroup("Gallery")
            };

            downloader.TransferGroup.TransferBehavior = BackgroundTransferBehavior.Parallel;


            // Create tasks and file for each pic
            StorageFile[] files = new StorageFile[gallery.Count];
            foreach (var image in gallery)
            {
                files[gallery.IndexOf(image)] = await galleryFolder.CreateFileAsync($"{gallery.IndexOf(image) + 1}.jpg", CreationCollisionOption.ReplaceExisting);
            }

            // Get the image uri and download data for each pic
            List <Task> getImageUriTasks = new List <Task>();

            foreach (var image in gallery)
            {
                if (files[gallery.IndexOf(image)] != null)
                {
                    getImageUriTasks.Add(StartImageDownloadAsync(gallery, image, files[gallery.IndexOf(image)], downloader));
                }
            }
            await Task.WhenAll(getImageUriTasks);


            downloader.CompletionGroup.Enable();
        }
예제 #14
0
        public void ChangeToChapter(string chapter)
        {
            chapter = simple_to_full_chapter_[chapter];

            if (chapter == current_chapter_)
            {
                return;
            }
            current_chapter_ = chapter;

            string url = website_ + current_chapter_;

            if (!chapter_to_background_.ContainsKey(chapter))
            {
                List <Image> new_storage = new List <Image>();
                chapter_to_images_[chapter] = new_storage;
                BackgroundDownloader bd = new BackgroundDownloader(url, new_storage);
                chapter_to_background_[chapter] = bd;
                bd.Start();
            }

            current_page_index_ = 0;

            List <Image> storage = chapter_to_images_[current_chapter_];
            Image        img     = null;

            while (img == null)
            {
                try {
                    Monitor.Enter(storage);
                    if (storage.Count == 0)
                    {
                        continue;
                    }
                    else
                    {
                        img = storage[current_page_index_];
                    }
                }
                finally {
                    Monitor.Exit(storage);
                }
            }

            MangaKitsuneForm.Inst.DrawImage(img);
        }
예제 #15
0
        public static BackgroundDownloader CreateBackgroundDownloader()
        {
            BackgroundTransferCompletionGroup completionGroup = new BackgroundTransferCompletionGroup();

            BackgroundTaskBuilder builder = new BackgroundTaskBuilder();

            builder.TaskEntryPoint = "Tasks.CompletionGroupTask";
            builder.SetTrigger(completionGroup.Trigger);

            // The system automatically unregisters the BackgroundTransferCompletionGroup task when it triggers.
            // You do not need to unregister it explicitly.
            BackgroundTaskRegistration taskRegistration = builder.Register();

            BackgroundDownloader downloader = new BackgroundDownloader(completionGroup);

            return(downloader);
        }
예제 #16
0
        private async void Btn_Resume_Items_Click(object sender, RoutedEventArgs e)
        {
            var data = (sender as Button).DataContext as DownloadDisplayInfo;
            var ls   = await BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(DownloadHelper2.group);

            foreach (var item in ls.Where(x => data.items.Count(y => y.guid == x.Guid.ToString()) != 0))
            {
                try
                {
                    item.Resume();
                }
                catch (Exception)
                {
                }
            }
            //LoadDowning();
        }
예제 #17
0
        private async void AttachDownloads_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                CurrentBlock.Text = String.Empty;
                IReadOnlyList <DownloadOperation> downloads = await BackgroundDownloader.GetCurrentDownloadsAsync();

                foreach (var download in downloads)
                {
                    AttachDownloadOperationHandles(download);
                }
            }
            catch (Exception ex)
            {
                DisplayException(ex);
            }
        }
예제 #18
0
        public async void StartDownloadAsync(string serverAddress)
        {
            // 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(serverAddress.Trim(), UriKind.Absolute, out Uri source))
            {
                //rootPage.ShowMessageBox($"Invalid URI ({serverAddress.Trim()}).");
                return;
            }

            int    index       = serverAddress.LastIndexOf('/');
            string destination = serverAddress.Substring(index + 1);

            if (string.IsNullOrWhiteSpace(destination))
            {
                await ContentDialogs.ShowSingleButtonContentDialogAsync("A local file name is required.");

                return;
            }

            StorageFile destinationFile;

            try
            {
                destinationFile = await SharedData.ArchivedMessagesFolder.CreateFileAsync(destination, CreationCollisionOption.ReplaceExisting);
            }
            catch (FileNotFoundException ex)
            {
                await ContentDialogs.ShowSingleButtonContentDialogAsync("Error while creating file: " + ex.Message);

                return;
            }

            BackgroundDownloader downloader = new BackgroundDownloader();
            DownloadOperation    download   = downloader.CreateDownload(source, destinationFile);

            log.Info(String.Format($"Downloading {source.AbsoluteUri} to {destinationFile.Name}, {download.Guid}"));

            download.Priority = BackgroundTransferPriority.Default;

            // Attach progress and completion handlers.
            await HandleDownloadAsync(download, true);
        }
예제 #19
0
        public static async Task<StorageFile> DownloadAsync(string version, DownloadOption option = DownloadOption.Default)
        {
            if (!MinecraftAPI.IsInitialized)
            {
                Debug.WriteLine($"MinecraftService is not initialized. Proceeds to initialize it.");
                await InitializeAsync();
            }
            if (!MinecraftAPI.Contains(version))
            {
                Debug.WriteLine($"Version {version} does not exist in available links.");
                return null;
            }

            if (await ContainsZip(version))
            {
                Debug.WriteLine($"Version {version} is already downloaded. No further steps required.");
                return null;
            }

            var uri = new Uri(MinecraftAPI.Get(version)?.Downloads.Client?.Url);

            var root = await GetOrCreateRootFolderAsync();
            var file = await root?.CreateFileAsync(version + ".zip", CreationCollisionOption.ReplaceExisting);

            try
            {
                BackgroundDownloader downloader = new BackgroundDownloader();
                DownloadOperation download = downloader?.CreateDownload(uri, file);
                Debug.WriteLine($"Downloading: {uri?.AbsolutePath}...");
                await download.StartAsync();
                Debug.WriteLine($"...Download completed: {uri?.AbsolutePath}");
            }
            catch (Exception e)
            {
                Debug.WriteLine($"Error when downloading {uri.AbsolutePath}:\n{e.Message}");
                return null;
            }

            await CreateResourceListAsync(version);

            if (option == DownloadOption.ExtractFiles)
                await Extract(version);

            return file;
        }
예제 #20
0
        public static async Task <string> DownloadDefinitionsDatabaseWork()
        {
            var appData   = ApplicationData.Current;
            var urlString = await FetchLatestDefinitionsPath();

            Log($"urlString: {urlString}");

            // TODO: check to see if it's already downloaded?

            var source = new Uri(urlString);

            Log($"source {source}");

            var baseName        = Path.GetFileNameWithoutExtension(urlString);
            var destFileName    = $"{baseName}.zip";
            var destinationFile =
                await appData.LocalCacheFolder.CreateFileAsync(destFileName, CreationCollisionOption.ReplaceExisting);

            Log($"Downloading {source} to {destinationFile.Path}");

            var downloader = new BackgroundDownloader();
            var download   = downloader.CreateDownload(source, destinationFile);

            await download.StartAsync();

            Log("maybe the download finished?");

            Log("Unzipping");
            await Task.Run(() => ZipFile.ExtractToDirectory(destinationFile.Path, appData.LocalCacheFolder.Path, Encoding.UTF8, true));

            var definitionsDbFile = Path.Combine(appData.LocalCacheFolder.Path, $"{baseName}.content");

            Log($"maybe finished unzipping? {definitionsDbFile}");

            if (!File.Exists(definitionsDbFile))
            {
                Log("Handle the definitions not existing?");
            }

            AppState.SaveSetting(SettingsKey.DefinitionsPath, definitionsDbFile);

            Log($"All finished, definitions at {definitionsDbFile}");

            return(definitionsDbFile);
        }
예제 #21
0
        /// <summary>
        /// 恢复已经开始的下载
        /// </summary>
        /// <param name="infos"></param>
        /// <returns></returns>
        public async void DiscoverActiveDownloadsAsync(ObservableCollection <DownloadInfo> infos)
        {
            _activeDownloads.Clear();
            _cts.Clear();

            DownloadInfo info = null;

            try
            {
                var downloads = await BackgroundDownloader.GetCurrentDownloadsAsync();

                if (downloads.Count > 0)
                {
                    await Task.Run(async() =>
                    {
                        var tasks = new List <Task>(downloads.Count);
                        foreach (var download in downloads)
                        {
                            info = infos.FirstOrDefault(v => v.DownloadGuid == download.Guid);
                            if (info != null)
                            {
                                tasks.Add(HandleDownloadAsync(download, info, false));
                            }
                        }
                        await Task.WhenAll(tasks);
                    });
                }
                else
                {
                    _isDownloading = false;
                    foreach (var downInfo in infos)
                    {
                        downInfo.DownloadState = DownloadState.Pause;
                    }
                }
            }
            catch (Exception ex)
            {
                _isDownloading = false;
                if (info != null)
                {
                    DownloadFailture(info, ex.Message);
                }
            }
        }
        /// <summary>
        /// args[0] : url, arg[1] : StorageFolder, args[2] : fileName, arg[3] : forceDownload
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public async Task <StorageFile> Download(params object[] args)
        {
            if (args.Length < 4)
            {
                throw new ArgumentException();
            }

            string        url           = (string)args[0];
            StorageFolder folder        = (StorageFolder)args[1];
            string        fileName      = (string)args[2];
            bool          forceDownload = (bool)args[3];

            bool        fileExist = false;
            StorageFile file      = null;

            try
            {
                file = await folder.GetFileAsync(fileName);

                fileExist = true;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                fileExist = false;
            }

            if (fileExist == false || forceDownload)
            {
                try
                {
                    file = await folder.CreateFileAsync(fileName);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }

                var downloader = new BackgroundDownloader();
                var operation  = downloader.CreateDownload(new Uri(url), file);
                await operation.StartAsync();
            }

            return(file);
        }
예제 #23
0
        async void PrepareSourse()
        {
            while (MusicRes == "shit")
            {
            }                               //not get resourse
            StorageFolder MyDownloadFolder;

            // 定位 folder
            try
            {
                MyDownloadFolder = await StorageApplicationPermissions.FutureAccessList.GetFolderAsync(App.MyDownLoadFolder);
            }
            catch (Exception)
            {
                MyDownloadFolder = await DownloadsFolder.CreateFolderAsync("Music", CreationCollisionOption.GenerateUniqueName);

                StorageApplicationPermissions.FutureAccessList.AddOrReplace(App.MyDownLoadFolder, MyDownloadFolder);
            }

            // try to open exist file
            try
            {
                StorageFile music = await MyDownloadFolder.GetFileAsync(SongPLayingName.Text + MusicRes.Substring(0, 4));

                var mediaSource = MediaSource.CreateFromStorageFile(music);
                App.Musicplayer.Source = mediaSource;

                mediaSource.OpenOperationCompleted += MediaSource_OpenOperationCompleted;
            }

            // not exist, download it
            catch (Exception)
            {
                StorageFile destinationFile = await MyDownloadFolder.CreateFileAsync(SongPLayingName.Text + MusicRes.Substring(0, 4), CreationCollisionOption.FailIfExists);

                var downloader        = new BackgroundDownloader();
                var downloadOperation = downloader.CreateDownload(new Uri(MusicRes.Substring(4)), destinationFile);
                await downloadOperation.StartAsync().AsTask();

                var mediaSource = MediaSource.CreateFromStorageFile(destinationFile);
                App.Musicplayer.Source = mediaSource;

                mediaSource.OpenOperationCompleted += MediaSource_OpenOperationCompleted;
            }
        }
예제 #24
0
        private async void MediaSourceDownloadOperation()
        {
            //<SnippetCreateMediaSourceFromDownload>
            StorageFile destinationFile = await KnownFolders.VideosLibrary.CreateFileAsync("file.mp4", CreationCollisionOption.GenerateUniqueName);

            var         downloader        = new BackgroundDownloader();
            var         downloadOperation = downloader.CreateDownload(new Uri("http://server.com/file.mp4"), destinationFile);
            MediaSource mediaSource       =
                MediaSource.CreateFromDownloadOperation(downloadOperation);

            //</SnippetCreateMediaSourceFromDownload>
            //<SnippetStartDownload>
            downloadOperation.IsRandomAccessRequired = true;
            var startAsyncTask = downloadOperation.StartAsync().AsTask();

            mediaPlayerElement.Source = mediaSource;
            //</SnippetStartDownload>
        }
예제 #25
0
        public void Stop_Normal_OK()
        {
            // Arrange
            BackgroundDownloader downloader =
                new BackgroundDownloader(
                    TestApp.Repositories,
                    TestApp.PodCastDownloader,
                    TestApp.EpisodeSaver);

            downloader.Start();
            Thread.Sleep(100);

            // Act
            downloader.Stop();

            // Assert
            Thread.Sleep(1000);
        }
예제 #26
0
        /// <summary>
        /// Downloads a file asynchronously.
        /// </summary>
        /// <param name="uri">The web-address to download the file from.</param>
        /// <param name="fileName">The name of the file to save to.</param>
        /// <param name="folder">The folder to download the file to.</param>
        public static async Task <StorageFile> DownloadFileAsync(Uri uri, string fileName, StorageFolder folder)
        {
            // Create download file path.
            var downloadFilePath = Path.Combine(folder.Path, fileName);
            // Create download file.
            var downloadFile = await folder.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName);

            // Download file.
            var downloader        = new BackgroundDownloader();
            var downloadOperation = downloader.CreateDownload(uri, downloadFile);
            // Wait for download to complete.
            await downloadOperation.StartAsync();

            // Return the downloaded file.
            return(downloadFile);
            // Add to gallery. TODO: Is this needed? Maybe revamp it so it doesn't do things twice.
            //await AddFileToGalleryAsync(vm, downloadFile, folder);
        }
예제 #27
0
        public async Task InitTasks()
        {
            IReadOnlyList <DownloadOperation> download;

            try {
                download = await BackgroundDownloader.GetCurrentDownloadsAsync();
            } catch (Exception e) {
                if (BackgroundTransferError.GetStatus(e.HResult) == WebErrorStatus.Unknown)
                {
                    throw;
                }
                return;
            }
            if (download.Count > 0)
            {
                await Task.WhenAll(download.Select((item) => HandleDownloadAsync(item, false)));
            }
        }
예제 #28
0
        private async void DownloadManager(string _requestUrl, string _title, string _thumb, string _type)
        {
            Thumbail = _thumb;
            Title    = _title;
            var    bgDownloader = new BackgroundDownloader();
            string result_title = _title.Replace("-", " ").Replace("&", " ").Replace("/", " ").Replace("!", " ").Replace("(", "").Replace(":", "").Replace(")", "");

            //FolderPicker fo = new FolderPicker();
            //fo.SuggestedStartLocation = PickerLocationId.Downloads;
            //fo.FileTypeFilter.Add(_type);
            // StorageFolder folder = await fo.PickSingleFolderAsync();
            StorageFolder folder = KnownFolders.VideosLibrary;
            var           part   = await folder.CreateFileAsync(result_title + _type, CreationCollisionOption.ReplaceExisting);

            DownloadOperation downloadOperation = bgDownloader.CreateDownload(new Uri(_requestUrl), part);

            await StartDonwloadAsync(downloadOperation);
        }
예제 #29
0
        public static async void SavePicture(object sender, RoutedEventArgs e)
        {
            var savePicker = new FileSavePicker();

            savePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;

            savePicker.FileTypeChoices.Add("Photo", new List <string>()
            {
                "." + (sender as MenuFlyoutItem).Tag.ToString().Split('.').Last()
            });

            savePicker.SuggestedFileName = "Avatar";
            var file = await savePicker.PickSaveFileAsync();

            var downloader = new BackgroundDownloader();
            var download   = downloader.CreateDownload(new Uri((sender as MenuFlyoutItem).Tag.ToString()), file);
            await download.StartAsync();
        }
예제 #30
0
        private static void CreateNotifications(BackgroundDownloader downloader)
        {
            var successToastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);

            successToastXml.GetElementsByTagName("text").Item(0).InnerText =
                "Downloads completed successfully.";
            ToastNotification successToast = new ToastNotification(successToastXml);

            downloader.SuccessToastNotification = successToast;

            var failureToastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);

            failureToastXml.GetElementsByTagName("text").Item(0).InnerText =
                "At least one download completed with failure.";
            ToastNotification failureToast = new ToastNotification(failureToastXml);

            downloader.FailureToastNotification = failureToast;
        }
예제 #31
0
        private async void Page_Loaded(object sender, RoutedEventArgs e)
        {
            var downloads = await BackgroundDownloader.GetCurrentDownloadsAsync();

            foreach (var item in downloads)
            {
                var download = new WtDownloadOperation
                {
                    Name              = item.ResultFile.Name,
                    Extension         = item.ResultFile.FileType,
                    DownloadOperation = item
                };
                Downloads.Add(download);
                await download.DownloadOperation
                .AttachAsync()
                .AsTask(CancellationToken.None, new Progress <DownloadOperation>(ProgressChanged));
            }
        }