In Windows 8.1, there’s a new WinRT-level HTTP API, specifically Windows.Web.Http.HttpClient that is intended to gradually supercede other APIs. More about this in my earlier post, Cool New APIs in Windows 8.1 #2: Windows.Web.Http.HttpClient.

One feature of this API is that it lets you manage cookies directly, something that APIs like the JavaScript XMLHttpRequest (and WinJS.xhr) lack.

In this context, some have asked whether cookies involved in one HttpClient request will persist to subseqeuent calls. The answer here is yes, in the same way that a desktop browser handles them. This means that cookies used with apps are subject to the typical app isolation policies for websites: cookies for app A are not visible to app B and vice-versa. The cookie will persist across calls, certainly, and also across app sessions, as they are stored in the WinINet cache like other HTTP request data. This assumes that the cookies are marked as persistent, and they are still subject to normal per-app limits and so on.

Calling HttpClient.Dispose(), mind you, will clear this stuff out.

The same policies apply to everything else in the WinINet cache, by the way–stuff that app A downloads is cached for it (subject to usual limitations), but is not accessible to app B. If the two apps request the same resource, that resource is cached separately for both apps and will be downloaded separately for each.


One of the next most interesting APIs added to Windows 8.1 that I also write in Chapter 4 of my Second Edition Preview is the Windows.Web.Http.HttpClient API (and associated classes). On the surface–and the API is designed to be very simple and easy to use for common cases–it seems redundant with other available APIs like WinJS.xhr (i.e. XMLHttpRequest) or the HttpClient API in .NET. In that sense it at least provides a robust HTTP API for C++ developers.

Digging down a little deeper, however, this new API goes well beyond the existing ones and should, in time, obsolete the other methods. For one thing, it provides cache control and access to cookies unlike the existing APIs. In comparison to the .NET API, this new WinRT API works with the WinINet cache, so benefits from any caching that happens via Internet Explorer, other apps, or the pre-caching API that’s now in Windows.Networking.BackgroundTransfer.ContentPrefetcher class.

The new API also provides a low-level hooking mechanism called filters that allows you to place handling code beneath the level of app logic. The HttpClient sample that’s now available shows how to create filters for authentication, 503 retries, and network cost awareness, meaning that the rest of the app can ignore the details of such concerns. That is, instead of having every HTTP request in your app have to think about cost awareness, you let the filter do that. The rest of the code either just gets the data or doesn’t, which makes it a lot simpler to write.

For additional details, also see Peter Smith’s talk from //build 2013: Five Great Reasons to Use the New HttpClient API to Connect to Web Services.


When testing your app, keep a keen eye out for how and when progress indicators are showing up, or how they aren’t showing up for that matter. Generally speaking progress indicators show that some long-running process is happening or that the app is waiting for some data or other results to be delievered. The latter is probably the most common, because long running processes like image manipulation are under the app’s control and is just a matter of crunching the pixels. Network latency, on the other hand, whether from connection timeouts of slow transfer speeds, isn’t something the app can do much about other than wait.

To simulate a slow connection, you can, of course, create additional traffic on your connection while you’re testing the app–e.g. playing videos, running big downloads (and uploads), and so forth. The faster your connection, the more you’ll have to load it up. You might also be able to change settings in your modem or router to make everything run more slowly. For example, if you have a wireless-N router, change it to run only at wireless-A speeds, then load it up with extra work.

You can also add some debugging code to simulate latency. In JavaScript, for example, wrap your network calls with a setTimeout of 1-2 seconds, or longer, depending on what you want to simulate. You can wrap the initial call itself and also wrap delivery of the results. You could create a small wrapper that would get the results quickly into a separate buffer, but then buffer them as real results within a series of setTimeout calls. Having such a setup that you can co

Whatever the case, slowing down the network speed will help show where and how progress indicators are being used. You’ll want to especially look for places where your app just appears to sit without any visual indication of the work it’s doing. This reveals that your code is making assumptions about how quickly data is coming back and that you’ll need to put up a progress indicator if the user waits for more than 1-2 seconds (the recommended timeout for showing an indicator).

On a slow connection, too, you can better evaluate whether you’re overusing progress indicators. That is, while it’s nice that we have controls to show work happening, they are something that users will get tired of looking at over and over. So think about how you might architect the app to wholly eliminate the need for those indicators. For example, if you are switching between a page with a list of items and a details page for one item, and there’s a delay in that switch, it’s a good place to simply switch the visibility of two pages that are fully constructed, rather than doing a real navigation that would tear down and rebuild the pages each time. The user won’t be able to tell the difference, except that everything is running much faster. Indeed, building a page with a list control of hundreds or thousands of items is a very expensive process, so avoiding that work is a good thing, especially when the list page itself doesn’t change in the process of navigating in and out of details.

On the flip side, also test your app on the fastest connection you can find and see if there are any places where progress indicators show up unnecessarily. This would also reveal places where you’re assuming that the data will take a long time to obtain, and where a progress indicator might just flash on the screen momentarily and create visual noise. In those cases you’ll want to make sure you again use a timeout before the indicator appears.

 

 


At first glance, and in reading different documentation (including the first edition of my book–I’m now working on the second), it seems like the Web Authentication Broker in WinRT is meant for a few key OAuth identity providers like Twitter and Facebook. That was at least my initial impression, but it’s mistaken.

The Web Authentication Broker is actually meant for any service that provides authentication. It’s primary purpose is to avoid collecting credentials in client apps and then transmitting those credentials over HTTP requests. Ideally, if apps always protected those credentials with appropriate encryption and using SSL over HTTP, and avoided storing any credentials on the client in plain text, then the web auth broker might not be necessary. But apps usually aren’t written that securely, so it’s best to authenticate directly with the service and have that service provide the app with an access token of some kind.

This is what the Web Authentication Broker is meant for. By invoking it–providing with your service’s authentication URI–an overlay appears above your app and displays the service’s page directly. This means that any and all information that the user enters at this point is going securely to the service and not to the app. The service, as described in the guidance for web auth broker providers, can provide whatever series of pages it needs for its own workflow, but at the end of it all it responds with a token that the client can use in subsequent calls.

So if your app in any way needs to collect credentials to authenticate with a service, consider using the web auth broker for this purpose and create the necessary pages on your service for this purpose. With just a little work, you can craft those pages so they look great within the broker window and integrate nicely into your app experience.


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
    SetDataConnectivityOptions();

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

void NetworkInformation_NetworkStatusChanged(object sender)
{
    // Set behavior based on connectivity status
    SetDataConnectivityOptions();
}

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)
            {
                caseNetworkCostType.Fixed:
                    // 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
                    }

                    break;

                caseNetworkCostType.Unknown:
                    // Cost information is not available
                    break;

caseNetworkCostType.Unrestricted:
// The connection is unlimited and has unrestricted usage charges 
                    // and capacity constraints.
break;

                caseNetworkCostType.Variable:
                    // The connection is costed on a per-byte basis.
                    if (cost.Roaming == true)
                    {
                        // User is roaming, possibly on a very expensive network
                    }
                    break;
            }
        }
        else
        {
            // Limited network access
            switch (connectivityLevel)
            {
                caseNetworkConnectivityLevel.ConstrainedInternetAccess:
                    // 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.
                    break;

                caseNetworkConnectivityLevel.LocalAccess:
                    // Local access only
                    break;

caseNetworkConnectivityLevel.None:
                    // No network access
                    break;
            }
        }
    }
    else
    {
        // Currently there are no network connections
        // Suspend pending network operations until network becomes available
    }
}

 


The Windows App Certification Kit or WACK, which is part of the Store Certification process, is something you should be running every day during app development to see if it comes up with any problems.

Typically it warns about startup time and suspend time, almost invariably, but it’s good to really watch these conditions because of the automatic deadlines built into Windows. To review, if an app takes more than 15 seconds to create its first window (and thus tear down the default splash screen), and the user switches away, Windows will terminate that app. If the user doesn’t switch away, mind you, the app will continue to launch. With suspend, if the app doesn’t return from its suspending event handler in five seconds, it will also be terminated.

Under optimal conditions, you typically don’t need to worry about these things, but if you’ve learned anything about testing you’ll know that apps seldom run under optimal conditions!

On such non-optimal condition is when there is a lot of disk and/or network activity going on at the same time, such that your app will experience slower than normal response from disk/network APIs. For example, the app might be trying to load file data from its package during startup, or might be trying to make various XmlHttpRequests on suspend. When there’s a bunch of activity going on, an operation that takes half a second normally might take much longer and perhaps cause the app to exceed the time limits.

This means two things. First, be sure to test app launch and suspend when other stuff is going on. Try, for instance, to launch your app as soon as you can after booting the system, when there’s still other disk activity. Or do some intensive operation on the file system (like run the Disk Cleanup tool) and see what happens when you launch or suspend. Try the same things after you’ve started a few large downloads and a few uploads, so your app has to compete with those transfers.

Second, implement your app to be resilient to high latency. If in the above tests you find that startup can take a long time, be sure to implement an extended splash screen to give yourself as much time as you need. For suspend, you can first take the approach to write/transfer as much state data to disk before suspend occurs (i.e. when the data changes), thereby minimizing the work that’s necessary during the event itself. Also avoid making the assumption that you can do the full load of possible work when suspending. If there’s doubt, create a strategy wherein you save the most critical data first, then attempt additional stages of secondary work if there’s still time. The suspending event tells you the deadline for completing your work, so you can keep checking elapsed time after each operation to see if you want to start another.

In any case, running your app under high-latency conditions will also show you where you might increase performance and/or show progress indicators where you haven’t before, because tests under optimal conditions never showed the need for such.

 


It’s very important–thought easy to overlook–that you test your app under varying levels of network connectivity, or at least consider what they might mean for your design. Those levels are:

  • Full connectivity to the Internet, with unmetered data and high speed transfers. This is the situation that we typically assume, because it means unrestricted access to network resources and whatever data we might want to acquire or share.
  • Limited connectivity (local network only). This is where there could be some access to resources on other local devices, but Internet resources are not available. This would only be a concern for apps that are specifically written to communicate with themselves or related apps on a local network (via IP addresses and mechanisms like sockets) and are not relying on remote resources from http[s] sources and such.
  • Connectivity with high latency. This means having connectivity to the resources you need, but the data comes down slowly, perhaps much more slowly that you expect. This is a concern where overall app performance is concerned. For example, an app might assume that it can just wait until the data is available to refresh its display and not show anything like progress indicators and such to tell the user that the app is waiting for some operation to complete. I’ve seen apps that assume they get their data in short order, but when there are timeouts or other such problems, the app becomes unresponsive or uninformative. Apps that do a better job have built-in resiliancy to timeouts, builthave -in retry mechanisms, and keep the user updated as to the status of network connectivity. (As an example, some of the system UI will say things like “Connecting to a network is taking longer than usual” with an option to cancel.
  • No connectivity (local or internet). This is the most important one to consider, becaue many apps, assuming the best where connectivity is concerned, are not written to gracefully handle the lack or loss of connectivity, and oftentimes just end up in a state where they appear hung. Worse still, some apps just fail to deliver any meaningful user experience without connectivity and give no suggestion that connectivity might be the problem. A bad app in this regard fails to give the user a means to retry whatever they might have done earlier, if they’ve taken steps to remedy connectivity problems. In these cases, the user is forced to close the app and launch is again, hoping for the best.
  • Metered connectivity (typically a mobile broadband network that might be pay-as-you-go or possibly nearing its data limit). The Store certification requirements state that apps that do large transfers need to be sensitive to possible overage charges. See section 4.5 of those requirements for details. Fortunately, the Background Transfer APIs in WinRT pay attention to this, but if you’re using your own mechanisms you’ll need to be attentive to metered situations.
  • Roaming a device between networks. For the most part, apps don’t need to concern themselves with this if they’re handling the other situations above. Windows itself automatically handles roaming to a new network and choosing the best one of those available. Sometimes this means entering a metered network, sometimes it means leaving one. Sometimes the network speed will increase, other times it will decrease.

You might also consider airplane mode, meaning that wi-fi is disabled by a wired network could still be used, though this is generally a case of “no connectivity” above when a wired connection doesn’t exist.

Whatever the case may be, the important event to know about and listen to is the Windows.Networking.NetworkInformation.onnetworkstatuschanged event. This is fired whenever there’s a change in connectivity, including cost. Similar to this event is aso the networkStatusChange background task trigger, which you can use to execute a small piece of background task code for this condition if the app itself is suspended or not running.

In the former case, you can learn more about the details from the Network information sample; in the latter, refer to the Network status background sample. I discuss these topics in more depth in Chapter 14 and 13 (respectively) of Programming Windows 8 Apps in HTML, CSS, and JavaScript.

 

Now knowing what conditions to test for is one thing; the second part is knowing when to test for these, that is, what app states to test along with the different levels of connectivity. The primary ones here are:

  • During first startup: what happens if the app is launched (from its tile and through whatever contracts it supports, such as Search and being a Share target)?
  • During subsequent startup: same tests as above, but now with the possibility that previously-cached data is available for offline use.
  • While the app is running; what happens when connectivity levels change while the app is active? This is important to test both on single pages that might make network requests, and especially on page transitions where the app might be making network requests to populate the new page with data.

The most reliable and robust apps will respond to different conditions at these different times in such a way that the user is never left confused as to what’s going on and what they might be able to do about it. The worst thing for an app is where the user ends up staring at a blank screen without any idea of what might be wrong. I’ve seen this with some apps, where I tried to launch them in airplane mode after just installing them while waiting for a flight, or when I run the app after having travelled somewhere and not having connected to the Internet yet.

It’s also very confusing when the app is working just fine, but goes through an indeterminate visual state while waiting for its data. Let’s say that you have the kind of app that shows a list of search results, then navigates into a details page for one of those items. Let’s say that under normal conditions that list of results comes down within half a second and acquiring the details within a similar timeframe. With those timings, the app doesn’t need to pay attention to visual details going between the results and details pages. However, increase those times to two seconds or more and a user could see blank screens or otherwise unresponise UI for too long a time. This could easily happen when the user is in a hotel or other situation with a shared internet connection that is handling many demands from multiple users. It could also happen where the servers providing all that data are slow to respond for whatever reason (say, a problem at one data center that is placing a larger-than-usual demand on the others).

The answer to such times may be as simple as putting up a progress indicator or other message that tells the user to wait a bit (something that’s good to do after two seconds of waiting). But these things often need to be designed, and should involve whatever designers you worked with on the rest of the app’s UX because such things are, in the end, part of that user experience. This is important to understand, because you often don’t see the need for such designs until you’re well into development and testing of the app. So be sure that you can go back to your designers for some of these concerns when you need to.

In some cases you can eliminate some of the delays with clever implementation. In apps with results-details pages, it’s not necessary to completely navigate away from the results page to show the details page, that is, it’s not necessary to tear down the results page when showing the details page. Instead, just create and show the details page on top of the results page. In HTML/CSS, this just means placing a full-screen div for the details page over the top of the results page. That way, when navigating back to the results page, which is often a very common activity, you just hide or tear down the details page, letting the pre-existing results page just become visible again. (You’ll want to determine how long it’s been since it was last visible, in case it’s appropriate to refresh the data.) This way you avoid most needs to reacquire the data for that page, thus eliminating a case where connectivity is a concern.

Whenever you acquire data, too, consider caching it in some way so that you can start the app again without connectivity and have something meaningful to show. There have been times where I know I’ve been using an app, as I have a website, and wanted later to return to that same data/page to see something again. So if connectivity has been lost, and the app is reloading that previously saved data, then I get to see something familiar instead of a blank page and a message saying there’s nothing to show. With cached data, at least I can see and interact with what I saw before, which may, in fact, be exactly what I wanted.