Developing connected applications

[ This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation ]

This paper provides a set of network considerations that every connected Windows Store app should know about.

Introduction

Windows 8 introduces the new Windows Runtime with a simple yet powerful set of APIs that developers can use for building apps in C++, C# or JavaScript. One of the important properties of Windows Store apps is that most of them will be "connected".

This document defines a connected (or network-aware) app as a Windows Store app that wishes to use the network for any purpose. Every connected app will need to follow the guidelines below in order to provide a predictable and enjoyable experience for users.

Selecting the right network capability

Apps must declare network isolation capabilities in order to have access to network resources. Use the following checklist to ensure that network isolation is configured for your app.

  • Determine the direction of network access required by your app. This can be outbound client-initiated requests, inbound unsolicited requests, or a combination of both.
  • Determine the type of network resources that your app will communicate with. Consider if your app needs to communicate with trusted resources on a home network, a work network, the Internet, or a combination of these network types.
  • Configure the minimum-required networking isolation capabilities in the app manifest. This can be accomplished using the Microsoft Visual Studio Express 2012 for Windows 8 during app development.
  • Deploy and run your app to test it using the network isolation tools provided for troubleshooting.

The capabilities declared are enforced by Windows. Apps should use the principle of least privilege and only add capabilities they need. The following table details the network isolation capabilities.

Network Capability Description

Internet (Client)

Provides outbound access to the Internet and networks in public locations, like airports and coffee shops. Most apps that require Internet access should declare this capability.

Note  

Declared as internetClient in the app manifest.

 

Internet (Client & Server)

Provides inbound and outbound access to the Internet and networks in public places like airports and coffee shops. Inbound access to critical ports are always blocked.

This capability is a superset of the Internet (Client) capability; there is no need to declare both.

Note  

Declared as internetClientServer in the app manifest.

 

Private Networks (Client & Server)

Provides inbound and outbound network access at locations trusted by the user, like at home or work. Inbound access to critical ports are always blocked.

Declared as privateNetworkClientServer in the app manifest.

 

Other certificates that may be required for your connected app include those that provide device proximity awareness or shared user certificates. For more information on network isolation and declaring capabilities, see How to configure network isolation capabilities.

Selecting the right API

The Windows Runtime provides support for a variety of networking APIs for communicating with remote endpoints on the Internet or on private networks. For cases where a specific higher-level protocol is not available to the developer through an API, the Windows Runtime also supports TCP and UDP sockets (along with multicast) to enable developers to implement other higher-layer protocols.

Who is impacted?

All Windows Store apps that need to send or receive data on the network are impacted.

Guidance

First, determine the functionality you want your app to have. If the functionality falls into one of the feature areas below, then use these APIs directly.

APIs Functionality

Windows.Web.AtomPub, Windows.Web.Syndication

APIs for retrieving feeds in the RSS or Atom formats across multiple versions. The Windows Runtime also supports the Atom Publication Protocol, enabling the publication of Atom collections. Additionally, these APIs make it easy to implement support for newer formats such as OData.

Windows.Networking.BackgroundTransfer

APIs used for uninterrupted, cost-aware, and resume-able downloading/uploading of content, even when the calling application is not in the foreground. This API supports download using HTTP, HTTPS, and FTP protocols.

XMLHTTPRequest (JavaScript), HttpClient (C#), IXHR2 (C++).

APIs used to interact with RESTful web services and other HTTP-based protocols.

Windows.Networking.Proximity

APIs used to detect close proximity between two devices after which applications can trigger network communication between them using Socket APIs.

Windows.Storage.Pickers

APIs used to communicate with remote file shares (such as saving a file to a remote file share) must use the file picker APIs.

 

If an API with the functionality you want to include isn't listed above, use the new Windows.Networking.Sockets APIs. However, apps that use these APIs will need to consider the following:

  • Windows 8 introduces a new type of socket, called a "WebSocket". Here are some considerations that will help you decide when to use the various types of sockets (UDP, TCP, or Websockets).

    • If you are connecting to a service that uses a protocol that is not supported by the APIs described in this section, like SMTP, MAPI, or telnet, use TCP or UDP sockets.

    • If you need to connect to another device on the same local network, use TCP or UDP sockets.

    • If you need a simple request and response protocol that can communicate through HTTP proxies, then use the REST APIs described above. (C++, C#, JavaScript).

    • If you are creating an app that requires socket-like semantics (asynchronous, bi-directional) to connect across the web (including through HTTP proxies) to a new service you are also creating – use WebSockets.

  • Use names to address endpoints. Avoid using IP addresses (including IP literals in URIs) to address endpoints because IP addresses can change, whereas the name typically does not. Using a name will generally ensure that you connect to the current IP address for the endpoint.

  • Windows APIs traditionally use Unicode strings as the native format (including for HostNames and URIs). However, a given protocol can require a different format; make sure to convert strings to whatever format the protocol requires using the DataReader/DataWriter class methods to do this.

  • HostNames and URIs must be implemented as class objects, not as strings, when comparing for equality because the rules of equality are different for objects.

  • Register for network change notifications, and follow the guidelines as detailed in Reacting to network status changes.

Adapting app behavior for metered networks

Metered networks have existed for a while on the Internet. For example, most ISPs have a cap (usually quite a large cap) on the amount of data users can transfer per month. More recently, the increasing popularity of mobile broadband technologies has made the problem more acute in that either exceeding the data cap or roaming can result in significant monetary charges to the user. Consequently, apps need to monitor available network resources and behave appropriately.

The table below lists possible connection costs defined by Windows.Networking.Connectivity.ConnectionCost.

Property Description

ApproachingDataLimit

Gets a value that indicates if a connection is approaching the usage allowance specified by the data plan.

NetworkCostType

Gets a value that indicates the current network cost for a connection.

  • Unrestricted: Use of this network connection is unlimited. It has unrestricted usage charges and capacity constraints.

  • Fixed: Use of this network connection is unrestricted up to a specific limit.

  • Variable: Use of this network connection is metered on a per-byte basis.

  • Unknown: Cost information is not available for this network connection.

OverDataLimit

Gets a value that indicates if the connection has exceeded the usage allowance specified by the data plan.

Roaming

Gets a value that indicates whether the connection is connected to a network outside of the home provider.

 

Who is impacted?

In general, all apps (especially those that transfer large amounts of data) need to follow the guidance below:

Users will be able to determine the amount of bandwidth that each application is using. Improper use of metered network bandwidth can influence the reputation of your app and company.

Guidance

Apps that connect to destinations on the Internet should obtain cost information about the network on which they are sending and receiving data using GetInternetConnectionProfile. Depending on the data transfer limitations set by the carrier, use the following guidelines:

Behavior Guidelines
Normal

In normal scenarios, the app should not implement restrictions. The connection should be treated as 'Unlimited' in cost, and unrestricted by usage charges and capacity constraints.

If the NetworkCostType is "Unrestricted" or "Unknown" and the ConnectionCost is not "Roaming" then the app should implement normal behavior.

Examples:

  • The media player app can play an entire HD movie.

  • An app can download a large file without any restrictions or prompts.

Conservative

In conservative scenarios, the app should implement restrictions for optimizing network usage to handle operations on metered networks.

If the NetworkCostType is "Fixed" or "Variable" and the ConnectionCost is not "Roaming" or "OverDataLimit" then the app should implement conservative behavior.

Examples:

  • The media player app can play movies in lower resolutions.

  • An app can delay non-critical downloads.

  • An app can avoid pre-fetching of information over a network.

  • Email apps can switch to a header-only mode when receiving email messages.

Opt-In

In opt-in scenarios, the app should handle exceptional cases where the network access cost is substantially higher than plan cost. For example, when a user is roaming, a mobile carrier can charge a significantly higher rate.

If the ConnectionCost is "Roaming" or "OverDataLimit" then the app should implement opt-in behavior.

Examples:

  • The app should prompt the user to access the network.

  • The app should suspend all background data network activities.

 

Reacting to network status changes

When Windows 8 detects new networks, it will automatically provide new connectivity options. For instance, if a user is using a 3G network to stream data and later comes into range of a Wi-Fi network, the new connectivity option will be available for the app to leverage if it makes sense to do so.

In any mobile device scenario, networks can come and go. A 3G network could go out of range within a user’s home or garage while Wi-Fi is still available; similarly, Wi-Fi may go out of range when a user leaves his home. Additionally, there may be times when no network is available. Given the proliferation of Wi-Fi and mobile broadband networks, such network changes (networks coming, going, or not being available) will be common. Connections do not automatically switch over to a new network seamlessly; the application needs to get involved. Note that the default policy in Windows 8 is to pick the unrestricted network over the metered network and the faster network over the slower network.

Who is impacted?

All Windows Store apps that use a network are impacted, and not following these guidelines can result in a poor user experience any time network changes occur.

Guidance

All Windows Store apps should do the follow these steps:

  1. If the connection the app was using is no longer available (indicated by an error):

    1. Check the cost of connecting to the Internet.

    2. Retry the operation. If this fails, then wait for another NetworkStatusChanged notification.

  2. Check the cost of connecting to the Internet and then adapt behavior as recommended in earlier Adapting behavior for metered networks.

  3. Register for network status change notifications (onNetworkStatusChanged).

  4. Start the network operation using one of the APIs described in Selecting the right API.

  5. A network status changed notification indicates that the available cost or connectivity options may have changed. When this notification is received do the following:

    1. Check the cost of connecting to the Internet. If the cost characteristic has changed (free -> cost, or cost -> free), then retry the network operation. Windows 8 will automatically use the best network/lowest cost network available. On retrying, if the network operation succeeds, then cancel the original network operation.

      Note  Advanced developers may also choose to optimize app behavior when retrying network operations. For example, you may want to replace an existing connection with a new connection over a higher speed network. In this scenario, a developer can use the Sockets APIs (BandwidthStatistics) to determine whether to switch.

       

    2. If the cost characteristic of connecting to the Internet has not changed, but a cost-related notification is received, like >80% cap consumed, variable cost, roaming, and so on, then adapt behavior.

Debugging and troubleshooting connected apps

Network glitches can cause apps to stop responding, crash, or show non-actionable dialog boxes and confusing error messages to the users. Debugging these errors can be difficult because errors can occur anywhere within the networking stack.

Who is impacted?

All Windows Store apps that use the network either directly (using sockets) or indirectly (using an API that eventually uses the network) are impacted. The ideal situation is for the operating system to automatically handle error conditions on behalf of the developer and when that does not work, apps should be prepared to deal with errors.

Guidance

Windows Store apps need to do the following:

  • When a networking error happens, retry the operation if appropriate. For instance, do not retry the operation if authentication fails, but retry the operation if the network you were communicating on went away because another one may be available. Many errors simply go away when the operation is retried. On retrying, follow the guidelines specified earlier in Reacting to network status changes.

  • Ensure that you use asynchronous APIs so that there is no blocking call on the UI thread. In other words, if a networking operation takes a long time to complete or there is an error, your application should not stop responding. Do not emulate synchronous behavior on top of the asynchronous nature of the Windows Runtime.

  • Ideally, have a model for handling errors planned in advance. Think through how to expose error information to the user as you design your app. For example, Outlook uses a discreet network indicator; Communicator has a "replace the whole UI" scheme; Internet Explorer includes a task-oriented dialog box for downloads that displays network errors. Catch exceptions for cases where an exception is thrown, understand each of the error strings, and appropriately inform the user.

  • Test your app in various networking environments with activities like disconnecting or reconnecting to your network, suspending or resuming, or switching from one network to another.

  • When you are testing your app and find errors that are not immediately obvious, enable ETW tracing.

Resources

The following documentation provides guidance and API details for Windows Runtime features described in this topic:

Feature implementation guidance

Adding support for networking

Connecting to a web service

Connecting to network services

Connecting to a web socket service

Accessing connection and data plan information

Transferring a file from a network resource

Accessing and managing syndicated content

Code samples

Namespace documentation

Windows.Networking.BackgroundTransfer

Windows.Networking.Connectivity

Windows.Networking.Proximity

Windows.Networking.Sockets

Windows.Storage.Picker

Windows.Web.AtomPub

Windows.Data.Html

Windows.Web.Syndication

Windows.Foundation (Uri Class)

Windows.Networking (HostName Class)

Windows.Storage.Streams (DataReader/DataWriter Classes)