Design Windows Store apps - Exam Ref 70-484: Essentials of Developing Windows Store Apps Using C# (2013)

Exam Ref 70-484: Essentials of Developing Windows Store Apps Using C# (2013)

Chapter 1. Design Windows Store apps

The launch of Windows 8 was accompanied with the introduction of Windows Runtime (WinRT), a new framework for building touch-friendly user interfaces (UIs) for Windows Store applications (apps). With WinRT, Windows Presentation Foundation (WPF) and Silverlight developers could leverage their existing XAML and C#/VB.NET skills to build Windows Store apps. In addition to the new framework and an accompanying toolset, Microsoft introduced a new design language called “Microsoft design style.”

The conceptual design of an application is the first stage of designing an application. In the conceptual design, you focus on a set of ideas and concepts about what your app should do, how it will behave when users interact with it, and what it should look like. A well-designed application has logical layers loosely coupled with a UI, which is used for presenting the data. Separating logic from presentation enables the application to be enhanced or updated without changing the conceptual design.

You can use design patterns such as Model-View-ViewModel (MVVM) to develop maintainable and extensible applications. Data and state preservation across various states of an application is important in providing a great user experience. After you build and test your application, you need to prepare the app for Windows Store certification. Microsoft provides a set of requirements to help you during the app certification process and deployment in the Windows Store.

Objectives in this chapter:

§ Objective 1.1: Design the UI layout and structure

§ Objective 1.2: Design for separation of concerns (SOC)

§ Objective 1.3: Apply the MVVM pattern to your app design

§ Objective 1.4: Design and implement Process Lifetime Management (PLM)

§ Objective 1.5: Plan for an app deployment

Objective 1.1: Design the UI layout and structure

The primary form of interaction with a Windows Store app by its users is through the user interface (UI). Microsoft design style consists of a set of principles that provide a consistent, elegant, and compelling user experience in Windows Store apps. You should plan and design Windows Store app UIs with these principles as a reference. The UI should be composed of visual elements and controls, with a clear hierarchy in their layout. You should also consider users with disabilities and preferences, and design your app for accessibility. Reusing UI code in multiple applications will help you to rapidly build Windows Store apps; therefore, you should consider building custom controls and using them in your apps.

NOTE

This objective covers how to:

§ Evaluate the conceptual design and decide how the UI will be composed

§ Design for the inheritance and re-use of visual elements

§ Design for accessibility

§ Decide when custom controls are needed

Evaluating the conceptual design and deciding how the UI will be composed

Windows Store apps provide Windows 8 users with a unique way of interacting with their PCs and devices. The apps are unique in their design and functionality; they share a set of important characteristics that are fundamental in their design. To design a compelling user experience in your app with an attractive user interface, it is important to plan your app well. Microsoft provides Windows Store app developers with a set of guidelines to help them in planning their app. The steps you should follow to plan and design your Windows Store app are described in the following sections.

Decide which features will make your app great

You might have an idea to create a blog reader or a weather app. When you check the Windows Store, you might find several dozen such apps, but none of them satisfies your needs. Although some apps may be simple to use, they are perhaps lacking in fundamental features such as sharing data with friends. You need to determine which features you think will make your app great and make it stand out from the rest of the apps in the Windows Store. Then, because it’s sometimes difficult to incorporate every feature you want in the first release of your app, prepare a list of must-have features for the first release. Your focus should be on your users and the scenarios in which they will use your app.

Assess user scenarios

Users will interact with your app in a variety of ways and you need to anticipate as many of them as possible. For example, in the case of a blog reader app, users might open the app if they see an interesting post when it appears in the app’s tile. This is one scenario you need to include when assessing the various scenarios your app will support. Then you visualize them by using sketches, prototypes, and storyboards. Remember that your app needs to perform well for such scenarios, and your design should accommodate any necessary requirements. You might prioritize these scenarios and implement only a few of them in the first release of your application, adding other scenarios in future updates.

Decide on your app’s features

After you decide on a set of scenarios to implement in your app, explore the Windows platform and investigate features to associate with your app’s needs. To provide users with the best experience while using your app, follow the User Experience (UX) guidelines for each feature.

§ Use the right contracts in your app. Contracts are agreements between apps that enable your app to interact with other apps. Complex interactions such as sharing content from within your app with your friends or searching with your app are easier to implement with contracts. If your app is a source of media, the Play To contract enables your app to stream media to devices such as televisions.

§ Touch-first design. Windows 8 has promoted touch and gestures as the primary form of interaction with Windows Store apps, leaving the keyboard and mouse as alternative methods of interaction. Therefore, you should consider using touch interactions, such as rotate, pan, swipe, cross-slide and others, to provide a more visual and informative way to interact with content in your app.

§ Engaging experience. Animations, toast notifications, live tiles, and secondary tiles can help users feel deeply immersed and engaged with your app.

§ Use device capabilities whenever possible. Modern devices have proximity sensors, cameras, accelerometers, and geolocation capabilities that you should consider using in your app.

MORE INFO USER EXPERIENCE (UX) GUIDELINES

See http://msdn.microsoft.com/en-US/library/windows/apps/hh465424 for more information on UX guidelines.

Design a great user interface for your app

After you establish the features you want to implement in your app, you should start working on the fundamentals of designing the UI. Remember that the UI is the main gateway to your app, enabling users to be immersed and engaged with your app’s features. Microsoft design style provides designers and developers with a set of simple principles to follow while designing the UI of Windows Store apps:

§ Showcase your content. You should strive to adapt a clean and open layout. Minimize distractions by removing unnecessary lines, boxes, blurs, and gradients; and use open space to frame your app’s content. Remember to put “content over chrome.” You should provide a clear and simple information hierarchy in your app with an emphasis on typography. Remember to support landscape, portrait, snapped, and fill views. Your app should look and work appropriately in any of these views.

§ Interact with content. Whenever possible, let your users interact with your app’s content directly, without using controls such as tabs for navigation and buttons for actions. Use Semantic Zoom and the app bar instead. Show commands contextually and use charms, which are shown on demand.

§ Be fast and fluid in actions. Using touch as the primary form of interaction with app content, design the UI to use gestures such as swipe, pinch-and-zoom, and so on. Provide visual feedback using animations and notifications whenever possible. Design for accessibility as well as for mouse and keyboard actions. Use built-in controls and their touch-optimized behaviors in your UI design. Note that built-in controls are accessible by default, so they lower the challenges and cost in building an accessible app.

§ Snap and scale beautifully. Your app will be downloaded and installed in devices and PCs with a variety of resolutions and form factors. Using the Microsoft Visual Studio simulator, test how your app looks and behaves on different form factors. The platform provides automatic scaling based on screen size and resolution. Use Scalable Vector Graphics (SVG) and three resolutions of your app’s assets to provide a crisp and polished UI to support screens with various pixel densities.

§ Make your app feel alive. The app tile is the entrance to your application. The app tile can be updated with fresh content regularly, which will draw the attention of the user. Time-sensitive notifications delivered in a live tile enable the user who opts in to receive them a way to feel engaged with your app. Secondary tiles help people bookmark interesting content from your application.

Designing the UI of a Windows Store app can be challenging. You should refer to the design guidelines provided by Microsoft to help you design your app. The guidelines can help you choose the app’s navigation pattern, which commands to use for common interactions such as copy and paste, how to include app branding, as well as how to create a great user experience. In the conceptual design stage, it is useful to create a prototype of the UI. The prototype can be used to validate your app’s design against the design guidelines.

MORE INFO DESIGN GUIDANCE FOR WINDOWS STORE APPS

Microsoft provides designers and developers with a set of design guidelines for Windows Store apps, which are available at http://msdn.microsoft.com/en-us/library/windows/apps/hh770552.aspx.

Designing for the inheritance and reuse of visual elements

The Extensible Application Markup Language (XAML) platform in Windows 8 enables developers to customize controls that ship with the WinRT framework through styles, templates, and visual states. Existing controls retain their functionality when customized; however, their rendered appearance can change, and new properties and methods can be added. This helps you reuse controls within your Windows Store app.

In your app, you can add input validation to a text box or add autocomplete support. The following example shows how to create a control by customizing the TextBox class:

Sample of C# code

using Windows.UI.Xaml.Controls;

namespace ContosoApp

{

public class ExtendedTextBox : TextBox

{

// Implement your customization here

}

}

Instead of extending a control, you might need to customize its visual appearance to meet the requirements of your application. Restyling a control in XAML is similar to using Cascading Style Sheets (CSS) with HTML pages. Styles are used to update the appearance of standard XAML controls. A style is represented by the Windows.UI.Xaml.Style class. A style is used to group together property values you would set individually. The style could then be used on multiple elements in the same page as well as different pages. Styles are declared in resources, in most cases. A style uses a collection of setters to set the target properties of the element. A setter uses a key and sets a value for the key. The following is a sample style for the TextBlock UI element:

Sample of XAML code

<Style x:Key="TextBlockHeaderStyle" TargetType="TextBlock">

<Setter Property="Foreground" Value="White" />

<Setter Property="FontSize" Value="44" />

<Setter Property="TextTrimming" Value="WordEllipsis" />

<Setter Property="TextWrapping" Value="Wrap" />

</Style>

Styles can be extended through inheritance, which avoids code duplication and (often) mistakes. You can extend a style and override setters in the parent style as follows:

<Style x:Key="TextBlockSubheaderStyle" TargetType="TextBlock"

BasedOn="{StaticResource TextBlockHeaderStyle}">

<!-- Extending a style -->

<Setter Property="FontStyle" Value="Italic" />

<!-- Overriding a setter in the parent style -->

<Setter Property="FontSize" Value="32" />

</Style>

Note that the parent style is referred as a StaticResource in the extended style. To apply these styles on any text block in an app, their keys are explicitly used to refer them. Such styles are called explicit styles.

Some styles can affect UI elements even if they are not explicitly applied on them. Such styles are called implicit styles. They are automatically applied to any instance of a type they are targeted for within the scope of the style. Here is an example of an implicit style:

<Style TargetType="Button">

<Setter Property="Background" Value="Red" />

</Style>

UI elements defined in XAML can contain a collection of resources used by themselves and their children. Resources are dictionaries that contain reusable values, and each value is provided with a unique key that is used to reference the value.

A resource is declared either at the app level, at the page level, or at a specific UI element—it cannot be declared multiple times in your application. This is because a resource is considered a visual element, and a visual element can be declared only once. Resources are generally reused; therefore, declaring them multiple times will result in an error. If a resource is declared at the app level, it can be used anywhere within the app. If it is declared in a page, it can be used only by the UI elements declared in the page. A resource can be scoped to a UI element, in which case it is available for use within the element by its children.

You can group all the resources you want to share across multiple pages in your application in a resource dictionary. One or more resource dictionaries declared in their own files are included in the App.xaml file, as follows:

<Application.Resources>

<ResourceDictionary>

<ResourceDictionary.MergedDictionaries>

<ResourceDictionary Source="Common/StandardStyles.xaml" />

<ResourceDictionary Source="Common/ControlStyles.xaml" />

</ResourceDictionary.MergedDictionaries>

</ResourceDictionary>

</Application.Resources>

Designing for accessibility

When designing your Windows Store app, you should consider app accessibility to serve various scenarios. This ensures that your application is usable by people with disabilities or other limitations such as mobility, vision, color perception, hearing, speech, cognition, and literacy, which might prevent them from using conventional UIs. Legal requirements might make it mandatory for your application to implement an accessible interface.

To implement accessibility in the design of your Windows Store app, you should follow these guidelines:

§ Screen reading. You can expose information such as name, role, and description about the visual elements in your UI. This helps blind or visually impaired users understand and access all UI elements and invoke available functionality.

§ Keyboard accessibility. Many users prefer to use the Tab key on the keyboard to navigate and use the UI, such as moving the focus on visual elements, and navigating through grids and lists. Users might also prefer to activate functionality using the Enter or Space key and common shortcuts such as Ctrl+P to print content.

§ Accessible visual experience. Visually impaired users require sufficient contrast in the UI. You should use high-contrast themes to accommodate such requirements. You should also consider colorblind users when using colors to convey information through the UI of your application. The Windows Store requires visually accessible UIs to have a minimum text contrast ratio of 4.5:1 against the background.

Consider providing options for your users to select themes that suit their preferences, adjust the font size and color, and adjust the dots per inch (dpi) setting. You can also allow users to select alternative controls and turn off nonessential elements and animations. Keep in mind the Narrator, Magnifier, and Touch Keyboard accessibility features that enable users to interact more comfortably with apps. If you use a custom control in your app, you should provide basic accessibility information for the control. You need to ensure that the control is fully accessible by keyboard, and that the UI meets requirements for visual accessibility.

The Microsoft UI Automation framework is an accessibility framework for Windows. It is integrated within the base classes and the built-in behavior of UI control classes in Windows Store apps built with C#, C++, and Visual Basic. The Windows Store app is treated as a top-level window by UI Automation, and all the content within the app window is reported to and available to a UI Automation client. This enables UI Automation to obtain information about the UI and send input to controls. For example, UI Automation enables screen readers to provide information about the UI to the users, and enables users to manipulate the UI through ways other than standard input.

Before you submit your application to the Windows Store, you should test your app for accessibility. A good test for keyboard accessibility is to disconnect the mouse from your PC and test your app with only the keyboard. You should be able to cycle through all UI elements by using the Tab key. Composite UI elements should be navigable with the arrow keys. You should ensure that interactive UI elements can be invoked by pressing the Enter or Space key. You should also verify that your app uses the contrast ratio properly, and that when a high-contrast theme is used, all the UI elements display correctly. Users can turn on the Make everything on your screen bigger setting in PC Settings, Ease of Access. In such a case, you should ensure that all the controls in the UI are accessible, all text is visible, and no UI elements overlap.

The screen reading experience of your application’s UI can be tested using Narrator. You can start Narrator while your app is running by pressing the Windows logo key and Enter button. Narrator automatically enters touch mode on devices that support more than four contacts. You can navigate through your UI by using single finger flick gestures, a three-finger swipe to the right or left to navigate like using Tab and Shift+Tab, and a three-finger swipe up to read the contents of the entire windows. To have Narrator read items under your finger, drag a single finger up and down or left and right.

The Windows Software Development Kit (SDK) for Windows 8 provides accessibility tools such as Inspect and UI Accessibility Checker to help you test your app for accessibility. Inspect enables you to select any UI element and view the element’s accessibility data. Figure 1-1 shows the Inspect tool being used to check an element’s accessibility information.

A screenshot of the Inspect UI accessibility test tool that you can use to select any UI element and view its accessibility data.

Figure 1-1. The Inspect UI accessibility test tool

The UI Accessibility Checker helps you identify problems with your UI at runtime. When you finish developing the UI of your app, use the UI Accessibility Checker to test various usage scenarios, verify that the runtime accessibility information is correct, and find any issues. Figure 1-2shows the UI Accessibility Checker being set up to test the accessibility information in an app.

A screenshot of the Verifications tab in the UI Accessibility Checker test tool. You can select from several options. The selected option is Choose Window: Hover with the Mouse then Press Ctrl+Shift+[.

Figure 1-2. The UI Accessibility Checker test tool

After you have implemented an accessible design for your app, you can mark your app as accessible in the Windows Store, which makes it easier for users with disabilities to discover your app. Windows Store provides an Accessible filter to let users search for apps that have an accessible UI. When you declare your app as accessible, the Accessible tag is added to the description of your app.

MORE INFO MAKING YOUR APP ACCESSIBLE

Read more about accessibility in Windows Store apps at http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh452678.aspx.

EXAM TIP

Although you are not expected to explain how a particular tool used for testing accessibility works, it is important to know the various ways of testing accessibility in a Windows Store app.

Deciding when custom controls are needed

Custom controls provide you with an option to create UI elements with a unique appearance that are often reusable across multiple apps. As a Windows Store app developer, you might consider building a user control or customize a control such as GridView using a template to extend its visual design. Therefore, you need to consider one of three options when building a control:

§ Custom control

§ User control

§ Create a template and apply it to control element

In most cases, you will create a user control in the application where you will use it and add other control elements to it. For example, you might need a watermarked TextBox control at multiple places in your app, but you are not sure whether you will need this control in other apps that you build. Therefore, it is best to create a user control in your application project itself. Visual Studio provides developers with a template to create a user control, as shown in Figure 1-3.

A screenshot of the Add New Item dialog. The User Control item is selected from a list.

Figure 1-3. Creating a user control with Visual Studio

When you add a new user control to your project, an XAML file is added to your project along with a C# code-behind file. The visual representation of the user control is defined in the XAML, and the code-behind file is used to implement the functionality of the control.

A custom control is a reusable UI component you can use in multiple Windows Store projects. You can restyle and re-template a custom control as needed, and package it into its own assembly that can be distributed as a Nuget package, for example. Using custom controls enables the flexibility to create a new visual element with custom code that implements various features of the element. Custom controls are derived from either core controls such as Button or control primitives such as Control and Panel.

In Visual Studio, you can add a custom control to your project by using the Templated Control item template in the Add New Item dialog box. This will create an XAML file—themes\generic.xaml—and a class file. The XAML file contains the default styles and templates for your custom control. The location of Generic.xaml is important because the XAML framework loads your custom control automatically.

You are expected to implement your control logic in the class file. You must set the DefaultStyleKey to the Type of your control in the constructor of the class; this tells the framework which style and template to apply to this Type when it is used in your application. A custom control is used in a way similar to how you use a user control: You declare a namespace and put it in the XAML wherever you need it.

THOUGHT EXPERIMENT

Designing a Windows Store app

In this thought experiment, apply what you’ve learned about this objective. You can find answers to these questions in the “Answers” section at the end of this chapter.

You are implementing a Windows Store app for a popular bistro. The bistro owners want the app to be easy to use by physically impaired users, and they want the app rebranded if they choose to use a variant of the app for their other restaurant businesses.

Use the knowledge you have gained in this objective to select some features that can be used to make the app easy to rebrand and be accessible to all users.

Objective summary

§ Evaluate the conceptual design of your application with an emphasis on how users will use your app.

§ Compose the UI so it showcases content in your app.

§ Use styles and resources to design the UI so that visual elements can be reused within your app.

§ Consider users with disabilities and impairments when designing and building the UI of your app.

§ Consider using custom controls whenever you find a need to reuse components across multiple Windows Store apps.

Objective review

Answer the following questions to test your knowledge of the information in this objective. You can find the answers to these questions and explanations of why each answer choice is correct or incorrect in the “Answers” section at the end of this chapter.

1. You have been asked to implement the UI of a Windows Store app. The application requirements make it essential for the app to be fast and fluid, and provide visual feedback to users for their actions at the same time. The designer of the user interface has recommended using animations. How should you implement animations while ensuring app requirements are met?

a. Convince the designer that animations will make the UI complex and unintuitive.

b. Use animations in the controls provided by the platform and in the animation library.

c. Implement your own animations and add them to the UI.

d. Build custom controls and add animations in them. Use these custom controls to build the UI.

2. You have created an application that aggregates news feeds from multiple sources. You have been asked to ensure your application is accessible by users with disabilities and visual impairments. Which tests should be carried out to ensure the app is accessible? (Choose all that apply.)

a. Run the Inspect tool on your application.

b. Run the UI Accessibility Checker on your application.

c. Let the Windows Store run all the relevant tests on accessibility.

d. Test your app with only the keyboard.

e. Install and test your app on as many PCs and devices as possible.

3. Your organization produces a number of Windows Store apps every year. Designers and developers are located in separate geographical locations. They have to collaborate on a number of apps for a particular client, ensuring that branding in the apps is consistent and that functionality, such as authentication, is uniform across all apps. As the lead developer, what are your recommendations to ensure consistency in the design and functionality of the apps for the client? (Choose all that apply.)

a. There should be only one project shared between designers and developers. Code in this project can be modified based on the applications’ requirements for the UI.

b. Wherever possible, visual elements specific to the brand should be implemented in styles that are defined in resources in the app level.

c. Components with similar functionality should be developed as custom controls. These controls should be used in the apps.

d. There is no easy way to share code within apps and between designers and developers. No recommendations can be made.

e. Use UX design resources provided by Microsoft for creating the conceptual design of the app.

Objective 1.2: Design for separation of concerns (SOC)

Separation of concerns (SOC) is a concept in software design and development that helps to remove dependencies between various parts of an application, allowing for maintainability and testability of the application. SOC involves planning the logical layers of your solution and designing them to be loosely coupled with interfaces. The implementation of any layer is independent of the implementation of others, allowing for loose coupling between them. It is often useful to develop layers of a solution as WinRT components called Windows Metadata (WinMD) components so that they can be used to develop Windows Store apps with C#, Visual Basic, C++, or JavaScript.

NOTE

This objective covers how to:

§ Plan the logical layers of your solution to meet app requirements

§ Design loosely coupled layers

§ Incorporate WinMD components

Planning the logical layers of your solution to meet app requirements

You should design a Windows Store app with maintainability and extensibility in mind. After you finalize the conceptual design of your app, the next step is to plan the logical layers based on your app’s requirements. Traditional software applications employ logical grouping of components into separate layers that communicate with each other and with other applications. Layers can be considered as logical divisions of components and functionality; they do not take into account physical location of components. Layers help to identify different kinds of tasks performed by components, thereby making it easier to create a design that supports the reuse of components.

In a logical layered design, a set of components performing similar tasks is grouped into a layer. Identifying logical layers in a design supports reusability of components as well as maintainability of your application. Figure 1-4 shows the architectural view of a logical layered system.

A diagram illustrating the logical layers of a solution. The Users box is on the top left, with a three-layer architecture below it that includes Presentation Layer, Business Layer, and Data Layer. The Other Apps box is on the top right with Presentation Layer below it and a dashed line connecting Presentation Layer to Business Layer on the left. Two-way arrows connect the Data Layer box to boxes below it: Data Sources and Web Services.

Figure 1-4. Logical layers of a solution

The three-layer architecture shown in Figure 1-4 consists of the following:

§ Presentation layer. This layer is the UI of your application and is responsible for your application’s layout and formatting. You will use XAML with core controls, user controls, and custom controls to implement this layer.

§ Business layer. This layer is where you implement your application’s core logic or business logic, and your application’s business rules. Other Windows Store apps interact with your application via this layer. For example, the business layer can use contracts provided by Windows for integration with the platform and other apps to share data.

§ Data layer. This layer provides the data repository required by the business layer of your application for storage and retrieval of data. It defines the interface used by the business layer for accessing a database, local settings, or remote web services.

These layers might be located in the same physical tier or they might be separated by physical boundaries. You should consider these layers as loosely coupled, with clearly defined interfaces that aid in the interaction between the layers. Loose coupling between the layers ensures your solution is maintainable and extensible, and is robust to any changes in implementation required in future updates. In addition, loose coupling helps with testing the different layers of a solution independent of each other.

Designing loosely coupled layers

When you design the layers of your solution, you should start by focusing on identifying and grouping functionality into layers. At the same time, you should identify the interfaces that help in the interaction between the various layers. After you define the layers and interfaces of your solution, you must consider how your solution will be deployed. At the final stage, you should choose the communication mechanism between various layers of your solution.

While designing loosely coupled layers for a solution, you should have a clear plan to group related functionalities into layers. Having too many layers adds to the complexity of the design, whereas having too few layers affects maintainability and extensibility. You should find a balance between reusability and loose coupling, and consider their impact on performance and complexity.

IMPORTANT BENEFITS OF A LOOSELY COUPLED DESIGN

In general, the benefits of a loosely coupled design outweigh any degradation of performance of your solution.

You must define rules for the various layers to interact with each other. This helps eliminate dependencies and circular references among the layers. A common rule is to allow only one-way interaction between the presentation and business layers, thereby enforcing a strict separation of concerns. You can use events to notify other layers of any changes in a layer, avoiding dependencies between the layers.

After you have defined the layers of your solution, you should identify the functionality that spans across layers. Logging, caching of data, data validation, authentication, and authorization are some crosscutting concerns that require implementation in separate components. Functionality implemented in such components must be available across multiple layers; therefore, you should ensure these components are available across different physical tiers.

When you define the interface between various layers of your solution, your aim should be to enforce loose coupling between layers. This means that a layer in the solution must not expose its internal implementation to any other layer. A public interface that hides the details of implementation of the layer should be sufficient for other layers to communicate with it.

Communication between various layers of your solution should consider how your solution is deployed. If all the layers of your solution reside in one physical tier, you should choose the communication protocol between the layers accordingly. If your solution interacts with remote web services for data or application logic, you should consider implementing security and encryption in the interfaces that are involved in such communication.

EXAM TIP

You should be comfortable with designing your application and implementing requirements in the various layers. You should understand the primary function of each layer and where a particular requirement can be implemented in an app.

Incorporating WinMD components

The WinRT platform provides developers with a new way to build reusable software components—as WinRT types packaged in a WinRT component, also called a WinMD component. In traditional .NET application development, you could create a dynamic-link library (DLL) as a managed class library and use it in one or more applications. This option is still available in Visual Studio. However, you can change the output type of a library project from class library to WinRT component, and the output of such a project is a WinMD file. The main difference between the two types of libraries is that a class library can be accessed only from (managed) C# and Visual Basic applications. A WinRT component can be additionally accessed from Windows Store apps developed with C++ and JavaScript. Thus, a WinRT component allows for language-agnostic software development for Windows Store apps.

WinRT imposes some restrictions on the design and implementation of a WinMD component. For example, public classes must be sealed, public fields are not allowed, and public data members must be declared as properties. In addition, there are restrictions on the data types passed from within the WinMD component to applications that use the component. You can only pass WinRT-compatible data types when returning values from methods defined in a WinMD component to a consuming application.

You might want to develop a WinMD component in C++ to get the performance advantage of C++ in complex and computationally intensive operations such as image processing and transformations. Legacy code written in C++ can be reused in Windows Store apps by using it in a WinMD component. A WinMD component developed in C++ must have at least one activatable or ref class, a class that can be instantiated from any other language such as C#, Visual Basic, or JavaScript. It can contain more than one activatable class as well as other internal classes implementing the functionality per the application’s requirements. An activatable class must be declared as public ref class sealed. If you choose not to expose a C++ type or a class that is not sealed, you should use the [WebHostHidden] attribute to prevent it from being exposed to consuming JavaScript applications. Note that an activatable class name and namespace name must not contain Unicode characters.

When you call methods implemented in a WinMD component developed in C++ in a JavaScript Windows Store app, you must use camel case in your JavaScript code. For example, for a method CalculateAverageOfNumbers implemented in a WinMD component, you will invoke it ascalculateAverageOfNumbers in JavaScript. When you reference C++ namespaces and classes in JavaScript, you should use the same casing as in the C++ implementation. C# and Visual Basic follow their normal casing rules. The following code shows a C++ class definition in a WinMD component and how it is used in JavaScript and C#:

Sample of C++ code

// ref class definition in C++

public ref class Multiplier sealed

{

// Class members

public:

double MultiplyAndAdd(double inputA, double inputB)

{

return (input A + inputB + (inputA * inputB));

}

};

Sample of JavaScript code

// Create an instance of the WinMD class and invoke the method

var nativeObject = new CppComponent.Multiplier();

var result = nativeObject.multiplyAndAdd(22.2, 30.1););

Sample of C# code

// Create an instance of the WinMD class and invoke the method

var nativeObject = new CppComponent.Multiplier();

var result = nativeObject.MultiplyAndAdd(22.2, 30.1);

If you are creating a component that is meant for use in Windows Store apps developed with Visual Basic or C#, and the component does not contain Windows Store controls, you should consider developing your component as a class library instead of a WinMD component because the former has fewer restrictions.

When you create a WinMD component in C#, you can return a managed type created in managed code to JavaScript in a way similar to the corresponding WinRT type. Note that when a managed type implements multiple interfaces, JavaScript uses the interface that appears first in the list.

You can declare events by using the event pattern provided in the Microsoft .NET Framework or other patterns available in WinRT. You can implement an event handler in a C# WinMD component by using the System.EventHandler<TEventArgs> delegate and the WinRT EventHandler<T>delegate. If you declare custom event accessors, you must use the WinRT event pattern.

MORE INFO MAPPINGS BETWEEN .NET FRAMEWORK AND WINRT TYPES, AND WINRT EVENT PATTERNS

A table of .NET Framework mappings of WinRT types is available at http://msdn.microsoft.com/en-us/library/windows/apps/hh995050.aspx. You can read more about the WinRT event pattern at http://msdn.microsoft.com/en-us/library/windows/apps/hh972883.aspx.

THOUGHT EXPERIMENT

Creating a Windows Store app from an existing desktop app

In this thought experiment, apply what you’ve learned about this objective. You can find answers to these questions in the “Answers” section at the end of this chapter.

A popular media publishing company has developed a desktop application that uses a number of C++ components. These components use proprietary algorithms that will need significant amounts of time and effort to re-implement in a Windows Store app.

What are your recommendations for the organization interested in building a Windows Store app and make it available for consumers?

Objective summary

§ Plan the logical layers of your solution with maintainability and extensibility of your app in mind.

§ Loosely coupled layers in a solution ensure flexibility of your solution to adapt to any change of requirements over time.

§ Consider incorporating WinMD components in your solution to harness the power of platform-specific features.

Objective review

Answer the following questions to test your knowledge of the information in this objective. You can find the answers to these questions and explanations of why each answer choice is correct or incorrect in the “Answers” section at the end of this chapter.

1. You have been asked to recommend an option for implementing logging in your app. The logging component should log events in an Extensible Markup Language (XML) file that resides in the local data store of the app and periodically uploads it to a remote web service. It should log events from the business layer as well as the data layer. Where should you implement the logging mechanism?

a. Business layer

b. Data layer

c. Presentation layer

d. As a separate component to maximize reuse

2. One of the requirements of the app you are implementing is to support contracts provided by the platform to exchange data between your app and the platform as well as with other apps. In which logical layer of your solution should you implement this feature?

a. Presentation layer

b. Data layer

c. Business layer

d. Application manifest

3. You have been given software that performs bit-rate manipulation of audio streams recorded using a microphone. The software is complex and is written in C++. Your organization does not have the budget to have the software rewritten for a Windows Store app. What are your recommendations for the conceptual design of a Windows Store app that does bit-rate manipulation? (Choose all that apply.)

a. Develop a WinMD component in C++ incorporating the existing software.

b. Develop a Windows Store app and use the C++/WinMD component for bit-rate manipulation.

c. Such an application is impossible to build unless the C++ component is rewritten in C#.

d. Use WinRT APIs (application programming interfaces) to implement the bit-rate manipulation algorithm.

e. Use the existing test procedures for the C++ component to test the C++/WinMD component.

Objective 1.3: Apply the MVVM pattern to your app design

It is challenging to develop the UI of a modern application while considering code and visual element reuse, separation of concerns, and maintainability. UI design patterns are reusable solutions that can help developers build UIs. You can use the MVVM design pattern to develop Windows Store apps that are maintainable, testable, and extensible.

NOTE

This objective covers how to:

§ Design and implement the appropriate data model to support business entities

§ Design your viewmodel to support your view based on your model

§ Develop a view to meet data-binding requirements

§ Create viewmodels using INotifyPropertyChanged, ObservableCollection, and CollectionViewSource

Designing and implementing the appropriate data model to support business entities

The data model in a Windows Store app implements the business logic and the mechanism for data access. It is responsible for notifying the viewmodel whenever data changes in the source and for persisting changes from the view in the data source. The model of the MVVM pattern is where the data model for the application is implemented.

Model-View-ViewModel pattern

The Model-View-ViewModel (MVVM) design pattern was introduced by John Gossman in 2005 as a variation of the popular Model-View-Controller (MVC) design pattern. The MVVM pattern helps you build your application with a clean separation of the business and presentation logic from the UI. It provides opportunities for code reuse, and encourages developers and UI designers to collaborate on developing various parts of the application.

MORE INFO MODEL-VIEW-VIEWMODEL PATTERN

For an introduction to the Model-View-ViewModel pattern for building WPF apps, go to http://blogs.msdn.com/b/johngossman/archive/2005/10/08/478683.aspx.

With the MVVM pattern, you can compose the design of your application using three loosely coupled layers or classes: the view, viewmodel, and model. Business logic in a Windows Store app is encapsulated in the model, including any services to fetch and store data from local or remote storage (that is, the data layer). The viewmodel encapsulates the presentation logic, and the view encapsulates the UI and UI logic. Figure 1-5 illustrates the MVVM pattern and the function of its various layers.

A diagram showing the various layers of a solution designed with the MVVM pattern. Three boxes are shown: View, ViewModel, and Model. The View box at the top is connected to the next box, ViewModel, by a two-way arrow. The ViewModel box is connected to the Model box below it by a two-way arrow.

Figure 1-5. MVVM layers and their functions

The View

The view is the visual interface of the application. It comprises a visual element, such as a page or a window, and controls provided by the framework. The layout and styling of the controls is defined in the view. In addition, the view can define animations that are triggered when there is a change in the state of the viewmodel (for example, when there is new data) or when the user interacts with the view. The code-behind of the view can contain the UI logic to present data through the controls in the view or code to directly manipulate the visual elements in the view. In some situations, complex animations that are otherwise difficult to set up in XAML can be expressed in the code-behind. It is recommended that you do not put business or presentation logic in the code-behind of the view; otherwise, UI testing becomes difficult.

The view references the viewmodel through a property called DataContext. This property can be set through XAML or the code-behind of the view. The controls in the view are data-bound to the properties and commands in the viewmodel. For views that do not require any UI logic, data templates can be used to specify the UI elements that will represent an object in the viewmodel. This enables visual designers to define and easily update the visual representation without changing the object the view bound to or the behavior of the control that is used to display the object.

The Viewmodel

The viewmodel encapsulates the presentation logic of the application. It does not have any knowledge of the view’s design, layout, style, and so on. The viewmodel implements the properties and commands that the view binds to and notifies the view of state change through events. Although the viewmodel provides the properties and commands required by the view, the view determines how these properties will be rendered on the interface and how it will integrate the commands with actions for the user.

The viewmodel acts as the glue between the view and one or more model classes. In a complex view, you can require more than one model class to provide data. The viewmodel can transform the data so that it can be represented in the view. The viewmodel can combine multiple fields from models in a property that is then bound to a visual element in the view. This helps where a new requirement adds a new field in the data model that is to be combined with an existing field. It requires an update in the viewmodel code, but the view does not require a change.

Actions invoked by the user in a view such as tapping a button are typically defined as commands in the viewmodel. Commands provide a clean way to encapsulate user actions so that they are separate from the UI. The ICommand interface provides the mechanism to connect the UI with commands that are defined in the viewmodel.

The Model

Business logic and data are encapsulated in the model. A model class defines the data structures based on the application’s data model. The business logic as well as data validation rules are often implemented in the model, although a separate repository for data access, caching, and storage can be used. The model classes are often generated as part of the data access layer or remote service that provides the data for the application.

The model usually implements the INotifyPropertyChanged interface that enables it to be bound to the view. The model can also implement the INotifyDataErrorInfo interface to provide support for data validation. In some cases, when the model doesn’t implement these interfaces, the viewmodel defines the model and implements these interfaces.

Data binding

Data binding is the mechanism that establishes a connection between the application’s UI and business logic. If the model implements the data binding interface, when the data changes its value, it is reflected in the UI element that is bound to the data. Data binding also implies that any changes in the representation of the data in the UI can be used to update the underlying data.

Data binding in the MVVM pattern provides a clean and simple way of connecting UI elements with data. A binding consists of the following:

§ A binding source that provides the data for the visual element in the view. A binding source can be a common language runtime (CLR) object such as a class defined in C# or any WinRT object of a type that has [BindableAttribute] or implements the ICustomPropertyProvider interface. To meet the app requirements, you can bind a property of a UI element with the value of a property of another UI element.

§ A binding target that is a visual element for presenting the data in the view. A visual element is an object of the type FrameworkElement. It provides one or more properties of the type DependencyProperty, which is used as the binding target. Most FrameworkElement properties (except the read-only properties) are dependency properties. FrameworkElement properties support data binding by default.

§ A binding object that defines the connection between the binding source and binding target and moves the data between them.

The binding object shown in Figure 1-6 provides the following information to the binding mechanism:

A diagram illustrating data binding between source and target, with a binding object mediating and defining the connection between the binding target (at the top) and the binding source (at the bottom).

Figure 1-6. Data binding between source and target

§ The source and target objects.

§ The direction of data flow, specified by setting the Binding.Mode property to one of the BindingMode enumeration values.

§ The value converter, if the data used in the binding needs to be formatted or modified before it is presented in the UI. A value converter is specified by setting the Converter property of the FrameworkElement to an instance of a class that implements the IValueConverter interface.

The BindingMode enumeration describes how the data propagates in a binding. Its members are OneWay, OneTime, and TwoWay. In a TwoWay binding, changes to the target propagate to the source, except if the binding target is the Text property of a FrameworkElement. In such a case, the change is propagated only when the TextBox loses focus. In OneWay binding, the target is updated when data is available in the binding source and changes in the source are propagated to the target. In OneTime binding, the target is updated only once: when the binding is created.

Setting up binding (in XAML) and the DataContext property (in C#) shows how to set up binding in XAML and set up the DataContext property for the target in the code-behind file.

SETTING UP BINDING (IN XAML) AND THE DATACONTEXT PROPERTY (IN C#)

Sample of XAML code

<TextBox x:Name="FirstNameTextBox" Text="{Binding FirstName, Mode=OneWay}" />

Sample of C# code

// Create an instance of the Person

// class that implements INotifyPropertyChanged

Person person = new Person();

person.FirstName = "Joseph";

person.LastName = "Samuel";

// Set the DataContext of the TextBox FirstNameTextBox

FirstNameTextBox.DataContext = person;

The binding target is created in the XAML by using the {Binding…} syntax. The binding source is set in the code through the DataContext property of the TextBox in the code shown in Handling the OnLaunched event. You can use the ElementName property or the RelativeSource property to specify the binding source. If you need to bind a property of a UI element to a property of another UI element, the ElementName property is useful (for example, when you are changing the diameter of a circle using a slider). The RelativeSource property is commonly used to bind one property of an object to another property of the same object, or to define a binding in a style or template.

Design and implement the model

The model in the MVVM pattern is the entity responsible for moving data to and from the data store and implementing the business logic. Although the implementation of the model can vary based on the app requirements, the interface from the model to the viewmodel does not change. In the case of a simple application, the model can contain the implementation for retrieval and storage of data from the file system, in plain text. If the application needs to retrieve data from a remote web service or data store, you can create a repository class to implement the web service client. In that case, the model defines the data structures required to extract the data obtained from the remote web service. The repository can additionally support user authentication and authorization.

Model objects are either exposed through viewmodels or defined in a viewmodel. When model objects are exposed via viewmodels, they need to implement the INotifyPropertyChanged interface and (optionally) the INotifyDataErrorInfo interface if it supports validation.

A single-page Windows Store app does not require more than one model class. For more complex applications, multiple models are required to support the business logic. Consider the design of a Windows Store app that enables user to search for photographs from a popular website using their web service. Amateurs and enthusiasts upload photographs and use a simple rating system to mark the photographs in order of popularity. A search term can be provided a string to query the web service. The web service returns the result of such a query as XML or JavaScript Object Notation (JSON) items in an array. Therefore, the model in this case is a data structure that can be used to extract the data from the raw XML or JSON response from the web service.

Using a model class shows the C# code for a model class representing an individual item in the result of the query to the web service.

USING A MODEL CLASS

public class SearchResultItem

{

public SearchResultItem(XElement elmt)

{

Id = elmt.Element("Id").Value;

Name = elmt.Element("Name").Value;

Description = elmt.Element("Name").Value;

ImageUri = new Uri(elmt.Element("Url").Value);

Votes = elmt.Element("Votes").Value;

}

public long Id { get; private set; }

public string Name { get; private set; }

public string Description { get; private set; }

public Uri ImageUri { get; private set; }

public int Votes { get; private set; }

}

The C# code in Querying a web service and parsing the results implements the logic to query the remote web service and parse the result into a list in a separate class. The result is sorted so that the photograph with the most number of votes is the first element in the list.

QUERYING A WEB SERVICE AND PARSING THE RESULTS

public static class ContosoImageSearchService

{

public static async Task<List<SearchResultItem>> SearchImagesAsync(string searchTerm)

{

HttpClient httpClient = new HttpClient();

Uri searchUri = new Uri("http://ws.contoso.com/?search=" + searchTerm);

List<SearchResultItem> searchResults = new List<SearchResultItem>();

using (HttpResponseMessage response = await

httpClient.GetAsync(searchUri.ToString()))

{

if (response.IsSuccessStatusCode)

{

using (Stream strm = await response.Content.ReadAsStreamAsync())

{

XElement elmnt = XElement.Load(strm);

searchResults = (from p in elmnt.DescendantsAndSelf("Photo")

select new SearchResultItem(p)

).OrderByDescending(r => r.Votes). ToList();

}

}

}

return searchResults;

}

}

You might notice that the query is executed asynchronously on the remote web service. Asynchronous execution of such requests is fundamental for the fast and fluid UI requirement in Windows Store apps. The viewmodel invokes the method to carry out the search through a command implemented with the ICommand interface, which facilitates binding the command with the view.

Designing a viewmodel to support the view based on your model

The classic definition of the viewmodel is that it is the model for the view. However, this definition is an oversimplification of the role a viewmodel plays in an application. The main features of a viewmodel are these:

§ It provides data that is represented in the view. This data can include properties that are required in the view but are not part of the model.

§ It provides commands that are connected to events of UI elements and are used to invoke an action. The commands are implementations of the ICommand interface.

§ It implements the INotifyPropertyChanged interface, thereby keeping the UI in synchronization with the data model.

§ It optionally implements the INotifyDataErrorInfo interface, which enables the viewmodel to provide feedback through the UI on issues with the data entered by the user.

You need to keep these features of a viewmodel in mind while designing your model, and you might have to simplify the complex object model that represents the data returned from a remote service. You might also need to transform model properties to allow binding in the view; for example, transforming an enumeration into a Boolean that can be used to set the visibility of a UI element. Instead of implementing the logic to carry out the transformation in the viewmodel, you can implement it in a value converter and use in the data binding.

A single-page Windows Store app requires the following presentation logic implemented in the viewmodel:

§ A property that is a list of photographs for the search term.

§ A property that is the search term inserted by the user. It is bound to a text box in the UI.

§ A property that is a command bound to the search button in the user interface.

Developing a view to meet data-binding requirements

In the MVVM pattern, the role of the view is to present the data and enable the user to interact with it. In a Windows Store app, the view can be a UserControl or a Page. The relationship between the view and its data is set up through data binding. The simplest way to set this up is to add a reference to the viewmodel in the DataContext property of the view. You can bind the properties and commands of the viewmodel to the corresponding UI elements in the view.

For the single page discussed so far, there are five steps you need to carry out to set up data binding in the XAML:

1. Set up binding for a TextBox to SearchTerm property in the viewmodel and a button’s command property to the SearchPhotosCommand in the viewmodel.

2. Define a CollectionViewSource in the XAML with the source set to the ObservableCollection member in the viewmodel.

3. Define a DataTemplate to represent the data in the ObservableCollection and name it SearchItemTemplate.

4. Declare a GridView and set its ItemsSource to the CollectionViewSource.

5. Set the ItemTemplate property of the GridView to the SearchItemTemplate.

These steps are shown in Setting up data binding in XAML.

SETTING UP DATA BINDING IN XAML

<Page.Resources>

<!-- Define a CollectionViewSource -->

<CollectionViewSource x:Name="SearchResultsCollection"

Source="{Binding SearchResultItems}" />

<!-- Declare a DataTemplate for the GridView -->

<DataTemplate x:Key="SearchItemTemplate">

<StackPanel VerticalAlignment="Top" Margin="0,0,0,10">

<Image Width="300" Height="150" Source="{Binding ImageUri}" />

<TextBlock Padding="0,15,0,10" Text="{Binding Name}" />

</StackPanel>

</DataTemplate>

</Page.Resources>

<!-- Set up the data binding for the search text box and the search button -->

<TextBox x:Name="SearchTermTextBox" Text="{Binding Path=SearchTerm, Mode=TwoWay}" />

<Button x:Name="SearchPhotosButton" Content="Search"

Command="{Binding SearchPhotosCommand}" />

<!-- Declare a GridView and set its ItemsSource to the CollectionViewSource -->

<GridView x:Name="SearchResultsGridView"

SelectionMode="None"

IsItemClickEnabled="False"

ItemsSource="{Binding Source={StaticResource SearchResultsCollection}}"

ItemTemplate="{StaticResource SearchItemTemplate}" />

In the code-behind of the page, you need to set up the DataContext of the page as an instance of the SearchResultsViewModel class:

Sample of C# code

// Create an instance of the SearchResultsViewModel

SearchResultsViewModel viewModel = new SearchResultsViewModel();

// Setup the DataContext

this.DataContext = viewModel;

Creating viewmodels using NotifyPropertyChanged, ObservableCollection, and CollectionViewSource

The viewmodel implements the INotifyPropertyChanged interface. The result of the search query is a list of items. You use the ObservableCollection class to represent the result returned by the search query. This class represents a data collection and provides notifications when items are added or removed, or when the collection is refreshed. The data source of the CollectionViewSource is the ObservableCollection property of the viewmodel.

Before implementing the viewmodel, implement the RelayCommand class that is used in the viewmodel as a property bound to the search button. The RelayCommand class implements the ICommand interface, shown in Implementing the RelayCommand class, and it can be used as a member in the viewmodel, thereby allowing it access private members of the viewmodel.

IMPLEMENTING THE RELAYCOMMAND CLASS

Sample of C# code

public class RelayCommand : ICommand

{

Action _TargetExecuteMethod;

Func<bool> _TargetCanExecuteMethod;

public RelayCommand(Action executeMethod)

{

_TargetExecuteMethod = executeMethod;

}

public RelayCommand(Action executeMethod, Func<bool> canExecuteMethod)

{

_TargetExecuteMethod = executeMethod;

_TargetCanExecuteMethod = canExecuteMethod;

}

public void RaiseCanExecuteChanged()

{

CanExecuteChanged(this, EventArgs.Empty);

}

bool ICommand.CanExecute(object parameter)

{

if (_TargetCanExecuteMethod != null)

{

return _TargetCanExecuteMethod();

}

if (_TargetExecuteMethod != null)

{

return true;

}

return false;

}

public event EventHandler CanExecuteChanged = delegate { };

void ICommand.Execute(object parameter)

{

if (_TargetExecuteMethod != null)

{

_TargetExecuteMethod();

}

}

}

The presentation logic for the single-page Windows Store app is the following:

§ The INotifyPropertyChanged interface and the PropertyChangedEventHandler event.

§ A member variable that is an ObservableCollection of the items returned in the search result.

§ A command that is used to fire the image search query. The ICommand interface is implemented in a separate class (RelayCommand) and defined as a member in the viewmodel.

Implementing the viewmodel for a single-page Windows Store app shows the implementation of the viewmodel of the single-page Windows Store app.

IMPLEMENTING THE VIEWMODEL FOR A SINGLE-PAGE WINDOWS STORE APP

public class SearchResultsViewModel : INotifyPropertyChanged

{

public event PropertyChangedEventHandler PropertyChanged;

ObservableCollection<SearchResultItem> _searchResultItems;

string _searchTerm = string.Empty;

public SearchResultsViewModel()

{

SearchPhotosCommand = new RelayCommand(SearchPhotos);

}

public string SearchTerm

{

get { return _searchTerm; }

set

{

if (_searchTerm != value)

{

_searchTerm = value;

if (PropertyChanged != null)

PropertyChanged(this, new PropertyChangedEventArgs("SearchTerm"));

}

}

}

public ObservableCollection<SearchResultItem> SearchResultItems

{

get { return _searchResultItems; }

set

{

if (_searchResultItems != value)

{

_searchResultItems = value;

if (PropertyChanged != null)

PropertyChanged(this,

new PropertyChangedEventArgs("SearchResultItems"));

}

}

}

// Command bound to search button

public RelayCommand SearchPhotosCommand { get; private set; }

public async void SearchPhotos()

{

SearchResultItems = new ObservableCollection<SearchResultItem>(

await ContosoImageSearchService.SearchImagesAsync(_searchTerm));

}

}

When set, each property raises the RaisePropertyChanged event. This event is raised for simple properties such as the search term as well as for the collection property that represents the search results. You can put the code used to implement the INotifyPropertyChanged interface in viewmodels in an abstract class, which is then used as the base class for all your viewmodels. The Grid App and Split App XAML templates in Visual Studio provide developers with an abstract base class that helps refactor the code seen in the viewmodel class properties. Code for theBindableBase class is shown in Implementing the INotifyPropertyChanged interface through BindableBase.

IMPLEMENTING THE INOTIFYPROPERTYCHANGED INTERFACE THROUGH BINDABLEBASE

public abstract class BindableBase : INotifyPropertyChanged

{

public event PropertyChangedEventHandler PropertyChanged;

protected bool SetProperty<T>(ref T storage, T value,

[CallerMemberName] String propertyName = null)

{

if (object.Equals(storage, value)) return false;

storage = value;

this.OnPropertyChanged(propertyName);

return true;

}

protected void OnPropertyChanged([CallerMemberName] string propertyName = null)

{

var eventHandler = this.PropertyChanged;

if (eventHandler != null)

{

eventHandler(this, new PropertyChangedEventArgs(propertyName));

}

}

}

Note that the implementation of OnPropertyChanged in the BindableBase class uses the caller member attribute, removing the requirement of specifying the property name. The property name is passed automatically to the [CallerMemberName] attribute, so there is no need to specify it. Using BindableBase as the base class, a viewmodel can be implemented with the properties in Implementing a viewmodel through BindableBase.

IMPLEMENTING A VIEWMODEL THROUGH BINDABLEBASE

public abstract class SearchResultsViewModel : BindableBase

{

private ObservableCollection<SearchResultItem> _searchResultItems;

private string _searchTerm;

public SearchResultsViewModel()

{

SearchPhotosCommand = new RelayCommand(SearchPhotos);

}

public ObservableCollection<SearchResultItem> SearchResultItems

{

get { return this._searchResultItems; }

set { this.SetProperty(ref this._searchResultItems, value); }

}

public string SearchTerm

{

get { return this._searchTerm; }

set { this.SetProperty(ref this._searchTerm, value); }

}

// Command bound to search button

public RelayCommand SearchPhotosCommand { get; private set; }

public async void SearchPhotos()

{

SearchResultItems = new ObservableCollection<SearchResultItem>(

await ContosoImageSearchService.SearchImagesAsync(_searchTerm));

}

}

EXAM TIP

You will not be asked to write XAML or C# code to illustrate how various interfaces and data binding work. However, it is important to understand the various interfaces, how they are used in data binding, and so on.

THOUGHT EXPERIMENT

Applying the MVVM pattern to a Windows Store app

In this thought experiment, apply what you’ve learned about this objective. You can find answers to these questions in the “Answers” section at the end of this chapter.

You have been handed over a set of requirements and code of a Windows Store app used as a prototype for a client demonstration. The prototype has a fully functional set of classes that work with the remote web service provided by the client. Branding of the app is also available and implemented in the prototype.

How can you apply the MVVM pattern to develop an app based on the prototype while reusing code that is already developed and tested?

Objective summary

§ A loosely coupled design for a Windows Store app can be prepared with the MVVM pattern.

§ The view contains UI elements, the view model contains presentation logic, and the model contains business logic and is responsible for moving data to and from the data store.

§ When designing an application, try to place as much code as possible in the business logic typically implemented in the model class and often in a repository class.

§ The viewmodel should contain the presentation logic and should be designed based on the model. Its design should not be influenced by the view and UI requirements.

Objective review

Answer the following questions to test your knowledge of the information in this objective. You can find the answers to these questions and explanations of why each answer choice is correct or incorrect in the “Answers” section at the end of this chapter.

1. You are designing your Windows Store app with the MVVM design pattern. In the data access layer, you use an XML file to store and retrieve data. To maximize reuse of code across Windows Store, WPF, and Silverlight applications, how should you implement data access layer in your application?

a. Implement the logic to read the XML file when the page loads and display data from the XML file.

b. Create a viewmodel and populate its properties from the XML file in its constructor. Data-bind the viewmodel to the page.

c. Create a file helper class to read the XML file. Use this file to populate the data model. Data-bind the viewmodel with the page.

d. Implement the logic to read the XML file when the page loads and populate the viewmodel. After the data is loaded, data-bind the viewmodel with the page.

2. You are creating an application that enables the user to review data in a database and save changes to a separate file, but not to save changes to the database. What is the correct way to implement this requirement?

a. Set the Mode property of the binding to OneTime.

b. Set the Mode property of the binding to OneWay.

c. Set the Mode property of the binding to TwoWay.

d. Create a new command to save the changes.

3. You are developing an application in which a collection of objects is returned by a web service when the user carries out a search. You need to bind a GridView control with the results from the web service. How should you set up the data source of the GridView so that when the UI is updated, the result from the search is returned?

a. Enumerate the members of the collection of objects from the search result. Add these members to a list and set the DataContext of the GridView to this list.

b. Create a CollectionViewSource and set its source to the collection returned by the web service. Set the ItemsSource property of the GridView to the CollectionViewSource.

c. Set the ItemsSource property of the GridView to the collection returned by the web service.

d. Create a custom control and data-bind the custom control with the collection returned by the web service.

Objective 1.4: Design and implement Process Lifetime Management (PLM)

One of the key features of Windows Store apps is their fast and fluid behavior. The user has the ability to switch between multiple Windows Store apps. At any time, the focus is on a single application that occupies the full screen. (Apps in a snapped state are considered to be in the foreground.) A Windows Store app is running only when it is visible on the user’s screen. At all other times, it is either suspended or not running. It is the application’s responsibility to preserve its state, such as the scroll position in a page, when it is suspended and use this information when it is resumed. Process Lifetime Management (PLM) is the mechanism of managing the state of Windows Store apps.

NOTE

This objective covers how to:

§ Choose a state management strategy

§ Handle the Suspending event and prepare for app termination

§ Handle the Resuming event

§ Handle the OnActivated event

§ Check the ActivationKind and previous state

Choosing a state management strategy

PLM is an important concept you must understand and apply when designing and developing Windows Store apps. Because Windows Store apps execute only when they are in the foreground, you need to ensure that your application saves the current state of the application when the user switches to another application.

A user launches a Windows Store app whenever the user activates the app by tapping its tile or through the Search contract or a share operation, for example. When an app launches, a splash screen displays to the user.

MORE INFO CONTRACTS AND TILE

See Chapter 2 for detailed information on contracts and Chapter 3 for tiles.

The app registers event handlers and prepares the UI before it enters the Running state and occupies the full screen. The user can send the app to the background by swapping with another app that is already running. The first app enters the Suspended state when it is sent to the background by the user. The app can remain in the Suspended state until the user brings it in the foreground by swapping with an app in the foreground, or it may be terminated by Windows if the operating system determines the app is consuming a lot of resources while in the background. Figure 1-7illustrates various states of an application’s lifetime.

A diagram illustrating the states of an application and the transitions between them. The Running box is connected to the Suspended box by a Suspending arrow. A Resuming arrow points from the Suspended box back to the Running box. A Low Resources arrow points from the Suspended box to the Not Running/Terminated box. An Activated arrow points from the Not Running/Terminated box to the Running box.

Figure 1-7. Application execution states

When Windows terminates your app, all state information that has not been saved is lost. Users will be disappointed when they restart the application and find all their unsaved work is gone. This is particularly relevant in applications that provide the user with multiple ways to interact, for example, navigating them through a number of pages, allowing them to save data in forms, and so on.

To provide users with an optimal experience while running your application, you need to implement a state management strategy. The key points while implementing such a strategy are the following:

§ If your application has multiple pages and a navigation scheme, save the navigation steps and visual artifacts of each page while the user navigates through the app. Consider a page that uses horizontal scrolling to display form fields for data entry. If the user decides to leave your application and later return to it after checking email, for example, you need to preserve both the form content as well as the scroll position. When the user switches back to your application, he or she will be presented with the unsaved data and can carry on using your application.

§ Windows can terminate your application while in the Suspended state if it finds the device is running low on resources. Therefore, as soon as your application is suspended, you should save the state of your application without waiting for your application to be terminated.

§ When your application is being suspended, it should release any resources and file handles so that other apps can access them while your application is suspended.

§ You can provide the user with an option to either resume from where they left your application or start afresh. This is relevant for applications such as games and media players.

§ You do not need to restore the state of your application if it is launched via a contract, such as the Search contract, or if your app is launched because of a file association.

§ If your application fetches data from a remote service on the Internet, you can check the time when it was suspended (and terminated if Windows ran out of resources) and refresh the UI instead of showing old content. This is relevant for applications that display the weather or news, for example.

§ If your app needs to run even when Windows suspends it, you can implement such application logic as a background task. For example, if users start a file upload or download task from within your application, they expect the task to be complete when they are back in your application.

Windows provides a way for users to close an application if they want to. Therefore, you should not provide any options in the UI, such as a button, for the user to terminate your app. If your application terminates due to an exception or hardware failure, the app should not try to resume from a previous state and instead start afresh. In the event of abnormal termination, state saved by your app might be corrupt, and restoring your application from corrupt data can cause further crashes and termination. You should never consider overriding the application lifetime management provided by Windows in your app. This helps with your applications’ performance and reduces power consumption in the device.

Handling the Suspending event and preparing for app termination

When a user suspends an app, explicitly saving the user’s data and page navigation state enables the user to resume from where the app was suspended, even when the app is terminated by Windows. Suspended apps do not receive any notification because they are terminated; therefore, you should implement the mechanism to save your application’s state in the Suspending event.

There are two kinds of data your app needs to manage: app data and session state. App data is persistent across sessions and must be available within the app to the user. Session state is temporary data that is relevant to a user’s current session with your application. To save the data and session state when your application is suspended, you must subscribe to the Suspending event. You save app data and session state using the event handler, shown in Using the Suspending event to save app data and session state.

USING THE SUSPENDING EVENT TO SAVE APP DATA AND SESSION STATE

using System;

using Windows.ApplicationModel;

using Windows.ApplicationModel.Activation;

using Windows.UI.Xaml;

public sealed partial class App : Application

{

public App()

{

InitializeComponent();

this.Suspending += OnSuspending;

}

private async void OnSuspending(object sender, SuspendingEventArgs e)

{

// Save your applications' state and data here

}

}

Windows allows 10 seconds for your application to suspend, so you must ensure that saving data and state information in the Suspending event handler does not take longer than 10 seconds. If the app takes longer than 10 seconds in the event handler, Windows assumes your app is not responding and terminates it. If your app needs to complete any task when the app is being suspended, you need to defer completion of the suspend operation until the task is complete. You must use the GetDeferral method of the SuspendingOperation object (from the SuspendingEventArgsobject) to delay completion of the suspend operation. After the task is complete, you can call the Complete method on the SuspendingDeferral object. The following C# code shows how to defer the suspend operation:

private void OnSuspending(object sender, SuspendingEventArgs e)

{

SuspendingDeferral deferral = e.SuspendingOperation.GetDeferral();

// Save your applications' state and data

deferral.Complete();

}

Although your application can use the Suspending event to save app data and its state, Visual Studio adds a SuspensionManager class when you create a Windows Store app with one of the templates. It is a helper class that simplifies the lifetime management in your app. It saves and restores the navigation state of your application’s pages that are hosted in the root Frame. It also provides every page in your application the opportunity to save and restore its state. SuspensionManager serializes app data and page state into an XML file that resides in your app’s local storage.

When you create a new Windows Store project in Visual Studio, the Grid App and Split App templates already include the SuspensionManager class in the Common folder, as shown in Figure 1-8.

A screenshot of a Windows Store app project showing the SuspensionManager class added by Visual Studio.

Figure 1-8. SuspensionManager class in a Visual Studio project

You have to register the app’s Frame object with the SuspensionManager class. SuspensionManager is then aware of every page in your app and can save and restore the navigation state. The Frame of your app is registered in the OnLaunched method immediately after it is created. This is shown in the following example:

protected override async void OnLaunched(LaunchActivatedEventArgs e)

{

var rootFrame = new Frame();

// Associate with the SuspensionManager

SuspensionManager.RegisterFrame(rootFrame, "AppFrame");

}

When your app is suspended, you need to save app data as well as session state. Because app data is not dependent on the device on which your application is running, you should consider using a data container that it is available to the user across multiple devices. TheWindows.Storage.ApplicationData object has a RoamingSettings property that returns an ApplicationDataContainer. You can use the ApplicationDataContainer to store app data that persists across sessions. If your application requires storage of device-specific data, you should use theLocalSettings property. In the sample application discussed in the previous objective, you might want to save the search term entered by the user. This can be done in the TextChanged event of the TextBox, as shown in the following example:

private void SearchTermTextBox_TextChanged(object sender, TextChangedEventArgs e)

{

Windows.Storage.ApplicationDataContainer roamingSettings =

Windows.Storage.ApplicationData.Current.RoamingSettings;

RoamingSettings.Values["SearchTerm"] = SearchTermTextBox.Text;

}

As mentioned previously, the session state of your application can be saved in the Suspending event. The SuspensionManager class makes it very easy to save the state of your application. All you need to implement is a single line of code to save your application’s state:

private async void OnSuspending(object sender, SuspendingEventArgs e)

{

SuspendingDeferral deferral = e.SuspendingOperation.GetDeferral();

// Save the applications' state

await SuspensionManager.SaveAsync();

deferral.Complete();

}

You can test your application for suspension and termination using the Visual Studio debugger. If the debugger isn’t available on the Visual Studio menu, ensure Debug Location is checked in the list of menu items. When you debug your application using Visual Studio, you can click the Suspend drop-down menu and test your application for various states, as shown in Figure 1-9.

A screenshot of Visual Studio showing the Suspend, Resume, and Suspend and Shutdown PLM events.

Figure 1-9. Visual Studio debugger with PLM testing support

Handling the Resuming event

A suspended Windows Store app resumes when the user switches it into view or when the device comes out of a low power state. Your application can subscribe to the Resuming event and refresh any content that is displayed in the page in view. This event is not raised in the UI thread, so a dispatcher must be used to update the UI. If your application does not have any displayed content that requires a refresh, there is no need for it to handle the Resuming event.

You can handle the Resuming event by providing an event handler, as shown in the following code:

partial class MainPage()

{

public MainPage()

{

InitializeComponent();

Application.Current.Resuming += OnResuming;

}

private void OnResuming(object sender, object e)

{

// Refresh the displayed contents in your app

}

}

When you handle the Resuming event in your app, you must remember that your application’s UI should be visible within 15 seconds. Ideally, you should add an extended splash screen in your application to provide continuous feedback to the user while your app refreshes the data.

Handling the OnActivated events

The OnLaunched and OnActivated events are used in Windows Store apps to check the kind of activation, obtain the previous state of execution of the application, and perform initialization of the application.

When your app is launched from its tile, in the OnLaunched event, a new Frame is created if the Window does not have content and the Frame navigates the user to your application’s startup page. The Frame is then set as the content for your application’s Window, and the Activate method is called to bring the application to the foreground, as shown in Handling the OnLaunched event.

HANDLING THE ONLAUNCHED EVENT

protected async override void OnLaunched(LaunchActivatedEventArgs e)

{

Frame rootFrame = Window.Current.Content as Frame;

if (rootFrame == null)

{

rootFrame = new Frame();

SuspensionManager.RegisterFrame(rootFrame, "AppFrame");

Window.Current.Content = rootFrame;

}

if (rootFrame.Content == null)

{

if (!rootFrame.Navigate(typeof(MainPage))

{

throw new Exception("Failed to create initial page");

}

}

// Ensure the current Window is active

Window.Current.Activate();

}

Your application does not require initialization if it is launched from a running state. Therefore, before initialization, it is important to see whether the previous state of your application is Running. The OnLaunched event needs an update, as shown in Updating the OnLaunched event.

UPDATING THE ONLAUNCHED EVENT

protected async override void OnLaunched(LaunchActivatedEventArgs e)

{

// Do not repeat app initialization when already running, just ensure that

// the window is active

if (args.PreviousExecutionState == ApplicationExecutionState.Running)

{

Window.Current.Activate();

return;

}

Frame rootFrame = Window.Current.Content as Frame;

if (rootFrame == null)

{

rootFrame = new Frame();

SuspensionManager.RegisterFrame(rootFrame, "AppFrame");

Window.Current.Content = rootFrame;

}

if (rootFrame.Content == null)

{

if (!rootFrame.Navigate(typeof(MainPage))

{

throw new Exception("Failed to create initial page");

}

}

// Ensure the current Window is active

Window.Current.Activate();

}

If your app is activated from the Terminated state, it needs to restore its app state and app data that was saved when the app transitioned into the Suspended state. In the OnLaunched event, you can use the SuspensionManager to restore the navigation state of the Frame and provide the Pagethe opportunity to restore its content, as shown in Restoring the app state and app data from the Suspended state.

RESTORING THE APP STATE AND APP DATA FROM THE SUSPENDED STATE

protected async override void OnLaunched(LaunchActivatedEventArgs e)

{

// Do not repeat app initialization when already running, just ensure that

// the window is active

if (args.PreviousExecutionState == ApplicationExecutionState.Running)

{

Window.Current.Activate();

return;

}

Frame rootFrame = Window.Current.Content as Frame;

if (rootFrame == null)

{

rootFrame = new Frame();

SuspensionManager.RegisterFrame(rootFrame, "AppFrame");

// Restore the saved navigation state and application content

if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)

{

try

{

await SuspensionManager.RestoreAsync();

}

catch (SuspensionManagerException)

{

// Something went wrong, assume there is no state and continue.

}

}

Window.Current.Content = rootFrame;

}

if (rootFrame.Content == null)

{

if (!rootFrame.Navigate(typeof(MainPage))

{

throw new Exception("Failed to create initial page");

}

}

// Ensure the current Window is active

Window.Current.Activate();

}

To restore the application data, you need to use the LoadState method in the page that is activated. In an example discussed previously, the search term entered by the user was saved in the RoamingSettings property of the ApplicationDataContainer. You need to load the search term fromRoamingSettings, as shown in the following code:

protected override void LoadState(Object navigationParameter, Dictionary<String, Object>

pageState)

{

Windows.Storage.ApplicationDataContainer roamingSettings =

Windows.Storage.ApplicationData.Current.RoamingSettings;

if (RoamingSettings.Values.ContainsKey("SearchTerm"))

{

SearchTermTextBox.Text = RoamingSettings.Values["SearchTerm"].ToString();

}

}

When a Windows Store app uses a contract such as Search or Share from another app, the Launched event is sent to the app. The LaunchActivatedEventArgs parameter passed in the event contains a Kind property that has a value of type ActivationKind. This value tells you why the application was activated.

As an alternative to checking the ActivationKind in the OnLaunched method and performing the initialization for the activation kind, you can perform initialization specific to the activation type by overriding one of the following methods instead of the OnLaunched method:

§ OnFileActivated. This event is fired when a Windows Store app is activated through a file-open action. The application needs to register as the default handler for a certain file type to receive this event.

§ OnSearchActivated. This event is fired when a Windows Store app is activated through a search association.

§ OnShareTargetActivated. This event is fired when a Windows Store app is activated through a sharing association; that is, the app receives content from other Windows Store apps.

§ OnFileOpenPickerActivated. This event is fired when a Windows Store app is activated when it provides files that are opened by another application.

§ OnFileSavePickerActivated. This event is fired when a Windows Store app is activated when it supports saving files created by another application.

§ OnCachedFileUpdaterActivated. This event is fired when the user saves or opens a file that is updated by an app.

Checking the ActivationKind and previous state

A Windows Store app can be activated in a variety of ways by the user. A specific type of Activated event is fired in your application if it implements a contract such as the Search contract. Alternatively, in your application, you might want to implement a check of the activation kind to set up the UI. In the OnLaunched event, you can check for the activation type, as shown in the following example:

protected override void OnLaunched(LaunchActivatedEventArgs e)

{

if (args.Kind == ActivationKind.Launch)

{

// The application has been launched by the user through its tile

}

else if (args.Kind == ActivationKind.ShareTarget)

{

// The application has been launched as a share target

}

}

Table 1-1 lists members for ActivationKind enumeration.

Table 1-1. ActivationKind enumeration members

MEMBER

VALUE

DESCRIPTION

Launch

0

The user launched the app or tapped a content tile.

Search

1

The user is about to search with the app.

ShareTarget

2

The app is activated as a target for share operations.

File

3

An app launched a file whose file type the current app is registered to handle.

Protocol

4

An app launched a URL whose protocol the current app is registered to handle.

FileOpenPicker

5

The user wants to pick files that are provided by the app.

FileSavePicker

6

The user wants to save a file and selected the app as the location.

CachedFileUpdater

7

The user wants to save a file that the app provides content management for.

ContactPicker

8

The user wants to pick contacts using the app.

Device

9

The app handles AutoPlay.

PrintTaskSettings

10

The app handles print tasks.

CameraSettings

11

The app captures photos or videos from an attached camera.

* Source: Adapted from http://msdn.microsoft.com/en-au/library/windows/apps/windows.applicationmodel.activation.activationkind

When an app is activated, if the PreviousExecutionState property is NotRunning, the application failed to save its application data successfully and the app should start as if it was launched for the first time. In the OnLaunched event handler of your application, you can check thePreviousExecutionState property of the LaunchActivatedEventArgs parameter. The value of the PreviousExecutionState property is a member of the ApplicationExecutionState enumeration as listed in Table 1-2.

Table 1-2. ApplicationExecutionState enumeration members

MEMBER

VALUE

DESCRIPTION

NotRunning

0

The app is not running.

Running

1

The app is running.

Suspended

2

The app is suspended.

Terminated

3

The app was terminated after being suspended.

ClosedByUser

4

The app was closed by the user.

* Source: Adapted from http://msdn.microsoft.com/en-au/library/windows/apps/windows.applicationmodel.activation.applicationexecutionstate

The NotRunning execution state of a Windows Store app is seen in the following scenarios:

§ After the app is installed from the Windows Store.

§ When the app is closed with the Task Manager when it is running.

§ After rebooting the device.

§ After logging off a user and logging back on.

§ After the user closes through the close gesture or Alt+F4 and activates it within about 10 seconds of closing it. Note that if the user closes the app and launches it after 10 seconds of closing it, the system sets the execution state to ClosedByUser.

The Suspended state of the app is seen when the app is activated using a secondary tile or using a contract or extension it is registered for while Windows is suspending it or after Windows has suspended it.

EXAM TIP

You are not expected to remember the various enumerations for the exam. However, you should be familiar with the values of properties commonly used for finding out the previous execution state, activation kind, and so on.

THOUGHT EXPERIMENT

Enhancing a photo editor Windows Store app

In this thought experiment, apply what you’ve learned about this objective. You can find answers to these questions in the “Answers” section at the end of this chapter.

Your organization has developed a photo editor app as a prototype for obtaining feedback and exploring interest among users of other apps developed previously. The three most common problems reported by the users of the prototype app are listed below. Suggest a solution for each problem with the concepts you have learned in this chapter.

1. Users have reported they cannot search for photos they have edited and saved previously.

2. Users have reported that after bringing another app to the foreground, the prototype app lost all their changes in photos that were open and being edited.

3. Users have reported they do not have an option to see a list of most recently edited photos in the app when it is launched.

Objective summary

§ When you are implementing a state management strategy in your app, it is important to save the UI specific state as well as data in the app.

§ Your application can be terminated by Windows while it is suspended. Therefore, any long-running tasks still being executed when the app is suspended need to be implemented as background tasks.

§ When you design an app to support contracts and charms, you must ensure the respective Activated events are implemented and used in your app.

§ Your application should check its previous state of execution before initializing the UI.

Objective review

Answer the following questions to test your knowledge of the information in this objective. You can find the answers to these questions and explanations of why each answer choice is correct or incorrect in the “Answers” section at the end of this chapter.

1. You are designing a Windows Store app that implements the Search contract and integrates with the Search charm. Which event should you implement to handle activation of your app?

a. OnLaunched

b. OnActivated

c. OnSearchActivated

d. LoadState

2. A Windows Store app is closed by the user using the Alt+F4 shortcut. Which app state will the app be in after it is closed?

a. ClosedByUser

b. Terminated

c. Suspended

d. NotRunning

3. You need to ensure that when your app resumes, it displays the information partially saved by the user. Which ApplicationExecutionState should you check to restore the state of the UI and the unsaved data?

a. ClosedByUser

b. Running

c. Suspended

d. Terminated

Objective 1.5: Plan for an app deployment

The Windows Store was originally launched to a restricted set of developers who had their apps evaluated by experienced Microsoft engineers. This process was implemented to ensure the application certification requirements were tested properly. During this phase, Microsoft used the feedback from developers around the world to refine requirements. Today, Microsoft provides a set of application certification requirements, guidance, and tools for developers to sign and test their applications before submitting them to the Windows Store.

NOTE

This objective covers how to:

§ Plan a deployment based on Windows Store app certification requirements

§ Prepare an app manifest

§ Sign an app

§ Plan the requirements for an enterprise deployment

Planning a deployment based on Windows Store app certification requirements

The Windows Store is the primary source from where applications are downloaded and installed on a Windows device or a PC. The Windows Store provides a unique way to sell and distribute your apps and their updates, interact with users of your apps, and make money with them. The Windows Store acts as an entity that maintains the quality and reliability of Windows Store apps for all users. Your application’s quality is evaluated by a testing process at Microsoft using a standard set of criteria, before the app is made available for download.

Your application must satisfy a basic set of requirements, as follows:

§ Application failures. Your app should not crash or become unresponsive while running. If your app crashes, it should gracefully exit without requiring users to restart their system. This provides your customers with a better user experience.

§ Security. Your app must use Windows security features. It should not compromise the security of the system under any circumstances.

§ Performance. Your app should have a fast and responsive startup and suspend experience. It should release resources while suspended and consume only a reasonable amount of system resources such as central processing unit (CPU), memory, and disk input/output (I/O).

§ App packaging. Your app manifest must contain all required attributes and must have valid resources defined as a Package Resource Index (PRI) file called Resources.pri. The app manifest is defined in the Package.appxmanifest file.

§ Platform application programming interfaces (APIs). Your app must only use APIs from the Windows 8 SDK. If you use an undocumented platform feature, your app will fail certification. Your app must use .NET 4.5 or later APIs.

It is important for your app to follow the Microsoft design style guidelines and its fundamental principles as well as the key features of Windows Store apps discussed previously. The Windows Store app certification requirements define a set of criteria your app should satisfy. To summarize, Windows Store apps:

§ Should be creative, unique and provide value to the customer.

§ Can display ads, but must not display only ads. The ads in your app must conform to the content and age rating guidelines.

§ Should be responsive and perform reasonably well on any device, and updates should not remove functionality from your app.

§ Should enable the customer to control data shared by the app, security, notifications, data transfers, and similar features.

§ Should not contain offensive content and must conform to the content and age rating guidelines.

§ Should have a unique name that helps with their identification in the Windows Store and their brand.

MORE INFO WINDOWS STORE APP CERTIFICATION REQUIREMENTS

You can read about the Windows Store app certification criteria at http://msdn.microsoft.com/en-us/library/windows/apps/hh694083.aspx.

You can use Visual Studio to deploy your app on your local PC, on a remote PC on your network, or in the local simulator. The simulator is helpful when testing your app during development; however, it is not suitable for testing prior to distribution.

When you are ready to distribute your app for testing among other developers and testers, you have to create an app package. You have the option of creating either an .appx file or an .appxupload file. You can upload either file to the Windows Store when you are ready to submit your app. The .appxupload file contains two files: .appx and .appxsym. The .appxsym file contains the public symbols from your app. It provides useful information if your application crashes when it is running.

The .appx packages are ZIP-based container files that contain the app’s payload files with information needed to validate, deploy, manage, and update the app. There are two ways to create an app package:

§ Use Visual Studio. In Visual Studio, under the PROJECT menu, choose Store and then Create App Packages. You can choose the location in which the app package will be created, set a version number for the package, and choose the solution configuration. You can also choose to include public symbols that help with analyzing crashes in your app.

§ Use the command prompt. You can build an app package by opening a Visual Studio command prompt and then running MSBuild or by using Team Foundation Build. By default, the app package is created in the same location as other build output. However, you can override this behavior by specifying /p:GenerateProjectSpecificOutputFolder=false as an argument for MSBuild.

After your application’s app package is ready, you should review the app submission checklist, test your app with the Windows App Certification Kit (ACK), have your app tested by some volunteers, and take some screenshots to submit with your app. Make sure you have included a privacy statement or license terms if your app collects personal information.

MORE INFO APP SUBMISSION CHECKLIST

Information about the app submission checklist is at http://msdn.microsoft.com/en-us/library/windows/apps/hh694062.aspx.

Windows ACK is a free tool available for download from Microsoft. Windows ACK ensures that your application meets the basic requirements of a Windows Store app. Your app has to be installed on the PC where you plan to run Windows ACK. The kit launches your app a few times; tests it for startup and suspends performance; and checks the build version of your package, its dependencies, app capabilities, and so on. At the end of the testing process, Windows ACK creates an XML file you can open in Microsoft Internet Explorer and examine the results. A snippet from the XML file is shown in Figure 1-10.

A screenshot showing a portion of a Windows ACK test results report, which shows the app name, version number, publisher, OS version, report time, and overall result.

Figure 1-10. Windows ACK test results

MORE INFO WINDOWS APP CERTIFICATION KIT

The Windows ACK download is at http://msdn.microsoft.com/en-US/windows/apps/jj572486.

Preparing an application manifest

A Windows Store app needs to be packaged before it is submitted to the Windows Store. When you create a new Windows Store project or item using Visual Studio, your application is set up for an app package to be created at a later stage of development. Visual Studio creates a source file for the app package (Package.appxmanifest) and adds it to your solution. When you build your project for the first time, Visual Studio transforms this file into the manifest file (AppxManifest.xml) and puts it in the output folder of the app. This is shown in Figure 1-11.

A screenshot of Solution Explorer with the application manifest file of a Windows Store app highlighted in the solution file list.

Figure 1-11. The application manifest file in Visual Studio

Your application’s manifest file describes your app, including its name, description, start page, splash screen, and logos. In addition, you can use the manifest file to add capabilities and declarations, such as the ability to access a webcam or a microphone, and if your app supports search or acts as a share target, for example.

You can create the package manifest file manually using a text editor. Package manifest example shows the code for a package manifest.

PACKAGE MANIFEST EXAMPLE

<?xml version="1.0" encoding="utf-8"?>

<Package xmlns="http://schemas.microsoft.com/appx/2010/manifest">

<Identity Name=""

Version=""

Publisher="" />

<Properties>

<DisplayName></DisplayName>

<PublisherDisplayName></PublisherDisplayName>

<Logo></Logo>

</Properties>

<Prerequisites>

<OSMinVersion></OSMinVersion>

<OSMaxVersionTested></OSMaxVersionTested>

</Prerequisites>

<Resources>

<Resource Language="" />

</Resources>

<Applications>

<Application Id="" StartPage="">

<VisualElements DisplayName="" Description=""

Logo="" SmallLogo=""

ForegroundText="" BackgroundColor="">

<SplashScreen Image="" />

</VisualElements>

<Extensions>

<Extension Category="windows.search" />

</Extensions>

</Application>

</Applications>

<Capabilities>

<Capability Name="internetClient" />

<DeviceCapability="webcam" />

<DeviceCapability="microphone" />

</Capabilities>

</Package>

You should prepare your application’s manifest using Visual Studio’s app manifest designer. When you double-click the manifest file (or use the PROJECT|Store|Edit App Manifest option in Visual Studio), the manifest designer with the Application UI tab is the active tab. The Capabilities tab shown in Figure 1-12 shows a portion of the capabilities a Windows Store app can use.

A screenshot of the manifest designer in Visual Studio showing some of the capabilities in the Capabilities list. The capabilities are listed in the pane on the left and a description is on the right.

Figure 1-12. The manifest designer with the capabilities of the app

Table 1-3 lists the capabilities available to a Windows Store app.

Table 1-3. Windows Store app capabilities

CAPABILITY

DESCRIPTION

Documents Library

Provides programmatic access to the user’s Documents library.

Enterprise Authentication

Typically used in line-of-business apps to access corporate resources.

Internet (Client)

Provides outbound access to the Internet and public networks through the firewall.

Internet (Client & Server)

Used in peer-to-peer (P2P) scenarios in apps that use file shares and voice over IP (VoIP).

Location

Provides access to the location functionality.

Microphone

Provides access to the microphone’s audio feed; enables the app to record audio from connected microphones.

Music Library

Provides programmatic access to the user’s Music library.

Pictures Library

Provides programmatic access to the user’s Pictures library.

Private Networks (Client & Server)

Provides inbound and outbound access to home and work networks though the firewall, typically used for games that communicate across the local area network (LAN).

Proximity

Enables multiple devices in close proximity to communicate with each other.

Removable Storage

Provides programmatic access to files on removable store such as USB keys and external hard drives.

Shared User Certificates

Enables an app to access software and hardware certificates, such as certificates stored on a smart card.

Videos Library

Provides programmatic access to the user’s Videos library.

Webcam

Provides access to the webcam’s video feed, which enables the app to capture screenshots and movies from a connected webcam. You need to add microphone capability to grant access to the audio stream as well.

Windows Store apps use contracts and extensions to declare their interaction with other apps. To use the WinRT APIs to communicate with other Windows Store apps, you must add the required declarations in your app’s manifest file. Visual Studio’s manifest designer provides a number of declarations for various contracts and extensions (see Figure 1-13).

A screenshot of the manifest designer in Visual Studio showing the declarations available.

Figure 1-13. The manifest designer with the declarations available

Table 1-4 lists the declarations available for Windows Store apps.

Table 1-4. Windows Store app declarations

CAPABILITY

DESCRIPTION

Account Picture Provider

If your app takes pictures, you can use this extension to list your app in the Account Picture Settings control panel.

AutoPlay Content

This extension enables your app to be listed as an AutoPlay choice.

AutoPlay Device

This declaration registers your app for device events such as attaching a camera. Multiple instances of this declaration is allowed in an app.

Background Tasks

This declaration enables your app to register a background task that runs even when the app is suspended. Multiple instances of this declaration are allowed in an app.

Cached File Updater

This declaration enables users to use your app as a central repository to track and maintain files.

Camera Settings

This declaration provides a custom UI for selecting camera options.

Certificates

This extension enables you to install a digital certificate in your app, useful to authenticate a user to remote web services over SSL.

Contact Picker

This extension enables your app to register to provide contact data.

File Open Picker

This declaration registers your app as a file open picker, making the content available in other apps.

File Save Picker

This declaration registers your app as a file save picker, making the app available as a save location for other Windows Store apps.

File Type Associations

This declaration registers file type associations with your app. Multiple instances of this declaration are allowed in this app.

Game Explorer

This declaration enables your app to register with the Windows Parental Controls system as a game.

Print Task Settings

This declaration enables your app to display a custom print-related UI and communicate directly with a print device.

Protocol

This declaration registers your app for existing or a custom uniform resource identifier (URI) scheme. Multiple instances of this declaration are allowed in this app.

Search

This declaration enables your app’s content to be searchable by other apps and present search results from other apps in your app.

Share Target

This declaration sets up your app as a share target for other apps to share content with your app.

Visual Studio provides developers with an easy way to add a File Open Picker contract, Search contract, and/or Share Target contract in Windows Store apps. Just right-click your project in Visual Studio and select the Add New Item option. The window shown in Figure 1-14 displays.

A screenshot of the Add New Items dialog box. On the left, Windows Store is selected in the Visual C# tree. In the middle, the Share Target Contract item is selected. On the right, there is a description of the selected item.

Figure 1-14. Adding a contract using Visual Studio

If you choose to implement one of these three contracts, the relevant declaration is automatically added to your app’s manifest. In addition, the Activated event for the contract is also added to the app. For the File Open Picker contract, the OnFileOpenPickerActivated event is added; for the Search contract, the OnSearchActivated event is added; and for the Share Target contract, the OnShareTargetActivated contract is added.

Signing an application

When you create an app package using Visual Studio, it is signed with a test certificate. The app package resides in a folder called AppPackages within the package directory; this folder is created by Visual Studio. The certificate (.cer) file present in the folder contains the public key used to sign the package. This key must be installed before the app package is installed.

Visual Studio generates and adds the certificate file (with a .pfx extension) to your project. This certificate is valid for one year after creation. You can generate a new certificate using Visual Studio through the Packaging tab in the app manifest designer. Click the Choose Certificate button to open the Choose Certificate dialog box. Expand the Configure Certificate list, choose Create test certificate, and click OK. You will then add the Publisher Common Name and a password for the certificate file. Visual Studio regenerates the certificate with a new expiration date.

MORE INFO CREATE AN APP PACKAGE SIGNING CERTIFICATE

If you plan to you create your own app package signing certificate, refer to the steps in this MSDN article at http://msdn.microsoft.com/en-us/library/windows/apps/jj835832.aspx.

Planning the requirements for an enterprise deployment

If you develop a Windows Store app and plan to make it available to a large number of Windows users, you should list your app in the Windows Store. If you want to target business users, you can offer your app through the Windows Store with each user purchasing your application. Alternatively, you can offer your app for free to users through the Windows Store and then manage licensing directly with the organization in which your app will be deployed.

If you plan to make your app available for selected enterprises and users, IT administrators can distribute your app within the enterprise without involving the Windows Store. This process is called sideloading. Although your app to be deployed for enterprise users does not need to go through the Windows Store certification process, it is expected that you have followed the Windows design style UI guidelines and your app has been tested with the Windows ACK.

The following steps describe how to distribute a Windows Store app within an enterprise:

1. Use the Windows ACK to test your application. You should also test your app on Windows RT with the Windows ACK for Windows RT if you plan to support Windows RT. Testing your app with the ACK helps identify issues before deployment to users.

2. Your app must be signed with a certificate issued by a certificate authority (CA) trusted by the target PCs. The publisher name in your application’s manifest must match the publisher name in the certificate used to sign the app. If you use a certificate from one of the many CAs trusted by Windows, you do not need to deploy and manage additional certificates on the targeted Windows 8 devices. If you choose to use your own CA to sign the app, IT administrators must ensure that the certificate is installed in the target Windows 8 devices because your CA might be untrusted.

3. When your app is tested and signed, give the signed app package and any app dependencies to the IT administrators.

4. IT administrators prepare the target Windows 8 PCs and deploy your app. Windows Server 2012 and Windows 8 Enterprise editions are enterprise sideloading ready, this means they are ready for your app to be installed. For such PCs, IT administrators should ensure they are joined in the domain and the Group Policy is set to Allow Trusted Apps To Install. IT administrators deploying your app to Windows 8 Pro, Windows RT, and Windows Enterprise devices should configure them by activating the product key for enterprise sideloading for each device and setting the Group Policy to Allow Trusted Apps To Install.

5. IT administrators can deploy your app to prepared PCs and devices by using a Windows image or at runtime.

Enterprise deployment of Windows Store apps does not stop users from installing business-related apps from the Windows Store. IT administrators might want to ensure that users in the enterprise network can access the Windows Store and the rich variety of apps. In a regulated environment, IT administrators can use a Group Policy to turn off access to the Windows Store for the users and their devices.

MORE INFO WINDOWS STORE APP DEVELOPMENT FOR WINDOWS RT HARDWARE

You can read more about developing Windows Store apps targeting Windows RT hardware in the white paper at http://www.microsoft.com/en-us/download/details.aspx?id=30703.

THOUGHT EXPERIMENT

Maintaining a separate, custom version of a Windows Store app

In this thought experiment, apply what you’ve learned about this objective. You can find answers to these questions in the “Answers” section at the end of this chapter.

You have developed a Windows Store app and made it available for users through the Windows Store. The app has received positive feedback, and you are satisfied with the popularity of the app. An organization with a global presence has expressed interest in deploying your app internally with its own branding.

In your discussions with the organization, you have been told that your app can continue to be available in the Windows Store. However, you are expected to develop, deploy, and maintain a custom version of the app for the organization. How can you satisfy the requirements of the organization with your new app?

Objective summary

§ Test a Windows Store app to ensure it meets Windows Store app certification requirements before making the app available to users through the Windows Store.

§ Visual Studio provides a streamlined process to create your app package after you have edited and updated the package manifest file in which you set up your app’s capabilities and declarations.

§ You can use your own certificate to sign your app package.

§ You can build Windows Store apps that target businesses and select a way to distribute them to users without submitting your app to the Windows Store.

Objective review

Answer the following questions to test your knowledge of the information in this objective. You can find the answers to these questions and explanations of why each answer choice is correct or incorrect in the “Answers” section at the end of this chapter.

1. You plan to send your application for testing to a small group of Windows 8 users. What is the best approach for deploying your app on the PCs of these users and obtain their feedback?

a. Request the users to send their PCs or devices to you so you can install the app.

b. Ask your users to install Visual Studio, send them your source code, and request them to compile the code and run your app.

c. Prepare an app package and send them a copy of the app package. Request the users to install your app using the Windows PowerShell script in the package and test your app.

d. Prepare an installer using one of the commercially available tools. Send the installer to your users.

2. You have prepared an app package and submitted it to the Windows Store. You have been informed that your app has passed certification and will be available in the Windows Store soon. You realize there are a few bugs that you should fix soon. What should be your approach in such a case?

a. Create a new app from the code used to build the original app. Submit the new app and withdraw the original app.

b. Bug fixes are not accepted in the Windows Store. You have to withdraw the app and you cannot submit updates to your app.

c. You prepare an update for your app, test it with Windows ACK, and submit it to the Windows Store for certification. After it is certified, it will be available to your users.

d. You can email a copy of your app with the bug fixes to your users.

3. You have completed the development of a Windows Store app that will be deployed in a few businesses. You choose to distribute the app yourself instead of using the Windows Store. What are the requirements for your app to be loaded onto PCs and devices in these organizations? (Choose all that apply.)

a. Your app must be signed with a certificate from a CA trusted by the target PCs and devices.

b. You should give your signed app and its dependencies to IT administrators in the organizations.

c. You should send your app by email to the users who want to install and run your app.

d. IT administrators can deploy your app using a Windows image or when the PC is in use.

e. You should ask the users to send you their PCs and devices so that you can install your app.

Chapter summary

§ Windows Store apps are unique in their appearance and behavior. The emphasis in these applications is on users and the way they interact with your application. You should following the principle of Microsoft design style and available guidance to design your app.

§ Consider separation of concerns, reusability, and maintainability of your application when planning the logical layers of your solution. Divide your application into three main loosely coupled layers: presentation layer, business layer, and data layer. Wherever you have the requirement to integrate legacy software, consider using WinMD components in your Windows Store app.

§ Use the MVVM pattern to implement the logical layers of your solution. The MVVM pattern is helpful for defining the interfaces for communication among the layers of your solution. Use the INotifyPropertyChanged interface to implement your viewmodels and employ data binding in your views to bind viewmodels. Use native controls such as GridView to render data collections in views using the CollectionViewSource and ObservableCollection classes.

§ Plan and implement a sound state management strategy, one that preserves the state and app data when your app is suspended. Use the OnLaunched and OnActivated events to provide the user with a way to resume using your app. Check for the PreviousExecutionState and ActivationKindwhen your app is launched; restore the state and data if necessary.

§ After development is complete, go through the Windows Store certification criteria to ensure your app meets all the requirements. Test your app with the Windows ACK and pay attention to the dependencies in your app. Prepare an app manifest ensuring all capabilities and declarations required by your app are included in the manifest. If you are planning to distribute your app directly, contact the IT administrators and give them the app package for deployment.

Answers

This section contains the solutions to the thought experiments and the answers to the lesson review questions in this chapter.

Objective 1.1: Thought experiment

1. Design for re-use of visual elements. Design and develop the app to maximize reuse of code, styles, and UI elements. This will be helpful if the app is re-branded for other businesses.

2. Design for accessibility. Use controls provided by the WinRT platform to compose the UI. These controls have built-in support for accessibility. Use the Inspect and UI Accessibility Checker tools to test for accessibility.

3. Design a unique user experience. Design the app for compelling UX with a UI that is easy and intuitive to use. Wherever possible, use device capabilities such as location sensors in the app.

Objective 1.1: Review

1. Correct answer: B

a. Incorrect: Animations make the UI intuitive and appealing to use.

b. Correct: Most controls have built-in animations. In addition, the Windows Animation library makes it easy to add animations.

c. Incorrect: It is often a time-consuming exercise to create your own animations when you already have them in standard controls and in the Windows Animation library.

d. Incorrect: It is best to use standard controls whenever possible.

2. Correct answers: A, B, D

a. Correct: The Inspect tool enables you to select any UI element and view its accessibility data.

b. Correct: The UI Accessibility Checker verifies that UI accessibility requirements are met in the design and implementation of UI Automation, regardless of the underlying UI framework.

c. Incorrect: You shouldn’t skip the accessibility tests and hope your application passes certification.

d. Correct: Disconnecting the mouse and using only the keyboard to operate your app is a good test of a real-life scenario.

e. Incorrect: Installing and testing your app on multiple PCs and devices is a time-consuming process and you are not guaranteed results that validate accessibility of the app.

3. Correct answers: B, C, E

a. Incorrect: Using a single version or copy of code among designers and developers could result in serious problems with version conflict, missing requirements, and so on.

b. Correct: Styles enable the reuse of visual elements.

c. Correct: Custom controls can be reused in multiple apps.

d. Incorrect: Tools provided by Microsoft such as Visual Studio facilitate collaboration between designers and developers.

e. Correct: UX design resources provided by Microsoft consist of templates that can be used to create the conceptual design of an app.

Objective 1.2: Thought experiment

1. Design and implement loosely coupled layers. The app should be designed with loosely coupled layers to avoid dependencies between the layers that prevent the app from being enhanced in the future.

2. Use C++/WinMD components. In order to minimize the investment of time and other resources, the organization should consider reusing the C++ code through C++/WinMD components. Test infrastructure that exists for the C++ code can be reused with some modifications for testing the WinMD components.

Objective 1.2: Review

1. Correct answer: D

a. Incorrect: The business layer is meant for the implementation of application logic.

b. Incorrect: The data layer is meant for data access.

c. Incorrect: The presentation layer is meant for implementing the UI.

d. Correct: Implementing logging in a separate component enables for SOC and maximizes code reuse.

2. Correct answer: C

a. Incorrect: The presentation layer is for implementing the UI.

b. Incorrect: The data layer is meant for data access.

c. Correct: Application logic is implemented in the business layer; this is the layer that interacts with other applications.

d. Incorrect: The application manifest is to declare the capabilities and declarations only.

3. Correct answers: A, B, E

a. Correct: It is easy to build a WinMD component in C++ using Visual Studio; the legacy code can be adapted easily.

b. Correct: Windows Store apps can use WinMD components to incorporate functionality in their application layer.

c. Incorrect: C# can impose limitations that could prevent the algorithm from being implemented.

d. Incorrect: The WinRT data types and APIs available might not be adequate to implement the algorithm.

e. Correct: Unit tests written in C++ for the existing software can be used as is or with minimal change to test the C++/WinMD component.

Objective 1.3: Thought experiment

1. Reuse the data access code. The prototype app has code that has been used to access the remote web service provided by the client. You should reuse the code in the data layer as the model of the MVVM pattern.

2. Use the presentation layer. The UI of the application should be designed and implemented so that styles and other UI components available in the prototype are reused in the view of the MVVM pattern.

3. Implement business logic. The business logic for the app should be implemented in the viewmodel of the application. The viewmodel can be data bound with the view to enable loose coupling.

Objective 1.3: Review

1. Correct answer: C

a. Incorrect: The MVVM pattern encourages you to minimize code-behind to avoid strong coupling.

b. Incorrect: It is not a good idea to implement business logic in the constructor of a viewmodel.

c. Correct: The file helper class can be used on other platforms.

d. Incorrect: The data is loaded in the data model, and the viewmodel is responsible for providing the data for data binding in the view. Data should not be loaded when the page loads.

2. Correct answer: B

a. Incorrect: OneTime binding binds data when the binding is created; there are no updates possible after the binding has been constructed.

b. Correct: OneWay binding from the database to the view and then from the view to a property in the viewmodel fulfills the requirements.

c. Incorrect: TwoWay binding updates the database if any change is made by the user, thereby violating the requirements.

d. Incorrect: A command is used with an element in the UI such as a button to invoke an action (for example, to load a new photo).

3. Correct answer: B

a. Incorrect: Data binding should be used to bind collections with controls.

b. Correct: The ItemsSource property should be used to set the data context for the GridView control.

c. Incorrect: You need to create a CollectionViewSource using the data returned by the web service.

d. Incorrect: There is no need to create a custom control; GridView supports data binding.

Objective 1.4: Thought experiment

1. Search edited photos. You should implement the Search contract and the OnSearchActivated event to present the user with the photos that they have edited previously.

2. Use the Suspending and Resuming events. You should use the Suspending event to save the state of the application and restore it through the Resuming event. This will help preserve the state the app was in when the application was sent to the background by the user.

3. Save a list of most recently edited photos. A list of most recently edited photos can be saved in the application data store when the application is suspended or closed by the user. This list can be displayed when the app is launched or resumed.

Objective 1.4: Review

1. Correct answer: C

a. Incorrect: OnSearchActivated is the correct event for search activation of an app.

b. Incorrect: You can check for the ActivationKind in OnActivated and react accordingly, but OnSearchActivated should be used.

c. Correct: OnSearchActivated is the correct event for search activation of an app.

d. Incorrect: The LoadState event is used in a page of a Windows Store app to restore data from the application settings or the application data store.

2. Correct answer: A

a. Correct: ClosedByUser is a valid state of an app when it is closed by the user.

b. Incorrect: An app is in the Terminated state when the operating system terminates it due to lack of resources.

c. Incorrect: An app is in the Suspended state when it is no longer occupies the screen.

d. Incorrect: An app is in the NotRunning state when it is yet to be launched.

3. Correct answer: D

a. Incorrect: You shouldn’t restore your app if it was closed by the user.

b. Incorrect: You do not need to restore your app if it is already running.

c. Incorrect: You shouldn’t restore your app if it is resumed from suspension.

d. Correct: An app is terminated when it is in the Suspended state when the system runs low on resources. You should restore your app if it was in the Terminated state before being resumed.

Objective 1.5: Thought experiment

1. Create a custom version of the app. Because the organization requires a custom version of your app, you should create one. In the custom version, you should implement the requirements that are specific for the organization.

2. Test your app with the Windows ACK. After you finish development of your app, you should test your app’s app package with the Windows ACK.

3. Sign your app with a certificate. You should sign your app with a certificate from a known CA. This will enable the app to be sideloaded in the PCs and devices of the organization.

4. Give the app package to the IT administrators. You should give the app to the IT administrators for deployment in the PCs and devices in the organization.

Objective 1.5: Review

1. Correct answer: C

a. Incorrect: Testers of your app would not send their PCs or devices to you for installation of the app.

b. Incorrect: Users need not have the skills to install Visual Studio, compile your app’s source code, and test it.

c. Correct: An app package is the best way to distribute your app.

d. Incorrect: Windows Store apps cannot be installed using an installer prepared with a commercial tool.

2. Correct answer: C

a. Incorrect: Although you can withdraw your app, you might not be able to use the same name and publish a new version of your app.

b. Incorrect: Bug fixes should be incorporated in an update and submitted to the Windows Store for certification and approval.

c. Correct: Updates of your app go through the same approval process as your app. After approval, they are distributed through the app store.

d. Incorrect: This is not allowed by the Windows Store.

3. Correct answers: A, B, D

a. Correct: You must sign your app with a certificate whose certificate authority is trusted by the target PCs.

b. Correct: IT administrators are responsible for deploying apps in their organizations.

c. Incorrect: Sending your app by email to users is neither recommended nor permitted.

d. Correct: IT administrators can prepare a Windows image that includes your app or deploy your app in the runtime. A similar procedure should be used to distribute updates to your app.

e. Incorrect: Users will not want to part with their PCs and devices for you to install your app. Installing the app manually on every PC or device is a time-consuming and inefficient process.