Windows 8 Store Apps Learning (66) Background tasks: Downloading and uploading

Source: Internet
Author: User
Tags foreach header http request rar tostring xmlns

Introduced

Re-imagine Windows 8 Store Apps after a task

Background Download Task

Background upload Task

Example

Extended downloadoperation and uploadoperation so that download progress or upload progress can be notified

Backgroundtask/transfermodel.cs

* * Extended downloadoperation and uploadoperation for download progress or upload progress to notify/using System;
Using System.ComponentModel;
    
Using Windows.Networking.BackgroundTransfer; Namespace Xamldemo.backgroundtask {public class Transfermodel:inotifypropertychanged {public Downloado
        Peration downloadoperation {get; set;}
    
        Public uploadoperation uploadoperation {get; set;}
        public string Source {get; set;}
            
        public string Destination {get; set;}
        private string _progress;
            public string Progress {get {return _progress;}
                set {_progress = value;
            raisePropertyChanged ("Progress");
        } public event PropertyChangedEventHandler propertychanged;
                protected void raisePropertyChanged (string name) {if (propertychanged!= null) { PropertyChanged (This, new PropertychangedeVentargs (name)); }
        }
    }
}

1. Demo Background Download task application

Backgroundtask/transferdownload.xaml

<page x:class= "XamlDemo.BackgroundTask.TransferDownload" xmlns= "http://schemas.microsoft.com/winfx/2006/xaml/
    Presentation "xmlns:x=" Http://schemas.microsoft.com/winfx/2006/xaml "xmlns:local=" Using:XamlDemo.BackgroundTask " Xmlns:d= "http://schemas.microsoft.com/expression/blend/2008" xmlns:mc= "http://schemas.openxmlformats.org/ markup-compatibility/2006 "mc:ignorable=" D "> <grid background=" Transparent "> <stackpanel margin= "0 0 0" > <scrollviewer height= "> <textblock name=" lblmsg "Font Size= "14.667" textwrapping= "Wrap"/> </ScrollViewer> <button name= "Btnadddownloa D "content=" New Download Task "margin=" 0 0 0 "click=" Btnadddownload_click "/> <button name=" Btnpause "Content = "Suspend all download Tasks" margin= "0 0 0" click= "Btnpause_click"/> <button name= "Btnresume" content= "continue all download Tasks" Mar gin= "0 0 0" click= "btnresume_click "/> <button name=" Btncancel content= "Cancel all download Tasks" margin= "0 0 0" click= "Btncancel_click"/> <listview name= "ListView" padding= "0 0 0" height= "> &LT;LISTVIEW.ITEMTEMPLATE&G"
                    T
                            <DataTemplate> <stackpanel margin= "0 5" background= "Blue" > <textblock text= "{Binding Source}" margin= "5"/> <textblock text= "{Binding Destinat
                        Ion} "margin=" 5 "/> <textblock text=" {Binding Progress} "margin=" 5 "/>
            </StackPanel> </DataTemplate> </ListView.ItemTemplate> </ListView> </StackPanel> </Grid> </Page>

Backgroundtask/transferdownload.xaml.cs

* * Demo Background Download Task Application * * Backgrounddownloader-Background Download Task Manager * costpolicy-Download cost policy, Backgroundtransfercostpolicy enumeration * Default-do not allow transmission on high cost (e.g. 2G 3G) network * unrestrictedonly-allows transmission on high cost (such as 2G 3G) network Always-can be transmitted in any case,  Even when roaming * servercredential-credentials * proxycredential when communicating with the server-the identity credentials * setRequestHeader (string headername) when the proxy is used  String headervalue)-Set HTTP request header * Createdownload (URI Uri, Istoragefile resultfile)-Create a download task, return to Downloadoperation Object * Group-for group download task * Static Getcurrentdownloadsasync (string group)-Gets all download tasks under the specified group * static GETCURRENTD Ownloadsasync ()-Get all download tasks not associated with the group * downloadoperation-Download Task Object * costpolicy-Download cost policy, BACKGROUNDTRANSFERCOSTP      Olicy enum * Group-Gets the group * Guid for this download task-Gets the identity of this download task * Requesteduri-Download Source URI * resultfile-Download target file * Getresponseinformation ()-The server-side response information obtained after the download is complete, returns the Responseinformation object * Actualuri-the true URI of the download source * He Aders-HTTP headers for server-side responses *         StatusCode-server-side response status code * PAUSE ()-Pause this task * Resume ()-Continue this task * Startasync ()-Add a download task, return to Iasyncope Rationwithprogress<downloadoperation, downloadoperation> Object * Attachasync ()-Monitors existing download tasks, returns Iasyncoperationwith     
 Progress<downloadoperation, downloadoperation> Object * Progress-Get download progress, return backgrounddownloadprogress Object * * backgrounddownloadprogress-Background Download Task download Progress Object * bytesreceived-Number of bytes downloaded * totalbytestoreceive-the total number of bytes to download, unknown to 0 * Status-download status, backgroundtransferstatus enum * Idle, Running, Pausedbyapplication, Pausedcostednetwork, Pa Usednonetwork, Completed, Canceled, Error * hasresponsechanged-Server response is true * hasrestarted-after the current load connection is broken, the system passes through H
The TTP range header continues to request a breakpoint on the server, and if the service side does not support a breakpoint continuation, it needs to be downloaded again, which is true/using System;
Using System.Collections.Generic;
Using System.Collections.ObjectModel;
Using System.Threading;
Using System.Threading.Tasks;
Using System.Linq;
Using Windows.Networking.BackgroundTransfer; USing Windows.storage;
Using Windows.UI.Xaml;
Using Windows.UI.Xaml.Controls;
    
Using Windows.web;
        Namespace Xamldemo.backgroundtask {public sealed partial class Transferdownload:page {//Download task collection
    
        Private observablecollection<transfermodel> _transfers = new observablecollection<transfermodel> (); The associated CancellationTokenSource object for all download tasks is private CancellationTokenSource _canceltoken = new Cancellationtok
           
        Ensource (); Public Transferdownload () {this.
    
            InitializeComponent ();
        Init ();
    
            Private async void Init () {listview.itemssource = _transfers;
        Get all download tasks await loaddownloadasync (); //load all download Tasks Private Async Task Loaddownloadasync () {Ireadonlylist<downloado
            Peration> downloads = null;
      try {//Get all background download tasks          Downloads = await backgrounddownloader.getcurrentdownloadsasync (); catch (Exception ex) {lblmsg.text = ex.
                ToString ();
                Lblmsg.text + = Environment.NewLine;
            Return } if (downloads.
                Count > 0) {list<task> tasks = new list<task> ();
                    foreach (downloadoperation download in downloads) {//monitor specified background download task Tasks.
                Add (Handledownloadasync (download, false));
            } await Task.whenall (tasks);
        }//Add a download task private async void Btnadddownload_click (object sender, RoutedEventArgs e) {///download address (note that you need to add package.appxmanifest to. rar type files)//View more highlights of this column: HTTP://WWW.BIANCENG.CNHTTP://WW W.bianceng.cn/programming/net/uri Sourceuri = new Uri ("http://files.cnblogs.com/webabcd/windows8.rar ", Urikind.absolute);
            Storagefile Destinationfile; try {//saved destination Address Destinationfile = await KnownFolders.DocumentsLibrary.CreateF
            Ileasync ("Windows8.rar", creationcollisionoption.generateuniquename); catch (Exception ex) {lblmsg.text = ex.
                ToString ();
                Lblmsg.text + = Environment.NewLine;
            Return
            //Create a background download task Backgrounddownloader Backgrounddownloader = new Backgrounddownloader ();
    
            downloadoperation download = backgrounddownloader.createdownload (Sourceuri, destinationfile);
        Monitors the specified background download task await Handledownloadasync (download, true); ///<summary>///Monitoring of the specified background download task///</summary>///<param name= "Downlo Ad "> Background download task </param>///<param name=" IsNew "> is newTask </param> Private Async Task Handledownloadasync (downloadoperation download, bool isnew) { try {//attach downloadoperation to Transfermodel so that the download progress can be notified Transfermodel tra
                Nsfer = new Transfermodel (); Transfer.
                downloadoperation = download; Transfer. Source = download.
                Requesteduri.tostring (); Transfer. Destination = download.
                Resultfile.path; Transfer.
    
                Progress = "0/0"; _transfers.
    
                ADD (transfer); Lblmsg.text = "Task Count:" + _transfers.
                Count.tostring ();
    
                Lblmsg.text + = Environment.NewLine; callback function Progress<downloadoperation> Progresscallback = new progress<downloadoperation& When download progress is changed
    
                gt; (downloadprogress); if (isnew) await download. Startasync (). Astask (_canceltoken.token, progresscallback);
       Add a background download task         else await download. Attachasync (). Astask (_canceltoken.token, progresscallback); Monitor the existing background download task//Get the response information for the server after the download is complete responseinformation response = download.
                Getresponseinformation (); Lblmsg.text + = "Completed:" + response. Actualuri + "-" + response.
                Statuscode.tostring ();
            Lblmsg.text + = Environment.NewLine; A catch (taskcanceledexception)//Call to Cancellationtokensource.cancel () throws this exception {L Blmsg.text + = "Canceled:" + download.
                Guid;
            Lblmsg.text + = Environment.NewLine; A catch (Exception ex) {//Converts an exception to a Weberrorstatus enumeration, if the Weberrorstatus.unknow is obtained n indicates that this exception is not a Web-related exception weberrorstatus error = Backgroundtransfererror.getstatus (ex.
    
                HResult); Lblmsg.text = ex.
                ToString ();
            Lblmsg.text + = Environment.NewLine;
      }      finally {_transfers. Remove (_transfers.
            (p => p.downloadoperation = = download)); }//Progress changes, update Transfermodel Progress to notify private void DownloadProgress (Downloadoperati on download) {Transfermodel transfer = _transfers.
            A (p => p.downloadoperation = = download); Transfer. Progress = download. Progress.BytesReceived.ToString ("#,0") + "/" + download.
        Progress.TotalBytesToReceive.ToString ("#,0"); //Pause all background download task private void Btnpause_click (object sender, RoutedEventArgs e) {L
            Blmsg.text + = "All paused";
            Lblmsg.text + = Environment.NewLine; foreach (Transfermodel transfer in _transfers) {if (transfer. DownloadOperation.Progress.Status = = backgroundtransferstatus.running) {transfer.
                Downloadoperation.pause ();
         }   }//Continue all background download tasks private void Btnresume_click (object sender, RoutedEventArgs e) {
            Lblmsg.text + = "all resumed";
            Lblmsg.text + = Environment.NewLine; foreach (Transfermodel transfer in _transfers) {if (transfer. DownloadOperation.Progress.Status = = backgroundtransferstatus.pausedbyapplication) {T Ransfer.
                Downloadoperation.resume (); //Cancel all background download task private void Btncancel_click (object sender, RoutedEventArgs E
            ) {_canceltoken.cancel ();
    
            _canceltoken.dispose ();
        _canceltoken = new CancellationTokenSource (); }
    }
}

2, Demo background upload task application

Backgroundtask/transferupload.xaml

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.