Chapter 2 - Designing Applications for Windows Phone 7
Windows® Phone 7 is a new and very versatile platform for building mobile client applications. However, when you design applications for Windows Phone 7, you must be aware of some of the inherent limitations placed on your applications by facets of the environment, such as the form factor, hardware resources, battery life, and intermittent connectivity common to all such devices.
This chapter describes the differences between applications that work well on mobile devices, such as Windows Phone 7 and applications designed for the desktop, along with the factors you should consider when designing for mobile devices. It will help you to understand the development and run-time platform of Windows Phone 7 devices. It will also assist you in making appropriate decisions on a range of factors, such as user interface (UI) design, storage, connectivity, data formats, and maximizing performance.
Basic Design Considerations
Before you examine the scenarios and considerations for mobile phone applications, use Figure 1 to frame the main areas of concern. All of these areas are covered in this chapter, with additional information available throughout the subsequent chapters and appendices of this guide.
Type of Application
The initial decisions you must make involve the type of application you will build, and how well this type of application is suited to a mobile device such as Windows Phone 7. You should also consider how you will implement your vision using a style and interactivity pattern that matches the built-in applications on the device, and how you can use the types of controls available on the phone to build a usable interface. In Windows Phone 7, the development platform you choose (Microsoft® Silverlight® browser plug-in or XNA®) will influence the application design and the types of controls available. For more information, read the sections "Mobile Phone Client Applications," "User Interface Design and Style Guidelines," and "User Input Considerations" later in this chapter.
Design and Implementation
Before you start to design and build your application, you should make some basic decisions about the way you will use techniques such as test-driven development (TDD), design patterns such as Model-View-ViewModel and Dependency Injection, and whether you will take advantage of third-party components or custom frameworks that match your requirements. You must also consider how you will implement data storage on the device, whether you will take advantage of phone capabilities such as the camera and Global Positioning System (GPS), and how you will manage connectivity to the network. In addition, you must be aware of how Windows Phone 7 devices may deactivate and tombstone your application. Although you do not have to finalize all of these decisions before you start, thinking about them now can help to stabilize your design and reduce the number of dramatic changes required later. For more information, read the sections "Storage Considerations," "Connectivity Considerations," and "Application Deactivation and Tombstoning" later in this chapter, and the discussion of the Model-View-ViewModel and Dependency Injection patterns in Chapter 4, "Building the Mobile Client."
Designing and building applications for small mobile devices such as the phone requires you to be aware of the resource limitations inherent in these types of devices. You should aim to make your application behave as a "good citizen" on the phone by optimizing performance and resource usage to provide the best experience for users and by avoiding any behavior that would negatively affect other features and applications on the phone. You must pay particular attention to allocating and releasing resources you use, minimizing battery drain, and maximizing performance on lower-power processors, such as those used in mobile phones. You should also understand how to take full advantage of the graphics processor in the device. For more information, read the section "Resource Management and Performance" later in this chapter and Chapter 5, "Using Services on the Phone."
Finally, you must consider how you will interact with remote services that provide the data used by your application. You can interact with many types of services, including cloud services such as Windows Live® network of Internet services, and the Location Service and Notifications Services that are specifically designed to integrate with Windows Phone 7 devices. Technically, the format of the data you use to drive your application is irrelevant, though you should consider interoperability with other devices, communication security, and whether you need to perform data or file synchronization between the device and the server. However, it is vitally important to consider the bandwidth utilization, transfer volumes, and the costs of connectivity for your chosen approach. For more information, read the section "Data Formats and Accessing Remote Services" later in this chapter; Chapter 5, "Using Services on the Phone;" and Chapter 6, "Connecting with Services."
Mobile Phone Client Applications
The physical properties of all mobile phones as a platform for building client applications apply certain limitations to the kinds of application you can build. For example, the device is unlikely to have access to large amounts of memory and storage, which prevents you from building applications that store large volumes of data. In addition, the likelihood of connectivity to the network being interrupted, and the lack of bandwidth available over some mobile connections, means that your applications must be able to either work with no connectivity or be able to manage interruptions and resynchronize when a connection is available.
|There are significant differences between the phone and the desktop in terms of device resources and capabilities.|
The following are some of the differences between a desktop or notebook computer and a mobile phone device:
- Processing power, memory, and storage. Mobile devices typically use lower power CPUs, have very limited memory, and have much less storage space available.
- Display size. Mobile devices typically have a small screen. In Windows Phone 7, the maximum screen resolution is 800 x 480 pixels. The screen display can also rotate to match the orientation of the device.
- Power consumption. The small battery in mobile devices means that application must exert the minimum possible drain on the battery. Techniques such as minimizing use of the Location Service and minimizing network activity can assist in achieving this.
- Application execution. Mobile devices usually allow only a single foreground application to execute in order to minimize power consumption and maximize performance. Mobile phone applications must be designed to preserve their state when they are interrupted or terminated by the operating system.
- Connectivity. Mobile devices often experience periods of limited or no connectivity as the user moves from one location to another. The bandwidth available and the cost of data transfer can vary considerably, depending on the type of connection that is available in each location and across different geographical regions.
- User interface. Mobile device applications are typically operated using a touch screen. The location, spacing, and types of controls that are suitable for a touch-based interface differ from those in a desktop or notebook application that relies on a mouse and keyboard.
For information about the requirements and restrictions for applications that you upload to Windows Marketplace, including the maximum size and the performance metrics, see Chapter 7, "Interacting with Windows Marketplace."
Suitable Application Types for Mobile Phones
You should also consider how and when the applications you build for a mobile phone will be used. In most cases, the user will be on the move, instead of sitting at a desk, and perhaps not in an ideal location for interacting with an application. Other factors, such as ambient lighting, noise, movement and vibration, and even interaction with other people, are common when using a mobile device.
Applications that are not likely to be successful on a mobile phone are those that have a complex interface, require multiple input steps to complete a task, or are unintuitive to use when adapted to a small screen. Users expect to be able to perform tasks quickly and without error in any environment, and they expect to be able to return to the application after interruptions, such as an incoming phone call.
|Not all types of applications work well on a mobile phone. Complex applications, and applications with a busy UI that demands extreme concentration, are unlikely to be easy to use on a phone.|
The types of consumer-oriented applications that work well on mobile phones are entertainment applications such as games, music players, photo viewers, video players, and social interaction applications that perform tasks such as sending messages, updating status information, or posting photos to a website. For business or enterprise oriented applications, the following are common scenarios that lend themselves well to the phone form factor:
- Messaging applications, such as email and SMS text messaging
- Collaboration applications that allow users to access and modify documents from the phone
- Meeting planners and calendaring applications
- Task-oriented applications for activities such as booking facilities and travel planning, service and schedule notifications, completing expense forms, obtaining approvals, or simple data-entry tasks that can be accomplished using the limited UI offered by the phone platform
- Specialized applications for specific industries, such as those used for viewing stock availability, for warehouse order picking, for placing sales orders, or for updating data in response to changing requirements
- Mobile-oriented and location-aware applications, such as those used for satellite navigation, delivery confirmation, surveying, or tracking vehicle movements
Silverlight and Windows Phone 7
In enterprise scenarios, and in many consumer scenarios other than media-rich applications and games, Silverlight is the optimum choice of development platform for Windows Phone 7 applications. The Tailspin Surveys example application described in this guide is a Silverlight application, although it does use interop to XNA to implement some features that are not accessible from Silverlight.
Windows Phone 7 supports almost the full capabilities of Silverlight 3, though there are some minor differences in the way it works, compared to Silverlight hosted in a web browser. For example, Windows Phone 7 does not support printing, and most of the visual controls are different to suit the UI requirements of the device, but the core programming platform is almost identical. If you are familiar with Silverlight, you will be immediately productive on Windows Phone 7.
UI design for the phone can be accomplished in Microsoft Visual Studio® 2010 development system and in Microsoft Expression Blend® 4 design software, both of which support creating Silverlight applications for Windows Phone 7.
|If you already know Silverlight, you will quickly be productive on Windows Phone 7.|
In addition, tools and frameworks are increasingly available for working with and extending Silverlight on Windows Phone 7. These include testing tools, additional controls, and frameworks for implementing common design patterns. Some examples are the patterns & practices Prism Library, Ninject (see http://ninject.org/), and Moq (see http://code.google.com/p/moq/).
This guide demonstrates how you can use well-known design patterns that are well suited to Silverlight, such as Model-View-ViewModel and Dependency Injection. Common development techniques, such as data binding for UI controls, and test driven development can be applied to Windows Phone 7 applications in the same way as for desktop and server applications.
|For information about developing Windows Phone 7 applications with Silverlight, see Appendix A, "Tools, Frameworks, and Processes." For information about the major differences between Silverlight and XNA, see Appendix B, "Silverlight and XNA in Windows Phone 7."|
However, there are some challenges when using Silverlight on Windows Phone 7 compared to the experience when using it in a web browser. For example, multitasking capabilities are limited, and the program itself cannot run in the background. Events such as a phone call arriving on the device will stop your application from running, and you must preserve state so that your application can correctly resume when required or can gracefully exit if the system requires the memory or resources it is using.
Design Considerations for Windows Phone 7 Applications
In addition to deciding on the type of application you will build and the platform (such as Silverlight or XNA) that you will use, you must consider the capabilities of the device and understand how these may affect your design. The following are the major factors:
- UI design and style guidelines
- Application deactivation and tombstoning
- User input considerations
- Storage considerations
- Connectivity considerations
- Security considerations
- Data formats and accessing remote services
- Resource management and performance
- Availability of components and frameworks
The next sections of this chapter explore these factors in more depth.
User Interface Design and Style Guidelines
The Windows Phone 7 Series uses a style named Metro that is designed to combine harmonious, functional, and attractive visual elements while clearly directing end users to the content they want. You should attempt to follow the same visual style and interaction paradigm for your application as is used in the built-in applications and the interface of Windows Phone 7 to ensure that your application is intuitive and easy to use.
|You must be aware of the style and UI guidelines when you design applications for Windows Phone.|
Microsoft provides a guide to the Metro design style and the recommended approach for creating a more consistent and fluid UI experience, including descriptions of standard input functionality within the UI framework, the software interaction elements, and the system-based controls. If you want to sell your application through Windows Marketplace, you must follow these design guidelines.
Remember that any images you use in your application should be suitable when the device theme is changed. For example, if you use a white icon or image and the user changes from the default black theme to the white theme, your image will not be visible. One approach is to use code to switch the selected image based on the current theme, as demonstrated in the Tailspin Surveys sample application that accompanies this guide.
|One of the major advantages of following the Metro theme is that the color scheme it uses helps to maximize battery life.|
For more information, see the guide, UI Design and Interaction Guide for Windows Phone 7; from the Microsoft Download Center (http://go.microsoft.com/fwlink/?LinkID=183218). For information about the Metro design and to learn about design and development recommendations for your applications, see the video presentation, Windows Phone UI and Design Language, on the Mix10 website (http://live.visitmix.com/MIX10/Sessions/CL14). For information about the resources (including the set of application bar icons) for Windows Phone 7 applications, see "Design Resources for Windows Phone" on MSDN® (http://msdn.microsoft.com/en-us/library/ff637515(VS.92).aspx). For a set of Adobe Photoshop design templates that help you create attractive applications that match the Metro theme, see the Microsoft Download Center (http://go.microsoft.com/fwlink/?LinkId=196225).
You must also consider how you will localize your application to achieve certification by Windows Marketplace. For a list of the supported languages for Windows Phone 7 applications, see "Globalization and Localization Overview for Windows Phone" on MSDN at http://msdn.microsoft.com/en-us/library/ff462083(VS.92).aspx; this page also provides a useful guide to the use of cultures, encodings, localizability, and links to other related resources.
Application Deactivation and Tombstoning
Unlike a traditional operating system on a desktop or server computer, Windows Phone 7 does not run multiple applications concurrently. Only one application—the foreground application—can be active and running at any one time. When the user switches away from the foreground application, or when an external event causes another application to become the foreground application, the original application is deactivated in a process referred to as "tombstoning." When the user switches back to the application, it is reactivated.
This means that if you want to preserve state (including page and control state) when your application stops being the foreground application, you must handle the events exposed by the operating system to save any state you require to implement a seamless resume experience (such as setting the contents of text boxes, a selected date, and so on). This saved state will be used to restore the application and page state when the application reactivates.
External events that may cause the application to be tombstoned include events such as a phone call being received; a system dialog box, such as the built-in photo selector, being displayed; or the phone lock screen being activated.
In addition, an application that is tombstoned may be completely removed from memory if, for example, the operating system detects that the device is running low on resources. In this scenario, when the user goes back to the application, it will restart. Therefore, you must make sure that you have preserved all persistent state to storage whenever your application is deactivated.
|When a phone call arrives or the user switches to another application, your application must save its state in case it is terminated by the operating system.|
You handle the Launching event to retrieve state for your application from isolated storage on the device and/or from a remote service, as appropriate, when the user first starts your application from the phone's Start screen. You also handle the Closing event that occurs when the user closes your application (or presses the Back button to navigate backward through the pages of the application past the application's first page) to save any state your application requires to isolated storage on the device and/or to a remote service, as appropriate.
You must also handle the Deactivated and Activated events. The Deactivated event occurs before the application is tombstoned, and you should save any transient state to the phone application service so that it can be quickly reinstated when the application is resumed. The operating system provides two objects where you save that transient state. Save transient application data to the PhoneApplicationService.State property, and save transient page state to the PhoneApplicationPage.State property. There is a time limit for the Deactivated event to complete. The device may terminate the application if it takes longer than 10 seconds to save the transient state.
|There is no guarantee that an application that was deactivated will be reactivated, so, in addition to the transient state, you should also save any persistent state to isolated storage or a remote service, as appropriate. Applications that require a large volume of persisted data may need to save that data incrementally while the application is running to ensure timely deactivation.|
The Activated event occurs when the user navigates back to your application using the Back button, or when a launcher or chooser that has interrupted execution to handle a phone call or to display the lock screen is deactivated. When your application is reactivated, you should retrieve the transient data from the PhoneApplicationService.State and PhoneApplicationPage.State property bags in the Activated event. As with the Deactivated event, there is a time limit for the Activated event to complete. The device may terminate the application if it takes longer than 10 seconds to reload the transient state and return the application to a running state.
|Launchers and choosers allow other applications or operating system features to execute while your application is running. For example, the PhoneCallTask launcher activates when a phone call is received, or your application may use a launcher, such as the PhotoChooserTask, to select a photo from the device storage. For more information, see "Launchers and Choosers for Windows Phone" on MSDN (http://msdn.microsoft.com/en-us/library/ff769556(VS.92).aspx).|
Figure 2 shows the life cycle, execution flow, and events you must handle to preserve state in a Windows Phone 7 application.
For a full explanation of the ways that you should handle the life cycle events in your application, see "Application Lifecycle" on Channel 9 (http://channel9.msdn.com/learn/courses/WP7TrainingKit/WP7Silverlight/ApplicationLifetimeWP7Lab/) and "Execution Model for Windows Phone" on MSDN (http://msdn.microsoft.com/en-us/library/ff769557(VS.92).aspx). A useful resource that explains how to use the PhoneApplicationService class is "How to: Preserve and Restore Page State for Windows Phone" on MSDN (http://msdn.microsoft.com/en-us/library/ff967548(VS.92).aspx).
User Input Considerations
The small screen on mobile devices and the requirement to support touch input present a challenge when designing UIs. Windows Phone 7 requires touch input and will not respond to pen-based or pointer input. In addition, the UI should be designed to work in both portrait and landscape modes. Some devices with a hardware keyboard will require the phone to be used in landscape mode for data entry tasks, as shown in Figure 3.
|Designing UIs for Windows Phone 7 is very different from designing UIs for the desktop.|
The following are some of the things you should consider when designing the UI for a mobile phone application:
- Do not try to adapt an existing UI design directly from a web or desktop application. Start afresh by thinking about the flow of user interaction and how you can maintain simplicity and make the application intuitive for use in the phone environment.
- Consider the fact that the design must work in both portrait and landscape mode.
- Choose the appropriate types of controls for display and input. Special controls designed to work well on Windows Phone 7, and used in the Metro theme, include the Pivot and Panorama controls.
- Place menus and other option boxes at the bottom of the page so that the user's hand does not obstruct the rest of the page content. However, remember that the on-screen keyboard will obstruct a large proportion of the screen when the user selects a text control.
- Follow the Windows Phone 7 application design guidelines by ensuring that buttons and other controls that the user must interact with are large enough, and that they have enough separation to prevent accidental activation of the wrong one.
- Provide feedback when an action is initiated so that the user is not tempted to retry the operation. Use a visual or other indication to signify that the program has recognized the gesture and is responding to it.
- Validate input where appropriate, especially before initiating communication with the server or starting a resource-intensive process. This prevents invalid input from causing additional data transfers and unnecessary communication costs; it also prevents wasting processor time and increasing drain on the battery.
- Consider setting the InputScope property of text controls to simplify user interaction. This property determines the type of on-screen keyboard displayed for the text control. For example, setting InputScope="Text" displays a simple predictive text-enabled keyboard, while setting InputScope="Url" displays a keyboard containing the characters most used in URLs. For a list of supported values, see "InputScopeNameValue Enumeration" on MSDN (http://msdn.microsoft.com/en-us/library/system.windows.input.inputscopenamevalue(VS.95).aspx).
Windows Phone 7 does not include a general-purpose file system or a local database. The only option for storing data on the phone is to use isolated storage via an API to access a virtual hierarchy of folders and files that is private to the application. Although third-party database mechanisms are likely to be available, you should consider whether the additional memory and resource overheads that a database will impose are necessary for your application. The majority of Windows Phone 7 applications will typically use only isolated storage.
|In future releases, there may be a database available on the phone; or you may alternatively consider using a third-party database that you install with your application.|
When storing data in isolated storage, the most common approach is to store it as serializable collections. The Tailspin Surveys client application discussed in this book uses isolated storage to hold collections of surveys and their content.
|Using serializable collections is a good way to store data in isolated storage on Windows Phone 7 devices.|
Storage is limited on mobile devices when compared to desktop and notebook computers. The minimum specification for Windows Phone 7 devices is 256 MB of memory, though manufacturers are likely to install more than this. The phone can also accept extended memory of up to 8 GB using a flash card.
Isolated storage on the device is shared among operating system data, built-in applications, user content (such as downloaded media), and other applications that the user installs on the device. Being a "good citizen" is especially important on the phone because there is no limit to the amount of data that an application can store (there are no per-application storage quotas). This means that your applications must minimize their use of storage without causing a reduction in performance of the device and your application. The following are some recommendations for using storage on the device:
- Use the DeviceExtendedProperties class to see how much memory your application is using, and how much memory is installed and available. For more information about the DeviceExtendedProperties class, see Appendix C, "Leveraging Device Capabilities."
- Make sure that your application cleans up and releases storage when it is no longer required, especially when the application is tombstoned or terminated.
- Consider using caching to improve application performance, but only cache data that is regularly required and that does not affect the availability of isolated storage for other applications and services.
- Consider compressing data that is placed in storage, though keep in mind that this will require additional processing and reduce battery life. You may be able to use data formats that are more compact; for example you might store configuration information or other types of data in binary or JSON format instead of XML format.
- Ensure that sensitive data is encrypted, especially when it might be stored in removable media, such as a flash card.
| Typically, you will see the following effects, depending on the serialization method you choose:|
XML: Larger payload, higher CPU utilization
JSON without compression: Smaller payload, lower CPU utilization
JSON with compression: Smallest payload, higher CPU utilization
When building traditional client-server and Web applications, a typical assumption is that connectivity between the server and the client will be available all the time. If the client cannot access the server, the application will usually stop working or produce an error.
However, when working with mobile devices, this assumption is no longer valid. The device may experience occasional loss of connectivity, depending on the availability of a sufficiently strong signal. It may also switch between networking methods, such as from Wi-Fi to GPRS (General Packet Radio Service), as signal strength and availability changes. In addition, some applications may be specifically designed to only download or synchronize data on demand, such as in the mornings and evenings when a travelling salesperson is within range of a corporate or home network, for example.
|Connectivity to the server will not always be available, so you must design your services and clients to support synchronization when connectivity becomes available.|
Therefore, mobile device applications must be designed in such a way that they can download or synchronize data, store it locally, and then upload local changes and resynchronize with the remote data store again at the appropriate times. This may be done automatically when a connection is available or on a predefined schedule, and take into consideration the communication costs of the different types of connections. It may be done only on demand, when the user has completed specific tasks, or it may be a mixture of the two approaches, such as uploading new sales data automatically, but synchronizing the product catalog only on demand.
In addition, some activities may not be possible, depending on the current network type. For example, if only Wi-Fi is available, the device will not be able to use the phone or SMS features. Also consider the cost of data transfer. Reducing the volume of data that you transfer over the network can considerably reduce the user's costs, especially when using the cellular phone network. Data transfer costs also vary considerably in different regions and countries of the world.
Windows Phone 7 applications take advantage of several fundamental features of the platform and the phone environment to maximize security. These include the certification of all applications that can be installed (all applications must be installed from Windows Marketplace), the use of only .NET Framework managed code, a sandbox for each application, and an execution manager that monitors resource usage and the behavior of applications.
However, when designing the data storage approach you will use, and the communication mechanism for accessing remote services, you must consider how you will secure the data. Even though the phone requires a user PIN to access it, and data in isolated storage is protected from access by other users of the phone, you should consider encrypting sensitive data that you store on the phone. In addition, unless you are accessing a public service, such as a site that exposes a list of movies currently showing at a local cinema, you must protect the data and the content of messages exchanged with the server from interception and tampering.
Therefore, when designing applications for Windows Phone 7, you should consider the following factors to maximize security:
- Use HTTPS (SSL) when connecting to services where sensitive data is exchanged. If the server certificate is not valid or trusted by a certification authority installed on the phone, the connection will be blocked (you can test a service by navigating to it using the version of Microsoft Internet Explorer® installed on the phone and the emulator). Users can add a certificate authority to the trusted authorities list in the phone, but they cannot add client Secure Sockets Layer (SSL) certificates to support client authentication by the server.
- Encrypt data that you store on the phone, and consider encrypting any particularly sensitive data that you transmit over the network—even when using SSL. Always encrypt sensitive data that you send over non-secure connections, and send only hashed versions of passwords over the network for verification on the server. You can use the AES, HMACSHA1, HMACSHA256, Rfc2898DeriveBytes, SHA1, and SHA256 algorithms on the phone.
- If your server application communicates with the Microsoft Push Notification Service (MPNS) to send notifications to the phone, consider using SSL when communicating with the MPNS server. This is possible only when you register for the full version of MPNS.
- Take advantage of the tools available for use as part of a Security Development Lifecycle (SDL). These include tools such as the Microsoft Threat Modeling Tool, FxCop, and BinScope.
If you decide that you need to store or encrypt your application's data on the phone, you must be aware of the following points:
- Windows Integrated Security Authentication is not supported on Windows Phone 7. You must implement authentication with remote services and servers using a technique such as Open Authentication (OAuth).
- The Windows Phone 7 API does not include an equivalent to the DPAPI that is available in other Windows operating systems for securing passwords and encryption keys. This means that there is no way to securely store data on a Windows Phone 7 device without requiring the user to enter a password or PIN at some point.
- If you decide to store confidential data on the server instead of on the Windows Phone 7 device, the device must authenticate with the server. This means that you must again prompt the user for a password or PIN at some point.
- You must consider the usability of your application and minimize the number of times that it prompts the user for a password or PIN to access the data. However, if you cache data on the device (including hashed data such as passwords) it may be vulnerable if the device is stolen.
- Encrypting and decrypting data will cause your application to consume more battery power.
For more information about securing Windows Phone 7 applications, see "Security for Windows Phone" at on MSDN (http://msdn.microsoft.com/en-us/library/ff402533(VS.92).aspx). For details of the cryptographic capabilities supported in Silverlight on Windows Phone 7, see "Cryptographic Services in Silverlight" on MSDN (http://msdn.microsoft.com/en-us/library/cc265159(VS.95).aspx).
|Microsoft offers a Find My Phone service (http://www.microsoft.com/windowsphone/en-us/howto/wp7/start/find-a-lost-phone.aspx) that will help locate missing phones by displaying their location and initiating a call to them, or locking and wiping the phone so that information cannot be accessed by others.|
Data Formats and Accessing Remote Services
The Microsoft vision of "three screens and the cloud" encompasses access to information and entertainment, irrespective of the type of device, the screen size, and the user's location. Applications that use data exposed by cloud services can provide a compelling user experience that is appropriate for the device the consumer is using (such as a phone, desktop computer, or large screen television), and in any fixed or mobile location. This guide focuses on consuming services exposed by cloud-based services, and in particular Windows Azure-hosted services.
|Windows Phone 7 applications can use data exposed by almost any remote service over HTTP in almost any format if you create a suitable proxy in your application.|
Windows Phone 7 applications can consume data from services implemented on any platform and operating system, using any data mechanism that exposes a suitable format and communication protocol. However, it is likely that you will aim to use standard data formats and protocols in your applications to provide decoupling and promote reuse of services. This is especially appropriate for scenarios where you expose data that may be consumed by many different types of devices.
|Windows Azure provides a scalable, reliable, and cost-effective solution for exposing data to client applications. For more information about building Windows Azure services, see the Windows Azure Guidance site on CodePlex (http://wag.codeplex.com/).|
Microsoft is evolving an end-to-end strategy for simplifying data communication between the server and mobile devices based on open standards that allow developers to target a wide range of data stores and devices. This strategy encompasses the typical requirements of receiving, sending, and synchronizing data between the server and the device. The data protocol that Microsoft is supporting as the core protocol for data transmission across the majority of its frameworks and technologies, and specifically between severs and mobile devices, is the Open Data Protocol (OData).
OData uses an HTTP verb extension named MERGE; it defines this in a way that is compliant with the protocol. Whereas the PUT verb requires all fields of a record to be specified when updating data, the MERGE verb will accept changes and use the existing values for other fields. This is beneficial because it can reduce the volume of data transmitted between the phone and the server.
|Remember that you should validate all data received during communication with a host computer and during over-the-air communication to prevent errors occurring in your application.|
Data Format and Synchronization Considerations
One way to reduce memory, storage, and communication bandwidth requirements is by choosing an appropriate format for the data and compressing the data. OData and other protocols support JSON serialization, or you can implement your own serialization for communicating and storing data. JSON serialization reduces the size of the data sent over the wire when compared to XML formats, which can reduce transmission costs. Compressing data sent between the server and the device is also a useful way to minimize data transfer costs when using slow and/or expensive network connections such as GPRS or 3G (when compared to cheaper and faster Wi-Fi connection).
However, serialization—particularly for the compressed JSON format and XML format—consumes processor resources. You must balance the communication cost and the processor load factors when you choose a protocol or data format.
|The Microsoft OData Client Library (beta) for Windows Phone 7 does not support JSON serialization. You must use the Atom Pub format with this proxy component.|
In addition to simply retrieving and uploading data, mobile devices often have a requirement to perform synchronization between data stored on the device and data stored on the server.
Synchronization must take into account occasional connectivity with the network, transmission errors, conflicts between the two data stores due to concurrent updates, and the correct application of keys and relationships between relational data rows on the database server. Synchronization is also often required between types of data that are not relational in nature. This may include log files, media files, or other types of information.
|Data synchronization is an important requirement in many mobile applications that use data exposed by a remote service. Consider whether you can simplify your synchronization requirements to avoid the additional complexity it can add to your design.|
However, before you decide to implement synchronization, consider whether the additional effort it requires can be avoided by applying a simpler pattern. In particular, bi-directional synchronization can be difficult to implement. You may decide to use the Ledger design pattern where, when a conflict occurs, the server or the client version overrides conflict, the content is duplicated, or the user specifies values to resolve the conflict. Alternatively, you may decide to implement synchronization tokens to simplify your design. For information about patterns for moving and synchronizing data, see "Data Patterns" on MSDN (http://msdn.microsoft.com/en-us/library/ff648502.aspx).
Alternatively, consider using a framework that implements synchronization if a suitable one is available. An example is the Microsoft Sync Framework, which is described in the following section.
Microsoft Data and Synchronization Technologies for Windows Phone 7
Microsoft provides a range of technologies for exposing data in standard formats. Typically, on the Windows platform, you will expose data through a SOAP-based or a REST-based service; using a technology such as Windows Communication Foundation (WCF) to implement SOAP-based services or a framework such as WCF Data Services for REST-based services. Frameworks such as WCF Data Services and WCF RIA (Rich Internet Application) Services can expose data in the OData, Atom, Atom Pub, and JSON formats, and support a full REST-based service interface for updating, deleting, and adding new data to the server-based store. Other server frameworks for Windows and other platforms can do the same.
|For information about the OData SDKs and providers that are currently available, see the Open Data Protocol website (http://www.odata.org/developers/odata-sdk) and the post, "OData interoperability with .NET, Java, PHP, iPhone and more," on the Interoperability @ Microsoft blog (http://blogs.msdn.com/b/interoperability/archive/2010/03/16/odata-interoperability-with-net-java-php-iphone-and-more.aspx).|
Mobile devices can also communicate directly with SQL Azure™ databases, although this requires use of an ADO.NET provider that understands the tabular data stream (TDS) protocol. It also requires more effort on the client side to write the data access code because the ADO.NET SQL client libraries are not available on the phone, and offers no opportunity to include server-based business logic outside of the database operations. However, it may be a useful technique in some application scenarios.
|The implementation of Silverlight on Windows Phone 7 does not directly support all the networking features of Silverlight 4.0 and the Silverlight 4.0 SDK. For more information, see "Networking for Windows Phone" on MSDN (http://msdn.microsoft.com/en-us/library/ff637320(VS.96).aspx).|
Built on top of OData is the OData Sync protocol. This protocol is specifically designed to make synchronizing data across networks much simpler by using pluggable providers for each type of data store or device. A central orchestration component managed by the application configures endpoints and controls the transfer of data changes between the endpoints.
To support the OData and OData Sync protocols, Microsoft and many third-party companies offer frameworks, providers, connectors, proxies, and other components that run both on Windows and other platforms. Figure 4 shows a high-level overview of the data communication and synchronization mechanisms build around the OData and OData Sync protocols.
|For more information about the Microsoft Sync Framework, see Appendix E, "Microsoft Sync Framework and Windows Phone 7."|
Resource Management and Performance
Like all mobile devices, Windows Phone 7 devices have limited processing, memory, and storage facilities compared to a desktop or laptop computer. It is important to take this into account when building applications that will run on Windows Phone 7.
|Failing to use the resources of the phone intelligently can considerably reduce the performance of your application|
The main areas of concern when designing mobile device applications are to manage device resource usage effectively and maximize performance on the device. Typically, maximizing performance involves optimizing memory utilization, maximizing use of the graphics processing unit (GPU), and more general issues, such as good programming practice. The following sections provide guidance on achieving these aims in your applications.
Minimize Device Resource Usage
Many hardware features of the device draw additional current and reduce battery life. You should consider limiting use of these features when not necessary. For example, you should access the location service (which may initiate the built-in GPS) only when necessary, and turn it off when not required. Consider implementing options or power profiles in your applications that allow the user to minimize power use or turn off features of the device when not required.
|Look at the recommendations earlier in this chapter for minimizing performance impact when communicating and storing data.|
Also consider how you can minimize the use of the network, Bluetooth, storage, video, sound, and background tasks. All of these require processor and memory resources, and they impose an additional load on the battery. For information about using the device capabilities, such as location services, and minimizing their impact on performance, see Appendix C, "Leveraging Device Capabilities."
Apply Good Practice Programming Techniques
You must be aware of the work your application is doing and the use of resources within your code. Where possible, you should attempt to do the following:
- Apply the optimizations you would use in any other .NET Framework code, such as caching the appropriate types and volumes of data, avoiding boxing (which occurs when you treat a value type as an object), and using lazy loading so that memory is only allocated to objects if they are actually used by the application.
- Use asynchronous programming techniques to perform any complex processing tasks on background threads instead of on the UI thread. Use Dispatcher.BeginInvoke to initiate operations on the UI thread, and pass data between tasks on different threads using local variables, a memory buffer, or isolated storage. Also consider using the Reactive Extensions (Rx) to implement asynchronous execution for tasks. Rx can simplify asynchronous programming tasks and make code easier to read and assimilate.
- Minimize the visual tree of objects and code execution. Less activity in the application will give better performance and reduce battery drain.
- Minimize the size of objects that you redraw or animate within the UI and the number of operations (such as transitions or effects) you perform on the objects. If you use code to drive animations with per-frame callbacks, these execute on the UI thread and may appear less smooth than those on the compositor thread when the UI thread is busy.
- Ensure that media you display or play (such as video or audio) is encoded at the appropriate size for display, and that it has the minimum acceptable frame or audio bit rate.
- Minimize the processing that occurs in the Loaded event of the initial page, which will delay initial display of the application. Alternatively, consider using the splash screen (SplashScreenImage.jpg) that is included in each Windows Phone 7 project template. You can modify it to show a suitable image while the application loads.
- Test regularly on a physical device, not just by using the emulator, because the performance of the two will vary dramatically based on the hardware available to each.
Optimize Memory Usage
Your application will perform better and be a "good citizen" when running on Windows Phone 7 if you carefully control use of memory and isolated storage. You must also be aware that garbage collection in Windows Phone 7 devices works differently than it does in desktop and server versions of the .NET Framework. In Windows Phone 7, the garbage collector runs only when memory usage exceeds a specified level, and it can interrupt execution—which can, therefore, affect performance.
Where possible, you should attempt to do the following:
- Optimize data downloads and store only data that is actually required on the device.
- When accessing large sets of remote data, consider using data paging so that only the data that will be viewed is sent to the device.
- If you will reuse objects you create in your code, consider holding them in memory instead of allowing them to be garbage collected and then recreating them. This reduces the frequency of garbage collection, which can interrupt program execution to a greater extent than in a desktop application. However, do not hold onto objects that will not be regularly reused, and consider minimizing the total number of object instances that you create in order to reduce memory requirements. Using a few large objects instead of a large number of small objects can also reduce garbage collection overhead, but you must also consider whether the performance gain outweighs the benefits of smaller, more-focused and decoupled objects that follow the single responsibility principle.
- Consider creating or loading the objects and data you need when your application starts. If you minimize the requirement to allocate memory for new objects as the application runs, the garbage collector will run less often. If you use mainly value types and arrays of value types, you will minimize the time that the garbage collector takes to execute. However, you must balance the effects, depending on whether you require fast startup or faster execution after startup. Alternatively, consider downloading the data you need asynchronously on a background thread and allowing the application to start with some limit to its functionality and then gradually enable features as the data that they need becomes available. A dependency injection container can help you to manage object creation.
- Consider calling the GC.Collect method to force garbage collection when the application is at a point where there is no interaction with the user and no major tasks are running in your application. This may be immediately after initializing when the main screen is displayed or at a suitable point where the user is reading content you have displayed. This reduces the chance that it will run at a more intrusive time and affect the interactivity of your application.
- Consider simplifying the structure of your application components when using design patterns that provide decoupling (such as MVVM or Dependency Injection) if you can do so without fundamentally affecting the architecture or objectives of the patterns. For example, you may be able to share a view model between two or more views.
- Minimize the size of the application assemblies. Use a Build Action of Content (instead of Resource) for media, images, and other content to include them as files in the XAP file instead of as resources embedded within the assembly. However, if you are building a reusable component, you will probably need to embed the resources within the assembly for easier distribution.
|You can query the current memory availability and usage by your application using the DeviceExtendedProperties class in Windows Phone 7. For more information, see Appendix C of this book, "Leveraging Device Capabilities," and "Device Information for Windows Phone" on MSDN (http://msdn.microsoft.com/en-us/library/ff941122(VS.92).aspx).|
Maximize GPU Usage
Windows Phone 7 provides a background compositor thread that generates output for display and a relatively powerful GPU that maximizes performance for graphics and maintains an acceptable frame rate. However, you must take care to not negate this advantage through the use of code that cannot run on the GPU.
Where possible, you should attempt to do the following:
- Minimize the code you execute on the UI thread, which handles input, the drawing of new visual elements, and calls to user code. Use the compositor thread to execute transitions and animations, and apply caching for bitmaps. The compositor thread handles opacity, scale transforms, translate transforms, rotate transforms, and plane projection. It does not handle opacity masks, non-rectangular clips, and texture for animated objects greater than 2000 × 2000 pixels.
- Consider caching complex visual elements if they will be regularly reused. When you hide a visual element (visibility = collapsed) it is discarded and requires no processor utilization. This means that it must be completely recreated when you show that element again. Instead, consider setting the opacity to zero. This causes the device to keep the object, while still minimizing processor usage. However, you must balance this with memory usage.
- Consider using images instead of creating complex visual elements in Extensible Application Markup Language (XAML) or code. This can considerably reduce processor load. If you need transparency, you must use a PNG image. If you do not need transparency, use a JPEG image because the render speed is higher for this image format.
- Images larger than 2000 × 2000 pixels will be sampled at a lower resolution when displayed, with subsequent loss of quality. Store larger images in a WriteableBitmap and display only the appropriate section.
There are several modes you can enable when debugging. These are especially useful when maximizing graphics performance; they are automatically included in the code generated by the phone application template in Visual Studio. Graphics debug mode is set by the following properties of the Application.Current.Host.Settings class in the startup code in your App.xaml.cs file:
- EnableFrameRateCounter. This displays a frame rate counter, memory usage information, and other useful data about the performance of the device. It shows the frame rates for the UI and the compositor threads, the amount of texture memory in use, the number of surfaces, and the fill rate. Ensure that the SystemTray.IsVisible static property is set to false in your application so that the system tray does not obscure the frame rate counter.
- EnableCacheVisualization. This shows the graphics items that are being drawn by applying tint and transparency to each one to show where overlapping textures are being drawn on each frame update. Each tinted area represents a texture that is handed off to the GPU for composition.
- EnableRedrawRegions. This shows the graphical items that are being redrawn in each frame update.
For more detailed information about the background compositor thread and maximizing performance on Windows Phone 7, see Creating High Performing Silverlight Applications for Windows Phone from the Microsoft Download Center (http://download.microsoft.com/download/B/2/7/B2748D7A-F368-4C33-B0F2-844CFE085193/SilverlightForWindowsPhonePerformance.zip). For more background information about performance optimization, see the video presentation, on Windows Phone, on the Mix 10 website (http://live.visitmix.com/MIX10/Sessions/CL60) and "WP7/Silverlight Graphics Performance" on andybeaulieu.com (http://www.andybeaulieu.com/Home/tabid/67/EntryID/196/Default.aspx).
These and all links in this book are accessible from the book's online bibliography. The URL to the bibliography can be found in the preface, in the final section, entitled, "Where to Go for More Information."
Availability of Components and Frameworks
In addition to the challenges developers face in managing connectivity and limited device resources, the fact that mobile device technologies are reasonably new and continually evolving makes technology choices more difficult. Although most server technologies are stable, the Windows Phone 7 is brand new and—at the time of this writing—many of the interoperability components and technologies are still under development or available only as preview versions.
As you will see when you read in this guide about the decisions Tailspin had to make during development of their Surveys application, the selection of data communication and synchronization technologies is influenced by the availability and stability of these technologies.
For example, if you choose to use WCF Data Services to expose your data in the standard Atom Pub REST format for Windows Phone 7 devices to consume, you can use the Microsoft OData Client Library for Windows Phone 7 instead of creating a custom proxy. This library is implemented in the assembly System.Data.Services.Client.dll, but is not yet (at the time of this writing) available as a final release version for Windows Phone 7.
In addition, other frameworks or components originally designed for the desktop or server, or specifically aimed at Silverlight applications running in a web browser, may not be compatible with the Windows Phone 7 operating system. You should test all components and frameworks on both an emulator and on a physical device before committing to use them in your application designs.
- Which of the following should you consider when designing the UI for a Windows Phone 7 application?
- Making it work in both portrait and landscape mode.
- Making it colorful and highly configurable.
- Maximizing the number of controls on each page.
- Reusing an existing web or desktop application UI.
- Which of the following languages and frameworks can be used to create Windows Phone 7 applications?
- Microsoft Visual Basic®.
- Which of the following are not events that may occur as part of the tombstoning and reactivation process for a Windows Phone 7 application?
- Which of the following ways would you consider storing the data used by an application?
- Using isolated storage on the phone.
- Using the built-in SQL Server® Compact Edition database on the phone.
- Using the file system on the phone.
- Storing it on the server and synchronizing it with the phone.
- Which of the following techniques should you consider for securing a Windows Phone 7 application?
- Never store any data on the phone.
- Encrypt all sensitive data stored on the phone.
- Use HTTPS for all requests containing sensitive data when communicating with the server.
- Perform a security analysis of your design and the code.
- Which of the following are useful techniques to maximize performance of a Windows Phone 7 application?
- Turn off features such as the Location Service if you do not require them, or turn them off as soon as possible after using them.
- Use single-letter names for variables in your code.
- Optimize your code using good coding practice and simplifications where appropriate.
- Make full use of the graphics processing unit (GPU) by avoiding code that cannot run on it.