MobileAdding an Auto-Upload Feature to Your Windows Phone 8 Application

Adding an Auto-Upload Feature to Your Windows Phone 8 Application

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Introduction

The Windows Phone 8 platform allows applications to support auto-uploading files. Since the task of uploading is potentially resource intensive, Microsoft introduced a new kind of background agent (http://www.codeguru.com/csharp/.net/wp7/article.php/c19821/Using-Background-Agents-in-your-Windows-Phone-75-Mango-Apps.htm) in Windows Phone 8  called ResourceIntensiveTask.

The key difference between resource-intensive agents and other background agents is that resource-intensive agents for auto-upload applications do not expire, even if the auto-upload application is not invoked. Resource intensive agents can be restricted to the connect mode they will operate in (for example, WIFI only).

Let us walk through the steps to build an application that supports auto-upload .

Hands On

Open Visual Studio 2012 and create a new Windows Phone project called WindowsPhoneAutoUploadDemo.

New Windows Phone project
New Windows Phone project

When prompted, select Windows Phone OS 8.0 as the target version.

Select Windows Phone OS 8.0
Select Windows Phone OS 8.0

The ability to specify whether an application supports auto upload or not is declared as a “Photos_Auto_upload” extension in the application manifest file.

Open WMAppManifest.xml file in the code editor and add the following extension.

<?xml version="1.0" encoding="utf-8"?>

 

<Deployment xmlns="http://schemas.microsoft.com/windowsphone/2012/deployment" AppPlatformVersion="8.0">

  <DefaultLanguage xmlns="" code="en-US"/>

  <App xmlns="" ProductID="{1127d500-9f4d-436e-b58f-15674728e558}" Title="WindowsPhoneAutoUploadDemo" RuntimeType="Silverlight" Version="1.0.0.0" Genre="apps.normal"  Author="WindowsPhoneAutoUploadDemo author" Description="Sample description" Publisher="WindowsPhoneAutoUploadDemo" PublisherID="{19e2742b-2278-4793-978e-2c6fa05b59bc}">

    <IconPath IsRelative="true" IsResource="false">AssetsApplicationIcon.png</IconPath>

    <Capabilities>

      <Capability Name="ID_CAP_NETWORKING"/>

      <Capability Name="ID_CAP_MEDIALIB_AUDIO"/>

      <Capability Name="ID_CAP_MEDIALIB_PLAYBACK"/>

      <Capability Name="ID_CAP_SENSORS"/>

      <Capability Name="ID_CAP_WEBBROWSERCOMPONENT"/>

    </Capabilities>

    <Tasks>

      <DefaultTask  Name ="_default" NavigationPage="MainPage.xaml"/>

    </Tasks>

    <Tokens>

      <PrimaryToken TokenID="WindowsPhoneAutoUploadDemoToken" TaskName="_default">

        <TemplateFlip>

          <SmallImageURI IsRelative="true" IsResource="false">AssetsTilesFlipCycleTileSmall.png</SmallImageURI>

          <Count>0</Count>

          <BackgroundImageURI IsRelative="true" IsResource="false">AssetsTilesFlipCycleTileMedium.png</BackgroundImageURI>

          <Title>WindowsPhoneAutoUploadDemo</Title>

          <BackContent></BackContent>

          <BackBackgroundImageURI></BackBackgroundImageURI>

          <BackTitle></BackTitle>

          <DeviceLockImageURI></DeviceLockImageURI>

          <HasLarge></HasLarge>

        </TemplateFlip>

      </PrimaryToken>

    </Tokens>

    <Extensions>

      <Extension ExtensionName="Photos_Auto_Upload"

           ConsumerID = "{0EB11746-6A44-4AE8-901D-551D04E3C956}"

           TaskID="_default"/>

    </Extensions>

    <ScreenResolutions>

      <ScreenResolution Name="ID_RESOLUTION_WVGA"/>

      <ScreenResolution Name="ID_RESOLUTION_WXGA"/>

      <ScreenResolution Name="ID_RESOLUTION_HD720P"/>

    </ScreenResolutions>

  </App>

</Deployment>

Next, we need to create a page, which will be called when we navigate to Settings application and select our application, because we want to directly offer the auto upload settings supported by our application. Let us add a new page to our project. We will call this page “ConfigureUpload.”

Add a new XAML page called “ConfigureUpload.xaml.”

Rename our newly created page to be titled “Configure Upload.”

Next, we will add a class, which will be responsible for Registering the ConfigureUpload URI to our project.

 Add a class
Add a class

In this class, we will implement logic to return the URI for the application configuration page if it contains the phrase “ConfigureUpload”.

// RegisterUri.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Navigation;

 

namespace WindowsPhoneAutoUploadDemo

{

    class RegisterUri : UriMapperBase

    {

        public override Uri MapUri(Uri uri)

        {

 

            if (uri.ToString().Contains("ConfigureUpload"))

            {

                // Launch to the auto-upload settings page if the application was launched and "ConfigureUpload" was passed as part URI to launch the application.

                return new Uri("/ConfigureUpload.xaml", UriKind.Relative);

            }

            else

                return uri;

        }

    }

}

Next, open App.xaml.cs and add the following line in InitializePhoneApplication() method to register the class we created above as the URI mapper class.

private void InitializePhoneApplication()

        {

            if (phoneApplicationInitialized)

                return;

 

            // Create the frame but don't set it as RootVisual yet; this allows the splash

            // screen to remain active until the application is ready to render.

            RootFrame = new PhoneApplicationFrame();

            RootFrame.Navigated += CompleteInitializePhoneApplication;

 

            // Handle navigation failures

            RootFrame.NavigationFailed += RootFrame_NavigationFailed;

 

            // Handle reset requests for clearing the backstack

            RootFrame.Navigated += CheckForResetNavigation;

 

            RootFrame.UriMapper = new RegisterUri();

            // Ensure we don't initialize again

            phoneApplicationInitialized = true;

        }

Now, we will create a second project, which implements the background agent.

Add a new project to the solution of type Windows Phone Scheduled Task Agent titled UploadScheduledTaskAgent.

Add a new project to the solution
Add a new project to the solution

Open up ScheduledAgent.cs and update the following OnInvoke method.

protected override void OnInvoke(ScheduledTask task)

        {

            // TODO: Add code to perform your task in background

            ShellToast backgroundToast = new ShellToast();

            backgroundToast.Title = "Auto Upload";

            backgroundToast.Content = "Running...";

            backgroundToast.Show();

            ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(10));

 

 

            NotifyComplete();

        }

Next, we will go back to working on the WindowsPhoneAutoUploadDemo project. Add a dependency on the UploadScheduledTaskAgent project.

In MainPage.xaml.cs, we add a variable of  type ResourceIntensiveTask.

Now, we will add a method, which does the work of starting our resource intensive agent.

Let’s call that method StartResourceIntensiveTask. In this method, we will implement the logic to create a new ResourceIntensiveTask object and call the method, which does the actual uploading of the file. Note that this demo project does not contain an actual implementation of upload. You can find APIs for DropBox and Flicker on CodePlex if you want to build an application to support these storage platforms.

        public void StartResourceIntensiveTask()

        {

 

            if (resourceIntensiveTask != null)

            {

                ScheduledActionService.Remove("ResourceIntensiveAgent");

            }

 

            resourceIntensiveTask = new ResourceIntensiveTask("ResourceIntensiveAgent");

            ScheduledActionService.Add(resourceIntensiveTask);

            

            StartUpload();

 

            // Place the call to Add in a try block in case the user has disabled agents.

 

        }

 

        public void StartUpload()

        {

            // Implement the logic to upload the file here. You will need to authenticate as well as provide support to upload a file

        }

Finally, we will add a UI element, which will initialize the upload. For this, we will add a button called “Upload” and on its click event we will call the StartResourceIntensiveTask() method.

private void buttonUpload_Click(object sender, RoutedEventArgs e)

        {

            StartResourceIntensiveTask();

        }

 

Now, we have laid out all the plumbing needed to support auto-upload in our application. To implement the actual uploading is left as an exercise to the reader.

If you are having trouble following, you can download the sample code of the project from here.

Summary

In this article, we learned about building support for auto-upload in your Windows Phone 8 application. I hope you have found this information useful.

Download WindowsPhoneAutoUploadDemo

About the author

Vipul Patel is a Program Manager currently working at Amazon Corporation. He has formerly worked at Microsoft in the Lync team and in the .NET team (in the Base Class libraries and the Debugging and Profiling team). He can be reached at vipul_d_patel@hotmail.com

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories