How to create and debug a background task in Windows 8 – Part 2

In the previous post we’ve created and configured a background task for our Windows 8 application: we’ve created a separate project for the task and we’ve configured the manifest file. Now it’s time to write the code in the client to register the background task, so that the application can take advantage of it. We’re going to register the background task we’ve created in the previous post: a timer based task that simply display a toast notification.

Here is the code that we insert in the MainPage.xaml.cs file, which is the code behind of the first page that is loaded when the application starts.

private async void RegisterBackgroundTask()
{
    try
    {
        BackgroundAccessStatus status = await BackgroundExecutionManager.RequestAccessAsync();
        if (status == BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity || status == BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity)
        {
            bool isRegistered = BackgroundTaskRegistration.AllTasks.Any(x => x.Value.Name == "Notification task");
            if (!isRegistered)
            {
                BackgroundTaskBuilder builder = new BackgroundTaskBuilder
                {
                    Name = "Notification task",
                    TaskEntryPoint =
                        "BackgroundTask.NotificationTask.NotificationTask"
                };
                builder.SetTrigger(new TimeTrigger(60, false));
                builder.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable));
                BackgroundTaskRegistration task = builder.Register();
            }
        }
    }
    catch (Exception ex)
    {
        Debug.WriteLine("The access has already been granted");
    }
}

The first thing we do is ask the user the permission to run the background task by calling the metod RequestAccesAsync of the BackgroundExecutionManager class. When this method is called, a dialog box is displayed and the user can choose if the wants to enable or not the task: the choice is returned by the method embedded into a BackgroundAccessStatus enumerator. You will immediately notice that the whole code is embedded into a try / catch statement: this is required due to a bug in WinRT APIs, that returns an exception in case the user has already accepted to run the background task.

In case the user has confirmed to run the task we search if it’s already registered in the operating system. Unlike in Windows Phone, in fact, it’s possible to register the same task multiple times: in Windows Phone, instead,  you’ll get an exception. To accomplish this task we access to the collection of all the registered tasks (BackgroundTasksRegistration.AllTasks) and we look for a task which name is Notification task: later you’ll see that this is the name we set for our task.

If the task isn’t registered yet, we go on and register it: we create a new BackgroundTaskBuilder object and we set two properties: Name, which is the identifer of the task (it’s the one we’ve used before to check if it’s already registered or not), and TaskEntryPoint, which is the same value we set in the Entry point parameter of the manifest: it’s the full name of the class which hosts the background task, plus the namespace. In our example, the entry point is BackgroundTask.NotificationTask.NotificationTask.

It’s now time to define the type of background task we’re going to register: we do this by using the SetTrigger method on the BackgroundTaskBuilder object. Since in this example we’re going to create a timer task, we set a new TimeTrigger and we choose to run it every 60 minutes. Background tasks in Windows 8 support also conditions, which are a great way to make sure that a task is execute only when one or more criteria are satisfied: in this example, since we’re going to simulate a background task that periodically checks for some news, we add a SystemCondition of type InternetAvailable. This way, we can avoid to check in the background task if there is an active Internet connection because, if it’s not the case, the task won’t be executed at all.

In the end we register the task by calling the Register method. Last but not the least, we need to add a reference of the background task’s project to the client: let’s right click on the client project, choose Add reference and, by using the Solutions tab, double click on the background’s task project.

It’s time to debug!

We’ve created a background task but how can we debug it? Obviously, Visual Studio 2012 offers a smarter way than simply waiting for the condition to be satisfied (in our example, an Internet connection is available and the 60 minutes time trigger is reached). First we have to register the task when the application is launched: in this example we’re going to call the RegisteredBackgroundTask method we’ve just defined when the MainPage is initalized, so we call it in the constructor.

The first time the application is launched, you’ll see the dialog that will ask you the permission to run in background: confirm it and, once the application is started, go back in Visual Studio. Now right click with your mouse on one of the empty spaces near the toolbars and choose to display the Debug location toolbar. Near the name of the process you’ll find a dropdown menu, with some precious options that will allow you to simulate the various states of the application lifecycle (Suspend, Resume or Suspend and shutdown): in our case, since we’ve registered a background task, you will see another option with the name of our background task, that is Notification task.

Click on it and… voilà, your background task will be executed: if you set a breakpoint on the Run method of your background task’s project, you’ll see that is triggered and you’ll be able to debug it as you would normally do with another application.

And if it doesn’t work? Here are some common things to check in case you have problems:

  • Make sure that the background task’s project type is Windows Runtime Component.
  • The client should have a reference of the background’s task project: check the References tree of your client’s project.
  • Check the application’s settings (using the setting’s icon in the charm bar) and make sure that both notifications and background tasks are enabled.
  • Make sure that the entry point is correct,  both in the manifest and in the code. It should be the name of the class with, as prefix, the full namespace.

If you want to play with background tasks, here is the link to download the sample project used in this tutorial.

Download the source code

Posted in Uncategorized | 20 Comments

How to create and debug a background task in Windows 8 – Part 1

Finally, after many tries, I’ve been able to find which is the correct way to create, configure and debug a background task in Windows 8. Let’s make a little step backward: like in the Windows Phone world, Windows 8 apps can’t run in the background. In fact, they are automatically suspended after 10 seconds that the app is not in foreground anymore. To override this limitation, Windows 8 has introduced background tasks, that are operations that can be executed in background when a criteria is satisfied: a timer is expired, a push notification is received, the computer status is changed and so on.

The concept should be familiar to Windows Phone developers: Windows Phone 7.5 has introduced the same way to support background operations. The biggest difference is that Windows 8 background tasks are more powerful: in Windows Phone there are only a few background tasks categories (mainly, based on timer events), while in Windows 8 you can create tasks that are executed when many different conditions are satisfied.

The downside is that, in Windows 8, background tasks are not so easy to implement and debug, mainly because a dedicated Visual Studio template is missing (unlike in Windows Phone), so it’s a bit tricky to understand how they work.

The first important thing to keep in mind is that a background task is a separate Visual Studio project, that is part of the same solution that contains the main application. So, the first step is to create a new project, by right clicking on the solution and choosing Add – New project. The template you’re going to use is Windows Runtime Component, inside the Windows Store category.

It’s important to use this template because, in this case, the output type of the project will be automatically set to Windows Runtime Component (you can see it in the dropdown under the Output type library in the project’s properties). If you use another project’s type (like Class Library) the background task won’t work.

Now let’s proceed to write some code: rename the class that is automatically created with the project to a more appropriate name (for example, NotificationTask) and change it so that it inherits from the IBackgroundTask interface.

This interface will required you to implement the Run method, which is the one that is called when the background task is executed: it will contain all the logic needed to perform the background operations. In this example, I will create a simple background task that displays a toast notification. Here is the method that we use to send the notification, using one of the available templates:

private void SendNotification(string text)
{
    XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);

    XmlNodeList elements = toastXml.GetElementsByTagName("text");
    foreach (IXmlNode node in elements)
    {
        node.InnerText = text;
    }

    ToastNotification notification = new ToastNotification(toastXml);
    ToastNotificationManager.CreateToastNotifier().Show(notification);
}

Using the ToastNotificationManager we get the XML that identifies one of the available templates and we proceed to change the text node, which contains the notification’s text. In the end, we create a new ToastNotification object using the updated template and we shot it using again the ToastNotificationManager.

In the Run method we’re simply going to call this method passing a fake text as parameter:

public void Run(IBackgroundTaskInstance taskInstance)
{
    SendNotification("This is a toast notification");
}

As you can see the Run method comes with a IBackgroundTaskInstance object, that contains all the information about the current task. This parameter is important especially if we’re going to write asynchronous code because, with the architecture we’ve just seen, the task will end before the asynchronous code is completed.

For this reason, we should use a BackgroundTaskDeferral object, that we can get from the taskInstance parameter, as in the following example:

public async void Run(IBackgroundTaskInstance taskInstance)
{
    BackgroundTaskDeferral deferral = taskInstance.GetDeferral();

    //we launch an async operation using the async / await pattern    
    await CheckNewItems();

    deferral.Complete();
}

First, we get the BackgroundTaskDeferral object by calling the GetDeferral metohod of the taskInstance object. Then, we execute our asynchronous code (in the example, we call a fake method that checks if there are new items to download) and then, in the end, when everything is complete, we call the Complete method on the BackgroundTaskDeferral object.

Show me some client love

Ok, so far we’ve seen how to create the background task. But how we tell to the client (the real Windows 8 application) to use the background task? There are two steps: the first one is to declare the task in the manifest. Double click on the Package.appxmanifest, so that the visual editor shows up, go to the Declarations section and add a Background Tasks declaration: we’re going to set two important fields.

  • The first one is the background task’s type: in our example we’re going to use a timer background tasks, which can be executed periodically. You’ll simply have to check one of the available options.
  • The second one is the background task’s full entry point, which is the namespace plus the name of the class. Since in our example I’ve created a NotificationTask class inside a project called BackgroundTask.NotificationTask, the entry point will be BackgroundTask.NotificationTask.NotificationTask.

We haven’t finished to edit the manifest yet: as you can see in the image, once we’ve set the background task a warning icon (the white cross over the red dot) appears in the Application UI tab. This happens because when you include a background task which type is Timer, Push notification or Control Channel you are forced to set which type of lock notification you’re going to use. This is required because these kind of background tasks are mainly used to support lock screen notifications.

To do that, open the Application UI tab and:

  • Set in the Lock screen notifications option if you’re going to use display just a badge (the icon with a number) or you support also text (like, for example, the Calendar app, that shows the title of the next appointiment).
  • Include an icon to use as a badge for lock notifications. It should be an image file with resolution 24×24.

The last thing to do is, in the Notifications section, set the option Toast capable to yes, since the background task we’ve created display toast notifications.

It’s time to write some code… almost

In the next post we’ll see how to register the background task in the code and how Visual Studio 2012 helps us in testing and debugging the background task.

Posted in Windows 8 | Tagged | 5 Comments

How to override the default color of a ProgressBar in a Windows 8 application

So you’re doing Windows 8 development and, very likely, your app needs to display some data. Rarely this data is immediately available: maybe you need to download it, or you have to parse it before displaying it. Here comes in help the ProgressBar, so that the user is aware that something is loading and that he needs to wait until the operation is completed.

By default, the ProgressBar automatically uses the accent color the user has selected for his Windows 8 installation: this isn’t always the best choice, because your application may use a background that doesn’t fit with the ProgressBar color.

The first thing you would try to do, as a developer, is to change the Foreground or the Background property of the control, but you’ll notice that the trick doesn’t work: the color of the ProgressBar doesn’t change.

This happens because the default ProgressBar color is defined in one of the default styles, so you have to override it to change it. To do this, simply add the following statement in the ApplicationResources defined in the App.xaml file:

<ResourceDictionary.ThemeDictionaries>
    <ResourceDictionary x:Key="Default">
        <x:String x:Key="ProgressBarIndeterminateForegroundThemeBrush">White</x:String>
    </ResourceDictionary>
</ResourceDictionary.ThemeDictionaries>

In this example, the ProgressBar is displayed with a white color: instead of writing the color’s name, you can also put the hexadecimal code of the color.

Enjoy it!

Posted in Windows 8 | Tagged | 2 Comments

SQLite for WinRT is now available on Visual Studio Gallery

Thanks to Tim Heuer I’ve found that there’s an easier way to add SQLite to your Windows 8 application rather than the manual one described in my post. Now SQLite for WinRT is available as a Visual Studio extension, you can simply add it by searching for the keyword sqlite: the name of the extension is SQLite for Windows Runtime. Once you’ve installed it and restarted Visual Studio, you can now simply add SQLite to your application by adding a reference to two of the available libraries in the Extensions panel: Microsoft Visual C++ Runtime Package and SQLite for Windows Runtime. You can access to the panel by right clicking on the project, choosing Add reference and selecting Extensions from the Windows menu.

SNAGHTML12499e4

SNAGHTML125199d

Be aware that, since the library uses C++ extensions, you can’t compile the application using as a platform the Any CPU option, but you should target a specific platform. To do that, open the Configuration manager from the Build menu and set the platform to one of the available options (x86, x64 or ARM).

SNAGHTML1270275

If you don’t do this, you’ll see a warning sign on the two references Microsoft Visual C++ Runtime Package and SQLite for Windows Runtime and the project won’t compile.

image

And… you’re done! No more manually downloading the dll library and copying it to the Visual Studio project: you can simply go on, install sqlite-net and use the same code you’ve learned to use in my first post.

Thanks to Tim Heuer for the tip and… happy coding!

Posted in Windows 8 | Tagged , | 5 Comments

Migrate your Windows 8 apps from Release Preview to RTM

Here we go again: a new Windows 8 version has been released (luckily, it’s the last one Smile) and we have to test our application against the RTM, to see if everything is working fine.

Luckily, this time the migration process is much easier than with the Release Preview: I’ve been able to run my applications on the RTM just by compiling them with the final Visual Studio 2012 release; when Release Preview was released, instead, I had to fix a lot of things, since there were a lot of breaking changes from the Consumer Preview.

In this post I would like just two highlight two important things to keep in mind.

Update the manifest file

Thanks to Daniele Bochicchio I’ve found that the Windows 8 manifest file contains a reference to the OS version which the application is compiled for. If you’re working on a project created with the Release Preview, the version number will be 6.2.0, while the RTM version number is 6.2.1. Unlucky, for old projects, Visual Studio doesn’t update it for you, so you need to proceed manually.

  • In Visual Studio 2012 right click on the Package.appxmanifest file and choose View code.
  • You’ll find a section in the XML file called Prerequisites.
<Prerequisites>
  <OSMinVersion>6.2.0</OSMinVersion>
  <OSMaxVersionTested>6.2.0</OSMaxVersionTested>
</Prerequisites>
  • Change the value 6.2.0 that is stored in both nodes to 6.2.1, so that it looks like this:
<Prerequisites>
  <OSMinVersion>6.2.1</OSMinVersion>
  <OSMaxVersionTested>6.2.1</OSMaxVersionTested>
</Prerequisites>

And you’re done! This way you’ll be able to take benefit of all the WinRT changes applied to the RTM: otherwise, the app will run in a compatibility mode called Release Preview Compatibility Mode. You’ll app will pass the certification process anyway, but it’s better if we set from the beginning the right OS version.

If you want to go deeper about the RTM changes, take a look at this document published by Microsoft that lists all the changes between the RP and the RTM from a developer point of view.

Unable to activate Windows Store application: the app didn’t start

The first time you open your project with Visual Studio 2012 RTM and you try to debug it, you may occur in a strange error:

Unable to activate Windows Store application. The activation request failed with error ‘The app didn’t start’

In this case the solution is simple: close Visual Studio, delete the bin and obj folders inside your project’s folder, open it again with Visual Studio and launch it. This time it will start successfully!

Posted in Windows 8 | Tagged | 3 Comments