private async void print()
        {
            //var success = await Windows.System.Launcher.LaunchUriAsync(uri);
            try
            {
                LoaderText.Text      = "Generando documento PDF...";
                grdLoader.Visibility = Visibility.Visible;

                JsonObject result = await Finances.printCC(UserId);

                Uri    uri      = new Uri(result.GetNamedString("url"));
                string filename = result.GetNamedString("file_name");

                StorageFile destinationFile = await DownloadsFolder.CreateFileAsync(filename, CreationCollisionOption.GenerateUniqueName);

                BackgroundDownloader downloader = new BackgroundDownloader();
                DownloadOperation    download   = downloader.CreateDownload(uri, destinationFile);
                await HandleDownloadAsync(download, true);

                await Windows.System.Launcher.LaunchFileAsync(download.ResultFile);

                grdLoader.Visibility = Visibility.Collapsed;
                LoaderText.Text      = "";
            }
            catch (Exception ex)
            {
                var dialog = new MessageDialog(ex.Message);
                await dialog.ShowAsync();
            }
        }
Example #2
0
    public void CancelDownload(DownloadOperation operation)
    {
        Profiler.BeginSample(string.Format("CancelDownload {0}", operation.ID));

        AndroidBridge.CallStatic("cancelDownload", Context, operation.ID);

        Profiler.EndSample();
    }
Example #3
0
 private void DownloadOperationProgress(DownloadOperation download)
 {
     // Note that this event handler is invoked on a background thread
     if (this.DownloadProgress != null)
     {
         this.DownloadProgress(download);
     }
 }
Example #4
0
        internal Task RestoreDownload(DownloadOperation operation)
        {
            VideoDownloadManager.DownloadStarted += VideoDownloadManager_DownloadStarted;
            IsCacheRequested = true;
            CacheState       = NicoVideoCacheState.Downloading;

            return(GetCacheFile());
        }
Example #5
0
        private async void ConnectUsingBackgroundTransfer(string resourceIdentity, Uri resourceUri)
        {
            ThreadNetworkContext context = null;

            try
            {
                // For demonstrational purposes, when "Use personal context" is selected,
                // the resourceIdentity is set to null to force personal context.

                // When using Windows.Networking.BackgroundTransfer, the app is responsible for disallowing connections
                // to enterprise owned URLs when in personal context.
                // Otherwise, the app may inadvertently access cached data for a different context.
                if (UsePersonalContext.IsChecked.Value && !string.IsNullOrEmpty(resourceIdentity))
                {
                    rootPage.NotifyUser("This app does not have access to the specified URL in personal context", NotifyType.ErrorMessage);
                    return;
                }

                rootPage.NotifyUser("Creating file.........", NotifyType.StatusMessage);

                StorageFile resultFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(
                    "ResultFile.txt",
                    CreationCollisionOption.GenerateUniqueName);

                if (!string.IsNullOrEmpty(resourceIdentity))
                {
                    context = ProtectionPolicyManager.CreateCurrentThreadNetworkContext(resourceIdentity);
                }

                rootPage.NotifyUser("Accessing network resource.........", NotifyType.StatusMessage);

                BackgroundDownloader downloader = new BackgroundDownloader();

                if (!string.IsNullOrEmpty(UserNameBox.Text) &&
                    !string.IsNullOrEmpty(Passwordbox.Password))
                {
                    downloader.ServerCredential = new PasswordCredential(
                        resourceUri.AbsoluteUri,
                        UserNameBox.Text,
                        Passwordbox.Password);
                }

                DownloadOperation download = downloader.CreateDownload(resourceUri, resultFile);

                await HandleDownloadAsync(download);
            }
            catch (Exception ex)
            {
                rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
            }
            finally
            {
                if (context != null)
                {
                    context.Dispose();
                }
            }
        }
        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);
        }
        public void AddDownloadOperation(DownloadOperation downloadOperation)
        {
            var entry = new BucketEntryViewModel(this, _bucketService, _objectService);

            entry.IsDownloadOperation = true;
            entry.DownloadOperation   = downloadOperation;
            entry.InitDownloadOperation();
            Entries.Add(entry);
        }
 protected override void OnNavigatedTo(NavigationEventArgs e)
 {
     Frame.BackStack.Clear();
     base.OnNavigatedTo(e);
     GC.Collect();
     GC.WaitForPendingFinalizers();
     download           = (DownloadOperation)e.Parameter;
     nameTextBlock.Text = download.ResultFile.Name;
 }
Example #9
0
        private void progressChanged(DownloadOperation downloadOperation)
        {
            int progress = (int)(100 * ((double)downloadOperation.Progress.BytesReceived / (double)downloadOperation.Progress.TotalBytesToReceive));

            if (progress >= 100)
            {
                downloadOperation = null;
            }
        }
Example #10
0
        private static async void CreateDown(DownloadTaskModel m, int index, string url, StorageFolder folder)
        {
            BackgroundDownloader downloader = new BackgroundDownloader();

            downloader.SetRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36");
            if (!url.Contains("360.cn"))
            {
                downloader.SetRequestHeader("Referer", "https://www.bilibili.com/blackboard/html5player.html?crossDomain=true");
            }
            //设置下载模式
            if (SettingHelper.Get_DownMode() == 0)
            {
                group.TransferBehavior = BackgroundTransferBehavior.Serialized;
            }
            else
            {
                group.TransferBehavior = BackgroundTransferBehavior.Parallel;
            }
            downloader.TransferGroup = group;
            //创建视频文件
            var filetype = ".flv";

            if (url.Contains(".mp4"))
            {
                filetype = ".mp4";
            }
            StorageFile file = await folder.CreateFileAsync(index.ToString("000") + filetype, CreationCollisionOption.OpenIfExists);

            DownloadOperation downloadOp = downloader.CreateDownload(new Uri(url), file);

            //设置下载策略
            if (SettingHelper.Get_Use4GDown())
            {
                downloadOp.CostPolicy = BackgroundTransferCostPolicy.Always;
            }
            else
            {
                downloadOp.CostPolicy = BackgroundTransferCostPolicy.UnrestrictedOnly;
            }
            SqlHelper.InsertDownload(new DownloadGuidClass()
            {
                guid    = downloadOp.Guid.ToString(),
                cid     = m.cid,
                index   = index,
                aid     = (m.downloadMode == DownloadMode.Anime) ? m.sid : m.avid,
                eptitle = m.epTitle,
                title   = m.title,
                mode    = (m.downloadMode == DownloadMode.Anime) ? "anime" : "video"
            });
            try
            {
                await downloadOp.StartAsync();
            }
            catch (Exception)
            {
            }
        }
Example #11
0
        public async Task GetPDF(int id, StorageFile file)
        {
            Uri source = new Uri($"{apiUrl}/Business/PdfForPromotion/{id}");

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

            download.StartAsync();
        }
Example #12
0
 private void OnDownloadProgressChanged(DownloadOperation download)
 {
     Dispatcher.DispatchAsync(() =>
     {
         var index             = OperationsList.IndexOf(download);
         OperationsList[index] = download;
         RaisePropertyChanged("Progress");
     });
 }
Example #13
0
        private async Task SaveImageSite(StorageFile savefile)
        {
            BackgroundDownloader downloader = new BackgroundDownloader();
            DownloadOperation    download   = downloader.CreateDownload(new Uri(image_url), savefile);
            await download.StartAsync();

            downloader = null;
            download   = null;
        }
 public NicoVideoCacheProgress(NicoVideoCacheRequest req, DownloadOperation op, IVideoStreamingDownloadSession session)
 {
     RawVideoId           = req.RawVideoId;
     Quality              = session.Quality;
     IsRequireForceUpdate = req.IsRequireForceUpdate;
     RequestAt            = req.RequestAt;
     DownloadOperation    = op;
     Session              = session;
 }
Example #15
0
        private async void progressChanged(DownloadOperation downloadOperation)
        {
            //Statustext.Visibility = Visibility.Visible;
            //Statusring.IsActive = false;
            int progress = (int)(100 * ((double)downloadOperation.Progress.BytesReceived / (double)downloadOperation.Progress.TotalBytesToReceive));

            //Statustext.Text = String.Format("{0} of {1} kb. downloaded - %{2} complete.", downloadOperation.Progress.BytesReceived / 1024, downloadOperation.Progress.TotalBytesToReceive / 1024, progress);
            //Statustext.Value = progress;

            switch (downloadOperation.Progress.Status)
            {
            case BackgroundTransferStatus.Running:
            {
                break;
            }

            case BackgroundTransferStatus.PausedByApplication:
            {
                break;
            }

            case BackgroundTransferStatus.PausedCostedNetwork:
            {
                break;
            }

            case BackgroundTransferStatus.PausedNoNetwork:
            {
                break;
            }

            case BackgroundTransferStatus.Completed:
            {
                MessageDialog msg = new MessageDialog("Download Completed");
                msg.ShowAsync();
                break;
            }

            case BackgroundTransferStatus.Error:
            {
                //Statustext.Text = "An error occured while downloading.";
                MessageDialog msg = new MessageDialog("No internet connection has been found.");
                msg.ShowAsync();
                break;
            }
            }
            if (progress >= 100)
            {
                downloadOperation         = null;
                downloadingText.Text      = "Đã tải";
                downloadingBar.Visibility = Visibility.Collapsed;
                await Task.Delay(1500);

                statusDownv2.Visibility = Visibility.Collapsed;
                //Statustext.Visibility = Visibility.Collapsed;
            }
        }
        private void Progress_ProgressChanged(object sender, DownloadOperation e)
        {
            DownloadProgress.Value = (e.Progress.BytesReceived / (double)e.Progress.TotalBytesToReceive) * 1000;

            if (e.Progress.BytesReceived == e.Progress.TotalBytesToReceive && e.Progress.TotalBytesToReceive != 0)
            {
                DownloadProgress.Visibility = Visibility.Collapsed;
            }
        }
Example #17
0
 public UniversalTransferRequest(DownloadOperation request, Progress <DownloadOperation> callback)
 {
     this.request  = request;
     this.callback = callback;
     if (this.callback != null)
     {
         this.callback.ProgressChanged += Request_ProgressChanged;
     }
 }
Example #18
0
 void UpdateDownloadProgress(DownloadOperation download)
 {
     if (download.Progress.TotalBytesToReceive == 0)
     {
         DownloadProgress = 0;
         return;
     }
     DownloadProgress = (int)((download.Progress.BytesReceived * 100) / download.Progress.TotalBytesToReceive);
 }
Example #19
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);
            }
        }
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            try
            {
                if (e.Parameter != null)
                {
                    Dictionary <string, string> parameter = new Dictionary <string, string>();
                    parameter = e.Parameter as Dictionary <string, string>;

                    if (parameter["bookUrl"] != null)
                    {
                        string bookUrl = parameter["bookUrl"];
                        pageTitle.Text = parameter["title"];

                        Uri         fileTarget = new Uri(bookUrl.Trim());
                        StorageFile file       = await KnownFolders.DocumentsLibrary.CreateFileAsync(pageTitle.Text.Trim() + ".pdf", CreationCollisionOption.GenerateUniqueName);

                        CancellationTokenSource cancellationToken = new CancellationTokenSource();

                        BackgroundDownloader         downloader = new BackgroundDownloader();
                        DownloadOperation            download   = downloader.CreateDownload(fileTarget, file);
                        Progress <DownloadOperation> progress   = new Progress <DownloadOperation>(progressChanged);

                        progressStatus.Text = "Initializing ....";
                        await download.StartAsync().AsTask(cancellationToken.Token, progress);

                        if (download.Progress.BytesReceived >= download.Progress.TotalBytesToReceive)
                        {
                            StorageFile bookPdf = await KnownFolders.DocumentsLibrary.GetFileAsync(pageTitle.Text.Trim() + ".pdf");

                            LoadPdfFileAsync(file);
                            HideProgressRing();
                        }
                        else
                        {
                            ShowProgressRing();
                        }
                    }
                }
                base.OnNavigatedTo(e);
            }
            catch (TaskCanceledException ex)
            {
                var popup = new Windows.UI.Popups.MessageDialog("Cant load the file. The program might have failed to open the file  or you are not connected");
                progressStatus.Text = "Download canceled.";
                popup.Commands.Add(new Windows.UI.Popups.UICommand("Ok"));
                popup.DefaultCommandIndex = 0;
                popup.CancelCommandIndex  = 1;
                var results = await popup.ShowAsync();

                if (results.Label == "Ok")
                {
                    this.Frame.GoBack();
                }
            }
        }
Example #21
0
        public async static Task <string> CoverAudio(IAudioFile audio)
        {
            if (audio.PlaylistId != 0)
            {
                var cover = await CoverPlaylistById(audio.PlaylistId, audio.Cover);

                return(cover);
            }
            else
            {
                var         uriImage  = audio.Cover;
                StorageFile coverFile = null;
                var         a         = await StaticContent.CoversFolder.TryGetItemAsync($"VK{audio.Id}Audio.jpg");

                if (a != null)
                {
                    try
                    {
                        coverFile = await StaticContent.CoversFolder.GetFileAsync($"VK{audio.Id}Audio.jpg");
                    }
                    catch
                    {
                        if (config.SaveImage)
                        {
                            var task = Task.Run(async() =>
                            {
                                coverFile = await StaticContent.CoversFolder.CreateFileAsync($"VK{audio.Id}Audio.jpg");
                                BackgroundDownloader downloader = new BackgroundDownloader();
                                DownloadOperation download      = downloader.CreateDownload(new Uri(uriImage), coverFile);
                                await download.StartAsync();
                            });
                        }

                        return(uriImage);
                    }
                }
                else
                {
                    if (config.SaveImage)
                    {
                        var task = Task.Run(async() =>
                        {
                            coverFile = await StaticContent.CoversFolder.CreateFileAsync($"VK{audio.Id}Audio.jpg");
                            BackgroundDownloader downloader = new BackgroundDownloader();
                            DownloadOperation download      = downloader.CreateDownload(new Uri(uriImage), coverFile);
                            await download.StartAsync();
                        });
                    }


                    return(uriImage);
                }

                return(coverFile.Path);
            }
        }
Example #22
0
        public void ProgressCallBack(DownloadOperation obj)
        {
            this.Visibility = Visibility.Visible;
            var Percentage = ((double)obj.Progress.BytesReceived / obj.Progress.TotalBytesToReceive) * 100;

            if (Percentage >= 100)
            {
                Saved.Visibility = Visibility.Visible;
            }
        }
Example #23
0
        private static void DownloadOperation_DownloadOperationProgressChanged(DownloadOperation downloadOperation)
        {
            Console.WriteLine($"{downloadOperation.ObjectName} {downloadOperation.PercentageCompleted}%");
            if (!string.IsNullOrEmpty(downloadOperation.ErrorMessage))
            {
                Console.WriteLine(downloadOperation.ErrorMessage);
            }

            File.WriteAllBytes(downloadOperation.ObjectName, downloadOperation.DownloadedBytes);
        }
Example #24
0
        private static void ProgressCallback(DownloadOperation obj)
        {
            double progress = ((double)obj.Progress.BytesReceived / obj.Progress.TotalBytesToReceive);

            //Debug.WriteLine("Progress: " + progress * 100);
            if (progress >= 1.0)
            {
                //Debug.WriteLine("Download complete!");
            }
        }
Example #25
0
        async public void Backgrounddownload(Imagemodel imagemodel)
        {
            StorageFolder folder = await KnownFolders.PicturesLibrary.CreateFolderAsync("ONE", CreationCollisionOption.OpenIfExists);

            StorageFile newFile = await folder.CreateFileAsync(imagemodel.Title + ".jpg", CreationCollisionOption.OpenIfExists);

            Uri uri = new Uri(imagemodel.CoverImage);
            DownloadOperation download = backgroundDownload.CreateDownload(uri, newFile);
            await download.StartAsync();
        }
Example #26
0
        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);
        }
        /// <summary>
        /// Приостанавливает выполнение запроса
        /// </summary>
        public void Pause()
        {
            if (State != RequestState.Processing)
            {
                return;
            }

            DownloadOperation.Pause();
            State = RequestState.Paused;
        }
        /// <summary>
        /// Возобновляет выполнение приостановленного запроса
        /// </summary>
        public void Resume()
        {
            if (State != RequestState.Paused)
            {
                return;
            }

            DownloadOperation.Resume();
            State = RequestState.Processing;
        }
Example #29
0
        private static void DownloadProgress(DownloadOperation obj)
        {
            Debug.WriteLine(obj.Progress.ToString());

            var progress = (double)obj.Progress.BytesReceived / (double)obj.Progress.TotalBytesToReceive;

            string tag = GetFileNameFromUri(obj.RequestedUri);

            UpdateToast(obj.ResultFile.Name, progress);
        }
Example #30
0
        public DownloadFileImplementation(DownloadOperation downloadOperation)
        {
            DownloadOperation = downloadOperation;

            var progress = new Progress <DownloadOperation>(ProgressChanged);

            _cancellationToken = new CancellationTokenSource();

            DownloadOperation.AttachAsync().AsTask(_cancellationToken.Token, progress);
        }
        /// <summary>
        /// Overrides the base execute logic to use the background downloader to download the file.
        /// </summary>
        protected async override void OnExecute()
        {
            var loginResult = await this.LiveClient.Session.AuthClient.GetLoginStatusAsync();
            if (loginResult.Error != null)
            {
                this.taskCompletionSource.SetException(loginResult.Error);
                return;
            }
            else
            {
                var downloader = new BackgroundDownloader();
                downloader.SetRequestHeader(
                        ApiOperation.AuthorizationHeader,
                        AuthConstants.BearerTokenType + " " + loginResult.Session.AccessToken);
                downloader.SetRequestHeader(ApiOperation.LibraryHeader, Platform.GetLibraryHeaderValue());

                downloader.Group = LiveConnectClient.LiveSDKDownloadGroup;
                this.downloadOp = downloader.CreateDownload(this.Url, this.OutputFile);
                this.taskCompletionSource.SetResult(new LiveDownloadOperation(downloadOp));
            }
        }