Background tasks, though they are essentially extensions of a app, only have limited capabilities where using the WinRT APIs are concerned. They can access the app’s appdata folders and settings, for example, and perform file I/O with Windows.Storage APIs. No problem there. Background tasks cannot, however, generate UI with the exception of issuing toast notifications and tile update.

Background tasks are also able to perform string lookups in resource files using the Windows.ApplicationModel.Resources.ResourceLoader class or Windows.ApplicationModel.Resources.Core.ResourceManager.current, meaning that they do have access to the app’s localized content.

One issue that comes up with background tasks written in JavaScript is that the task itself, which runs as a web worker, cannot employ the WinJS library. As a result, a JavaScript background task cannot access resources through WinJS.Resources.getString, and occasionally this leads developers to think that background tasks cannot access resources at all. But because this particular WinJS API is implemented with the WinRT APIs, you can just use the latter directly.

Using a <form> element in a Windows Store app is allowable, but has a few caveats to be aware of. The most important part to understand is that generally speaking, <form> really isn’t a necessary construct in an app. On a website, <form> is often used to collect information within a group of other controls (children of the <form>). So far so good. The tricky part is what happens with the contents of those controls when some kind of button is clicked or tapped, where the behavior is specifically defined by the method and action attributes of <form>.

The method attribute, either “get” or “post,” defines the HTTP method used to interact with whatever URI is given in the action attribute. On the web, if you want to take the contents of the form’s controls and post them to another URI–presumably to store that info in a database or such–you’d use method=”post” with that URI. In this case the form contents are transmitted within the body of the HTTP request. With method=”get”, the contents of those controls are appended to the action URI as name-value pairs, such that the URI can do whatever it wants with that data.

The main caveat, then, for Store apps is that typical form submission implies navigation to a new URI, meaning that you lose your script context. If this is what you want to do, that’s perfectly fine, but typically you want to stay in the same page context as apps normally do.

The navigation behavior can be hidden if the <form> element has no explicit action, for instance:

<form method=”post”>
<input type=”text” name=”login_username” />
<input type=”password” name=”login_password” />
<input type=”submit” id=”login_submit” name=”login_submit” />

In this case, action defaults to the same URI as the current page (a web page can post form data to itself, as when doing validation). As a result, using this kind of markup in an app will cause you to lose the script context. What could happen with the above code, then, is that if you’d assigned a handler for the login_submit button’s click event in the app’s activated handler, it would work the first time but not the second time. That is, the URI navigation that happens with a submit button like this doesn’t restart the app, so the activated handler isn’t called again, even though the HTML and JavaScript for that page is reloaded.

Let me be clear on this point. When you start a Store app written in JavaScript, what gets launched is an instance of wwahost.exe that will load up whatever HTML page you identify in the app’s manifest as the start page. This, as always, means it will load and execute whatever JavaScript exists in that page (directly or via <script>). The code in such a page typically subscribes to the app’s activated event (Windows.UI.WebUI.WebUIApplication.onactivated, for which many apps use the WinJS.Application.onactivated wrapper). And this is exactly what happens if the page is reloaded through a <form> submit.

However, even though the code in the reloaded page listens for the activated event, it won’t be fired again because the app is already running. That is, the activated event is fired from within WinRT only when the app is launched or activated from some other system event (like various contracts), An internal URI navigation within an app does not “activate” the app and therefore the event is not fired.

So if the activated code for the app wired up a click handler for the submit button, it will work only the first time and not after the page is reloaded.

A second issue is that even if you did reload the page properly, an app doesn’t have access to the HTTP request body, so the form data is loast anyway.

In the code above, you can just remove the <form> element completely, then in the submit button’s click handler just extract the data you need and act on it–typically using WinJS page controls to “navigate” via DOM replacement.

Alternately, if you use type=”button” instead of type=”submit” then you remove the reposting behavior of <form> and can handle the button click in the same way. That is, a button in this case doesn’t trigger the form’s navigation behavior, so the page won’t be reloaded.

The bottom line is really that <form> isn’t particularly useful in an app (the local context, anyway), so you need to disable it’s navigation behavior one way or another. If you want to use the element for semantic markup purposes to delineate a group of input controls, that’s fine–just use type=”button” for the submit, or just use a <button> to begin with. Otherwise you can use a <div> to group the controls.


A recent MSDN forum post asked a good question, one that I realized isn’t often adequately answered for developers new to the concept of data binding. It’s simply then question, “When do I use data binding at all?”

Here’s how I answered the question, and I’d enjoy hearing your thoughts on the matter.

Data binding is typically used to set up an automatic relationship between a data source and one or more UI elements. This is so you can

  1. Simplify the initialization of UI element contents from a data source (one-time binding)
  2. Have the UI elements update whenever the data source changes (one-way binding, which effectively includes one-time)
  3. Have changes in the UI element also be reflected back to the data source (two-data binding, which includes one-way)

When small bits of UI are involved, you can just as easily do all this manually, just by setting innerText/innerHTML values (or other attributes) within the appropriate event handler. However, when the UI gets more involved, e.g. you’re using collections or you’re starting to set up relationships to multiple properties of multiple elements, then having a more formalized structure to handle the data-to-UI wiring starts to make a lot of sense. This is really what data-binding is meant for (and really shines when you’re dealing with database sources and other large data sets.)

“Formalized structure” is what you often see referred to in the context of “view models” (e.g. model-view-controller (MVC), model-view-viewmodel (MVVM), and so forth). Those patterns are ones that have developed from data-binding capabilities; they encapsulate a structure wherein data (the model) is managed independently of how it’s shaped (view), how it’s presented (viewmodel), and how it’s manipulated procedurally (controller). These patterns achieve a ‘separation of concerns’ between data and UI, which is an adjunct to a similar but different separation between markup (HTML), styling (CSS), and code (JS).

[Here I inserted this note as the question was related to WinJS: Note that WinJS provides mechanisms for one-time and one-way data-binding, but not two-way; the latter, however, is not too hard to wire up on your own. I talk about all this in Chapter 4 of my book.]

The bottom line is that data binding is really a best practice, but not a requirement, especially in simple cases.

This flag exists to answer the question: “Is there a way with WinJS.Navigation.navigate to navigate to a new page without adding an entry in the history?” If you look in WinJS’s base.js, you’ll find that when this flag is true, WinJS skips the step of adding whatever page you’re navigating to to the nav stack. That flag itself exists in WinJS to apparently prevent the initial page in an app from being entered into the history, but as it’s implemented you can use it also for this more general purpose. Just be sure to set it to false when you want pages to be added to the history again.


The Windows Store Certification requirements (section 4.5) stipulates that apps doing data transfers must avoido doing large transfers over metered connections (you know, the ones that charge you outrageous amounts of money if you exceed a typically-small transfer limit!). At the same time, getting a device set up on such a network can be time consuming and costly (especially if you exceed the limit).

There is certainly room here for third-party tools to provide a comprehensive solution. At present, within Windows itself, the trick is to use a Wi-Fi connection (not an Ethernet cable), then open up the Settings charm, tap on your network connection near the bottom (see below left, the one that says ‘Nuthatch’), then in the Networks pane that appears (below right), right click the wireless connection and select Set As Metered Connection.

network settings  Wifi menu

Although this option doesn’t set up data usage properties in a network connection profile, and other things a real metered connection might provide, it will return a networkCostType of fixed which allows you to see how your app responds. YOu can also use the Show estimated data usage menu item (shown above) to watch how much traffic your app generates during its normal operation, and you can reset the counter so that you can take some accurate readings:

Wifi usage

It’s also worth noting that Task Manager has a column in its detailed view, on the App history tab, for metered network usage, where you can track your app’s activities.

Task manager app history

It’s good to know this as a user, too, as you can see if there are any misbehaving apps you might want to reconfigure or uninstall.


Thanks to my associate Tonu Vanatalu for this. He wrote it in response to some brainstorming we did in my larger team about common code patterns in Windows Store apps. It’s written in C#, but it just uses WinRT APIs so I trust that JavaScript devs can translate the casing and insert fully-qualified identifiers where needed:

public App()
    // Set initial behavior based on connectivity

    // Set up handler for network status change
    NetworkInformation.NetworkStatusChanged += NetworkInformation_NetworkStatusChanged;

void NetworkInformation_NetworkStatusChanged(object sender)
    // Set behavior based on connectivity status

void SetDataConnectivityOptions()
    // Get connection profile for currently active connection
    ConnectionProfile profile = NetworkInformation.GetInternetConnectionProfile();

    if (profile != null)
        NetworkConnectivityLevel connectivityLevel = profile.GetNetworkConnectivityLevel();
        if (connectivityLevel == NetworkConnectivityLevel.InternetAccess)
            // Get connection cost associated with the profile
            ConnectionCost cost = profile.GetConnectionCost();

            // Check if there is limit imposed on maximum transfer size
            DataPlanStatus dataplanStatus = profile.GetDataPlanStatus();

            if (dataplanStatus.MaxTransferSizeInMegabytes != null)
                // Maximum transfer size is limited
                // Suspend transfers exceeding the size and warn the user

            switch (cost.NetworkCostType)
                    // The use of this connection is unrestricted up to a specific limit.
                    if (cost.Roaming == true)
                        // Even if the cost is fixed up to a limit the user is roaming
                        // Which means the limit might be relatively low and cost per byte expensive

                    if (cost.ApproachingDataLimit == true)
                        // The connection is approaching it’s unrestricted limit

                    if (cost.OverDataLimit == true)
                        // The connection is over the data limit, possibly either connectivity
                        // is severely limited or very costly


                    // Cost information is not available

// The connection is unlimited and has unrestricted usage charges 
                    // and capacity constraints.

                    // The connection is costed on a per-byte basis.
                    if (cost.Roaming == true)
                        // User is roaming, possibly on a very expensive network
            // Limited network access
            switch (connectivityLevel)
                    // This value indicates captive portal connectivity, where local
                    // access to a web portal is provided, but access to the Internet
                    // requires that specific credentials are provided via the portal.

                    // Local access only

                    // No network access
        // Currently there are no network connections
        // Suspend pending network operations until network becomes available


The WinRT API, Windows.System.Display.displayRequest.requestActive, is that you use to tell Windows to keep the screen turned on while your app is in the foreground. That is, calling this API prevents Windows from turning off the screen when that app is active, as is appropriate for video players, navigation apps, and so forth.

It’s very important to note, however, that Windows honors the request only when the app is visible (in whatever view state). If an app has made a request but is then hidden, regardless of whether it’s using background tasks or not, Windows will turn off the screen as usual.

Note that if you make a request, call requestRelease when the app is suspended and call requestActive again when it’s resumed. The Display power state sample demonstrates these.

The point here is that requestActive is meant for apps that need to keep the display active, but cannot be used to prevent a device from going into a sleep state, for example, to perform background processing. Background tasks exists for that purpose so that the system can manage their overall impact on battery life.

The resuming event is fired for all Windows Store apps when they return to the foreground (or visibility) from a suspended state. The event is surfaced to apps written in JavaScript via Windows.UI.WebUI.WebUIApplication.onresuming; in C#/VB/XAML it’s Application.Resuming. For C++/DirectX, it surfaces as CoreApplication.Resuming. Whatever the case may be, the event is useful for a variety of purposes. I mention a number of these in my book, but it’s helpful to collect all those in one place. If you have other scenarios where resuming is helpful, I’d love to hear about them in the comments.

  1. Check if you need to refresh data from an online source that might have changed while the app was suspended.
  2. If you were offline when suspended, check whether connectivity exists on resuming, and switch into online mode. The opposite is also true, especially if the user got on an airplane while you were suspended.
  3. Refresh any sensor input that you’re tracking, such as the compass, orientation, or geolocation.
  4. Refresh the app’s layout, because it’s possible for the app to resume directly into a different view state than when it was suspended, even to a different resolution and scaling if the device has been connected to an external monitor, docking station, etc. (or disconnected from such). The user might also have gone to PC Settings > Ease of Access and toggled Make Everything On the Screen Bigger. You’ll also get focus, visibility, and sizing related events where you might do this work already, but in any case it’s a good case to test.
  5. Enable or disable app bar commands and other on-canvas controls that are dependent on clipboard contents.
  6. If you make a request to keep the screen on through Windows.System.Display.displayRequest.requestActive, then docs say to call requestRelease on the suspending event. This means that you would then call requestActive again on resuming.
  7. Check license status for trial apps and in-app purchases if you’re using expiration dates. See yesterday’s post on the licencechanged event. Here, if you’re suspended you won’t get the event; it might fire sometime after you resume, but I haven’t tested that specifically. In any case, resuming is a good time to check licenses in any case.
  8. If you’re using background tasks of any kind to update appdata, use resuming to refresh the app with that new state.
  9. Check if there’s new roaming appdata that appeared while the app was suspended. I believe that Windows will queue the Windows.Storage.ApplicationData.dataChanged event if this happens, in which case you could handle it that way, but I haven’t tested this to be sure.
  10. If you issue tile updates or toasts while the app is running (and aren’t using periodic or push notifications), think about whether to refresh those updates on resuming, including scheduled notifications.
  11. Refresh any push notifications channels if you’ve been suspended for some time, especially if any channel’s expirationTime has passed.
  12. If you perform data transfers that might be affected by cost-awareness on metered networks, use resuming to check the network type and respond accordingly. Note that transfers you set up using the Background Transfer API will work with this automatically while you’re suspended.
  13. If you’re accessing external devices using many of the Windows 8.1 APIs in Windows.Devices, you generally need to close those devices while suspending and them open them again on resuming. One exception are the APIs for point-of-service devices that have a distinct cooperative model through which you need to claim a device, and a claim is automatically released unless you explicitly retain it on suspend. If you don’t retain, however, then you’ll need to reclaim on resume.

In any case where you need to check how long the app was suspended, simply save a timestamp in the suspending event (Windows.UI.WebUI.WebUIApplication.onsuspending, WinJS.Application.oncheckpoint, Application.Suspending, or CoreApplication.Suspending), get another one upon resuming, and check the difference. Whether you take additional action depends on the nature of your data. An RSS feed, for example, might only go stale after a few hours or a day, but a geolocation reading or stock quote is pretty much immediately stale, in which case you’d always get new data on resuming.

In short, you really want to identify any external data or conditions that might affect your apps function, and how the data/conditions might change while an app is suspended. The resuming event is then there for you to know when to update the app accordingly.


The short answer is yes, but not to the e xact second of the expiration time.

The background: in playing with the Trial app and in-app purchase sample, I tried setting the ExpirationDate for the trial license (in trial-mode.xml for Scenario 1) to a time that’s only a minute in the future. When running the app in Visual Studio, I expected to see a licensechanged event fired when that time passed, but didn’t. I could use the buttons in the app to check the license and see that it’s expired, but the event wasn’t there. So I wondered if this was expected behavior, or if it was related to using the CurrentAppSimulator object instead of CurrentApp.

Turns out that I just needed to be more patient! For sake of performance and reducing power consumption, the license time tracker in Windows does not send such notifications the moment a license expires. But the event will eventually fire, generally on the order of a few tens of minutes. So yes, your customers might get another half-hour of free usage, but those trials will indeed expire and the app will receive the event.

(Thanks to Sanjeev Dwivedi for the insight here.)