Documente Academic
Documente Profesional
Documente Cultură
Apps Development - I
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:
The detailed instructional material Training aids, Learner material, reference material, project
guidelines, etc.- are then developed. Rigorous quality checks are conducted at every stage.
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.
*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.
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.
2.
3.
4.
Storage Mechanisms
5.
6.
7.
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
Windows 8 or higher
Concepts
Session
1
Windows Store Apps Essentials
Metro UI Design
Windows Store
Family Safety
Picture Password
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.
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.
Concepts
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.
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.
Session
1
Windows Store Apps Essentials
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
yy
yy
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.
Session
1
Windows Store Apps Essentials
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.
Concepts
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.
2.
Create a new project using File New Project Blank App (XAML).
3.
4.
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.
Session
1
Windows Store Apps Essentials
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.
3.
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
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.
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
Session
1
Windows Store Apps Essentials
Create a blank application by selecting File New Project Blank App (XAML).
2.
3.
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/>
Concepts
Session
1
Windows Store Apps Essentials
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.
Session
3.
1
Windows Store Apps Essentials
Concepts
Session
1
Windows Store Apps Essentials
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.
Session
1
Windows Store Apps Essentials
Create a blank application by selecting File New Project Blank App (XAML).
2.
3.
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.;
}
}
Concepts
Session
1
Windows Store Apps Essentials
2.
Concepts
1.
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.
Concepts
4.
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.
Concepts
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>
Concepts
Session
1
Windows Store Apps Essentials
2.
Add two pages named Navigate1.xaml and Navigate2.xaml, using the option as shown in figure
1.17.
Concepts
1.
Session
3.
1
Windows Store Apps Essentials
Design the page by creating two buttons inside MainPage.xaml as shown in figure 1.18.
5.
Concepts
{
this.Frame.Navigate(typeof(Navigate1), null);
}
private void Button2_Click(object sender, RoutedEventArgs e)
{
this.Frame.Navigate(typeof(Navigate2), null);
}
Session
1
Windows Store Apps Essentials
7.
Concepts
Session
1
Windows Store Apps Essentials
9.
Concepts
this.Frame.Navigate(typeof(MainPage), null);
}
Session
1
Windows Store Apps Essentials
When the page is loaded, the rectangle appears by default, as shown in figure 1.21.
Concepts
Session
1
Windows Store Apps Essentials
Concepts
AutoReverse: When the key frame reaches the end of the animation. Then, it repeats the
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
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.
Concepts
</Storyboard>
Session
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
Session
1
Windows Store Apps Essentials
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.
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
Session
1
Windows Store Apps Essentials
...
...
<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
Concepts
Session
Border.ChildTransitions
yy
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
yy
Popup.ChildTransitions
yy
SettingsFlyoutTemplateSettings.ContentTransitions
yy
such
Transformation
Consider an example that shows how to transfer data from one page to another.
1.
2.
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}>
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.
Concepts
<Page x:Class=navigation.page2
Session
5.
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));
}
Session
1
Windows Store Apps Essentials
2.
3.
(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
4.
(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.
(C)
Session
1
Windows Store Apps Essentials
1.4.1 Answers
A
2.
3.
4.
5.
Concepts
1.
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.
Concepts
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
Concepts
1. Open Control Panel, click Language and Region, and navigate to Language.
Session
2
Windows Store UI Localization
Concepts
Note - For each app, implementing localization creates a new assembly namely, Hub, which has the
local language specifications.
Session
2
Windows Store UI Localization
Concepts
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
more images.
Session
2
Windows Store UI Localization
class that allows the user to customize the date and time when the user develops an app.
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.
Concepts
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
CurrencyFormatter
yy
PermilleFormatter
yy
DecimalFormatter
yy
PercentFormatter
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.
Session
2
Windows Store UI Localization
yy
yy
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.
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.
Concepts
Session
2
Windows Store UI Localization
After installing the Toolkit, the following steps must be performed for enabling Multilingual Toolkit.
1.
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.
Now, select Add translation languages from the Project menu to add multiple languages. This is
shown in figure 2.8.
Concepts
4.
Session
2
Windows Store UI Localization
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.
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.
Session
Concepts
When the application is executed, the output will appear as shown in figure 2.11.
Session
2
Windows Store UI Localization
Figure 2.12: The Value Received from the Resource File (.resw)
Concepts
Session
2
Windows Store UI Localization
{
get;
}
{
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.
Concepts
Session
2
Windows Store UI Localization
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
Session
2
Windows Store UI Localization
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)
(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.
Session
2
Windows Store UI Localization
2.3.1 Answers
A
2.
3.
4.
Concepts
1.
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
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
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
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.
Concepts
2.
Session
33
Concepts
3.
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.
3.1.2
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.
Session
33
Concepts
When the user develops an app with a basic splash screen, the output will be as shown in figure 3.8.
Session
3
Adding Splash Screens and Branding to Apps
Concepts
Session
33
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>
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>
Session
33
</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
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.
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
Session
33
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
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>
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)
{
Session
33
// 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();
Concepts
Session
3.1.3
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
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
Session
33
3.2.1
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.
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
yy
Gallery description
Navigation must be present at the top of the app, which makes the app to navigate to
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
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
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.
Session
33
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
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.
Concepts
Figure 3.13 shows the application of Visual Asset Settings tab. This tab will have the image assets of an
app.
Session
3
Adding Splash Screens and Branding to Apps
Concepts
Session
33
2.
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
Concepts
(A)
(B)
Session
3
Adding Splash Screens and Branding to Apps
3.3.1 Answers
A
2.
3.
4.
5.
Concepts
1.
Session
33
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
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
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
Concepts
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.
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.
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.
Open a database.
yy
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
The code in Code Snippet 1 explains the process of creating and using IndexedDB database.
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
};
Concepts
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
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.
Concepts
Session
4
Storage Mechanisms
a service.
Concepts
Session
4
Storage Mechanisms
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)
{ ... }});
Concepts
The data with larger size can be stored inside the cloud using the code.
Session
4
Storage Mechanisms
Concepts
1.
Session
2.
4
Storage Mechanisms
Search for Q42. Then, install the Q42.WinRT package as shown in figure 4.5.
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);
Concepts
Session
Storage Mechanisms
var p = await JsonConvert.DeserializeObjectAsync(r);
return p;
});
this.DefaultViewModel[Groups] = r.photos.photo;
}
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)
{
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();
}
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
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)
Concepts
Session
4
Storage Mechanisms
{
this.NotifyUserFileNotExist();
}
private void NotifyUserFileNotExist()
{
lblRemark.Text = The file not found;
}
private void ResetScenarioOutput()
{
this.lblRemark.Text = ;
this.txtRemark.Text = ;
}
Concepts
EntryPoint=FileManipulation.App>
<m2:VisualElements
DisplayName=FileManipulation
Square150x150Logo=Assets\Logo.png
Square30x30Logo=Assets\SLogo.png
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.
Concepts
Session
4
Storage Mechanisms
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
Session
4
Storage Mechanisms
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
(C)
(B)
(D)
Concepts
4.
Session
4
Storage Mechanisms
4.5.1 Answers
B
2.
3.
4.
Concepts
1.
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.
Concepts
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.
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.
Concepts
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.
2.
3.
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.
Session
5
Working with Controls
Figure 5.3 also shows Property window on the screen after the TextBlock is dragged and dropped.
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.
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.
Concepts
Higher Resources
Resource Dictionaries
User Controls
Custom Controls
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>
Concepts
</StackPanel.Resources>
Session
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.
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
User Controls
The user can create their own controls using the User Control Templates. A user control is a layout
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.
Custom Control
User Control
Concepts
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.
Concepts
2.
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.
Concepts
</Grid>
Session
5
Working with Controls
When the user executes the app, the output will be displayed as shown in figure 5.7.
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
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>
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.
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 />
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>
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.
2.
Add your custom control using the Add New Item template wizard as shown in figure 5.12.
Concepts
1.
Session
5
Working with Controls
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.
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!
Session
5
Working with Controls
this.DefaultStyleKey = typeof(HelloCustomControl);
}
public bool Blink {
get { return (bool)GetValue(BlinkProperty); }
set { SetValue(BlinkProperty, value); }
}
public static readonly DependencyProperty BlinkProperty =
DependencyProperty.Register(
Blink,
typeof(bool),
typeof(HelloCustomControl),
ed)
)
);
private DispatcherTimer __timer = null;
//To set the time
{
get
{
if (__timer == null)
{
Concepts
Session
5
Working with Controls
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
}
}
}
Session
5
Working with Controls
Concepts
Session
5
Working with Controls
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
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();
}
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.
Session
5
Working with Controls
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.
Session
5
Working with Controls
Concepts
using System.Threading.Tasks;
Session
{
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.
Session
5
Working with Controls
Step 3: Select the file created in previous example MyWinRtComponent.winmd as shown in figure 5.16.
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.
Session
5
Working with Controls
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;
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.
Concepts
Session
5
Working with Controls
Concepts
Then, the user can design their own user control as shown in figure 5.19.
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>
Concepts
Session
5
Working with Controls
2.
3.
4.
(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.
Session
5
Working with Controls
5.5.1 Answers
A
2.
3.
4.
5.
Concepts
1.
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
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
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.
Session
6
Using Contracts, Print Settings, and Speech Synthesis
Concepts
Session
6
Using Contracts, Print Settings, and Speech Synthesis
Concepts
Step 2: Click the Solution Explorer and then navigate to add new items as shown in figure 6.3.
Session
6
Using Contracts, Print Settings, and Speech Synthesis
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.
Session
6
Using Contracts, Print Settings, and Speech Synthesis
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.
Session
6
Using Contracts, Print Settings, and Speech Synthesis
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.
Concepts
Session
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.
Session
6
Using Contracts, Print Settings, and Speech Synthesis
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.
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.
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>
Session
6
Using Contracts, Print Settings, and Speech Synthesis
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.
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.
Session
6
Using Contracts, Print Settings, and Speech Synthesis
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.
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.
Session
6
Using Contracts, Print Settings, and Speech Synthesis
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.
Session
6
Using Contracts, Print Settings, and Speech Synthesis
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.
Session
6
Using Contracts, Print Settings, and Speech Synthesis
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.
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.
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.
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)
Session
6
Using Contracts, Print Settings, and Speech Synthesis
{
this.btnTalkCon.IsEnabled = true;
this.media.CurrentStateChanged -= this.media_CurrentStateChanged;
}
}
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
Session
6
Using Contracts, Print Settings, and Speech Synthesis
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.
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.
Session
6
Using Contracts, Print Settings, and Speech Synthesis
2.
3.
4.
(A) Printer
(C)
Print manager
(B)
(D)
Print function
Print contract
(C)
Search tool
(B)
(D)
Search box
Plan to contract
(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.
Session
6
Using Contracts, Print Settings, and Speech Synthesis
6.4.1 Answers
B
2.
3.
4.
5.
Concepts
1.
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
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
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
Session
7
Push Notification Services
Concepts
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.
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
Session
7
Push Notification Services
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.
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.
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
Concepts
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.
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
Concepts
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.
{
case PushNotificationType.Badge:
nc = e.BadgeNotification.Content.GetXml();
break;
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.
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.
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
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.
Concepts
Content-Type: application/json
Session
7
Push Notification Services
Description
200 OK
400 Bad Request
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
Concepts
To put the URI in acknowledged form, the URI does the following steps:
Acknowledges the path for ordered URIs by compressing orders such as /./, /../, //, including
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/
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
{
App.ChannelExpiryDate = ExpirationTime.DateTime.ToUniversalTime();
}
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
Session
7
Push Notification Services
2.
3.
4.
(A) Badge
(C)
Tile
(B)
(D)
Channel
Toast
(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
_________.
(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.
Session
7
Push Notification Services
7.4.1 Answers
A
2.
3.
4.
5.
Concepts
1.
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
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
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)
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();
}
}
}
}
Session
8
Media Capturing
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.
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.
Concepts
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.
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);
}
Concepts
Session
8
Media Capturing
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.
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;
Session
8
Media Capturing
Concepts
Session
8
Media Capturing
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}>
Session
8
Media Capturing
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();
Concepts
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.
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.
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.
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.
Session
8
Media Capturing
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;
}
}
Session
8
Media Capturing
Concepts
{
w.Stop();
}}
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
if (i[count2].Id = = devUpdate.Id)
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.
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)
{
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
Concepts
Session
8
Media Capturing
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.
Concepts
Session
8
Media Capturing
Concepts
Session
8
Media Capturing
2.
3.
MediaCapture
(D)
CameraCaptureUI
(A) Device
(C)
Audio
(B)
(D)
Windows Media
AutoPlay
(B)
media.Capture
(C)
Media
(D)
Media.Capture
(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)
Session
8
Media Capturing
8.5.1 Answers
A
2.
3.
4.
5.
Concepts
1.
Session
8
Media Capturing
Summary
The user must use MediaElement class to play audio or video inside the app.
ameraCaptureUI performs the capture through advanced Windows UI built-in features. To get
C
the complete UI experience, the CameraCaptureUI uses CaptureElement.
Media APIs such as AddEffectAsync and ClearEffectsAsync methods can be used for
MediaElement effects.
Concepts