How to Add Support for Background Transfers in your Windows Phone Application

Introduction

Today, mobile applications hardly persist data on the devices. They get their information from the cloud. A typical example is an application that streams YouTube videos or downloads data to work on.

Whenever there is a large file to work on, the user experience can be dismal if the application developer does a synchronous download of the file. The asynchronous file transfer can be a workable solution as long as the application can let the user know that a download has been queued and notify the user when it is complete.

Windows Phone "Mango" introduced support for background transfers. Let us write an application that makes use of the "Background transfer" feature in a Windows Phone application.

Hands-On

To start with, create a Windows Phone application titled "WPBackgroundTransferDemo".

Add a Button and two TextBox controls to the MainPage.xaml. Rename the first TextBox control to "textBoxStatus", the second TextBox to "textBoxProgress" and the Button control to "buttonAddToTransfer".

Add an Event for Click on the button buttonAddToTransfer. To do this, double click the buttonAddToTransfer control on MainPage.xaml.

        private void buttonAddToTransfer_Click(object sender, RoutedEventArgs e)
        {
            Uri transferUri = new Uri(Uri.EscapeUriString("http://vipuldpatel.web.officelive.com/Documents/pictures.zip"), UriKind.RelativeOrAbsolute);

            BackgroundTransferRequest transferRequest = new BackgroundTransferRequest(transferUri);
            transferRequest.TransferStatusChanged += new EventHandler<BackgroundTransferEventArgs>(transferRequest_TransferStatusChanged);

     transferRequest.TransferProgressChanged +=new EventHandler<BackgroundTransferEventArgs>(transferRequest_TransferProgressChanged);
            transferRequest.Method = "GET";
            Uri downloadUri = new Uri("shared/transfers/pictures.zip", UriKind.RelativeOrAbsolute);
            transferRequest.DownloadLocation = downloadUri;
            IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
            bool exists = isf.FileExists(@"shared\transfers\pictures.zip");
            BackgroundTransferService.Add(transferRequest);

 
            exists = isf.FileExists(@"shared\transfers\pictures.zip");
        }

Here, we create an instance of BackgroundTransferRequest class and make a "GET" HTTP request and pass in the URL from where we want to download the file.

We also add code to wire up the "TransferStatusChanged" event and the "TransferProgressChanged" events.

Our TransferProgressChanged event handler is very simple. It calculates the progress of the transfer request by dividing the "Bytes Received" by "the total bytes to be received".

        private void transferRequest_TransferProgressChanged(object sender, BackgroundTransferEventArgs e)
        {
            textBoxProgress.Text = ((e.Request.BytesReceived * 100.0) / e.Request.TotalBytesToReceive).ToString();
        }

The Transfer Status Changed event updates the status of the request by updating the textbox.

private void transferRequest_TransferStatusChanged(object sender, BackgroundTransferEventArgs e)
        {
            Debug.WriteLine("transfer status: " + e.Request.TransferStatus.ToString());
            //Console.WriteLine(e.Request.TransferStatus.ToString());
            IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
            textBoxStatus.Text = e.Request.TransferStatus.ToString();
             if (e.Request.TransferStatus == TransferStatus.Completed)
                Debug.Assert(isf.FileExists(@"shared\transfers\pictures.zip") == true);
        }

Compile and run your application. When we run the application for the first time, we see the screen shown below.

Run the application for the first time
Figure 1: Run the application for the first time

Compile and run your application

Click the "Button" control to add the background transfer request to the queue.

Click the
Figure 2: Click the "Button" control to add the background transfer request to the queue.

Add the background transfer request to the queue

You will notice that the transfer starts and the Status and Progress textboxes get updated with the current status, which is "Transferring" and the current progress.

When the transfer is complete, you will notice the Status to be completed and Progress to be 100.

This implies that the background transfer has completed successfully.

The background transfer has completed
Figure 3: The background transfer has completed

This was a very simple example of using the BackgroundTransferRequest class. In a future article, we will visit the best practices of using the BackgroundTransferRequest class.

If you are having trouble following along, you can download the sample code below.

Summary

In this article, we learned about using the BackgroundTransferRequest class to add an asynchronous download request in a Windows Phone "Mango" application. I hope you have found this information useful.



About the Author

Vipul Vipul Patel

Vipul Patel is a Software Engineer currently working at Microsoft Corporation, working in the Office Communications Group and has worked in the .NET team earlier in the Base Class libraries and the Debugging and Profiling team. He can be reached at vipul_d_patel@hotmail.com

Downloads

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Today's agile organizations pose operations teams with a tremendous challenge: to deploy new releases to production immediately after development and testing is completed. To ensure that applications are deployed successfully, an automatic and transparent process is required. We refer to this process as Zero Touch Deployment™. This white paper reviews two approaches to Zero Touch Deployment--a script-based solution and a release automation platform. The article discusses how each can solve the key …

  • On-demand Event Event Date: December 18, 2014 The Internet of Things (IoT) incorporates physical devices into business processes using predictive analytics. While it relies heavily on existing Internet technologies, it differs by including physical devices, specialized protocols, physical analytics, and a unique partner network. To capture the real business value of IoT, the industry must move beyond customized projects to general patterns and platforms. Check out this webcast and join industry experts as …

Most Popular Programming Stories

More for Developers

RSS Feeds