Gaining Access: Making Sure Your Windows 8 App Background Task Has What It Needs

Overview

In Windows 8, Windows Store (formally known as metro style) apps have the ability to define background tasks that can perform tasks that run even when the app isn’t in the background. Though to make sure the user’s battery doesn’t cry uncle prematurely these background tasks are resource constrained. In this post we’ll take a look at how Windows 8 does resource management for background tasks.

The Constraints

Windows 8 performs resource management for background tasks through the use of resource constraints. There are two main types of constraints a background task needs to worry about: CPU time and network usage. The amount of CPU time and network usage an app’s background task is allocated depends on if the app is on the lock screen or not.

A Windows Store app is considered a lock screen app if it occupies one of the seven available lock screen slots on the lock screen.

When your app is a lock screen app Windows will give your background tasks a higher quality of service over resources then a non-lock screen app. The CPU time constraint is enforced regardless of the current power state of the device but the network usage constraints only come into play when PC off of AC power.

 

Note: Windows will dynamically adjust the network usage constraint based on the power usage of the active network link. Typically, Wi-Fi connections use less power than the cellular connections and will be allowed to send more over the link over a given period of time than cellular connections.

The Elite

Among all the possible triggers available to an app to trigger their background tasks the following triggers are considered “critical” as far a Windows is concerned.

  • Push notification trigger
  • Control channel trigger

These triggers are meant to be used during real time scenarios like receiving a VOIP call. These background tasks are given guaranteed app resource quotas according to the resource quotas listed previously. Meaning Windows will not try and terminate these tasks early even if the system becomes resource constrained. These triggers require an app to be a lock screen app in order to be used.

The Hook

If your app doesn’t require the increased resources or trigger capabilities of a lock screen app you’re better off sticking with triggers that don’t require lock screen capabilities. It’ll simplify things but from a programming and certification standpoint and from a user standpoint in terms of battery life.

If you do require lock screen capabilities for your background tasks here’s what you need to know. To be on the lock screen you’ll need to provide an additional image asset, a 24 by 24 pixel png image, for the badge that gets displayed on the lock screen. As there are only 7 slots available on the lock screen for apps you’ll be competing with other apps for those slots so you’ll have to make a compelling case to the user to add your app. Which brings us to our next point, the app will needs to be added to the lock screen explicitly by the user.

That last point is key, there is no programmatic way to add an app the lock screen. Windows does toss the app a bone by giving a way for the app to programmatically ASK the user to add the app to the lock screen though the BackgroundExecutionManager.RequestAccessAsync() method but it comes with a big caveat. It’s a one shot deal. No matter the outcome: yes, no or dismissed it will only work once.

Making the Connection: Lighting up Metro IE’s Ability Direct Link to an App in the Windows Store

How do I make users aware that my app exists? That’s most likely one of the most prominent questions a developer’s ask themselves when they release an app, and for good reason. No one likes to see their hard work go to waste. A little known feature in Metro IE is its ability to advertise the availability of Windows Store app (also known as a Metro style app) for the current website in the Windows Store though Metro IE’s appbar.

Metro IE allows a website to specify the following actions for an app:

  • Install an app if it’s not already installed
  • Switch to an app if it’s already installed

A website can choose to have just one of the options active or both depending on their needs. The way Metro IE recognizes a website has an associated Windows Store app is through the use custom meta tags in the header area of a website’s page.

The minimum required meta tags to light this up are:

  • msApplication-ID
  • msApplication-PackageFamilyName

Both of these can be found in the app manifest of the project once the app is associated with store though Visual Studio and are used to link the website and Windows Store app together.

When an app is launched though Metro IE in this manner a custom argument can be specified through another meta tag with the name “msApplication-Arguments”. The app can then read this argument from the OnLaunched method in App.xaml.cs.

As actions speak louder than words, if you want to see this behavior in action you just visit Relay’s website in Metro IE and give it a try. For context, Relay is our sample notification app, feel free to give that a try too while you’re at it :)

The Bing homepage also has this integration setup if you want to see another live example.

Until next time!

C# Feature Dossier: Tasks Based Asynchrony with Async and Await

If you haven’t been living under a rock for the past year you’ve at least probably heard about the new C# async and await keywords coming in C# 5 that’s shipping in with Visual Studio 2012. In a nutshell what the feature allows you write asynchronous code and make it look like it’s synchronous. That means that you no longer have to write callback handlers to handle what happens when the async operation you invoked has returned. An illustrative example using good old HttpWebRequest should drive the point:

In this first example we used the traditional Begin/End async pattern on HttpWebRequest to request a website and print it to the console. Notice how you have to split your logic between setting up the request and dealing with the result once results come in. In .net 4 this became a bit easier with the introduction of the Task Parallel Library (TPL) and the Task class.

A way you can think about a Task is that it represents a promise of a future result rather than the actual. In other words sometime in the future I’ll have the value you request. What’s nice about this abstraction is that it allows you to combine asynchronous operations into a single operation thanks to since your returning a promise rather than the actual result.

One thing you might be asking yourself at this point is great I can write an async method in one go now by return a promise of something to come. What if I need to act on the result before I return it to the caller? Glad you asked! And that’s where Task continuations come in. They basically allow you to specify an action to take on a Task once it completes. So enough talk, let’s see this stuff in action:

There are a couple things going on here but take note that unlike with the begin/end async pattern everything is neatly contained within a single method with a Task being returned that will contain the async result being returned.. Let’s break this down starting off with the call to the Task.Factory.FromAsync method. FromAsync is a static method provided by the TPL base class library for bridging the traditional async begin/end pattern over to the new Task based async pattern. The method returns a Task representing the result the begin/end async invocation.

That in and of itself is pretty neat but the real magic of this examples lies in the continuation that’s being defined of the Task we got back from the FromAsync method. All tasks have a method called ContinueWith that then allows you act upon the future result of the Task you call ContinueWith on. Basically, you’re saying what you should do once the parent task or antecedent has completed. No longer do you have to define call backs and event handlers to handle async. You can simple call a method and pass in a delegate. This makes writing async methods immensely easier since your async code is all in one place and reads much better.

The last part is this example is returning the task that was given to us by the call to continue with. This the Task that calling code will wait on for the final result of this asynchronous method. Pretty, nifty right? So now that we’ve seen TPL and Task based asynchrony in action how do C#’s new async and await come into the picture. They make writing and consuming task based async methods so easy that they look like synchronous method calls. No callbacks, no wrapping delegates, events hooks. Just code. (Well it’s all just code in the end but you get my drift).

Seeing is believing so here’s what are method looks like with async and await.

 

Like I said, just code :) The interesting to point here are the introduction on two new keywords. The async keyword in the method signature and the await used in front of the methods that have async at the ends of their names. The async keyword marks a method as being asynchronous and allows the use of the await keyword within it.

The await keyword is the bread and butter of all this. What it does in a nutshell is unwrap a Task by introducing a point of asynchrony into the method at which the compiler can logically pause code flow execution until the Task completes. Point of emphasis here “logically pause” code flow execution. Note I didn’t say block but pause.

One thing to be aware of when writing task based methods with async and await is that the method returns after the first await in the method. Which could or could not be what you want. On WinRT and asp.net the thread is released to do other work and will reschedule itself once the Task that is awaited on completes and continue execution after the await. If you try and await on your main method (in actuality you’ll get compile error, but work with me) in a console app you’ve now released your app’s main thread and the program will terminate. Point of this being while async and await do make async work easier to manage you do still need to be aware of their nature.

Hopefully, this you’ve found this high level overview of async and await at least somewhat helpful. But we’ve only just scratched the surface of what the TPL is capable of. We have yet to talk about CancellationToken that help provide unified cooperative cancellation, scheduling of Tasks with the TaskScheduler, concurrent collection primitives like ConcurrentBag and ConcurrentQueue and many more. One last thing parting gift I’d like to leave you with is that if you’re still on .net 4 you can still leverage the async and await keywords in your app. Since async and await are really just a compiler transform all you really need is the C# 5 compiler in Visual Studio 2012 and the set of supporting types which the C# team has made available to .net 4 developers as Nuget package which you can find here.

Windows 8 App Developer Registration is Now Open! Here’s What you Need to Know.

Today’s an exciting day if your an individual Windows 8 app developer. The store now open. Before you go off and open your shinny new developer account here are few last minute good to know.

If your a STUDENT, MSDN subscriber or BizSpark member you get your Windows 8 developer account for FREE! The links below will get you to the right place. You’ll be given a registration code to enter when you sign up for your Windows 8 developer account.

When registering you’ll enter the code your given in a registration code field as shown below:

If none of the above apply an individual Windows 8 will cost USD $49.00 to register.

Now without further adu the link below will take you directly to the Windows Store dashboard:

Good luck! Hopefully we’ll see you on the flip side as an official Windows 8 developer.

Azure Mobile Services: For Those Who Just Want to Code

If you follow Azure news on the web you might have noticed a new Azure service being offered in preview form called Mobile Services.

In this blog post we’ll be doing a high level overview of what Azure Mobile Services is and what it gives you. In subsequent posts we’ll dive deeper into how to get your hands dirty and actually use the thing.

With this initial preview the Windows 8 app development scenario has been enabled. We’re likely to see other platforms such as iOS and Windows Phone (my personal favorite) come on board as the Azure mobile team develops the new service.

Why should I Care?

The idea behind mobile services is to provide is quick and easy way to bootstrap client app development by providing a supporting backend. If you want to write client apps and don’t want write all of backend web service logic yourself from scratch then you should take look at mobile services.

So here’s what we get out of the box mobile services:

  • Data storage
  • Authentication
  • Push notification

Like any other Azure service you also get a nice dashboard that shows a graph of your mobile service activity. In this case you’re able to see how the number of API calls, CPU time and data going out that service has made over time.

Data Storage

The data service is particularly interesting as it’s backed by Azure SQL Server and uses the JSON version of the OData protocol to communicate on the wire. One of the more interesting features of the data service is dynamic schema support which automatically updates the tables that backs the model as it changes. This makes it extremely easy to get up and running quickly as you no longer have to setup a database schema ahead of time, you can just let the service take care of creating the columns and choosing the appropriate data types in SQL server. Note that before you go into production you should turn off dynamic schema support to ensure that the schema can’t be changed outside of development.

The notion of dynamic schemas should by familiar to those who play with NoSQL document databases such as Mongo and RavenDB. The development experience is also very similar to that of entity framework code first if you ever used that before.

The C# primitives that mobile services is able to map out of the box include the following:

  • Integer types (int, long, etc.)
  • Floating points (double, decimal)
  • String
  • DateTime and DateTimeOffset

For any other data type like TimeSpan or a custom type you will need to convert to string or provide a client side converter that implements IDataMemberJsonConverter and handles the JSON serialization for that type to simple JSON types.

Authentication

One really nice thing about the mobile service is its client authentication support. To set it up all you need to do is register the web service with Windows Live, drop in your client id and secret with the mobile service and call a few methods on the client app and hey presto you’ve got authenticated calls going though.

The authentication service in mobile services is backed using Microsoft Accounts or Windows Live accounts if you haven’t got the branding memo yet. In order to make use of authentication in the client app you will also need the Windows Live Connect SDK. The Live SDK is responsible for displaying the sign in UI and eventually giving you an authentication token which you in turn hand over to mobile services client so it can perform authenticated requests to the backend. The code for this is actually simpler than it sounds.

And that’s all the code it takes to authenticate with our mobile service backend on Azure.

Push Notification

Last but not least we have push notification support which helps us to do push notifications back to our mobile client. The way push notifications work in the mobile services preview today is that they are created using server side scripts that are authored by the developer in the Azure mobile service portal. These scripts are written in JavaScript which get executed on the server when create, read, update and delete (CRUD) operations occur on data in the mobile service.

These scripts are responsible for creating push notifications will comprise the core of your server backend logic as well. They are responsible not only for creating push notifications but for validating and modifying in coming requests and performing authorization logic based on the incoming authenticated identity.

Under the covers, these scripts are actually being executed by node.js, Azure mobile services exposes a small subset of node modules that can be used by the scripts to do their work. We’ll go into more details in another blog post on how to use these scripts and what you can do with them. This is a pretty big topic in and over itself and a simple blub wouldn’t do the topic justice.

Anyways, now that we know where push notifications get created on the server we need to know the how. In order to leverage push notifications on the server the client app is responsible for obtaining the push notification channel URL from the PushNotificationChannelManager from within their app and uploading it to the service. Typically this gets saved as property on the model that you use to save data to mobile service.

The code for this would look something like this:

Once the notification channel is saved to the mobile service the server side scripts will then be able to use that push notification channel url to send push requests back to our app.

Hopefully this post gave you a good overview of how Azure mobile services work. In future blog posts I’ll be doing some deep dives on using specific pieces of the Azure mobile services like scripts, push notifications and the data service.

Engines Start. Development is Go!

Welcome to the inaugural posting of the MarkedUp blog!

Hopefully the first of many such posts. On this blog we’ll share our experiences not just with developing MarkedUp but with our general development experience from Windows 8 development and others as well.

We’re a passionate bunch of developers and hope this blog and the posts that follow will help the greater development community as a whole. Even if it’s just in small way. Since that’s what we do.