You are on page 1of 200

Windows Store Apps

Development – II
Windows Store Apps Development – II
© 2014 Aptech Limited

All rights reserved.

No part of this book may be reproduced or copied in any form or by any means – graphic, electronic or
mechanical, including photocopying, recording, taping, or storing in information retrieval system or sent
or transferred without the prior written permission of copyright owner Aptech Limited.

All trademarks acknowledged.

APTECH LIMITED
Contact E-mail: ov-support@onlinevarsity.com

Edition 1 - 2014
Dear Learner,

We congratulate you on your decision to pursue an Aptech Worldwide course.

Aptech Ltd. designs its courses using a sound instructional design model – from conceptualization
to execution, incorporating the following key aspects:

¾¾ Scanning the user system and needs assessment

Needs assessment is carried out to find the educational and training needs of the learner

Technology trends are regularly scanned and tracked by core teams at Aptech Ltd. TAG*
analyzes these on a monthly basis to understand the emerging technology training needs for
the Industry.

An annual Industry Recruitment Profile Survey is conducted during August - October to


understand the technologies that Industries would be adapting in the next 2 to 3 years.
An analysis of these trends & recruitment needs is then carried out to understand the skill
requirements for different roles & career opportunities.

The skill requirements are then mapped with the learner profile (user system) to derive the
Learning objectives for the different roles.

¾¾ Needs analysis and design of curriculum

The Learning objectives are then analyzed and translated into learning tasks. Each learning
task or activity is analyzed in terms of knowledge, skills and attitudes that are required to
perform that task. Teachers and domain experts do this jointly. These are then grouped in
clusters to form the subjects to be covered by the curriculum.

In addition, the society, the teachers, and the industry expect certain knowledge and skills
that are related to abilities such as learning-to-learn, thinking, adaptability, problem solving,
positive attitude etc. These competencies would cover both cognitive and affective domains.

A precedence diagram for the subjects is drawn where the prerequisites for each
subject are graphically illustrated. The number of levels in this diagram is determined
by the duration of the course in terms of number of semesters etc. Using the precedence
diagram and the time duration for each subject, the curriculum is organized.

¾¾ Design & development of instructional materials

The content outlines are developed by including additional topics that are required for the
completion of the domain and for the logical development of the competencies identified.
Evaluation strategy and scheme is developed for the subject. The topics are arranged/organized
in a meaningful sequence.
The detailed instructional material – Training aids, Learner material, reference material, project
guidelines, etc.- are then developed. Rigorous quality checks are conducted at every stage.

¾¾ Strategies for delivery of instruction

Careful consideration is given for the integral development of abilities like thinking, problem
solving, learning-to-learn etc. by selecting appropriate instructional strategies (training
methodology), instructional activities and instructional materials.

The area of IT is fast changing and nebulous. Hence considerable flexibility is provided in the
instructional process by specially including creative activities with group interaction between the
students and the trainer. The positive aspects of Web based learning –acquiring information,
organizing information and acting on the basis of insufficient information are some of the
aspects, which are incorporated, in the instructional process.

¾¾ Assessment of learning

The learning is assessed through different modes – tests, assignments & projects. The
assessment system is designed to evaluate the level of knowledge & skills as defined by the
learning objectives.

¾¾ Evaluation of instructional process and instructional materials

The instructional process is backed by an elaborate monitoring system to evaluate - on-time


delivery, understanding of a subject module, ability of the instructor to impart learning. As an
integral part of this process, we request you to kindly send us your feedback in the reply pre-
paid form appended at the end of each module.

*TAG – Technology & Academics Group comprises of members from Aptech Ltd., professors from
reputed Academic Institutions, Senior Managers from Industry, Technical gurus from Software
Majors & representatives from regulatory organizations/forums.

Technology heads of Aptech Ltd. meet on a monthly basis to share and evaluate the technology
trends. The group interfaces with the representatives of the TAG thrice a year to review and
validate the technology and academic directions and endeavors of Aptech Ltd.
Aptech New Products Design Model

Key Aspects
1

Scanning the Evaluation of


user system Instructional
and needs Processes and
assessment Material

2 Need Analysis 6
and design of Assessment
curriculum of learning

3 Design and 5
Strategies for
development of 4 delivery of
instructional instructions
material
Preface

Windows Store Apps also known as Metro-styled Apps is a mobile app that runs on Smartphones, tablet,
computers, and other mobile devices running Windows 8 or Windows 8.1. Windows Store App is a
new application that runs on Windows 8 devices. Users can create their own apps using programming
language such as C#. Apps have one Window that supports multiple views that interact with each other.

The book, Windows Store Apps Development – II begins with creating a UI with XAML Designer. This
book introduces the working with tiles, data and files. It also allows to connect to networks and Web
services. It also covers the launching, debugging and publishing Windows Store Apps.

This book is the result of a concentrated effort of the Design Team, which is continuously striving to bring
you the best and the latest in Information Technology. The process of design has been a part of the ISO
9001 certification for Aptech-IT Division, Education Support Services. As part of Aptech’s quality drive,
this team does intensive research and curriculum enrichment to keep it in line with industry trends.

We will be glad to receive your suggestions.

Design Team
Table of Contents

Sessions
1. Creating a UI Using XAML Designer

2. Adding Personality to UI

3. Working with Tiles and Search

4. Working with Data and Files

5. Connecting to Networks and Web Services

6. Managing User Info

7. Launching, Debugging, and Publishing Windows Store App


Session - 1
Creating a UI Using XAML Designer
Welcome to the session, Creating a UI Using XAML Designer.

The session will discuss how to work with the XAML designer and use
various options such as elements and resources. The session will also
discuss the binding of data in the designer.

In this session, you will learn about:

ÎÎ Explain to work with XAML Designer elements

ÎÎ Describe how to work with resources

ÎÎ Explain the use of data binding in XAML designer

ÎÎ Describe the accessibility information for the XAML


Designer

ÎÎ Describe how to use the XAML Designer UI reference


1
Session Creating a UI Using XAML Designer

1.1 Introduction
Microsoft Visual Studio 2012 offers the XAML Designer that a user can use to design the Windows Store
Apps. Users will be able to customize User Interfaces (UIs). You could edit the XAML code in the XAML
view to customize or you could drag and drop the required controls from the Toolbox menu and modify
the properties in the Properties window.

1.2 Working with Elements in XAML Designer


The user can use the XAML Designer to add elements. The user can also modify the margin and the way
the elements are layered or aligned. They can also reset the layout of the elements apart from grouping
and ungrouping them.
Figure 1.1 shows how an XAML Designer.
Concepts

Figure 1.1: XAML Designer

V 1.0 © Aptech Limited


1
Session Creating a UI Using XAML Designer

A layout is a way of positioning and arranging the various elements of a UI. The user has to keep in mind
to arrange the elements within a layout panel.
A panel is made of StackPanel, Canvas, and a Grid. The user can use these child elements as layout
containers and position and re-arrange the elements. A Grid panel is the default top-level layout container
in a page document. They can add layout panels, other elements, and controls to the top-level page
layout.
The user can access a Visual Studio project and perform one of these steps:

ÎÎ In the Toolbox, double-click any element.

ÎÎ Drag and drop an element from the Toolbox to the Layout window

ÎÎ Select a tool from the drawing tools and draw an element.


Figure 1.2 shows the Toolbox with the controls.

Figure 1.2: Toolbox


The user can edit the XAML content to add an element to the layout.
Code Snippet 1 shows how to create a button.
Code Snippet 1:
Concepts

<Grid x:Name=”ContentPanel” Margin=”12,0,12,0”>


<Button Height=”72” Width=”160” Content=”Click Me” />
</Grid>

The user can use the <Button> element to develop a Button control. A <Grid> element is created
when a user develops a new Windows Store App.

V 1.0 © Aptech Limited


1
Session Creating a UI Using XAML Designer

ÎÎ Modifying the element’s layer order


When a user adds an element to existing layout container, the element will get placed in front of
other elements. They can use the Order command to re-arrange the elements.
yy To create a custom element layer order, drag and drop elements in the Document Outline
window.
yy To select an option listed in the artboard or Document Outline window, right-click an
element, and click Order. Following are the list of options:
ŠŠ Bring to Front: Brings the element to the top of the layering order
ŠŠ Bring Forward: Brings the element one level forward in the existing order
ŠŠ Bring Backward: Sends the element back one level in the existing order
ŠŠ Send to Back: Sends the element to the back (last level) of the layering order
yy To modify the layering order, in the Properties window, from the Layout section, edit the
ZIndex value.

ÎÎ Modifying the element’s alignment


To modify the elements alignment, the user can do the following:
1. Use menu commands
ŠŠ Select an element to be aligned. Use the Ctrl key to select multiple items.
ŠŠ In the Layout section, from Horizontal Alignment, select a property: Left, Center, Right,
or Stretch.
ŠŠ Select a property: Top, Center, Bottom, or Stretch.
2. Use snaplines
ŠŠ Drag an element to align it with other elements in a Layout with more than one
element.
ŠŠ Alignment is indicated by a boundary, a red line.

ÎÎ Modifying the element’s margin


The space surrounding an element on the artboard and between two elements is known as the
margin. The user can modify the margin by using the following:
Concepts

yy Changing the value of: Top, Left, Right, or Bottom.


yy Using the margin adorners.

V 1.0 © Aptech Limited


1
Session Creating a UI Using XAML Designer

ÎÎ Ungrouping and grouping different elements


The user can use grouping to create a new layout container and place related elements in it. The
grouping helps the user in selecting, moving, or modifying elements within a group.
To group the elements, the user should follow these steps:
1. Select the element.
2. Right-click and navigate to Group Into, select the desired layout container.
To ungroup the element, the user has to right-click and then, click Ungroup. The option just deletes the
layout containers.

ÎÎ Resetting the element’s layout


The users can use the Reset Layout command to revert the element to its default layout properties
values.

1.3 Creating and Applying a Resource in XAML Designer


The styles and properties set for a particular element are stored in a reusable entity called resources.
A resource helps to reuse the saved styles and properties of an element across multiple elements for a
consistent appearance. The steps to create a new resource are as follows:

ÎÎ Create an element using options in the Document Outline window.

ÎÎ Click the property marker, then, click Convert to New Resource in the Properties window. A
dialog box to create a resource is displayed.
Figure 1.3 shows the Create Brush Resource dialog box.

Concepts

Figure 1.3: Create Brush Resource Dialog Box

V 1.0 © Aptech Limited


1
Session Creating a UI Using XAML Designer

ÎÎ In Name text box, type the name of the resource.

ÎÎ Under Define in:


yy Select Application if you want to make the resource available to all the documents in the
application.
yy To make the resource available to the current document, click This document.
yy Select Document if you want to make the resource available only to the current document.
yy To define the resource in the resource dictionary to reuse the resource in another project,
click Resource dictionary.

ÎÎ Click OK.
To apply resource to a property or element,
yy Select the element to apply the resource.
yy To map a resource and a property, click the property marker for the property value, in the
Properties window. Click Locate Resource and then, select Available Resources.
Right-click a control and point to Edit Template. Then, select Apply Resource to apply a style or control
template resource to a control.

1.4 Binding Data in XAML Designer


Using the XAML Designer, the user can map the data binding properties. Here is an example to demonstrate
the procedure to bind data with a UI Element control.
1. Create a C# project using blank app template in Microsoft Visual Studio.
2. Add the following code in ‘MainPage.xaml.cs’ and then, build the application.
Code Snippet 2 shows the example for building the application.
Code Snippet 2:

public class Employee


{
public string Name
{
Concepts

get { return “William”; }


set { value = “William”; }
}
public string Designation

V 1.0 © Aptech Limited


1
Session Creating a UI Using XAML Designer

{
get { return “Software Developer”; }
set { value = “Software Developer”; }
}
public string Pay
{
get { return “$6000”; }
set { value = “$6000”; }
}
public string CityName
{
get { return “Texas”; }
set { value = “Texas”; }
}
}

3. From the MainPage.xaml page, click Grid. Point to the Properties window as shown in figure 1.4.

Concepts

Figure 1.4: Properties Window

V 1.0 © Aptech Limited


1
Session Creating a UI Using XAML Designer

4. In the Properties window, click Common, and then, click New as shown in figure 1.5.

Figure 1.5: Properties Window Showing Common Options


5. Under our project, select Employee, and then, click OK as shown in figure 1.6.
Concepts

Figure 1.6: Select Object Dialog Box

V 1.0 © Aptech Limited


1
Session Creating a UI Using XAML Designer

6. Add a TextBlock control from the artboard by double-clicking it from the Toolbox.
7. Select a TextBlock control, and go to its Properties window. In Properties window select Text
Binding under Common option and click Create Data Binding as shown in figure 1.7.

Figure 1.7: Create Data Binding


8. In the window, select the value(one out of the four fields, you defined earlier in code ) you want to
Concepts

display with this control, for example, here it is the Name field. Then, click OK.

V 1.0 © Aptech Limited


1
Session Creating a UI Using XAML Designer

Figure 1.8 shows the output.

Figure 1.8: Output

1.5 Accessibility Information for XAML Designer


The user can use the information given here to learn about accessibility features. These features will help
them develop apps using the XAML Designer. Keyboard shortcuts available in the Designer are grouped
broadly as: Access keys and Shortcut keys.

ÎÎ Access keys
The users can use these keys to access a menu command or any area within a dialog box. These
keys are identified by underscores.
For example, in XAML Designer, if you press Alt, an underline will appear under F in the File menu
so that you can recognize it as access key. If you press and hold Alt and then, press F, the File menu
is shown expanded. Then, press O and later, P key. A project dialog box with a list of projects is
opened.

ÎÎ Shortcut keys
Shortcut keys will speed up the users task rate. These keys reduce the time taken to do an action.
They can use these keys to perform repetitive actions such as modify a tool’s behavior, by pressing
a combination of keys.
For example, the Cut command on the Edit menu displays Ctrl+X which is the keyboard shortcut.
Concepts

ÎÎ Modifier Keys
You cannot discover certain shortcut keys that are not in the menu item.

V 1.0 © Aptech Limited


1
Session Creating a UI Using XAML Designer

Following is list of some actions and corresponding shortcut keys.


Table 1.1 lists the shortcut keys for the modifier keys.

Action Shortcut Keys


Rotate an element in increments of 15-degree While rotating the element, press and hold the
Shift key
Choose multiple elements While selecting each element, press and hold the
Shift key
Choose multiple non-adjacent elements While selecting the first and last elements, press
and hold the Shift key
Switch between open documents and windows Press, both the buttons simultaneously, Ctrl+Tab
Table 1.1: Modifier Keys

ÎÎ Project Keys
The following are the project based shortcut keys in XAML Designer.
Table 1.2 lists the project shortcut keys.

Action Shortcut Keys


To create a new project Press Ctrl+Shift+N
To open a solution or project Press Ctrl+Shift+O
To add a new item Press Ctrl+Shift+A
To build a project Press the key F6
Table 1.2: Project Keys

ÎÎ Document Shortcut Keys


Following shortcuts can be used when working with documents:
Table 1.3 lists the document shortcut keys.

Action Shortcut Keys


Switch between open documents and windows Press Ctrl+Tab
To save the active document Press Ctrl+S
To save all active documents Press Ctrl+Shift+S
Close all the documents that are currently open Press Ctrl+Shift+W
Concepts

Undo the previous action Press Ctrl+Z


Do the action again that was performed last Press Ctrl+Y
Cut the selected stuff Press Ctrl+X
Copy the selected stuff Press Ctrl+C
Paste the selected stuff Press Ctrl+V

V 1.0 © Aptech Limited


1
Session Creating a UI Using XAML Designer

Action Shortcut Keys


Delete the selected stuff Press Delete
Find the specified text (in XAML view) Press Ctrl+F
Find the specified text in next occurrence (in XAML Press F3 or Ctrl+H
view)
Table 1.3: Document Shortcut Keys

ÎÎ Elements Shortcut Keys


Table 1.4 lists the shortcuts available to work with elements on an artboard.

Action Shortcut Keys


Create an element Press Ctrl+N
Duplicate the selected element Press an arrow key by holding down Alt
Change the text in a control Press F2 or press Esc to exit
Choose a single element Press Tab if you want to select elements in the
order similar to how they appear in the document
Choose multiple elements While selecting each element, press and holds the
Shift key
Choose multiple non-adjacent elements While selecting the first and last elements, press
and hold the Ctrl key
Move chosen elements Press the arrow keys (T, For each key press, you
can increase the distance to move and this is done
by holding down the Shift key.)
Rotate an element in increments of While rotating the element, hold down the Shift
15-degree key
Choose all elements Press Ctrl+A
Clear selection of elements that were Press Ctrl+Shift+A
previously selected
To show or hide element handles Press F9
To select an element property Press Tab while the element selected, and the
focus is on Properties window
Table 1.4: Elements Shortcut Keys
Concepts

ÎÎ Document Outline Window Shortcut Keys


Table 1.5 lists the shortcuts that are available to work with elements in the Document Outline
window.

V 1.0 © Aptech Limited


1
Session Creating a UI Using XAML Designer

Action Shortcut Keys


When the focus is on the Document Outline window, Press Ctrl + H
hide the artboard objects
When the focus is on the Document Outline window, Press Shift+Ctrl+H
unhide the artboard objects
When the focus is on the Document Outline window, Press Ctrl+L
lock the artboard objects
When the focus is on the Document Outline window, Press Shift+Ctrl+L
unlock the artboard objects
Table 1.5: Document Outline Keys

1.6 XAML Designer UI Reference


The user can use the built-in visual UI in XAML Designer to design Windows Store Apps by using XAML,
WPF, and Silverlight.
The user can use the Collection Editor dialog box to add and remove items to and from a collection. The
editor is available for all the properties that have an ellipse symbol (…) in the Properties window.
Table 1.6 lists the controls.

Items Description
Items Lists all the items in the collection.
Remove item Removes the items that are selected.
Up arrow Moves the selected item up, to the top of the list, in the collection.
Down arrow The selected item are moved down to the bottom of the list in the
collection.
itemType Allows to choose the type of item that can be added to the
collection.
Add Enables to add a new item to the collection. The new item is given
a default name and added to the bottom of the list. You can edit
name and similar properties in the Properties pane.
Properties Displays the properties that you can update for the item that is
selected.
Table 1.6: Controls
The Select Object dialog box is used in the designer when they need to select a Common Language
Concepts

Runtime (CLR) type. The Select Object dialog box appears in many contexts. For example, they can use
it in the Collection Editor when they want to choose an item type.

V 1.0 © Aptech Limited


1
Session Creating a UI Using XAML Designer

Figure 1.9 shows the Select Object dialog box for a row definition opened in the Collection Editor.

Figure 1.9: Collection Details in Select Object Dialog Box


Table 1.7 lists the related items and their descriptions.

Items Description
Search box Here you can search for a CLR type by name.
Select Type list This is a tree view with which you can choose the CLR
type to match with the current property or element.
Show all assemblies All framework assemblies in the Visual Studio project
are shown with the option to include or exclude them.
Table 1.7: Items
A value converter helps the user modify data. They can create value converters using the
IValueConverter interface. When the users perform data binding, they can select a converter from
the Converter drop-down list. They can also select <Add value converter> to create a new one.
Concepts

V 1.0 © Aptech Limited


1
Session Creating a UI Using XAML Designer

Figure 1.10 demonstrates the Add Value Converter dialog box.

Figure 1.10: Add Value Converter Dialog Box

Concepts

V 1.0 © Aptech Limited


1
Session Creating a UI Using XAML Designer

1.7 Check Your Progress


1. The user can use the ____________________ command to rearrange elements.

(A) Order (C) Rearrange


(B) Sort (D) Filter

2. The user can use the ___________ to modify the margins.

(A) Margin adorners (C) Margin indents


(B) Margin rulers (D) Margin scale

3. The user can use grouping to create a ______________ and place related elements in it.

(A) New layout container (C) Artboard


(B) Interface (D) Layout

4. Identify the following that is included in a panel.

(A) Canvas (C) Document Keys


(B) Access Keys (D) Layout

5. The users can use ______________ keys to access a menu command or any area within a dialog
box.

(A) Document (C) Outline


(B) Group (D) Access
Concepts

V 1.0 © Aptech Limited


1
Session Creating a UI Using XAML Designer

1.7.1 Answers
1. A
2. A
3. A
4. A
5. D

Concepts

V 1.0 © Aptech Limited


1
Session Creating a UI Using XAML Designer

Summary
ÎÎ The user can use the XAML designer to add elements.
ÎÎ The user can also modify the margin and the way the elements are layered or aligned.
ÎÎ The styles and properties set for a particular element are stored in a reusable entity called
resources.
ÎÎ To create a custom element layer order, drag and drop elements in the Document Outline
window.
ÎÎ The users can use the Reset Layout command to revert the element to its default layout
properties values.
ÎÎ A panel is made of StackPanel, Canvas, and a Grid. The user can use these child elements as layout
containers and position and re-arrange the elements.
ÎÎ When a user adds an element to existing layout container, the element will get placed in the front
of other elements.
Concepts

V 1.0 © Aptech Limited


Session - 2
Adding Personality to UI
Welcome to the session, Adding Personality to UI.

The session will discuss how to manage information that is important to


the user. It will also discuss to use cryptography and certificates in Windows
Store App.

In this session, you will learn about:

ÎÎ Describe animating app components and Storyboarded


animations

ÎÎ Explain the key frame animations and easing function


animations

ÎÎ Define adding a splash screen

ÎÎ List guidelines for app help and app settings

ÎÎ Define displaying images, graphics, and thumbnails

ÎÎ Add app settings using XAML and add multimedia


2
Session Adding Personality to UI

2.1 Animations
List animation is used to show the inserting or deleting an item in a collection of identical items and
named for their simplest use. Animations are used in collections of other forms such as group of photos
in a grid.

2.1.1 Animating List Additions and Deletions


To make the user clear about what has happened, animations gives for the entry or exit a polish visual
transition of the new items. While an ‘add’ animation, present items go out of their position to provide space
for the new entry. The new entry then, comes into the place, by updating as it fades in. In the reverse manner,
a ‘delete’ animation works. The createAddToListAnimation, createDeleteFromListAnimation,
createAddToSearchListAnimation, and createDeleteFromSearchListAnimation are the
APIs consisted by set of animations.

2.1.2 Animating Edge-based UI


Edge-based UI animations originate from the edge of the screen, so use these animations to show or hide
UI. The animations which use PaneThemeTransition are mainly for use on custom controls. These
existing controls such as AppBar and CommandBar have library animations for edge UI built-in. This
animated behaviour can be simply made available by including such controls in your UI.
Two types of edge-based elements with their own set of animation APIs are as follows:
1. Edge UI - This animation can be used with smaller edge-based UI which is intended to animate a
custom control. This is similar in behavior to AppBar or CommandBar.
2. Pane UI - This animation can be used with larger edge-based UI which covers most of the app
window. For example, soft keyboard.

2.1.3 Animating Fades


Fade animations can be used to see an item. Based on different scenario, fade animations can be
categorized into three types:

ÎÎ Fade in

ÎÎ Fade out
Concepts

ÎÎ Crossfade
Using FadeInThemeAnimation and FadeOutThemeAnimation methods, the XAML animation library
implements these animations.

V 1.0 © Aptech Limited


2
Session Adding Personality to UI

ÎÎ Fade in
Fade in animation is used to place an item into place. Fade in animation can be viewed in the app
bar, where new controls can appear as the result of user interaction. While transiting from an
appeared item to the real item, fade in animation also can be used. Here, content dynamically
loads or shows a custom tooltip or dialog control.

ÎÎ Fade out
To delete an item, the fade out animation can be used. For example, in transient controls such as
scroll bar or panning indicator, which are faded out after some time is lost and no input has been
identified.

ÎÎ Cross fade
Fade in and fade out animations can be simultaneously used to carry out a substitution of an existing
item with an entering item. While animating the existing items fades away as the replacement
items fades into the same space.

2.1.4 Animating Pop-up Elements


To show and hide popup UI, the popup animations can be used. This includes context menus and flyouts.
When user performs a click action, the Popup elements appear and are dismissed if the user taps or clicks
outside of the popup element. The Popup, Flyout, and MenuFlyout elements in XAML, have built-in
library animations and need not add any behavior.
The animations that are relevant for popup behavior are as follows:

ÎÎ PopInThemeAnimation

ÎÎ PopOutThemeAnimation

ÎÎ PopupThemeTransition

2.1.5 Animating Page Transitions


To transit between pages within an app or to display the first page of a newly launched app, the page
transition animations are used. Following APIs are consisted by the set of animations:

ÎÎ
Concepts

enterPage

ÎÎ exitPage

V 1.0 © Aptech Limited


2
Session Adding Personality to UI

Following are the points which help you to know about animations:

ÎÎ Outgoing objects

ÎÎ Incoming objects

ÎÎ How far and from which angle the incoming content is entering

2.1.6 Animating Content Transitions


Keeping the container or background constant, you can alter the area content of the screen using content
transition animations. As it fades in, new content comes on the screen slides in from an offset. If it
is required to replace the existing content, then the earlier content should be faded out as the latest
content is getting in. Following APIs are consisted by the set of animations:

ÎÎ enterContent

ÎÎ exitContent
It is not mandatory that original content and the replacement content need not have the same layout or
size.
Following are the points which help to know about animations:

ÎÎ Outgoing objects

ÎÎ Incoming objects

ÎÎ How far and from which angle the incoming content is entering

2.1.7 Animating Pointer Clicks


To provide visual feedback, press an item, the pointer animations are used. When a user presses an
object, the animation of the item slightly shrinks to indicate that it is pressed. When the tap or click is
released, the pointer up animation is played and to indicate that it has been released the animation
replaces the object to its actual size.
Following APIs are consisted by the set of animations:
Concepts

ÎÎ pointerUp

ÎÎ pointerDown

V 1.0 © Aptech Limited


2
Session Adding Personality to UI

2.1.8 Animating Repositions


To move an element or elements into a new position, the reposition animations such as
RepositionThemeAnimation or RepositionThemeTransition are used.
Animating repositions in default Windows Runtime control behavior are progress bar which uses
RepositionThemeAnimation in a VisualTransition to its ‘Determinate’ state. It also consists of
ToggleSwitch which uses RepositionThemeAnimation in several VisualTransition instances
for different state transitions.

2.1.9 Animating Drag and Drop Sequences


Drag and drop animations are required to place user objects when they move it with their fingers, or with
an input device. Moving a single item in a list and placing one item on other is a common drag and drop
actions.

Note - When the user is moving the object, use the drag and drop animations otherwise use the
reposition animations.
Following APIs are consisted by the set of animations:

ÎÎ DragItemThemeAnimation

ÎÎ DropTargetItemThemeAnimation

ÎÎ DragOverThemeAnimation

ÎÎ Drag Start
With a drag start (DragItemThemeAnimation), every drag and drop animation sequence begins.
This animation customizes the look of the Drag Source and affected objects.
Figure 2.1 shows the drag object and its next objects before the user drag the object.

Concepts

Figure 2.1: Drag Objects

V 1.0 © Aptech Limited


2
Session Adding Personality to UI

When the object is selected and it is dragged, the affected objects become smaller and the dragged
object becomes larger as shown in figure 2.2.

Figure 2.2: Affected Objects


Figure 2.3 shows the next objects that are not changed and remains stable.

Figure 2.3: Unchanged Objects

ÎÎ Drag End
With the drag end animation (DropTargetItemThemeAnimation), drag and drop animation
sequence ends. Once the Drag Start animation is used, the Drag End animation is used to end it.
The same affected object is used to call DragItemThemeAnimation. Figure 2.4 shows the effect
of the drag source to its changed item in the end of drag animation.
Concepts

Figure 2.4: Effect of the Drag Source

V 1.0 © Aptech Limited


2
Session Adding Personality to UI

In the first image, it is shown that before a user drops an object in a set of changed item. The drag
object becomes larger than its normal size, and aligned down from the list. The affected objects
become smaller than their original size.
Figure 2.5 shows the Drag Source is larger and aligned down from the affected objects, and these
are in their original size.

Figure 2.5: Aligned Drag Source


When the Drag Source is dropped, all the affected objects return to their normal size and also
repositioned if necessary as shown in figure 2.6.

Figure 2.6: Normal Position of Drag Source

ÎÎ Drag Between
When it is required by the user to drag an item in the two other objects, then the Drag Between
animation (DragOverThemeAnimation) is used. In this animation, when the user drops the Drag
Source in required position, the affected objects will move aside to make space for the Drag Source.
Concepts

V 1.0 © Aptech Limited


2
Session Adding Personality to UI

In the following images, the movement of the affected objects with respect to the drag source is
shown.
Figure 2.7 shows that before a user triggers Drag Source into a set of affected objects, enter
animation is used.

Figure 2.7: Drag Source Using Enter Animation


Figure 2.8 shows the Drag Source has triggered the Drag Between animation and has placed the
two objects on both the side of the Drag Source to place apart.

Figure 2.8: Effect of Enter Animation


Concepts

The drag and drop animations in behavior of Windows Runtime control consist of ListViewItem
and GridViewItem templates which define visual states for drag and multidrag.

V 1.0 © Aptech Limited


2
Session Adding Personality to UI

2.1.10 Animating Swipe Gestures


For the selecting an item, when you implement the Windows 8 touch selection model, use swipe
animations such as SwipeHintThemeAnimation and SwipeBackThemeAnimation.
For XAML swipe animations, the ListView and GridView controls are included. They are as follows:

ÎÎ Swipe Hint
The swipe hint animation (SwipeHintThemeAnimation) supports the user. When the items is
pressed and hold by a user, which supports the swipe interaction, the animation presses the object
down and brings it back up, conveying that the item supports the swipe interaction.

ÎÎ Swipe Select
The XAML will not have a swipe select animation, since selection is performed by different models.
This each has its self visual simile that will not involve animation.

ÎÎ Swipe Deselect
When the user drags a present selected object and wants to deselect it or release the item, then
the swipe deselect animation is used. This swipe deselect animation deletes the chosen identifier
from the object and moves the object to its rest position.
The swipe gesture animations in behavior of Windows Runtime control consist of ListViewItem and
GridViewItem which defines visual states for selection hinting.

2.2 Storyboarded Animations


To change the value of a dependency properties as a function of time, a storyboarded animation method
is used. Defining the visual position for a control, as part of a page definition is the main reason for the
need of a storyboarded animation.

ÎÎ Defining Storyboarded Animations


As a function of time, a storyboarded animation is a method to change the value of a property.
The animating property is not always a property which directly changes the UI of the app. XAML
is used for defining UI for an app, which is an animated UI-related property. For example, angle of
RotateTransform can be animated or the color value of a button’s background can be animated.
Being an author of a control, you are defining the visual states. This is the main reason for defining
Concepts

a storyboarded animation.

V 1.0 © Aptech Limited


2
Session Adding Personality to UI

Following example demonstrates the Opacity property is animated on a particular Rectangle


object.
Example: XAML

<!-- Use this code to animate the rectangle’s opacity. -->


<Storyboard x:Name=”mynewStoryboard”>
<DoubleAnimation
Storyboard.TargetName=”MynewAnimatedRectangle”
Storyboard.TargetProperty=”Opacity”
From=”1.0” To=”0.0” Duration=”0:0:1”/>
</Storyboard>
// in a different area of XAML
<Rectangle x:Name=”MynewAnimatedRectangle”
Width=”302” Height=”202” Fill=”Green” />

2.3 Key Frame and Easing Function Animations


Different techniques for key frame animations are as follows:
1. Key frame of linear animations
2. KeySpline value’s key frame animations
3. Easing functions
Creating a storyboarded animation is bit difficult and from initial to a last state, uses a non-linear animation
behavior.

ÎÎ Animating Using Key Frame Animations


Sometimes, multiple target value which is approached at a point along the animation timeline
permits key frame animations. In this, each key frame specifies a different intermediate value and
the final animation value is the last key frame reached. Animations can be made more complex by
specifying multiple values. The implemented key frame subclass per animation type is enabled by
key frame animations.
For specifying its key frames, each and every key frame animation type has an Easing, Spline,
Concepts

Linear, and Discrete variation of its KeyFrame class. For example, key frames to declare an
animation that targets a Double and uses key frames such as DiscreteDoubleKeyFrame,
LinearDoubleKeyFrame, SplineDoubleKeyFrame, and EasingDoubleKeyFrame. Any one
or all of these types can be used within a single KeyFrames collection.
The Timeline based properties can be set on a key-frame animation.

V 1.0 © Aptech Limited


2
Session Adding Personality to UI

Table 2.1 lists the key frame animations.

Key frame Description


AutoReverse Frames are repeated in reverse order
BeginTime Delays the start of the animation
FillBehavior Controls when the last key frame is reached
RepeatBehavior If set to Forever, infinitely, the key frames and their timeline repeat.
Timeline repeats specified times, if set to an iteration count. The timeline
repeats until the specified time is reached, if set to a Duration
Table 2.1: Key Frame Animations

ÎÎ Linear key frames


Until the frames KeyTime is reached, the linear key frames provides a simple linear interpolation
of the value.
Following example shows use of linear key frames to scale the appeared height of a rectangle.
Example: XAML

<StackPanel1>
<StackPanel1.Resources>
<myStoryboard x:Name=”mynewStoryboard”>
<DoubleAnimationUsingKeyFrames
Storyboard.TargetName=”mynewRectangle”
Storyboard.TargetProperty=”(UIElement.RenderTransform).
(ScaleTransform.ScaleY)”>
<LinearDoubleKeyFrame Value=”1” KeyTime=”0:0:0” />
<LinearDoubleKeyFrame Value=”1.2” KeyTime=”0:0:4” />
<LinearDoubleKeyFrame Value=”2” KeyTime=”0:0:5” />
</DoubleAnimationUsingKeyFrames>
</myStoryboard>
</StackPanel1.Resources>
</StackPanel1>
Concepts

In this example, for the first four seconds, linearly operates an animation in which the height of the
rectangle gets increased slightly. For the last second, scales rapidly till the rectangle is two times
the starting height.

V 1.0 © Aptech Limited


2
Session Adding Personality to UI

ÎÎ Discrete key frames


Any interpolation is not used by the discrete key frames, however a new Value is simply applied
when a KeyTime is reached. When UI property is being animated, it often produces an animation
which appears to ‘jump’. Since, this is aesthetic and the apparent jumps can be minimized by
increasing the number of key frames. If a smooth animation is your intention, then instead of using
key frames, better use linear or spline.

ÎÎ Easing key frames


Interpolation can be being applied in easing key frame in which the interpolation is controlled by
some predefined mathematical formulas. You can actually produce almost same result with a spline
key frame compared to easing function types, still some of the easing functions with which cannot
reproduce with a spline such as BackEase. Set the EasingFunction property to implement an
easing function to an easing key frame as a property element in XAML.

2.4 Adding a Splash Screen


By using Microsoft Visual Studio 2012, set your apps splash screen image and background color.

2.4.1 Prerequisites
Using Visual Studio 2012 quickstart can be done.

2.4.2 Setting the Splash Screen Image and Background Color


When you create the app using Visual Studio 2012 template, a default image is added to the project and
it is set as the splash screen image. By default, a light gray background color applies to the splash screen.
Following steps to be used to change the default image or color of the apps splash screen:
1. In Visual Studio 2012, open your existing Windows Store App project.
2. Open the ‘Package.appxmanifest’ file in the Solution Explorer. Also, this file can be opened from
the menu bar by choosing Project  Store  Edit App Manifest.
3. From the All Image Assets pane on the left of the ‘Package.appxmanifest’, click the Visual Assets
tab and select Splash Screen.
4. Press the button with an ellipsis to select a new splash screen image. When you press the
belowScaled, assets it will appear next to 620 x 300 px label.
Concepts

5. Set the background color displayed with the splash screen image in the Background Color field of
the Splash Screen section. Either the color name or ‘#’ and the hex value of a color can be entered
in this field.

V 1.0 © Aptech Limited


2
Session Adding Personality to UI

2.4.3 Creating an Extended Splash Screen Page


Splash screen can be displayed by creating an extended splash screen for the app. When your app is
launched, the enlarged screen follows the splash screen shown by Windows which can be modified.

ÎÎ 620 x 300 pixel image size should be used by the enlarged splash screen page.

ÎÎ The enlarged splash screen should use a background color which is specified for the splash screen
in the app manifest.

ÎÎ To position the apps splash screen image, the code should use the SplashScreen class. This
should happen at that screen coordinates in which Windows positions the image while displaying
the splash screen.

ÎÎ Using the SplashScreen class to reposition items on the enlarged splash screen, the code should
respond to window resize events.
Following are the steps to create an enlarged splash screen:
Step 1: Adding a Blank Page item to your existing app
yy In Visual Studio 2012, open your app.
yy In the menu bar, press or open Project and click Add New Item. Now, an Add New Item
dialog box will appear.
yy From this Add New Item dialog box, add a new Blank Page to your app. Two files are
generated by adding a Blank Page item and they are as follows:
1. For markup (ExtendedSplash.xaml)
2. For code (ExtendedSplash.xaml.cs).
Step 2: Essential XAML for an extended splash screen
Following are the steps to add an image and progress controls to the extended splash screen:
yy By default, the splash screen color is a light gray. Change the default Grid element of
Background property to match the background color for the apps splash screen in the app
manifest.
yy To the Grid element, add a Canvas element. To position your enlarged splash screen
image, the Canvas will be used.
Concepts

yy To the Canvas, add an Image element. For the enlarged splash screen, use the 600 x 320
pixel image which you select for the splash screen displayed by Windows.

V 1.0 © Aptech Limited


2
Session Adding Personality to UI

To define Canvas and Image elements, add the following example:


Example: XAML
<Grid Background=”#464846”>
<Canvas>
<Image x:Name=”extendedSplashScreenImage” Source=”Assets/
SplashScreenImage.png”/>
<ProgressRing Name=”splashProgressRing” IsActive=”True” Width=”20”
HorizontalAlignment=”Center”></ProgressRing>
</Canvas>
</Grid>

The ProgressRing control is added to ExtendedSplash.xaml. Width is set to 20 pixels of the


ProgressRing and also manually width can be set to a value.
Step 3: Extended splash screen class essential code
Whenever the size of the window or orientation alters, the enlarged splash screen has to respond.
For the good look of the enlarged splash screen, the position of the image which you use must be
updated.

2.4.4 Modify the Launch Activation Handler


To the launch activation event handler of the app, the system passes splash screen information, when
your app is launched. To position image correctly, this information can be used on the enlarged splash
screen page. The activation event arguments are passed to the apps OnLaunched handler and from here
you can get this splash screen information.

ÎÎ Creating and displaying an extended splash screen


Add the following example in App.xaml.cs.
Example: C#

protected override void OnLaunched(LaunchActivatedEventArgs args)


{
if (args.PreviousExecutionState != ApplicationExecutionState.Running)
Concepts

{
bool loadStatestatus = (args.PreviousExecutionState ==
ApplicationExecutionState.Terminated);
ExtendedSplash = new ExtendedSplash(args.SplashScreen, loadStatestatus);

V 1.0 © Aptech Limited


2
Session Adding Personality to UI

Window.Current.Content = extendedSplash;
}
Window.Current.Activate();
}

2.5 Adding Guidelines for App Help and Settings


Following guidelines explain to design effective Help content for the app. In single page, Help content can
be written which should include text, links, and images. If a dynamic Help content to be provided, then
connect to a support Website or add an online page in the Help section.
Do’s and Don’ts

ÎÎ The Settings flyout can be used to display the Help content.

ÎÎ From the Settings pane, allow users to access Help content.

ÎÎ To clearly identify it, label the entry point in the Settings pane as, ‘Help’.
1. Guidelines for Help Settings
yy Help page should be short and simple to refer.
yy If Help content will not be suitable on a single page or if it is required to include dynamic
content, then connect to a support Website or add an online page in the Help flyout.
While creating Help content, following are some things to prevent:

ÎÎ From the Help entry points, don’t directly link to a Website. In place of this, link to online content
in the connected Help flyout.

ÎÎ Avoid using technical and complex terms.

ÎÎ Help should be provided for quick, basic reference not for every feature in the app.

ÎÎ Help should not be used to notify availability of newer version of the app.
2. Guidelines for App Settings
Concepts

For every Windows Store App, Windows provides a Settings pane by default. Each entry point
displays the Settings options themselves and it opens a Settings flyout. In this section, you will learn
the good practices to create and display app settings.

V 1.0 © Aptech Limited


2
Session Adding Personality to UI

Do’s and Don’ts

ÎÎ In the Settings pane, create entry points for all the app settings.

ÎÎ Number of settings should be kept minimum, simple, and define smart defaults.

ÎÎ If required, then link from app’s UI elements to the settings pane.

ÎÎ As soon as the user changes a setting, immediately the change should be reflected by the app.

2.6 Displaying Images, Graphics, and Thumbnails


Shape and Geometry are the two sets of classes which defines a region of space in XAML UI. Shape has
a brush associated with it whereas Geometry simply defines a region of space. The Shape class includes
Line, Ellipse, Rectangle, Polygon, Polyline, and Path. The Geometry class define the parts of
a Path.

ÎÎ Scenarios for Shapes


For a UI control, a shape can be used for the XAML template definition of UI. For focusable controls,
Rectangle shape is used to show a visible focus indicator, so it is seen in many control templates.
Just like controls, panels, and other elements, the Path element can be placed in a XAML UI.

ÎÎ Fill and Stroke for Shapes


A Brush is required for a Shape to depict to the app canvas by setting the Fill property of the
Shape. Stroke is a line and it is drawn encircling the shape’s perimeter that requires a Brush
which defines its appearance. It should have a non-zero value for StrokeThickness.

ÎÎ Ellipse
By specifying a Width, Height, and a Brush for the Fill, a basic Ellipse can be created.
The following example creates an Ellipse whose Width is of 200 and a Height is of 200, and
Fills with SolidColorBrush as colored using SteelBlue.
Example: XAML

<Ellipse Fill=”Blue” Height=”210” Width=”210” />


Concepts

ÎÎ Rectangle
A Rectangle has a four sides’ shape whose opposite sides are equal. By specifying a Width, a
Height, and a Fill, a basic Rectangle can be created. A Rectangle corners can be rounded. By
specifying a value for the RadiusX and RadiusY properties, a round cornered rectangle can be
created.

V 1.0 © Aptech Limited


2
Session Adding Personality to UI

The following example creates a Rectangle whose Width is of 210 and Height is of 110. For
its Fill it uses a Blue value of SolidColorBrush and for its Stroke it uses a Black value of
SolidColorBrush. StrokeThickness is set to 4. The RadiusX property is set to 60 and the
RadiusY property is set to 20, to get Rectangle rounded corners.
Example: XAML
<Rectangle Fill=”SteelBlue”
Width=”210”
Height=”110”
Stroke=”Green”
StrokeThickness=”4”
RadiusX=”60”
RadiusY=”12” />

ÎÎ Line
A Line is simply a line which connects two points. For a Line, values for the Stroke and
StrokeThickness properties should be mentioned. Instead of using a Point values to specify a
Line shape, you use discrete Double values for X1, Y1, X2, and Y2.

ÎÎ Stretching an Image
By default, the Width or Height of the image is displays specified by the Source. Using the
Stretch property, image is filled by the containing area. Following are the Stretch properties
which accept the values, as shown in table 2.2.

Stretch Property Description


None Image does not stretch to fill the output dimensions
Uniform Image is updated to make it suitable for the output dimensions
UniformToFill Preserves its original aspect ratio as the image is updated to fill the
output area
Fill Image is updated to make it suitable for the output dimensions
Table 2.2: Stretch Property
Concepts

ÎÎ Cropping an Image
Clip property is used to trim off an area from the output by setting the Clip property to Geometry.
The following example shows how to use a RectangleGeometry as the clip region for an image.
Here, it is defined an Image object with a Height of 200.

V 1.0 © Aptech Limited


2
Session Adding Personality to UI

XAML

<Image Source=”test.jpg” Height=”220”>


<Image.Clip>
<RectangleGeometry Rect=”26,26,110,152” />
</Image.Clip>
</Image>

2.7 Adding App Settings Using XAML


Using the XAML SettingsFlyout control, the settings are modified to your app’s settings pane. If it is
not modified, then the user can use a default Settings pane. This system provided Settings pane that
contains a Permissions link as well as six system settings, including volume, network information, and
power.

ÎÎ Prerequisites
yy Microsoft Visual Studio 2012
yy Windows 8

2.8 Adding Multimedia


You will learn to use audio and video in the Windows Store App using C#.

ÎÎ Capturing or rendering audio, video, and images


1. Capture photos and videos from a capture device, such as camera, Webcam.
2. Render audio streams in a Windows Store App using C#.
Step 1: Setting the device capability in the app manifest file
The app must include the Webcam DeviceCapability in the application manifest to enable
Webcam access.
1. From Solution Explorer in Microsoft Visual Studio, open the designer.
2. Click Capabilities.
Concepts

3. Check the box for Webcam.


Step 2: To Create a CaptureElement to render video
In Extensible Application Markup Language (XAML), create a CaptureElement which is used to
display the video as shown in the example.

V 1.0 © Aptech Limited


2
Session Adding Personality to UI

Example:
XAML

<CaptureElement Name=”captureView” Height=”420” />

Step 3: To create the MediaCapture object


Managing the captured video is contained by the MediaCapture class. It is required to use
InitializeAsync and StartPreviewAsync to capture video from a camera and preview it.
The following example instantiates a new MediaCapture object. To initialize the MediaCapture
object to the default settings, it calls InitializeAsync.
Example:
C#

MediaCapture captureManager = new MediaCapture();


await captureManager.InitializeAsync();

Step 4: To start the video preview


Set the CaptureElement.Source to the MediaCapture object and start the preview using
StartPreviewAsync as shown in the example.
Example:
C#

// The following code snippet starts the capture preview.


// capturePreview is a CaptureElement defined in XAML.
capturePreview.Source = captureManager;
await captureManager.StartPreviewAsync();

2.8.1 Playing and Previewing Audio and Video


By using a MediaElement, play audio and video media in the Windows Store App using C# code.

ÎÎ MediaElement Basics
By creating a MediaElement object in XAML, add media to your app. Then, set the Source to a
Uniform Resource Identifier (URI) which points to an audio or video file.
Concepts

V 1.0 © Aptech Limited


2
Session Adding Personality to UI

Table 2.3 lists the MediaElement properties.

Property Description
AutoPlay It indicates whether the MediaElement initiate playing
automatically. By default, it displays true.
IsMuted It indicates whether the volume is muted. By default, it
displays false.
IsFullWindow Present in Windows 8.1.
IsFullWindow property should be used to enable
and disable full window rendering.
AreTransportControlsEnabled Present in Windows 8.1. It allows or blocks the built in
transport controls.
Volume It indicates the audio volume. The range varies from 0
to 1.
Balance It indicates the ratio of stereo speaker’s volume. The
range varies from -1 to 1.
Stretch Present in Windows 8.1.
How the MediaElement fills the space of the container
is defined by the MediaElement.Stretch property.
The Stretch states are similar to settings pictures on
many TV sets. You can allow the user to choose their
own setting.
Table 2.3: MediaElement Properties

ÎÎ Controlling Media Playback


For controlling the media playback, some of the built in transport controls are present in Windows
8.1. Set the AreTransportControlsEnabled to true to enable the built in transport controls.
This is the easiest way to control the MediaElement playback.
Some media-specific properties are provided by the MediaElement object. Some of the media-
specific events are provided by the MediaElement object.

2.8.2 Processing Image Files and Transcoding


Decode images and editing the pixels and metadata took place by Windows.Graphics.Imaging
Concepts

namespace. The result can be encoded in various formats.


Video files transcode from one format to another by the Windows.Media.Transcoding API.
Transcoding means the conversion of audio file or video from one format to another. It happens by
decoding and then, re-encoding the file.

V 1.0 © Aptech Limited


2
Session Adding Personality to UI

You will learn to transcode a video file to MP4 format. It explains how to open a video file from the system
to use the FileOpenPicker class, and then, transcode the MediaTranscoder class to video file to the
MP4 format.
1. Create new project
Create a blank Windows Store App using C# by initiating.
2. Selecting a source file and creating a destination file
To select a source file, use the FileOpenPicker and to create the destination file, use the
FileSavePicker class. Then, set the SuggestedStartLocation and FileTypeFilter
properties on the FileOpenPicker. On the FileSavePicker object, set the
SuggestedStartLocation, DefaultFileExtension, SuggestedFileName, and
FileTypeChoices properties as shown in the example.
Example:
C#

async void TranscodeVideoFilenew()


{
Windows.Storage.StorageFile src;
Windows.Storage.StorageFile dest;
var opennewPicker = new Windows.Storage.Pickers.FileOpenPicker();
opennewPicker.SuggestedStartLocation = Windows.Storage.Pickers.
PickerLocationId.VideosLibrary;
opennewPicker.FileTypeFilter.Add(“.wmv”);
opennewPicker.FileTypeFilter.Add(“.mp4”);
src = await opennewPicker.PickSingleFileAsync();
var savenewnewPicker = new Windows.Storage.Pickers.FileSavePicker();
savePicker.SuggestedStartLocation =
Windows.Storage.Pickers.PickerLocationId.VideosLibrary;
savenewPicker.DefaultFileExtension = “.mp4”;
savenewPicker.SuggestedFileName = “New Video”;
savenewPicker.FileTypeChoices.Add(“MPEG4”, new string[] { “.mp4” });
Concepts

dest = await savenewPicker.PickSaveFileAsync();


//This function performs transcoding
TranscodeFile(src, dest);
}

V 1.0 © Aptech Limited


2
Session Adding Personality to UI

3. Create an encoding profile


The settings that determine how the destination files will be encoded that are contained by the
encoding profile. A set of predefined encoding profiles are provided by the Windows.Media.
MediaProperties namespace are as follows:
yy The AAC audio (M4A), MP3 audio, and Windows Media Audio (WMA) profiles contain audio
only. The MP4 video (H.264 video plus AAC audio) and Windows Media Video (WMV)
contain video and audio.
The following example shows how to create a profile for MP4 video.
Example:
C#

MediaEncodingProfile encodeprofile =
MediaEncodingProfile.CreateMp4(VideoEncodingQuality.HD720p);
MediaTranscoder medtranscoder = new MediaTranscoder();

The static CreateMp4 method creates an MP4 encoding profile whose parameter gives the target
resolution for the video. In the example, 1280 x 720 pixels is the VideoEncodingQuality.hd720p
at 30 frames per second.
By using the Windows.Media.MediaProperties.MediaEncodingProfile.
CreateFromFileAsync method, a profile can be created which matches an existing media file.
4. Transcode the file
To create a new MediaTranscoder object, transcode the file, then call the MediaTranscoder.
PrepareFileTranscodeAsync method. Now, pass in the encoding profile, the destination file,
and the source file. Then, call the TranscodeAsync function on the PrepareTranscodeResult
object.
Concepts

V 1.0 © Aptech Limited


2
Session Adding Personality to UI

2.9 Check Your Progress


1. Fade in, fade out, cross fade are the types of ______________.

(A) Animating List (C) Animating Fades


(B) Edge-Based UI (D) All of these

2. _________________ animation can be used with smaller edge-based UI which is intended to
animate a custom control.

(A) Pane UI (C) Edge-based UI


Animating Pop-up (D) Edge UI
(B)
Elements

3. _____________________ can be used to transit between pages within an app or to display the
first page of a newly launched app.

Animating Pop-up (C) Edge-based Animation


(A)
Elements
(B) Animating Fades (D) Page Transition Animations

4. _______________ are used to provide visual feedback press on an item.

(A) Pointer Animations (C) Animating Fades


Animating Pop-up (D) Edge-based Animation
(B)
Elements

5. ___________________ are required to place users objects when they move it with their fingers,
or with an input device

Drag and Drop (C) Animating Pop-up Elements


(A)
Animations
(B) Pointer Animations (D) Animating Fades


Concepts

V 1.0 © Aptech Limited


2
Session Adding Personality to UI

2.9.1 Answers
1. C
2. D
3. D
4. A
5. A
Concepts

V 1.0 © Aptech Limited


2
Session Adding Personality to UI

Summary
ÎÎ List animation is used to show the inserting or deleting an item in a collection of identical items
and named for their simplest use.
ÎÎ Fade animations can be used to view an item or take items out of a view.
ÎÎ The popup animations can be used to show and hide popup UI.
ÎÎ To provide visual feedback of pressing an object, the pointer animations are used.
ÎÎ Animating repositions in default Windows Runtime control behavior are progress bar which uses
RepositionThemeAnimation in a VisualTransition to its ‘Determinate’ state.
ÎÎ With the drag end animation (DropTargetItemThemeAnimation), for drag and drop animation
sequence ends.
ÎÎ When the user drags a present chosen object and wants to deselect it or release the item then,
the swipe deselect animation is used.
ÎÎ The static CreateMp4 method creates an MP4 encoding profile whose parameter gives the target
resolution for the video.

Concepts

V 1.0 © Aptech Limited


Session - 3
Working with Tiles and Search
Welcome to the session, Working with Tiles and Search.

The session will discuss how to work with the Tiles and Badges in addition
to creating and delivering notifications. The session will also discuss about
adding a search to an App.

In this session, you will learn about:

ÎÎ How to create Tiles and Badges

ÎÎ How to pin Secondary Tiles

ÎÎ Describe how to send and deliver notifications

ÎÎ Explain how to troubleshoot tile, toast, and badge


notifications

ÎÎ Describe how to create search


3
Session Working with Tiles and Search

3.1 Working with Tiles, Badges, and Toast Notifications


A tile is nothing but a rectangle or square icon representing the App on the Start screen of Windows 8.
Besides launching an App, it can also be used to display content screens associated with the app. For
example, the tile of a finance app will show a screen shot of major stock market indexes. The tiles that
are showing dynamic data are known as ’live tiles’.
Badges are displayed on tiles to indicate an App’s status or state. The user can set the badge to show a
small image (glyph) or a number, based on the data the user want to convey.
Toast notifications are app specific pop-up messages send to the user. It is displayed when the user is
using another application or on the desktop.

3.1.1 Creating Tiles and Badges


Following are the steps involved in creating a default tile:
1. Start a new Windows Store App in Visual Studio 2012.
2. Open Package.appxmanifest in Solution Explorer by double-clicking it.
Figure 3.1 shows the Solution Explorer with the Package.appxmanifest file.
Concepts

Figure 3.1: Package.appxmanifest File

V 1.0 © Aptech Limited


3
Session Working with Tiles and Search

3. Go to Application UI tab in Package.appxmanifest.


4. In the Application UI, scroll down to Tile and click Logo. Browse to select images for default tile
(image size being 150x150). Click Wide Logo. Browse to select wide logo image for default tile (image
size being 310*150).
Instead of image, you can set the title color by selecting a background color. You can also set the
name of the title by using the Short Name option.
5. Run the application and go to Start screen to see the default tile created.
Figure 3.2 shows the Windows 8 Start screen with the newly created tile.

Figure 3.2: Windows 8 Start Screen

ÎÎ Sending a Tile update:


The three main processes involved in sending a tile update are as follows:
Concepts

yy Create a tile updater component for the application.


yy Create the XML document for the notification. This is done by retrieving the XML document
of one of the templates available and then, alter its DOM.
yy Create a Tile Notification object from the XML of the tile and use it to update the tile.

V 1.0 © Aptech Limited


3
Session Working with Tiles and Search

Following are the steps to send an update to a tile:


1. Use the following namespace:
using Windows.UI.Notifications;
using Windows.Data.Xml.Dom;
2. You can select a template from the catalog provided in the system that suits the layout needs
of our content. In this example, you are going to use TileWide310x150ImageAndText01
template, which needs one image and text.
Example:

XmlDocument myTileXml =
TileUpdateManager.GetTemplateContent(TileTemplateType.
TileWide310x150
ImageAndText01);

This code retrieves the XML content using the GetTemplateContent method. Code Snippet
1 is the retrieved XML code.
Code Snippet 1:

<tile>
<visual version=”2”>
<binding template=”TileWide310x150ImageAndText01”
fallback=”TileWideImageAndText01”>
<image id=”1” src=””/>
<text id=”1”></text>
</binding>
</visual>
</tile>

3. Code Snippet 2 retrieves all the elements in the XML template with the tag name ‘text’.
Code Snippet 2:

XmlNodeList myTextAttributes = MyTileXml.


GetElementsByTagName(“text”);
Concepts

myTextAttributes[0].InnerText = “This is notification #3”;

The TileWide310x150ImageAndText01 template has a single text attribute and it is assigned


a required string.

V 1.0 © Aptech Limited


3
Session Working with Tiles and Search

4. Following code retrieves all elements with a tag name ’image’.


The TileWide310x150ImageAndText01 contains a single image tag and it is assigned image
as in Code Snippet 3.
Code Snippet 3:

XmlNodeList myImageAttributes = myTileXml.


GetElementsByTagName(“image”);
((XmlElement) myImageAttributes[0]).SetAttribute(“src”, “ms-appx:///
images/blueWide.png”);
((XmlElement) myImageAttributes[0]).SetAttribute(“alt”, “red
graphic”);

5. It is always best practice to use both square and wide version of tile notification as the user
may resize the tile at any time. Code Snippet 4 uses both versions of tile notification.
Code Snippet 4:

XmlDocument newSquareTileXml = TileUpdateManager.


GetTemplateContent(TileTemplateType.TileSquare150x150Text04);
XmlNodeList newSquareTileTextAttributes = newSquareTileXml.
GetElementsByTagName(“text”);
newSquareTileTextAttributes[0.AppendChild(
newSquareTileXml.CreateTextNode(”This is notification#3”));

Then, to the wide tile’s payload, add the medium tile. The user then, retrieves the binding
element, which defines the medium tile in the newSquareTileXml payload. This binding
element is then, appended as a sibling of the wide tile. Code Snippet 5 displays the binding
element.
Code Snippet 5:

IXmlNode node = myTileXml.ImportNode(squareTileXml.


GetElementsByTagName(“binding”).Item(0), true);
myTileXml.GetElementsByTagName(“visual”).Item(0).AppendChild(node);

Code Snippet 6 shows result in two binding elements for a single visual element in the XML
payload.
Code Snippet 6:
Concepts

<tile>
<visual version=”2”>
<binding template=”TileWide310x150ImageAndText01”
fallback=”TileWideImageandText01”>
<image id=”1” src=”ms-appx:///images/blueWide.png”/>

V 1.0 © Aptech Limited


3
Session Working with Tiles and Search

<text id=”1”>This is my notification 3</text>


</binding>
<binding template=”TileSquare150x150Text04” fallback=”TileSquareText04”>
<text id=”1”>This is my notification 3</text>
</binding>
</visual>
</tile>

6. Code Snippet 7 creates the XML content for the XML code, the user has specified.
Code Snippet 7:

TileNotification myTileNotification = new TileNotification(myTileXml);

7. The user then, sends the notification to the app tile as shown in Code Snippet 8.
Code Snippet 8:

TileUpdateManager.CreateTileUpdaterForApplication().
Update(myTileNotification);

Figure 3.3 shows the output image of square and wide tile notification.

Figure 3.3: Square and Wide Tile Notification

ÎÎ Sending a Batch update:


Concepts

Following are the steps to send a batch update:


1. Following namespace declarations are added to the code:
using Windows.UI.Notifications;
using Windows.Data.Xml.Dom;

V 1.0 © Aptech Limited


3
Session Working with Tiles and Search

2. A batch can display numbers 0-99 or system-defined status glyphs. A glyph is nothing but a
graphical form that provides appearance or form for a character.
For example, an e-mail program may display a number of unread mails or a new message
glyph to indicate new messages is there in the inbox.
Numbers and glyphs in badges are updated through different XML and hence, you need to
retrieve the appropriate XML. Following example retrieves a template for the numeric badge:
Example:

XmlDocument myBadgeXml = BadgeUpdateManager.


GetTemplateContent(BadgeTemplateType.BadgeNumber);

Following example retrieves the template for the glyph badge:


Example:

XmlDocument myBadgeXml = BadgeUpdateManager.


GetTemplateContent(BadgeTemplateType.BadgeGlyph);

3. Assigning value to the batch is to be done separately for numeric and glyph values. Following
example retrieves a batch template and assigns it a numeric value:
Example:

XmlElement badgeElement = (XmlElement)myBadgeXml.SelectSingleNode(“/


badge”);
badgeElement.SetAttribute(“value”, “12”);

4. Following example retrieves a batch template and assigns it a glyph value:


Example:

XmlElement badgeElement = (XmlElement)myBadgeXml.SelectSingleNode(“/


badge”);
badgeElement.SetAttribute(“value”, “newMessage”);
This code creates a badge notification and sends it to the badge
BadgeNotification myBadge = new BadgeNotification(myBadgeXml);
BadgeUpdateManager.CreateBadgeUpdaterForApplication().
Update(myBadge);

This code creates a badge notification and sends it to the badge.


Concepts

V 1.0 © Aptech Limited


3
Session Working with Tiles and Search

Figure 3.4 displays the output of the badge notification code.

Figure 3.4: Badge Notification

3.1.2 Pinning Secondary Tiles


Each App has a main tile to denote the App itself. There can be multiple secondary tiles so that a ’deep
link’ can be created to a certain item to the start screen. For example a weather app can show the
weather for a specific city. Secondary tiles will also be able to show live updated content.
Code Snippet 9 defines a button and after clicking it you can create a secondary tile.
Code Snippet 9:

<Page
x:Class=”tiles.MainPage”
IsTabStop=”false”
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
xmlns:local=”using:tiles”
xmlns:d=”http://schemas.microsoft.com/expression/blend/2008”
xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006”
mc:Ignorable=”d”>

<Grid Background=”#FFE63939” >


Concepts

<StackPanel>
<Button x:Name=”PinTileButton” Content=”Pin a Secondary Tile “
Margin=”100,50” Click=”PinTileButton_Click”/>
<TextBlock x:Name=”Status” FontSize=”40” Foreground=”red”></TextBlock>
</StackPanel>

V 1.0 © Aptech Limited


3
Session Working with Tiles and Search

</Grid>
</Page>

1. You set some properties to create a Secondary tile and then, you define the SecondaryTile class with
its constructor as shown in Code Snippet 10.
Code Snippet 10:

public static int counter = 1;


static string logoSecondaryTileId;
public static string dynamicTileId = “SecondaryTile.LiveTile”;
public static string appbarTileId = “SecondaryTile.AppBar”;
Uri logo = new Uri(“ms-appx:///Assets/s.png”);
Uri smallLogo = new Uri(“ms-appx:///Assets/smallTile-sdk.png”);

string tileActivationArguments = MainPage.logoSecondaryTileId + “


WasPinnedAt=” + DateTime.Now.ToLocalTime().ToString();
logoSecondaryTileId = “SecondaryTile.Logo” + counter.ToString();

2. Now, you create an object of the SecondaryTile Class and call its constructor as shown in Code
Snippet 11.
Code Snippet 11:

SecondaryTile myTile = new SecondaryTile(MainPage.


logoSecondaryTileId,”Title text shown on the tile”, “Name of the tile the user
sees when searching for the tile”, tileActivationArguments, TileOptions.
ShowNameOnLogo,logo);
myTile.DisplayName = “mytiel”;

3. You call a method of the SecondaryTile class that pins the tile to the start screen after user confirmation
and returns a status as a boolean value as shown in Code Snippet 12.
Code Snippet 12:

bool isPinned = await myTile.RequestCreateForSelectionAsync


(MainPage.GetElementRect((FrameworkElement)sender)
Concepts

Windows.UI.Popups.Placement.Below);

4. You check the boolean result returned by the RequestCreateForSelectionAsync method and show a
status message to the user as shown in Code Snippet 13.
Code Snippet 13:

if (isPinned)

V 1.0 © Aptech Limited


3
Session Working with Tiles and Search

{
Status.Text = “Secondary tile successfully pinned.”;
}
else
{
Status.Text = “Secondary tile is not pinned.”;
}

Now, you can run the application to see an output as shown in figure 3.5.

Figure 3.5: Secondary Tile Creation


In this figure, the secondary tile is created that has a button which when clicked will show the tile.
Figure 3.6 displays the output after clicking the button.
Concepts

Figure 3.6: Output after Button Click

V 1.0 © Aptech Limited


3
Session Working with Tiles and Search

Type the name of the secondary tile and click Start button to see the secondary tile added to the Start
screen as shown in figure 3.7.

Figure 3.7: Secondary Tile Added

3.1.3 Sending Toast Notifications and Delivering Notifications


Following are the steps involved to create a toast notification:
1. The user uses the following namespace declarations:
using Windows.UI.Notifications;
using Windows.Data.Xml.Dom;
2. The user can select a template for the toast notification and retrieve its XML content. In our example,
you use the template named ToastImageAndText01, which requires a single image and a text.
Code Snippet 14 retrieves the XML content for the selected template.
Code Snippet 14:

ToastTemplateType myToastTemplate = ToastTemplateType.


ToastImageAndText01;
Concepts

XmlDocument myToastXml = ToastNotificationManager.


GetTemplateContent(myToastTemplate);

V 1.0 © Aptech Limited


3
Session Working with Tiles and Search

The XML content for Code Snippet 14 is as follows:


XML:

<toast>
<visual>
<binding template=”ToastImageAndText01”>
<image id=”1” src=””/>
<text id=”1”></text>
</binding>
</visual>
</toast>

3. Add the message you want to notify to the user through toast notification as shown in Code Snippet
15.
Code Snippet 15:

XmlNodeList myToastTextElements = myToastXml.


GetElementsByTagName(“text”);
myToastTextElements[0].AppendChild(myToastXml.CreateTextNode(“This is
the new toast notification”));

4. Next, the user needs to add an image to the toast notification by retrieving the image tag and
assigning the required image to it as shown in Code Snippet 16.
Code Snippet 16:

XmlNodeList myToastImageAttributes = myToastXml.


GetElementsByTagName(“image”);
((XmlElement) myToastImageAttributes[0]).SetAttribute(“src”, “ms-
appx:///images/redWide.png”);
((XmlElement) myToastImageAttributes[0]).SetAttribute(“alt”, “red
graphic”);

5. When a user clicks the notification, the application is launched. You use the launch attribute of the
toast notification. The attribute value is app-defined string as shown in Code Snippet 17.
Code Snippet 17:
Concepts

((XmlElement)toastNode).SetAttribute(“launch”,
“{\”type\”:\”toast\”,\”param1\”:\”12345\”,\”param2\”:\”67890\”}”);

V 1.0 © Aptech Limited


3
Session Working with Tiles and Search

6. Finally, you create and send the toast notification as shown in Code Snippet 18.
Code Snippet 18:

ToastNotification myToast = new ToastNotification(myToastXml);


ToastNotificationManager.CreateToastNotifier().Show(myToast);

ÎÎ Delivering Notifications:
This topic discusses about delivery mechanism of Scheduled, Periodic, and Push notifications.

ÎÎ Scheduled Notification:
The user can schedule notification so that it can appear at a specific time. They are going to schedule
the toast notification created in the earlier section.
Code Snippet 19 sets the DateTime object so that the toast notification appears in three hours.
Code Snippet 19:

Int16 dueTimeInHours = 3;
DateTime dueTime = DateTime.Now.AddHours(dueTimeInHours);

You then, create the scheduled toast notification object with the notification content and time
scheduled as shown in Code Snippet 20.
Code Snippet 20:

ScheduledToastNotification myScheduledToast = new


ScheduledToastNotification(myToastXml, dueTime);

You can then, create an ID for the scheduled notification. This ID can be used to cancel the
notification later and it can be 16 characters long as shown in Code Snippet 21.
Code Snippet 21:

scheduledToast.Id = “Future_Toast”;

You can then, add the toast notification to the schedule as shown in Code Snippet 22.
Code Snippet 22:

ToastNotificationManager.CreateToastNotifier().
AddToSchedule(myScheduledToast);
Concepts

ÎÎ Periodic Notifications:
Periodic notifications also known as ‘polled notifications’ used to update live tiles and badges at a
specified interval.

V 1.0 © Aptech Limited


3
Session Working with Tiles and Search

To use periodic notification, the client code should have the following two elements:
1. The Uniform Resource Identifier (URI) of the Web location, the app polls for the badge or live tile
update
2. The time interval with which the given URI needs to be polled
The app should host a cloud service to use periodic notification. Cloud services provide easy,
scalable access to resources, applications and services, and a cloud services provider manages
them. The users of the app will poll this cloud service periodically. At each polling period, for
example, an hour, Windows will send an HTTP GET request to the specified URI, download the
requested badge or tile content (as XML) which is the response to the request, and displays the
downloaded content on the tile.
Following are the steps involved in creating a periodic notification:
1. Identify a Web service to host the live content
At specific intervals, Windows polls the Web service for updated content of App’s tile.
Only the Web services that support HTTP must be choose. During testing, the user can use
Microsoft Internet Information Services (IIS) on the user’s local machine to test the XML.
2. Tile’s XML file needs to be placed in a Web-accessible location
The user needs to place the XML content in a file named Tile.xml and place it in a Web-
accessible location in server (for example, http://www.fabrikam.com/tile.xml). UTF-8
encoding must be used in the XML document and follow the tile schema. Code Snippet 23
shows the XML code.
Code Snippet 23:

<tile>
<visual version=”2”>
<binding template=”TileWide310x150Text03”
fallback=”TileWideText03”>
<text id=”1”>This is periodic notification</text>
</binding>
</visual>
</tile>

3. Start the periodic updates with single URL


Code Snippet 24 shows how to poll a single URL to provide new content for the tile each
Concepts

hour.
Code Snippet 24:

using Windows.UI.Notifications;
PeriodicUpdateRecurrence newRecurrence = PeriodicUpdateRecurrence.
Hour;

V 1.0 © Aptech Limited


3
Session Working with Tiles and Search

System.Uri newUri = new System.Uri(polledUrl);


TileUpdateManager.CreateTileUpdaterForApplication().
StartPeriodicUpdate(newUri, newRecurrence);

This code uses already defined variable namely polledUrl, which is a string that contains
the URL to be polled.
4. Start the periodic updates with multiple URLs
The user can also allow up to five different URLs to be polled by Windows and supply a set
of content that are displayed one after another in the tile’s notification queue.
Following example polls content once an hour.
Example:

using Windows.UI.Notifications;
TileUpdateManager.CreateTileUpdaterForApplication().
EnableNotificationQueue(true);
PeriodicUpdateRecurrence newPeriodicRecurrence =
PeriodicUpdateRecurrence.Hour;
TileUpdateManager.CreateTileUpdaterForApplication().
StartPeriodicUpdateBatch(urisToPoll, newPeriodicRecurrence);

In this code, the notification queue must be enabled if was not enabled previously. i.e. the
call to EnableNotificationQueue is made only once after the user creates a secondary
tile or installs the App. A previously defined variable named urisToPoll, an array of URL
objects, each representing a different URL is used to get polled content.

ÎÎ Push Notifications:
Push notification enables third-party developers to send tile, badge, toast, and raw updates from
their own cloud service.
Following are the steps involved in sending a push notification:
1. Following are the namespace declarations:
using System.Net;
using System.IO;
using System.Runtime.Serialization;
Concepts

using System.Runtime.Serialization.Json;
using System.Web;
using System.Text;

V 1.0 © Aptech Limited


3
Session Working with Tiles and Search

2. HTTP POST request creation:


HttpWebRequest class is used to create the post request and URI parameter as shown in
Code Snippet 25.
Code Snippet 25:

HttpWebRequest HTTPRequest = HttpWebRequest.Create(uri) as


HttpWebRequest;
HTTPRequest.Method = “POST”;

3. Include required headers:


The four required headers included in all push notifications are X-WNS-Type, Authorization,
Content-Length, and Content-Type.
ŠŠ X-WNS-Type header is used to identify whether it is a tile, badge, toast, or raw
notification.
ŠŠ The Content-Type depends on X-WNS-Type value.
ŠŠ The size of the notification payload is specified by the Content-Length.
ŠŠ The Authorization header has the authentication credential, which allows the user to
send a push notification over this channel.
The Authorization header must have the accessToken parameter. This accessToken is
received from WNS during cloud server authentication and stored on the server. If the access
token is not included, the notification will be rejected as shown in Code Snippet 26.
Code Snippet 26:

request.Headers.Add(“X-WNS-Type”, newNotificationType);
request.ContentType = newContentType;
request.Headers.Add(“Authorization”, String.Format(“Bearer {0}”,
accessToken.AccessToken));

4. Include the prepared content:


In the HTTP request, the XML content of the notification is included as a data blob in the
request body. The content is nothing but an XML payload and added to the request as bytes
stream as shown in Code Snippet 27.
Code Snippet 27:
Concepts

byte[] contentInBytes = Encoding.UTF8.GetBytes(xml);


using (Stream requestStream = request.GetRequestStream())
requestStream.Write(contentInBytes, 0, contentInBytes.Length);

V 1.0 © Aptech Limited


3
Session Working with Tiles and Search

5. WNS will send response to acknowledge receipt of notification:


There will not be any delivery confirmation response for the notification. The user will only
receive an acknowledgement. The acknowledgement response will be captured as shown in
Code Snippet 28.
Code Snippet 28:

using (HttpWebResponse webAcklResponse = (HttpWebResponse)request.


GetResponse())
return webAcklResponse.StatusCode.ToString();

3.1.4 Troubleshooting Toast, Tile, and Badge Notifications


Table 3.1 lists the problems in creating tile notification and the appropriate fixes.

S.No Problem Cause Fix


1. Check user settings The administrator has Administrator must enable
disabled notifications notifications through group policies.
through settings or Check Turn live tile on/off is not off in
group policies options bar of the App
2. Logo resource is wide The App manifest does A default logo image resource of all
or large in the App not have a default tile Tile size can be provided in the App’s
manifest resource for the image manifest
size specified in the
notification
3. Check image sizes Notification images Shrink the images
should be less than
1024 x 1024 pixels. Size
should be less than 200
KB
4. Verify URLs URL syntax error If a path is used, make sure it is given
using one of the http:// and https://,
ms-appx:///, ms-appdata:///local/
protocols
5. Examine the image The images are in Correct the image formats that are
formats unsupported formats supported by the App
6. Check XML syntax and XML syntax and Fix XML errors and verify using a XML
Concepts

content validation errors syntax checker available in Visual


Studio
7. Make sure notification Expiration time is set to Use a larger value for expiration time
has not expired a very small value

V 1.0 © Aptech Limited


3
Session Working with Tiles and Search

S.No Problem Cause Fix


8. Notification queue Tile notification queue In the App’s initialization code, call
is enabled in case of is not enabled enableNotificationQueue(true)
cycling notifications
Table 3.1: Tile Notifications
Table 3.2 lists the troubleshooting scheduled notification.

S.No Problem Cause Fix


1. Scheduled tile or toast The notification’s XML content is Test the XML content
is missing formatted incorrectly through a local notification
and debug the delivery
problem
2. App’s AddToSchedule The user has exceeded the Reduce the number of
method call fails maximum allowed notifications scheduled notifications.
Maximum allowed is 4096
notifications
Notification scheduled in past time
Update the notification
relative to the current clock
so that its time is in the
future
Table 3.2: Troubleshooting Scheduled Notifications
Table 3.3 lists the troubleshooting push notifications.

S.No Problem Cause Fix


1. Check event logs Notification is received Using Event viewer examine
but not shown the log Microsoft-Windows-
TWinUI/Operational under
Applications and Services\
Microsoft\Windows\Apps.
Notification is not Using Event Viewer examine
received at all the log under Services\
Microsoft\Windows\
PushNotifications-Platform
2. ‘200 OK’ response The notification content Fix the errors in the XML
is received but the has XML errors content and make sure it is
Concepts

notification is not complete and correct


Improper use of
displayed
notification API Verify the API documentation
parameters and fix the issues

V 1.0 © Aptech Limited


3
Session Working with Tiles and Search

S.No Problem Cause Fix


Header type does not Verify and check the server of
match notification the App, using the required
content value for X-WNS-Type header
The Time To Live (TTL) Provide a larger TTL value.
value is too small Note that the value is given in
seconds
3. Notification returns a 400 Bad request - Make sure all custom headers
code other than ‘200 WNS headers may are used by the App as
OK’ be incorrect or HTTP required
request is invalid
401 Unauthorized –
Visit Windows Store
App server should use
Dashboard to verify Package
the required secret
SID and secret
and Package Security
Identifier ( Package SID)
given while registering
the App
401 Unauthorized,
token is expired – Request a new access token
Sending a notification from WNS
with expired token
403 Forbidden –
Occurs when access Update App manifest
token does not match to match cloud service
with the credentials of credentials
the notification
404 Not found – Verify Channel URL is not
Channel URL not modified by code
formed correctly
406 Not acceptable
– Excessive number Review notification frequency
of notifications in too
short time
410 Gone – Channel
Concepts

URL expired Make sure App requests


a channel URL, when it is
launched

V 1.0 © Aptech Limited


3
Session Working with Tiles and Search

S.No Problem Cause Fix


Errors while creating ERROR_NO_ Verify Internet connectivity
a Push notification NETWORK – WNS
channel requires Internet
connection to create a
notification channel
WPN_E_CLOUD_
INCAPABLE – Internet Ensure App manifest has
capability not declared Internet capability declared
by the App in its
manifest file
WPN_E_INVALID_APP
– A valid package name Make sure a valid package
must be used name is used by the App

Table 3.3: Troubleshooting Push Notifications


Table 3.4 lists the troubleshooting toast notifications.

S.No Problem Cause Fix


1. Verify user settings The notifications are Make sure administrator has
disabled through enabled notification through
settings group policy or settings
2. Verify manifest entries The manifest has not Make sure notification specific
required information entries are included in the
to deliver toast App’s manifest file
notification
3. Check image sizes Notification images Shrink the images
should be less than
1024 x 1024 pixels. Size
should also be less than
200 KB
4. Verify URLs URL syntax error If a path is used make sure it is
given using one of the http://
and https://, ms-appx:///, ms-
appdata:///local/ protocols
5. Examine the image The images are in Correct the image formats that
Concepts

formats unsupported formats are supported by the App


6. Check XML syntax and XML syntax and Fix XML errors and verify using
content validation errors a XML syntax checker available
in Visual Studio

V 1.0 © Aptech Limited


3
Session Working with Tiles and Search

S.No Problem Cause Fix


7. Make sure notification Expiration time is set to Use a larger value for
has not expired a very small value expiration time
Table 3.4: Troubleshooting Toast Notifications

3.1.5 Adding Search to an App


The SearchBox control is made available in the Windows.UI.Xaml.Controls namespace for XAML
developers. When the user uses the SearchBox control for an application, he/she need not use global
search to search the application. This control integrates with a search contract allowing support for
search suggestions and results. There is also built-in support for keyboard, touch, and mouse interaction.
This Search contract allows up to five suggestions, image separated result suggestions, and three history
items.
The user must implement the AppendQuerySuggestion to provide search suggestions for the search
pane.
The application must handle the SearchBox.QuerySubmitted event, when the user submits a search
term, to track what is being searched. When a user makes changes to the text searched, the application
must handle the event to provide new suggestions in the search pane.
The user implements a simple application where users will search for bike names. When the user in
search box types few letters, the search control will provide suggestions for matching bike names.
In Visual Studio 2012, the user creates a new project of type Blank App (XAML) titled Windows 8.1
SearchBoxDemo.
Figure 3.8 displays the New Project window.

Concepts

Figure 3.8: New Project Window

V 1.0 © Aptech Limited


3
Session Working with Tiles and Search

The user adds a SearchBox Control using the MainPage.xaml file in XAML editor. The search control is
named searchBoxNewSearchBox.
Now, the XAML code will be as shown in Code Snippet 29.
Code Snippet 29:

<Grid Background=”{StaticResource ApplicationPageBackgroundThemeBrush}”>


<SearchBox x:Name=” searchBoxNewSearchBox “ HorizontalAlignment=”Left”
Margin=”534,210,0,0” VerticalAlignment=”Top”/>
</Grid>

The QuerySubmitted event handler must store the user’s search term. The user adds a TextBox and
TextBlock control for this and the equivalent XAML code as shown in Code Snippet 30.
Code Snippet 30:

<TextBlock HorizontalAlignment=”Left” Margin=”4825800” TextWrapping=”Wrap”


Text=”Searches for” VerticalAlignment=”Top”/>
<TextBox x:Name=”newTextBoxSearchTerm” HorizontalAlignment=”Left”
Margin=”5755800” TextWrapping=”Wrap” VerticalAlignment=”Top”/>

Add the following code by double-clicking the QuerySubmitted event handler as shown in Code Snippet
31.
Code Snippet 31:

private void searchBoxNewSearchBox_QuerySubmitted(SearchBox userSender,


SearchBoxQuerySubmittedEventArgs newArgs)
{
newTextBoxSearchTerm.Text = userSender.QueryText;
}

The user then, adds a list of bike names for suggestion as shown in Code Snippet 32.
Code Snippet 32:

public sealed partial class MainPage : Page


{
private static readonly string[] bikeList = {
Concepts

“Vespa”,”Suzuki”,”Honda”
}

V 1.0 © Aptech Limited


3
Session Working with Tiles and Search

The SuggestionsRequested event handler is then, implemented and a SearchSuggestion


Collection object is created to which the user can add any bike name that matches the string and
provide a suggestion as shown in Code Snippet 33.
Code Snippet 33:

private void searchBoxNewSearchBox_SuggestionsRequested(SearchBox mySender,


SearchBoxSuggestionsRequestedEventArgs myArgs)
{ Windows.ApplicationModel.Search.SearchSuggestionCollection
mySuggestionCollection = args.Request.SearchSuggestionCollection;
foreach (string newSuggestion in bikeList)
{
if (newSuggestion.StartsWith(args.QueryText, StringComparison.
CurrentCultureIgnoreCase))
{ suggestionCollection.AppendQuerySuggestion(newSuggestion);
}
}
}

Now, run the application and give it any bike name like ’Honda’ to test it out.
Figure 3.9 displays the output showing SearchBox control.

Concepts

Figure 3.9: SearchBox Control

V 1.0 © Aptech Limited


3
Session Working with Tiles and Search

3.1.6 Creating a Basic Search Results Page for an App


1. Add a basic search result page by using the Add a New Item dialog box.
This dialog is opened in three ways:
yy Select the menu option ProjectAdd New Item
yy Select the menu option AddNew Item from the project’s context menu
yy Use the keyboard shortcut key Crtl+Shift+A
2. In the Add a New Item dialog box, select Search Results Page and click Add.
You can use the item templates available for Grid and List layouts or customize the search result
page, if the default search results page does not match with the user’s requirements.

3.2 Handling Queries and Displaying the Search Result Page


When the user enters a query text through the SearchBox, it fires a QuerySubmitted event. The user
then adds a QuerySubmitted event handler to the SearchBox control. This event handler will process
the query and show the search results page.
Code Snippet 34 adds a SearchBox control.
Code Snippet 34:

<SearchBox x:Name=”mySearchBox”
FocusOnKeyboardInput=”True”
QuerySubmitted=”SearchBoxEventsQuerySubmitted”
Height=”35”/>

Code Snippet 35 process the QuerySubmitted event.


Code Snippet 35:

private void SearchBoxEventsQuerySubmitted(Windows.UI.Xaml.Controls.


SearchBox querySender,
SearchBoxQuerySubmittedEventArgs newArgs)
{
// Process results and show the search results page.
Concepts

V 1.0 © Aptech Limited


3
Session Working with Tiles and Search

3.3 Handling Search Activation


1. In the App manifest, the user must declare the Search contract to support App activation.
yy The user must select the manifest file in Visual Studio project and then, select the
Declarations tab.
yy The user then, needs to select Search from the Available Declarations drop-down and
click Add.
2. When the user searches the App while it is not in the running state, the App’s OnSearchActivated
method is called by the system and SearchActivatedEventArgs i.e., the query text and language
is passed to it. During implementation, the user must override the OnSearchActivated method
in App.xaml.cs/App.xaml.vb/App.xaml.cpp file to process the query and show the results page.
Users may select this App from the Search charm without entering any query text. They may do
this to filter their search to a particular App, or as an instant way to get back to their previous page
or screen. The App needs to be designed in such a way to anticipate the user’s needs and respond
appropriately.
Code Snippet 36 searches activation.
Code Snippet 36:

async protected override void OnSearchActivated(SearchActivatedEventArgs


newArgs)
{
await EnsureMainPageActivatedAsync(newArgs);
if (newArgs.QueryText == “”)
{
// navigate to landing page.
}
else
{
// display search results.
}
}
Concepts

3.4 Adding Search Suggestion


Search suggestions are a set of suggestions shown, similar to the query entered by the user, under the
search box. These are important because they give useful hints about the types of things users can search
in the App and save a specific amount of user’s time.

V 1.0 © Aptech Limited


3
Session Working with Tiles and Search

The suggestions are retrieved from several sources:

ÎÎ The user may define them. For example, the user can create a list of bike manufacturers.

ÎÎ The user can fetch them from Windows, if the search is based on local files.

ÎÎ The suggestions are retrieved from a Web service or server.


Concepts

V 1.0 © Aptech Limited


3
Session Working with Tiles and Search

3.5 Check Your Progress


1. Tiles displaying dynamic data are known as ___________.

(A) Badges (C) Secondary Tiles


(B) Live Tiles (D) Primary Tiles

2. The notification that appears in a specified time is ______________.

(A) Periodic notification (C) Scheduled notification


(B) Push notification (D) Polled notification

3. When the user enters a query in the SearchBox, it fires the event ______________.
QuerySubmitted (C) SearchSubmitted
(A)
(B) SearchActivated (D) QueryProcessed

4. The SearchBox control is available in the ________________ namespace.

(A) System.Net (C) System.Web

(B) System.IO (D) Windows.UI.Xaml.Controls

5. The ________________ method is called by the system when the user searches the App that is
not in the running state.

(A) OnUserSearch (C) OnSearchActivated

(B) OnSearchEvent (D) OnAppActivated

Concepts

V 1.0 © Aptech Limited


3
Session Working with Tiles and Search

3.5.1 Answers
1. B
2. C
3. A
4. D
5. C
Concepts

V 1.0 © Aptech Limited


3
Session Working with Tiles and Search

Summary
ÎÎ Tiles are icons representing applications on Windows 8 Start screen.
ÎÎ Badges are displayed on tiles representing App’s state or status.
ÎÎ Notifications are of three type such as Scheduled, Periodic, and Push notifications.
ÎÎ Scheduled notifications appear at a specified time.
ÎÎ Periodic notifications used to update status at specified interval of time.
ÎÎ Push notifications allow tile, badge, and toast updates to be send from a cloud service.
ÎÎ Troubleshooting steps and processes involved in delivering notifications were discussed.
ÎÎ Search contract is used to create a search pane with SearchBox control with search suggestions
and displaying results.

Concepts

V 1.0 © Aptech Limited


Session - 4
Working with Data and Files
Welcome to the session, Working with Data and Files.

The session will discuss how to work with Data and Files. Methods involved
in sharing and protecting data will discuss.

In this session, you will learn about:

ÎÎ Explain JSON data format and its properties

ÎÎ Discuss processed involved in sharing data

ÎÎ Explain the methods involved in cryptography to secure


data

ÎÎ Describe the steps involved to work with certificates

ÎÎ Describe how to protect data maintained between apps


4
Session Working with Data and Files

4.1 Using JavaScript Object Notification (JSON)


JavaScript Object Notification (JSON) is a lightweight data-interchange format on the Web. It is easy
to read and write for humans and easy to parse and generate for machine. It is used in applications
that need to exchange or store structured information as text. JSON data format is an alternate to XML
and primarily used to transfer data between a Web application and server. It is completely language
independent and hence, classes and methods to create and parse JSON data are available in almost all
programming languages. For example, in a site that requires user registration, the users are required to
fill a sign-up form. When the user enters the required details and submits the form, the user details are
send to the server using this JSON data format and appropriate response is received back by the browser
from the server in the same format.
JSON is based on following two data structures:

ÎÎ Key/value pairs: In programming languages, this is recognized as object, record, hash table,
struct, or associative array.

ÎÎ Ordered list: In programming languages, this is recognized as array, list, sequence, or vector.
Code Snippet 1 is a sample JSON data representing a person object.
Code Snippet 1:

{
“firstName”: “John”,
“lastName”: “Adams”,
“isAlive”: true,
“height_cm”: 167.64,
“age”: 45,
“address”: {
“streetAddress”: “32 6th Street”,
“city”: “Texas”,
“state”: “TX”,
“postalCode”: “10031-4100”
},
Concepts

“phoneNumbers”: [
{ “type”: “home”, “number”: “312 555-3234” },
{ “type”: “fax”, “number”: “645 545-4568” }

V 1.0 © Aptech Limited


4
Session Working with Data and Files

]
}

The entire data is enclosed within an object named person within braces {}. Data in this object is called
member and each member may contain a pair, array, or another object. In the example, sample shown in
each entity separated by comma are members. The pair contains data in the format key:value. Here,
key must be a string value and distinct from other keys in the object. Keys are separated by a colon from its
corresponding value. “firstName”: “John” is an example of the key:value pair. Array contains values or
otherwise known as elements enclosed within square brackets [] separated by comma. Elements, in turn,
may contain values or other elements. The values for phoneNumbers are enclosed within an array. The value
may be any value with data type such as string, number, object, array, true, false, or null.
In Windows 8 Store Applications, the user needs to use the HttpClient class to retrieve the response
from the Web server. The GetAsync method will return an HttpResponseMessage that contains the
response headers, status code, and content. Code Snippet 2 demonstrates the process of retrieving the
JSON response from the Web server.
Code Snippet 2:

var newClient = new HttpClient();


HttpResponseMessage httpResponse = await newClient.GetAsync(new Uri(“http://
mynewapi.com/”));
var jsonString = await httpResponse.Content.ReadAsStringAsync();

ÎÎ Deserialize and serialize objects


Code Snippet 3 demonstrates the process of retrieving the named values from the JsonObject i.e
deserializing an object from JSON text.
Code Snippet 3:

JsonValue newJsonValue = JsonValue.Parse(“{\”Width\”: 900, \”Height\”:


400, \”Title\”: \”JSON string parsing\”, \”IDs\”: [117, 942, 254, 38692]}”);
double widthValue = jsonValue.GetObject().GetNamedNumber(“Width”);
double heightValue = jsonValue.GetObject().GetNamedNumber(“Height”);
string titleValue = jsonValue.GetObject().GetNamedString(“Title”);
JsonArray idsValue = jsonValue.GetObject().GetNamedArray(“IDs”);
Concepts

V 1.0 © Aptech Limited


4
Session Working with Data and Files

Code Snippet 4 creates a new JsonObject and populates it with new name/JsonValue pairs
using the JsonObject::Insert method. Then, the user calls JsonObject::Stringify to
serialize the JsonObject as JSON text.
Code Snippet 4:

JsonObject newJsonObject = new JsonObject();


jsonObject[“Width”] = JsonValue.CreateNumberValue(900);
jsonObject[“Height”] = JsonValue.CreateNumberValue(400);
jsonObject[“Title”] = JsonValue.CreateStringValue(“JSON string parsing”);
jsonObject[“IDs”] = JsonValue.Parse(“[117, 942, 254, 38692]”);
string jsonNameValueString = jsonObject.Stringify();

ÎÎ Deserialize and serialize arrays


Code Snippet 5 creates a new JsonObject and populates it with new name/JsonValue pairs
using the JsonObject::Insert method. The user then, calls the JsonObject::Stringify
to serialize the json object as JSON text.
Code Snippet 5:

JsonObject newJsonObject = new JsonObject();


jsonObject[“Width”] = JsonValue.CreateNumberValue(900);
jsonObject[“Height”] = JsonValue.CreateNumberValue(400);
jsonObject[“Title”] = JsonValue.CreateStringValue(“Parsing JSON array”);
jsonObject[“IDs”] = JsonValue.Parse(“[126, 953, 264, 38823]”);
string jsonArrayString = newJsonObject.Stringify();

Code Snippet 6 creates a new JsonArray object and populates it with JsonValue objects using
the JsonArray::Append method. The user then, calls the JsonArray::Stringify to serialize
the json array as JSON text.
Code Snippet 6:

JsonArray newJsonArray = new JsonArray();


jsonArray.Add(JsonValue.CreateNumberValue(126));
Concepts

jsonArray.Add(JsonValue.CreateNumberValue(2.14149));
jsonArray.Add(JsonValue.CreateBooleanValue(true));
jsonArray.Add(JsonValue.CreateStringValue(“sample”));
string jsonArrayString = newJsonArray.Stringify();

V 1.0 © Aptech Limited


4
Session Working with Data and Files

ÎÎ Deserialize and serialize numbers


Code Snippet 7 parses a number value from JSON text and retrieves the number from the Json
value using JsonValue::GetNumber.
Code Snippet 7:

JsonValue newJsonValue = JsonValue.Parse(“6”);


double newNumberValue = newJsonValue.GetNumber();

Code Snippet 8 serializes a number value as JSON text and creates a new Json value and assign
preferred value with JsonValue::CreateNumberValue.
Code Snippet 8:

JsonValue newJsonValue = JsonValue.CreateNumberValue(6);


string jsonNumberString = newJsonValue.Stringify();

ÎÎ Deserialize and serialize strings


Code Snippet 9 parses a string value from JSON text and retrieves it from the Json value using
JsonValue::GetString.
Code Snippet 9:

JsonValue jsonStringValue = JsonValue.Parse(“\”sample text\””);


string newStringValue = jsonStringValue.GetString();

Code Snippet 10 allows the user to serialize a string value as JSON text and create a new Json value.
Then, the user can assign preferred value with JsonValue::CreateStringValue.
Code Snippet 10:

JsonValue jsonStringValue = JsonValue.CreateStringValue(“sample text”);


string newJsonString = jsonStringValue.Stringify();

4.2 Sharing and Exchanging Data


In today’s world, users of information technology want to connect and share with other people often. For
example, a user may want to share a link on their social networking site or upload to cloud storage. Apps
that are currently developed need to ensure that the data is shared and exchanged effectively by users.
Windows 8 provides many ways to exchange data with other Apps.
Concepts

4.2.1 Share Charm


The users can quickly exchange data to other apps by staying in the current app by using the Share Charm
feature of Windows 8. A user may want to share a Webpage link with their friends of a particular social
networking site. Share Charm allows users to perform such tasks easily and quickly. This Share Charm is

V 1.0 © Aptech Limited


4
Session Working with Data and Files

used in Apps that support sharing. Users of an App can launch Share Charm through touch gesture or
programmatically.
Figure 4.1 displays the Share charm.

Figure 4.1: Share Charm


In C#, the Share Charm can be invoked programmatically by using the showShareUI method. This
method had no parameters. Code Snippet 11 invokes the Share Charm.
Code Snippet 11:

private void ShareProgrammatically()


Windows.ApplicationModel.DataTransfer.DataTransferManager.ShowShareUI();
}

4.2.2 Tap and Send


Tap and send is a sharing feature made available through the Devices charm. It is automatically provided
for Apps that act as share sources. They use Near Field Communication (NFC) to share and exchange data
between people. NFC is nothing but a high frequency wireless communication technology that allows
exchange of data between two NFC compatible devices within a short range i.e less than 2 cm. To mention
specifically, tap and send is ideal for sharing files and links with a nearby friend. They are available only to
Concepts

users whose App has the right hardware, and only shows in the Devices charm, when there is something
to share in the App. Usually, the user starts the Devices charm and chooses Tap and Send by a touch
gesture or click of mouse.

V 1.0 © Aptech Limited


4
Session Working with Data and Files

4.2.3 Copy and Paste


Copy and paste is one of the classic ways of sharing data within the same App or between two different
Apps. It is a very familiar way and most common method used in sharing data. It is the only way to
interchange data from Apps in Windows 8 to the desktop or vice versa. For example, consider a user who
is editing an image using a legacy App. Since the App is not a Windows Store App, the user is currently in
the desktop. Later, the user decides to use a Windows Store App feature to improve the picture. In this
scenario, using the Share Charm is not correct. Rather, using the common copy and paste commands
belonging to the clipboard is the correct solution. Every App should support Copy and Paste to some
extent.
When the user supports for copy and paste, he/she must take care on how to access the commands. In
a keyboard and mouse environment, the usual shortcut keys are probably. However, if the user is using
a tablet he/she must consider using the context-sensitive menu or App bar to show the copy and paste
options.

4.3 Encrypting Data and Working with Certificates


You will see how to use cryptography and certificates for user data security while sharing.

4.3.1 Manipulating Cryptographic Data and Hashing Data


Manipulating Cryptographic Data
The process of protecting information by transforming or encrypting into an unreadable format is called
cryptography. Only those users who possess a secret key can decrypt the message back to the original
text. Encrypted messages may be broken by cryptanalyst is also known as code breaking. Cryptography is
used to protect e-mails, credit card information, and corporate data.
Following topics discusses some common data manipulations that are essential during cryptographic
operations:

ÎÎ Creating Random Numbers


The security of cryptographic code depends on some secret information that is known by users who
are authorized but unknown and unpredictable to other users. To maintain this unpredictability,
few randomizations are used which is demonstrated in Code Snippet 12.
Code Snippet 12:

using Windows.Security.Cryptography;
Concepts

using Windows.Storage.Streams;
namespace Random
{
sealed partial class GenerateRandomDataCrypt : Application

V 1.0 © Aptech Limited


4
Session Working with Data and Files

{
public GenerateRandomDataCrypt()
{
// Initialize the app.
this.InitializeComponent();
// Creates a buffer with random data.
String strRandomHex = this.GenerateRandomData();
// Create a random integer.
UInt32 unsignedIntRandom = this.GenerateRandomNumber();
}
public String GenerateRandomData ()
{
// Defines the length of the buffer in bytes
UInt32 newLength = 32;
// Generate random number and copy to buffer.
IBuffer newBuffer = CryptographicBuffer.GenerateRandom(newLength);
// Encode buffer to hexadecimal string to display
String hexRandom = CryptographicBuffer.EncodeToHexString(newBuffer);
return hexRandom;
}
public UInt32 GenerateRandomNumber()
{
// Generates new random number.
UInt32 Random = CryptographicBuffer.GenerateRandomNumber();
return Random;
}
}
Concepts

V 1.0 © Aptech Limited


4
Session Working with Data and Files

ÎÎ Comparing Buffers
Code Snippet 13 shows how to compare buffer for equality.
Code Snippet 13:

public void CompareBuffers()


{
// Creates hexadecimal string.
String stringHex = “30310aff”;
// Creates Base64 string that is equivalent to stringHex.
String strBase64v1 = “MDEK/w==”;
// Create a Base64 string that is not equivalent to stringHex.
String strBase64v2 = “KEDM/w==”;
// Decode stringHex to a buffer.
IBuffer bufferOne = CryptographicBuffer.DecodeFromHexString(stringHex);
// Decode strBase64v1 to a buffer.
IBuffer bufferTwo = CryptographicBuffer.
DecodeFromBase64String(strBase64v1);
// Decode strBase64v2 to a buffer.
IBuffer bufferThree = CryptographicBuffer.
DecodeFromBase64String(strBase64v2);
// Compare bufferOne and bufferTwo
// The code points with Boolean value true and buffer value being equal
Boolean bVal_1 = CryptographicBuffer.Compare(bufferOne, bufferTwo);
// Compare bufferOne and bufferThree.
// The code points with Boolean value false and buffer value not equal
Boolean bVal_2 = CryptographicBuffer.Compare(bufferOne, bufferThree);
}

The two buffers are equal when each code point matches the corresponding code point in another buffer.
Concepts

ÎÎ Converting Between Strings and Binary Data


Code Snippet 14 shows how to convert between string and binary data.
Code Snippet 14:

public void ConvertData()

V 1.0 © Aptech Limited


4
Session Working with Data and Files

{
// Creates string to convert.
String strInput = “Input String”;
// Convert the string to UTF16BE binary data.
IBuffer bufferUTF16BE = CryptographicBuffer.
ConvertStringToBinary(strInput, BinaryStringEncoding.Utf16BE);
// Convert the string to UTF16LE binary data.
IBuffer bufferUTF16LE = CryptographicBuffer.
ConvertStringToBinary(strIn, BinaryStringEncoding.Utf16LE);
// Convert the string to UTF8 binary data.
IBuffer bufferUTF8 = CryptographicBuffer.
ConvertStringToBinary(strInput, BinaryStringEncoding.Utf8);
}

ÎÎ Hashing Objects
The CryptographicHash object is used to hash different data repeatedly without having to
create the object again for each use. The Append method adds new data to a buffer that needs is
to be hashed. The GetValueAndReset method hashes the data and resets the object as shown
in Code Snippet 15.
Code Snippet 15:

public void SampleReusableHash()


{
// Creates string that has the name of the hashing algorithm to use.
String strAlgorithmName = HashAlgorithmNames.Sha512;
// Creates a HashAlgorithmProvider object.
HashAlgorithmProvider objAlgorithmProv = HashAlgorithmProvider.
OpenAlgorithm(strAlgorithmName);
// Create a CryptographicHash object which is reused continually
// hash new messages.
Concepts

CryptographicHash objNewHash = objAlgorithmProv.CreateHash();


// First Hash message
String strMsgOne = “This is message one.”;
IBuffer buffMsgOne = CryptographicBuffer.ConvertStringToBinary(strMsgOne,
BinaryStringEncoding.Utf16BE);

V 1.0 © Aptech Limited


4
Session Working with Data and Files

objHash.Append(buffMsgOne);
IBuffer buffHashOne = objHash.GetValueAndReset();
// second Hash message
String strMsgTwo = “This is message Two.”;
IBuffer buffMsgTwo = CryptographicBuffer.
ConvertStringToBinary(strMsgTwo, BinaryStringEncoding.Utf16BE);
objHash.Append(buffMsgTwo);
IBuffer buffHashTwo = objHash.GetValueAndReset();
// Hash message three
String strMsgThree = “This is message three”;
IBuffer buffMsgThree = CryptographicBuffer.
ConvertStringToBinary(strMsgThree, BinaryStringEncoding.Utf16BE);
objHash.Append(buffMsgThree);
IBuffer buffHashThree = objHash.GetValueAndReset();
// Convert the hashes to string values (for display);
String strHashOne = CryptographicBuffer.
EncodeToBase64String(buffHashOne);
String strHashTwo = CryptographicBuffer.
EncodeToBase64String(buffHashTwo);
String strHashThree= CryptographicBuffer.
EncodeToBase64String(buffHashThree);
}

4.3.2 Using the Data Protection API


In the Windows.Security.Cryptography.DataProtection namespace, the
DataProtectionProvider class provides a simple way to encrypt and decrypt data. The user can
use the class to protect data based on the following:

ÎÎ The user can use a SID to make the data safe on an Active Directory (AD). Any member belonging
to the group can decrypt data.
Concepts

ÎÎ The user can protect data belonging to current user.

ÎÎ The user can protect data to the credentials used during sign-in to a Website.
When the user creates a DataProtectionProvider object, they must specify a protection descriptor
to protect data before calling ProtectAsync or ProtectStreamAsync.

V 1.0 © Aptech Limited


4
Session Working with Data and Files

Code Snippet 16 shows the possible protection descriptors.


Code Snippet 16:

“SID=S-1-5-21-4392301 AND SID=S-1-5-21-3101812”


“SDDL=O:S-1-5-5-0-290724G:SYD:(A;;CCDC;;;S-1-5-5-0-290724)(A;;DC;;;WD)”
“LOCAL=user”
“LOCAL=machine”
“WEBCREDENTIALS=MyNewPassword”
“WEBCREDENTIALS= MyNewPassword,newweb.com”

4.3.3 Working with Certificates


In public key cryptography, digital certificates are used to bind a public key to computer, organization,
or person. The identities are mostly used to authenticate one entity with the other entity. For example,
certificates are widely used to authenticate a user to a Web server and a Web server to a user.

ÎÎ Setting Certificate Store Capabilities


Certificates are stored on basis of a single user, per app container locations based on their usage in
App. A Windows Store App has write access to only for its own storage. Windows 8 App, other than
the MY and REQUEST store, has read privilege to local machine stores.
The certificates and keys present on the card are informed to the user MY store, when a smart card
is processed by a reader. By default, App containers do not have access to the MY store.
The capabilities concept are supported by the app container isolation model. A capability is nothing
but allowing an app container to use a specific resource. The sharedUserCertificates capability
provides read access to the keys and certificates contained in all stores and the Smart Card Trusted
Roots store. Further, it also provides an app container write privilege to the smart card to allow
direct enrollment of certificates on to smart cards.
The user specifies the sharedUserCertificates capability as shown in Code Snippet 17.
Code Snippet 17:

<Capabilities>
<Capability Name=”sharedUserCertificates” />
</Capabilities>
Concepts

ÎÎ Setting the Certificates Extension


The Certificates extension enables the user to install certificates with the application. It also allows
the user to set certificate selection criteria and specify whether to inherit from system trust.

V 1.0 © Aptech Limited


4
Session Working with Data and Files

Code Snippet 18 is the certification extension sample.


Code Snippet 18:

<Extensions>
<!--Certificates Extension-->
<Extension Category=”windows.Certificates”>
<Certificates>
<Certificate StoreName=”Root” Content=”Certificates\Root\myrootone.
cer”/>
<Certificate StoreName=”Root” Content=”myroottwo.cer”/>
<Certificate StoreName=”TrustedPeople” Content=”mypeerone.sst”/>
<Certificate StoreName=”Issuer” Content=”myissuer.cer”/>
<TrustFlags ExclusiveTrust=”true”/>
<SelectionCriteria HardwareOnly=”true” AutoSelect=”true”/>
</Certificates>
</Extension>
</Extensions>

ÎÎ Creating a Certificate Request


The user must first create a CertificateRequestProperties object to create a certificate
request. Then, the essential certificate properties are defined.
Table 4.1 lists the properties.

Property Default value


Subject Empty string
KeyAlgorithmName KeyAlgorithmNames.RSA
KeySize KeySize.RSA2048
FriendlyName Empty String
HashAlgorithmName HashAlgorithmNames.Sha256
Exportable ExportOption.NotExportable
KeyUsages EnrollKeyUsage.Signing
Concepts

KeyProtectionLevel KeyProtectionLevel.NoConsent
KeyStorageProviderName KeystorageProviderNames.SoftwareKeyStorageProvider

This is the ‘Microsoft Software Key Storage Provider’


Table 4.1: Properties

V 1.0 © Aptech Limited


4
Session Working with Data and Files

ÎÎ Installing a Certificate Using a Manifest


The user can write a Windows 8 App that uses their own trust anchor instead of inheriting from
system trust. They use the Certificates extension to identify the trust certificates, the user wants to
install when their application is deployed. Code Snippet 19 adds a root certificate and a standalone
CA certificate to app container stores.
Code Snippet 19:

<Extensions>
<!--Certificates Extension-->
<Extension Category=”windows.certificates”>
<Certificates>
<Certificate StoreName=”Root” Content=”myroot.cer” />
<Certificate StoreName=”CA” Content=”mystandca.cer”/>
<TrustFlags ExclusiveTrust=”true” />
</Certificates>
</Extension>
</Extensions>
Concepts

V 1.0 © Aptech Limited


4
Session Working with Data and Files

4.4 Check Your Progress


1. JSON is a ____________________.

(A) Data-interchange format (C) Language independent


(B) Light-weight compared to XML (D) All of these

2. The method is _______________ to serialize the JsonObject as JSON text.

(A) JsonObject::Stringify (C) JsonObject::Append

(B) JsonObject::Insert (D) None of these

3. Which of the following is not a data sharing method?

(A) Share Charm (C) Search Charm


(B) Tap and Send (D) Copy and Paste

4. In public key cryptography, ___________________ are used to bind a public key to computer.

(A) Digital certificates (C) Private key


(B) Hashed data (D) All of these

5. ________________ is used to protect e-mails, credit card information, and corporate data.

(A) Cryptography (C) JSON data format


(B) Hashed data (D) All of these


Concepts

V 1.0 © Aptech Limited


4
Session Working with Data and Files

4.4.1 Answers
1. D
2. A
3. C
4. A
5. A
Concepts

V 1.0 © Aptech Limited


4
Session Working with Data and Files

Summary
ÎÎ JSON data format is a lightweight and language independent data exchange format used on the
Web.
ÎÎ JSON data is based on two data structures namely Key/Value pairs and Ordered list.
ÎÎ Data sharing formats discussed include Share Charm, Tap and Send, and Copy and Paste.
ÎÎ Manipulating cryptographic data and hashing data were discussed.
ÎÎ Methods involved in creating certificate files were discussed.
ÎÎ Process involved in data protection were discussed.

Concepts

V 1.0 © Aptech Limited


Session - 5
Connecting to Networks
and Web Services
Welcome to the session, Connecting to Networks and Web
Services.

The session will discuss how to connect to networks and Web services, how
to authenticate resources, concepts of data caching, and how to connect
to sockets and Web sockets.

In this session, you will learn about:


ÎÎ Explain how to set network capabilities

ÎÎ Describe how to authenticate and secure resources

ÎÎ Explain the concept of data caching

ÎÎ Describe how to stay connected in the background

ÎÎ Describe how to connect to Web services

ÎÎ Describe how to connect to sockets and Web sockets

ÎÎ Describe how to work with syndicated content


5
Session Connecting to Networks and Web Services

5.1 Introduction
This session will teach the users how to create connected apps. The user can use a connected app, also
called a network-aware app, that will help them to use a network for multiple purposes such as playing
games, getting feeds, games, and interacting with other devices close by.

5.2 Setting Network Capabilities


A user can isolate a network and map network capabilities. They can help control the access to a network
completely for any app of the Windows Store.
They should be aware of the following technologies:

ÎÎ Windows.Networking.BackgroundTransfer: Enables a user to perform advanced upload and


download.

ÎÎ Windows.Networking.Sockets: Helps a user in network communication by using WebSockets


and sockets.

ÎÎ Windows.Web.AtomPub: Helps a user access any Web resources by using the protocol called
AtomPub.

ÎÎ Windows.Web.Http: Provides a user with an API based on a HTTP client to connect to Web
services.

ÎÎ Windows.Web.Syndication: Helps a user manage feeds from RSS.

ÎÎ System.Net.Http: Enables a user to connect to Web services by using a Web client with only
C#/VB languages.

ÎÎ Prerequisites
The apps written in JavaScript will be affected apart from those written in languages such as C#,
VB.NET, and C++ based on .NET Framework 4.5.

ÎÎ Network Isolation Checklist


They can use the following checklist to determine if the network isolation is available for their app:
Concepts

yy Find out the direction of the network access that is required by the app. These requests
could be inbound unsolicited, outbound client-initiated, or it could be a combination.
yy Identify the network resources that will communicate with the app. The resources could be
trusted resources available on the Home/Office network, or on the Internet.
yy The user must also configure the minimum applicable networking isolation capabilities.

V 1.0 © Aptech Limited


5
Session Connecting to Networks and Web Services

yy They should configure and test the app by using the network isolation tools.

ÎÎ Capabilities Related to Network Isolation


In Windows 8, the application security model includes the concept of network isolation. The
Windows 8 OS actively tries to locate the boundaries of the network and restricts access to networks
for network isolation.
Table 5.1 lists the network boundaries that a system looks for.

Items Description
Home\Work Network This is the local home or office network. Internet proxies are not
included. Within a domain, the boundary includes subnets and
Active Directory sites ranges.
Internet This does not include either the Office or Home network. This
comprises proxy servers that give access to the Internet. A
network that is not part of Home\Work Network is considered as
the Internet.
Table 5.1: Network Boundaries
The app should have some capabilities related to networking for the app to get access to the network.
The capabilities are called Security Identifiers (SIDs). These are enabled by the OS to implement the
boundaries.
Table 5.2 lists the security identifiers.

Visual Studio Terms Description


Internet (Client) This gives outbound access to the Internet and any public
networks, such as airports. Apps that need to access the
net, utilize the capability.
It is a internetClient capability available in the app’s
manifest.
Internet (Client & Server) This provides the app inbound and outbound access to a
network over the Internet and any public networks.
It is a internetClientServer capability of the app
manifest.
Private Networks (Client & This provides the app with inbound and outbound
Server) network access at many trusted places.
Concepts

It is a privateNetworkClientServer capability of the


app manifest.
Table 5.2: Security Identifiers
They have to enable a few other capabilities (called as GUIDs) in the app to get access to the network.

V 1.0 © Aptech Limited


5
Session Connecting to Networks and Web Services

Table 5.3 lists the GUIDs.

Visual Studio Terms Description


Enterprise This will allow an app to connect to any network resource
Authentication that may require domain credentials.
It is the enterpriseAuthentication capability of the
app manifest.
Proximity This is required for any near-field proximity communication
with some devices that are in close proximity with
a computer. It is the proximity capability of the app
manifest.
Shared User This ability allows the app to access any software and
Certificates hardware certificates. It is the sharedUserCertificates
capability of the app manifest.
Table 5.3: GUIDs
They may also have to enable some device capabilities related to device access. This is required to ensure
the GUIDs function as designed.
Table 5.4 shows the GUIDs functions.

Visual Studio Description


Terms
Webcam This gives them access to any Webcam’s audio-video
feed. It is also the Webcam’s capability available in its
app manifest.
Table 5.4: GUIDs Functions
They should understand the capabilities they need for their app.

ÎÎ Network Boundaries and Isolation


If the Windows OS should implement network isolation, the system should locate the boundaries
for the network in the following ways:
yy Local subnets and the addresses of a home/work network
yy Proxies
Concepts

yy Internet gateways

V 1.0 © Aptech Limited


5
Session Connecting to Networks and Web Services

Figure 5.1 shows the network isolation concept in Windows OS.

Figure 5.1: Network Isolation


When they connect their laptop to a network/WI-Fi network for the first time, they are asked if they
want to share their network. Then, Windows categorizes their network as trusted or non-trusted.
They can include a network endpoint as a part of the Home\Work Network for the following
conditions:
yy Categorize it as a part of the local subnet which is part of a trusted network
yy Is on a network
yy Is authorized for a domain controller
yy If it is configured for DirectAccess and it is part of the Intranet
yy Other endpoints that do not meet the conditions are considered legit on the Internet

ÎÎ Network Enforcement and Isolation


The system checks the capabilities that are enabled for an app in the manifest and decides to block/
allow an outbound request that is initiated by the client server for a specific host. If the system
allows the outgoing client-initiated request, then, the server responses are also allowed.
When the app listens to inbound and unwarranted pings, the system checks the app capabilities
decides whether to block or allow the communication from a remote IP address. An app should have
enabled either an InternetClientServer or a privateNetworkClientServer capability to
be allowed.

ÎÎ Loopback and Network Isolation


Concepts

Interprocess communication (between two apps) cannot use network communications using an IP
loopback address as it is restricted due to the concept of network isolation.
Network communication that happens in any app inside a communication process is allowed using
IP loopback address.

V 1.0 © Aptech Limited


5
Session Connecting to Networks and Web Services

ÎÎ Toast Notifications and Background Transfer


The classes such as BackgroundDownloader and BackgroundUploader in the Windows.
Networking.BackgroundTransfer namespace, which are parts of Windows Server 2012 R2
and Windows 8.1 permit a user to receive tile and toast notifications in case of a failure. If an app
must use the class Windows.Networking.BackgroundTransfer to communicate by using
a toast notification, they should declare its Toast capability in the app manifest. The capability
setting is available in the Notifications section of the Application tab.
To enable the app to receive toast notifications, they should set the option Toast capable to Yes.
If the capability is not enabled, then, the toast settings in the class Windows.Networking.
BackgroundTransfer namespace are ignored and the app will not receive toasts.

5.3 Securing Connections and Authenticating Requests


The Windows Runtime service enables the Windows Store Apps to secure connections. The service also
provides authentication details that are necessary to implement and use a secure network connection.
The technologies that are useful are as follows:

ÎÎ Windows.Networking.Sockets

ÎÎ Windows.Networking.BackgroundTransfer

ÎÎ Windows.Web.Syndication

ÎÎ Windows.Web.AtomPub

ÎÎ Create a Secure Socket Connection


Cryptographic protocols such as Secure Sockets Layer (SSL) and Transport Layer Security (TLS) are
developed to authenticate and encrypt any communication over a network. They can configure a
StreamSocket object to use the protocols to communicate to the client or the server. Only using
the StreamSocket object as a client in the SSL/TLS negotiation is allowed.

ÎÎ Create a Secure WebSocket Connection


Similar to a traditional socket connection, the WebSocket connection can encrypted with the
SSL/TSL protocols when they use the StreamWebSocket and MessageWebSocket features in
Windows 8. Apart from this, a server can also need to see a Sec-WebSocket-Protocol header
Concepts

value for completing the initial handshake, which is like an initial sign.

V 1.0 © Aptech Limited


5
Session Connecting to Networks and Web Services

Figure 5.2 shows a WebSocket.

Figure 5.2: WebSocket


The header value is defined by the Stream SocketInformation.Protocol and
MessageWebSocketInformation.Protocol. This shows that the version of the protocol of a
connection enables the server to understand how to read the initial signs sent by the service.

ÎÎ Provide Authentication Credentials to a Web Service


Apps can interact with secured Web services, if they are allowed by Windows Runtime networking
APIs. The APIs have their personal ways to initialize a client machine or setting a request header with
the credentials for server and proxy authentication. Every method has a PasswordCredential
object. This demonstrates the use of a user name, password, and resource.
Table 5.5 lists a mapping of the networking APIs.

API Mapping
Concepts

WebSockets MessageWebSocketControl.ServerCredential
MessageWebSocketControl.ProxyCredential
StreamWebSocketControl.ServerCredential
StreamWebSocketControl.ProxyCredential

V 1.0 © Aptech Limited


5
Session Connecting to Networks and Web Services

API Mapping
Background BackgroundDownloader.ServerCredential
Transfer BackgroundDownloader.ProxyCredential
BackgroundUploader.ServerCredential
BackgroundUploader.ProxyCredential
Syndication SyndicationClient(PasswordCredential)
SyndicationClient.ServerCredential
SyndicationClient.ProxyCredential
AtomPub AtomPubClient(PasswordCredential)
AtomPubClient.ServerCredential
AtomPubClient.ProxyCredential

Table 5.5: Networking APIs

5.4 Data Caching During Network Operations


Data caching can be done using the following network operations in an app:

ÎÎ Caching Network Content as App Data


If the users store data on a disk, they enable the app to work with speed and fluidity. This will help
if the app terminates unexpectedly or if there is a usage restriction. If the app that reads feeds
from an RSS service can show feeds cached to a disk from earlier sessions. When the latest feed is
available, the app updates the data. This will ensure that a user can view some content immediately
after the launch.
Windows 8 enables the class ApplicationData in the Windows.Storage namespace. The class
gives access to the Windows Store Apps data. Application data is mutable and is specific to a specific
type of app. The app data contains user preferences, runtime state, and other similar settings.
App data is developed, viewed, modified, and removed when an app is functioning. Files that are
transferred by the app are cached as app data in the Local, Roaming, or the Temporary folders.
Table 5.6 lists the folder details.

Folder Descriptions
Local Files get saved on the local machine. The files are not
Concepts

synchronized with any other devices.


Temporary Files can be deleted when they are not in use. The system
decides to delete a file depending on whether there is disk
space and how old the file is.

V 1.0 © Aptech Limited


5
Session Connecting to Networks and Web Services

Folder Descriptions
Roaming Such files get synchronized with all the devices that they sign
is with connected accounts. Roaming is not instantaneous.
They should be sure to keep the usage lower than the quota
as defined by the property RoamingStorageQuota. If not,
the roaming of data can get suspended. If an app is writing to
a file, such files cannot be roamed. They should close the file
objects when they are not required.
Table 5.6: Folder Details
Initially, they define a reference to the Roaming folder. Then, the cacheResponse file helps to
create a new file in the Roaming folder. It shows that an existing file with a same name, as the
previous one must be overwritten. After a file is created, the new serverResponse.txt file is
created based on the file originally returned from the response of the server.
Code Snippet 1 shows the caching of the response from a server.
Code Snippet 1:

var roamFolder = Windows.Storage.ApplicationData.current.roamFolder;


var filename = “serverResponse.txt”;
function cacheResponse(strResponse) {
roamFolder.createFileAsync(filename, Windows.Storage.
CreationCollisionOption.replaceExisting)
.done(function (file) {
return Windows.Storage.FileIO.writeTextAsync(file, strResponse);
});
}
//The user can use this to access a cached serverResponse.txt file later. The
example helps retrieve the file, and shows the included text.//
JavaScript
function getCachedResponse() {
roamFolder.getFileAsync(filename)
.then(function (file) {
Concepts

return Windows.Storage.FileIO.readTextAsync(file);
}).done(function (response) {
print(response);

V 1.0 © Aptech Limited


5
Session Connecting to Networks and Web Services

}, function () {
// getFileAsync or readTextAsync failed.
// No cached response
});
}

The code shows the caching of the response from a server as a .txt file from a network operation.
The code also shows the retrieval of cached data by using the relevant file name.
If the app terminates or is relaunched, caching content, or the app data, that is available in the
server response will allow quicker access and display.

5.5 Staying Connected in the Background


The background network connectivity features available in an app are typically written in JavaScript and
HTML. The users need to understand how to configure these background connectivity options.
Table 5.7 shows the technologies that are used.

Item Description
IXMLHTTPRequest2 This allows access to the Web resources that use an
extension to the XMLHttpRequest object.
System.Net.Http This enables connections made to Web services by using
a modern Web client.
Table 5.7: Technologies

ÎÎ Prerequisites
They will apply the information given here to a connected resource or to an app. The connection
depends solely on the network connections.

ÎÎ Lifecycle Model for Windows Store Apps


Windows 8 OS includes a new lifecycle model for all the Windows Store Apps. This model enhances
the responsiveness of an app running in the foreground. It also reduces the power that a computer
consumes. To enable the real-time networking scenarios for apps that are written in JavaScript
language always remain connected. Following are the new features available:
Concepts

yy Background tasks
yy System trigger for SessionConnected
yy Time triggers
yy Windows Notification Services (WNS)
yy Raw push notifications

V 1.0 © Aptech Limited


5
Session Connecting to Networks and Web Services

The features support continuous connectivity for apps that must receive raw push notifications
when an app is suspended. Such apps are also always available. Many other tasks that run in the
background features may also be used by the app. Other triggers that can be used by the app are
as follows:
yy Triggers for Maintenance (These are periodic time events to signal maintenance activity)
yy Triggers from a system for users and sessions (online ID change, user session is connected or
disconnected, and user is present or away)
yy System triggers for the network status (change in network state, Internet available or
unavailable)
yy System triggers for locking the screen (app add or delete)
They can use a time trigger if the app must run for a short time at an interval. They can use a system
trigger when an app must keep tabs on events.
They can combine multiple triggers in an app to enable different scenarios. Many apps do not use
raw push notifications. Apps may give an impression that they are always running in the background
through a live tile. Their app need not be a lock screen app or even run in the background.

ÎÎ Requirements to Remain Always Connected


If a user wants an app to be always connected, the following two elements are required:
yy Long-running process: This ensures that an incoming network notification is received and
quickly processed.
yy Long-running network connection to any endpoint that is remote: This technique
ensures that an app can send and receive data as and when required.

ÎÎ Lock Screen in the Windows Store Apps


Windows 8 OS includes a new software model that helps them suspend apps when they move
them to the background. When an app is suspended, any packet received by the system cannot be
delivered immediately to the app. The network packets that are coming in may also be dropped.
When the app is suspended, no new packets are sent. Hence, current open network connections
may get closed. Hence, to remain connected, the app must be a lock screen app.

ÎÎ Using WNS in Windows Store Apps


WNS is a cloud service that Windows Store Apps use to get notifications to perform many actions.
Concepts

WNS is hosted by Windows 8 and can help them to update a live tile, run a code, and send
notifications. To use the WNS service, their local machine should be connected to the Internet.
Only then, the WNS service will be able to communicate.
An app that is running in the foreground can use the WNS service to send notifications, update live
tiles, or even update the badges. Apps need not be on the lock screen to be able to use the WNS
service.

V 1.0 © Aptech Limited


5
Session Connecting to Networks and Web Services

They should use WNS if they must run a code to respond to a push notification. For the apps which
need not be available on the lock screen, WNS provides an update on the live tile.
The use of the WNS service can help improve the power efficiency rather than using the available
network triggers in the apps that are written in C++/XAML and the apps that use the .NET Framework
4.5. These apps are written in C#, VB.NET languages. These could be managed using languages such
as C++ on Windows 8 and Windows Server 2012.
They get the following benefits by using the WNS service:
yy It offers a very powerful solution to deliver notifications for lock screen apps.
yy It makes the developer model for the app simpler.
yy They need not maintain a persistent socket connection between a client app and a remote
server. Windows OS maintains the connection to the WNS service.
yy It can support most apps available on the local machine.
yy It reduces the server side operational cost as there is no necessity to maintain the TCP
socket connections between a client and a remote server.
yy Their app need not be available in the computer’s memory all the time. The app can be
stopped and the WNS can still update the tile and do other things.
It is recommended that developers of apps for Instant Messengers, VoIP services, and e-mail
messages should use the WNS notifications for lock screen apps.

5.6 Connecting to Web Services


To connect their app to a Web service, a user can use the class Windows.Web.Http.HttpClient. The
class is a WindowsRuntime class and is available for all supported languages.
The apps that are written using C++ and XAML can also use the languages such as C++ REST SDK to
develop any code that is reusable. These codes will be able to run on any desktop applications or other
apps that are available on older versions of the Windows OS and Linux OS.
Table 5.8 shows a summary of the APIs and platforms supported.

API Languages Platform


Windows.Web.Http.HttpClient C#, Visual Basic, C++ Windows 8.1, Windows
Server 2012 R2
System.Net.Http.HttpClient C#, Visual Basic Windows 8.1*, Windows
Server 2012 R2*, Windows
Concepts

8, Windows Server 2012,


Windows 7 SP1, Windows
Server 2008 R2 SP1,
Windows Server 2008 SP 2,
Windows Vista SP 2

V 1.0 © Aptech Limited


5
Session Connecting to Networks and Web Services

API Languages Platform


XML HTTP Extended Request C++ Windows 8.1*, Windows
(IXMLHttpRequest2) Server 2012 R2*, Windows
8, Windows Server 2012
C++ REST SDK C++ Windows 8.1, Windows
Server 2012 R2, Windows
8, Windows Server 2012,
Windows 7 SP 1, Windows
Server 2008 R2 SP1,
Windows Server 2008 SP 2,
Windows Vista SP 2, Linux
Table 5.8: APIs Platforms

5.6.1 Connecting to an HTTP Server


If the user has to send a GET request to any Web service that uses these languages such as C++, Visual
Basic, C#, in an app, they must use the class Windows.Web.Http.HttpClient.
The various classes in the namespace Windows.Web.Http support with a UI for the latest HTTP client
apps. The namespace and its related namespaces Windows.Web.Http.Headers and Windows.Web.
Http.Filters, support the HTTP client components.
A new API is used in place of three separate APIs with varied features. Such different APIs were used for
any language projections within the Windows 8 OS are as follows:
ÎÎ WinJS.xhr for JavaScript
ÎÎ System.Net.Http.HttpClient in the System.Net.Http namespace for C# and VB

ÎÎ XML HTTP Extended Request (IXMLHTTPRequest2) for C++


For all simple requests, the API Windows.Web.Http.HttpClient includes a simplistic design that
can handle all common tasks. It also gives sensible defaults to authenticate (AUTH). This applies to many
scenarios. For other complex operations over HTTP, extra capabilities will be needed.

ÎÎ Methods for common verbs (DELETE, GET, PUT, and POST)

ÎÎ Support for common authentication settings and patterns

ÎÎ Access to Secure Sockets Layer (SSL) details on the transport


Concepts

ÎÎ Ability to include customized filters in advanced apps

ÎÎ Ability to get, set, and delete cookies

ÎÎ HTTP Request progress info available on asynchronous methods

V 1.0 © Aptech Limited


5
Session Connecting to Networks and Web Services

The class Windows.Web.Http.HttpClient can be used to send/receive messages over HTTP.


This class is the main class to send/receive any HTTP requests from resources identified by the URI. The
class is used to send a PUT, GET, POST, DELETE, and so on requests to the required Web service.

ÎÎ Create a new project


The user should use the following steps:
1. Open Microsoft Visual Studio 2012.
2. From the File menu, select New Project.
3. From the list of templates, select Visual C++, Visual C#, or Visual C++.
4. Under the relevant section, select the app, and then, click Blank Application.
5. For the name of the app, type ‘HttpClientGet’, and then, click OK.

ÎÎ Set capabilities to enable network access


The user can set the network capabilities for their app and give access to any network. For the app,
they will have to enable the network capabilities as their client will be looking for Web services.
The user will need Internet (Client) capability if their app has to connect as a client to a Web service.
Any private networks capability will be needed if their app wants to connect as a client.

ÎÎ Add XAML UI
The user first defines the app layout in XAML. They specify the size and the position of each object.
They complete the app’s UI and add controls and content.
The sample here uses the following simple XAML UI elements:
yy A horizontal StackPanel containing a TextBlock for a Label, a TextBox for the input URI
address, and a Button used to start the asynchronous request.
yy A horizontal StackPanel containing a TextBlock for a Label and a TextBox for the current
status. This is where status and error messages will be displayed.
yy A StackPanel containing a TextBox where the output received from the Web service is
displayed. In this sample, the result of the HTTP GET operation is displayed as plain text
containing HTML markup. You can change the output display from plain text to a WebView
by using a WebView instead of a TextBox.
Concepts

The user must open the cs or the cpp folder. Then, they must open an existing BlankPage.xaml
file and rename the file as, MainPage.xaml.

V 1.0 © Aptech Limited


5
Session Connecting to Networks and Web Services

They should add these UI elements as shown in Code Snippet 2.


Code Snippet 2:
XAML

<Page
x:Class=”HttpClientGet.MainPage”
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
xmlns:local=”using:HttpClientGet”
xmlns:d=”http://schemas.microsoft.com/expression/blend/2008”
xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006”
mc:Ignorable=”d”>
<Grid Background=”{ThemeResource ApplicationPageBackgroundThemeBrush}”>
<StackPanel Orientation=”Vertical”>
<StackPanel Orientation=”Horizontal”>
<TextBlock Text=”URI Address:” FontSize=”24” Height=”28”
Margin=”30,30,0,0” />
<TextBox x:Name=”inputAddress” Text=”http://www.contoso.com”
FontSize=”13”
Height=”41” Width =” 471” Margin=”31,31,0,0” />
<Button Content=”Start” Click=”Start_Click” Margin=”51,21,0,0”
FontSize=”25” Height=”81” Width=”121” />
</StackPanel>
<StackPanel Orientation=”Horizontal”>
<TextBlock Text=”Status:” FontSize=”23” Height=”29” Margin=”30,20,0,0” />
<TextBox x:Name=”statusText” Text=”Idle” FontSize=”17” Height=”Auto”
Width=”700”
TextWrapping=”Wrap” Margin=”31,31,0,0” />
</StackPanel>
Concepts

<StackPanel Orientation=”Horizontal”>
<TextBox x:Name=”outputView” FontSize=”17” Margin=”30,30,0,0”
TextWrapping=”Wrap”
Height=”401” Width=”801” ScrollViewer.
VerticalScrollBarVisibility=”Visible”/>

V 1.0 © Aptech Limited


5
Session Connecting to Networks and Web Services

</StackPanel>
</StackPanel>
</Grid>
</Page>

ÎÎ Create the HttpClient


The user can create an object called Windows.Web.Http.HttpClient object and then,
add a user-agent header. They will then, add the header to the property HttpClient.
DefaultRequestHeaders.
In the C# language, they must open the cs folder and then, the MainPage.xaml.cs file. They have
to add the given Code Snippet 3.
Code Snippet 3:
C#

using System;
using Windows.Web.Http;
using Windows.Web.Http.Headers;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Navigation;
namespace HttpClientGet
{
public sealed partial class MainPage : Page
{
private HttpClient httpClient;
private HttpResponseMessage resp;
public MainPage()
{
this.InitializeComponent();
httpClient = new HttpClient();
Concepts

// Add a user-agent header


var headers = httpClient.DefaultRequestHeaders;
// HttpProductInfoHeaderValueCollection is a collection of
// HttpProductInfoHeaderValue items used for the user-agent header

V 1.0 © Aptech Limited


5
Session Connecting to Networks and Web Services

// The safe way to check a header value from the user is the TryParseAdd method
// Since you know this header is okay, you use ParseAdd with will throw an
exception
// with a bad value
headers.UserAgent.ParseAdd(“ie”);
headers.UserAgent.ParseAdd(“Mozilla/5.0 (compatible; MSIE 10.0; Windows NT
6.2; WOW64; Trident/6.0)”);
}
}
}

ÎÎ Send the GET request and receive the response


When the users click the Start button, they first check if the URI is valid. Then, they will send any
GET request by using the URI. They will wait to get a response from the HTTP server.
An error will be thrown if any invalid URI string is passed to the constructor for the Windows.
Foundation.Uriobject. For .NET Framework 4.5, the System.Uri class will be used in place
of the class Windows.Foundation.Uri.
They can avoid this error if they use the class System.Uri in the .NET Framework 4.5. The example
will also check if the HTTP scheme available in the URI is HTTP or HTTPs. As the client supports only
these two.
They can use the await keyword in Visual Basic and C#. Remember that the code to send/receive
the GET request asynchronously is same as the code they would use to complete an operation
synchronously. They can use the await keyword if their method can be defined as async as shown
in Code Snippet 4.
Code Snippet 4:
C#

private async void Start_Click(object sender, RoutedEventArgs e)


{
resp = new HttpResponseMessage();
outputView.Text = “”;
Concepts

// The value of ‘InputAddress’ is set by the user and is therefore, untrusted


input.
// If you can’t create a valid URI,
// You notify the user about the incorrect input.

V 1.0 © Aptech Limited


5
Session Connecting to Networks and Web Services

statusText.Text = “Test if URI is valid”;


Uri resourceUri;
if (!Uri.TryCreate(inputAddress.Text.Trim(), UriKind.Absolute, out
resourceUri))
{
statusText.Text = “Invalid URI, please re-enter a valid URI”;
return;
}
if (resourceUri.Scheme != “http” && resourceUri.Scheme != “https”)
{
statusText.Text = “Only ‘http’ and ‘https’ schemes supported. Please re-enter
URI”;
return;
}
string responseBodyAsText;
statusText.Text = “Waiting for response ...”;
try
{
HttpResponseMessage response = await httpClient.GetAsync(resourceUri);
response.EnsureSuccessStatusCode();
responseBodyAsText = await resp.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
// Need to convert int HResult to hex string
statusText.Text = “Error = “ + ex.HResult.ToString(“X”) +
“ Message: “ + ex.Message;
}
Concepts

statusText.Text = resp.StatusCode + “ “ + resp.ReasonPhrase;


// Format the HTTP response to display better
responseBodyAsText = responseBodyAsText.Replace(“<br>”, Environment.
NewLine);

V 1.0 © Aptech Limited


5
Session Connecting to Networks and Web Services

outputView.Text = responseBodyAsText;
}
}

The class Windows.Web.Http.HttpClient will use WinInet to send HTTP and Web service
requests and to get responses. For an HTTP connect operation, the default timeout value is only
60 seconds.

5.6.2 Connecting Using an XML HTTP Request


To send the requests, a user uses HTTP GET and POST to a Web service by using the C++ language in an
app. The developer can use XML HTTP Extended Request and the IXMLHTTPRequest2 interfaces.
The class IXMLHTTPRequest2 will permit the apps to function in a Multi-Threaded Apartment (MTA).
This is a pre-requisite to run in the Windows Runtime. When the app runs in an MTA, a thread with access
to an object called an IXMLHTTPRequest2 will not block any request for any other IXMLHTTPRequest2
objects that may run in the same environment.
The interface will also implement a call back model to handle events. As the methods of the
sample IXMLHTTPRequest2 will allow only asynchronous calls, an app has to pass a pointer to an
IXMLHTTPRequest2Callback object as shown in Code Snippet 5.
Code Snippet 5:

HRESULT hr = S_OK;
DWORD dwStatus = 0;
BOOL fAbort = TRUE;
ComPtr<IXMLHTTPRequest2> spXHR;
ComPtr<CXMLHttpRequest2Callback> spXhrCallback;

The user will create and then, initialize the instances of the objects, IXMLHTTPRequest2 and
IXMLHTTPRequest2Callback as shown in Code Snippet 6.
Code Snippet 6:

//
// Create and initialize an IXMLHTTPRequest2 object
//
Concepts

hr = CoCreateInstance(CLSID_FreeThreadedXMLHTTP60,
NULL,
CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&spXHR));

V 1.0 © Aptech Limited


5
Session Connecting to Networks and Web Services

//
//Create and initialize an IXMLHTTPRequest2Callback object
//
hr = MakeAndInitialize<CXMLHttpRequest2Callback>(&spXhrCallback);
//The developer will first configure a GET request and then, send the request to a
server.
C++
hr = spXHR->Open(L”GET”, // Method.
pcwszUrl, // Url.
spXhrCallback.Get(), // Callback.
NULL, // Username.
NULL, // Password.
NULL, // Proxy username.
NULL); // Proxy password.
//
//Send the GET request
//
hr = spXHR->Send(NULL, 0);
Wait for the completion of the request.
C++
hr = spXhrCallback->WaitForComplete(&dwStatus);

ÎÎ Create and send a POST request


First, the user will create references that are required for an operation as well as a callback as
shown in Code Snippet 7.
Code Snippet 7:

HRESULT hr = S_OK;
Concepts

DWORD dwStatus = 0;
ULONGLONG ullFileSize = 0;
BOOL fAbort = TRUE;
ComPtr<IXMLHTTPRequest2> spXHR;
ComPtr<CXMLHttpRequest2Callback> spXhrCallback;

V 1.0 © Aptech Limited


5
Session Connecting to Networks and Web Services

ComPtr<CXMLHttpRequestPostStream> spXhrPostStream;

The user will create and then, initialize objects of IID_IXMLHTTPRequest2,


CXMLHTTPRequest2Callback, and XMLHTTPRequestPostStream classes as shown in Code
Snippet 8.
Code Snippet 8:

//Initialize IXMLHTTPRequest2Callback
hr = MakeAndInitialize<CXMLHttpRequest2Callback>(&spXhrCallback);
if (FAILED(hr))
{
goto Exit;
}
// Create an object of the CXMLHttpRequestPostStream class
spXhrPostStream = Make<CXMLHttpRequestPostStream>();
if (spXhrPostStream == NULL)
{
hr = E_OUTOFMEMORY;
goto Exit;
}

The user will attempt to open a file to understand its size as shown in Code Snippet 9.
Code Snippet 9:

//
//Open the file
//
hr = spXhrPostStream->Open(pcwszFileName);
//
//Get file size
//
Concepts

hr = spXhrPostStream->GetSize(&ullFileSize);

V 1.0 © Aptech Limited


5
Session Connecting to Networks and Web Services

The developer must send a POST request to a server as shown in Code Snippet 10.
Code Snippet 10:
//
//Configure the POST request
//
hr = spXHR->Open(L”POST”, // Method.
pcwszUrl, // Url.
spXhrCallback.Get(), // Callback.
NULL, // Username.
NULL, // Password.
NULL, // Proxy username.
NULL); // Proxy password.
if (FAILED(hr))
{
goto Exit;
}
//
//Send the POST request
//
hr = spXHR->Send(spXhrPostStream.Get(), ullFileSize);
if (FAILED(hr))
{
goto Exit;
}
Wait till the request is completed as shown in Code Snippet 11.
Code Snippet 11:

hr = spXhrCallback->WaitForComplete(&dwStatus);
Concepts

if (FAILED(hr))
{
goto Exit;
}
fAbort = FALSE;

V 1.0 © Aptech Limited


5
Session Connecting to Networks and Web Services

5.6.3 Connecting to an HTTP Server


The user can connect to a Web service by using the System.Net.Http.HttpClient class written
using C# or Visual Basic in an app.
The namespace System.Net.Http and any related namespaces give the components of the HTTP
client and allow the users to use Web services over a HTTP connection.
The user can use the System.Net.Http.HttpClient class to send/receive requests over a HTTP
connection.

ÎÎ Create a new project


The user must access Microsoft Visual Studio 2012. From the File menu, click New Project, and
from the list of templates, select Visual C#. Select the app and then, click Blank Application,
then, type a name for app ‘HttpClientBasic’ and then, click OK.

ÎÎ Set capabilities to enable network access


The user must set network capabilities for their app if they want to access any private network
and the Internet. They must enable relevant network capabilities, as a client will connect to Web
services.
The user should use the following steps to set up network capabilities for their app:
1. To open the package.appxmanifest file, the user should use the Visual Studio 2012 package.
2. Click Capabilities.
3. Select the Internet (Client).
4. Select Private Networks (Client & Server) capabilities.
5. Save and close the manifest file.

ÎÎ Add XAML UI
The user will learn about layout of an app in XAML to understand the size and the position of each
object within an app. The given sample includes XAML UI elements:
yy The horizontal StackPanel has a TextBlock as a label, the input URI address is a TextBox,
and a Button used helps start an asynchronous request.
yy The horizontal StackPanel contains a TextBlock for a label. It also contains a TextBox for
its current status. The status and the error messages are displayed.
Concepts

The output from the Web service displays in the Grid. The user should open the folder called cs.
Then, they must open the blankPage.html file.

V 1.0 © Aptech Limited


5
Session Connecting to Networks and Web Services

They have to rename as, MainPage.xaml as shown in Code Snippet 12.


Code Snippet 12:

<Page
x:Class=”HttpClientBasic.BlankPage”
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
xmlns:local=”using:HttpClientBasic”
xmlns:d=”http://schemas.microsoft.com/expression/blend/2008”
xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006”
mc:Ignorable=”d”>
<Grid Background=”{StaticResource ApplicationPageBackgroundBrush}”>
<StackPanel Orientation=”Vertical”>
<StackPanel Orientation=”Horizontal”>
<TextBlock Text=”URI Address:” FontSize=”16” Height=”20” Margin=”15,0,0,0”
/>
<TextBox x:Name=”InputAddress” Text=”http://www.contoso.com”
FontSize=”16” Height=”20” Margin=”15,0,0,0” />
<Button Content=”Start” Click=”Start_Click” Margin=”280,0,0,0” />
</StackPanel>
<StackPanel Orientation=”Horizontal”>
<TextBlock Text=”Status:” FontSize=”16” Height=”20” Margin=”15,0,0,0” />
<TextBox x:Name=”StatusText” Text=”Idle” FontSize=”16” Height=”Auto”
TextWrapping=”Wrap” Margin=”15,0,0,0” />
</StackPanel>
<Grid
Grid.Column=”1” Margin=”15,0,0,0”>
<Grid.RowDefinitions>
<RowDefinition Height=”Auto” />
Concepts

<RowDefinition Height=”*” />


</Grid.RowDefinitions>
<TextBlock x:Name=”OutputView” FontSize=”16” Height=”Auto”
Margin=”15,0,0,0” TextWrapping=”Wrap” />

V 1.0 © Aptech Limited


5
Session Connecting to Networks and Web Services

</Grid>
</StackPanel>
</Grid>
</Page>

5.6.4 Connecting to Bing Maps


The user must use the class Windows::Web::Http::HttpClient if they want to connect to Bing
Maps. They must use this class if they are using the C++ language within an app. They must create an
account in the Bing Maps Location API. They should also get a key that their app will use to access any
service.

ÎÎ Create a new C++ Windows Store Blank App Project


They can access Visual Studio to create a project. They use the template called Blank App. They
must name it as, BingMapsWithHttpClient.

ÎÎ Create the User Interface (UI)


The UI includes two TextBox controls. These controls will help the user to enter values for the
longitude and latitude. This is a TextBlock. It will show the information about location that is
thrown by the Bing browser. They must add the given XAML StackPanel code to the available grid
in the page called MainPage.xaml as shown in Code Snippet 13.
Code Snippet 13:

<StackPanel>
<TextBlock x:Name=”TitleText” HorizontalAlignment=”Left”
Margin=”10,10,0,0”
TextWrapping=”Wrap” Text=”Connect to Bing Maps Web Service using the C++ REST
SDK”
VerticalAlignment=”Top” Height=”52” Width=”1356” FontSize=”36”/>
<StackPanel HorizontalAlignment=”Left” Height=”204” Margin=”20,25,0,0”
VerticalAlignment=”Top” Width=”922”>
<StackPanel Orientation=”Horizontal”>
<TextBlock Padding=”0,0,10,0” FontSize=”14” Text=”Enter a valid latitude:”
Concepts

Width=”152”></TextBlock>
<TextBox x:Name=”Latitude” TextWrapping=”Wrap” Text=”47.640194”
Height=”28” Width=”149”/>

V 1.0 © Aptech Limited


5
Session Connecting to Networks and Web Services

</StackPanel>
<StackPanel Orientation=”Horizontal”>
<TextBlock Padding=”0,0,10,0” FontSize=”14” Text=”Enter a valid
longitude:”></TextBlock>
<TextBox x:Name=”Longitude” TextWrapping=”Wrap” Text=”-122.129865”
Height=”28.519”
UseLayoutRounding=”False” Width=”149.021” d:LayoutRounding=”Auto”/>
</StackPanel>
<Button x:Name=”LocationButton” Content=”Get Location” Height=”50”
Width=”304” Click=”Button_Click”/>
<StackPanel Orientation=”Horizontal” Margin=”0,20,20,20”>
<TextBlock Padding=”0,0,10,10” FontSize=”14” Text=”Bing Maps Response:”></
TextBlock>
<TextBlock x:Name=”BingMapsResponse” FontSize=”14”
HorizontalAlignment=”Left” TextWrapping=”Wrap”
VerticalAlignment=”Top” Width=”744”/>
</StackPanel>
</StackPanel>
</StackPanel>

The user must add a button handler for the class LocationButton.

ÎÎ Connect to Bing Maps Location API and Parse the Results


The user uses the GetLocationAsync method to get the work done. This method shows how
they create an URI first. Then, they send any request to the relevant Web service. This contains the
longitude and latitude data apart from a query string. The string tells them that the response must
be formatted as JSON. It also provides them with the unique key.
They then, develop a new object called as, Windows::Web::Http::HttpClient. This will
include an HTTP session. The method GetStringAsync commences the asynchronous GET
operation.

5.6.5 Handling Exceptions in Network Apps


Concepts

The user will learn to manage exceptions while they use networking APIs in apps that are written in
languages such as VB.NET, C#, or C++.

V 1.0 © Aptech Limited


5
Session Connecting to Networks and Web Services

Technologies that are important for a user are as follows:

ÎÎ Windows.Networking.Sockets: It helps network communications by using WebSockets and


sockets.

ÎÎ Windows.Web.Http: It provides a modern client API for apps based on HTTP and REST.

ÎÎ Exceptions in Network Apps


When there is an error in their app, a user must understand that there is a failure. The exceptions
can occur due to the following reasons:
1. Code can have issues that will throw an error.
2. When networking APIs are used, errors cause network connectivity changes and other
network-related issues.
While using networking APIs, these can cause errors:
yy Improper parameter validation
yy Failure of name resolutions while searching for hostnames or URIs
yy Losing network connectivities
yy Failure of Network connection while using sockets/HTTP client APIs
yy Errors in Network server/remote endpoints
yy Any other miscellaneous issues
They must write codes that can handle all errors when they call the most asynchronous network
methods. When an error happens, the relevant network method is reused. Else, the app has to
continue without any network connectivity.
The apps from Windows Store usually throw only a single failure error. The in-built exception
handler software will get more information on the cause to make appropriate future decisions.

ÎÎ Exceptions in Windows.Networking.Sockets
The constructor used with the class HostName that is useful for sockets can give an error if the string
is not valid. If their app has an input from any user for the class HostName, then, the constructor
also should be part of a try/catch block. If there is an exception, the app will tell the user and ask
for a new host name.
Concepts

ÎÎ Exception in Windows.Networking.BackgroundTransfer
There will be a failure when any invalid string for a URI is sent to a constructor for the object called
as, Windows.Foundation.Uri.

V 1.0 © Aptech Limited


5
Session Connecting to Networks and Web Services

.NET: The Windows.Foundation.Uri type appears as System.Uri in C# and VB.


C# and Visual Basic: The user can avoid this failure if they use the class System.Uri in the .NET
Framework 4.5.

5.7 Connecting with Sockets and Web Sockets


The user can enable their app to send/receive data over WebSockets to ensure security, low-latency, and
real-time bi-directional communication. To do this, the users must use the namespace called Windows.
Networking.Sockets available in the Windows Runtime environment.

ÎÎ Define WebSockets
WebSocket is a two-way communication method, which is very fast and happens over the Internet
between a server and a client machine.
Data transfer is almost immediate and happens over a full-duplex single socket connection. The
messages can be sent/received from both the endpoints. A WebSocket is perfect for an apps that
includes real-time games, social networking, and so on.
For getting a connection, the client and server exchange an HTTP handshake. If the handshake is
successful, the protocol in the application-layer changes to WebSockets.
They must remember that a client cannot transfer data to a server unless the server uses WebSockets.
If there is a mismatch, they should use some other method.
The Windows.Networking.Sockets namespace supports these two types of WebSockets,
MessageWebSocket and StreamWebSocket.
Table 5.9 lists the two types of WebSockets.

MessageWebSocket StreamWebSocket
It can be used very large It can be used to transfer large files such as media
messages. files.
It enables a notification that says It permits few sections of any message to be read in
that the complete WebSocket is each read operation.
received.
It supports binary and UTF-8 It supports only binary type of messages.
messages.
It is similar to a DatagramSocket This is similar to a StreamSocket or TCP socket.
or a UDP socket.
Concepts

Table 5.9: Types of WebSockets

V 1.0 © Aptech Limited


5
Session Connecting to Networks and Web Services

5.7.1 Connecting with a StreamSocket and DatagramSocket


The user will learn about enabling an app to receive/send data using the StreamSocket with a TCP
StreamSocket.

ÎÎ Connecting with a StreamSocket


TCP socket allows bi-directional transfer of data at a lower level over a network. The TCP sockets
are used by mostly all the network protocols as shown in Code Snippet 14.
Code Snippet 14:

<Page
x:Class=”StreamSocketBasic.BlankPage”
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
xmlns:local=”using:StreamSocketBasic”
xmlns:d=”http://schemas.microsoft.com/expression/blend/2008”
xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006”
mc:Ignorable=”d”>
<Grid Background=”{StaticResource ApplicationPageBackgroundBrush}”>
<StackPanel Orientation=”Vertical”>
<StackPanel Orientation=”Horizontal”>
<TextBlock Text=”Hostname:” FontSize=”16” Height=”20” Margin=”15,0,0,0” />
<TextBox x:Name=”ServerHostname” Text=”www.contoso.com” FontSize=”16”
Height=”20” Margin=”15,0,0,0” />
<TextBlock Text=”Port:” FontSize=”16” Height=”20” Margin=”15,0,0,0” />
<TextBox x:Name=”ServerPort” Text=”http” FontSize=”16” Height=”20”
Margin=”15,0,0,0” />
<Button Content=”Connect” Click=”Connect_Click” Margin=”220,0,0,0” />
</StackPanel>
<StackPanel Orientation=”Horizontal”>
Concepts

<TextBlock Text=”Text to send:” FontSize=”16” Height=”20” Margin=”15,0,0,0”


/>
<TextBox x:Name=”SendText” Text=”hello” FontSize=”16” Height=”20”
Margin=”15,0,0,0” />
<Button Content=”Send” Click=”Send_Click” Margin=”220,0,0,0” />

V 1.0 © Aptech Limited


5
Session Connecting to Networks and Web Services

</StackPanel>
<StackPanel Orientation=”Horizontal”>
<TextBlock Text=”Status:” FontSize=”16” Height=”20” Margin=”15,0,0,0” />
<TextBox x:Name=”StatusText” Text=”Idle” FontSize=”16” Height=”Auto”
TextWrapping=”Wrap” Margin=”15,0,0,0” />
</StackPanel>
<Grid
Grid.Column=”1” Margin=”15,0,0,0”>
<Grid.RowDefinitions>
<RowDefinition Height=”Auto” />
</Grid.RowDefinitions>
<TextBlock x:Name=”OutputView” FontSize=”16” Height=”Auto”
Margin=”15,0,0,0” TextWrapping=”Wrap” />
</Grid>
</StackPanel>
</Grid>
</Page>

This code given here talks about the following:


yy Using the StreamSocket class to help create the TCP socket.
yy Using a StreamSocket.ConnectAsync method to connect to a network and to a TCP
network server.
yy Sending data to a server by using the object Streams.DataWriter. The object permits
them to develop integers or strings, that is common types on a stream.
yy Receiving data from the server by using an object called Streams.DataReader. This
permits them to scan common types on the stream.

ÎÎ Create a StreamSocket and Connect to a Server


The code given in this section will create a few variables that include a client socket and some
variables that help track the status.
Concepts

The variables help track if a client socket is connected or closed. It will also define the hostname
apart from defining the service name. The values for the hostname and service name are default
values.

V 1.0 © Aptech Limited


5
Session Connecting to Networks and Web Services

ÎÎ Running the App


If they want to run their app, they must use the F5 key in the Microsoft Visual Studio Express 2012
tool. This will invoke the project. They must select their buttons for connecting, sending data, and
closing a socket.

ÎÎ Connecting with a DatagramSocket


The user will learn about enabling an app to send/receive data with a UDP DatagramSocket by
using a DatagramSocket. They can use the socket to send/receive packets with a low overhead.

ÎÎ Define Variables for Sockets and Event Functions


For example, a listener socket, a client socket, and so on. They can create a variable to track when
a client socket connected or closed.

ÎÎ Create a Listener and Start Listening to a Service Name (Port)


When a user asks a listener to bind an IP address and a UDP port, accept a connection, and read
data sent from the client, other functions are added to handle such events.

ÎÎ Create the Socket and Connect to a Remote Endpoint


The function is added to create a socket. It also helps connect to a remote endpoint. This will be
a server usually. The code adds a function that will handle a message receipt sent by a client. A
function is also added that handles cases, in case there is an exception while the client attempts a
connection.

5.7.2 Using Advanced Socket Controls


Advanced socket options can be configured in an app on a DatagramSocket, a StreamSocket, and by
using the StreamSocketListener features.
ÎÎ Overview of Advanced Controls
The classes DatagramSocket, StreamSocketListener, and StreamSocket are similar and
follow one model to use advanced controls. There are many primary classes that are required to
access the following advanced controls:
yy DatagramSocketControl – It gives socket control data for a DatagramSocket object.
yy StreamSocketControl – This provides socket control data for a StreamSocket object.
Concepts

yy StreamSocketListenerControl – It provides socket control data for a


StreamSocketListener object.
The basic model to use advanced controls is the same for all three classes. The discussion uses
a StreamSocket as an example, but the same process can be used with a DatagramSocket or
StreamSocketListener.

V 1.0 © Aptech Limited


5
Session Connecting to Networks and Web Services

yy Create a StreamSocket.
yy Use the StreamSocket.Control property to get the StreamSocketControl instance
associated with a StreamSocket object.
yy Get or set a property on the StreamSocketControl to set an advanced socket option.

ÎÎ DatagramSocket Controls
A DatagramSocket helps communication over a network by using the UDP DatagramSocket. Many
advanced options that are available on a DatagramSocket.
DatagramSocketControl.QualityOfService – This defines the Quality of Service (QoS) for
a DatagramSocket.
The QOS will affect the thread priority for receiving packets on an object. The QOS can be configured
to any value for SocketQualityOfService. By default, normal setting is used to create the
object. The code sample given here helps them develop a DatagramSocket. It also sets the
DatagramSocketControl.QualityOfService to LowLatency.

ÎÎ StreamSocket Controls
The StreamSocket supports communication over a network by using the TCP StreamSocket.
Following are the advanced options:
yy StreamSocketControl.KeepAlive – It shows when the keep-alive packets get sent to
any destination that is remote.
yy StreamSocketControl.NoDelay – This shows whether Nagle’s algorithm is used or not.
yy StreamSocketControl.OutboundBufferSizeInBytes – This helps control the size of
the sent buffer.
yy StreamSocketControl.QualityOfService – This denotes the QOS of the object.

ÎÎ StreamSocketListener Controls
This will support them to listen for any incoming network connection by using the TCP StreamSocket.
The StreamSocketListener.QualityOfService is the QOS that must be configured on the
object while receiving a connection from the StreamSocketListener object.

5.8 Accessing and Managing Syndicated Content


Concepts

Windows Runtime supports Syndication APIs. They can use these APIs to enable their app in retrieving/
creating latest and popular content for the Web. They can use RSS feeds that are generated as per the
RSS and Atom standards.

V 1.0 © Aptech Limited


5
Session Connecting to Networks and Web Services

ÎÎ Web Feed
It is a document containing many entries of text, hyperlinks, and/or images. Any updates that are
made to a Web feed will be in the form of new entries. These entries will promote the current
content across the Internet.
Consumers use an app that reads feeds to collect and view content from many individual authors.
They get access to latest content almost immediately.
yy Supported Feed Format Standards
Windows Runtime supports these feed retrieval standards:
ŠŠ RSS standards: 0.91 to 2.0
ŠŠ Atom standards: 0.3 to 1.0
The classes called Windows.Web.Syndication help define these feeds. The feed items can
represent both elements to both Atom and RSS standards.
Moreover, feeds from Atom 1.0 and RSS 2.0 formats include elements not defined in official
specifications. Such customized elements and attributes help define any domain-specific
information.

Concepts

V 1.0 © Aptech Limited


5
Session Connecting to Networks and Web Services

5.9 Check Your Progress


1. A Web feed is a __________ containing text, ___________, and images.

(A) Document, Hyperlinks (C) Document, URIs


(B) File, Links (D) Sheet, Links

2. Windows Runtime supports _______ RSS standards.

(A) 0.91 to 2.0 (C) 0.91 to 2.1


(B) 0.91 to 2.2 (D) 0.91 to 2.221

3. _________________ helps a user listen for any incoming network connection by using the TCP
StreamSocket.

(A) Efficiency (C) Speed


(B) Response Levels (D) Errors

4. Nagle’s Algorithm helps improve the ___________ of TCP/IP networks.

(A)
Windows.Networking. (C) StreamSocketListener
Sockets
StreamSocketListener (D) listenSocket.Control.
(B) QualityOfService
Socket Controls

5. The class IXMLHTTPRequest2 will permit the apps to function in a ______________.

Multi-Threaded (C) Macintosh Environment


(A)
Apartment
(B) Multi-level Environment (D) Windows Runtime Environment
Concepts

V 1.0 © Aptech Limited


5
Session Connecting to Networks and Web Services

5.9.1 Answers
1. A
2. A
3. B
4. A
5. A

Concepts

V 1.0 © Aptech Limited


5
Session Connecting to Networks and Web Services

Summary
ÎÎ The user can use a connected app, also called a network-aware app.
ÎÎ The network-aware app will help the user to use a network for multiple purposes such as playing
games, getting feeds, games, and interacting with other devices close by.
ÎÎ A user can isloate a network and map network capabilities.
ÎÎ The apps written in JavaScript will be affected apart from those written in languages such as C#,
VB.NET, and C++ based on .NET Framework 4.5.
ÎÎ The user must also configure the minimum applicable networking isolation capabilities.
ÎÎ They can use the checklist to determine if the network isolation is available for their app.
ÎÎ The user can include a network endpoint as a part of the Home\Work Network.
ÎÎ The system checks the capabilities that are enabled for an app in the manifest and decides to
block/allow an outbound request.
ÎÎ Even if one capability is available, the system allows the app to listen on a port.
ÎÎ When the sockets close, any pending operations halt and exceptions are thrown.
ÎÎ The classes DatagramSocket, StreamSocketListener, and StreamSocket are similar and follow one
model to use advanced controls.
Concepts

V 1.0 © Aptech Limited


Session - 6
Managing User Info
Welcome to the session, Managing User Info.

The session will discuss how to manage information that is important to


the user. It will also discuss to use cryptography and certificates in Windows
Store App.

In this session, you will learn about:

ÎÎ Write introduction about authentication and user identity

ÎÎ Describe to use cryptography and certificates in Windows


Store App

ÎÎ Describe how to data bind a control to a single object

ÎÎ Define and usage of selective wipe

ÎÎ Define securing apps

ÎÎ Describe how to manage user contacts


6
Session Managing User Info

6.1 Authentication and User Identity


Windows Store Apps provided few options for user authentication. The very highly secured authentication
using trusted certificates or smart card authentication is provided by it. It also provides persisted
user credentials or Single Sign-On (SSO). Following are the Windows Store Apps options available for
authentication:

ÎÎ Credential Locker
App uses to connect to services such as mail, messaging, Twitter, Facebook, and so on. The
Credential Locker is a comfortable and safe way to store these user credentials. The user name and
password can be stored in the Credential Locker. When user uses the app, using credential locker,
you can automatically log them on to services. With a user’s Microsoft Account stored credentials
can automatically roam in the Credential Locker.
Some of the user’s Microsoft account tasks can be simplified with the Credential Locker such as
storing and retrieving user credentials safely.
For example, if there is an app to connect that provides assistance for taking protected resources
such as social networking, mail, or media files. Then, each user should be provided with login
information and password. So, a User Interface (UI) should be built in such a way that the app that
takes the user name and password for the user, should then, be used to login the user into the app.

ÎÎ Web Authentication Broker


Sometimes, it is required to integrate the app with a Web service which allows user authentication.
This job is done by the Web authentication broker who supports Internet authentication protocols
such as OAuth and OpenID. It also allows utilizing user identity in the apps from services such as
Google, Flickr, Twitter, and Facebook. For multiple Internet authenticated apps, Web authentication
broker can also be used to allow SSO.
Web authentication broker especially is used in Windows Store Apps to connect to online identity
providers. This is done in the following manner:
AuthenticateAsync method is called by an app that calls the online identity provider then,
sends a request and gets back an access token.

ÎÎ Working of Web Authentication Broker


Web authentication broker works in the following ways:
yy Register your app with your online provider
Concepts

With the online identity provider, the app should be registered which you want to connect.
Once registered, the online provider gives an ID for the app.
yy Build the authentication request URI
The authentication request is sent to the online provider to an address included by request
URI. It is supplemented with other necessary information, such as a redirect URI and app ID.

V 1.0 © Aptech Limited


6
Session Managing User Info

Required parameters can be found by the provider.


The request URI is sent as the requestUri parameter of the AuthenticateAsync method
which should be a safe address which starts with https://.
Code Snippet 1 demonstrates how to build the request URI.
Code Snippet 1:
C#

string beginURL = “https://<specifyproviderendpoint>?client_


id=<clientid>&scope=<scopes>&response
_type=token”;
string finalURL = “http://<specifyappendpointhere>”;
System.Uri beginURI = new System.Uri(beginURL);
System.Uri finalURI = new System.Uri(finalURL);

In this code, the beginURL is a string value which is an authentication request including the
parameters such as client_id, scope, and response_type. The finalURL is the redirect url to
which the App is redirected, once the authentication request is successful. Both the beginURL and
finalURL are initialized using System.URI class to have the url of same type.

ÎÎ Connect to the Online Provider


Connecting to the identity of online provider and getting an access token can be done by calling
the AuthenticateAsync method. As the requestUri parameter is constructed in the previous
method which takes the URI and a user to be redirected as the callbackUri parameter URI.
Code Snippet 2 shows connecting to an online identity provider.
Code Snippet 2:

JavaScript
string res;
try
{
var webAuthenticationRes =
await Windows.Security.Authentication.Web.WebAuthenticationBroker.
Concepts

AuthenticateAsync(
Windows.Security.Authentication.Web.WebAuthenticationOptions.None,
beginURI,
finalURI);
switch (webAuthenticationResult.ResponseStatus)

V 1.0 © Aptech Limited


6
Session Managing User Info

{
case Windows.Security.Authentication.Web.WebAuthenticationStatus.
Success:
// Authentication is successful.
res = webAuthenticationRes.ResponseData.ToString();
break;
case Windows.Security.Authentication.Web.WebAuthenticationStatus.
ErrorHttp:
// HTTP error.
res = webAuthenticationRes.ResponseErrorDetail.ToString();
break;
default:
// Other error.
res = webAuthenticationRes.ResponseData.ToString();
break;
}
}
catch (Exception ex)
{
// Authentication has failed. Handle any SSL/TLS, parameter, and Network
Unavailable errors here.
res = ex.Msg;
}

In this code, the AuthenticateAsync method is called with request uri, in this case, the finalURL
and beginURL, to connect to the online service provider. The status of this connection is retrieved
from webAuthenticationResult.ResponseStatus which is run through a switch case. If the
connection is successful or failed, the appropriate messages are displayed.

ÎÎ Connecting with SSO


Concepts

Web authentication broker will not provide cookies to preserve by default. Since, user have to login
each time when they need to access resources for the provider. The online identity provider should
allow SSO for Web authentication broker to login with SSO. The app must call the overload of
AuthenticateAsync function which does not take a parameter callbackUri.

V 1.0 © Aptech Limited


6
Session Managing User Info

Code Snippet 3 shows connecting to an online identity provider with SSO.


Code Snippet 3:

string res;
try
{ var webAuthenticationRes =
await Windows.Security.Authentication.Web.WebAuthenticationBroker.
AuthenticateAsync( Windows.Security.Authentication.Web.
WebAuthenticationOptions.None,
beginURI);
switch (webAuthenticationRes.ResponseStatus)
{
case Windows.Security.Authentication.Web.WebAuthenticationStatus.
Success:
// Authentication is successful.
res = webAuthenticationRes.ResponseData.ToString();
break;
case Windows.Security.Authentication.Web.WebAuthenticationStatus.
ErrorHttp:
// Returns the http error.
res = webAuthenticationRes.ResponseErrorDetail.ToString();
break;
default:
// Other error is returned.
res = webAuthenticationRes.ResponseData.ToString();
break;
}
}
catch (Exception ex)
Concepts

{
// Authentication has failed. Handle any SSL/TLS, parameter, and Network
Unavailable errors here.
res = ex.Msg;
}

V 1.0 © Aptech Limited


6
Session Managing User Info

In this code, the AuthenticateAsync method is called without the callbackuri i.e the finalURL
parameter. It takes only two parameters, options and authentication request (beginURL). The
result is then, run through switch case and appropriate messages are displayed.

ÎÎ Fingerprint (Biometric) Authentication


Sometimes, user should be in agreement with a particular action such as accessing a restricted
resource or authorizing an in-app purchase. By making a fingerprint request, the Fingerprint
(biometric) verification allows to increase the security of the app.
For example, fingerprint authentication may be required for authorization of access to restricted
resources or in-app purchase. The UserConsentVerifier class present in the Windows.
Security.Credentials.UI namespace manages this fingerprint authentication.

ÎÎ Check the Device for a Fingerprint Reader


Call the UserConsentVerifier.CheckAvailabilityAsync method to identify whether the
system has a fingerprint reader. Though the device supports fingerprint authentication, the app still
gives an option in setting to enable or disable this authentication.
In the following example, it is shown that a function which checks the current device and returns a
message with the result by supporting fingerprint authentication.
Example:
C#

public async System.Threading.Tasks.Task<string>


CheckFingerprintAvailability()
{
string returnMsg = “”;
try
{
// Check for the availability of fingerprint authentication.
var ucvAvail = await Windows.Security.Credentials.
UI.UserConsentVerifier.CheckAvailabilityAsync();
switch (ucvAvail)
{
Concepts

case Windows.Security.Credentials.UI.UserConsentVerifierAvailability.
Available:
returnMsg = “You can use fingerprint verification.”;
break;

V 1.0 © Aptech Limited


6
Session Managing User Info

case Windows.Security.Credentials.UI. UserConsentVerifierAvailability.


DeviceBusy:
returnMsg = “Biometric device is busy currently.”;
break;
case Windows.Security.Credentials.UI.
UserConsentVerifierAvailability.DeviceNotPresent:
returnMsg = “Biometric device could not be found.”;
break;
case Windows.Security.Credentials.UI.
UserConsentVerifierAvailability.DisabledByPolicy:
returnMsg = “Biometric verification is disabled by a policy.”;
break;
case Windows.Security.Credentials.UI.
UserConsentVerifierAvailability.NotConfiguredForUser:
returnMsg = “The user has no fingerprints registered. Try again by adding a
fingerprint to the “ +
“fingerprint database.”;
break;
default:
returnMsg = “Fingerprints verification is currently not available.”;
break;
}
}
catch (Exception ex)
{
returnMsg = “Failed to check Fingerprint authentication availability: “ +
ex.ToString();
}
return returnMsg;
Concepts

In this code, the method Windows.Security.Credentials.UI.UserConsentVerifier.


CheckAvailabilityAsync() checks for the availability of fingerprint authentication device.
The result of this method is run through switch case and appropriate messages such as device
available, busy, disabled, and fingerprint database is empty are displayed.

V 1.0 © Aptech Limited


6
Session Managing User Info

ÎÎ Request User Consent for a Fingerprint Scan


Call the UserConsentVerifier.RequestVerificationAsync method to ask user agreement
from a fingerprint scan. The user must already have an added fingerprint ‘signature’ to the
fingerprint database.
When the UserConsentVerifier.RequestVerificationAsync method is called, it displays
the following image. Figure 6.1 displays the fingerprint.

Figure 6.1: Fingerprint


Image Courtesy: msdn.com
Following example demonstrates a method asks fingerprint verification and displays a message
with the result.
Example:
C#

private async System.Threading.Tasks.Task<string> RequestConsent(string


userMsg)
{
string returnMsg;
if (String.IsNullOrEmpty(userMsg))
{
Concepts

userMsg = “Please give your fingerprint to verify.”;


}
try
{

V 1.0 © Aptech Limited


6
Session Managing User Info

// Request the consent of the logged on user, using the fingerprint swipe
mechanism
var consentRes = await Windows.Security.Credentials.
UI.UserConsentVerifier.RequestVerificationAsync(userMsg);
switch (consentRes)
{
case Windows.Security.Credentials.UI.UserConsentVerificationResult.
Verified:
returnMsg = “Fingerprint has been verified.”;
break;
case Windows.Security.Credentials.UI.UserConsentVerificationResult.
DeviceBusy:
returnMsg = “The biometric device is busy.”;
break;
case Windows.Security.Credentials.UI.UserConsentVerificationResult.
DeviceNotPresent:
returnMsg = “Unable to find the biometric device.”;
break;
case Windows.Security.Credentials.UI.UserConsentVerificationResult.
DisabledByPolicy:
returnMsg = “Biometric verification is disabled by a policy.”;
break;
case Windows.Security.Credentials.UI.UserConsentVerificationResult.
NotConfiguredForUser:
returnMsg = “The user does not have any fingerprints registered. Try again
after adding a fingerprint to the “ +
“fingerprint database.”;
break;
case Windows.Security.Credentials.UI.UserConsentVerificationResult.
RetriesExhausted:
Concepts

returnMsg = “Fingerprint authentication cancelled due to too many failed


attempts.”;
break;
case

V 1.0 © Aptech Limited


6
Session Managing User Info

Windows.Security.Credentials.UI.UserConsentVerificationResult.
Canceled:
returnMsg = “Fingerprint authentication cancelled.”;
break;
default:
returnMsg = “Fingerprint authentication currently not available.”;
break;
}
}
catch (Exception ex)
{
returnMsg = “Fingerprint authentication failed: “ + ex.ToString();
}
return returnMsg;
}

In this code, the method Windows.Security.Credentials.UI.UserConsentVerifier.


RequestVerificationAsync(userMsg) is used to get the user consent for fingerprint
authentication. The result of this method is run through switch case and the appropriate messages
such as fingerprint verified, device busy, not available, and authentication cancelled are displayed.

ÎÎ Smart Cards and Virtual Smart Cards


For the app, the smart cards and virtual smart cards give a very high level of authentication. In the
Windows.Devices.SmartCards namespace, a user can be authenticated by using the APIs.
The authentication can be done by gathering information about smart card devices, managing,
and using them. Without requiring a physical smart card from the user a Trusted Platform Module
(TPM) virtual smart cards provide smart card-level authentication.
Following section shows how to access a physical smart card or how to create a new virtual smart card:

ÎÎ Prerequisites
The following example refers the Windows 8.1 Smart card sample. Not only it refers the new
Concepts

Windows.Devices.SmartCards namespace, but also refers the creation of virtual smart cards of
admin keys for which it contains some APIs defined by the Windows.Security.Cryptography
namespace.

V 1.0 © Aptech Limited


6
Session Managing User Info

ÎÎ Access Connected Card Readers and Smart Cards


Pass the device ID (which is specified in DeviceInformation) to the SmartCardReader.
FromIdAsync method to query for readers and attached smart cards. Call function rdr.
FindAllCardsAsync to access the smart cards which is currently attached to the returned reader
device.
Code Snippet 4 demonstrates the SmartCardReader.
Code Snippet 4:
C#

string selector = SmartCardReader.GetDeviceSelector();


DeviceInfoCollection devices =
await DeviceInfo.FindAllAsync(selector);
foreach (DeviceInfo device in devices)
{
SmartCardReader rdr =
await SmartCardReader.FromIdAsync(device.Id);
// we need to find all the cards associated for each reader.
// Creating a SmartCardListItem for each (reader, card) pair.
IReadOnlyList<SmartCard> cards =
await rdr.FindAllCardsAsync();
}

In this code, the method DeviceInfo.FindAllAsync returns all the card readers associated
with the given device. Then, we iterate through each card reader and get the associated cards for
the given reader.
On card insertion by implementing a method to handle app behavior, an app should be allowed to
observe for CardAdded events. Following is the syntax for SmartCardReader:
Syntax:

private void rdr_CardAdded(SmartCardReader sender, CardAddedEventArgs


args)
Concepts

{
// A card is inserted into the sender SmartCardReader.
}

Each returned SmartCard object can be passed to SmartCardProvisioning to access the


function that provide app to access and customize its configuration.

V 1.0 © Aptech Limited


6
Session Managing User Info

ÎÎ Creating a Virtual Smart Card


Before creating a virtual smart card using SmartCardProvisioning, first the app is required
to provide an admin key, name, and a SmartCardPinPolicy. The app will still require to give
an admin key and produces an instance of the current SmartCardPinPolicy before passing
all these values to RequestVirtualSmartCardCreationAsync. Code Snippet 5 demonstrates
the SmartCardPinPolicy.
Code Snippet 5:

SmartCardPinPolicy newPinPolicy = new SmartCardPinPolicy();


newPinPolicy.MinLength = 7;
IBuffer newAdminkey = CryptographicBuffer.GenerateRandom(29);
SmartCardProvisioning newProvisioning = await
SmartCardProvisioning.RequestVirtualSmartCardCreationAsync(
“Card-friendly-name”,
newAdminkey,
newPinPolicy);

In this code, the function RequestVirtualSmartCardCreationAsync has returned the related


SmartCardProvisioning object and the virtual smart card is equipped and ready for use.

ÎÎ Handle Authentication Challenges


The app should allow the behavior to complete the challenges to authenticate with virtual smart
cards or smart cards. The challenge is between the admin key data well kept by the authentication
server and the data stored on the card.
Code Snippet 6 demonstrates how to support smart card authentication for providing assistance or
customization of physical or virtual card details.
Code Snippet 6:

static class ChallengeRespAlgorithm


{
public static IBuffer CalculateResponse(IBuffer challenge, IBuffer
newAdminkey)
{
Concepts

if (challenge == null)
throw new ArgumentNullException(“challenge”);
if (newAdminkey == null)
throw new ArgumentNullException(“adminkey”);

V 1.0 © Aptech Limited


6
Session Managing User Info


SymmetricKeyAlgorithmProvider newAlg = SymmetricKeyAlgorithmProvider.
OpenAlgorithm(SymmetricAlgorithmNames.TripleDesCbc);
var newSymmetricKey = objAlg.CreateSymmetricKey(newAdminkey);
var newBuffEncrypted = CryptographicEngine.Encrypt(newSymmetricKey,
challenge, null);
return newBuffEncrypted;
}
}

In this code, the authentication is successful if the admin key generated data on the card (‘challenge’) is
same, as the admin key data allowed by the server or management tool (‘adminkey’).

ÎÎ Verifying Virtual Smart Card or Smart Card Authentication Response


It is clear that logic for authentication challenges defined can be communicated using the reader to
get the smart card or can also access a virtual smart card for authentication.
1. Calling GetChallengeContextAsync from the SmartCardProvisioning object related
to the smart card begins the challenge. This generates an instance of
SmartCardChallengeContext, which contains the card’s Challenge value.
2. Admin key is provided by the service or management tool. Now, pass this and card’s challenge
value to the ChallengeResponseAlgorithm is defined in the previous example.
3. If authentication is successful, VerifyResponseAsync will return true.
Code Snippet 7 demonstrates the Admin key.
Code Snippet 7:
C#

bool verifyRes = false;


SmartCard newCard = await rootPage.GetSmartCard();
SmartCardProvisioning newProvisioning =
await SmartCardProvisioning.FromSmartCardAsync(newCard);
using (SmartCardChallengeContext newContext =
Concepts

await newProvisioning.GetChallengeContextAsync())
{
IBuffer bufferResponse = ChallengeResponseAlgorithm.CalculateResponse(
context.Challenge,

V 1.0 © Aptech Limited


6
Session Managing User Info

rootPage.AdminKey);
verifyResponse = await context.VerifyResponseAsync(bufferResponse);
}

In this code, the smart card is retrieved from the GetSmartCard method and the associated
smart card provisioning is retrieved using the method SmartCardProvisioning.
FromSmartCardAsync(newCard). The challenge value is retrieved using the
GetChallengeContextAsync method. This challenge value and the admin key are used to
calculate the challenge response algorithm using the method ChallengeResponseAlgorithm.
CalculateResponse. If the response is true then, the smart card authentication is successful.

6.1.1 Certificate Authentication


Certificate authentication is used for high level authentication of user. It provides secured
authentication beyond a user name and password combination.

ÎÎ Enable IIS and client certificate mapping


Using the Windows Control Panel, IIS can be enabled, since it is disabled by default.
Following are the steps to enable IIS:
1. Select Programs after opening the Windows Control Panel.
2. Choose the Turn Windows features on or off.
3. Expand Internet Information Services, World Wide Web Services, and Application
Development Features and then, select ASP.NET 3.5 and ASP.NET 4.5. These selections
will automatically enable IIS.
4. To apply the changes, click OK.

ÎÎ Create and publish a secured Web service


Here, a secured Web service is created and published to the IIS server.
1. As an administrator, run the Microsoft Visual Studio and from the start page select New
Project.
2. Change the Framework to .NET Framework 4.5 in the New Project dialog box.
3. Choose Visual C# Web  Visual Studio ASP.NET Web Service Application.
Concepts

4. Type the application name as ‘FirstContosoBank’. Click OK to create the project.


5. Replace the default HelloWorld Web method in the Service1.asmx.cs file with the following
’Login’ method.

V 1.0 © Aptech Limited


6
Session Managing User Info

Code Snippet 8 demonstrates the Web method.


Code Snippet 8:

[WebMethod]
public string Login()
{
// Verify certificate using Certificate Authentication
var cert = new System.Security.Cryptography.X509Certificates.
X509Certificate2(
this.Context.Request.ClientCertificate.Certificate);
bool test_cert = cert.Verify();
return test_cert.ToString();
}

6. Save the Service1.asmx.cs file.


7. Right-click the FirstContosoBank app in the Solution Explorer, and select Publish.
8. Name the new profile as ‘ContosoProfile’ once it is created in the Publish Web dialog box.
Click Next.
9. Enter the server name for the IIS server on the next page and indicate site name of ’Default
Web Site/FirstContosoBank’.
10. To publish your Web service, click Publish.

ÎÎ Configuring the Web service to use client certificate authentication


1. Run the Internet Information Services (IIS) Manager.
2. Choose the new FirstContosoBank Web service by expanding the sites for your IIS server.
3. Choose Advanced Settings in the Actions section.
4. Set the Application Pool to .NET v2.0 and click OK.
5. Choose the IIS server in the IIS Manager, and then, double-click Server Certificates.
6. Choose Create Self-Signed Certificate. Then, type name as ‘ContosoBank’ for the certificate
and click OK.
Concepts

7. Choose the default Web site in the IIS Manager. Click Add in the Actions section, select
Binding and then, choose https as the type. Then, set the port to “443”, and type the IIS
server’s full host name ’<server-name>.<domain-name>’. Set the SSL certificate to
ContosoBank. Click OK and then, Click Close in the Site Bindings window.
8. In the IIS Manager, choose the FirstContosoBank Web service. Double-click the SSL

V 1.0 © Aptech Limited


6
Session Managing User Info

Settings. Check Require SSL. Select Require under Client certificates. Click Apply in the
Actions section.
9. Now, check if the Web service is configured correctly by opening the Web browser and typing
the following Web address: ‘https://<server-name>.<domain-name>/FirstContosoBank/
Service1.asmx’.
For example, ’https://myserver.example.com/FirstContosoBank/Service1.asmx’.
10. If the Web service is configured correctly, then, you will be allowed to select a client certificate
in order to access the Web service.
To create multiple Web services, the previous steps can be repeated that can be got using the
certificate of same client.

ÎÎ Creating a Windows Store App which uses certificate authentication


To create Windows Store Apps now you have one or more secured Web services. The starting
request will not contain a client certificate when request is made to an authenticated Web service
using the HttpClient object. With a request, the authenticated Web service will reply only for
client authentication. It is required to give the user with a manner to input the password for a
certificate since certificates are password protected.
1. Add the following XAML to the default Grid element in the MainPage.xaml file. This XAML
includes the following:
ŠŠ Button to browse the PFX file for importing
ŠŠ Text box to type a password for a password-protected PFX file
ŠŠ Button to import a selected PFX file
ŠŠ Button to log in to the secured Web service
ŠŠ Text block to display the status of the current action
Code Snippet 9 demonstrates the design of using the certificate authentication.
Code Snippet 9:
XAML

<Button x:Name=”Import” Content=”Import Certificate (PFX file)”


HorizontalAlignment=”Left” Margin=”359
Concepts

315
0
0” VerticalAlignment=”Top” Height=”66” Width=”261” Click=”Import_Click”
FontSize=”16”/>
<Button x:Name=”Login” Content=”Login” HorizontalAlignment=”Left”

V 1.0 © Aptech Limited


6
Session Managing User Info

Margin=”611
305
0
0” VerticalAlignment=”Top” Height=”74” Width=”245” Click=”Login_Click”
FontSize=”15”/>
<TextBlock x:Name=”Result” HorizontalAlignment=”Left” Margin=”345
398
0
0” TextWrapping=”Wrap” VerticalAlignment=”Top” Height=”143” Width=”550”/>
<PasswordBox x:Name=”PfxPassword” HorizontalAlignment=”Left” Margin=”473
271
0
0” VerticalAlignment=”Top” Width=”219”/>
<TextBlock HorizontalAlignment=”Left” Margin=”345
278
0
0” TextWrapping=”Wrap” Text=”PFX password” VerticalAlignment=”Top”
FontSize=”19” Height=”39” Width=”123”/>
<Button x:Name=”Browse” Content=”Browse for PFX file”
HorizontalAlignment=”Left” Margin=”352
189
0
0” VerticalAlignment=”Top” Click=”Browse_Click” Width=”489” Height=”68”
FontSize=”19”/>
<TextBlock HorizontalAlignment=”Left” Margin=”717
271
0
0” TextWrapping=”Wrap” Text=”(Optional)” VerticalAlignment=”Top”
Concepts

Height=”39” Width=”73” FontSize=”17”/>


2. Save the MainPage.xaml file.

V 1.0 © Aptech Limited


6
Session Managing User Info

3. Add the following statements in the MainPage.xaml.cs file as shown in Code Snippet 10.
Code Snippet 10:

using Windows.Web.Http;
using System.Text;
using Windows.Security.Cryptography.Certificates;
using Windows.Storage.Pickers;
using Windows.Storage;
using Windows.Storage.Streams;

4. Add the following variables to the MainPage class in the MainPage.xaml.cs file as shown
in Code Snippet 11.
Code Snippet 11:
C#

private Uri reqUri = new Uri(“https://<server-


name>/FirstContosoBank/Service1.asmx?op=Login”);
private string pfxCertificate = null;

They give the address for the safe ‘Login’ method of the FirstContosoBank Web service. Also,
they specify the address for the global variable which keeps a PFX certificate to import in the
certificate store. For your IIS server then, update the <server-name> to the fully-qualified server
name.
5. Add the following click event handler for the login button in the MainPage.xaml.cs file, and
method to access the secured Web service as shown in Code Snippet 12.
Code Snippet 12:

private void Login_Click(object newSender, RoutedEventArgs newArgs)


{
MakeHttpsCall();
}
private async void MakeHttpsCall()
{
Concepts

StringBuilder res = new StringBuilder(“Login “);


HttpResponseMessage resp;
try {
Windows.Web.Http.HttpClient newHttpClient = new

V 1.0 © Aptech Limited


6
Session Managing User Info

Windows.Web.Http.HttpClient();
resp = await newHttpClient.GetAsync(reqUri);
if (resp.StatusCode == HttpStatusCode.Ok)
{
res.Append(“It’s successful”);
}
else
{
res = res.Append(“ failed with “);
res = res.Append(resp.StatusCode);
}
}
catch (Exception ex)
{
res = res.Append(“ failed with “);
res = res.Append(ex.Msg);
}
Res.Text = res.ToString();
}

6. Add the following click event handlers in the MainPage.xaml.cs file. To browse and import
a selected PFX file into the certificate store as shown in Code Snippet 13.
Code Snippet 13:

private async void Import_Click(object newSender, RoutedEventArgs


eventArgs)
{
try
{
Res.Text = “The selected certificate is being imported to user certificate
Concepts

store....”;
await CertificateEnrollmentManager.UserCertificateEnrollmentManager.
ImportPfxDataAsync(
pfxCertificate,

V 1.0 © Aptech Limited


6
Session Managing User Info

PfxPassword.Password,
ExportOption.Exportable,
KeyProtectionLevel.NoConsent,
InstallOptions.DeleteExpired,
“Imports Pfx”);
Res.Text = “Certificate import succeeded”;
}
catch (Exception error)
{
Res.Text = “Certificate import failed with “ + error.Msg;
}
}
private async void Browse_Click(object newSender, RoutedEventArgs
eventArgs)
{
StringBuilder strBuilderresponse = new StringBuilder(“Pfx file selection
“);
FileOpenPicker pfxFileOpenPicker = new FileOpenPicker();
pfxFileOpenPicker.FileTypeFilter.Add(“.pfx”);
pfxFileOpenPicker.CommitButtonText = “Open”;
try
{
StorageFile pfxStorageFile = await pfxFileOpenPicker.
PickSingleFileAsync();
if (pfxStorageFile!= null)
{
IBuffer newBuffer = await FileIO.ReadBufferAsync(pfxStorageFile);
Concepts

using (DataReader newDataReader = DataReader.FromBuffer(newBuffer))


{
byte[] firstByte = new byte[newBuffer.Length];
dataReader.ReadBytes(firstByte);
pfxCertificate = System.Convert.ToBase64String(firstByte);

V 1.0 © Aptech Limited


6
Session Managing User Info

PfxPassword.Password = string.Empty;
res.Append(“succeeded”);
}
}
else
{
res.Append(“ failed”);
}
}
catch (Exception error)
{
res.Append(“ failed with “);
res.Append(error.Msg); ;
}
Res.Text = res.ToString();
}

7. Save the MainPage.xaml.cs file.


8. To run your Windows Store App, press F5.
9. In the local certificate store, import a PFX file and log in to the secured Web service.
These steps can be used to create multiple Windows Store Apps. These multiple Windows Store Apps
utilize the same user certificate to get the secured Web services which might be same or different.

6.2 Certificates and Encryption


Following namespaces can be used for encrypting data and creating the certificate requests:

ÎÎ Windows.Security.Cryptography

ÎÎ Windows.Security.Cryptography.Core
Concepts

ÎÎ Windows.Security.Cryptography.Certificates

ÎÎ Windows.Security.Cryptography.DataProtection

V 1.0 © Aptech Limited


6
Session Managing User Info

ÎÎ Encoding and decoding data


The data must be serialized that means it must be disassembled into a bit string. Then, between
computers across a network it is transmitted serially to send data. This data reassembles into its
original data format. Static methods in the Windows.Security.Cryptography namespace can
be used to encode and decode data. Table 6.1 lists the methods of encoding and decoding data.

Methods Description
DecodeFromBase64String It decodes a string from base 64.
DecodeFromHexString It decodes from a hexadecimal string.
EncodeToBase64String It encodes data to a base 64 string.
EncodeToHexString It encodes data to a hexadecimal string.
Table 6.1: Encode and Decode Methods

ÎÎ Encrypting and decrypting data


Users can use the following static methods on the CryptographicEngine class to encrypt and
decrypt data:
yy decrypt: Decrypts content that was earlier encrypted by using an asymmetric or
symmetric algorithm.
yy encrypt: Encrypts data by using an asymmetric or symmetric algorithm.
yy decryptAndAuthenticate: Performs authenticated decryption.
yy encryptAndAuthenticate: Encrypts and authenticates data.

6.3 Selective Wipe


Selective wipe can be revoked when an app is not authorized to the app data. It can be used to identify
protected files in your app. This is a usual scenario in companies where employees bring their own device
to work. The company’s business files can be removed on their personal device once the employee leaves
the company. Code Snippet 14 demonstrates the denied access.
Code Snippet 14:

ApplicationData newappRootFolder = ApplicationData.Current;


string newenterpriseIdentity = “eg.com”;
int defaultAccessDeniedHResult = -2147024891; // Indicates that access is denied
Concepts

(0x80070005)

ÎÎ Protect a file or folder using Selective Wipe


The ProtectAsync method can be used to protect a file or folder. It can be done using a Selective
Wipe. This file is protected for the enterprise identifier, such as ’eg.com’, which is shown in the

V 1.0 © Aptech Limited


6
Session Managing User Info

earlier example. Using the ProtectAsync method if a folder is protected, then, same protection
is inherited by all files in that folder. Code Snippet 15 demonstrates how to use selective wipe.
C#
Code Snippet 15:

// How to use Selective Wipe to Add a folder and protect the folder
private async Task<StorageFolder> AddnewFolder(string newfolderName)
{
StorageFolder newFolder = await newappRootFolder.LocalFolder.
CreateFolderAsync(newfolderName);
var status = await ProtectItem(newFolder, newenterpriseIdentity);
return newFolder;
}
// How to use selective wipe to add a file and protect it.
private async Task<StorageFile> AddnewFile(string newfileName,
StorageFolder newfolder)
{
StorageFile newFile = await newfolder.CreateFileAsync(newfileName);
var status =
await Windows.Security.EnterpriseData.FileRevocationManager.
GetStatusAsync(newFile);
if (status != Windows.Security.EnterpriseData.FileProtectionStatus.
Protected)
{
status = await ProtectItem(newFile, newenterpriseIdentity);
}
return newFile;
}
private async Task<Windows.Security.EnterpriseData.FileProtectionStatus>
Concepts

ProtectItem(IStorageItem item, string newenterpriseIdentity)


{
var status =
await Windows.Security.EnterpriseData.FileRevocationManager.

V 1.0 © Aptech Limited


6
Session Managing User Info

ProtectAsync(item, newenterpriseIdentity);
return status;
}

ÎÎ Get the status of a file


The GetStatusAsync method can be used to decide the files’ selective wipe protection status or
a folder to check whether the file is protected or not. Benefit of using GetStatusAsync method is
to decide when a protected file should be deleted. In the following example, the GetStatusAsync
method decides whether the file is revoked by selective wipe and if it has revoked it deletes it.
Example:

private async Task<IRandomAccessStream> GetFileContents(string


newfilePath)
{
IRandomAccessStream newstream = null;
StorageFile newfile = null;
try
{
file = await StorageFile.GetFileFromPathAsync(newfilePath);
stream = await newfile.OpenReadAsync();
}
catch (UnauthorizedAccessException e)
{
if (e.HResult == DefaultAccessDeniedHResult)
{
// Use this function to delete a file if it is revoked.
SelectiveWipeCleanup(file);
}
return null;
Concepts

}
return newstream;
}
// Delete the items that are revoked using Selective Wipe.

V 1.0 © Aptech Limited


6
Session Managing User Info

private async void SelectiveWipeCleanup(StorageFile newfile)


{
var lateststatus = await Windows.Security.EnterpriseData.
FileRevocationManager.GetStatusAsync(newfile);
if (lateststatus == Windows.Security.EnterpriseData.FileProtectionStatus.
Revoked)
{
await newfile.DeleteAsync();
}
}

ÎÎ Copying a protected file


When users copy a file using the CopyAsync or CopyAndReplaceAsync methods, the copied file
of the selective wipe protection will not apply to the new copy of the file by itself. In this case, the
selective wipe protection copy from the original files using the CopyProtectionAsync method,
as shown in the following example.
Example:

public async newTask<bool> CopynewFile(StorageFile newfile, StorageFolder


newFolder)
{
bool finalresult = false;
try
{
var newFile = await file.CopyAsync(newFolder);
finalresult = await
Windows.Security.EnterpriseData.FileRevocationManager.
CopyProtectionAsync(file, newFile);
}
catch (Exception e)
Concepts

{
// You must add code to handle exception.
return finalresult;
}

V 1.0 © Aptech Limited


6
Session Managing User Info

6.4 Securing Apps


Windows Runtime provides authentication and cryptography and its security can be improved by
different authentication APIs. These APIs can be used to verify the identity of a user as well as verify user
agreement for purchases. The cryptography APIs can be used to secure data and resources.

6.5 Managing User Contacts


Users are allowed to share content, info, calendar, messages, or e-mail with each other, or whatever
functionality developer designs.

6.5.1 Setting Up the Contact Picker


Following section shows how to retrieve only the app required contact information of configuring the
contact picker:
Create an instance of Windows.ApplicationModel.Contacts.ContactPicker and assign it to a
variable as shown in Code Snippet 16.
C#
Code Snippet 16:

var newcontactPicker = new


Windows.ApplicationModel.Contacts.ContactPicker();

6.5.2 Providing a Name for the Commit Button


To confirm a contact user has to press a button which is nothing but the Commit button. This Commit
button name has to be set with newcontactPicker.CommitButtonText as shown in Code Snippet
17.
C#
Code Snippet 17:

newcontactPicker.CommitButtonText = “Choose”;

ÎÎ Setting the selection mode


User selects all the available data for the contacts retrieved by contact picker by default. The contact
picker is configured by the SelectionMode property which retrieves only the required app data
fields.
First, set the SelectionMode property to fields as shown in Code Snippet 18.
Concepts

Code Snippet 18:

newcontactPicker.SelectionMode =
Windows.ApplicationModel.Contacts.ContactSelectionMode.Fields;

V 1.0 © Aptech Limited


6
Session Managing User Info

In this code, the contact picker can be retrieved using the


desiredFieldsWithContactFieldType property.
Following example configures to retrieve e-mail addresses from the contact picker.
C#
Example:

contactPicker.desiredFieldsWithContactFieldType.append(Windows.
ApplicationModel.Email

6.5.3 Launching the Picker


If you want to launch the picker, then select only one contact using PickContactAsync and then, call
a function as shown in Code Snippet 19.
Code Snippet 19:

Contact newcontact = await contactPicker.PickContactAsync();

Code Snippet 20 uses the PickContactsAsync to enable the use to select one or multiple contacts.
C#
Code Snippet 20:

public IList<Contact> contactslist;


contactslist = await contactPicker.PickContactsAsync();

6.5.4 Processing the Contacts


When the picker is returned, check if the user has selected any contacts. If yes, process the contact
information of the selected contact.
Following example demonstrates how to process a single contact. Here, you retrieve the name of the
contact and copy it into a TextBlock control. You also retrieve the contact’s thumbnail image and copy
it into an Image control.
Example:

if (newcontact != null)
{
OutputName.Text = newcontact.FirstName;
Concepts

IRandomAccessStreamWithContentType newstream = await contact.Thumbnail.


OpenReadAsync();
if (newstream != null && newstream.Size > 0)
{

V 1.0 © Aptech Limited


6
Session Managing User Info

BitmapImage newbitmap = new BitmapImage();


newbitmap.SetSource(stream);
OutputThumbnail.Source = newbitmap;
}

Following example shows how to process multiple contacts.


Example:

if (contactslist.Count > 0)
{
foreach (Contact newcontact in contactslist)
{
// Add code here to work on the contact information.
}
}
Concepts

V 1.0 © Aptech Limited


6
Session Managing User Info

6.6 Check Your Progress


1. The request URI is sent as the requestUri parameter of the ____________________.

(A) AuthenticateSync (C) AuthenticateCertificate

(B) AuthenticateAsync (D) AuthenticateSyncCertificate



2. Making a fingerprint request, the Fingerprint (biometric) verification allow to increase the
__________________.

(A) Accessibility of the app (C) Security of the app


(B) Approachability of the app (D) Correction of the app

3. _____________________________ method is called to identify whether the system has a
fingerprint reader.

(A) UserConsentVerifier.CheckAvailabilityAsync

(B) Windows.Security.Credentials.UI

(C) UserConsentVerifier

(D) System.Threading.Tasks

4. _________________ can be revoked when an app is not authorized to the app data.

(A) Copy a protected file (C) Contact picker


(B) Secured apps (D) Selective wipe

5. _________________ to be used to select only one contact to launch the picker.

(A) pickContactselect (C) pickContactSync

(B) pickContactpicker (D) pickContactAsync


Concepts

V 1.0 © Aptech Limited


6
Session Managing User Info

6.6.1 Answers
1. B
2. C
3. A
4. D
5. D
Concepts

V 1.0 © Aptech Limited


6
Session Managing User Info

Summary
ÎÎ Authentication challenges defined can be communicated using the reader to get the smart card or
can also access a virtual smart card for authentication.
ÎÎ Certificate authentication is used for high level authentication of user.
ÎÎ Certificate authentication provides secured authentication beyond a user name and password
combination.
ÎÎ Selective Wipe can be used to identify protected files in your app.
ÎÎ The GetStatusAsync method can be used to decide the file’s Selective Wipe protection status or a
folder to check whether the file is protected or not.
ÎÎ Different authentication APIs can be used to verify the identity of a user as well as verify user
agreement for purchases.
ÎÎ The contact picker is configured by SelectionMode property which retrieves only the required app
data fields.

Concepts

V 1.0 © Aptech Limited


Session - 7
Launching, Debugging, and
Publishing Windows Store App
Welcome to the session, Launching, Debugging, and Publishing
Windows Store App.

The session will discuss how to launch, resume, and multitask. It will also
discuss the debugging and testing and packaging the Windows Store App.

In this session, you will learn about:

ÎÎ Launching, resuming, and multitasking an app

ÎÎ Debug and test Visual Studio and DLL load failures with
the Event Viewer

ÎÎ Package the Windows Store App

ÎÎ Optimize images for different screen resolutions

ÎÎ Validate an app package in automated builds

ÎÎ Override a package manifest


7
Session Launching, Debugging, and Publishing Windows Store App

7.1 Launching, Resuming, and Multitasking


This session will explain you how to launch, suspend, and resume your app and learn about Multitasking
with Notifications and Background tasks.

ÎÎ Launching, suspending, and resuming apps


Windows 8 suspends your app in memory when users move your app off-screen and enables
another app to have the foreground. Windows stops suspended app from running and the app
resides in memory. Users expect the app to restart from where they left off, when the app is brought
back to the foreground.

ÎÎ Multitasking with Notifications and Background tasks


Background task can be used to run lightweight code in the background. In response to certain
system events, app can register a background task. Background tasks show information to the user
with toast notifications, tile updates, and badge updates. Since, it cannot run the code that directly
updates the UI. Mail, Voice Over Internet Protocol (VOIP), and Instant Message (IM) are some
apps that allow the user to communicate. On the lock screen, when your app can show a tile or a
badge, then it gains access to real-time background tasks. From the background, you can also keep
providing functionality with notifications and background audio.

7.1.1 How to Activate an App


Windows Store App allows you to define the activation experience. Following example overrides the
OnLaunched method:
Step 1: Overriding the launch handler
The system sends the Activated event when an app is activated. ActivationKind enumeration can be
referred for any kind of activation types. To handle the various activation types, the Windows.UI.Xaml.
Application class defines methods which can override. Few activation types have a specific method
to override, and to override some other activation types, the OnActivated method can be used. Code
Snippet 1 demonstrates the XAML code.
Code Snippet 1:

XAML
<App xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
Concepts

x:Class=”AppName.App” >

Whenever the user launches the app, the OnLaunched method is called. The previous state of the app
and the activation arguments are stored in LaunchActivatedEventArgs parameter.

V 1.0 © Aptech Limited


7
Session Launching, Debugging, and Publishing Windows Store App

Code Snippet 2 demonstrates the C# code for activation.


Code Snippet 2:
C#

using System;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;
namespace Myapplication
{
public partial class NewApp
{
async protected override void OnLaunched(LaunchActivatedEventArgs newArgs)
{
MainPageCreateAndActivate();
}
// Creates the MainPage if not already created. This also activates
// the window to focus on foreground and input.
private MainPage MainPageCreateAndActivate()
{
if (Window.Current.Content == null)
{
Window.Current.Content = new MainPage();
}
Window.Current.Activate();
return Window.Current.Content as MainPage;
}
}
}
Concepts

Step 2: If app was suspended (later, it gets terminated), then restore application data
The system sends the Activated event when the user switches to the terminated app. Here, Kind is set
to Launch and PreviousExecutionState is set to Terminated or ClosedByUser. The displayed
content should be refreshed and app should store its saved application data.

V 1.0 © Aptech Limited


7
Session Launching, Debugging, and Publishing Windows Store App

Code Snippet 3 demonstrates the suspension of the application.


Code Snippet 3:
C#

async protected override void OnLaunched(LaunchActivatedEventArgs eventArgs)


{
if (eventArgs.PreviousExecutionState == ApplicationExecutionState.Terminated
||
eventArgs.PreviousExecutionState == ApplicationExecutionState.ClosedByise)
{
// TODO: Populate UI with the application date that was previously saved
}
else
{
// TODO: Populate the UI with default values
}
MainPageCreateAndActivate();
}

In this code, the app has failed to save its application data, if the value of PreviousExecutionState
is NotRunning. In this case, the app should start from were being initially launched.

7.1.2 Suspend an App


When the system suspends your Windows Store, the app.save is an important application data for the
Suspending event. The following example registers an event handler and it also saves a string to a file:
Step 1: Suspending event handler should be registered.
To handle the Suspending event, register it. Code Snippet 4 demonstrates the Suspending event.
Code Snippet 4:
C#

using System;
Concepts

using Windows.UI.Xaml;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;

V 1.0 © Aptech Limited


7
Session Launching, Debugging, and Publishing Windows Store App

partial class MainPage


{
public MainPage()
{
InitializeComponent();
App.Current.Suspending += new SuspendingEventHandler(Current_App_
Suspending);
}
}

This code indicates that before the system suspends it, the app is required to save its application data.
Step 2: Before suspension, application data should be saved.
While app is handling the Suspending event, in the handler function, it has got an opportunity to save its
important application data. To save simple application data, the app should use the Local Settings storage
API synchronously. Code Snippet 5 demonstrates how to save the application data.
Code Snippet 5:
C#

partial class MainPage


{
async void App_Suspending(
Object newSender,
Windows.ApplicationModel.SuspendingEventArgs eventArgs)
{
//this is the code to save application data

int HighestScore = 1000;


ApplicationData.Current.LocalSettings.Values[“HighScore”] =
HighestScore;
// Loading App Data
Concepts

// Add this to OnLaunched() in App.xaml.cs


if (eventArgs.PreviousExecutionState == ApplicationExecutionState.
Terminated)
{

V 1.0 © Aptech Limited


7
Session Launching, Debugging, and Publishing Windows Store App

// App is being resumed after being termination, so settings


// should be restored.
if (ApplicationData.Current.LocalSettings.Values.
ContainsKey(“HighScore”))
{
int HighestScore;
HighestScore = (int)(ApplicationData.Current.LocalSettings.
Values[“HighScore”]);
}
}
else
{
// App is being resumed after being suspended, so typically you do not
// need to restore settings.
}

Step 3: Exclusive resources and file handles should be released.


While the app handles the Suspending event, it also has got a chance to release separate resources and
file handles. Some of the examples of exclusive resources are I/O devices, Webcams, network resources,
and external devices. Releasing exclusive resources and file handles help other apps to access them,
while this app is not using them. After termination, when the app is activated, it should open its separate
resources and file handles.

7.1.3 Guidelines for App Suspend and Resume


App should be designed in such a way that when the user switches away, it should get suspended and
should resume when the user switches back to it. Following guidelines help to design the Suspended and
Resume behavior of Windows Store App:

ÎÎ Do’s and Don’ts


Concepts

yy After a short period of time to resume an app, take users to the state from where they had
left.
yy After a long period of time if user wants to resume then, take users to default landing page.
yy Provides users to select if they want to restore their app to its earlier state or start fresh.

V 1.0 © Aptech Limited


7
Session Launching, Debugging, and Publishing Windows Store App

yy When the app is being suspended then, save its data. To ensure the restore of an app state,
save app data. Since suspended apps will not receive notification, when Windows
terminates them.
yy To restore app, use saved app data.
yy When the app gets suspended, try to release plenty of resources and file handles.
yy Update the UI if content has changed as it was last visible to the user. It should look like as if
it was working when the user was not present there.
yy When the app moved off screen, don’t terminate it.
yy During app crash, the app gets terminated then, do not restore its state.
yy Do not provide users Close buttons or other ways to terminate the app in its UI. They
should feel that Windows is taking care of their apps for them.

7.1.4 Auto-launching with File and URI Associations


A file type or protocol can be used to associate the launching of API to launch the user’s app. Also, for a
file type or protocol, one can enable your app to be the default app.

ÎÎ How to handle file activation


For a certain file type, Windows allow an app to register as a default handler. As a default file
handler, either desktop apps or Windows Store Apps can get registered. As a default app, the
chosen app will be activated every time when that type of file is launched.
Here are the steps which show how to get registered for a conventional file type .alsdk and also
it shows when the user launches an .alsdk file how your app can be activated.
Step 1: In the package manifest, the extension point should be shown.
Only for the file extensions, the app receives activation events which are listed in the package manifest.
The following steps show how to indicate the app handles files with the .alsdk extension:
1. To open package.appxmanifest in Solution Explorer, double-click it.
2. Click Declarations tab.
3. Click File Type Associations from the drop-down list and select Add.
4. Type the name as alsdk.
5. ENTER .alsdk as the File Type.
Concepts

6. ENTER images\Icon.png as the Logo.


7. To save the changes to package.appxmanifest, press Ctrl+S.

V 1.0 © Aptech Limited


7
Session Launching, Debugging, and Publishing Windows Store App

Code Snippet 6 demonstrates the extension point.


Code Snippet 6:
Element hierarchy is as follows:
<Package>
<Applications>
<Application>
<Extensions>
<Extension>

XML

<Package xmlns=”http://schemas.microsoft.com/appx/2010/manifest”
xmlns:m2=”http://schemas.microsoft.com/appx/2013/manifest”>
<Apps>
<App Id=”AutoLaunch.App”>
<Extensions>
<Ext Category=”windows.fileTypeAssociation”>
<FileTypeAssociation Name=”alsdk”>
<DispName>SDK Type</DispName>
<Icon>image\Icon.png</Icon>
<Tip>SDK tip </Tip>
<EditFlags OpenIsSafe=”true” />
<SupportedFileTypes>
<FileType ContentType=”image/jpeg”>.alsdk</FileType>
</SupportedFileTypes>
</FileTypeAssociation>
</Ext>
</Extensions>
</App>
Concepts

</Apps>
</Package>

This code adds an Extension element to the package manifest. The windows.fileTypeAssociation category
indicates that the app handles files with the .alsdk extension. The extension element declares an
extensibility point for the app.

V 1.0 © Aptech Limited


7
Session Launching, Debugging, and Publishing Windows Store App

Step 2: Proper icons should be added.


The default app for a file type will be displayed in various places in the system. For example,

ÎÎ Context menus, Windows Explorer ItemsView, and the Ribbon

ÎÎ Control Panel of Default programs

ÎÎ File picker

ÎÎ On the Start screen when search results are displayed


Following are some guidelines:
1. Include appropriate icons in project to give a good look to logo.
2. Folder 16/32/48/256 px should be included for the small logo and icon sizes in the image.
3. The icons should be tested on white background so that it should suitable to the look and color plate
of the app tile logo. Figure 7.1 displays the icon image.

Concepts

Figure 7.1: Icons Image


Image Courtesy: msdn.com

V 1.0 © Aptech Limited


7
Session Launching, Debugging, and Publishing Windows Store App

Step 3: Handle the activated event.


All file activation events are received by the OnFileActivated event handler.

Note: The received file could have come from an untrustworthy source. So before taking action on it,
one should validate the content of a file.

ÎÎ How to handle URI activation


For a URI scheme name, as a default handler either desktop or Windows Store Apps can get
registered. As a default app, the chosen app will be activated every time when URI is launched. For
that type of URI scheme name, you should be registered to handle all URI launches.
Following steps show how to register for a custom URI scheme name, alsdk:// and activation app:
Step 1: The extension point in the package manifest should be specified.
The activation events are received by the app only for the URI scheme names which are listed in
the package manifest. The following steps show how you indicate the app handles the alsdk URI
scheme name.
1. Double-click package.appxmanifest in the Solution Explorer to open the file.
2. Click the Declarations tab.
3. Click Protocol from the drop-down list and click Add.
4. Type Name as the alsdk.
5. Type images\Icon.png as the Logo.
6. To save the changes to package.appxmanifest, press Ctrl+S.
If you follow these steps, it adds an Extension element to the package manifest. The app handles the
alsdk URI scheme name is indicated by windows.protocol category. Code Snippet 7 demonstrates the
use of Extensions.
Code Snippet 7:
XML

<Package xmlns=”http://schemas.microsoft.com/appx/2010/manifest”
xmlns:m2=”http://schemas.microsoft.com/appx/2013/manifest”>
<Apps>
<App Id=”AutoLaunch.App”>
Concepts

<Extensions>
<Ext Category=”windows.protocol”>
<Protocol Name=”alsdk” m2:DesiredView=”useLess”/>
<Icon>images\logo.png</Icon>

V 1.0 © Aptech Limited


7
Session Launching, Debugging, and Publishing Windows Store App

<DispName>SDK Sample URI Scheme</DispName>


</Ext>

</Extensions>
</App>
</Apps>
</Package>

The code snippet is used to add an Extension element to the package manifest. The windows.protocol
category indicates that the app handles the alsdk URI scheme name.
Step 2: Proper icons should be added.
The default app for a URI scheme name will be displayed in various places in the system.
Following are some guidelines:
1. Include appropriate icons in project to give a good look to logo.
2. Folder 16/32/48/256 px should be included for the small logo and icon sizes in the image.
3. The icons should be tested on white background which should be suitable for the look of the app
tile logo and the color plate.
Step 3: Handle the Activated event.
All activation events are received by the OnActivated event handler. The type of activation is indicated
by the event Kind property. Code Snippet 8 demonstrates how to set up to handle URI activation events.
Code Snippet 8:
C#

public partial class App


{
protected override void OnActivated(IActivatedEventArgs eventArgs)
{
if (eventArgs.Kind == ActivationKind.Protocol)
{
Concepts

ProtocolActivatedEventArgs protocoleventArgs = eventArgs as


ProtocolActivatedEventArgs;
// TODO: Write code to handle URI activation

V 1.0 © Aptech Limited


7
Session Launching, Debugging, and Publishing Windows Store App

// The received URI is eventArgs.Uri.AbsoluteUri


}
}
}

7.1.5 Auto-launching with AutoPlay


When a user links a device to their computer, AutoPlay enables you to provide your application as an
option. Using Proximity (tapping), AutoPlay when users share files between two machines, it allows
registering the application as an option.
To add AutoPlay declarations and to create a new project, few steps are shown here:
1. Open Visual Studio 2012 IDE.
2. Click File  New Project.
3. Select Windows Store Apps from the Visual C# section.
4. Type the application name as AutoPlayDisplayOrCopyImages and click OK.
5. Open the file Package.appxmanifest and Click Capabilities tab. To the removable storage
devices, access can be provided for camera memory.
6. Select the Removable Storage and Pictures Library capabilities that provide the access to local
pictures.
7. Click Declarations tab from the manifest file. In the Available Declarations drop-down list, select
AutoPlay Content, and click Add. Select the new AutoPlay Content item which was added to the
Supported Declarations list.
8. When AutoPlay raises a content event, an AutoPlay Content declaration identifies the application as
an option. AutoPlay inspects the content of the volume device (DVD or a thumb drive) and determines
which content event to raise. AutoPlay raises the ShowPicturesOnArrival event in the following
situations:
yy A DCIM, AVCHD, or PRIVATE\ACHD folder contained by the root of the volume. If a user has
enabled Choose what to do with each type of media in the AutoPlay Control Panel.
yy In the root of the volume, pictures are found.
For the first launch action, following values to be entered in the Launch Actions section. Table 7.1 lists
the settings.
Concepts

Setting Value
Verb Show
Action Display Name Show Pictures
Content Event ShowPicturesOnArrival
Table 7.1: Settings

V 1.0 © Aptech Limited


7
Session Launching, Debugging, and Publishing Windows Store App

The string which is AutoPlay displays for the application is identified by the ActionDisplayName setting.
For the selected option, the Verb setting identifies a value which is passed to the application. The multiple
launch actions for an AutoPlay event can be specified and use the Verb setting to identify which option a
user has selected for the application. The activation event arguments is passed to the application and by
checking this Verb property, you can identify which option the user has selected. You can use any value
for the Verb setting except, open, which is reserved.
9. In the Launch Actions section for the AutoPlay Content item, to add a second launch action, click
Add New. For the second launch action, enter the following values. Table 7.2 lists the values of the
second launch action.

Setting Value
Verb Copy the content
Action Display Name Copy Pictures Into Library
Content Event ShowPicturesOnArrival
Table 7.2: Values of Second Launch Action
10. Choose File Type Associations from the Available Declarations drop-down list and click Add.
11. Set the Display Name field to ‘AutoPlay Copy or Show Images’ and the Name field to ‘image_
association1’ from the Properties of the new File Type Associations declaration.
12. Set the File Type field of the default supported file type to .jpg from the Supported File Types
section. Then, click Add New in the Supported File Types section.
13. From the new file association, set the File Type field to .png. Then, save and close the manifest file.
Steps for the XAML page are as follows:
1. Open the MainPage.xaml file and to the default <Grid> section and add the following XAML code.
Code Snippet 9 demonstrates the XAML UI code.
Code Snippet 9:
XAML

<TextBlock FontSize=”17”>File List</TextBlock>


<TextBlock x:Name=”FilesBlock” HorizontalAlignment=”Left” TextWrapping=”Wrap”
VerticalAlignment=”Top” Margin=”0,20,0,0” Height=”270” Width=”230” />
<Canvas x:Name=”FilesCanvas” HorizontalAlignment=”Left”
VerticalAlignment=”Top”
Concepts

Margin=”260,20,0,0” Height=”270” Width=”90”/>

In this code, the columns and rows consisted by the grid class defines a flexible grid area.
2. Child elements to the row/column assignments of Grids are arranged and measured.
3. Initialization code should be added.

V 1.0 © Aptech Limited


7
Session Launching, Debugging, and Publishing Windows Store App

The verb value in the Verb property is checked by in this step. During this step, the startup arguments
are passed to the application during the OnFileActivated event. A user selected method related
to the option is called by the code. To the application for the camera memory event, the root folder
of the camera storage is passed by the AutoPlay. From the first element of the Files property, this
folder can be retrieved.
a. Add the following code to the App class by opening the App.xaml.cs or App.xaml.vb file.
Code Snippet 10 demonstrates the App class code.
Code Snippet 10:

C#
protected override void OnFileActivated(FileActivatedEventArgs
fileActivatedArgs)
{
if (fileActivatedArgs.Verb == “show”)
{
Frame firstRootFrame = (Frame)Window.Current.Content;
MainPage newPage = (MainPage) firstRootFrame.Content;
// Call DisplayImages with root folder from the camera storage.
newPage.DisplayImages((Windows.Storage.StorageFolder)
fileActivatedArgs.Files[0]);
}
if (fileActivatedArgs.Verb == “copy”)
{
Frame firstRootFrame = (Frame)Window.Current.Content;
MainPage newPage = (MainPage) firstRootFrame.Content;
// Call CopyImages with root folder from the camera storage.
newPage.CopyImages((Windows.Storage.StorageFolder)
fileActivatedArgs.Files[0]);
}
base.OnFileActivated(fileActivatedArgs);
Concepts

b. Save and close the App.xaml.cs file.


The OnFileActivated method is invoked when the application is activated through file-open.
Its parameter, Args denote the event data for the event. OnFileActivated is a pre-defined
activation point handler that is invoked for a core Activated event when the ActivationKind
is File. In the following step, code checks for the verb value in the Verb property, that is one

V 1.0 © Aptech Limited


7
Session Launching, Debugging, and Publishing Windows Store App

of the initial arguments passed to the application while the OnFileActivated event. The
method is then called which is related to the user selected option.
4. Add code to display images.
In the MainPage.xaml.cs or MainPage.xaml.vb file, add the following code to the MainPage
class. Code Snippet 11 demonstrates to display images.
Code Snippet 11:
C#

async internal void DisplayImages(Windows.Storage.StorageFolder


newRootFolder)
{
// Display images from the first folder in root\DCIM.
var dcimnewFolder = await newRootFolder.GetFolderAsync(“DCIM”);
var myFolderList = await dcimnewFolder.GetFoldersAsync();
var myCameraFolder = myFolderList [0];
var myFileList = await myCameraFolder.GetFilesAsync();
for (int j = 0; j < myFileList.Count; j++)
{
var newFfile = (Windows.Storage.StorageFile) myFileList [j];
WriteMsgText(newFfile.Name + “\n”);
DisplayImage(newFfile, j);
}
}
async private void DisplayImage(Windows.Storage.IStorageItem file, int
index)
{
try
{
var newStorageFile = (Windows.Storage.StorageFile)newFile;
Concepts

Windows.Storage.Streams.IRandomAccessStreamnewIimageStream =
await newStorageFile.OpenAsync(Windows.Storage.FileAccessMode.
Read);
Windows.UI.Xaml.Media.Imaging.BitmapImage newImageBitmap =

V 1.0 © Aptech Limited


7
Session Launching, Debugging, and Publishing Windows Store App

new Windows.UI.Xaml.Media.Imaging.BitmapImage();
newImageBitmap.SetSource(imageStream);
var newElement = new Image();
newElement.Source = imageBitmap;
newElement.Height = 100;
Thickness elementMargin = new Thickness();
elementMargin.Top = index * 100;
element.Margin = elementMargin;
FilesCanvas.Children.Add(newElement);
}
catch (Exception error)
{
WriteMsgText(error.Message + “\n”);
}
}
// Write a message to MessageBlock on the UI thread.
private Windows.UI.Core.CoreDispatcher messageDispatcher = Window.
Current.CoreWindow.Dispatcher;
private void WriteMsgText(string message, bool overwrite = false)
{
messageDispatcher.InvokeAsync(Windows.UI.Core.
CoreDispatcherPriority.Normal,
(s, a) =>
{
if (overwrite)
FilesBlock.Text = newMessage;
else
FilesBlock.Text += newMessage;
Concepts

}, this, null);
}
The code snippet is used to display all the images specified in the GetFolderAsync method.
This method gets a single sub folder from the current folder using the specified folder name.

V 1.0 © Aptech Limited


7
Session Launching, Debugging, and Publishing Windows Store App

The InvokeAsync method executes the specified delegate asynchronously on the thread the
Dispatcher is associated with.
5. To copy images, code should be added.
In the MainPage.xaml.cs or MainPage.xaml.vb file, add the following code to the MainPage class.
Code Snippet 12 demonstrates how to copy images.
Code Snippet 12:
C#

async internal void CopyImages(Windows.Storage.StorageFolder


newRootFolder)
{
// Copy images from first folder in root\DCIM.
var newDCIMFolder = await newRootFolder.GetFolderAsync(“DCIM”);
var newFolderList = await newDCIMFolder.GetFoldersAsync();
var newCameraFolder = newFolderList [0];
var newFileList = await newCameraFolder.GetFilesAsync();
try
{
var newFolderName = “Images “ + DateTime.Now.ToString(“yyyy-MM-dd
HHmmss”);
Windows.Storage.StorageFolder newImageFolder = await
Windows.Storage.KnownFolders.PicturesLibrary.
CreateFolderAsync(newFolderName);
foreach (Windows.Storage.IStorageItem newFfile innewFileList)
{
CopyImage(newFfile, newImageFolder);
}
}
catch (Exception error)
Concepts

{
WriteMsgText(“Failed to copy images.\n” + error.Message + “\n”);
}
}

V 1.0 © Aptech Limited


7
Session Launching, Debugging, and Publishing Windows Store App

async internal void CopyImage(Windows.Storage.IStorageItem newFfile,


Windows.Storage.StorageFolder newImageFolder)
{
try
{
Windows.Storage.StorageFile storageFile = (Windows.Storage.
StorageFile) newFfile;
await stFile.CopyAsync(newImageFolder, storageFile.Name);
WriteMsgText(storageFile.Name + “ copied.\n”);
}
catch (Exception error)
{
WriteMsgText(“File copy failed.\n” + error.Message + “\n”);
}
}

In this code, the images are copied from the first folder in the DCIM folder to the new image folder.
6. Build and execute the application. Press F5 to build and deploy the application in debug mode.
To run your application, insertion of a camera memory card or any other storage camera device
into the machine is necessary. From the AutoPlay list of options, choose one of the content event
options which you specified in your package.appxmanifest file. The camera memory card in
the DCIM folder, the sample code displays or copies pictures. The camera memory card stores
pictures in a PRIVATE\ACHD or AVCHD folder which is required to update the code accordingly. In
case of unavailability of camera memory card, a flash drive can be used as long as it has a folder
named DCIM in the root.

7.1.6 Transferring Data in the Background and Supporting with


Background Tasks
Windows.Networking.BackgroundTransfer APIs are provided in the Windows Runtime. It is used to improve
Concepts

the Windows Store App with advanced upload features and file download that run in the background
during App suspension, Operation lifecycle management, and persistence beyond app termination.
The Background Transfer feature works as follows:

ÎÎ The request is configured and initialized using BackgroundDownloader or

V 1.0 © Aptech Limited


7
Session Launching, Debugging, and Publishing Windows Store App

BackgroundUploader class objects. It is used to initiate a transfer of Windows Store App


Background Transfer.

ÎÎ Each transfer operation is managed individually by the system and through an app UI progress
information is available for display.

7.2 Debugging and Testing


A set of testing and debugging tools are included in the Visual Studio which helps to ensure that the
Windows Store App is of the highest quality.

7.2.1 Debugging and Testing with Visual Studio 2012


Windows Store Apps run on a broad range of devices, and Visual Studio provides you with a number of
ways to run and interact with those apps.

ÎÎ Run Windows Store Apps from Visual Studio


F5 is used to make it easy to test apps, profile, and debug during development. Figure 7.2 displays
the debug mode.

Figure 7.2: Debug Mode


Image Courtesy: msdn.com

ÎÎ Debug Windows Store Apps in Visual Studio


The Visual Studio debugger controls the execution of a program and also examines its state.
Debugger can be used to find the cause of defects in Windows Store App. Also, it is used to
Concepts

understand exactly how your app works. Executing code is displayed by the visual studio when the
execution in the debugger gets suspended. The change of values of the program can be seen by
executing the program one statement at a time.

V 1.0 © Aptech Limited


7
Session Launching, Debugging, and Publishing Windows Store App

7.2.2 Debugging DLL Load Failures with the Event Viewer


Following steps show using the Event Viewer to debug DLL load failures in Windows Store Apps and
desktop Apps:
1. Open Event Viewer.
2. Go to Windows Logs and select Application channel.
3. View the Level: information and Source: User-loader properties.
To see error messages:
1. Open Event Viewer.
2. Select Show Analytic and Debug Logs from the View menu to enable the analytic log channel.
3. Go to Applications and Services Logs, select Microsoft and then, select Windows later then, select
User-Loader analytic channel.

7.2.3 Using the Windows App Certification Kit


Before app get certified and listing in the Windows Store, validate and test it on your system. You will
learn to install and run the Windows App Certification Kit.
Following are the prerequisites for developing a Windows 8 app:

ÎÎ Windows 8 or Windows 8.1 must be installed.

ÎÎ Windows App Certification Kit version 3.1 must be installed which appears along with the
Windows Software Development Kit (SDK) for Windows 8.1.

ÎÎ A valid developer license must be in your computer.

Note: When the app package is created in Visual Studio, run the Windows App Certification Kit.

The installation of Windows App Certification Kit version 3.1 or higher version will replace any earlier
version of the kit that is installed on the system.

7.3 Packaging the Windows Store App


Using Visual Studio, Windows Store can be accessed and Windows Store App can be packaged for
distribution. Before uploading app to store, it must be packaged and prepared. When you create a
Concepts

Windows Store project or item based on a template then, the packaging process gets started. When
Windows Store App is created, Visual Studio creates a source file for the app package.

V 1.0 © Aptech Limited


7
Session Launching, Debugging, and Publishing Windows Store App

7.3.1 Optimizing Images for Different Screen Resolutions


In different screen resolutions, the logos and splash screen should look properly before publishing the
Windows Store App. Also it should provide some versions of each image at different sizes to make images
fit into app. Then, it will reduce the degree to Windows which will stretch or shrink to the graphics.

ÎÎ Obtaining image files


The App logos, Store logo, and splash screen are required in the following sizes shown in table 7.3.

Square 70 x 70 Logo Scale Factors Image Dimensions


For Scale 180 (180%) Image Dimension is 126 x 126px
For Scale 140 (140%) Image Dimension is 98 x 98px
For Scale 100 (100%) Image Dimension is 70 x 70px
For Scale 80 (80%) Image Dimension is 56 x 56px
Square 150 x 150 Logo Scale Factors Image Dimensions
For Scale 180 (180%) Image Dimension is 270 x 270px
For Scale 140 (140%) Image Dimension is 210 x 210px
For Scale 100 (100%) Image Dimension is 150 x 150px
For Scale 80 (80%) Image Dimension is 120 x 120px
Table 7.3: Image Sizes

ÎÎ How to add image files


Add the appropriate sizes of image files to the project and then, in the manifest file, it should be
identified. According to the type of asset, name the files.
Adding the image files to your project:
1. Open the Windows Store App project.
2. To the Assets folder in the project, add the image files.
To identify the files in the manifest:
1. Open the App Manifest Designer (Package.appxmanifest) from the Solution Explorer and
then, choose the Application UI tab.
2. For logos and the splash screen, display the settings by selecting All Image Assets from the
list of visual assets.
Concepts

3. Specify one in the Short Name text box on your main logo.
4. For the main logo, indicate a logical name in the Square 150 x 150 Logo text box and the
default value is Assets\Logo.png.
5. In the Scaled Assets area of the page, choose the Browse button next to the Scale 80 box,
move to the Assets folder, show the file that contains the image that’s scaled to 80%, and then,

V 1.0 © Aptech Limited


7
Session Launching, Debugging, and Publishing Windows Store App

choose the Open button.


6. Choose the appropriate files by completing the Square 150 x 150 Logo settings and add them
to the Scale 100, Scale 140, and Scale 180 boxes.
7. Steps 4-6 to be repeated for other dimensional, Store logo, and the splash screen.

7.3.2 Localizing the Package Manifest


By considering the local name of the display, other identifying features and description that are described
in the package manifest file, Windows Store App can be made more attractive to international audiences.
While localizing a field, set its value to ms-resource: TokenName. TokenName identifies a resource in a
file that’s located in a language-appropriate folder, as shown in Code Snippet 13.
Code Snippet 13:

<Properties>
<Property>
<DisplayName>ms-resource:calculator</DisplayName>
<Desc>ms-resource:numbers</Desc>
<Icon>tile.png</Icon>
</Property>
</Properties>

This code localizes the values of DisplayName and Desc tags.


Follow the following steps to create the resource file:
1. Open the Solution Explorer.
2. For the project name, open the shortcut menu.
3. Choose Add.
4. Choose New Item.
5. Click Resources file.
6. Click Yes.
7. In application, type values for each resource, and then, save the file.
Concepts

8. Update Design view by switching to Source view if the resource changes are not displayed, and
then, switch back to Design view.
For additional languages to create resource files, copy the file from Solution Explorer or in Windows
Explorer, and then, rename it using name.language.resx or using name.language-culture.resx
patterns.

V 1.0 © Aptech Limited


7
Session Launching, Debugging, and Publishing Windows Store App

7.3.3 Generating the Package Manifest


When it generates the manifest for the app package, Visual Studio resides in the following tables:

ÎÎ The value of the field is a generated GUID, by default.

ÎÎ If Windows Store is associated with the app or the Create App Package command is invoked
then, sign in with a developer account, from the associated app on the Store, the value of the field
is restored.

ÎÎ If you have invoked the Create App Package command but not signed into the account of
Microsoft developer, then from the source manifest, the value of this field is taken.

7.3.4 Creating an App Package


Through Windows Store or to other local computer app can be distributed. Following steps guide you to
create an app package by using the Create App Packages wizard:
Step 1: Start the wizard
On the menu bar, choose ProjectStoreCreate App Packages then, the Create App Packages will
be displayed.
Creating an app package for the Store
1. Select the Yes button.
To create a developer account, choose Create an account link.
2. Select the Next button.
3. In the Sign In dialog box, enter the Microsoft account and password, and then choose the Sign In
button.
Then, the wizard Select an app name page appears.
For local testing and distribution how to create an app package
First, choose the No button, and then choose the Next button. Wizard’s Select and Configure Packages
page appears.
Step 2: Name the app
To publish in the Windows Store, the following procedure is applied:
Concepts

1. Before choosing the Reserve button, type a name in the Reserve a new app name text box.
2. Choose the Next button after selecting the app name for which you want to create this package.
Wizard’s Select and Configure Packages page appears.

V 1.0 © Aptech Limited


7
Session Launching, Debugging, and Publishing Windows Store App

Step 3: Select and configure app packages


1. Enter the package files creating location (In the Output location text box).
The package can be uploaded from this location.
2. Select the Automatically increment check box (recommended) to maintain version automatically.
3. To increment the version numbers manually.
4. To create and the solution configuration mappings under Select the packages.
5. To create a package for each build configuration, select the check box.
6. Choose the Solution Configuration for specified each build configuration.
7. If any Include public symbol files are present there then, select or clear them. This is essential to
enable crash analysis for the app check box.
8. Create button should be chosen.
Once this packaging process gets completed, the Package Creation Completed page appears.
Step 4: Validate app packages
Validation of app should be done against devices that you plan to target before it is certified. In Windows
Store, submit it for certification and listing.

7.3.5 Signing an App Package


By default, all Visual Studio generated app packages are signed with a test certificate. Visual Studio
generates a folder when you create a package and includes the signed package itself. The public key
which is used to sign the package is contained by the certificate (.cer) file that is included in the folder.
Before the app package is installed, the key must be installed on the system.
Generating the Test Certificate
When the project is created, the certificate file (.pfx) is generated and it is added to your project.
The Publisher attribute of the Identity element of the source manifest (.appxmanifest) file is set by the
certificate’s Subject field.

ÎÎ The default value of the Publisher attribute is your user name if you create a local package.

ÎÎ The Publisher attribute is set to the Publisher ID which is either created by a package for the
Concepts

Windows Store or associates your app with it. When you sign in during package creation, it is
obtained from your developer account at the Store.

V 1.0 © Aptech Limited


7
Session Launching, Debugging, and Publishing Windows Store App

Code Snippet 14 adds a property to certificate creation to the project file.


Code Snippet 14:

<PackageCertificateKeyFile>
RisingStar_TemporaryKey.pfx
</PackageCertificateKeyFile>

The connected path or full path of the source certificate itself is the value of the PackageCertificateKeyFile.
The values of following properties are set when the Visual Studio creates a certificate.

ÎÎ The value of the Basic Constraints extension is set to Subject Type=End Entity.

ÎÎ The value of the Enhanced Key Usage (EKU) extension is set to Code Signing.
Certification validity gets over for one year from the date when they were created.
Modifying installed apps
If installed package files are modified, launching the app may prevented by signing verification. Make the
changes in the original source files using a developer license to modify a package, and then redeploy the
modified package.

7.3.6 Sharing an App Package Locally


1. In the Visual Studio output directory, find the Add-AppDevPackage PowerShell script in the .appx
file.
2. Select Run with PowerShell on the shortcut menu for Add-AppDevPackage.ps1 file.
3. Following steps are performed by the script:
a. Certificate that the script will install, displays information about it. On the problem of
changing the execution policy, a warning message is displayed on your local machine by the
script.
b. Execution policy can be confirmed by entering the following:
ŠŠ Enter Y to change the execution policy.
ŠŠ Enter N, to skip the operation and continue with the next operation.
ŠŠ Enter S, to pause the existing pipeline and go back to the command prompt.
Concepts

ŠŠ Enter the word exit to resume the pipeline.


c. Checks for developer license and if the present license has expired, you are provided to get
one.
d. Checks for if any item is missing. If items are missing, displays a message to install them.

V 1.0 © Aptech Limited


7
Session Launching, Debugging, and Publishing Windows Store App

e. The presence of any required dependency packages verified by it.


f. Dependency packages and the app package are installed by it.
4. Choose the tile which shows the name of the app on the Start screen. Then, the app starts.

7.3.7 Building an App Package at a Command Prompt


Before installing a Windows Store App, on one or more local computers, upload it to the Windows Store.
Then, build an app package.
1. An app package can be built by either opening a Visual Studio command prompt or by using Team
Foundation Build.
2. Windows Store App can be built at a command prompt and indicate no additional targets or flags.
Under OutDir, the output appeared in a project-specific folder i.e. initially, build an app by opening
a Visual Studio command prompt and then, specify the following command line:
MSBuild MyProject.csproj /p:OutDir=C:\builds\droplocation\
In the following location, app package and other build output is created as follows:
C:\builds\droplocation\MyProject\
By specifying the following the project-specific folder, behavior can be overridden.
/p:GenerateProjectSpecificOutputFolder=false

7.3.8 Validating an App Package in Automated Builds


By validating an app you should make sure that it will pass through the validation tests, which are required
by a Windows Store when app is published.
Integrating Windows ACK validation with Team Foundation Build
1. To make it editable, unload the project file.
2. Copy the following PostPackageEvent target, and then near the end of the file, it should be pasted.
Code Snippet 15 demonstrates the PostPackageEvent.
Code Snippet 15:

<Target Name=”PostPackageEvent” AfterTargets=”_GenerateAppxPackage”>


<ReadLinesFromFile Condition=”Exists($(AppxPackagingInfoFile))”
Concepts

File=”$(AppxPackagingInfoFile)”>
<Output TaskParameter=”Lines”
PropertyName=”AppxPackagingOutputForWinACK” />
</ReadLinesFromFile>

V 1.0 © Aptech Limited


7
Session Launching, Debugging, and Publishing Windows Store App

<Exec Command=”&quot;$(TargetPlatformSdkPath)App Certification Kit\


appcert.exe&quot; reset” />
<Exec Command=”&quot;$(TargetPlatformSdkPath)App Certification Kit\
appcert.exe&quot; test -apptype windowsstoreapp -packagefullname
&quot;$(AppxPackagingOutputForWinACK)&quot; -reportoutputpath
&quot;$(ProjectDir)$(outdir)ValidationResult.xml&quot;” />
<Exec Command=”copy &quot;$(userprofile)appdata\Local\Microsoft\
appcertkit\ValidationResult.htm&quot; &quot;$(ProjectDir)$(outdir)
ValidationResult.htm&quot;” />
</Target>

3. In report, the output file ValidationResult.xml, will be written. Make sure that the directory exists
before you queue the build, if you specify a static location rather than $(outdir). Also, ensure that
before you queue the build again, delete the output file. Build should be automated.
4. When the build finishes, examine the test results in the ValidationResult.htm file. In the last entry of
the PostPackageEvent target, the test results appear which is previously pasted into the
ValidationResult.htm file.

7.3.9 Overriding a Package Manifest


The source manifest (.appxmanifest) file is transformed by package build process which is included in the
package contents. Changes into the manifest can be introduced in this transformation. This transformation
can be overridden by providing self target manifest file.
1. Open the shortcut menu from the Solution Explorer for the project name, choose Add, and then,
choose New Item.
2. In the Add New Item dialog box, choose XML file, and name the file AppxManifest.xml.
Rather than in a sub folder, the file should be in the project root.
3. Edit the rest of the AppxManifest.xml file to match the requirements of the app.
4. Delete the Package.appxmanifest file, or exclude it from the project.
Concepts

V 1.0 © Aptech Limited


7
Session Launching, Debugging, and Publishing Windows Store App

7.4 Check Your Progress


1. Background task can be used to run _________________ code in the background.

(A) Heavyweight (C) Short


(B) Lengthy (D) Lightweight

2. Registering is necessary to handle the Suspending event in which app is required to save its
_________________.

(A) Application data (C) Initial data


(B) Registered data (D) App data

3. App should be designed in such a way that, it should get _________________ and should resume
when the user switches back to it.

(A) Registered (C) Suspended


(B) Terminated (D) Stopped

4. As a ______________________ the chosen app will be activated every time when that type of
file is launched.

(A) Chosen app (C) Windows app


(B) Default app (D) Suspended app


5. The app receives activation events for the __________________ scheme names, listed in the
package manifest.

(A) URI (C) CRI


(B) MRI (D) FRI
Concepts

V 1.0 © Aptech Limited


7
Session Launching, Debugging, and Publishing Windows Store App

7.4.1 Answers
1. D
2. A
3. C
4. B
5. A

Concepts

V 1.0 © Aptech Limited


7
Session Launching, Debugging, and Publishing Windows Store App

Summary
ÎÎ Windows 8 suspends your app in memory when users move your app off-screen and enables
another app to have the foreground.
ÎÎ The system sends the Activated event when the user switches to the Terminated app.
ÎÎ By releasing exclusive resources and file handles which helps other apps can access them while
this app is not using them.
ÎÎ As a default app, the chosen app will be activated every time when that type of file is launched.
ÎÎ URI scheme name should be registered to handle all URI launches for that type of URI scheme.
ÎÎ User connects a device to their computer auto play to provide your application as an option.
ÎÎ A set of testing and debugging tools are included in the Visual Studio which helps to ensure that
the Windows Store App is of the highest quality.
ÎÎ Using Visual Studio Windows Store can be accessed and Windows Store App can be packaged for
distribution.
Concepts

V 1.0 © Aptech Limited

You might also like