Sunteți pe pagina 1din 206

Advanced Windows Store

Apps Development - I

Advanced Windows Store Apps


Development - I
Learners Guide
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
First Edition - 2014

Dear Learner,
We congratulate you on your decision to pursue an Aptech 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 prepaid form appended at the end of each module.

*TAG Technology & Academics Group comprises 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.
Industry Recruitment Profile Survey - The Industry Recruitment Profile Survey was conducted
across 1581 companies in August/September 2000, representing the Software, Manufacturing,
Process Industry, Insurance, Finance & Service Sectors.

Aptech New Products Design Model


Key Aspects

1
Scanning the
user system
and needs
assessment

Evaluation of
Instructional
Processes and
Material

Need Analysis
and design of
curriculum

Design and
development of
instructional
material

Assessment
of learning

Strategies for
delivery of
instructions

Preface
The book aims to provide students with the skills to develop basic and advanced Windows Store apps.
This book begins with introducing Windows Store app development and describes animations and
transitions. The book also describes, transforms and the advantage of using Windows Runtime animation
library. The concept and implementation of localization is also covered in the book. The book also
explains about extending splash screens. The book further discusses creating and using custom controls
and WinRT controls. The book then moves on to the concepts of contracts, printing settings, and PDF
conversion classes. It also teaches speech synthesis and acquaints the users with speech synthesis
classes.
With Windows 8 and later versions, Microsoft had added some of the cloud computing features such as
Notification Service and Microsoft Windows Notification Service Channel. Using these features, the users
can create, send, request ,and save such notifications on the cloud. In todays world, multimedia is at the
base of all. Pictures, audio, and video are very much in demand. Windows Store apps allows the users to
embed these multimedia features in their applications. This book provides the knowledge about all these
multimedia extensions to the existing programming world.
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 Aptechs 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.

Windows Store Apps Essentials

2.

Windows Store UI Localization

3.

Adding Splash Screens and Branding to Apps

4.

Storage Mechanisms

5.

Working with Controls

6.

Using Contracts, Print Settings, and Speech Synthesis

7.

Push Notification Services

8.

Media Capturing

Session -1
Windows Store Apps Essentials
Welcome to the Session, Windows Store Apps Essentials.
This session introduces you to Windows Store Apps essentials, creating User
Interfaces (UIs) with eXtensible Application Markup Language (XAML), and also
describes animations and transitions.
In this Session, you will learn to:
Describe Windows Store Apps essentials
Explain the process of creating UIs with XAML
Define animations and transitions
Describe the process to use animation functions

Session

1
Windows Store Apps Essentials

1.1 Windows Store Apps Essentials


Windows Store is an Application Store, which was established under Windows 8. It provides various apps,
similar to Google, Apple, or BlackBerry apps and allows the distribution and purchase of apps designed
for Windows 8. These apps can be developed for Windows 8 PCs and Tablets.
Minimum requirements for developing Windows Store apps are as follows:

Windows 8 or higher

Microsoft Visual Studio Express 2012 or higher

Microsoft .NET Framework 4.5 or higher

A developer license registration

1.1.1 Windows 8 Platform, Architecture, and Features

Concepts

Figure 1.1 shows the architecture for Windows 8.

Figure 1.1: Windows 8 Runtime Architecture

V 1.0 Aptech Limited

Session

1
Windows Store Apps Essentials

The features of Windows 8 are as follows:

Fast Boot Time

Metro UI Design

Secure Boot (Using Unified Extensible Firmware Interface (UEFI))

New Installation, Repair, and Reboot

Start Screen and Dynamically Updated Tiles

Built-in Antivirus Capability

Windows Store

Family Safety

Improved File Explorer (formerly Windows Explorer)

Improved Task Manager

Microsoft Account Information

Picture Password

PC Reset and PC Refresh

1.1.2 Windows 8 Design and Features


Live Tiles
Live tiles are used to show the live updates from the Internet. These are a key part of Start screen.
This tile dynamically synchronizes stock updates, live news, and calendar from Hotmail accounts
and displays the status on the home screen. They are used for making the design fast and fluid. A
Live tile can either be static or live.

Splash Screen
Whenever any app is started, a splash screen is displayed. This can also be configured to show when
a dynamic update of any app is going on. It normally consists of screen image and background color.
A well-designed splash screen will make application more lively, attractive, and inviting.

V 1.0 Aptech Limited

Concepts

Session

1
Windows Store Apps Essentials

Hub Control
A hub control helps you to create multiple sections. It is displayed in the apps main content. It is
also called Hub View or Hub Page. It gives flexibility to design and customize the app to suit our
brand needs. It uses a hierarchical navigation pattern.

App Bar
App bars are applied to perform actions on UI elements, such as filtering results or navigating within
the app, or deleting photos. They are invoked by swiping from the top or bottom of the screen or
by right- clicking on the current app. They provide easy access to various commands. They can also
be hidden or made context sensitive.

Detail Page
The detail page is the content page for all the apps developed for Windows 8. It shows the actual
information related to the current app. When the user selects a particular option or command, this
screen is displayed to show the details related to the selected option or command.

1.1.3 Windows Charms and Contracts


When you move the mouse on the right side of the screen, you can see the Search, Share, Start, Device,
and Settings options, these are called charms. These charms can also be displayed by tapping Win+C
keys. It is a universal toolbar for Windows 8. It can be used to work productively and add beauty to
Windows Store apps.

Concepts

Figure 1.2 shows the charms used in Windows 8.

Figure 1.2: Windows Charms


V 1.0 Aptech Limited

Session

1
Windows Store Apps Essentials

Search

Search command is used to search any files from Windows Explorer, SkyDrive, or from the Bing Search
Engine. Press the Win+S keys and enter the file name or text to be searched. This search charm will show
the matching result with links. You can open the file just by clicking on the given links.
By default, it shows the contents from the PC and SkyDrive at the beginning and then, it lists the contents
from the Web. If you wish to go back to the Search charm again, you can point the mouse cursor to the
upper-left corner and click the given thumbnail. This will take you to the Search charm again.
Figure 1.3 shows an example of using Search charm to search for Lock Screen.

Figure 1.3: Search for Lock Screen

Concepts

In Windows 8, you can share files, photos, or thoughts with known people, any social media network,
and share the SkyDrive files with any contact. You can share an app or a link by selecting Share button
on the charm and then, selecting the person with whom you wish to share the app or link, as shown in
figure 1.4.

V 1.0 Aptech Limited

Session

1
Windows Store Apps Essentials

Figure 1.4: Share a File


We can modify the settings of the share content by choosing the Settings charm button and navigating
to Change PC Settings.

Start
When you click the Windows Logo, home screen is displayed. You can go back to previous screen
by clicking on the same button once again.

Devices
Swipe to the right edge of the screen to select the active and connected devices in your system. By
using this option, you can:

Concepts

yy

View and/or play streaming music, videos, or a photo.

yy

Print a document and photo or send an email.

yy

Start Projector connected to the PC (presentation, slide show).

Settings
Swipe to the right side of the screen to view the Settings charm. Using this, you can view or modify
settings for an app, network, devices, user accounts, PCs information, and so on, as shown in figure
1.5.

V 1.0 Aptech Limited

Session

1
Windows Store Apps Essentials

Figure 1.5: Settings

1.1.4 Layout Controls in XAML


Layouts are used for sizing and positioning objects in the current UI. If you wish to position your objects
properly, you must put them in containers such as Panel, Canvas, StackPanel, and Grid controls provided
by XAML for this purpose. These containers allow us to position and arrange our objects inside the UI.

Absolute layout

Dynamic layout

Absolute layout controls are used to position your objects inside the panel or Canvas. Here, we specify
the exact position of the element or an object by specifying Canvas.Left and Canvas.Top properties
of the child element. In Dynamic layout, the user can fix their own size in the user interface based on the
screen resolution. Absolute layout is independent of the screen resolution. Dynamic layout on the other
hand, does not specify the exact positioning of the child elements. The size as well as the location of the
child elements is automatically adjusted as per the changes in the resolution of the screen. Controls such
as Grid, StackPanel, and VariableSizedWrapGrid are used to define and create Dynamic layout.

V 1.0 Aptech Limited

Concepts

There are mainly two types of layouts in XAML:

Session

1
Windows Store Apps Essentials

Canvas
In XAML, the default container is Canvas. It is a type of absolute layout. We can set its
Canvas.Left and Canvas.Top properties to its exact position in the parent container.
Note - Canvas has a property called Canvas.ZIndex, which can be set on each of the child

elements.

The following example shows how to design a layout in the Canvas using a step-by-step procedure:
1.

Launch Visual Studio 2013.

2.

Create a new project using File New Project Blank App (XAML).

3.

Enter the Project name as CanvasDemo and click OK.

4.

Add the code shown in Code Snippet 1 to MainPage.xaml.

Code Snippet 1:
<Page
x:Class=CanvasDemo.MainPage
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
xmlns:local=using: CanvasDemo
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}>
<Canvas Background=Black>
<Rectangle Canvas.Left=100 Canvas.Top=50 Fill=Red Width=50
Height=150 />
</Canvas>

Concepts

</Grid>
</Page

The code creates a Canvas which has a Rectangle UI element defined inside it. The output of
Code Snippet 1 is shown in figure 1.6.

V 1.0 Aptech Limited

Session

1
Windows Store Apps Essentials

Figure 1.6: Canvas Layout with a Rectangle

StackPanel
The StackPanel container is applied to align the child elements either horizontally or vertically.
The user can specify the Orientation property of the child element in the StackPanel. You can
specify the Height and Width properties of the control. If you specify orientation as Horizontal,
then all the elements will be arranged in horizontal order. There are two options Horizontal or
Vertical. The following step-by-step procedure shows how to create a vertical StackPanel of
items.
1.

Create a blank application by selecting File New Project Blank App (XAML).

2.

Enter name of the project as StackPanelDemo and click OK.

3.

Add the code shown in Code Snippet 2 to MainPage.xaml.

Code Snippet 2:
<Page
x:Class=StackPanelDemo.MainPage
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
xmlns:local=using:StackPanelDemo
xmlns:d=http://schemas.microsoft.com/expression/blend/2008

V 1.0 Aptech Limited

Concepts

xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation

Session

1
Windows Store Apps Essentials
xmlns:mc=http://schemas.openxmlformats.org/markup-ompatibility/2006
mc:Ignorable=d>
<StackPanel Margin=20>
<Rectangle Fill=Blue Width=25 Height=25 Margin=10 />
<Rectangle Fill=Green Width=25 Height=25 Margin=10 />
<Rectangle Fill=Red Width=25 Height=25 Margin=10 />
<Rectangle Fill=Yellow Width=25 Height=25 Margin=10 />
</StackPanel>
</Page>

Concepts

When the Orientation property of StackPanel is set to vertical, then the output of Code
Snippet 2 will be displayed as shown in figure 1.7.

Figure 1.7: StackPanel with Four Rectangles in Vertical Orientation

Grid
The Grid panel is utilized to set the controls in array dimensions similar to
multi-row and multi-column layouts. The user can specify a Grids row and

V 1.0 Aptech Limited

Session

1
Windows Store Apps Essentials

column definitions by using the RowDefinitions


and ColumnDefinitions properties
within the Grid element. The user can specify the Grid.Column and Grid.Row properties,
and set the number of rows and columns that should be there in the current Grid.
The step-by-step procedure to use a Grid control is as follows:
1.

Create a blank application by selecting File New Project Blank App (XAML).

2.

Enter name of the project as GridDemo and click OK.

3.

Add the code shown in Code Snippet 3 to MainPage.xaml.

Code Snippet 3:
<Page
x:Class= GridDemo.MainPage
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
xmlns:local=using:App25
xmlns:d=http://schemas.microsoft.com/expression/blend/2008
xmlns:mc=http://schemas.openxmlformats.org/markupcompatibility/2006
mc:Ignorable=d>
<Grid Grid.Column=4 Grid.Row=2 Background=Beige Opacity=10
Visibility=Visible>
<Button Content=Click Me 1 HorizontalAlignment=Left Margin=59,27,0,0
VerticalAlignment=Top Height=126 Width=256 Background=Blue
Foreground=White/>
<Button Content=Click Me 2 HorizontalAlignment=Left
Margin=331,189,0,0 VerticalAlignment=Top Height=126 Width=256
Background=Blue Foreground=White/>

<Button Content=Click Me 4 HorizontalAlignment=Left


Margin=331,27,0,0 VerticalAlignment=Top Height=126 Width=256
Background=Blue Foreground=White/>
<Button Content=Click Me 5 HorizontalAlignment=Left
Margin=620,27,0,0 VerticalAlignment=Top Height=126 Width=256
Background=Blue Foreground=White/>

V 1.0 Aptech Limited

Concepts

<Button Content=Click Me 3 HorizontalAlignment=Left


Margin=916,27,0,0 VerticalAlignment=Top Height=126 Width=256
Background=Blue Foreground=White/>

Session

1
Windows Store Apps Essentials

<Button Content=Click Me 6 HorizontalAlignment=Left Margin=620,189,0,0


VerticalAlignment=Top Height=126 Width=256 Background=Blue
Foreground=White/>
<Button Content=Click Me 7 HorizontalAlignment=Left Margin=916,189,0,0
VerticalAlignment=Top Height=126 Width=256 Background=Blue
Foreground=White/>
<Button Content=Click Me 8 HorizontalAlignment=Left Margin=59,188,0,0
VerticalAlignment=Top Height=126 Width=256 Background=Blue
Foreground=White/>
</Grid>
</Page>

The output of the code is shown in figure 1.8.

Figure 1.8: Grid with Four Columns and Two Rows

VariableSizedWrapGrid
VariableSizedWrapGrid is used to style the grid layout panel for each tile or cell, which

change their sizes based on contents in it. The elements are arranged in rows or columns and are
automatically wrapped until the MaximumRowsOrColumns value is reached.

Concepts

Each cells size is specified using ItemHeight and ItemWidth (in pixels). Child elements can use
VariableSizedWrapGrid.ColumnSpan and VariableSizedWrapGrid.RowSpan (values as
cell counts) to adjust inside the screen. WrapGrid and VirtualizingStackPanel are panels
that can only be used to display items in an ItemsControl.
The step-by-step procedure to use a VariableSizedGrid control is as follows:
1.

Create a blank application by selecting File New Project Blank App (XAML).

2.

Enter name of the project as VariableSizedGridDemo and click OK.

V 1.0 Aptech Limited

Session
3.

1
Windows Store Apps Essentials

Add the code shown in Code Snippet 4 to MainPage.xaml.


Code Snippet 4:
<Page
x:Class= VariableSizedWrapGridDemo.MainPage
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
xmlns:local=using:App26
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}>
<VariableSizedWrapGrid Orientation=Horizontal>
<Rectangle Width=150 Height=400 Margin=50 Fill=Blue />
<Rectangle Width=150 Height=50 Margin=5 Fill=Red />
<Rectangle Width=150 Height=150 Margin=15 Fill=Green />
<Rectangle Width=150 Height=300 Margin=5 Fill=Red />
<Rectangle Width=150 Height=180 Margin=5 Fill=Yellow />
</VariableSizedWrapGrid>
</Grid>
</Page>

Concepts

The output of the code is shown in figure 1.9.

Figure 1.9: VariableSizedWrapGrid


V 1.0 Aptech Limited

Session

1
Windows Store Apps Essentials

1.1.5 Snapping and Resizing


When the user needs to access more than one task at a time, he/she can snap the screen. The default
width of a snap screen is 320px wide. To create a snap screen, the user has to navigate the mouse pointer
to the upper-left part of the screen and drag the thumbnail to the right. This will have a large screen
width of 1024px, whereas if the user drags the thumbnail to the left, the screen will be small with the
size of 320px width. The user must design the apps, which look good when viewed in any size, so that the
app can support different resolutions and orientations.
Note - Windows 8 allows snapping feature when the screen resolution is more than 1366 x 768; In

Windows 8.1, the minimum resolution is not required. It works with all resolution types.

The user either can change the size of some apps or can display many apps on single screen. The minimum
height of an app always fits the height of the screen.
Support for Window Resizing:
The user can change the size of the window to any width they require. Meanwhile, the user can rotate
or flip tablets or monitors. Windows 8 handles both orientations automatically. The user only needs to
consider how the apps size affects its layout. Windows apps can run on different resolutions from a small
tablet to a laptop or desktop. The result is that on these large resolutions, there is more space and on the
smaller screen, there is less space. However, Windows automatically adjusts the screen as per the screen
size of the device on which this application is viewed.

Concepts

Figure 1.10 shows an example of the snapping of apps in Windows 8. The Calendar app and the browser
window are snapped.

Figure 1.10: Windows Snapping and Resizing in Windows 8

V 1.0 Aptech Limited

Session

1
Windows Store Apps Essentials

1.2 Creating User Interfaces with XAML


The user interface is reusable. The main problems within the presentation layer of the application lies
under business logic, business services, and data. To create and use these components, the user must
understand fundamental UI concepts. The UI also provides tools for designing user interfaces in app. UIs
can make use of resources defined in XAML.

1.2.1 Accessing Resources in XAML


A resource can be accessed and used anywhere in the application. Brushes and styles are the best
instances of resources. Virtually, anything can be changed to a resource.
Solid, Gradient, or Tile brush can be created as a resource and used in the application. The user can assign
resources at object-level, document-level, dictionary-level, and application-level. The resource editors
help the user to produce a resource file with .resw extension.
The following steps show how to use the TextBlock, TextBox, and Button controls and how to write
the code to handle the Button_Click event.
1.

Create a blank application by selecting File New Project Blank App (XAML).

2.

Enter name of the project as EventHandlingDemo and click OK.

3.

Add the code shown in Code Snippet 5 to MainPage.xaml.


Code Snippet 5:
<Page
x:Class=EventHAndlingDemo.MainPage
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
xmlns:local=using: EventHAndlingDemo
xmlns:d=http://schemas.microsoft.com/expression/blend/2008
xmlns:mc=http://schemas.openxmlformats.org/
markup-compatibility/2006
mc:Ignorable=d>
<TextBlock Text=Message Height=40 Width=200 Margin=20
VerticalAlignment=Top HorizontalAlignment=Left Foreground=Blue
FontSize=30/>
<TextBox Name=MyName Height=40 Width=300 VerticalAlignment=Top
HorizontalAlignment=Left Margin=160,20/>

V 1.0 Aptech Limited

Concepts

<Grid Background=Beige>

Session

1
Windows Store Apps Essentials
<Button Content=Click Me Margin=470,20 VerticalAlignment=Top
Height=40 Width=100 Background=Green Click=Button_Click/>
</Grid>
</Page>

4.

Double-click the Button control or open MainPage.xaml.cs file and add the code shown in Code
Snippet 6 in it.
Code Snippet 6:
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
MyName.Text = Welcome To Aptech Ltd.;
}
}

Figure 1.11 shows the output of the EventHandlingDemo program.

Figure 1.11: Using TextBlock, TextBox, and Button

Concepts

1.2.2 Resource Dictionary


Resource dictionary has a collection of objects (resources) inside the dictionary, which can be developed
by the user using the programming code in C#. The ResourceDictionary has two properties, namely
FrameworkElement.Resources and Application.Resources. Generally, the user prescribes
FrameworkElement.Resources value inside the root element of the app page.
Resource dictionary can be divided into Styles, Templates, Colors, Brushes, and Transmutes. The
MergedDictionary can be used to merge many dictionaries and refers to the external file, as shown
in figure 1.12.

V 1.0 Aptech Limited

Session

1
Windows Store Apps Essentials

Figure 1.12: Dictionaries


The following example shows how to create a resource dictionary. The resource files can be accessed
through the Windows.ApplicationModel.Resources.ResourceLoader namespace.
Create a new project named DictionaryDemo.

2.

Right-click Project Add New Item as shown in figure 1.13.

Concepts

1.

Figure 1.13: Adding New Item in a Project


V 1.0 Aptech Limited

Session
3.

1
Windows Store Apps Essentials

Select Resource Dictionary option. Enter name of the dictionary as MyDictionary.xaml as shown
in figure 1.14.

Figure 1.14: Adding a Resource Dictionary Item


Double-click MyDictionary.xaml, as shown in figure 1.15.

Concepts

4.

Figure 1.15: Selecting MyDictionary.xaml to Add Resource Code

V 1.0 Aptech Limited

Session
5.

1
Windows Store Apps Essentials

Enter the code shown in Code Snippet 7 into the dictionary file, MyDictionary.xaml.
Code Snippet 7:
<ResourceDictionary xmlns=http://schemas.microsoft.com/winfx/2006/
xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml>
<SolidColorBrush x:Key=scbColor Color=#800800/>
</ResourceDictionary>

6.

Add the code shown in Code Snippet 8 to MainPage.xaml file. This is where the Resource Dictionary
will be applied.
Code Snippet 8:
<Page
x:Class=DictionaryDemo.MainPage
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
xmlns:local=using:DictionaryDemo
xmlns:d=http://schemas.microsoft.com/expression/blend/2008
xmlns:mc=http://schemas.openxmlformats.org/markupcompatibility/2006
xmlns:local=using:DictionaryDemo.DictionaryDemo_XamlTypeInfo
mc:Ignorable=d>
<Grid Background={ThemeResource ApplicationPageBackgroundThemeBrush}>
<TextBlock Text=Hello World Foreground={StaticResource scbColor}
FontSize=30 Margin=573,78,593,0 Height=50 Width=200
VerticalAlignment=Top/>
</Grid>
</Page>

Using the visual properties from the resource dictionary, the user can define styles for any controls. Code
Snippet 9 shows how to style the controls. Each control contains many properties such as background
color, foreground color, font, alignment, and so on. For customizing the controls, the template can be
created using ControlTemplate class, as shown in figure 1.16.

V 1.0 Aptech Limited

Concepts

1.2.3 Changing Appearance of XAML Controls

Session

1
Windows Store Apps Essentials

First, create a page CheckBoxDemo.xaml and add the code shown in Code Snippet 9.
Code Snippet 9:
<Page
x:Class=CheckBoxDemo.MainPage
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
xmlns:local=using:App3
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}>
<CheckBox Content=CheckBox IsThreeState=True Margin=100/>
<CheckBox Content=CheckBox IsThreeState=True Margin=200/>
<CheckBox Content=CheckBox IsThreeState=True Margin=300/>
</Grid>
</Page>

The output of Code Snippet 9 is shown in figure 1.16.

Concepts

Figure 1.16: CheckBox with Three States

1.2.4 Presenting Data in XAML


The user can bind the data using simple methods in C# to interact with the controls. For example, the
ForeColor of a TextBox can be called through SolidColorBrush to change the style of the value,
which can be change of its data. Code Snippet 10 shows how to assign the color for TextBox. The
binding source is a property of the Style class. Code Snippet 10 shows how to add the style.

V 1.0 Aptech Limited

Session

1
Windows Store Apps Essentials

Code Snippet 10:


<TextBox x:Name=MyTextBox Text=Text Foreground={Binding Brush1}/>
// Create an instance of the Style class
// that implements INotifyPropertyChanged.
MyColors textcolor = new Style ();
// Brush1 is set to be a SolidColorBrush with the value Red.
textcolor.Brush1 = new SolidColorBrush(Colors.Red);
// Set the DataContext of the TextBox MyTextBox.
txtSample.DataContext = textcolor;

1.2.5 Navigating Between Pages in a Windows Store App


When an app is created, the user must ensure that there is support for page navigation between pages.
There are some predefined templates, which are preinstalled in Visual Studio 2013 for navigation. The
following steps show how to navigate within the pages in the application.
Create a blank application named PageNavigation.

2.

Add two pages named Navigate1.xaml and Navigate2.xaml, using the option as shown in figure
1.17.

Concepts

1.

Figure 1.17: Add New Item in the Application


V 1.0 Aptech Limited

Session
3.

1
Windows Store Apps Essentials

Design the page by creating two buttons inside MainPage.xaml as shown in figure 1.18.

Figure 1.18: Adding Buttons to Main Page


4.

Add the code shown in Code Snippet 11 to MainPage.xaml file.


Code Snippet 11:
<Grid Background={ThemeResource ApplicationPageBackgroundThemeBrush}>
<Button Content=First Page HorizontalAlignment=Left
Margin=536,160,0,0 VerticalAlignment=Top Height=130 Width=261
Click=Button1_Click/>
<Button Content=Second Page HorizontalAlignment=Left
Margin=536,398,0,0 VerticalAlignment=Top Height=130 Width=261
Click=Button2_Click/>
</Grid>

5.

Add the code shown in Code Snippet 12 in MainPage.xaml.cs file.


Code Snippet 12:
private void Button1_Click (object sender, RoutedEventArgs e)

Concepts

{
this.Frame.Navigate(typeof(Navigate1), null);
}
private void Button2_Click(object sender, RoutedEventArgs e)
{
this.Frame.Navigate(typeof(Navigate2), null);
}

V 1.0 Aptech Limited

Session

1
Windows Store Apps Essentials

The output of the application is displayed as shown in figure 1.19.

Figure 1.19: Output of First Page


6.

Add the code shown in Code Snippet 13 to Navigate1.xaml file.


Code Snippet 13:
<Grid Background={ThemeResource ApplicationPageBackgroundThemeBrush}>
<Button Content=Go Back to Home HorizontalAlignment=Left
VerticalAlignment=Top Margin=644,394,0,0 Height=95 Width=190
Click=Button_Click/>
<TextBlock HorizontalAlignment=Left Margin=540,201,0,0
TextWrapping=Wrap Text=Welcome to Page 1 VerticalAlignment=Top
Height=89 Width=526 FontSize=48/>
</Grid>

7.

Add the code shown in Code Snippet 14 to Navigate1.xaml.cs file.


Code Snippet 14:
private void Button_Click (object sender, RoutedEventArgs e)
this.Frame.Navigate(typeof(MainPage), null);
}

The Navigate2.xaml page is created as shown in figure 1.20.

V 1.0 Aptech Limited

Concepts

Session

1
Windows Store Apps Essentials

Figure 1.20: Output of Second Page


8.

Add the code shown in Code Snippet 15 into page Navigate2.xaml.


Code Snippet 15:
Grid Background={ThemeResource ApplicationPageBackgroundThemeBrush}>
<Button Content=Go Back to Home HorizontalAlignment=Left
VerticalAlignment=Top Margin=644,394,0,0 Height=95 Width=190
Click=Button_Click/>
<TextBlock HorizontalAlignment=Left Margin=540,201,0,0
TextWrapping=Wrap Text=Welcome to Page 2 VerticalAlignment=Top
Height=89 Width=526 FontSize=48/>
</Grid>

9.

Add the code shown in Code Snippet 16 in Navigate1.xaml.cs file.


Code Snippet 16:
private void Button_Click(object sender, RoutedEventArgs e)
{

Concepts

this.Frame.Navigate(typeof(MainPage), null);
}

1.3 Animations and Transitions


Animations and transitions are the most essential thing for better user experience in Windows 8 apps.
Animations should be shown when there is a need for it. If there is any update or a task running in the
background, then animations are shown. The developer should develop applications to impress the app

V 1.0 Aptech Limited

Session

1
Windows Store Apps Essentials

user by providing proper animations and transitions.

1.3.1 Creating Animations and Transitions in a Windows Store App


Here, you will see how to create a simple animation. Create a blank application.
In MainPage.xaml file, write the code shown in Code Snippet 17.
Code Snippet 17:
<StackPanel>
<StackPanel.Resources>
Storyboard x:Name=EnterStoryboard>
<FadeOutThemeAnimation Storyboard.TargetName=ftaRect />
</Storyboard>
<Storyboard x:Name=ExitStoryboard>
<FadeInThemeAnimation Storyboard.TargetName= ftaRect />
</Storyboard>
</StackPanel.Resources>
<Rectangle x:Name=ftaRect PointerEntered=Rectangle_Click
PointerExited=Rectangle_Click2
Fill=Gray Width=100 Height=300 />
</StackPanel>
private void Rectangle_Click(object sender, PointerRoutedEventArgs e)
{
EnterStoryboard.Begin();
}
private void Rectangle_Click1(object sender, PointerRoutedEventArgs e)
ExitStoryboard.Begin();
}

When the page is loaded, the rectangle appears by default, as shown in figure 1.21.

V 1.0 Aptech Limited

Concepts

Session

1
Windows Store Apps Essentials

Figure 1.21: Output of Storyboard On Loading


If the user loads the same page again, the rectangle disappears.

1.3.2 Appropriate and Inappropriate Content Transitions


While creating empty container, the user can use content transitions to create new items. For example,
when the app is loaded, some part inside the app cannot be seen initially, but once the app is ready, then
the animation to load the content will be shown. The user can move the content from one part of the
container to another part using content transitions. This transition is already in-built in the container. For
example, in an email inbox, it may show the content by sliding to general page. When an animation is
displaying the content from the left side, then the new content must come from the right. Arrange each
content logically. When there is more than one container, then update them by triggering all together
with transition animation. Whenever the whole page changes, the user must not use content transition
animations, instead the user can call the Page transition animations. Use Fade animations to refresh the
content instead of refreshing the container.

1.3.3 Creating Key Frame Animations


Key frame animations are specified with the animation timeline and it is declared by using different sub
classes for each animation. If the user targets Double data type values for animation, then he/she must
have animation types such asLinear, Easing, Discrete, orSpline.
The user can set the Timeline property based on the key frame for setting the Duration such as:

Concepts

AutoReverse: When the key frame reaches the end of the animation. Then, it repeats the

frames in the reverse order.

BeginTime: The user can set the start time of the timeline for the animation inside the app.

FillBehavior: This does not have any effect. It controls what should be done when it reaches

the last key frame.

V 1.0 Aptech Limited

Session

1
Windows Store Apps Essentials

RepeatBehavior:

yy

If the user sets the property as Forever, the timeline animation will be played continuously.

yy

If the user sets the property to a certain count, the timeline animation will be played up to
the count.

yy

If the user sets the Duration, inside the timeline, then it will repeat up to the duration
specified.

SpeedRatio: It is a property, which is not used in most often. It sets the speed ratio of the

animation.

Linear Key Frame


In linear key frame animation, the animation progresses at a constant rate of the segment duration.
For example, if a key-frame segment transitions from 0 to 100 over a duration of 10 seconds, the
animation shows each key frame in the linear order with equal duration between display of the
next frame.
Code Snippet 18 shows how to create a linear key frame.
Code Snippet 18:
<StackPanel>
<StackPanel.Resources>
<Storyboard x:Name=SampleBoard>
<DoubleAnimationUsingKeyFrames
Storyboard.TargetName=myRect
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>
</StackPanel.Resources>
</StackPanel>

Discrete Key Frame


In discrete key frame animation, the animation function jumps from one value to the next without
interpolation. It sets a new value depending on the animation in the UI.

V 1.0 Aptech Limited

Concepts

</Storyboard>

Session

Windows Store Apps Essentials

Code Snippet 19 shows how to create a Discrete Key Frame.


Code Snippet 19:
<Storyboard x:Name= SampleBoard>
<DoubleAnimationUsingKeyFrames
Storyboard.TargetName=TestTransform
Storyboard.TargetProperty=X
Duration=0:0:10 EnableDependentAnimation=True>
<LinearDoubleKeyFrame Value=500 KeyTime=0:0:3 />
<DiscreteDoubleKeyFrame Value=400 KeyTime=0:0:4 />
SplineDoubleKeyFrame KeySpline=0.6,0.0 0.9,0.00 Value=0
KeyTime=0:0:6 />
</DoubleAnimationUsingKeyFrames>
</Storyboard>

Easing Key Frame


This works based on the calculation provided by the user. Easing has a set of functions, some of
which are listed as follows:
BackEase: In this type of easing function, the animation goes slightly backward before it
begins to animate in the indicated path.

yy

CircleEase: In this type of easing function, the animation moves using a circular path.

yy

BounceEase: In this type of easing function, the animation adds a bouncing effect.

yy

ElasticEase: In this type of easing function, an animation is created that is similar to a spring
oscillator back and forth until it stops.

yy

SineEase: In this type of easing function, an animation is created that moves using a sine
formula.

Concepts

yy

V 1.0 Aptech Limited

Session

1
Windows Store Apps Essentials

Code Snippet 20 shows how to create an easing key frame.


Code Snippet 20:
<StackPanel x:Name=LayoutRoot Background=White>
<StackPanel.Resources>
<Storyboard x:Name=SampleBoard>
<DoubleAnimation From=30 To=200 Duration=00:00:3
Storyboard.TargetName=myRect Storyboard.TargetProperty=(UIElement.
RenderTransform).(ScaleTransform.ScaleY)>
<DoubleAnimation.EasingFunction>
<BounceEase Bounces=2 EasingMode=EaseIn Bounciness=2 />
</DoubleAnimation.EasingFunction>
</DoubleAnimation>
</Storyboard>
</StackPanel.Resources>
<Rectangle x:Name=myRect Fill=Blue Width=200 Height=30 />
</StackPanel>

1.3.4 Functions in Animations


The various functions related to animations are as follows:

Page Transitions
The page will be animated within the view, which means it will be shown at the time of each
transition. Page Transitions have their own Application Programming Interfaces (APIs) namely,
enterPage and exitPage.

Content Transitions

Fade In/Out
The controls or UI will be animated using Fade In/Out. The Fade In/Out have their own APIs namely,
fadeIn and fadeOut.

V 1.0 Aptech Limited

Concepts

The contents in the page will be animated independently. Content Transitions have their own APIs
namely, enterContent and exitContent.

Session

1
Windows Store Apps Essentials

Crossfade
When there is a change inside content, this crossfade functionality will be called smoothly. It uses

crossfade API.

Pointer Up/Down
When the mouse is hovered over a tile, the animation is invoked. This Pointer Up/Down uses
pointerUp and pointerDown API.

Expand/Collapse
When the user hovers over the content, it will expand the sub content. Collapse animation is called
when the mouse is hovering out the content. This Expand/Collapse uses createExpandAnimation
and createCollapseAnimation API.

Reposition
To show the content to a new position, the Reposition animation function is used. The Reposition
function uses the createRepositionAnimation API.

Show/Hide Popup
To show or hide the contextual UI, the Show/Hide Popup animation is called. This uses showPopup
and hidePopup API. This is shown when the mouse is moved to the bottom of the page, inside
any app.

Show/Hide EdgeUI
To show or hide the Edge based UI, the Show/Hide EdgeUI animation is called. This uses showEdgeUI
and hideEdgeUI API.

Show/Hide Panel
To show or hide the panel, the Show/Hide Panel animation is called. This uses showPanel and
hidePanel API. This is shown when the mouse is moved to the left side of the page, inside any
app.

Concepts

1.3.5 Working with Transitions and Transformations


When the user navigates from one page to another within the app, a splash screen/some animation
is shown. This kind of animations is called Transitions. To give a fluid UI to the user, there is a built-in
Transition class in Windows 8. To show a single Transition animation inside the page, the user has to write
the code shown in Code Snippet 21.

V 1.0 Aptech Limited

Session

1
Windows Store Apps Essentials

Code Snippet 21:


<Grid Background={StaticResource ApplicationPageBackgroundBrush}>
<Grid.Resources>
<Style x:Key=btnStyle TargetType=Button>
<Setter Property=Transitions>
<Setter.Value>
<TransitionCollection>

...
...

<EntranceThemeTransition/>
</TransitionCollection>
</Setter.Value>
</Setter>
</Style>
</Grid.Resources>
<Button Style={StaticResource btnStyle}
Content=Transition Animation is applied />
</Grid>

yy

AddDeleteThemeTransition

yy

ContentThemeTransition

yy

EdgeUIThemeTransition

yy

EntranceThemeTransition

yy

PopupThemeTransition

yy

ReorderThemeTransition

yy

RepositionThemeTransition

TransitionCollection Class
This class is called when there is more than one object. The code shows how to call the

TransitionCollection class and get the objects in a list.

public sealed class trsnCol: IList<Transition>, IEnumerable<Transition>

V 1.0 Aptech Limited

Concepts

The transitions types are as follows:

Session

Windows Store Apps Essentials

The TransitionCollection class types are as follows:


yy

Border.ChildTransitions

yy

ContentControl.ContentTransitions(on content controls such asButtonor


AppBar)

yy

ContentPresenter.ContentTransitions

yy

ItemsControl.ItemContainerTransitions

asGridView,ListBox,ListView,andSelector)

(on

items

controls

yy

ItemsPresenter.FooterTransitions

yy

ItemsPresenter.HeaderTransitions

yy

ListViewBase.FooterTransitions

yy

ListViewBase.HeaderTransitions

yy

Panel.ChildrenTransitions(onGrid,StackPanel,and other panels)

yy

Popup.ChildTransitions

yy

SettingsFlyoutTemplateSettings.ContentTransitions

yy

UIElement.Transitions(on hundreds of classes)

such

Transformation
Consider an example that shows how to transfer data from one page to another.
1.

Create a blank application.

2.

Create two pages named First.xaml and Second.xaml.

In FirstPage.xaml page, write the code shown in Code Snippet 22.


Code Snippet 22:
<Page
x:Class=navigation.page1
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml

Concepts

xmlns:local=using:navigation
xmlns:d=http://schemas.microsoft.com/expression/blend/2008
xmlns:mc=http://schemas.openxmlformats.org/markupcompatibility/2006mc:Ignorable=d>
<GridBackground={StaticResourceApplicationPageBackgroundThemeBrush}>

V 1.0 Aptech Limited

Session

1
Windows Store Apps Essentials

<StackPanel>
<TextBlockName=txtSampleText=User Name FontSize=22 Margin=50
Height=50Width=150/>
</StackPanel>
<StackPanelOrientation=VerticalMargin=100>
<StackPanelOrientation=Horizontal >
<TextBlock Name=txtb_f_name Text=Please enter your Name FontSize=22/>
<TextBoxName=txtF_nameHeight=50Width=150></TextBox>
</StackPanel>
</StackPanel>
<StackPanelGrid.Row=1Margin=550>
<HyperlinkButtonx:Name= btnProceedContent=Next
PageFontSize=22Margin=110Width=500Click=btnProceed_Click/>
</StackPanel>
</Grid>
</Page>

3.

In the FirstPage.xaml.cs file, write the code shown in Code Snippet 23.
Code Snippet 23:
privatevoidbtn1_Click(objectsender,RoutedEventArgse)
{
this.Frame.Navigate(typeof(page2),txtF_name.Text);
//for navigating the second page and transfer the value of textbox from 1st
page to 2nd page.
}

4.

In Second.xaml page, write the code shown in Code Snippet 24.


Code Snippet 24:
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
xmlns:local=using:navigation

V 1.0 Aptech Limited

Concepts

<Page x:Class=navigation.page2

Session

Windows Store Apps Essentials


xmlns:d=http://schemas.microsoft.com/expression/blend/2008
xmlns:mc=http://schemas.openxmlformats.org/markupcompatibility/2006 mc:Ignorable=d>
<GridBackground={StaticResourceApplicationPageBackgroundThemeBrush}>
<StackPanelMargin=463,20,-463,-20>
<TextBlockName=lblText=SecondpageFontSize=22/>
</StackPanel>
<StackPanelOrientation=VerticalMargin=200,300,0,0>
<StackPanelOrientation=Horizontal>
<TextBlockName=txtbnameText=User NameFontSize=22></TextBlock>
<TextBoxName=txtgetnameWidth=300Height=50TextChanged=
txtgetname_TextChanged></TextBox>
</StackPanel>
</StackPanel>
<StackPanelGrid.Row=1Margin= 550,200,0,0>
<HyperlinkButtonName=btngetContent=Back to first Page FontSize=22
Click=btnget_Click></HyperlinkButton>
</StackPanel></Grid> </Page>

5.

In Second.xaml.cs file, write the code shown in Code Snippet 25.


Code Snippet 25:

Concepts

protectedoverridevoidOnNavigatedTo(NavigationEventArgse)
{
strings = e.Parameterasstring;
if(!string.IsNullOrWhiteSpace(s))
{
txtgetname.Text = s;
}
else
{
txtgetname.Text =Text cant be blank on first page ;
}
}
privatevoidbtnget_Click(objectsender,RoutedEventArgse)
{this.Frame.Navigate(typeof(First));
}

V 1.0 Aptech Limited

Session

1
Windows Store Apps Essentials

1.4 Check Your Progress


1.

2.

3.

___________ is used to get the live updates from the Internet.


(A) Live tile

(C)

Snap

(B)

(D)

Notification

Hub

The ___________ is the content page for all the apps developed in a Windows 8 application.
(A) Splash Page

(C)

Hub Page

(B)

(D)

App Page

Detail Page

Which of the following is not required tobegin developing Windows 8 apps?


(A) Windows 8 or higher
(B)

4.

A developer license registered with


Hotmail ID

(D)

Web Host

An application can produce output based on the size of the devices using the ______________.
(A) XAML

(C)

Panel System

(B)

(D)

Canvas Layout

Grid System

Solid, Gradient, or Tile brush can be created as a resource and used in the application as a
____________.
(A) Live Tile

(C)

Predefined templates

(B)

(D)

SkyDrive

Resource Dictionary

Concepts

5.

Microsoft Visual Studio Express 2012


or higher

(C)

V 1.0 Aptech Limited

Session

1
Windows Store Apps Essentials

1.4.1 Answers
A

2.

3.

4.

5.

Concepts

1.

V 1.0 Aptech Limited

Session

1
Windows Store Apps Essentials

Summary
indows Store is a Windows 8 based platform that allows for the distribution and purchase of
W
apps designed for Windows 8.

pp bars are applied to perform actions on substances, such as filtering results or navigating
A
within the app or deleting photos.

In Windows Store apps, you can use XAML to create various types of containers and controls.

ser can create a snap screen by navigating the mouse pointer to the top left of the screen and
U
dragging the thumbnail to the right.

Windows apps can run on different resolutions from a small tablet to a laptop or desktop.

By using resource dictionaries, the code in Windows Store apps can be made reusable.

ResourceDictionary has two properties, namely FrameworkElement.Resources and Application.


A
Resources to take the values.

Concepts

V 1.0 Aptech Limited

Session - 2
Windows Store UI Localization
Welcome to the Session, Windows Store UI Localization.
This session explains the process of localizing Windows Store Apps.
In this Session, you will learn to:
Define and describe Localization
Describe the process to implement localization in Store apps
Explain the process of integrating resource files in Store apps

Session

2
Windows Store UI Localization

2.1 Understanding Localization


Localization is the concept of translating the content to a specific language by means of multi-lingual
support. Visual Studio Integrated Development Environment (IDE) is built-in such a way that it can be
used to develop applications for various countries with their local language support.
In Windows Store apps, Visual Studio has introduced a new localization technique called Hub and Spoke.
The hub and spoke model is designed to provide a home screen for the app to which all other screens
will navigate in a linear manner.
Hub:
A Hub control helps you create multiple sections or multiple types of data all under one core. XAML and
C# include support for the Hub control.Unlike the ListView control which enables you to render and
display homogeneous data, the Hub control is useful for data that are of various kinds.
Spoke:
A Spoke is a set of connections arranged similar to a wheel through which traffic moves along spokes
connected to the hub at the center. Whenever a user wishes to check for information, he/she can click
the spoke. When the user wants to come back to main page again, he/she needs to select the hub. Thus,
a spoke is a central or pivotal node of information or contents.

2.1.1 .NET Localization


CultureInfo.CurrentCultureis the property that is used to set the culture of an app to current culture.
Before checking an app for localization, the developer must develop an app and change the language
through the Control Panel to test for localization.
To set the language:

Concepts

1. Open Control Panel, click Language and Region, and navigate to Language.

V 1.0 Aptech Limited

Session

2
Windows Store UI Localization

Figure 2.1 shows the different languages in the Control Panel.

Figure 2.1: Language Preference Window


For packing and deployment, the .NET Framework uses the Hub and Spoke model. The main assembly
for the app is the Hub, which holds the code to be executed. The satellite assembly is connected through
spokes and hence, coding is not required.

Concepts

Note - For each app, implementing localization creates a new assembly namely, Hub, which has the
local language specifications.

V 1.0 Aptech Limited

Session

2
Windows Store UI Localization

Figure 2.2 shows how each Spoke is connecting to the Hub.

Figure 2.2: Hub and Spoke Model

2.1.2 Localizing Your App


Generally, to globalize an application, there is no need for any code for its cultural settings, but in case of
Localization, cultural settings must have their own code and images to translate the app.

Concepts

Figure 2.3 shows an example of how localization occurs.

Figure 2.3: Localizing the Text for en-Us Culture

V 1.0 Aptech Limited

Session

2
Windows Store UI Localization

String Data
When a user develops a store app, it may contain more text than images. If the app is required to localize
the text in the app, the text must be placed inside the associated resource files. These resource files
should be created in the directory named as strings and identified through an extension .resw. Each
language must be created under its own language folder, under the respective strings folder.
Images
Localizing images is easier than localizing the text. A folder named images is created and then, all the
images are stored in this folder and the same name is given to the image files kept in the different
language folders. Figure 2.4 shows how to create the folders and the image files.

Concepts

Figure 2.4: Localizing Images for Each Currency Code


If users develop Store apps without any text or culture info, then there is no need for localizing the app.
To localize the images of the apps, the images must be placed inside the resources folder as shown in
figure 2.4. Figure 2.4 shows the currency code for each country placed under its own resource folder
namely, en, fr, and ja.
Note - When the user develops a localization app, the size of the app will increase if there are

more images.

V 1.0 Aptech Limited

Session

2
Windows Store UI Localization

Date and Time


As shown in figure 2.5, Date and Time data are available in different formats. The user should not
change the date and time manually while developing the apps.
Windows.Globalization.DateTimeFormatting.DateTimeFormatter is a date and time format

class that allows the user to customize the date and time when the user develops an app.

Figure 2.5: Date Formats in Regional Settings


Instead, make use of the Windows.Globalization.DateTimeFormatting.DateTimeFormatter
class. Whenever the user develops an app using DateTimeFormatter class, he/she has to convert it as
a string value to get the output, as shown in the following statement:

Now, use this formatter to format a date:


var sdate = shortDateformatter.Format(DateTime.Now);

The user can send these values in string format to any constructors. The user must make sure to avoid the
formats that are not available in all languages.

V 1.0 Aptech Limited

Concepts

DateTimeFormatter df = new DateTimeFormatter(shortdate);

Session

2
Windows Store UI Localization

The users can use following formats while developing their app:
yy

Shortdate

yy

Shorttime

yy

Hour

yy

Minute

yy

Second

yy

Day

yy

Month

yy

Year

yy

Dayofweek

yy

Day Month Year

Numbers and Currencies


The users can convert string to number or number to string using numbers and currency formatter
classes. The following formats can be called while developing their apps:
yy

CurrencyFormatter

yy

PermilleFormatter

yy

DecimalFormatter

yy

PercentFormatter

Code Snippet 1 explains the usage of the CurrencyFormatter class.


Code Snippet 1:
var c = Windows.System.UserProfile.GlobalizationPreferences.Currencies[0];
var cf = new Windows.Globalization.NumberFormatting.CurrencyFormatter(c);
var cn = 1;
var cfd = cf.Format(currencyNumber);

Concepts

var cp = cf.ParseDouble(cfd);

When working with the formatters, set the IsGrouped and FractionDigits properties. These
properties will decide whether to display the group separator and minimum number of fractional digits
to be displayed.

2.1.3 Localizing Your Manifest


Before sharing the app to Windows market, the user must localize the manifest which is used to view the
translated content of the app in the Windows Store.

V 1.0 Aptech Limited

Session

2
Windows Store UI Localization

Localization can be applied in different values of the manifest:


yy

Name and description

yy

Descriptions inside Declaration page

yy

Content Uniform Resource Identifier (URI)

Inside the Package.appxmanifest, languages can be set by default in Visual Studio Editor. Inside UI
default language, this language is known as fallback language for the app.
Inside the manifest file, the user must declare the ms-resource:<identifier> and refer the resource
strings. Figure 2.6 shows an example.

Figure 2.6: App Manifest Settings

The user must check the languages to be declared in the app inside the Manifest file. Windows Store lists
all the languages that can be localized. By default, the app takes the language provided in the Control
Panel. The default language can be changed by changing the languages in the manifest file.

2.2.1 Applying Language-Specific Formatting for Multilingual App


To develop a Multilingual Store app, the user must download Multilingual Toolkit which is required for
translating the app in Visual Studio that is used to localize app translations.

V 1.0 Aptech Limited

Concepts

2.2 Language Definition in Windows Store Apps

Session

2
Windows Store UI Localization

After installing the Toolkit, the following steps must be performed for enabling Multilingual Toolkit.
1.

Launch Visual Studio 2013.

2.

Enable Multilingual option by navigating to Tools Enable Multilingual App Toolkit option as shown
in figure 2.7. This creates the resource files languages required and also for a pseudo language. The
pseudo language is needed for testing Store apps to ensure that text is used from inside the resource
files.

Figure 2.7: Enabling Multilingual App Toolkit


3.

Now, select Add translation languages from the Project menu to add multiple languages. This is
shown in figure 2.8.

Figure 2.8: Adding Multiple Languages


Then, select the required languages from the Translation Languages dialog box and click OK.

Concepts

4.

V 1.0 Aptech Limited

Session

2
Windows Store UI Localization

Figure 2.9 shows how to select a language.

Figure 2.9: Selecting the Required Languages

2.2.2 Implementing .resw Files to Translate Text

Concepts

The user can create a multi-lingual app by creating a resource file which has an extension .resw and
integrate that into the app. These files can be called through a simple reference in the code. The resource
file design is shown in figure 2.10.

Figure 2.10: Creating Resource File (.resw)

V 1.0 Aptech Limited

Session

2
Windows Store UI Localization

After creating the resource file, write the code as shown in Code Snippet 2.
Code Snippet 2 demonstrates the use of multi-language support for Store apps. In the code, a ComboBox
control is created with three different languages. On appropriate language selection, a message from
respective resource files will be shown as output on the button Click event.
Code Snippet 2:
MainPage.xaml
<Page
x:Class=LanguageLocalization.MainPage
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
xmlns:local=using:LanguageLocalization
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}>
<ComboBox Margin=538,155,0,0 SelectedIndex=0 SelectedValuePath=Name
x:Name=ddlLang Grid.Column=0 HorizontalAlignment=Left
VerticalAlignment=Top Width=106 Height=34 >
<ComboBoxItem x:Name=en Content=English/>
<ComboBoxItem x:Name=fr Content=France/>
</ComboBox>
<TextBlock x:Name=lblResult HorizontalAlignment=Left
TextWrapping=Wrap VerticalAlignment=Top Margin=538,275,0,0 Height=66
Width=407 FontSize=20/>
<Button x:Name=btnTranslate Content=Get Value
HorizontalAlignment=Left VerticalAlignment=Top Margin=763,154,0,0
Click=btnTranslate_Click/>

Concepts

</Grid>
</Page>

In code-behind file, in the button Click event handler, appropriate resources are loaded for which
language resources are created and stored as a string value and displayed on a label as per the selection
made by the user.

V 1.0 Aptech Limited

Session

Windows Store UI Localization

This is shown in Code Snippet 3.


Code Snippet 3:
MainPage.xaml.cs
private void btnTranslate_Click(object sender, RoutedEventArgs e)
{
Button b = sender as Button;
if (b != null)
{
var context = new ResourceContext();
var lang = ddlLang.SelectedValue;
if (lang != null)
{
var strlang = new List<string>();
strlang.Add(strlang.ToString());
context.Languages = strlang;
var rstring = ResourceManager.Current.MainResourceMap.
GetSubtree(Resources);
this.lblResult.Text = rstring.GetValue(UserDefined, context).
ValueAsString;
}
}
}

Concepts

When the application is executed, the output will appear as shown in figure 2.11.

V 1.0 Aptech Limited

Session

2
Windows Store UI Localization

Figure 2.11: Output


When the user clicks the Get Value button, it reads the resource file and displays the result as shown in
figure 2.12.

Figure 2.12: The Value Received from the Resource File (.resw)

Concepts

2.2.3 Implement Collation and Grouping


The user can make use of CharacterGroupings class which is available inside the namespace
Windows.Globalization.Collation for ordering the group or collation of a language.

V 1.0 Aptech Limited

Session

2
Windows Store UI Localization

Code Snippet 4 can be used for collation and grouping.


Code Snippet 4:
using System;
using Windows.Foundation.Metadata;
namespace Windows.Globalization.Collation
{

[DualApiPartition(version = 100794368u),
MarshalingBehavior(MarshalingType.Agile), Version(100794368u)]

public sealed class CharacterGrouping : ICharacterGrouping

public extern string string1

{
get;
}

public extern string string2

{
get;

}
}
var cgs = new Windows.Globalization.Collation.CharacterGroupings();
var size = cgs.Count;
if (size > 0)
{
cg. var cgs = cgs[0];
var string2 = cg.string2;
}

When en-US is used for localization, the user receives special char groupings such as &, ;, , or 0-9 and all
alphabets.
Note - The user can employ the method Lookup to receive the string of a label.

V 1.0 Aptech Limited

Concepts

var string1 = cg.string1;

Session

2
Windows Store UI Localization

2.2.4 Implement Culture-Specific Formatting for Date and Time


Through the DateTime type, Windows Store apps can be made culture-sensitive. Based on the culture,
the DateTimeFormatInfo class is called to format the Date.
When the user needs to format a date through ShortDatePattern format, the date March 1, 2014 can
be formatted as 3/1/2014 for the English (United States) en-US culture, and 01/03/2014 for the English
(United Kingdom) en-GB culture. The object for DateTimeFormatInfo can be formed for a specific
culture.
Code Snippet 5 shows todays date by calling the ShortDatePattern as the CurrentThread culture
is set to English and German.
Note - The object for DateTimeFormatInfo cannot be created in Neutral.

In Code Snippet 5, a date object is created which shows current system date.
Code Snippet 5:
using System;
using System.Globalization;
using System.Threading;
public class GetDateFormat
{
public static void Main()
{
DateTime d = DateTime.Now;
Thread.CurrentThread.CurrentCulture = new CultureInfo(en-US);
Console.WriteLine(d.ToString(d));
CultureInfo c = new CultureInfo(de-DE);
Console.WriteLine(d.ToString(d, c));
}

Concepts

V 1.0 Aptech Limited

Session

2
Windows Store UI Localization

2.3 Check Your Progress


1.

2.

3.

(A) Localization

(C)

Polymorphism

(B)

(D)

Conversion

Globalization

Before sharing the app to Windows market, the user must localize the manifest which is used to view
the translated content of the app in the _________.
(A) Localization

(C)

Month

(B)

(D)

Windows Server

Windows Store

The user must check the languages to be declared in the app inside the ________.
(A) Date file

(C)

Windows config file

(B)

(D)

Package

Manifest file

The user can create a multi-lingual app by creating a resource file, which has an extension _______
and integrate that into the app.
(A) .resw

(C)

.js

(B)

(D)

.cshtml

.abc

Concepts

4.

____________ is the concept of translating the content to a specific language by means of


multi-lingual support.

V 1.0 Aptech Limited

Session

2
Windows Store UI Localization

2.3.1 Answers
A

2.

3.

4.

Concepts

1.

V 1.0 Aptech Limited

Session

2
Windows Store UI Localization

Summary
Localization is the concept of translating the content to a specific language by means of
multi-lingual support.

Generally, there is no need of writing lines of code for globalizing an app for its cultural settings,
but in case of localization, its cultural settings must have its own code and images to translate the
app.

The user must check the languages to be declared in the app inside the Manifest file. Windows
Store will list all the languages that can be localized.

The user can create a multilingual app by creating a resource file which has an extension .resw
and integrate that into the app.

In the DateTime type, use the Store app to make culture-sensitive procedures. Based on the
culture, the DateTimeFormatInfo class is called to format the date.

Concepts

V 1.0 Aptech Limited

Session - 3
Adding Splash Screens
and Branding to Apps
Welcome to the Session, Adding Splash Screens and Branding to Apps.
This session introduces the concept of splash screens and describes how to create
splash screens. The session also describes the branding process for Windows Store
apps.
In this Session, you will learn to:
Define splash screens
Describe how to create customized splash screens
Explain branding of Windows Store App

Session

33

Adding Splash Screens and Branding to Apps

3.1 Splash Screens


Splash screen is the screen that is loaded when any application is launched. When users develop any
Store app, they need to create their own splash screen, which may have an image or a background color.
Using various properties, users can change the style or design of the splash screen.
Each app, regardless of whether it is a user-defined app or a built-in Windows app, displays a splash
screen upon loading. This splash screen will be closed automatically after the app is ready to load. Figure
3.1 shows the splash screen when the built-in Calendar app is loaded. By default, a splash screen created
in the app is neither gradient nor animated.

Figure 3.1: Splash Screen for Calendar

Figure 3.2: Default Splash Screen of an App

V 1.0 Aptech Limited

Concepts

Placing images or setting a background color for a splash screen in your apps makes the splash screen
visually attractive. The image will be resized in the app based on the resolution of the current system. If
you do not customize the splash screen, then a default splash screen will be loaded as shown in figure
3.2.

Session

3.1.1

Adding Splash Screens and Branding to Apps

Changing and Presenting the Default Splash Screen

While using Visual Studio 2013 template, a default image is generated for a splash screen. By default, the
background color will be grey. This can be changed using the properties of the Package.appxmanifest
file. The step-by-step procedure to change the default splash screen is outlined as follows:
1.

Create a blank application as shown in figure 3.3.

Figure 3.3: Creating a New Blank Application


Select Show All Files in the top section of the Solution Explorer, as shown in figure 3.4.

Concepts

2.

V 1.0 Aptech Limited

Session

33

Adding Splash Screens and Branding to Apps

Figure 3.4: Selecting Show All Files


Select Package.appxmanifest, select Splash Screen, and set the background color to Green as
shown in figure 3.5.

Concepts

3.

Figure 3.5: Selecting Package.appxmanifest

V 1.0 Aptech Limited

Session
4.

3
Adding Splash Screens and Branding to Apps

Build and execute the app. The output of the Splash Screen will be as shown in figure 3.6.

Figure 3.6: Output of the Splash Screen

3.1.2

Customizing Splash Screen

The splash screen will run for a short time, if the contents of an app take shorter time to load. In such a
case, no animation is required. However, if the user develops an app with database connectivity, network
connections, or using Web services, the splash screen will run for a longer duration or may take longer
waiting time for the app to load fully. This can result in a frustrating experience for end-users because it
takes longer time to load. The end-user may close such an app assuming that it is not launching properly.
To avoid or overcome such a problem, one can use extended splash screens. Extended Splash Screen is
a feature that allows you to enhance the UI with a short animation on the splash screen. This animation
can include some images, text, or any other content. Another reason for using extended splash screens
is as follows:

Concepts

Nowadays, Windows 8.1 apps fail to load and show a message Current app fails to load. Try again later.
This is mostly true while loading apps that targets ARM processors. These machines are faster in speed
and are good for running animated apps. These ARM targeted apps fail to load if they do not meet the
minimum system requirements. Figure 3.7 shows the lifecycle for an app.

V 1.0 Aptech Limited

Session

33

Adding Splash Screens and Branding to Apps

Figure 3.7: App Lifecycle


This problem can be solved by creating an extended splash screen.
The loading time for the splash screen is more, hence, it is called as extended splash screen.
As Windows 8 apps need to load data or other content at startup, it is recommended to add an extended
splash screen page. When users create a splash screen for the app, the screen will not be centered all the
time. This leads the extended splash screen to adjust the image position and size of the image to a static
size. When the app is clicked from the tile, it takes its own loading time depending on the performance
of the hardware configuration of the system. The apps will be in the state of activation or launched.
Activation means that the app is already opened and it is in a running state. Therefore, this will not load
the splash screen as the app is already running.

Concepts

When the user develops an app with a basic splash screen, the output will be as shown in figure 3.8.

V 1.0 Aptech Limited

Session

3
Adding Splash Screens and Branding to Apps

Figure 3.8: Output of a Basic Splash Screen


Generally, an extended splash screen can be added to an app easily with a small line of code. The code
shown in Code Snippet 1 demonstrates with a complete example how to develop the extended splash
screen.
Code Snippet 1:
SplshWindow.xaml
<UserControl
x:Class=SplashScreenApp.Controls.SplshWindow
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
xmlns:local=using:SplashScreenApp.Controls
xmlns:d=http://schemas.microsoft.com/expression/blend/2008
xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006
xmlns:h=using:SplashScreenApp.Helpers
mc:Ignorable=d d:DesignHeight=768 d:DesignWidth=1366>

Concepts

<Grid x:Name=LayoutRoot Background=#999>


<VisualStateManager.VisualStateGroups>
<VisualStateGroup>
<VisualState x:Name=Extended>
<Storyboard>
<DoubleAnimationUsingKeyFrames EnableDependentAnimation=True

V 1.0 Aptech Limited

Session

33

Adding Splash Screens and Branding to Apps

Storyboard.TargetProperty=(FrameworkElement.Width)
Storyboard.TargetName=rectangle>
<EasingDoubleKeyFrame KeyTime=0:0:1.3 Value=1900>
<EasingDoubleKeyFrame.EasingFunction>
<CircleEase EasingMode=EaseInOut/>
</EasingDoubleKeyFrame.EasingFunction>
</EasingDoubleKeyFrame>
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames EnableDependentAnimation=True
Storyboard.TargetProperty=(FrameworkElement.Width)
Storyboard.TargetName=rectangle1>
<EasingDoubleKeyFrame KeyTime=0:0:1.5 Value=1900>
<EasingDoubleKeyFrame.EasingFunction>
<CircleEase EasingMode=EaseInOut/>
</EasingDoubleKeyFrame.EasingFunction>
</EasingDoubleKeyFrame>
</DoubleAnimationUsingKeyFrames>
<DoubleAnimation Duration=0:0:1.0 To=0.2
Storyboard.TargetProperty=(UIElement.Opacity)
Storyboard.TargetName=tileCanvas d:IsOptimized=True/>
<DoubleAnimation Duration=0:0:1.4 To=-150
Storyboard.TargetProperty=(UIElement.RenderTransform).(CompositeTransform.
TranslateX)
Storyboard.TargetName=textBlock d:IsOptimized=True>
<DoubleAnimation.EasingFunction>
<CircleEase EasingMode=EaseInOut/>
</DoubleAnimation>
<DoubleAnimation Duration=0:0:1.6 To=-100 Storyboard.
TargetProperty=(UIElement.RenderTransform).(CompositeTransform.
TranslateX) Storyboard.TargetName=textBlock1 d:IsOptimized=True>

V 1.0 Aptech Limited

Concepts

</DoubleAnimation.EasingFunction>

Session

3
Adding Splash Screens and Branding to Apps
<DoubleAnimation.EasingFunction>

<CircleEase EasingMode=EaseInOut/>
</DoubleAnimation.EasingFunction>
</DoubleAnimation>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<h:TileCanvas x:Name=tileCanvas
Images/BackgroundPattern.png

Grid.RowSpan=2

ImageSource=/Assets/

Opacity=0 />
<Grid Grid.RowSpan=2>
<Grid.Clip>
<RectangleGeometry Rect=0,0,2000,1080>
<RectangleGeometry.Transform>
<RotateTransform Angle=-45 />
</RectangleGeometry.Transform>
</RectangleGeometry>
</Grid.Clip>
<StackPanel VerticalAlignment=Center>
<TextBlock
x:Name=textBlock
Text=Splash
Style={StaticResource
PageHeaderTextStyle} HorizontalAlignment=Center VerticalAlignment=Center
erTransformOrigin=0.5,0.5>
<TextBlock.RenderTransform>
<CompositeTransform TranslateX=400 TranslateY=-100/>
</TextBlock.RenderTransform>

Concepts

</TextBlock>
<TextBlock
x:Name=textBlock1
Text=Loading
Style={StaticResource
SubheaderTextStyle} HorizontalAlignment=Center VerticalAlignment=Center
RenderTransformOrigin=0.5,0.5>
<TextBlock.RenderTransform>
<CompositeTransform TranslateX=500 TranslateY=-125/>
</TextBlock.RenderTransform>

V 1.0 Aptech Limited

Session

33

Adding Splash Screens and Branding to Apps

</TextBlock>
</StackPanel>
</Grid>
<Grid Grid.RowSpan=2 RenderTransformOrigin=0.5,0.5>
<Grid.RenderTransform>
<RotateTransform Angle=-45 />
</Grid.RenderTransform>
<StackPanel HorizontalAlignment=Center VerticalAlignment=Center>
<Rectangle
x:Name=rectangle
Margin=0,0,0,8 />

Fill=#FFFFFF

Height=22

Width=130

<Rectangle x:Name=rectangle1 Fill=#FFFFFF Height=22 Width=130 />


</StackPanel>
</Grid>
<Canvas Grid.Row=0>
<Image x:Name=SplshWindowImage Source=/Assets/SplashScreen.png />
</Canvas>
<ProgressBar
IsIndeterminate=True
RenderTransformOrigin=0.5,0.5>

VerticalAlignment=Center

<ProgressBar.RenderTransform>
<CompositeTransform Rotation=-45 TranslateX=50 />
</ProgressBar.RenderTransform>
</ProgressBar>
</Grid>
</UserControl>

Concepts

Note - The user need to ensure that the extended splash screen has the same background color as in
the splash screen.

V 1.0 Aptech Limited

Session

3
Adding Splash Screens and Branding to Apps

After writing the XAML markup, you write the code to execute the splash screen as shown in Code Snippet
2.
Code Snippet 2:
SplashWindow.xaml.cs
public SplshWindow() {
InitializeComponent();
Window.Current.SizeChanged += new
WindowSizeChangedEventHandler(SplshWindow_OnResize);
splash = App.SplashScreen;
if (splash != null)
{
splash.Dismissed += new TypedEventHandler<SplashScreen,
Object>(DismissedEventHandler);
splashImageRect = splash.ImageLocation;
PositionImage();
}
RestoreStateAsync(App.LoadState);
VisualStateManager.GoToState(this, Extended, true);
}
async void RestoreStateAsync(bool loadState)

if (loadState)
await SuspensionManager.RestoreAsync();
await SimulateLoadingData();
if (sd != null)
sd();
}

Concepts

private async Task SimulateLoadingData()


{
await Task.Delay(5000);
}
void PositionImage()
{

V 1.0 Aptech Limited

Session

33

Adding Splash Screens and Branding to Apps

eSI.SetValue(Canvas.LeftProperty, sr.X);
eSI.SetValue(Canvas.TopProperty, sr.Y);
eSI.Height = sr.Height;
eSI.Width = sr.Width;
}
void SplshWindow_OnResize(Object sender, WindowSizeChangedEventArgs e)
{
if (splash != null)
{
// Update the coordinates of the splash screen image.
sr = splash.ImageLocation;
PositionImage();
}
}
void DismissedEventHandler(SplashScreen sender, object e)
{
dismissed = true;
}

Concepts

Figure 3.9 shows the output of the extended splash screen.

Figure 3.9: Output of the Extended Splash Screen


V 1.0 Aptech Limited

Session

3
Adding Splash Screens and Branding to Apps

Code Snippets 3 and 4 contain code to create a splash screen to be added from user selection through
markup.
First, create a new blank XAML project in Visual Studio 2013 with the name Extended_splash_screen.
In MainPage.xaml, add the code given in Code Snippet 3.
Code Snippet 3:
<Grid Background=Brown>
<Image x:Name=extendedSplashImage Source=Assets/ChessSet.jpg
Height=400 Width=600 VerticalAlignment=Center />
<ProgressRing x:Name=ProgressRing Foreground=White
IsActive=True MaxHeight=50 MinHeight=50 MaxWidth=80 MinWidth=30
Margin=580,550,630,238 Width=78 Height=74></ProgressRing>
<Button Content=welcome HorizontalAlignment=Left Margin=690,122,0,0
VerticalAlignment=Top/>
</Grid>

In the MainPage.xaml.cs page, add the code given in Code Snippet 4.


Code Snippet 4:
public MainPage(SplashScreen splash)
{
InitializeComponent();
this.InitializeComponent();
this.extendedSplashImage.SetValue(Canvas.LeftProperty,
ImageLocation.X);

splash.

this.extendedSplashImage.SetValue(Canvas.TopProperty,
ImageLocation.Y);

splash.

this.extendedSplashImage.Height = splash.ImageLocation.Height;
this.extendedSplashImage.Width = splash.ImageLocation.Width;

Concepts

this.ProgressRing.SetValue(Canvas.TopProperty,
splash.ImageLocation.Height + 32);

splash.ImageLocation.Y

this.ProgressRing.SetValue(Canvas.LeftProperty, splash.ImageLocation.X +
(splash.ImageLocation.Width / 2) - 15);
}
internal void onSplashScreenDismissed(Windows.ApplicationModel.Activation.
SplashScreen sender, object e)
{

V 1.0 Aptech Limited

Session

33

Adding Splash Screens and Branding to Apps

// The splash screen has been dismissed and the extended splash screen
is now in view.
}

Under the OnLaunched function of App.xaml, define the code given in Code Snippet 5.
Code Snippet 5:
if (args.PreviousExecutionState == ApplicationExecutionState.Running)
{
Window.Current.Activate();
return;
}
SplashScreen splashScreen = args.SplashScreen;
MainPage eSplash = new MainPage(splashScreen);
// Register an event handler to be executed when the splash screen
has been dismissed.
splashScreen.Dismissed += new TypedEventHandler<SplashScreen,
object>(eSplash.onSplashScreenDismissed);
Window.Current.Content = eSplash;
Window.Current.Activate();

Figure 3.10: Output of Custom Extended Splash Screen

V 1.0 Aptech Limited

Concepts

The output of the code is shown in figure 3.10.

Session

3.1.3

Adding Splash Screens and Branding to Apps

Differentiating Windows Store Apps with Branding

There are many design principles for a better experience while the user sets the design in their store app.
The design must impress and attract the user to the store app. It should be catchy and it should heighten
the interest of the user in acquiring such an app. This is essentially important to make the app stand out
in the market. Branding creates this impact and impression on the minds of the user. Branding can be
incorporated easily in the Windows Store app. The developers must have their own branding contents
such as Logos, Images, Taglines, Captions, Themes, and Styles, and so on. The app must be designed in
such a way that it should create an ever-lasting impact on the mind of the user. It should make it possible
for the user to be able to differentiate the current app from all other apps in the market. This is the main
purpose of branding in Store apps.
Visual Elements of the Brand:
The users must follow the guidelines for each app they develop. The users also have to look out for
unique color, resolutions, images, and image sizes for creating the Store app.
Standard guidelines for dimensions of images and logos for Store apps are listed in table 3.1.
Image/Logo
Size
Store logo
150x150 Logo
30x30 Logo
310x150 Logo

310x310 Logo

70x70 Logo

Badge logo

Concepts

Splash screen

80%

100%

N/A
50x50
120x120 150x150

140%

180%

70x70
210x210

90x90
270x270

Defined in Following Components

Package/Properties/Logo
Package/Applications/ Application/
VisualElements /@150x150Logo
24x24
30x30
42x42
54x54
Package/Applications/Application/
VisualElements/@30x30Logo
248x120 310x150 434x210
558x270
Package/Applications/
Application/ VisualElements/
DefaultTile/@310x150Logo
248x248 310x310 434x434
558x558
Package/Applications/
Application/ VisualElements/
DefaultTile/@310x310Logo
56x56
70x70
98x98
126x126
Package/Applications/
Application/ VisualElements/
DefaultTile/@70x70Logo
N/A
24x24
33x33
43x43
Package/Applications/Application/
VisualElements/LockScreen
N/A
620x300 868x420
1116x540 Package/Applications/Application/
VisualElements/SplashScreen
Table 3.1: Guidelines for App Developers

3.2 Branding
To ensure the quality of the users app, branding is essential. The user must look out in the app in such
a way that proper description, images, contents, and other information needs to be in the right position

V 1.0 Aptech Limited

Session

33

Adding Splash Screens and Branding to Apps

as they develop an app.

3.2.1

Branding the App UI

Based on the guidelines and coding procedure, the user has to develop the app which will look natural
while compared to other apps. An example is shown in figure 3.11.

Figure 3.11: Example for App Design


Some of the guidelines are as follows:
1.

App Setup
The user must plan the app before development. The process regarding how to target the customers,
why the app is being created for, and how to make it unique from other apps are the things to plan
before development.
Positioning App UI
Whenever the app is created, the user must look out for all the items placed in the app. The user
must follow these considerations before start developing the app:
yy

While placing the elements inside the canvas check for:

yy

Gallery description

Grouping controls: This helps to find the controls easily

Navigation must be present at the top of the app, which makes the app to navigate to

V 1.0 Aptech Limited

Concepts

2.

Session

3
Adding Splash Screens and Branding to Apps
another page effortlessly.

yy

ierarchical Navigation can be created from the section pages which are holding the control
H
list in the section page.

yy

I n the same way each section page has a Back Button to navigate back to the previous
section page.
A detail page will contain:

3.

Control description

Detail page navigation from the gallery or through section page

Control and Code snippets

Adding Controls

The users must have hands-on experience in the design and development concepts and how to handle
the controls they add in their app. This understanding and knowledge leads the user to create any app
with enhanced layout and will be a better competitor for other apps.
Layout
The user will have to take more time while designing the layout by implementing the creativity for the
app page. The app must be designed in such a way that it can be resized to any resolution, or change the
orientation. Layout is used for this purpose.

3.2.2

Branding a Windows Store App

Further, the user must look out for the following:

Colors
The user must look out for the color coding while developing the app. Color is the main attribute
for any application. These color coding must impress the user to use the app regularly. User must
select the unique color in all the section pages as per the brand or logo.

Icons

Concepts

Icons must contain the short logo image of the brand with which it can be easily identified in the
store market. These icons are used mainly for navigating to pages on a single touch.

Images
Images used in the app must be natural and unique and should have a neat design. The app must
have various images with different sizes/resolutions so that it will not affect the app while resizing.

Grid
These are used to separate the canvas layout in various sizes and placed in different positions.

V 1.0 Aptech Limited

Session

33

Adding Splash Screens and Branding to Apps

Typography
Typography is another most important attribute of an app. The user must check the font-size, fontfamily, width, and height of each grid so that they will not look different at anytime.

3.2.3

Apply Branding to a Windows Store App

Branding can be applied through any app from the Package.appxmanifest file. Figure 3.12 shows the
Application Settings tab. This tab will have the basic settings of an app.

Figure 3.12: Application Layout Settings

Concepts

Figure 3.13 shows the application of Visual Asset Settings tab. This tab will have the image assets of an
app.

V 1.0 Aptech Limited

Session

3
Adding Splash Screens and Branding to Apps

Concepts

Figure 3.13: Application of Visual Asset Settings

V 1.0 Aptech Limited

Session

33

Adding Splash Screens and Branding to Apps

3.3 Check Your Progress


1.

Based on the _____________, the image will be resized in the app.


(A)
(B)

2.

Visual Studio 2013


Blank application

(C) Visual elements


(D) Database connectivity

Visual elements
Web services

(C)
(D)

Store app
Template

The user must follow the ___________ for each app they develop.
(A)
(B)

5.

Type of app
Performance

I f the user makes an app with a database connectivity or using _________, the splash screen will
run for a long term waiting for the app to load fully.
(A)
(B)

4.

(C)
(D)

A default image is generated for splash screen while using ____________ template.
(A)
(B)

3.

Pixels
Size

Template
Elements

(C) Guidelines
(D) Process

Splash screen issues can overcome by developing the app with an __________________.
Database
Network

(C) Extended splash screen


(D) Web access

Concepts

(A)
(B)

V 1.0 Aptech Limited

Session

3
Adding Splash Screens and Branding to Apps

3.3.1 Answers
A

2.

3.

4.

5.

Concepts

1.

V 1.0 Aptech Limited

Session

33

Adding Splash Screens and Branding to Apps

Summary
When users develop any Store app, it will be loaded with its default splash screen.

Users can create their own splash screen, which may have an image or a background color.

When Visual Studio 2013 template is used, a default grey image is generated for splash screen.

T he users must also look out for the unique color coding, resolutions, and images for creating the
Store app.

A splash screen will run for a short time, if the contents of an app are less.

hen an app is clicked, it takes its own loading time depending on the performance of the
W
hardware of the system.

Concepts

V 1.0 Aptech Limited

Session - 4
Storage Mechanisms
Welcome to the Session, Storage Mechanisms.
This session covers various storage options and mechanisms for Windows Store
Apps. The session also explains data caching and file manipulation.
In this Session, you will learn to:
Describe various storage options for Windows Store Apps
Explain Data Caching
Describe working with files in apps

Session

4
Storage Mechanisms

4.1 Storage Mechanisms


Windows 8 supports storage mechanisms to store data both in local system and on the server. The
Windows.Storage namespace is used to store and retrieve data to and from Windows Store apps.
Note - Windows 8 also offers storage of data in the Cloud through products such as Azure and
SkyDrive.

4.1.1 Storage Options in Windows Store App


After an app is loaded in the device app store, the data is stored inside the system or in the cloud. Using
APIs in the app will make it easier to develop and faster to execute, since the code will be shorter and
concise.
Data stored from an app through one of the following data stores:

Local
Local storage is used for storing on the current system.

Roaming
Roaming is used to access the app data that is present in all devices where the user has installed
the app.

Temporary
Temporary storage is like roaming storage, which can be removed from the device at any time.

Note - For all the types, the data is removed at any time when the app is uninstalled or updated to

its latest version.

4.1.2 Windows Store App Storage Considerations


In any Windows Store app, file manipulation is important. The app should support reading and accessing
files from any location or from a device.

Concepts

Planning for Data Storage


Before creating the project, a Windows Store app developer must take care of planning a suitable data
store and storage options. This is because changing the data store midway during the project can lead to
a lot of rework, resulting in project delays.
The developer can choose one of the following options:

Local: By default, the local data can be accessed or stored from or on the device or from the local
database. However, Windows Store apps have an in-built feature named File Picker and also
support contracts, hence using one of these two approaches, a developer can even use local data
from other apps.

V 1.0 Aptech Limited

Session

4
Storage Mechanisms

Remote: As the name indicates, remote storage is used to save the file or data remotely. It is
mainly used to store the data on the cloud (such as on Azure or on SkyDrive). Remote storage can
also be used to access the public APIs for social networking sites such as Flickr. The developer can
store the data inside the device or on the remote location depending on the size of the file. The
reason being, the mobile devices will have low space and hence, cannot store large data so they
are stored remotely onto both devices at times.

Some of the approaches for storing data are as follows:

IndexedDB
IndexedDB is available with HTML5 and stores local data in a structured format. IndexedDB can be
used in browsers and also inside store apps. IndexedDB can store large data from apps or browsers
in a database as Binary Large Objects (BLOBs). Blob format is mainly used in apps to store media
files which are large in file size. Figure 4.1 depicts a representation of IndexedDB.

Figure 4.1: Accessing Images or Videos from IndexedDB


Note - IndexedDB is an object database and hence they do not require any SQL queries. Thus, the

user must develop the app as object oriented.


yy

Open a database.

yy

Create an object store in the database.

yy

Start a transaction and make a request to do some database operation, such as adding,
updating, or retrieving data.

yy

Wait for the operation to complete by listening to the right kind of DOMevent.

yy

Perform necessary operations with the results.

The code in Code Snippet 1 explains the process of creating and using IndexedDB database.

V 1.0 Aptech Limited

Concepts

The basic steps that are recommended for using IndexedDB are as follows:

Session

4
Storage Mechanisms

Code Snippet 1:
//Create object ds that holds name of the IndexDB
var ds = MyData;
//Create a Transaction Object
var t = db.transaction(ds, IDBTransaction.READ_ONLY);
//Retrieve the Object Store and store it in variable s
var s = t.objectStore(ds);
t.oncomplete = function(evt)
{
// successful DB transaction
};
//Variable r holds an pointer to Open Cursor
var r = store.openCursor();
r.onsuccess = function(evt)
{
var c = evt.openCursor();
};
r.onerror = function(error)
{
// handling errors
};

Files as Data and the File API


Instead of storing data in the database, the user can develop an API to access the file from the cloud
or from the local devices. Primarily, pictures can be stored in a cloud and can be accessed using a
file picker. The file picker will interact with the app and the file for storing and retrieving. This file
picker interacts remotely or to local directories such as documents, pictures, or music folder.

Concepts

Code Snippet 2 shows the usage of the File Picker.

V 1.0 Aptech Limited

Session

4
Storage Mechanisms

Code Snippet 2:
fileOpen: function ()
{
var o = new Windows.Storage.Pickers.FileOpenPicker();
openPicker.viewMode= Windows.Storage.Pickers.PickerViewMode.thumbnail;
openPicker.suggestedStartLocation =
Windows.Storage.Pickers.PickerLocationId.picturesLibrary;
o.fileTypeFilter.replaceAll([.png, .jpg, .jpeg]);
o.pickSingleFileAsync().done(function (file) {
// ...
});}

Web Storage
Web storage is one of the best methods to store the data because it does not require database or
any local disk space. Web Storage has two types:
yy

localStorage: Stores the temporary data in the device and clears the data when the app is
closed.

yy

sessionStorage: Maintains the session state of the app.

Code Snippet 3 demonstrates the use of local storage.


Code Snippet 3:
sessionStorage.lastPage = 2;
WinJS.r({ url: data/data.json }).then(function (r)
{
localStorage.data = r.responseText;
};

Web Services
Web services are generally developed by users to access data from multiple devices at the same
time through the Web. Web services are piped through HyperText Transfer Protocol (HTTP) to
transfer XML data, as shown in figure 4.2.

V 1.0 Aptech Limited

Concepts

Session

4
Storage Mechanisms

Figure 4.2: Web Service Request and Response


Code Snippet 4 demonstrates an example.
Code Snippet 4:
WinJS.x({ url: data.json }).then(function (x)
{
var i = JSON.parse(x.responseText);
i.forEach(function (i) {
list.push(i);
})
});
Note - The user must use the HttpWebRequest and HttpWebResponse classes to get the data from

a service.

Concepts

SkyDrive and Azure


Users also have an option to store data over the cloud using SkyDrive. SkyDrive offers users 7 GB of
data storage so that the data can be stored without any need for a database, as shown in figure 4.3.

V 1.0 Aptech Limited

Session

4
Storage Mechanisms

Figure 4.3: Data Access from SkyDrive or Cloud through API


Note - Microsoft provide the Microsoft.Live namespace to get data from SkyDrive through APIs.

Windows Azure Mobile Services is another powerful option to build apps that are cross-platform
and multi-platform. It offers a variety of powerful and useful features. The SDK for Windows Azure
Mobile Services is integrated with Windows Store.
Code Snippet 5 demonstrates how to perform a query using Windows Azure Mobile Services SDK.
Code Snippet 5:
var q = t.orderBy(columnname).read({ success: function(res)
{ ... }});

Application Data Management and Storage Options


The ApplicationData class which is under the Windows.Storage namespace has settings to
store data as shown in Code Snippet 6.
Code Snippet 6:
var ls = Windows.Storage.ApplicationData.current.localSettings;
var rs = Windows.Storage.ApplicationData.current.roamingSettings;

4.2 File Manipulation


The file manipulation includes the Create, Update, Retrieve, and Delete (CRUD) operations. Users can
store the file locally or remotely.

V 1.0 Aptech Limited

Concepts

The data with larger size can be stored inside the cloud using the code.

Session

4
Storage Mechanisms

Code Snippet 7 shows how to read data locally.


Code Snippet 7:
StorageFolder l =
Windows.Storage.ApplicationData.Current.LocalFolder;
<Image Source=ms-appdata:///local/pic.png/>

Code Snippet 8 shows how to read data remotely.


Code Snippet 8:
StorageFolder r =
Windows.Storage.ApplicationData.Current.RoamingFolder;
<Image Source=ms-appdata:///roaming/pic.png/>

4.3 Implementing Data Caching


The user must cache the data in order to make the app consume less Internet and load things faster.
Cached data helps the user to load the data without Internet connection while loading
the app. Windows store SDK supports a NuGet library named Q42.WinRT to cache the data much easily.
To add the Q42 library, follow these steps:
Create a blank XAML application with an appropriate name. In the Solution Explorer, right-click the
project and select Manage NuGet Packages as shown in figure 4.4.

Concepts

1.

Figure 4.4: Manage NuGet Packages Option


The Manage NuGet Packages dialog box is displayed.

V 1.0 Aptech Limited

Session
2.

4
Storage Mechanisms

Search for Q42. Then, install the Q42.WinRT package as shown in figure 4.5.

Figure 4.5: Search Q42 and Install in the Solution


3.

After adding the package, create an API from a social networking application such as Flickr. For
example, to access the photos from Flickr, write the code shown in Code Snippet 9.
Code Snippet 9:
protected async override void LoadState(Object navigationParameter,
Dictionary<String, Object> pageState)
{
var client = new HttpClient();
string url = http://api.flickr.com/services/rest/?method=flickr.photos.
getRecent&api_key=YOUR_API_KEY&format=json;
async () =>
{
var tmp = await client.GetStringAsync(new Uri(url,UriKind.Absolute));
var r = tmp.Substring(14, tempResult.Length - 15);

V 1.0 Aptech Limited

Concepts

var res = await JsonCache.GetAsync(CalculateMD5Hash(url),

Session

Storage Mechanisms
var p = await JsonConvert.DeserializeObjectAsync(r);
return p;
});
this.DefaultViewModel[Groups] = r.photos.photo;
}

4.4 Advanced File Functionality


To perform any CRUD operations in the file, the user must provide permissions to add or delete a file.
These CRUD operations can be used either in local or remote storage. The user can access the file system
through the File Picker.
Code Snippet 10 shows how to create a test.txt file in the file system.
Code Snippet 10:
StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
var fle = await storageFolder.CreateFileAsync(
test.txt, CreationCollisionOption.ReplaceExisting);
lblRemark.Text = fle.Name + created.;

The earlier code creates a text file under the Documents folder. Code Snippet 11 shows how to write the
contents inside the created text file.
Code Snippet 11:
StorageFile file = this.fle;
if (file != null)
{
string userContent = txtRemark.Text;
if (!String.IsNullOrEmpty(userContent))

Concepts

{
using (IRandomAccessStream sessionRandomAccess = await
file.OpenAsync(FileAccessMode.ReadWrite))
{
Stream stream = sessionRandomAccess.AsStreamForWrite();
if (stream.Length > 0)
{

V 1.0 Aptech Limited

Session

4
Storage Mechanisms
stream.Seek(stream.Length, SeekOrigin.Begin);

}
byte[] array = Encoding.UTF8.GetBytes(userContent);
stream.SetLength(stream.Length + array.Length);
await stream.WriteAsync(array, 0, array.Length);
await stream.FlushAsync();
await sessionRandomAccess.FlushAsync();
}
ResetScenarioOutput();
await ReadFromFile();
}
else
{
lblRemark.Text = @The text box is empty, please
write something and then click Write again.;
}
}
else
{
lblRemark.Text = @File not open!;
}

To read the written content of the text file, the user must write the code as shown in Code Snippet 12.
Code Snippet 12:
if (this.fle == null)
{
await OpenFile();

Concepts

}
if (this.fle != null)
{
await ReadFromFile();
}

V 1.0 Aptech Limited

Session

Storage Mechanisms

else
{
lblRemark.Text = @Create the file to read / write.;
}

To open the file, asynchronous threading code must be written as shown in Code Snippet 13.
Code Snippet 13:
private async System.Threading.Tasks.Task OpenFile()
{
StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
this.fle = await storageFolder.GetFileAsync(MainPage.NfNe);
lblRemark.Text = The file + fle.Name + was loaded.;
}
private async System.Threading.Tasks.Task ReadFromFile()
{
using (IRandomAccessStream sessionRandomAccess =
await this.fle.OpenAsync(FileAccessMode.Read))
{
if (sessionRandomAccess.Size > 0)
{
byte[] array3 = new byte[sessionRandomAccess.Size];
IBuffer output = await
sessionRandomAccess.ReadAsync(
array3.AsBuffer(0, (int)sessionRandomAccess.Size),
(uint)sessionRandomAccess.Size,
InputStreamOptions.Partial);

Concepts

string reRead = Encoding.UTF8.GetString(output.ToArray(), 0, (int)


output.Length);
lblRemark.Text = this.fle.Name + Content - + Environment.NewLine +
Environment.NewLine + reRead;
}
else

V 1.0 Aptech Limited

Session

4
Storage Mechanisms

{
lblRemark.Text = File is empty;
}
}
}

After the usage of the file, the user can delete the text file from the storage device by writing the code
given in Code Snippet 14.
Code Snippet 14:
try
{
this.ResetScenarioOutput();
StorageFile file = this.fle;
if (file == null)
{
await OpenFile();
}
if (file != null)
{
string fne = file.Name;
await file.DeleteAsync();
this.fle = null;
lblRemark.Text = fne + is deleted;
}
else
{
}
}
catch (FileNotFoundException)

V 1.0 Aptech Limited

Concepts

lblRemark.Text = The file not found;

Session

4
Storage Mechanisms
{
this.NotifyUserFileNotExist();
}
private void NotifyUserFileNotExist()
{
lblRemark.Text = The file not found;
}
private void ResetScenarioOutput()
{
this.lblRemark.Text = ;
this.txtRemark.Text = ;
}

4.4.1 Setting Up File Extensions and Associations


When users want to use their own file extensions, the extension must be registered inside the
appxManifest file. This appxManifest file can hold any type of extension inside it. For some
pre-integrated files, extension that appears inside the app is available as an in-built feature. The user has
to edit the appxManifest file using any XML Editor in order to register the file extension. To open the
appxManifest file, click the file from the Solution Explorer and select Open with option. Then, select
the name of any XML Editor and clickOK.
In theExtensions element of the app manifest file, a file association is specified with the
FileTypeAssociation element. Code Snippet 15 shows how to add the file type inside the
appxManifest file.
Code Snippet 15:
<Applications>
<Application Id=App
Executable=$targetnametoken$.exe

Concepts

EntryPoint=FileManipulation.App>
<m2:VisualElements
DisplayName=FileManipulation
Square150x150Logo=Assets\Logo.png
Square30x30Logo=Assets\SLogo.png

V 1.0 Aptech Limited

Session

4
Storage Mechanisms

Description=FileManipulation
ForegroundText=light
BackgroundColor=#0099FF>
<m2:SplashScreen Image=Assets\Splash.png />
</m2:VisualElements>
<Extensions>
<Extension Category=windows.fileTypeAssociation>
<FileTypeAssociation Name=ftype>
<SupportedFileTypes>
<FileType>.jpg</FileType>
<FileType>.png</FileType>
<FileType>.gif</FileType>
<FileType>.tiff</FileType>
<FileType>.mp3</FileType>
<FileType>.mkv</FileType>
<FileType>.dat</FileType>
<FileType>.data</FileType>
</SupportedFileTypes>
</FileTypeAssociation>
</Extension>
</Extensions>
</Application>
</Applications>

The user must take care of the file size when using files in an app. If the file size exceeds a particular
limit, it becomes difficult to download the file. For instance, if the device storage has less space and
the size of the file being downloaded is more than the free space, then, it interrupts the ongoing tasks
while downloading the file. Hence, the user must compress large data into zip formats so that it can be
downloaded with less Internet bandwidth and by consuming less disk space. Windows 8 has two classes
namely, Compressor and Decompressor to compress the file and uncompress the file.

V 1.0 Aptech Limited

Concepts

4.4.2 Compressing Files in an App

Session

4
Storage Mechanisms

Code Snippet 16 shows how to create a compressed file.


Code Snippet 16:
var st = await ApplicationData.Current.LocalFolder.
CreateFileAsync(filename.zip, CreationCollisionOption.ReplaceExisting);
var bytes = Encoding.UTF8.GetBytes(_text);
var s = await storage.OpenStreamForWriteAsync();
var c = new Compressor(st.AsOutputStream());
await c.WriteAsync(bytes.AsBuffer());
await c.FlushAsync();
await c.FinishAsync();
await s.FlushAsync();

Code Snippet 17 demonstrates the decompression of file after the file is stored inside the disk.
Code Snippet 17:
var dc = new Decompressor(st.AsInputStream());
var b = new Byte[100000];
var bfr = b.AsBuffer();

Concepts

var bu = await dc.ReadAsync(bfr, 999999, InputStreamOptions.None);

V 1.0 Aptech Limited

Session

4
Storage Mechanisms

4.5 Check Your Progress


1.

2.

3.

(A) Server

(C)

Local Store

(B)

(D)

Database

Cloud

The ____________ namespace is used to store and retrieve data to and from Windows Store apps.
(A) Store

(C)

WinStore.Storage

(B)

(D)

Windows.Storage

Storage

When the user wants to use their own file extension, then the extension must be registered inside
the _______ file.
(A) appxManifest

(C)

Resource dictionary

(B)

(D)

app.config

manifest

Which of the following are the correct types of Web Storage?


(A) local storage and session storage

(C)

current storage and session storage

(B)

(D)

user storage and remote storage

local storage and remote storage

Concepts

4.

Windows 8 offers storage of data in the _________ through Windows Azure.

V 1.0 Aptech Limited

Session

4
Storage Mechanisms

4.5.1 Answers
B

2.

3.

4.

Concepts

1.

V 1.0 Aptech Limited

Session

4
Storage Mechanisms

Summary
Windows 8 supports storage mechanisms to store data in local system and on the server.

The Windows.Storage namespace is used to store and retrieve data to and from a Windows Store
app.

Users must take care of planning for data storage before creating the project.

IndexedDB can store large data from the app or browsers in the database in the form of BLOBs.

The file manipulation supported by Windows Store apps include the CRUD operations. Users can
store the file locally or remotely.

Web storage is one of the best methods to store the data.

Concepts

V 1.0 Aptech Limited

Session - 5
Working with Controls
Welcome to the Session, Working with Controls.
This session introduces the user to working with controls, creating and using
custom controls, and creating and consuming WinRT components.
In this Session, you will learn to:
Explain the process of working with controls
D
escribe the process of creating and using a custom control and
template
Explain the process of creating and consuming WinRT Components

Session

5
Working with Controls

5.1 Controls
Visual Studio provides a set of many controls to the developers. To design a UI for an app, the user needs
a set of controls such as Text Block, Check Box, Drop-down list, Button, and so on. These controls are
built-in and can be directly merged into our existing UI. To add these controls, user can directly drag and
drop it into Visual Studio form or page in the designer or can add these controls by writing XAML code.
Figure 5.1 shows the list of some built-in controls.

Figure 5.1: Windows 8 Built-in Controls List


Figure 5.1 shows the list of some of the built-in controls that can be added in the current Windows Store
app.

In order to add more functionality to the existing controls, the user needs to create new controls based
on the existing controls. Sometimes, the user wants to create and save the controls so that it can be
reutilized in future or these controls may add more functionality to existing controls. This type of controls
are called custom controls or template controls. For this purpose, the user needs to know how to create
and use custom controls.

V 1.0 Aptech Limited

Concepts

5.1.1 Creating Custom and Templated Controls

Session

5
Working with Controls

There are three ways of using these built-in controls and creating the custom controls. They are as follows:
1.

Using Blend/Visual Studio

2.

Using XAML editor

3.

Through backend code

Using Blend/Visual Studio


This is the easiest way to add the controls from the toolbox. When the users develop the apps,
they can add the controls in the form/page wherever they needed. They can also change the style
and appearance of the controls as needed. These changes can be done by changing the values
of various properties or by writing appropriate XAML codes. The user can drag the controls from
the toolbox and drop it onto the canvas, form, or panel and add the necessary properties and
functionalities to the existing controls and create his/her own custom controls. Figure 5.2 shows
how to use controls from the toolbox.

Figure 5.2: Page after a TextBlock is Dragged and Dropped

Concepts

Figure 5.2 shows the page after the user drags a TextBlock inside the page. The user can change
the properties of the TextBlock instance by changing the appropriate values in the Property
window as shown in figure 5.3.

V 1.0 Aptech Limited

Session

5
Working with Controls

Figure 5.3 also shows Property window on the screen after the TextBlock is dragged and dropped.

Figure 5.3: Property Window for TextBlock


When the user changes the text size of TextBlock to 24, the result of this change will be as shown in
figure 5.3.

Using XAML Editor


While using XAML Editors, the users need to write code for every control they want to customize.
For example, if the user needs to add a TextBlock control inside the design view, then he/she can
write the code shown in Code Snippet 1. The user then can change the necessary properties or add
functions to this existing control. Thus, customizing the control as per the users need.
Code Snippet 1:
<TextBlock HorizontalAlignment=Left Margin=572,357,0,0
TextWrapping=Wrap Text=TextBlock VerticalAlignment=Top/>

Code Snippet 1 shows how the XAML code is written to create controls.
Through Backend Code
If the user needs to add control to the app, then he/she can add such controls by writing the
backend code in C# or any other preferred language. He/she can create a control at runtime, change
its properties at runtime, and then, use such an object in his/her Store app. This is also referred to
as creating controls dynamically.

V 1.0 Aptech Limited

Concepts

Session

5
Working with Controls
Note - When the users create the control through back end then they are known as custom

controls.

Code Snippet 2 shows how to add the controls dynamically in the Store app by writing the back end
code in C#.
Code Snippet 2:
public MainPage()
{
this.InitializeComponent();
TextBox textbox = new TextBox();
textbox.Text = (Enter some text);
textbox.Height = 50;
textbox.Width = 200;
textbox.Name = textbox;
Button button = new Button();
button.Height=50;
button.Width = 200;
button.Content = Dynamic Button;
this.myGrid.Children.Add(button);
this.myGrid.Children.Add(textbox);
}

In Code Snippet 2, a text box and a button are created and added dynamically. Appropriate
properties of these controls are set dynamically before adding these controls to the grid.

5.1.2 Types of Controls


In C#, the developer can re-use controls in two ways, that is, by using inheritance and static methods. In
XAML, there are four types of controls or strategies that can be used to re-use the controls.

Concepts

These controls are as follows:

Higher Resources

Resource Dictionaries

User Controls

Custom Controls

V 1.0 Aptech Limited

Session

5
Working with Controls

Higher Resources
To design the elements to impress the users, the developer have to create <Resources/>
properties which are properties for any control. These properties have the scope to the entire
page. Any property such as style, template, or variables set here will be available or applicable to
all the UI elements in the current page. This is added as a child element inside the controls code.
Code Snippet 3 shows how to apply styles using the higher resources file.
Code Snippet 3:
<Page
x:Class=ResourceDemo.MainPage
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
xmlns:local=using:ResourceDemo
xmlns:d=http://schemas.microsoft.com/expression/blend/2008
xmlns:mc=http://schemas.openxmlformats.org/markupcompatibility/2006
mc:Ignorable=d>
<Grid Background={ThemeResourceApplicationPageBackgroundThemeBrush}>
<StackPanel Margin=612,108,594,220>
<StackPanel.Resources>
<Style TargetType=TextBox>
<Setter Property=Foreground Value=Red />
<Setter Property=FontSize Value=16 />
</Style>
<Style TargetType=Button>
<Setter Property=Foreground Value=Maroon />
<Setter Property=Background Value=Wheat />
</Style>
<TextBox Margin=5 Text=TextBox />
<Button Margin=5,5,0,5 Content=Button />
</StackPanel>

V 1.0 Aptech Limited

Concepts

</StackPanel.Resources>

Session

Working with Controls


</Grid>
</Page>

Code Snippet 3 changes the Foreground color of any TextBox placed inside the page to Red and
FontSize property to 16. This is done by changing the higher resource property, Foreground
color to Red and FontSize to 16 and specifying the target type to TextBox. As a effect of these
settings, any TextBox added in the current page will automatically have Red color for text contents
and font size will be 16. When the user writes the code and executes, the output will be displayed
as shown in figure 5.4.

Figure 5.4: Changed Foreground Color

Resource Dictionaries

Concepts

The developer can create a list of key/value pairs in the current project. This is the collection of
multiple keys and values. The multiple values stored inside a resource file are called the resource
dictionaries. These dictionaries will have the templates, styles, or any variables. These values are
related to some controls or objects on the current pages in an app. These dictionaries support the
following objects:

yy

Styles

yy

Templates

yy

Brushes

yy

Colors

yy

Animations

yy

Transforms

yy

Matrix

yy

XAML essential data types

User Controls
The user can create their own controls using the User Control Templates. A user control is a layout

V 1.0 Aptech Limited

Session

5
Working with Controls

container or group of controls that act like a little page. The developer can use and reuse a user
control on the same page or across multiple pages in the current project. A user control has
code-behind and an event pipeline. These controls can be called inside the app using their own
namespaces. These user controls are reusable.
These controls can be called and used anywhere inside the Windows Store app, instead of writing
the same code again and again inside the pages in an app. The users just have to call these user
controls and start using it. It helps the user to develop the apps easily and swiftly. Thus, user controls
save the developers time.

Custom Controls
A custom control is a light-weight control. It is created by subclassing an existing control and
overriding all or some of the properties or functions of the existing control. These custom controls
can be reused any number of times. This saves the developers time. Developers can interact with
these controls same as the standard controls.

Difference between User Controls and Custom Controls


Table 5.1 shows the difference between a User Control and a Custom Control.

Custom Control

User Control

It is a loosely coupled control


It is derived from Control class
It defines UI in a ResourceDictionary
It has dynamic layout
UI can be changed in different projects. It is
customizable as per needs
It can be added to toolbox and has full toolbox
support
It defines a single control
It offers full flexibility
For creating this control, the user need to have
in-depth knowledge of Silverlight UI Model

It is a tightly coupled control


It is derived from UserControl class
It defines UI as normal XAML
It has static layout
UI is fixed and can't have different looks
in different project
It cannot be added to the toolbox
It defines a set of controls
It is not as flexible as a Custom Control
There is no need to have in-depth
knowledge of the UI Model

Table 5.1: Differences between User Controls and Custom Controls


The Reusable controls are user defined controls which can be re-used in the current app/project, or in
any other app/project. They can be developed by extending the existing controls and enhancing their
own design features or adding more functionality to it. These user controls can be created by adding a
new class file in the current project.

V 1.0 Aptech Limited

Concepts

Creating Reusable Controls and Components

Session

5
Working with Controls

Note - Instead of using more pre-defined controls, these user controls are created to add more

features and functionality to the existing controls. It is one of the time saving tools that are available
to developers.

User controls file can be created using the following steps:


1.

Click AddNew Item as shown in figure 5.5.

Figure 5.5: Adding New Item


Select the User Control option as shown in figure 5.6 to add a user control to the current Windows
Store app project.

Concepts

2.

Figure 5.6: Selecting User Control

V 1.0 Aptech Limited

Session

5
Working with Controls

After the control is created, users can create their own user control as per their need with added features
and functionality. Code Snippet 4 shows auto-generated XAML code for the user control.
Code Snippet 4:
<UserControl
x:Class=UserControlDemo.DemoUserControl
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
xmlns:local=using:UserControlDemo
xmlns:d=http://schemas.microsoft.com/expression/blend/2008
xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006
mc:Ignorable=d
d:DesignHeight=300
d:DesignWidth=400>
<Grid Background=WhiteSmoke>
<TextBlock HorizontalAlignment=Left Margin=120,140,0,0
TextWrapping=Wrap Text=User Control Demo Foreground=Maroon FontSize=20
VerticalAlignment=Top/>
</Grid>
</UserControl>

Code Snippet 4 creates a user control with a TextBlock and this user control can be called anywhere in
the application whenever required. To call this UserControl, the user must write the code as shown in
Code Snippet 5.
Code Snippet 5:
<Grid Background={ThemeResource ApplicationPageBackgroundThemeBrush}>
<local:DemoUserControl x:Name=UsrCntrl Margin=380,236,409,208></
local:DemoUserControl>

Code Snippet 5 shows how to add a user control in any other XAML page. The line <local:
DemoUserControl x:Name=UsrCntrl Margin=380,236,409,208> adds the user control,
DemoUserControl to the current XAML page.

V 1.0 Aptech Limited

Concepts

</Grid>

Session

5
Working with Controls

When the user executes the app, the output will be displayed as shown in figure 5.7.

Figure 5.7: Output for User Control

5.1.3

Controls by Function

Visual Studio holds a broad library of XAML controls inside Windows Store development to change the
designing of the UI. The user can select an appropriate control for his scenario by comparing controls
that offer similar functionality. Some of these controls are part of the Silverlight libraries in the Silverlight
SDK. Comparing controls by functions is possible in Visual Studio. After making such comparison, the user
can then decide which control to use for best functionality and features. Buttons, selection controls, date
display controls, information display controls, text display and editing controls, data display controls, and
html display controls are some of the examples of controls by function.
The following examples show how to use some of these controls:

App Bars

Concepts

Figure 5.8: App Bar Commands

V 1.0 Aptech Limited

Session

5
Working with Controls

The App Bar is used to take specific actions based on the selected controls, as shown in figure 5.8. To
create an App Bar, the code shown in Code Snippet 6 can be used.
Code Snippet 6:
<Page Background=ForestGreen
x:Class=App6.MainPage
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
xmlns:local=using:App6
xmlns:d=http://schemas.microsoft.com/expression/blend/2008
xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006
mc:Ignorable=d>
<Page.BottomAppBar>
<CommandBar Background=#FF1C6BA2 Foreground=#FFA66262>
<AppBarButton Label=Refresh Icon=Refresh />
<AppBarButton Label=Help Icon=Help/>
<CommandBar.SecondaryCommands>
<AppBarButton Label=Edit Icon=Edit />
<AppBarButton Label=Remove Icon=Remove />
<AppBarButton Label=Add Icon=Add />
</CommandBar.SecondaryCommands>
</CommandBar>
</Page.BottomAppBar>
<Grid Background=ForestGreen HorizontalAlignment=Left Height=1024
VerticalAlignment=Top Width=1366>
<TextBlock HorizontalAlignment=Left Margin=531,391,0,0
TextWrapping=Wrap FontSize=26 Text=Welcome to AppBar Demo
VerticalAlignment=Top/>

Concepts

</Grid>
</Page>

V 1.0 Aptech Limited

Session

5
Working with Controls

When the app is executed by pressing the F5 button, the output screen will be displayed as shown in
figure 5.9.

Figure 5.9: Starting Screen of the App Bar Demo


After the app is loaded, click the screen to view the App Bar, as shown in figure 5.10.

Figure 5.10: Output Displaying the App Bar

Concepts

Buttons
There are different types of buttons, each of which can have a click event. To create a button, write
the code as shown in Code Snippet 7 or drag the button from the Toolbox.
Code Snippet 7:
<Button x:Name=button1 Content=Button Click=Button_Click />

V 1.0 Aptech Limited

Session

5
Working with Controls

A hyperlink button is used to navigate between pages or to navigate to other Web pages and can
be created using Code Snippet 8.
Code Snippet 8:
<HyperlinkButton Content=www. google.com NavigateUri=http://www.
google.com/>

ListView
ListView control is used to list the items from the database or statically. This list view is created
to select one or more items from the list box. Code Snippet 9 demonstrates the usage of the
ListView control.
Code Snippet 9:
<Page
x:Class=ListBoxDemo.MainPage
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
xmlns:local=using:ListBoxDemo
xmlns:d=http://schemas.microsoft.com/expression/blend/2008
xmlns:mc=http://schemas.openxmlformats.org/markupcompatibility/2006
mc:Ignorable=d>
<Grid Background=ForestGreen>
<ListView x:Name=lvApp Background=WhiteSmoke Foreground=Maroon
FontSize=22 Margin=590,225,567,276>
<x:String>Item 1</x:String>
<x:String>Item 2</x:String>
<x:String>Item 3</x:String>
<x:String>Item 4</x:String>
<x:String>Item 5</x:String>

Concepts

</ListView>
</Grid>
</Page>

V 1.0 Aptech Limited

Session

5
Working with Controls

When the user executes the code by pressing the F5 key, the output will be displayed as shown in
figure 5.11.

Figure 5.11: Output of the AppBar

5.2 Custom Controls


One of the most powerful features of XAML in Windows 8 is the flexibility that the platform provides
to create custom controls. Custom controls are reusable controls or user-defined controls which can be
used anywhere in the app or in any other app to be developed.
Consider an example to build a custom control named HelloCustomControl. To create
a custom class called HelloCustomControl, it is necessary to derive it from the class
Windows.UI.XAML.Controls.Control, as all custom controls are based on this class.
To create new custom control, perform the following steps:
Create a new project in Visual Studio using the Blank Project template and name it as CustomControls.

2.

Add your custom control using the Add New Item template wizard as shown in figure 5.12.

Concepts

1.

V 1.0 Aptech Limited

Session

5
Working with Controls

Figure 5.12: Creating Templated Control


When the template control item is created, the code given in Code Snippet 10 will be added automatically to the current project.
Code Snippet 10:
public class HelloCustomControl: Control
{
public HelloCustomControl()

this.DefaultStyleKey = typeof(HelloCustomControl);
}

In the code, the HelloCustomControl class derives from Control. Setting the DefaultStyleKey indicates to the XAML platform that this class uses an implicit style. The templated
control template also adds a folder named Themes, and in that folder creates a new file named
Generic.xaml.
A controls default style is defined in a custom Generic.xaml file that the platform loads automatically. In this file, you define an implicit style that will be applied by default to all controls of a
specific type.

V 1.0 Aptech Limited

Concepts

Session
3.

5
Working with Controls

Add the following XAML to a new Generic.xaml file in the Themes folder.
Code Snippet 11:
<ResourceDictionary
xmlns=http://schemas.microsoft.com/winfx/2006/XAML/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/XAML
xmlns:local=using:CustomControls>
<Style TargetType=local:HelloCustomControl>
<Setter Property=VerticalAlignment Value=Center />
<Setter Property=HorizontalAlignment Value=Center />
<Setter Property=Template>
<Setter.Value>
<ControlTemplate TargetType=local:HelloCustomControl>
<Border
Background={TemplateBinding Background}
BorderBrush={TemplateBinding BorderBrush}
BorderThickness={TemplateBinding BorderThickness}>
<TextBlock Text=HelloCustomControl

FontFamily=Courier

New FontSize=36/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

Concepts

</ResourceDictionary>

In Code Snippet 11, the Generic.xaml file defines a style that will be applied by default to all instances of the HelloCustomControl control. You define a Control Template, and this template
specifies that it is simply a TextBlock with the text HelloCustomControl.
4.

In the MainPage.xaml file, add the following markup. You must include the local: designation
to let XAML know in which namespace to find the HelloCustomControl class. The local:
designation is defined at the top of the XAML file.
<local:HelloCustomControl />

When this app is executed, the control is loaded and it displays the text Hello, World!

V 1.0 Aptech Limited

Session

5
Working with Controls

Defining Control Options


Controls become more useful and reusable when you add configurable options. To add this option, you
add a Dependency Property (DP) to the control. There is a built-in Visual Studio snippet that helps to
add DPs in a fast and easier manner. Place the cursor below a constructor, type propdp, and press Tab
twice. Code Snippet 12 shows the resultant code.
Code Snippet 12:
public class HelloCustomControl : Control
{
public HelloCustomControl()

this.DefaultStyleKey = typeof(HelloCustomControl);
}
public bool Blink {
get { return (bool)GetValue(BlinkProperty); }
set { SetValue(BlinkProperty, value); }
}
public static readonly DependencyProperty BlinkProperty =
DependencyProperty.Register(
Blink,

// The DependencyProperty name

typeof(bool),

// The DependencyProperty type

typeof(HelloCustomControl),

// The DependencyProperty owner type

new PropertyMetadata(false, new PropertyChangedCallback(OnBlinkChang

ed)

)
);
private DispatcherTimer __timer = null;
//To set the time
{
get
{
if (__timer == null)
{

V 1.0 Aptech Limited

Concepts

private DispatcherTimer _timer

Session

5
Working with Controls

__timer = new DispatcherTimer();


__timer.Interval = new TimeSpan(0,0,0,0,500); // 500 ms

interval

__timer.Tick += __timer_Tick;
}
return __timer;
}
}
private static void OnBlinkChanged(
DependencyObject d,
DependencyPropertyChangedEventArgs e
)
{
var instance = d as HelloCustomControl;
if (instance != null)
{
if (instance._timer.IsEnabled != instance.Blink)
{
if (instance.Blink)
{
instance._timer.Start();
}
else
{
instance._timer.Stop();
}

Concepts

}
}
}

V 1.0 Aptech Limited

Session

5
Working with Controls

private void __timer_Tick(object sender, object e)


{
DoBlink();
}
private void DoBlink()
{
this.Opacity = (this.Opacity + 1) % 2;
}
}

In MainPage.xaml, add the configuration option to the control.


<local:HelloCustomControl Blink=True />

Run the app and observe the control blinking.


Adding Support for Events
By adding events to controls, the user can increase their functionality. Events allow getting interrupts
from the control when actions take place. You can run code that reacts to the actions. To add an event
that fires each time the control blinks, type the code shown in Code Snippet 13.
Code Snippet 13:
public class HelloCustomControl : Control
{
...
...
private void __timer_Tick(object sender, object e)
{
DoBlink();
}
{
this.Opacity = (this.Opacity + 1) % 2;
OnBlinked();
}
public event EventHandler Blinked;

V 1.0 Aptech Limited

Concepts

private void DoBlink()

Session

5
Working with Controls

private void OnBlinked()


{
EventHandler eh = Blinked;
if (eh != null)
{
eh(this, new EventArgs());
}
}
}

Then, in MainPage.xaml, add an x:Name property to the element so that you can retrieve the control
instance later in code:
<local:HelloCustomControl x:Name=HelloCustomControlWithEvents Blink=True
/>

Now in MainPage.xaml.cs, add an event listener function delegate to print debug output when the
event is fired.
Code Snippet 14 shows how to add an event handler to handle the Blinked event.
Code Snippet 14:
HelloCustomControlWithEvents.Blinked += (object sender, EventArgs args) =>
{
System.Diagnostics.Debug.WriteLine(HelloCustomControlWithEvents Blinked);
};

When you execute this code, it shows a message every 500 milliseconds in the Output Console window.
Exposing Public Methods
A private method DoBlink is written to cause the control to blink, and this method is made public to allow
option to blink the control at any time. For this, you will change the visibility of the DoBlink method to
public as shown in Code Snippet 15.

Concepts

Code Snippet 15:


public class HelloCustomControl : Control
{
...
public void DoBlink()
{

V 1.0 Aptech Limited

Session

5
Working with Controls

this.Opacity = (this.Opacity + 1) % 2;
OnBlinked();
}
...
}

Call the public DoBlink method in C# code-behind in a button click handler as shown in Code Snippet
16.
Code Snippet 16:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
HelloCustomControlWithEvents.DoBlink();
}

5.3 Creating and Using Custom WinRT Components


Windows Runtime or WinRT is an application architecture on Windows 8. WinRT enables you to expose
apps so that they can be called from JavaScript, C++, C#, and so on. A WinRT component that is built and
packaged in your app is called as a 3rd party or custom WinRT component. This is different from 1st party
components that are built-in with Windows 8 platform. The custom WinRT components can be created
using C++, C#, or Visual Basic. You can then call or consume these components from anywhere, including
other WinRT components packaged into your app.
Internally, your Windows Runtime types can use any .NET Framework functionality that is allowed in a
Windows Store app. When you build your solution, Visual Studio builds your .NET Framework Windows
Runtime Component project and then executes a build step that creates a Windows metadata (.winmd)
file. This is your Windows Runtime component, which Visual Studio includes in your app. This component
can be re-used in any other application.
Note - The .NET Framework automatically maps some commonly used .NET Framework types, such as

primitive data types and collection types, to their Windows Runtime equivalents.

Concepts

The metadata files for the system are located under C:\Windows\System32\WinMetadata as shown in
figure 5.13.

V 1.0 Aptech Limited

Session

5
Working with Controls

Figure 5.13: WinMD Files Inside the System


The following tasks are to be performed to create a WinRT component:

Creating a simple Windows Runtime class

Using the Windows Runtime from JavaScript and managed code

Returning managed types from your component

Creating a simple Windows Runtime class


The following example creates a WinRT component using C#. It shows how to define a managed Windows
Runtime type:

Concepts

Step 1: In Visual Studio, create a new C# project using File New Project and select Windows
Runtime Component as the template as shown in figure 5.14.

V 1.0 Aptech Limited

Session

5
Working with Controls

Figure 5.14: Creating WinRT Component


Step 2: Add the following code shown in Code Snippet 17 to Class1.cs.
Code Snippet 17:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyWinRTComponent
{
public sealed class Class1
{
public double GetAddition(double n1, double n2, double n3)

V 1.0 Aptech Limited

Concepts

using System.Threading.Tasks;

Session

Working with Controls

{
return (n1+n2+n3);
}
public int SampleProperty { get; set; }
}
}

This code adds a method called GetAddition which accepts three numbers n1,n2, and n3 of type
double. It performs addition of these three numbers and returns answer as double value.
Consuming the WinRT component in Another project
Step 1: Create new project called ConsumingWinRTComponent.

Concepts

Step 2: Add reference to .Winmd file that was created in the MyWinRTComponent project as shown in
figure 5.15.

Figure 5.15: Adding Reference to WinMD File

V 1.0 Aptech Limited

Session

5
Working with Controls

Step 3: Select the file created in previous example MyWinRtComponent.winmd as shown in figure 5.16.

Figure 5.16: Selecting the WinMD File


This file will be added as an reference in the current project. The developer can make use of all the types
and functions in the .winmd file.

Concepts

Step 4: Create the interface shown in figure 5.17 in XAML to accept three numbers from the user and
pass these values to the WINRT component.

V 1.0 Aptech Limited

Session

5
Working with Controls

Figure 5.17: User Interface


Step 5: Double-click the Add Numbers button and add the following code shown in Code Snippet 18 to
MainPage.xaml.cs file.
Code Snippet 18:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;

Concepts

using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;

V 1.0 Aptech Limited

Session

5
Working with Controls

using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using MyWinRTComponent;
// The Blank Page item template is documented at http://go.microsoft.com/
fwlink/?LinkId=234238
namespace UsingWinRTComponent
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a
Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
MyWinRTComponent.Class1 wrtc = new Class1();
double answer = wrtc.GetAddition(Convert.ToDouble(n1.Text),
Convert.ToDouble(n2.Text), Convert.ToDouble(n3.Text));
textbox4.Text=answer.ToString();
}
}

In the example, the user will enter three random numbers in the given text boxes. When he/she clicks Add
Numbers, the call to WinRT component is made. The WINRT component will pass it to GetAddition()
method, which in turn will calculate the addition of the three numbers passed to it and finally returns the
answer back to the calling function. This will be shown in text box 4.

V 1.0 Aptech Limited

Concepts

Session

5
Working with Controls

5.4 Creating and Using Custom XAML Controls


To create a custom XAML control, the user must create a blank app and then, a user control by creating
new items from the context menu of Solution Explorer as shown in figure 5.18.

Figure 5.18: Adding a User Control

Concepts

Then, the user can design their own user control as shown in figure 5.19.

Figure 5.19: Design the Page

V 1.0 Aptech Limited

Session

5
Working with Controls

After the design is complete, the user can view the markup which would be similar to Code Snippet 19.
Code Snippet 19:
<Page
x:Class=App5.MainPage
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
xmlns:local=using:App5
xmlns:d=http://schemas.microsoft.com/expression/blend/2008
xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006
mc:Ignorable=d>
<Grid Background={ThemeResourceApplicationPageBackgroundThemeBrush}>
<local:MyUserControl1 x:Name=UsrCntrl />
</Grid>
</Page>

Write the code shown in Code Snippet 20.


Code Snippet 20:
private void Button_Click(object sender, RoutedEventArgs e)
{
txtResult.Text = string.Format(Result : , txtVal.Text);

Concepts

V 1.0 Aptech Limited

Session

5
Working with Controls

5.5 Check Your Progress


1.

2.

3.

4.

(A) Visual Studio

(C)

Template Control

(B)

(D)

Visual Basic

Virtual Studio

___________ is the easiest way to add the controls from the toolbox.
(A) XAML Editor

(C)

Visual Studio

(B)

(D)

Text Editor

Blend

Using __________, the user must have to hardcode for every control they require for the app.
(A) Blend

(C)

Visual Studio

(B)

(D)

Visual Basic

XAML Editor

To design the elements that can impress the users, you need to create the __________ file which
is a property of any control which is associated inside any child elements.
(A) <controls/>

(C)

<Resources/>

(B)

(D)

<controls/ />

<dictionaries/>

_________ are user-defined controls which can be used anywhere in the app or in any other app
to be developed.
(A) Reusable controls

(C)

XMAL editor

(B)

(D)

None of these

Useable controls

Concepts

5.

______________ holds a set of controls for the developers.

V 1.0 Aptech Limited

Session

5
Working with Controls

5.5.1 Answers
A

2.

3.

4.

5.

Concepts

1.

V 1.0 Aptech Limited

Session

5
Working with Controls

Summary
When users develop apps, they can add the controls in the form/page wherever they need.

sers can add controls to the apps using one of the three options, that is, by using Visual Studio or
U
Blend, through XAML Editor, or by adding back end code in C#.

T he key/value pair data stored in a separate file for loose coupling is called a resource dictionary.
These dictionaries will have the template, style, or variables that are related to the components
on the current page in an app.

T he user can create their own controls using the User Control Templates. These controls can be
called inside the app using their own namespaces.

F or re-usability, the user can use any one of four strategies: Higher Resources, Resource
Dictionary, User Controls, and Custom Controls.

WinRT controls are light-weight controls that can be embedded within current Store apps.

Concepts

V 1.0 Aptech Limited

Session - 6
Using Contracts, Print Settings,
and Speech Synthesis
Welcome to the Session, Using Contracts, Print Settings, and Speech Synthesis.
This Session explains the use of contracts to print documents and speech
synthesizer for voice control.
In this Session, you will learn to:
Explain the use of contracts in an apps
Describe how to add print functionality to apps
Explain the process of converting and printing to a .pdf file
Explain speech synthesis

Session

6
Using Contracts, Print Settings, and Speech Synthesis

6.1 Contracts
When a user moves the mouse cursor on the right side of the screen, he/she can find the Charm, which
is also called the Universal Toolbar. It shows Search, Share, Start, Device, and Settings options. These
charms can also be called by tapping Win + C or Win + Q keys. These charm options are called contracts.
A contract is an agreement between one or more apps. Contracts define the minimum requirements that
apps must meet to interact with other apps. A contract is necessary when the user wish to share some
data or information between two apps. The app that shares content supports a source contract, while
the app that receives the shared content supports a target contract. Both these apps must meet the basic
requirements in order to communicate with each other and share data or information. In this case, both
apps need not know anything about each other. Thus, sharing emails contacts, databases, calendars,
files, and so on can be done using contracts.
There are many built-in contracts available in Windows 8. These contracts have various functionality and
features.

Account Picture
The Account picture extensions help the user to change their profile picture. By default, the account
picture is loaded from their Hotmail/Live account, which is set by the user at the time of installation
of Hotmail/Live account.

Play To Contract
The Play To contract is used to stream line any audio, video, and picture files to Digital Living
Network Alliance (DLNA) enabled devices. DLNA is a non-profit collaborative trade organization
initiated by Sony with the aim of sharing digital contents. The user can select the files from the
storage device or through their music/video folder which can be uploaded automatically to DLNA
servers and can be shared with others.

Print
Print contract is used to print any document from any app. The print task will be enabled only for
the app which is registered with PrintTask. Any application that is registered with PrintTask

can send the documents for printing by using this contract.

Concepts

Setting
The setting contract is a useful feature in Windows 8. The user can use these settings contract for
changing the password, account picture, wallpapers, notification settings, and many more.

Search
Search contract can be called through the search charm or the search option inside the app. This
allows searching documents or files in the local machine or on the Internet.
Note - The search contract have a feature to send the search results to other app.

V 1.0 Aptech Limited

Session

6
Using Contracts, Print Settings, and Speech Synthesis

Figure 6.1 shows the Search charm or contract.

Figure 6.1: Search Contract

6.1.1 Activating Contracts in Windows Store App


The user has many options using which controls can be added while developing the app. To develop the
search pane, the user has to perform the following steps:

Concepts

Step 1: Create a blank new application as shown in figure 6.2.

V 1.0 Aptech Limited

Session

6
Using Contracts, Print Settings, and Speech Synthesis

Figure 6.2: Create a Blank New Application

Concepts

Step 2: Click the Solution Explorer and then navigate to add new items as shown in figure 6.3.

V 1.0 Aptech Limited

Session

6
Using Contracts, Print Settings, and Speech Synthesis

Figure 6.3: Adding New Item

Concepts

Step 3: After selecting the new item, a window will be displayed to select the item to be added as shown
in figure 6.4.

V 1.0 Aptech Limited

Session

6
Using Contracts, Print Settings, and Speech Synthesis

Figure 6.4: Select Search Result Page

Concepts

Step 4: After the Search Result Page is added, open the Package.appxmanifest file and navigate to
Declarations as shown in figure 6.5.

Figure 6.5: Navigate to Declaration Tab


Step 5: Select Search option from the available declaration as shown in figure 6.6.

V 1.0 Aptech Limited

Session

6
Using Contracts, Print Settings, and Speech Synthesis

Figure 6.6: Select the Search from the Available Declarations


If the user wants to add a Search contract in any app, then the user has to write the code as given in Code
Snippet 1.
Code Snippet 1:
<Grid Background={ThemeResource ApplicationPageBackgroundThemeBrush}>
<SearchBox x:Name=SrchTab/>
</Grid>

If the user wants to focus, when the search contract is called then FocusOnKeyboardInput property
must be called by setting the value to True.
Code Snippet 2 shows how to add a SearchBox in the XAML code.
Code Snippet 2:

To display a search box inside the app, the user has to write the code as given in Code Snippet 3.
Code Snippet 3 show how to add a text box and a search box in the XAML page.

V 1.0 Aptech Limited

Concepts

<SearchBox x:Name=SrchTab FocusOnKeyboardInput=True>

Session

Using Contracts, Print Settings, and Speech Synthesis

Code Snippet 3:
<Page
x:Class=SearchTabDemo.MainPage
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
xmlns:local=using:SearchTabDemo
xmlns:d=http://schemas.microsoft.com/expression/blend/2008
xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006
mc:Ignorable=d>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width=120/>
<ColumnDefinition Width=*/>
<ColumnDefinition Width=Auto/>
</Grid.ColumnDefinitions>
<TextBlock x:Name=pageTitle Text=Search Box Demo
Style={StaticResource HeaderTextBlockStyle}
Grid.Column=1
IsHitTestVisible=false TextWrapping=NoWrap
VerticalAlignment=Bottom Margin=0,0,30,728/>
<SearchBox Grid.Column=1 Height=35 Width=270 Margin=232,233,449,500
/>
</Grid>
</Page>

In Code Snippet 3, a text box and search box are added in the XAML page. When the user enters text to
search in the given search box and presses the Enter key, the search box will search and show the results.

Concepts

When the app is executed, the search box will be displayed in the app as shown in figure 6.7.

V 1.0 Aptech Limited

Session

6
Using Contracts, Print Settings, and Speech Synthesis

Figure 6.7: Output of Search Box Demo

6.1.2 Print Contract


The print contract is used to print the content of any app. Before developing the app the user must
register the print option. This registration will then allow this app to use print option. Your app uses the
print contract to communicate with the print platform. It provides the print content, and Windows 8
provides the print experience and the underlying infrastructure. After registration, the user has to add
the code given in Code Snippet 4 to register the PrintTask.
When adding print support to your app, there are two core elements you need to consider:

Providing the content to print

Changing the print settings that work best for your app
Code Snippet 4:
var PM = Windows.Graphics.Printing.PrintManager.getForCurrentView();

Concepts

After successful registration, the user must call PrintTaskRequested event to trigger the
printing task.

V 1.0 Aptech Limited

Session

6
Using Contracts, Print Settings, and Speech Synthesis

Code Snippet 5 shows creating a PrintManager and adding the PrintTaskRequested method.
Code Snippet 5:
private void Button_Click(object sender, RoutedEventArgs e)
{
var PM = Windows.Graphics.Printing.PrintManager.GetForCurrentView();
PM.PrintTaskRequested += PM_PrintTaskRequested;
}
void PM_PrintTaskRequested(Windows.Graphics.Printing.PrintManager
sender, Windows.Graphics.Printing.PrintTaskRequestedEventArgs args)
{
...
...
}

Code Snippet 5 creates an object called PM which is an instance of PrintManager. After creating the
PM object, an event handler is added to the object by adding a delegate PM_PrintTaskRequested.
This event handler will be activated when the user requests the Print contract to start printing.

6.1.3 Play To Contract


The Play To contract is basically used to streamline any audio or video. The user has to register at the
sourceRequested event in order to use the Play To contract. After successful registration, the user
receives a reference for PlayToManager, when getForCurrentView method is called.
Code Snippet 6 shows how to add MediaElement object in an app and how to set some of the parameters
of MediaElement.
Code Snippet 6:
<Page x:Class=MediaPlayTo.MainPage
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml

Concepts

xmlns:local=using:MediaPlayTo
xmlns:d=http://schemas.microsoft.com/expression/blend/2008
xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006
mc:Ignorable=d>
<Grid Background=White>

V 1.0 Aptech Limited

Session

6
Using Contracts, Print Settings, and Speech Synthesis

<MediaElement x:Name=VideoSource AutomationProperties.Name=VideoSource


Source=http://ie.microsoft.com/testdrive/Graphics/VideoFormatSupport/big_
buck_bunny_trailer_480p_baseline.mp4 HorizontalAlignment=Center
VerticalAlignment=Center Height=360 Width=640 AutoPlay=True
PosterSource=Assets/play.png IsLooping=True />
</Grid>
</Page>

In Code Snippet 6, a Media element is added to the design and its Name is set to VideoSource and
Source property is set to point to a media file located on the Internet. Along with this Height, Width,
AutoPlay, and other properties are also set.
When Code Snippet 6 is executed, output will be displayed as shown in figure 6.8.

Figure 6.8: Output of the Play To Contract

6.2 Print Functionality

Concepts

The user can print the content from any app using the Print charm. By default, apps will not support
a document to be printed from within an app. The user can print the pages only by registering for the
Print Contract through the Device charm shown in figure 6.9.

V 1.0 Aptech Limited

Session

6
Using Contracts, Print Settings, and Speech Synthesis

Figure 6.9: Device Charm


PrintManager helps to compose the document before printing. To print any document, the printer

must be added in the devices of Windows 8 using the Devices tab.

When CreatePrintTask method is called, the PrintTask object is created. At the time of creating
PrintTask, the user has to provide the content to be printed.
Note - PrintManager is not sharable between pages. If needed, use GetForCurrentView method
inside the OnNavigatedTo method.

6.2.1 Printing Single Page

Concepts

The user can print the document by setting the range or by giving the individual page number to print.
The user can also set the page orientation property or the page type to be printed as shown in figure
6.10.

V 1.0 Aptech Limited

Session

6
Using Contracts, Print Settings, and Speech Synthesis

Figure 6.10: Print Pages with Range

6.2.2 Printing Multiple Pages

Concepts

The user can print multiple pages by selecting the pages option while previewing the document. The user
can set a range at 1-5 or 1-5, 10-15 or all pages as shown in figure 6.11.

V 1.0 Aptech Limited

Session

6
Using Contracts, Print Settings, and Speech Synthesis

Figure 6.11: Print Multiple Pages

6.2.3 Paginating and Previewing the Document

Concepts

When the document is ready to print, the user must show the document preview so that the user can
change any settings or margins. The user can paginate while previewing the document as shown in figure
6.12.

Figure 6.12: Print Preview and Pagination of Document

V 1.0 Aptech Limited

Session

6
Using Contracts, Print Settings, and Speech Synthesis

6.2.4 Implementing In-App Printing


When a document is ready to print, the user selects the device through the Print Device charm.
Before this, the user has to ensure that the app is registered with PrintTaskRequested listener. Once
the app is registered with this listener, in-app printing is possible.

6.3 PDF Files


When the document is ready to print, the user selects the Devices charm and selects the printer to print
the file. If the user wants to save the printable document in the storage device for future reference, then
the user can select Print to PDF option. This will print the file to selected PDF printer rather than printing
to the printer device.

6.3.1 Integrating Contacts and Calendars


To import contacts and calendars, the user has to sign the app with their Live mail id. This allows the
contacts or calendars to be saved over the cloud. To get started, the user has to download and install the
LiveSDK. After installation, the user can call the reference by using the namespace Microsoft.Live.

Single Sign-on
Single sign-on is used to log in the users to their Microsoft account through devices. To use this
single sign-on feature in the Store app, the user must get an Authentication API from Microsoft.

6.3.2 Support PDF Files and Screenshots


As Windows 8 apps supports PDF files with various readers such as Adobe, Foxit, and so on, they also
allow to take screenshots of the screen. In desktop computers, it is easier to take a screenshot which
is most commonly done pressing the PrintScreen/PrtScn button. In tablets or mobile devices, these
screenshots can be taken by pressing the Home + Volume Up buttons together. This will take a screen
snapshot and allow saving it automatically.

Concepts

When taking the screenshots with PrtScn button or by pressing Home + Volume Up, the user can use the
Snipping tool. The Snipping tool allows cropping the selected screenshot. Figure 6.13 shows how you can
search for the Snipping tool.

Figure 6.13: Search for Snipping Tool


V 1.0 Aptech Limited

Session

6
Using Contracts, Print Settings, and Speech Synthesis

The Snipping tool is used to capture the screen in an easier way. The user has to select the New button
and drag the portion to be shot and save in the image formats.

6.3.3 Display PDF Documents in Your App


The PDF files can be opened only through an API. Windows.Data.Pdf is a new namespace which
is available in Windows 8 runtime API. Any PDF files can be opened by using a static method called
LoadFileFromAsync. This method allows the user to open a PDF file and read the contents of the
same, but it never allows you to view the file.
Note - By default, there are no pre-installed components to view any PDF files.

6.3.4 Integrating Speech Synthesis


Speech synthesis allows reading the text from the app. By using speech synthesis, it is possible to read
out the contents to the reader. A special voice can be set for reading. When a user types some text in the
app, the app reads out the contents to the reader. It is mostly helpful when the user do not wish to read
the contents himself/herself, instead just wishes to listen to the contents. For example, a user may want
to read the content of an email or a letter received by him/her. These speech synthesis functions can be
called through SpeechSynthesizer. If the developer wants the app to read the text entered by the
user, then he/she can use speech synthesizer in the app.
The code given in Code Snippet 7 shows how to create a MediaElement object and use

SpeechSynthesizer to read the given text.

Code Snippet 7:
private async Task fnSpeak()
{
MediaElement mediaElement = new MediaElement();
var synth = new Windows.Media.SpeechSynthesis.SpeechSynthesizer();
SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync(tbData.
Text);
mediaElement.SetSource(stream, stream.ContentType);
mediaElement.Play();

Concepts

return;
}
void media_CurrentStateChanged(object sender, RoutedEventArgs e)
{
if (this.media.CurrentState == Windows.UI.Xaml.Media.MediaElementState.
Paused)

V 1.0 Aptech Limited

Session

6
Using Contracts, Print Settings, and Speech Synthesis

{
this.btnTalkCon.IsEnabled = true;
this.media.CurrentStateChanged -= this.media_CurrentStateChanged;
}
}

In Code Snippet 7, objects of MediaElement, SpeechSynthesisStream, and SpeechSynthesizer


are created, Source property is set and Play() method is called. With the result, MediaElement
object will start playing the specified sound/video source using the synthesizer. The code will convert
the entered text to media stream using SynthesizeTextToStreamAsync function and renders the
content through the app. The output of the application is shown in figure 6.14.

Figure 6.14: Output for the Application when Executed


The following example shows the step-by-step procedure to create an application that accepts some text
from the user and reads the given text for him/her. In this example, the developer is making use of the
speech synthesizer provided by Microsoft. The user enters any text in the text box and when he/she clicks
Speak button, the text is read for the user.
Step 1: Create a blank new application.
Step 2: Design the form by writing the following Code Snippet 8.
The user can add the code given in Code Snippet 8 to the current application so that it can read the text
entered by the user in the TextBox. Here, MediaElement class is used to read the text and give the
output in the form of a voice.
Code Snippet 8:
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
xmlns:local=using:SpeechTest
xmlns:d=http://schemas.microsoft.com/expression/blend/2008

V 1.0 Aptech Limited

Concepts

<Page x:Class=SpeechTest.Talk

Session

6
Using Contracts, Print Settings, and Speech Synthesis

xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006
mc:Ignorable=d>
<Grid x:Name=LayoutRoot Background=ForestGreen
HorizontalAlignment=Left VerticalAlignment=Top Width=1356 Height=758>
<Button x:Name=btnTalkCon Content=Speak ToolTipService.ToolTip=Text
will be played Margin=613,489,0,231 Click=btnTalkCon_Click Grid.Row=1/>
<MediaElement Grid.Row=0 x:Name=media AutoPlay=False
CurrentStateChanged=media_CurrentStateChanged/>
<TextBox x:Name=tbData Margin=194,72,226,347
TextWrapping=Wrap AcceptsReturn=True
Text=Welcome to Text to Speak Demo FontSize=16
VerticalAlignment=Stretch
HorizontalAlignment=Stretch Grid.Row=1 />
</Grid>
</Page>

In the Code Snippet 8, a MediaElement, Button and a TextBox objects are added.
Step 3: Write the code given in Code Snippet 9 so as to speak the text entered in the TextBlock.
Code Snippet 9:
public sealed partial class Talk : Page
{
private SpeechSynthesizer s;
private bool disposed = false;
public Talk()
{
this.InitializeComponent();
}

Concepts

private async void btnTalkCon_Click(object sender, RoutedEventArgs e)


{
fnSpeak();
}

V 1.0 Aptech Limited

Session

6
Using Contracts, Print Settings, and Speech Synthesis

private async Task fnSpeak()


{
MediaElement mediaElement = new MediaElement();
var synth = new Windows.Media.SpeechSynthesis.SpeechSynthesizer();
SpeechSynthesisStream stream = await synth.
SynthesizeTextToStreamAsync(tbData.Text);
mediaElement.SetSource(stream, stream.ContentType);
mediaElement.Play();
return;
}
void media_CurrentStateChanged(object sender, RoutedEventArgs e)
{
if (this.media.CurrentState == Windows.UI.Xaml.Media.MediaElementState.
Paused)
{
this.btnTalkCon.IsEnabled = true;
this.media.CurrentStateChanged -= this.media_CurrentStateChanged;
}
}
}

The code will translate the text to stream and speak the text.

Concepts

Step 4: When the code is executed the screen will be displayed as shown in figure 6.15.

Figure 6.16: Output After Speak Button is Clicked

V 1.0 Aptech Limited

Session

6
Using Contracts, Print Settings, and Speech Synthesis

Concepts

After entering the text in the given textbox, if the user clicks Speak button, then the text in the given text
box will be read by converting to voice. This is automatically done by the speech synthesizer provided by
Microsoft in the MediaElement class.

V 1.0 Aptech Limited

Session

6
Using Contracts, Print Settings, and Speech Synthesis

6.4 Check Your Progress


1.

2.

3.

4.

(A) Printer

(C)

Print manager

(B)

(D)

Print function

Print contract

The ___________ is basically used to stream any mp3 or videos.


(A) Print contract

(C)

Search tool

(B)

(D)

Search box

Plan to contract

__________ takes control to compose the document while it is printing.


(A) Print function

(C)

Printer

(B)

(D)

Print file

Print contract

When the document is ready to print the user must have to make the document to be previewed so
that any change in _____________ can be rearranged.
(A) Styles and Margin

(C)

Font

(B)

(D)

Size

Format

________________ is used to log in the user to their Microsoft account through devices.
(A) Print functionality

(C)

Single sign on

(B)

(D)

Multiple sign in

Margin

Concepts

5.

The ________ is used to print the content of any app.

V 1.0 Aptech Limited

Session

6
Using Contracts, Print Settings, and Speech Synthesis

6.4.1 Answers
B

2.

3.

4.

5.

Concepts

1.

V 1.0 Aptech Limited

Session

6
Using Contracts, Print Settings, and Speech Synthesis

Summary
When the user moves the mouse on the right side of the screen, he/she can find the Search,
Share, Start, Device, and Settings options. These options are called as charms.

T he user has to write the code to print the page. The user can also set the page orientation
property and the page type to be printed.

Before printing any page from the app, the document must be registered with Print Contract.

I f the printable document is to be saved in the storage device for a reference, then the user can
select Print to PDF option to save.

indows.Data.Pdf, is a namespace for opening and reading PDF documents. It is available in the
W
Windows 8 runtime API. Use static method LoadFileFromAsync to open any PDF file.

Concepts

V 1.0 Aptech Limited

Session -7
Push Notification Services
Welcome to the Session, Push Notification Services.
This session explains communicating with the Windows Push Notification
Services (WNS), managing a Windows Notification Service Channel, requesting,
creating, and saving notifications.
In this Session, you will learn to:
Explain how to communicate using WNS
Describe Windows Notification Service Channel
Explain requesting, creating, and saving notifications

Session

7
Push Notification Services

7.1 Introduction to Push Notifications


Push notifications are notifications to the user whenever they are using the app. In Windows 8, Microsoft
has released Windows Push Notification Service (WNS). Windows Store app can use this facility to send
notifications to and from cloud server. The Windows Push Notification Services enables third-party
developers to send toast, tile, badge, and raw updates from their own cloud service. This provides a
mechanism to deliver new updates to your users in a power-efficient and dependable way.
Push notifications are of three types as follows:
Tile As the application is loaded this will modify the tile and notification is displayed. Tile
notifications can modify the appearance of game and application tiles that a phone user has
pinned to the Quick Launch area of their device. Tile notifications can specify a title, a count value,
and a background image that can be either a local or remote resource. Tiles in the Quick Launch
area respond to notifications regardless of whether the game is running or not. Games cannot
intercept tile notifications.

Toast To display a message to the user immediately, these notifications are used. Toast
notifications are short, text-based messages that appear to let a user know about transient data.
They consist of two strings of text, and appear at the top of the phones display. Clicking a toast
notification launches the associated application. While a game is running in the foreground, toast
messages received on its notification channel bypass the system pop-up user interface and are
routed directly to the game.

Raw Notifications Raw notifications are similar to tile and toast notifications, except they do not
have a particular display style or predefined payload format. The data contained in a raw
notification is determined by the sender, and the game running on the phone must understand
the content. As the underlying operating system does not handle raw notifications, the game for
which the notification is designed must be running in order to handle this type of notification. If
the game is not running, the notification is ignored by the phone.

Concepts

V 1.0 Aptech Limited

Session

7
Push Notification Services

7.1.1 Managing a WNS Channel


Push notifications can be enabled or disabled through the notification settings as shown in figure 7.1.

Figure 7.1: WNS Settings


The user can also set the notification display time by changing the Visual Options from PC Settings
Ease of Access Other Options, as shown in figure 7.2.

Concepts

Note - The default expiry date of badge notifications is three days.

Figure 7.2: WNS Notification Timeout Settings

V 1.0 Aptech Limited

Session

7
Push Notification Services

Silencing Notifications
Notifications will be displayed whenever there is any new mails, reminders, lock screen, and many
more. The notification service can be disabled or prolonged through PC settings. The user can click
the notification icon and set or change the idle time as shown in figure 7.3.

Figure 7.3: Windows Notification Settings

7.1.2 Communicating with the WNS


The process of Windows Notification Service Channel is as follows:
The app sends a request for the push notification channel.

The client request WNS to create a channel. As the channel is created, the client sends the URI
back to the app.

Then, the app sends the URI to the cloud to receive data.

This cloud server passes the received URI through the POST method to the WNS and WNS sends
the data in the form of notification.

Concepts

V 1.0 Aptech Limited

Session

7
Push Notification Services

Figure 7.4 shows the process of WNS Channel.

Figure 7.4: WNS Channel Process

Push Notifications

Concepts

Push notifications will be running as a service and will notify the messages. For example, if a user
receives any emails or reminders, these push notification will be processed and displayed as a
tile notification. The push notifications can be enabled by changing the Application settings in
Package.appxmanifest file as shown in figure 7.5.

Figure 7.5: Enable Notification in the App

V 1.0 Aptech Limited

Session

7
Push Notification Services

The app can send a request to the Windows Runtime through channel Universal Resource Identifier
(URI) and returns to service which stores the data/results and they can be used for displaying toasts,
tiles, or badges. The classical example for this notification is the Calendar app which makes a request to
the Windows runtime and receives the data. The notification channel will not be shared while sending
request to the server. When users have two devices and had installed the same apps on their devices, the
user receives two types of notifications.
Before developing the PushNotification, the user need not add any reference inside the app.
If there is any need for creating references, then the user has to call the Windows.Networking.
PushNotification namespace in the project.
The CreatePushNotificationChannelForApplicationAsync() method is used to create a new
channel, which returns a notification channel as PushNotificationChannel object.

Code Snippet 1 shows how to create a PushNotificationChannel.


Code Snippet 1:
PushNotificationChannel c = null;
try
{
c = await PushNotificationChannelManager.
CreatePushNotificationChannelForApplicationAsync();
var d = new MessageDialog(c.Uri);
d.ShowAsync();
}
catch (Exception ex)
{
// Channel creation failed
}

Push Notification Authentication

Step 1: Go to the following link:


https://appdev.microsoft.com/StorePortals/en-us/account/signup/start

V 1.0 Aptech Limited

Concepts

In order to receive notification from the cloud to the app, the user have to register their app in the
Store. To register, the user have to follow the following steps:

Session

7
Push Notification Services

Step 2: Click the Register now button as shown in figure 7.6.

Figure 7.6 Open the URL


Step 3: Then, login to the Development Center by providing the user credentials of Live/Hotmail
account as shown in figure 7.7.

Concepts

Figure 7.7 Login to Live/Hotmail

V 1.0 Aptech Limited

Session

7
Push Notification Services

Step 4: To submit the app, click Submit an app link on the left menu, as shown in figure 7.8.

Figure 7.8 Submit an App Link

Figure 7.9: Provide App Identification Details

V 1.0 Aptech Limited

Concepts

Step 5: After submitting the app, provide the app details such as pricing details, app name, and so
on as shown in figures 7.9 and 7.10.

Session

7
Push Notification Services

Figure 7.10: After Submission of the App


Step 6: After the identification of app, Microsoft provides a Package Security Identifier (SID) as
shown in figure 7.11.

Concepts

Figure 7.11: Create New Client Secret ID

V 1.0 Aptech Limited

Session

7
Push Notification Services

Step 7: Click Create a new client secret link to create a client secret code to authenticate the
notifications. Now, Windows provides an identity attribute which must be copied and placed inside
the package.appxmanifest file as shown in figure 7.12.

Figure 7.12: Authenticate the Service

7.1.3 Intercept Notifications for Running Apps


The user can develop the app to start/stop push notifications. When the app sends a request to the cloud
server and/or receives the response, it can be set to hide without showing any notifications. To intercept
the notification through the app, the user needs to write the code as shown in Code Snippet 2.
Code Snippet 2:
string c = null;
private async void OnPushNotification(PushNotificationChannel sender,
PushNotificationReceivedEventArgs e)
{
String nc = String.Empty;

{
case PushNotificationType.Badge:
nc = e.BadgeNotification.Content.GetXml();
break;

V 1.0 Aptech Limited

Concepts

switch (e.NotificationType)

Session

7
Push Notification Services

case PushNotificationType.Tile:
nc = e.TileNotification.Content.GetXml();
break;
case PushNotificationType.Toast:
nc = e.ToastNotification.Content.GetXml();
break;
case PushNotificationType.Raw:
nc = e.RawNotification.Content;
break;
}
e.Cancel = true;
}

Code Snippet 2 makes use of the OnPushNotification() method which identifies the type of
notification using NotificationType which is passed as a argument to switch.
When the code is executed, the service will check the notification type and hide the notification without
displaying to the user.

7.2 Service Request and Response Headers


This shows the process of request and response parameters while authenticating with WNS through the
app.

Access token request

Concepts

An HTTP request is sent to WNS to authenticate the cloud service and retrieve an access token in
return. The request is issued to the Fully Qualified Domain Name (FQDN) by using Secure Sockets
Layer (SSL).
https://login.live.com/accesstoken.srf

Request parameters
The cloud service submits these required parameters in the HTTP request body, using the

application/x-www-form-urlencoded format.

V 1.0 Aptech Limited

Session

7
Push Notification Services

Ensure that all parameters are URL encoded, as shown in table 7.1.

Parameter

grant_type
client_id

client_secret
scope

Type
Required
Required
Required
Required

Description
Always to client_credentials.
Package Security Identifier (SID) for your cloud service.
Secret key for cloud service.
Always to:

Windows: notify.windows.com

Windows Phone: notify.windows.com or


s.notify.live.net

Table 7.1: Parameters in the HTTP Header

Access token response


WNS authenticates the cloud service and if successful, responds with a 200 OK, including the
access token. Otherwise, WNS responds with an appropriate HTTP error code as described in the
OAuth 2.0 protocol draft.
An access token is returned in the HTTP response if the cloud service successfully authenticated.
This access token can be used in notification requests until it expires. The HTTP response uses the
application/json media type, as shown in tables 7.2 and 7.3.

Parameter

Type

access_token Required
token_type

Optional

Description
It is the access token that is returned by the cloud
service when a notification is sent.
Always returned as bearer.

Table 7.2: HTTP Response Parameters


Code Snippet 3 shows how to receive the token if the cloud service is successfully authenticated.
Code Snippet 3:
HTTP/1.1 200 OK
Cache-Control: no-store
Content-Length: 400
{
access_token:AesdWersdQEddd/c+Cftecvfyr62sdfewr61dst13ALoj=,
token_type:bearer
}

V 1.0 Aptech Limited

Concepts

Content-Type: application/json

Session

7
Push Notification Services

HTTP Response Code

Description

200 OK
400 Bad Request

WNS accepts the notification.


Headers specified with incorrect data or clash with another
header.
No valid authentication ticket from cloud. OAuth ticket may
be invalid.
The cloud service is not authorized to send a notification to
this URI even they are authenticated.
Channel URI is in valid or unknown by WNS.
Invalid method.
Cloud service exceeded its control limit.
The channel expired.
Notification payload exceeds.
Internal failure produced notification delivery to fail.
Server is currently unavailable.

401 Unauthorized
403 Forbidden
404 Not Found
405 Method Not Allowed
406 Not Acceptable
410 Gone
413 Request Entity Too Large
500 Internal Server Error
503 Service Unavailable

Table 7.3: HTTP Response Code

7.3 Channel URI


A Channel URI is a compressed form of a resource in the app over the Intranet or Internet. The Channel
URI handles parsing, comparing, and combining of the string passed to it. Channel URI is available to
the users with its properties and methods. The Channel URI class is read-only. In order to make it to
be updatable the user has to make use of the URIBuilder class. URIBuilder is used to update URI
Channel.
Proper URIs (for example, /demo/home.html) must be given by the full URL address so that it can
connect to the cloud easily. Absolute URI can be converted to Relative by using the MakeRelative
method, whenever required. The URI strings will not be escaped when the string is a formatted properly
including a scheme identifier. In the escaped encoding, this URI returns acknowledgement, with all values
in Unicode characters.

Concepts

To put the URI in acknowledged form, the URI does the following steps:

Changes the URI to lowercase.

Changes the host name to lowercase.

If the host is IPv6, the acknowledgement IPv6 address is called.

Eliminates default port numbers.

Acknowledges the path for ordered URIs by compressing orders such as /./, /../, //, including

V 1.0 Aptech Limited

Session

7
Push Notification Services

escaped depictions.
Note - There are some structures which escaped depictions are not compacted.

For hierarchical URIs, if the host address is not terminated with a forward slash (/), it is automatically
added by URI class.
Code Snippet 4 shows a URI constructor for the http scheme.
Code Snippet 4:
Uri u = new Uri(http://appUrl/%2E);
Console.WriteLine(u.AbsoluteUri);
Console.WriteLine(u.PathAndQuery);

When this code is executed, the output will be compressed and displayed as follows:
http://appUrl/

Code Snippet 5 shows an example of URI constructor for FTP address.


Code Snippet 5:
Uri u = new Uri(ftp://appUrl/%2E);
Console.WriteLine(u.AbsoluteUri);
Console.WriteLine(u.PathAndQuery);

When this code is executed, it returns the following output with the escaped sequence and not compacted.
ftp://appUrl/%2E/%2E
Note - Some reserved characters might still be escaped in the output of the ToString method.

Code Snippet 6 shows how to get a Channel URL and how to set the expiry date for the same.
Code Snippet 6:
try
{

// Try to get Channel URI

// Get Expiry time of Channel Uri


var ET = c.ExpirationTime;
// Set Channel Expiry Date

App.ChannelExpiryDate = ExpirationTime.DateTime.ToUniversalTime();
}

catch (Exception ex)


V 1.0 Aptech Limited

Concepts

c = await PushNotificationChannelManager.
CreatePushNotificationChannelForApplicationAsync();

Session

7
Push Notification Services

{
MessageDialog errormsg = new MessageDialog(
string.Format(SHK018: Unable to create PushNotificationChannel.\nException:
{0},
ex.Message));
var ignoreAsyncOpResult = errormsg.ShowAsync();

Concepts

V 1.0 Aptech Limited

Session

7
Push Notification Services

7.4 Check Your Progress


1.

2.

3.

4.

(A) Badge

(C)

Tile

(B)

(D)

Channel

Toast

The notification service can be silenced through __________.


(A) Settings

(C)

PC settings

(B)

(D)

Mobile settings

Notification settings

The push notifications can be enabled by changing the ________________ file application settings.
(A) Package/appxmanifest

(C)

Package\appxmanifest

(B)

(D)

Package<appxmanifest>

package.appxmanifest

CreatePushNotificationChannelForApplicationAsync method is used to create a

_________.

(A) New channel

(C)

Settings

(B)

(D)

Source

Channel

An _________ request is sent to WNS to authenticate the cloud service and retrieve an access
token in return.
(A) HTPP

(C)

HTP

(B)

(D)

HTTP

HPPT

Concepts

5.

____________ will display an overlay on the tile.

V 1.0 Aptech Limited

Session

7
Push Notification Services

7.4.1 Answers
A

2.

3.

4.

5.

Concepts

1.

V 1.0 Aptech Limited

Session

7
Push Notification Services

Summary
Push notifications are automatic notifications sent to the user whenever they are using the app.

Notifications will be displayed whenever there is any new mails, reminders, lock screen, and many
more.

The app can send a request the Windows Runtime through channel URI and returns to service
which stores the data/results and they can be used for displaying toasts, tiles, or badges.

When the app sends a request to the cloud server or receives the response, it can be hidden or
disabled without showing any notifications.

WNS authenticates the cloud service and if successful, responds with a response code 200 OK,
including the access token.

Absolute URI can be converted to Relative by using the MakeRelative method, whenever required.

Concepts

V 1.0 Aptech Limited

Session -8
Media Capturing
Welcome to the Session, Media Capturing.
This Session introduces you to media capturing in Windows Store apps. The
session explores the various classes and enumerations defined in the
Windows.Media.Capture namespace.
In this Session, you will learn to:
Define and describe MediaElement class
Describe the CameraCaptureUI class
Explain the MediaCapture namespace and members of namespace
Define and explain the Devices.Enumeration namespace

Session

8
Media Capturing

8.1 Media Element


To play audio or video inside the app, the user has to use MediaElement class. To control media
playback these MediaElement provides various methods, properties, and events. The user has to
set AreTransportControlsEnabled to be true in order to use the MediaElement. Media
elements can set the Source property for any audio or video files. There is an AutoPlay property which
can make the media to play in a loop. To call these media element in the app, the user has to write the
code as given in Code Snippet 1.
Code Snippet 1:
<MediaElement AutoPlay=True Source=Media/myvideo.mp4 />

To create a Store app which can play any media file, the user has to create a new blank app and write the
code as given in Code Snippet 2 in the Mainpage.XAML.cs. The code explains that the app will play
the media file as the app is initiated.
Code Snippet 2:
namespace UsingMediaElement
{
public sealed partial class MainPage : Page
{
DispatcherTimer p = new DispatcherTimer();
public MainPage()
{
this.InitializeComponent();
ME _ Play.MediaOpened += (Object s, RoutedEventArgs args) =>
{
ME _ Play.Play();
};
ME _ Play.MediaEnded += (Object s, RoutedEventArgs args) =>
{
};
ME _ Play.CurrentStateChanged += (Object s, RoutedEventArgs args) =>
{
if (ME _ Play.CurrentState == MediaElementState.Playing)

V 1.0 Aptech Limited

Concepts

ME _ Play.Stop();

Session

Media Capturing
{
p.Start();
}

else
{

p.Stop();
}
};
p.Tick += (Object s, Object args) =>
{
};

}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
}

After initiating, write the code as given in Code Snippet 3 to load the media file by setting the source.
Code Snippet 3:
private void Page _ AfterLoad(object sender, RoutedEventArgs e)
{
ME _ Play.Source = new Uri(http://englishsong.in/glory-data/downloadfile/13926/
Crowded _ (John _ Frusciante)(www.englishsong.in).mp3, UriKind.
RelativeOrAbsolute);
if (ME _ Play.CurrentState == MediaElementState.Playing)
{
ME _ Play.Pause();
}
else

Concepts

{
ME _ Play.Play();
}
}
}
}

V 1.0 Aptech Limited

Session

8
Media Capturing

8.1.1 Windows.Media.Capture Namespace


The Media.Capture namespace holds many classes with different features, some of the classes are
listed in table 8.1.
Class
CameraCaptureUI
CameraCaptureUIPhotoCaptureSettings
CameraCaptureUIVideoCaptureSettings
CameraOptionsUI
CapturedFrame
CapturedPhoto
MediaCapture
MediaCaptureFailedEventArgs
MediaCaptureFocusChangedEventArgs
MediaCaptureInitializationSettings
MediaCaptureSettings

Description
Used to capture audio, video, and photos
in a full screen mode.
Used to capture photos from the device
this class is used.
Used to capture videos from the device
this class is used.
Used to set options for photos, audio
recordings, and videos to capture.
Used to represent a captured video
frame.
Used to represent a photo captured
from the webcam.
Used to capture photos, audio, and
videos from webcam.
Used to provide data for the
MediaCapture.Failed event.
Used to provide data for the
FocusChanged event.
Used to set initialization settings for the
MediaCapture.
Used to contain the read-only
configuration settings.

Table 8.1: Classes Available in Windows.Media.Capture Namespace

Sometimes, the user wants to get the devices which are available in the system. The user has to ensure
the devices such as camera and microphone are connected or enabled in the system. Windows.
Devices.Enumeration namespace exposes the DeviceInformation class, which provide two
ways of enumeration through two static functions to retrieve the device information.

V 1.0 Aptech Limited

Concepts

8.2 Enumerating and Discovering Device Capabilities

Session

8
Media Capturing

Code Snippet 4 shows how to create a function to monitor all the devices connected/emulated in the
system.
Code Snippet 4:
async void fnMonitor(object sender, RoutedEventArgs eventArgs)
{
try
{
d = Window.Current.CoreWindow.Dispatcher;
w = DeviceInformation.CreateWatcher();
w.Added += watcher _ Added;
w.Removed += watcher _ Removed;
w.Updated += watcher _ Updated;
w.EnumerationCompleted +=
watcher _ EnumerationCompleted;
w.Stopped += watcher _ Stopped;
w.Start();
lblOutput.Text = Enumeration Process Started.;
}
catch (ArgumentException)
{
lblOutput.Text = Failed;
}

Concepts

After emulation process is completed, the emulation has to be stopped by writing the code given in Code
Snippet 5.

V 1.0 Aptech Limited

Session

8
Media Capturing

Code Snippet 5:
async void fnMonitorEnd(object sender, RoutedEventArgs eventArgs)
{
try
{
if (w.Status == Windows.Devices.Enumeration.DeviceWatcherStatus.Stopped)
{
s = Enumeration Already Stopped.;
}
else
{
w.Stop();
}
}
catch (ArgumentException)
{
lblOutput.Text = Failed;
}
}

To display the device or emulation inside the system, the user has to write the code as shown in Code
Snippet 6.
Code Snippet 6:
async void DisplayDeviceInterface(DeviceInformation deviceInterface)
{
var name = deviceInterface.Name;
var isEnabled = IsEnabled: + deviceInterface.IsEnabled;
var item = id + is \n + name + and \n + isEnabled;
lstResult.Items.Add(item);
}

V 1.0 Aptech Limited

Concepts

var id = Id: + deviceInterface.Id;

Session

8
Media Capturing

8.3 Using CameraCaptureUI Class


If the user wants to capture any photo, audio or video, the best way to do it is by calling the WinRT API.
The user has to mention some configuration settings so that the system itself can adjust with the given
configuration.
To interact with a webcam, there are two ways as follows:

By coding, the user can control the WinRT API to complete the control flow of operations.

The user can manage the secondary camera by using the delivered user interface.

CameraCaptureUI performs the capture through advance Windows UI built-in features. To get the
complete UI experience, the CameraCaptureUI uses CaptureElement. The CameraCaptureUI API

allows users to take photos and audio/video recording. Video stream as well as audio stream can be
recorded as single stream by using any webcam.
Note: CameraCaptureUI API doesnt allow user to handle or record audio and video separately. It
records both stream as a single stream. There is no separation for audio or video recordings.

Other way to take pictures or videos is by using the CameraCaptureUI API and allowing the system to
manage the configurations and settings.

8.4 Using MediaCapture Namespace


VideoDeviceController has a MediaCapture to adjust the configuration programmatically.
These configurations include brightness, contrast, exposure, white balance, hue, saturation, and backlight
compensation. There are many advanced camera devices which have a facility to focus, zoom, roll, and
tilt. MediaCapture and MediaElement classes can be used to add effects to video recordings.
AddEffectAsync and ClearEffectAsync methods can be used for MediaElement effects.

Transcoding
Using BitmapDecoder and BitmapEncoder, transcoding can be done. Windows Media APIs
allows transcoding of audio and video files. Transcoding is used for conversion of any digital media
files to any format. The user has to use the code as shown in Code Snippet 7 for transcoding.

Concepts

Code Snippet 7:
async void TranscodeVideoFile()
{
Windows.Storage.StorageFile src;
Windows.Storage.StorageFile d;

V 1.0 Aptech Limited

Session

8
Media Capturing

var o = new Windows.Storage.Pickers.FileOpenPicker();


o.SuggestedStartLocation =
Windows.Storage.Pickers.PickerLocationId.VideosLibrary;
o.FileTypeFilter.Add(.wmv);
o.FileTypeFilter.Add(.mp4);
src = await o.PickSingleFileAsync();
var s = new Windows.Storage.Pickers.FileSavePicker();
s.SuggestedStartLocation =
Windows.Storage.Pickers.PickerLocationId.VideosLibrary;
s.DefaultFileExtension = .mp4;
s.SuggestedFileName = New Video;
s.FileTypeChoices.Add(MPEG4, new string[] { .mp4 });
d = await s.PickSaveFileAsync();
// Method to perform the transcoding.
TranscodeFile(src, d);
}

To play the media file

Concepts

Step 1: Create New Blank (XAML) application as shown in figure 8.1.

V 1.0 Aptech Limited

Session

8
Media Capturing

Figure 8.1: Select New Blank (XAML) Application


Step 2: Add code given in Code Snippet 8 to MainPage.xaml design page.
Code Snippet 8:
<Page
x:Class=UsingMediaElement.MainPage
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml

Concepts

xmlns:local=using:UsingMediaElement
xmlns:d=http://schemas.microsoft.com/expression/blend/2008
xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006
mc:Ignorable=d Loaded=Page_AfterLoad>
<Grid Background={StaticResource ApplicationPageBackgroundThemeBrush}>

V 1.0 Aptech Limited

Session

8
Media Capturing

<Image Source=assets/play.png Width=150 />


<MediaElement Name=ME_Play HorizontalAlignment=Left Height=100
Margin=563,267,0,0 VerticalAlignment=Top Width=100/>
</Grid>
</Page>

Step 3: Add code given in Code Snippet 9 to add control to play the media file when the page is
loaded.
Code Snippet 9:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace UsingMediaElement
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();

V 1.0 Aptech Limited

Concepts

DispatcherTimer p = new DispatcherTimer();

Session

8
Media Capturing
ME_Play.MediaOpened += (Object s, RoutedEventArgs args) =>
{
ME_Play.Play();
};

Step 4: When the user executes the application the output is displayed as shown in figure 8.2.

Figure 8.2: Output of the Application Plays the Audio

Device Enumerator

Concepts

Device enumerator allows the user to create a list of all the devices that are connected to the current system. This can be used to build a list of user interface through which the user can select
which microphone, speaker, printer, or any other machine he/she wants to connect to. Discovery of
the devices and notifications when these devices are either connected or disconnected is possible
with the device enumerator.

V 1.0 Aptech Limited

Session

8
Media Capturing

Device Monitor
The following application, Device Monitor, demonstrates how to use the Device Enumerators to
generate the list of all the devices that are connected to the current system.
Step 1: Create a blank new application with name DeviceTest as shown in figure 8.3.

Figure 8.3: Create a Blank New Application


Step 2: Add Code Snippet 10 to MainPage.xaml file to design the page.
Code Snippet 10:
<Page
Background=CadetBlue
x:Class=DeviceTest.MainPage
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
xmlns:local=using:DeviceTest
xmlns:d=http://schemas.microsoft.com/expression/blend/2008

V 1.0 Aptech Limited

Concepts

xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation

Session

8
Media Capturing
xmlns:mc=http://schemas.openxmlformats.org/markupcompatibility/2006
mc:Ignorable=d>
<Grid x:Name=ContentRoot Margin=10 Background=CadetBlue >
<ScrollViewer VerticalScrollBarVisibility=Auto HorizontalScrollBarVisi
bility=Auto Grid.Row=1 ZoomMode=Disabled>
<StackPanel x:Name=SPPnl>
<TextBlock Text=Device Monitor Margin=0,25,0,20 FontSize=26 />
<Button x:Name=btnMonitor Content=Monitor Devices Click=fnMonitor />
<Button x:Name=btnStop Content=Stop Click=fnMonitorEnd />
<TextBlock Text=Enumeration Results Margin=0,25,0,20 />
<StackPanel x:Name=SPResult>
<TextBlock Name=lblOutput />
<ListBox Name=lstResult IsEnabled=False BorderThickness=0 />
</StackPanel>
</StackPanel>
</ScrollViewer>
</Grid>
</Page>

Concepts

Step 3: Add Code Snippet 11 to monitor the devices or emulators available in the system.

V 1.0 Aptech Limited

Session

8
Media Capturing

Code Snippet 11:


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Devices.Enumeration;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/
fwlink/?LinkId=234238
namespace DeviceTest
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
{
this.InitializeComponent();
}

V 1.0 Aptech Limited

Concepts

public MainPage()

Session

Media Capturing

Windows.UI.Core.CoreDispatcher d;
public static DeviceWatcher w = null;
public static int count = 0;
public static DeviceInformation[] i = new DeviceInformation[1000];
public static bool EC = false;
public static string s = null;
//A function to create and set delegates to handle addition, removal
// and updation events of Device Monitor class
async void fnMonitor(object sender, RoutedEventArgs eventArgs)
{
try
{
d = Window.Current.CoreWindow.Dispatcher;
w = DeviceInformation.CreateWatcher();
w.Added += watcher_Added;
w.Removed += watcher_Removed;
w.Updated += watcher_Updated;
w.EnumerationCompleted +=
watcher_EnumerationCompleted;
w.Stopped += watcher_Stopped;
w.Start();
lblOutput.Text = Enumeration Process Started.;
}
catch (ArgumentException)

Concepts

{
lblOutput.Text = Failed;
}
}

V 1.0 Aptech Limited

Session

8
Media Capturing

//This method is called when user wish to end the processing of


//enumerating the Monitor class
void fnMonitorEnd(object sender, RoutedEventArgs eventArgs)
{
try
{
if (w.Status ==
Windows.Devices.Enumeration.DeviceWatcherStatus.Stopped)
{
s = Enumeration Already Stopped.;
}
else
{
w.Stop();
}
}
catch (ArgumentException)
{
lblOutput.Text = Failed;
}
}
{
s = Enumeration Already Stopped.;
}
else

Concepts

{
w.Stop();
}}

V 1.0 Aptech Limited

Session

8
Media Capturing

catch (ArgumentException)
{
lblOutput.Text = Failed;
}
}
//When the watcher is added this function will be called
async void watcher_Added(DeviceWatcher sender, DeviceInformation
deviceInterface)
{
i[count] = deviceInterface;
count += 1;
if (EC)
{
await d.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
DisplayDeviceInterfaceArray();
});
}
}
async void watcher_Updated(DeviceWatcher sender, DeviceInformationUpdate
devUpdate)
{
int count2 = 0;

Concepts

foreach (DeviceInformation deviceInterface in i)


{
if (count2 < count)
{

if (i[count2].Id = = devUpdate.Id)

V 1.0 Aptech Limited

Session

8
Media Capturing

{
//Update the element.
i[count2].Update(devUpdate);
}
}
count2 += 1;
}
await d.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
lblOutput.Text = Enumeration updated. ;
DisplayDeviceInterfaceArray();
});
}
//This method is called when watcher is removed
async void watcher_Removed(DeviceWatcher sender, DeviceInformationUpdate
devUpdate)
{
int count2 = 0;
//Convert interfaces array to a list (IList).
List<DeviceInformation> interfaceList = new List<DeviceInformation>(i);
foreach (DeviceInformation deviceInterface in i)
{
if (count2 < count)
{

Concepts

if (i[count2].Id == devUpdate.Id)
{
//Remove the element.

V 1.0 Aptech Limited

Session

Media Capturing

interfaceList.RemoveAt(count2);
}
}
count2 += 1;
}
//Convert the list back to the interfaces array.
i = interfaceList.ToArray();
count -= 1;
await d.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
lblOutput.Text = Enumeration device removed. ;
DisplayDeviceInterfaceArray();
});
}
//This method will be called when the Enumeration task is completed
async void watcher_EnumerationCompleted(DeviceWatcher sender, object args)
{
EC = true;
await d.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
lblOutput.Text = Enumeration complete. ;
DisplayDeviceInterfaceArray();
});
}
async void watcher_Stopped(DeviceWatcher sender, object args)

Concepts

{
if (w.Status ==
Windows.Devices.Enumeration.DeviceWatcherStatus.Aborted)
{

V 1.0 Aptech Limited

Session

8
Media Capturing

s = Enumeration stopped;
else if (w.Status ==
Windows.Devices.Enumeration.DeviceWatcherStatus.Stopped)
{
s = Enumeration stopped;
}
}
//This method creates an array of Device information
async void DisplayDeviceInterfaceArray()
{
lstResult.Items.Clear();
int count2 = 0;
foreach (DeviceInformation deviceInterface in i)
{
if (count2 < count)
{
DisplayDeviceInterface(deviceInterface);
}
count2 += 1;
}
}
//this method will display the list of all the devices

async void DisplayDeviceInterface(DeviceInformation deviceInterface)


{
var id = Id: + deviceInterface.Id;

V 1.0 Aptech Limited

Concepts

//Enumerated by the Device monitor class

Session

8
Media Capturing

var name = deviceInterface.Name;


var isEnabled = IsEnabled: + deviceInterface.IsEnabled;
var item = id + is \n + name + and \n + isEnabled;
lstResult.Items.Add(item);
}
}
}

In the code, an empty page is created that can be used on its own or navigated to within a Frame. A
function to create and set delegates to handle addition, removal, and updation events of DeviceMonitor
class, nMonitorEnd() method is called when the user wishes to end the processing of enumerating the
Monitor class. When the watcher is added, the watcher_Added() function will be called. The method
DisplayDeviceInterfaceArray() creates an array of device information and list of devices will be
shown as demonstrated in figure 8.4.

Figure 8.4: Output of Device Monitor Application


Step 4: Click the Monitor Device button. The screen displays the results as shown in figure 8.5.

Concepts

V 1.0 Aptech Limited

Session

8
Media Capturing

Concepts

Figure 8.5: Output after the Monitor Device Button is Clicked

V 1.0 Aptech Limited

Session

8
Media Capturing

8.5 Check Your Progress


1.

The user has to set AreTransportControlsEnabled to be true in order to use the


___________.
(A) Windows Media APIs
(B)

2.

3.

MediaCapture

(D)

CameraCaptureUI

(A) Device

(C)

Audio

(B)

(D)

Windows Media

AutoPlay

The ___________ namespace holds many classes with different features.

(B)

media.Capture

(C)

Media

(D)

Media.Capture

Windows.Devices.Enumeration namespace exposes the ____________ class.


(A) DeviceInformation

(C)

Device.Information

deviceInformation

(D)

DeviceInformation.Enums

(B)

____________ is used for conversion of any digital media files to any format.
(A) MediaCapture

(C)

Windows UI

(B)

(D)

Transcoding

Media APIs

Concepts

5.

MediaElement

There is an __________ property which can make the media to play in a loop.

(A) MediaCapture

4.

(C)

V 1.0 Aptech Limited

Session

8
Media Capturing

8.5.1 Answers
A

2.

3.

4.

5.

Concepts

1.

V 1.0 Aptech Limited

Session

8
Media Capturing

Summary
The user must use MediaElement class to play audio or video inside the app.

indows.Devices.Enumeration namespace exposes the DeviceInformation class, which provide


W
two ways of enumeration through static functions to retrieve the device information.

ameraCaptureUI performs the capture through advanced Windows UI built-in features. To get
C
the complete UI experience, the CameraCaptureUI uses CaptureElement.

MediaCapture and MediaElement can be used to add effects.

Media APIs such as AddEffectAsync and ClearEffectsAsync methods can be used for
MediaElement effects.

Windows Media APIs allows transcoding of audio and video files.

Concepts

V 1.0 Aptech Limited

S-ar putea să vă placă și