Você está na página 1de 175

Advanced Windows Store

Apps Development - II
Advanced Windows Store Apps
Development - II
Learners Guide
2014 Aptech Limited
All rights reserved.
No part of this book may be reproduced or copied in any form or by any means graphic, electronic or
mechanical, including photocopying, recording, taping, or storing in information retrieval system or sent
or transferred without the prior written permission of copyright owner Aptech Limited.
All trademarks acknowledged.
APTECH LIMITED
Contact E-mail: ov-support@onlinevarsity.com
First Edition - 2014
Dear Learner,
We congratulate you on your decision to pursue an Aptech course.
Aptech Ltd. designs its courses using a sound instructional design model from conceptualization
to execution, incorporating the following key aspects:
Scanning the user system and needs assessment
Needs assessment is carried out to fnd the educational and training needs of the learner
Technology trends are regularly scanned and tracked by core teams at Aptech Ltd. TAG*
analyzes these on a monthly basis to understand the emerging technology training needs for
the Industry.
An annual Industry Recruitment Profle Survey
#
is conducted during August - October
to understand the technologies that Industries would be adapting in the next 2 to 3 years.
An analysis of these trends & recruitment needs is then carried out to understand the skill
requirements for different roles & career opportunities.
The skill requirements are then mapped with the learner profle (user system) to derive the
Learning objectives for the different roles.
Needs analysis and design of curriculum
The Learning objectives are then analyzed and translated into learning tasks. Each learning
task or activity is analyzed in terms of knowledge, skills and attitudes that are required to
perform that task. Teachers and domain experts do this jointly. These are then grouped in
clusters to form the subjects to be covered by the curriculum.
In addition, the society, the teachers, and the industry expect certain knowledge and skills
that are related to abilities such as learning-to-learn, thinking, adaptability, problem solving,
positive attitude etc. These competencies would cover both cognitive and affective domains.
A precedence diagram for the subjects is drawn where the prerequisites for each
subject are graphically illustrated. The number of levels in this diagram is determined
by the duration of the course in terms of number of semesters etc. Using the precedence
diagram and the time duration for each subject, the curriculum is organized.
Design & development of instructional materials
The content outlines are developed by including additional topics that are required for the
completion of the domain and for the logical development of the competencies identifed.
Evaluation strategy and scheme is developed for the subject. The topics are arranged/organized
in a meaningful sequence.
The detailed instructional material Training aids, Learner material, reference material, project
guidelines, etc.- are then developed. Rigorous quality checks are conducted at every stage.
Strategies for delivery of instruction
Careful consideration is given for the integral development of abilities like thinking, problem
solving, learning-to-learn etc. by selecting appropriate instructional strategies (training
methodology), instructional activities and instructional materials.
The area of IT is fast changing and nebulous. Hence considerable fexibility is provided in the
instructional process by specially including creative activities with group interaction between
the students and the trainer. The positive aspects of web based learning acquiring information,
organizing information and acting on the basis of insuffcient information are some of the
aspects, which are incorporated, in the instructional process.
Assessment of learning
The learning is assessed through different modes tests, assignments & projects. The
assessment system is designed to evaluate the level of knowledge & skills as defned by the
learning objectives.
Evaluation of instructional process and instructional materials
The instructional process is backed by an elaborate monitoring system to evaluate - on-time
delivery, understanding of a subject module, ability of the instructor to impart learning. As an
integral part of this process, we request you to kindly send us your feedback in the reply pre-
paid form appended at the end of each module.
*TAG Technology & Academics Group comprises 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 Profle Survey - The Industry Recruitment Profle Survey was conducted
across 1581 companies in August/September 2000, representing the Software, Manufacturing,
Process Industry, Insurance, Finance & Service Sectors.
Scanning the
user system
and needs
assessment
Evaluation of
Instructional
Processes and
Material
Need Analysis
and design of
curriculum
Assessment
of learning
Design and
development of
instructional
material
Strategies for
delivery of
instructions
Key Aspects
Aptech New Products Design Model
1
2
3
4
5
6
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
Notifcation Service and Microsoft Windows Notifcation Service Channel. Using these features, the users
can create, send, request ,and save such notifcations 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 certifcation 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
Preface
Sessions
1. Background Task
2. Device Capabilities
3. Generating Revenue Apps
4. Developing Universal Apps
5. Managing Windows and Web Authentication
6. Securing Windows Store App Data
7. Diagnosing Problems and Monitoring Applications
Table of Contents
Background Task
Session - 1
Welcome to the Session, Background Task.
This session introduces you to creatng and consuming background tasks for
the Windows Store Apps.
In this Session, you will learn to:
Create a Background Task
Consume a Background Task
V 1.0 Aptech Limited
1
Background Task
C
o
n
c
e
p
t
s
1.1 What is Background Task?
In old Windows versions, it was possible to run multple applicatons on the desktop without disturbing
each other. However, with Windows Store Apps, things have changed. If an app is not running actvely
and is not currently visible on the screen, it is suspended by the operatng system. Windows automatcally
suspends the app that is not actve at present. If an app needs to perform certain periodic actvites afer
an interval, it is very difcult to keep such applicaton running and alive in the memory. To overcome this
difculty, the WinRT libraries include a collecton of classes called background tasks. These tasks can be
used to construct a workfow that will work with the new life cycle of an app. Background Tasks are used
when no user interacton is needed.
A background task is a class that implements an interface called IBackgroundTask which is available
in the namespace called Windows.ApplicationModel.Background.
The IBackgroundTask includes a single method called Run. This method returns an object called
IBackgroundTaskInstance and it allows the task to interact with the current running process.
This task remains alive in the memory as a thread that can communicate with app when it is reloaded in
the memory. Thus, using BackgroundTask, it becomes easy to share the data or contnuously run an
actvity in the background without requiring the app to remain actve on the screen.
There are certain conditons or optons that can be set for a background tasks. Using these optons, the
developer can control the behavior of the task that is running in the background. These conditons are
defned by an enumerator class known as SystemConditionType. The SystemConditionType
has following optons available in it:
InternetAvailable/InternetNotAvailable Checks if the Internet is available or not
SessionConnected/SessionNotConnected Checks if the session connected or
disconnected
UserPresent/UserNotPresent Checks if user available or unavailable
To understand the Background Tasks, it is necessary to understand the concept of threading in Windows
Store apps. Users might be aware of what is threading, but to recap the knowledge here is brief
introducton to threading.
1.2 What is Threading?
Threading allows running multple tasks within a single process. The main thread can be forked into
multple sub threads called tasks. The two types of thread concepts available to execute in the app are
a UI thread and a background thread. The thread pool will queue the threads and are confgured and
designed to start executon automatcally whenever the processor needs it. The thread pool is same
as the asynchronous programming, which is available under Windows Runtme. The next thread in the
queue will start when the executon of frst thread is complete. The user can use tmer inside the app to
specify the interval tme to the thread through code.
V 1.0 Aptech Limited
1
Background Task
C
o
n
c
e
p
t
s
Figure 1.1 shows the life cycle of a thread in the Windows Store App.
Figure 1.1: Thread Life Cycle
As shown in fgure 1.1, it can be seen that when an app is launched, initalized and the control is passed
on to the UI thread. Afer UI thread is over, the control will be passed to background task if it exists. Either
the terminaton stage can close the app or it again reloads the app by going to initalize stage.
Note - The developer can use CreatePeriodicTimer to run the thread repeatedly.
1.2.1 Create and Register a Background Task
Similar to a thread, a background task is a functon that runs in the memory of an app without disturbing
the normal executon of other apps. Background task can execute the code in the memory without
making the app actve. This is not possible to execute using UI tasks. Therefore, the background tasks are
very important when it comes to running some tasks that will perform some actons in the background
afer certain interval.
Background tasks will be necessary in the following situatons:
When some streaming audio is to be played.
A Live Tile needs to update new data from the server.
A Push Notfcaton pops up when the notfcaton is sent or received.
A Lock screen updates when a device is locked or unlocked.
In case of such situatons, it is not possible to launch an app and keep it running contnuously on the
screen. This actvity needs to run in the background without coming to front end or without showing the
UI. In these cases the best solutons is to create and run a background task. The user can create a class
based on interface IBackgroundTask and implements its method called Run().
V 1.0 Aptech Limited
1
Background Task
C
o
n
c
e
p
t
s
Here is a basic implementaton of IBackgroundTask:
public class SimpleBgTask : IBackgroundTask
{
public void Run(IBackgroundTaskInstance taskInstance)
{
// Insert code to perform some activities here
}
}
When an app is registered to run in the background at a periodic interval, it is necessary to assign such an
app to a single trigger that will decide when and how ofen this app should be executed in the background.
There are fve types of triggers that can be assigned to the current task. These triggers will automatcally
start executon of the background task. These triggers are shown in table 1.1.
Trigger Descripton
Control channel This is actvated when Incoming message is received on a control channel
(socket)
Push notfcaton It is actvated when the Raw notfcaton is received from Windows Push
Notfcaton Services
Audio This is a trigger for Audio events
Timer This actvates when the Timer event occurs
System event This is actvated and responds to a predefned system event
Locaton This actvates when the user locaton changes or updates
Table 1.1: Types of Triggers for Background Tasks
To register a background task in an app, the user has to enable background tasks in the Package.
appxmanifest fle as shown in fgure 1.2.
Figure 1.2: Selectng Background Tasks from the Declaratons Tab
V 1.0 Aptech Limited
1
Background Task
C
o
n
c
e
p
t
s
Select the System Event property as shown in fgure 1.3.

Figure 1.3: Enable System event inside Background Tasks
1.2.2. Respond to System Events with Background Tasks
The background task can made to respond to the user through system events. The user has to declare the
Entry point in the app manifest fle by selectng the background task from the declaraton tab as shown
in fgure 1.4.

Figure 1.4: Selectng the Background Task from the Declaraton Tab
V 1.0 Aptech Limited
1
Background Task
C
o
n
c
e
p
t
s
To register the Background Task the user has to write the code shown in Code Snippet 1.
Code Snippet 1:
private void RegisterBackgroundTask(string n, string p)
{
BackgroundTaskBuilder b = new BackgroundTaskBuilder();
b.Name = n;
b.TaskEntryPoint = p;
b.SetTrigger(new SystemTrigger(SystemTriggerType.InternetAvailable,
false));
BackgroundTaskRegistration t = b.Register();
}
Create a functon fnChkReg() to check whether the task is registered or unregistered by writng the
code shown in Code Snippet 2.
Code Snippet 2:
private void fnChkReg()
{
foreach (var task in BackgroundTaskRegistration.AllTasks)
{
if (task.Value.Name == Update)
{
isRegistered = true;
break;
}
}
if (isRegistered)
{
RegisterButton.Content = Unregister;
lblResult.Text = Task Registered;
}
else if (!isRegistered)
{
RegisterButton.Content = Register;
lblResult.Text = Task UnRegistered;
}
}
V 1.0 Aptech Limited
1
Background Task
C
o
n
c
e
p
t
s
1.2.3 Set Conditons for Running a Background Task
The user has to know how to check the conditons and apply them for the background task. These
conditons are checked by using a trigger in the app. For example, if the user has to set the Internet
connectvity inside the app, then use the SystemTriggerType called InternetAvailable and
set it to either true or false. If the InternetAvailable trigger is set to false, then it minimizes the
batery usage. Code Snippet 3 shows how to set the SystemTriggerType for the background task.
Code Snippet 3:
BackgroundTaskBuilder builder = new BackgroundTaskBuilder();
builder.Name = nameofbktask;
builder.TaskEntryPoint = programname;
builder.SetTrigger(new SystemTrigger(SystemTriggerType.InternetAvailable,
false));
BackgroundTaskRegistration t = builder.Register();
1.2.4 Handle a Cancelled Background Task
The background tasks are short running processes, which executes the code and restarts automatcally
for executng the task again using a tmer. The user can cancel any running background tasks if it is
not necessary to run at that tme. In order to cancel the background task the user has to register for
cancellaton handler. As the handler is registered, the system stops the async tasks running in the
background. To cancel the task the user has to declare the CancellationTokenSource by writng
code as shown in Code Snippet 4.
Code Snippet 4:
CancellationTokenSource c = new CancellationTokenSource();
On the OnCancelled method write c.Cancel() to stop the task by writng Code Snippet 5.
Code Snippet 5:
private void OnCancelled(IBackgroundTaskInstance sender,
BackgroundTaskCancellationReason reason)
{
c.Cancel();
}
V 1.0 Aptech Limited
1
Background Task
C
o
n
c
e
p
t
s
1.2.5 Monitor Background Task Progress and Completon
Tasks can be monitored by displaying a message in the UI of the app. The user can set the trigger to
update the status of the task running. For example, if the user needs to execute task contnuously then
for every completon of the task, there must be a notfcaton in the UI in the form of a message displayed
in a TextBlock as shown in Code Snippet 6.
Code Snippet 6:
if(isRegistered)
{
RegisterButton.Content = Unregister;
lblResult.Text = Task Registered;
}
if(!isRegistered)
{
RegisterButton.Content = Register;
lblResult.Text = Task UnRegistered;
}
The code displays the status of the task to the user. If the task is registered then the result will display as
Task Registered in a TextBlock of the UI.
1.2.6 Run a Background Task Using a Timer
If the user wants to run the task repeatedly afer some interval, then the task can be called using a tmer.
A class called TimeTrigger is available for this purpose. Create an instance of this class and set necessary
propertes to make it work. The tmer has to be declared in the functon as shown in Code Snippet 7.
Code Snippet 7:
TimeTrigger t = new TimeTrigger(15, false);
The user has to set the tme to restart the task, as mentoned in Code Snippet 7, the task will execute
afer every 15 minutes.
1.3 Triggers
Triggers are created in the background task to keep the app stable and to execute the code without
disturbing the UI. These triggers are declared with some duraton. Thus, the triggers can execute the
code periodically afer an interval from the background of the app.
V 1.0 Aptech Limited
1
Background Task
C
o
n
c
e
p
t
s
1.3.1 Maintenance Triggers
As the maintenance trigger occurs, the device will update the task periodically as set by the user in the
code. This MaintenanceTrigger can be declared by writng code as shown in Code Snippet 8.
Code Snippet 8:
MaintenanceTrigger t = new MaintenanceTrigger(15, false);
Note - MaintenanceTrigger will execute only when the device plugged into AC power
The code shown in Code Snippet 8 will execute the trigger afer every 15 minutes.
1.3.2 Declare Background Tasks in the Applicaton Manifest
The user has to declare the background task in the Package.appxmanifest fle. To do so, the user
has to right-click the manifest fle and select View Code or Press F7 as shown in fgure 1.5.
Figure 1.5: View App Manifest File Code
V 1.0 Aptech Limited
1
Background Task
C
o
n
c
e
p
t
s
In the applicaton node, write the code to menton the extension for the background task.
To apply the Background Task extension in the manifest fle, the user has to write the code as shown in
Code Snippet 9 in the applicaton tag.
Code Snippet 9:
<Application Id=App Executable=$targetnametoken$.exe
EntryPoint=BGTrigger.App>
<m2:VisualElements DisplayName=BGTrigger Square150x150Logo=Assets\
Logo.png Square30x30Logo=Assets\SmallLogo.png Description=BGTrigger
ForegroundText=light BackgroundColor=#464646>
<m2:SplashScreen Image=Assets\SplashScreen.png />
</m2:VisualElements>
<Extensions>
<Extension Category=windows.backgroundTasks EntryPoint=Tasks.Update>
<BackgroundTasks>
<Task Type=systemEvent />
</BackgroundTasks>
</Extension>
</Extensions>
</Application>
The code declares a background task with an entry point as Tasks.Update.
1.3.3 Guidelines and Checklists for Background Tasks
Guidelines:
The user has to follow the guidelines while developing the app.
1. CPU and Network Quotas
The user has to maintain the CPU or Network usage limit, as it should not exceed.
2. Manage Background Tasks
The app must be writen in such a way that each task must be updated in the event entry, so that the
system log helps the user to fnd error in the app.
3. Update App Manifest
The user has to ensure that all the background tasks are declared in the app manifest fle whenever they
are created along with the trigger type.
V 1.0 Aptech Limited
1
Background Task
C
o
n
c
e
p
t
s
Checklist:
1. Point the correct trigger for each background task.
2. Maintain conditons to check the status while the background tasks are running.
3. Except Tile, Toast or Badge notfcatons, the user need not display any info in the UI of the app.
4. There should not be any user interacton in the background task.
5. The background task should not be dependable on the user.
6. Using Maintenance Trigger, check for Registraton errors.
1.3.4 How to Debug a Background Task?
The user can debug the code to check the status of the code, if the code is successfully executng or
intervening errors in the task. To check, the user has to select the desired opton such as suspend, resume,
suspend and shutdown, update as shown in fgure 1.6.
Suspend opton halts the task at that point of tme and can be resumed as the user selects the resume
opton as shown in fgure 1.6.
Figure 1.6: Debug Menu
As the code is suspended, the user can navigate to Event Viewer to view the system logs of the tasks.
Press Win + R key to open the run command. Type eventvwr.exe and press Enter to open the event
viewer as shown in fgure 1.7.
Figure 1.7: Run Command
V 1.0 Aptech Limited
1
Background Task
C
o
n
c
e
p
t
s
When the Event Viewer window is opened the user has to navigate to
Applicaton and Services Logs Microsof Windows BackgroundTaskInfrastructure
To view the debug logs, the user has to select Show Analytc and Debug Logs opton from the view menu
as shown in fgure 1.8.
Figure 1.8: Enable Show Analytc and Debug Logs
The user can now view the Diagnostc menu in the lef tree menu as shown in fgure 1.9. Select the
Diagnostc Menu and select Enable Log opton to record all the logs of the background task.
Figure 1.9: Enable Log
V 1.0 Aptech Limited
1
Background Task
C
o
n
c
e
p
t
s
Now, run the code by resuming and click the Register buton to register the background task as shown in
fgure 1.10.
Figure 1.10: Register the App
Open the event viewer and refresh the diagnostc menu to view the log created inside. To view the log,
select the log created and then the user can view the descripton of the log, as shown in fgure 1.11.
Figure 1.11: View the Event Descripton
V 1.0 Aptech Limited
1
Background Task
C
o
n
c
e
p
t
s
Exercise 1: Register Background Task
Step 1: Create a blank new project as shown in fgure 1.12.
Figure 1.12: Create a Blank New Applicaton
Step 2: Open the app manifest fle and navigate to Declaraton tab. Now, select the Background Task from
the available declaratons as shown in fgure 1.13.
Figure 1.13: Select the Declaraton
V 1.0 Aptech Limited
1
Background Task
C
o
n
c
e
p
t
s
Step 3: Enable the System event from the Background Task Declaraton as shown in fgure 1.14.
Figure 1.14: Enable System Event
Step 4: Declare the entry point for the app to run the Background Task as shown in fgure 1.15.
Figure 1.15: Declare the Entry Point
V 1.0 Aptech Limited
1
Background Task
C
o
n
c
e
p
t
s
Step 5: Write Code Snippet 10 to create a buton and a Text Block.
Code Snippet 10:
<Page
x:Class=RegisterBGTask.MainPage
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
xmlns:local=using:RegisterBGTask
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}>
<Button x:Name=RegisterButton Content=Register Width=200 Height=50
Click=RegisterButton_Click Margin=491,300,0,318 />
<TextBlock x:Name=lblResult HorizontalAlignment=Left
TextWrapping=Wrap FontSize=20 VerticalAlignment=Top
Margin=424,484,0,0 Height=61 Width=349/>
</Grid>
</Page>
V 1.0 Aptech Limited
1
Background Task
C
o
n
c
e
p
t
s
Step 6: Write Code Snippet 11 in the code behind fle.
Code Snippet 11:
bool isRegistered = false;
protected override void OnNavigatedTo(NavigationEventArgs e)
{
fnChkReg();
}
// To check the status of the task whether registered or unregistered
private void fnChkReg()
{
foreach (var task in BackgroundTaskRegistration.AllTasks)
{
if (task.Value.Name == Update)
{
isRegistered = true;
break;
}
}
if (isRegistered)
{
RegisterButton.Content = Unregister;
lblResult.Text = Task Unregistered;
}
else if (!isRegistered)
{
RegisterButton.Content = Register;
lblResult.Text = Task Registered;
}
}
V 1.0 Aptech Limited
1
Background Task
C
o
n
c
e
p
t
s
Step 7: Write Code Snippet 12 to register the Background Task using System Event.
Code Snippet 12:
private void RegisterBackgroundTask(string n, string p)
{
BackgroundTaskBuilder b = new BackgroundTaskBuilder();
b.Name = n;
b.TaskEntryPoint = p;
b.SetTrigger(new SystemTrigger(SystemTriggerType.InternetAvailable,
false));
BackgroundTaskRegistration t = b.Register();
}
private void UnregisterBackgroundTask(string name)
{
foreach (var t in BackgroundTaskRegistration.AllTasks)
{
if (t.Value.Name == name)
{
t.Value.Unregister(true);
}
}
}
private void RegisterButton_Click(object sender, RoutedEventArgs e)
{
if (isRegistered)
{
UnregisterBackgroundTask(Update);
isRegistered = false;
}
else
{
RegisterBackgroundTask(Update, BackgroundTasks.Update);
}
fnChkReg();
}
V 1.0 Aptech Limited
1
Background Task
C
o
n
c
e
p
t
s
Step 8: Output screen is seen when the app is executed by pressing F5 buton, as shown in fgure 1.16.
Figure 1.16: Output When Executed
Step 9: When the user clicks the Register buton, the task is registered in the system event and is ready
to execute the background process, as shown in fgure 1.17.
Figure 1.17: Output When Task is Registered
V 1.0 Aptech Limited
1
Background Task
C
o
n
c
e
p
t
s
Step 10: When the user clicks the UnRegister buton, the task is unregistered by creatng a log in the
system event, as shown in fgure 1.18.
Figure 1.18: Output When Task Is Unregistered
Exercise 2: Background Task Timer
Step 1: Create a blank new project as shown in fgure 1.19.
Figure 1.19: Create a Blank New Applicaton
V 1.0 Aptech Limited
1
Background Task
C
o
n
c
e
p
t
s
Step 2: Write Code Snippet 13 to create a buton and a Text Block.
Code Snippet 13:
<Page
x:Class=BackgroundProcessTimer.MainPage
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
xmlns:local=using:BackgroundProcessTimer
xmlns:d=http://schemas.microsoft.com/expression/blend/2008
xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006
mc:Ignorable=d>
<Grid Background={StaticResource ApplicationPageBackgroundThemeBrush}>
<StackPanel Orientation=Vertical Margin=20,50
HorizontalAlignment=Center>
<TextBlock x:Name=TimerLog FontSize=30></TextBlock>
<TextBlock x:Name=TimerStatus FontSize=25></TextBlock>
<StackPanel Orientation=Horizontal>
<Button x:Name=tStart Content=Start Click=tmrStart_Click></Button>
<Button x:Name=tStop Content=Stop Click=tmrStop_Click></Button>
</StackPanel>
</StackPanel>
</Grid>
</Page>
V 1.0 Aptech Limited
1
Background Task
C
o
n
c
e
p
t
s
Step 3: Write Code Snippet 14 in the code behind.
Code Snippet 14:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
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 BackgroundProcessTimer
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
DispatcherTimer tmr;
int timesTicked = 1;
int timesToTick = 100;
public void DispatcherTimerSetup()
{
tmr = new DispatcherTimer();
tmr.Tick += tmr_Tick;
tmr.Interval = new TimeSpan(0, 0, 0, 0, 200);
V 1.0 Aptech Limited
1
Background Task
C
o
n
c
e
p
t
s
tmr.Start();
TimerStatus.Text = tmr.IsEnabled = + tmr.IsEnabled + \n;
}
void tmr_Tick(object sender, object e)
{
TimerLog.Text = timesTicked.ToString() + %;
if (timesTicked == timesToTick)
{
TimerStatus.Text = Calling tmr.Stop()\n;
tmr.Stop();
TimerStatus.Text = tmr.IsEnabled = + tmr.IsEnabled + \n Process Completed
Successfully;
}
timesTicked++;
}
private void tmrStart_Click(object sender, RoutedEventArgs e)
{
TimerStatus.Text = Calling tmr.Start()\n;
DispatcherTimerSetup();
}
private void tmrStop_Click(object sender, RoutedEventArgs e)
{
TimerStatus.Text = Calling tmr.Stop()\n;
tmr.Stop();
TimerStatus.Text = tmr.IsEnabled = + tmr.IsEnabled + \n;
}
private void Page_Loaded_1(object sender, RoutedEventArgs e)
{
TimerStatus.Text = tmr.IsEnabled = False;
}
}
}
V 1.0 Aptech Limited
1
Background Task
C
o
n
c
e
p
t
s
Step 4: The output of the app when executed, is as shown in fgure 1.20.
Figure 1.20: Output of the App
Step 5: The output of the app when the user clicks Start buton, as shown in fgure 1.21.
Figure 1.21: Create a Blank New Applicaton
Step 6: The output of the app completes the background task, as shown in fgure 1.22.
V 1.0 Aptech Limited
1
Background Task
C
o
n
c
e
p
t
s
Figure 1.22 Blank New Applicaton Created
V 1.0 Aptech Limited
1
Background Task
C
o
n
c
e
p
t
s
1.4 Check Your Progress
1. The user can use tmer in the app to execute the ________ through code.
(A) UI (C) Tab
(B) Background Task (D) Thread
2. Background Task executes the code, which cannot be executed by _______.
(A) Entry point (C) UI task
(B) Suspend Option (D) App
3. To register a background task, the user has to enable the device inside the ____________ fle.
(A) Package.appxmanifest (C) Declarations
(B) Web.Config (D) Application
4. ____________ opton halts the task at that point of tme, and can be restarted when the user
selects the resume opton.
(A) Play (C) Stop
(B) Suspend (D) Pause
Edited by Foxit Reader
Copyright(C) by Foxit Software Company,2005-2008
For Evaluation Only.
V 1.0 Aptech Limited
1
Background Task
C
o
n
c
e
p
t
s
Summary
The two types of thread concepts available in the app are - UI thread and BackgroundTask.
The user has to declare the Entry point in the app manifest fle by selectng the background task
from the declaraton tab.
The user must know how to check the conditons and apply them for the background task.
The user can cancel any running background tasks if it is not needed.
Triggers are created in the background task to make the app stable and to execute the code
without disturbing the UI.
Suspend opton halts the task at that point of tme and can be resumed as the user selects the
resume opton.
Device Capabilities
Session - 2
Welcome to the Session, Device Capabilites.
This session introduces users to device connectvity through Enumeratng
Devices, Plug and Play Devices, Sensors, and Locaton Services with the
Windows Store Apps.
In this Session, you will learn to:
Enumerate Devices
Describe the Plug and Play (PnP) devices
Troubleshoot Asynchronous errors
Describe Sensors
Explain Locaton Services
V 1.0 Aptech Limited
C
o
n
c
e
p
t
s
2
Device Capabilites
2.1 Devices
Microsof insists their manufacturers and operators to create devices with beter connectvity so that the
device can be tracked anywhere. The manufacturers also implement and follow these guidelines in case
of internal as well as external devices they create. Operators will provide the Geopositoning service to
locate the device. This session explains the structures in Windows 8.1 that support Store apps, mobile
apps, Storage, and Printers.
Whenever a user develops a store apps, they can also integrate it as a device app. With device metadata,
apps can automatcally set up the device connected for the frst tme and provide more features than
normal apps. Apps can make use of features and utlize the variety of functonalites provided by devices.
The app can also grant or deny various privileges to the user at runtme.
2.1.1. Enumeratng Devices
Windows.Devices.Enumeraton and Windows.Devices.Enumeraton.Pnp are the two namespaces to
enumerate the devices connected or disconnected. This Windows.Devices.Enumeraton class provides
two methods, namely FindAllAsync and CreateWatcher to enumerate the devices.
FindAllAsync - This will search the device only once as the device is connected. This will not
update whenever the user adds or delete the devices.
CreateWatcher This will always enumerate devices by raising notfcaton as the user adds or
deletes the devices.
To enumerate devices the user has to frst identfy the GUID class for the device to be tested. Microsof
has released the common GUID class with Windows 7, which is called and tested for enumeraton.
Note - The default class GUID for
Printer: {0ECEF634-6EF0-472A-8085-5AD023ECBCCD}
Webcam: {E5323777-F976-4F5B-9B55-B94699C46E44}
Portable Devices: {6AC27878-A6FA-4155-BA85-F98F491D4F33}
V 1.0 Aptech Limited
C
o
n
c
e
p
t
s
2
Device Capabilites
Step 1: To get the GUID class of a device, the user has to insert any portable device such as pen drive,
printer, or webcam. Right-click the device and go to propertes as shown in fgure 2.1.
Figure 2.1: Propertes
Step 2: Go to Hardware tab, select the device, and go to propertes as shown in fgure 2.2.
Figure 2.2: Select the Device
V 1.0 Aptech Limited
C
o
n
c
e
p
t
s
2
Device Capabilites
Step 3: In the propertes window, select events, and select the device to view the Class GUID as shown
in fgure 2.3.
Figure 2.3: Navigate to Events and Select the Device
2.1.2. Using DeviceWatcher
The DeviceWatcher class is in charge for device enumeraton; foatng exact events each tme
the devices are added, removed, or altered afer the inital enumeraton is fnished. The events of
DeviceWatcher class are:
Added Occurs when new device is found and added by the DeviceWatcher class
EnumeratonCompleted Occurs when the device enumeraton is completed
Removed Occurs when a device is removed
Stopped Occurs when enumeraton process is stopped
Updated Occurs when enumeraton process is modifed
2.1.3. Plug and Play (PnP) Devices
Plug and Play (PnP) is a mixture of hardware and sofware that enables a system to identfy, setup, and
get used to hardware structure modifcatons when any new device is connected by the user. A user can
connect or disconnect any number of devices to/from the computer. The system will automatcally adjust
V 1.0 Aptech Limited
C
o
n
c
e
p
t
s
2
Device Capabilites
the confguraton whenever such devices with plug and play capability are connected to the system.
Some of the competence acknowledged in the app manifest fle such as microphone, camera, and the
locaton can expose private informaton (For example, Current locaton). For the app to be able to access
devices acknowledged in the app manifest, the user needs to grant access privileges in order to access
the feature of the device.
These devices can be made available in the app by enabling the device in the app manifest fle as shown
in fgure 2.4.
Figure 2.4: Enable Device Capabilites in the Manifest File
2.1.4. Handling Device Capability Errors
To deliver a good user experience the app needs access to sensitve devices, its required to handle the
errors that can occur when trying to access a disabled device.
Reasons for not being able to access a device includes:
The user may not have proper permissions to access the device.
The user may revoke the permission in the setngs.
The device capability is not available on the system.
V 1.0 Aptech Limited
C
o
n
c
e
p
t
s
2
Device Capabilites
2.2. Sensors
Windows.Devices.Sensors namespace is used to capture moton, device orientaton, or light
sensors.Windows.Devices.Geolocation is the namespace for fnding the locaton of the
device through GPS or Locaton Provider. If the user is trying to access the map for the frst tme, the app
will automatcally request the user for permission as shown in fgure 2.5.
Figure 2.5: Locaton Access Permission
Figure 2.5 shows the dialog box shown when user tries to open the map for the frst tme. It will prompt
the user to either allow or block the access to map on the system. If the user selects Allow opton, he/
she is allowed to view the map. If he/she clicks Block then it will restrict the app from accessing the map.
2.2.1. Working with Sensors
Windows 8 supports many sensors. In order to work with these sensors, the user must enable the
capabilites in the app manifest fle. If the capabilites are not enabled or properly set in the manifest fle,
then the user will receive an excepton message statng that there is no sensor available in the device.
SimpleOrientatonSensor
The SimpleOrientationSensor is used to sense the device orientaton. Many devices have rec-
ognized the necessity that when the user rotates the device, the display shall also rotate to the new
orientaton. The images or screen should be adjusted accordingly. The view of the screen should
remain original even if the device is rotated by the user. User may change the positon of or rotate
the device vertcally or horizontally, the images should remain in the same positon.
V 1.0 Aptech Limited
C
o
n
c
e
p
t
s
2
Device Capabilites
LightSensor
The LightSensor is used to increase or decrease the brightness of the device. This light sensor will
automatcally turn Of the display afer a certain period of tme. It also adjusts the display bright-
ness or contrast according to the environment.
Compass
To detect the magnetc positon towards the north to navigate the user using GPS. It keeps details
of directons. Moreover, always points the directon indicator towards the north directon. This al-
lows the user to know the directons in which he/she is moving.
Inclinometer
This sensor provides the rotaton values by showing the pitch, roll, and yaw values. It monitors the
surface movements and deformatons if any.
2.2.2. Using the SimpleOrientatonSensor
To make use of the device orientaton sensor, the user has to write the code to make the screen rotate
whenever the user rotates the device. To make use of this orientaton the user has to select the supported
rotatons from the applicaton tab in the app manifest fle as shown in fgure 2.6.
Figure 2.6: Supported Rotatons
V 1.0 Aptech Limited
C
o
n
c
e
p
t
s
2
Device Capabilites
To check and determine the current positon of the device, the user has to check the device by writng
the code shown in Code Snippet 1.
Code Snippet 1:
switch (SimpleOrientation)
{
case SimpleOrientation.NotRotated:
AlertBox.Text = Not Rotated;
break;
case SimpleOrientation.Rotated90DegreesCounterclockwise:
AlertBox.Text = 90 Degrees Rotated;
break;
case SimpleOrientation.Rotated180DegreesCounterclockwise:
AlertBox.Text = 180 Degrees Rotated;
break;
case SimpleOrientation.Rotated270DegreesCounterclockwise:
AlertBox.Text = 270 Degrees Rotated;
break;
case SimpleOrientation.Facedown:
AlertBox.Text = Face Down;
break;
case SimpleOrientation.Faceup:
AlertBox.Text = Face Up;
break;
default:
AlertBox.Text = Unknown;
break;
}
The code given in Code Snippet 1, checks for various orientaton positons of the current device using the
switch case block and accordingly takes the acton.
This code will only work on the device that has the orientaton sensor. If there is no device orientaton
sensor present on the device, then this orientaton detecton code will not work. The app will ignore the
rotate event and will not show any efect on the screen.
V 1.0 Aptech Limited
C
o
n
c
e
p
t
s
2
Device Capabilites
2.3. Locaton Services
Locaton providers can control the locaton of a device through:
Wi-Fi
Tracking IP Address
Tracking mobile Network
Global Positon System (GPS)
The user has to use the Windows Locaton Provider for developing the apps. The Locaton Provider
calculates the lattude and longitude; based on the calculated locaton, the device fnds the accuracy
of the positon in which the device is located. If there is no network available, the Locaton Provider
automatcally captures IP Address of the device with an accuracy of 50 kilometers. The Locaton Provider
retrieves lattude, longitude, and device informaton based on accuracy. This informaton can be used to
determine the exact locaton of the device. This is very helpful for tracking the device or the person that
is holding this device. The namespace Windows.Devices.Geolocaton will provide the necessary classes
and providers needed to access the locaton informaton.
2.3.1. Using Locaton Services
To access the locaton of the device the user has to write the code given in Code Snippet 2.
Code Snippet 2:
g = new Geolocator();
Geoposition p = await g.GetGeopositionAsync();
txtLatitude.Text = Latitude: + p.Coordinate.Point.Position.Latitude.
ToString();
txtLongitude.Text = Longitude: + p.Coordinate.Point.Position.Longitude.
ToString();
txtAccuracy.Text = Accuracy: + p.Coordinate.Accuracy.ToString();
V 1.0 Aptech Limited
C
o
n
c
e
p
t
s
2
Device Capabilites
The code given in Code Snippet 2 is used to track the Geo position of a device. This GeoPositon will
show the lattude and longitude point, which shows the exact place where the device is located. When
the code is executed, the output will request user to access the device locaton as shown in fgure 2.7.
Figure 2.7: Output Requestng to Access Device Locaton
As the user allows to access the device locaton permission, the app will display the device lattude,
longitude, and the accuracy as shown in fgure 2.8.
Figure 2.8: Output Displaying the Locaton Informaton
2.3.2. Using Geofencing
Geofencing provides an API to track the device and generate a trigger when the user enters or leaves
a partcular locaton or area. Store apps support hundreds of Geofencing optons. If more than
one Geofencing is triggered then the app will automatcally notfy the locaton that is actve. The
V 1.0 Aptech Limited
C
o
n
c
e
p
t
s
2
Device Capabilites
GeofenceStateChanged event is called, as one or more objects in the collecton are changed. As soon
as the Geofencing is triggered, the ReadReports() method is called to return the Geofencing
list, which is modifed. The user has to check the entry and exit state when the device is identfed in the
defned locaton by showing a notfcaton by setng the ID in CreateGeofence()method.
GeofenceMonitor will save the Geofencing list automatcally and it will be actve untl the app is
executed. The user has to use the Remove() method to clear the list.
2.4 Troubleshootng Async Errors
Whenever users creates any app, they have to handle the errors if it occurs at runtme. If an app is
developed without handling errors, then the error will be refected in the app. This will also close the app
abruptly or abnormally. This will lead to bugs in the app. To overcome these types of errors, the user can
use the try - catch block to handle such errors or to capture these exceptons. An appropriate excepton
can be handled and an error message can be thrown without stopping the current running app. The app
contnues executon without an interrupton.
The code shows how the try catch block is used to capture or handle certain error occurred in the app.
Method fnErrorHandle() will handle an excepton or error thrown by the app.
async void fnErrorHandle()
{
try
{
Int i; int j, int k;
i=5;
j=Test;
k=i+j;
}
catch (Exception ex)
{
new MessageDialog(ex.Message).ShowAsync();
}
}
The code given here, declares three integer value and when adding those two values it throws castng
error so, to handle this the user can throw a message using the catch block.
V 1.0 Aptech Limited
C
o
n
c
e
p
t
s
2
Device Capabilites
Device Enumeraton
Step 1: Create a blank new applicaton from File New Project Blank App
Step 2: Write the code given in Code Snippet 3 to create the design view of the page.
Code Snippet 3 shows how to create a layout with components as shown in fgure 2.9.
Code Snippet 3:
<Page x:Class=DeviceTesting.MainPage
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
xmlns:local=using:DeviceTesting
xmlns:d=http://schemas.microsoft.com/expression/blend/2008
xmlns:mc=http://schemas.openxmlformats.org/markup-
compatibility/2006
mc:Ignorable=d>
<Grid x:Name=ContentRoot Background=Black Margin=100,20,100,20>
<Grid.RowDefnitions>
<RowDefnition Height=Auto/>
<RowDefnition Height=*/>
<RowDefnition Height=Auto/>
</Grid.RowDefnitions>
<StackPanel x:Name=Header Grid.Row=0>
<StackPanel Orientation=Horizontal/>
</StackPanel>
<ScrollViewer VerticalScrollBarVisibility=Auto
HorizontalScrollBarVisibility=Auto Grid.Row=1>
<StackPanel>
<StackPanel Orientation=Horizontal HorizontalAlignment=Left>
<StackPanel/>
<StackPanel Margin=25 >
<StackPanel x:Name=Description MaxWidth=500 Height=250>
<StackPanel>
<StackPanel Orientation=Horizontal Margin=0,10,0,0/>
<TextBlock TextWrapping=Wrap FontSize=15 Text=Select the device to
Enumerate Margin=10,10,0,0 Width=888 />
<ListBox Name=lstDevices Width=400 HorizontalAlignment=Left>
<ListBoxItem Name=Webcam>Webcams</ListBoxItem>
V 1.0 Aptech Limited
C
o
n
c
e
p
t
s
2
Device Capabilites
<ListBoxItem Name=PortDevices>Portable Devices</ListBoxItem>
<ListBoxItem Name=Printer>Printers</ListBoxItem>
</ListBox>
<StackPanel Orientation=Horizontal Margin=0,10,0,0>
<TextBlock Text=Class GUID: HorizontalAlignment=Left
VerticalAlignment=Center />
<TextBox Name=txtClassGuid Margin=10,0,0,0 MinWidth=350 />
</StackPanel>
<Button Name=btnEnumerate Content=Enumerate Margin=0,10,10,0
Click=btnEnumerate_click />
</StackPanel>
</StackPanel>
</StackPanel>
</StackPanel>
<TextBlock Text=Output FontSize=15 Margin=0,25,0,20 />
<StackPanel HorizontalAlignment=Left>
<TextBlock Name=txtResult />
<ListBox Name=lstResult IsEnabled=False BorderThickness=0 />
</StackPanel>
</StackPanel>
</ScrollViewer>
</Grid>
</Page>
When the user writes the code given in Code Snippet 3 in the design mode, the UI will be displayed as
shown in fgure 2.9.
Figure 2.9: UI Design Layout Created
V 1.0 Aptech Limited
C
o
n
c
e
p
t
s
2
Device Capabilites
Step 3: Add following code given in Code Snippet 4, in the code behind fle, MainPage.xml.cs.
Code Snippet 4:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Devices.Enumeration;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Devices.Enumeration;
using Windows.Devices.Enumeration.Pnp;
namespace DeviceTesting
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
lstDevices.SelectionChanged += new SelectionChangedEventHandler(lstDevices_
SelectionChanged);
}
V 1.0 Aptech Limited
C
o
n
c
e
p
t
s
2
Device Capabilites
Step 4: Write Code Snippet 5 to call the functon, when the device is selected from the list.
Code Snippet 5:
void lstDevices_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (lstDevices.SelectedItem == Printer)
{
txtClassGuid.Text = {0ECEF634-6EF0-472A-8085-5AD023ECBCCD};
}
else if (lstDevices.SelectedItem == Webcam)
{
txtClassGuid.Text = {E5323777-F976-4F5B-9B55-B94699C46E44};
}
else if (lstDevices.SelectedItem == PortDevices)
{
txtClassGuid.Text = {6AC27878-A6FA-4155-BA85-F98F491D4F33};
}
}
Code given in Code Snippet 5 creates a class called Device Testng, this class then uses switch-case to
identfy the device that was selected for enumeraton.
V 1.0 Aptech Limited
C
o
n
c
e
p
t
s
2
Device Capabilites
Step 5: Write the code given in Code Snippet 6 to call the functon when the user clicks Enumerate buton.
Code Snippet 6:
async void btnEnumerate_click(object sender, RoutedEventArgs eventArgs)
{
btnEnumerate.IsEnabled = false;
lstResult.Items.Clear();
try
{
var s = InterfaceClassGuid:=\ + txtClassGuid.Text + \;
var i = await DeviceInformation.FindAllAsync(s, null);
txtResult.Text = i.Count + device found\n\n;
foreach (DeviceInformation d in i)
{
fnDeviceInfo(d);
}
}
catch (ArgumentException)
{
txtResult.Text = Exception: Verify interface class GUID.;
}
btnEnumerate.IsEnabled = true;
}
V 1.0 Aptech Limited
C
o
n
c
e
p
t
s
2
Device Capabilites
Code Snippet 7 shows how to use the enumeraton devices and how to generate the list. The device
informaton is shown in the result box, as shown in Code Snippet 7.
Code Snippet 7:
async void fnDeviceInfo(DeviceInformation d)
{
var id = Id: + d.Id;
var name = d.Name;
var isEnabled = IsEnabled: + d.IsEnabled;
var item = id + is \n + name + and \n + isEnabled;
lstResult.Items.Add(item);
}
}
}
When the user executes the applicaton by pressing F5 or Run opton, the output will be displayed as
shown in fgure 2.10.
Figure 2.10: List of Devices
V 1.0 Aptech Limited
C
o
n
c
e
p
t
s
2
Device Capabilites
Step 6: When the user clicks the enumerate buton the device informaton will be displayed as shown in
fgure 2.11.
Figure 2.11: Output Afer Clicking Enumerate Buton
Using DeviceWatcher
Step 1: Create a blank new applicaton
Step 2: Write the code given in Code Snippet 8, to create the design view of the page.
Code Snippet 8:
<Page
x:Class=DeviceWatcherTest.MainPage
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
xmlns:local=using:DeviceWatcherTest
xmlns:d=http://schemas.microsoft.com/expression/blend/2008
xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006
mc:Ignorable=d>
<Grid x:Name=ContentRoot Background=Black Margin=100,20,100,20>
<Grid.RowDefnitions>
<RowDefnition Height=Auto/>
<RowDefnition Height=*/>
<RowDefnition Height=Auto/>
</Grid.RowDefnitions>
V 1.0 Aptech Limited
C
o
n
c
e
p
t
s
2
Device Capabilites
<StackPanel x:Name=Header Grid.Row=0>
<StackPanel Orientation=Horizontal/>
</StackPanel>
<ScrollViewer VerticalScrollBarVisibility=Auto
HorizontalScrollBarVisibility=Auto Grid.Row=1 ZoomMode=Disabled>
<StackPanel>
<TextBlock Text=Device Watcher Enumeration Margin=0,25,0,20
FontSize=18 />
<StackPanel x:Name=InputPanel Orientation=Horizontal
HorizontalAlignment=Left Height=100 >
<StackPanel/>
<StackPanel MaxWidth=900 Height=80 Margin=5>
<!-- Enumerate Device Interfaces -->
<StackPanel Height=100 Width=857>
<TextBlock Text=Input/>
<StackPanel Orientation=Horizontal Margin=5/>
<StackPanel Orientation=Horizontal Margin=5/>
<Button Name=WatchAllDevices Content=Watch (All devices)
Margin=5 Click=fnDevicesWatch />
<!--<Button Name=StopAllWatcher Content=Stop Margin=0,10,10,0
Click=StopWatcher />-->
</StackPanel>
</StackPanel>
</StackPanel>
<TextBlock Text=Result FontSize=18 Margin=0,25,0,20 />
<!-- Output section -->
<StackPanel x:Name=Output HorizontalAlignment=Left>
<TextBlock Name=txtResult />
<!-- Device Interfaces-->
<ListBox Name=lstResult IsEnabled=False BorderThickness=0 />
</StackPanel>
</StackPanel>
</ScrollViewer>
</Grid>
</Page>
V 1.0 Aptech Limited
C
o
n
c
e
p
t
s
2
Device Capabilites
Step 3: Write Code Snippet 9 in the code behind of the page.
Code Snippet 9:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Devices.Enumeration;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace DeviceWatcherTest
{
public sealed partial class MainPage : Page
{
public MainPage() {
this.InitializeComponent();
}
Windows.UI.Core.CoreDispatcher d;
public static DeviceWatcher w = null;
public static int c = 0;
public static DeviceInformation[] i = new DeviceInformation[1000];
public static bool isComplete = false;
public static string Status = null;
V 1.0 Aptech Limited
C
o
n
c
e
p
t
s
2
Device Capabilites
Code Snippet 10 functon is to start the enumeraton.
Code Snippet 10:
async void fnDevicesWatch(object sender, RoutedEventArgs eventArgs)
{
try
{
d = Window.Current.CoreWindow.Dispatcher;
w = DeviceInformation.CreateWatcher();
w.Added += watcher_Added;
w.Removed += fnRemovedwatcher;
w.Updated += watcher_Updated;
w.EnumerationCompleted += fnEnumComplete;
w.Stopped += fnStoppedwatcher;
w.Start();
txtResult.Text = Enumeration started.;
}
catch (ArgumentException)
{
txtResult.Text = Caught ArgumentException. Failed to create watcher.;
}
}
V 1.0 Aptech Limited
C
o
n
c
e
p
t
s
2
Device Capabilites
Code Snippet 11 functon is to stop the enumeraton.
Code Snippet 11:
async void StopWatcher(object sender, RoutedEventArgs eventArgs)
{
try
{
if (w.Status == Windows.Devices.Enumeration.DeviceWatcherStatus.Stopped)
{
Status = The enumeration is already stopped.;
}
else
{
w.Stop();
}
}
catch (ArgumentException)
{
txtResult.Text = Caught ArgumentException. Failed to stop watcher.;
}
}
V 1.0 Aptech Limited
C
o
n
c
e
p
t
s
2
Device Capabilites
Code Snippet 12 is to display the device list if the enumeraton is completed.
Code Snippet 12:
async void watcher_Added(DeviceWatcher sender, DeviceInformation
deviceInterface)
{
i[c] = deviceInterface;
c += 1;
if (isComplete)
{
await d.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
fnDisplayDeviceList();
});
}
}
Code Snippet 13 is used to update the device list if the enumeraton is completed.
Code Snippet 13:
async void watcher_Updated(DeviceWatcher sender, DeviceInformationUpdate
devUpdate)
{
int count2 = 0;
foreach (DeviceInformation deviceInterface in i)
{
if (count2 < c)
{
if (i[count2].Id == devUpdate.Id)
{
//Update the element.
i[count2].Update(devUpdate);
}
}
count2 += 1;
V 1.0 Aptech Limited
C
o
n
c
e
p
t
s
2
Device Capabilites
}
await d.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
txtResult.Text = Enumeration updated. ;
fnDisplayDeviceList();
});
}
Code Snippet 14 is used to remove the existng device list if the enumeraton is completed.
Code Snippet 14:
async void fnRemovedwatcher(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 < c)
{
if (i[count2].Id == devUpdate.Id)
{
//Remove the element.
interfaceList.RemoveAt(count2);
}
}
count2 += 1;
}
//Convert the list back to the interfaces array.
i = interfaceList.ToArray();
c -= 1;
await d.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
V 1.0 Aptech Limited
C
o
n
c
e
p
t
s
2
Device Capabilites
txtResult.Text = Enumeration device was removed. ;
fnDisplayDeviceList();
});
}
async void fnEnumComplete(DeviceWatcher sender, object args)
{
isComplete = true;
await d.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
txtResult.Text = Enumeration complete. ;
fnDisplayDeviceList();
});
}
V 1.0 Aptech Limited
C
o
n
c
e
p
t
s
2
Device Capabilites
Code Snippet 15 is used to stop the enumeraton.
Code Snippet 15:
async void fnStoppedwatcher(DeviceWatcher sender, object args)
{
if (w.Status == Windows.Devices.Enumeration.DeviceWatcherStatus.Aborted)
{
Status = Enumeration stopped.;
}
}
async void fnDisplayDeviceList()
{
lstResult.Items.Clear();
int count2 = 0;
foreach (DeviceInformation deviceInterface in i)
{
if (count2 < c)
{
fnDisplayDeviceInterface(deviceInterface);
}
count2 += 1;
}
}
V 1.0 Aptech Limited
C
o
n
c
e
p
t
s
2
Device Capabilites
Code Snippet 16 is used to display device informaton.
Code Snippet 16:
async void fnDisplayDeviceInterface(DeviceInformation deviceInterface)
{
var id = Id: + deviceInterface.Id;
var name = deviceInterface.Name;
var isEnabled = IsEnabled: + deviceInterface.IsEnabled;
var item = id + is \n + name + and \n + isEnabled;
lstResult.Items.Add(item);
}
}
}
Step 4: The output screen to display the page when the user executes the app as shown in fgure 2.12.
Figure 2.12: Output Screen
V 1.0 Aptech Limited
C
o
n
c
e
p
t
s
2
Device Capabilites
Step 5: The output screen to display the device informaton when the user clicks watch all device buton
as shown in fgure 2.13.
Figure 2.13: Output
V 1.0 Aptech Limited
C
o
n
c
e
p
t
s
2
Device Capabilites
2.5 Check Your Progress
1. ___________ will search the device only once as the device is connected.
(A) CreateWatcher (C) GUID class
(B) FindAllAsync (D) Enumerate devices
2. Microsof has released the common GUID class with __________, which is called and tested for
enumeraton.
(A) Windows 8 (C) Windows 7
(B) Windows 8.1 (D) Windows 9
3. ________________ is a mixture of hardware and sofware that enables a system to identfy and
get used to hardware structure modifcatons by the user.
(A) Plug and Play (C) Sensitive devices
(B) App manifest (D) GPS
4. _________ supports many sensors.
(A) Windows 8.1 (C) Windows Vista
(B) Windows 8 (D) Windows XP
5. The LightSensor is used to increase or decrease the __________ of the device.
(A) Colour (C) Sensor
(B) Resoluton (D) Brightness
Edited by Foxit Reader
Copyright(C) by Foxit Software Company,2005-2008
For Evaluation Only.
V 1.0 Aptech Limited
C
o
n
c
e
p
t
s
2
Device Capabilites
Summary
Windows.Devices.Enumeraton and Windows.Devices.Enumeraton.Pnp are the two namespaces
to enumerate the devices connected or disconnected.
To enumerate devices the user has to frst identfy the GUID class for the device to be tested.
The DeviceWatcher class is in charge for device enumeraton with passion; foatng exact events
each tme the devices are added, removed, or altered afer the inital enumeraton is fnished.
Some of the competence acknowledged in the app manifest fle such as microphone, camera, and
the locaton can expose private informaton.
Windows.Devices.Sensors namespace is used to capture moton, device orientaton or light
sensors.
To make use of this orientaton the user has to select the supported rotatons from the applicaton
tab in the app manifest fle.
V 1.0 Aptech Limited
C
o
n
c
e
p
t
s
2
Device Capabilites
Generating Revenue Apps
Session - 3
Welcome to the Session, Generating Revenue Apps.
This session introduces you to concepts of generatng revenue apps in the Windows
Store. Users can earn money by developing apps that generate revenue. This
session shows the user how to develop and distribute the apps through Windows
Store.
In this Session, you will learn to:
Explain Trial Functonality
Describe the process of In-app Purchase
Explain the process of Advertsing in Windows Store apps

C
o
n
c
e
p
t
s
Session
V 1.0 Aptech Limited
3
Generatng Revenue Apps
3.1 Implementng Trial Functonality in a Windows Store App
When users selects free trial or try from an app, then the user is allowed to use the app upto certain
period, which may vary from 7 to 30 days. If the trial period ends, same user cannot use that app
anymore unless the app is purchased. For example, if the user wants to buy the chess challenger app as
shown in fgure 3.1, the user can try for a certain period and if the app is as per the expectatons of the
user, then the user can purchase the same app.
Figure 3.1: Trial App
Implementng the trial functonality for an app will help the user for marketng the app, and Microsof
Apps Store recommends it. It is recommended to implement these trial functonalites in an app so that
user can get a chance to evaluate the app. If the user fnds the app to be useful then he/she may purchase
the same from the Windows Store and get full benefts. If the developer uploads an app that costs high
and does not provide any trial functonality in it, then it will be more difcult to sell or market the app.
The customers will think before they purchase an app for higher cost. Putng some screenshots, ratngs,
or reviews in the store may convince the customers to purchase the app. This will lead to increase in the
sale of an app.
Time-Based Trials
To set a trial-based app, the user has to set a tme or date calculaton mechanism in the store app. The
store will take care of the app as the trial period ends, so the user need not worry about the usage of the
app afer trial period. While submitng the app in the store the developer has to specify the trial period
in days for the app as shown in fgure 3.2. The trial period will starts when the user downloads and installs
the app from the store. When the trial expires, Windows Store will automatcally prompt the user to pay
for the app if he/she wishes to contnue using the app or else the app will stop executon.

C
o
n
c
e
p
t
s
Session
3
V 1.0 Aptech Limited
Generatng Revenue Apps
No special programming skills are required to do the same. Windows Store will take care of tracking the
trial period.
Figure 3.2: Set Trial Period for the App
In Windows Store apps, LicenseInformation class stores the license state in the app property.
The user has to create functons that depend on the license state. The developer has to decide how to
handle changes to the apps license while the app is running. The trial app can be full-featured version.
Such version of the app can have in-app ad banners, whereas the paid-for version should not have such
in-apps or ad banners. Other alternatve is that the trial app can disable certain features, or display
regular messages asking the user to buy it. To make a good trial app, the developer can create the app
by removing the some features or setng up to various levels of the app. Each level will have certain
features installed in it, while others will not have these features. Even the developer of the app can
charge diferent prices for diferent level. Most of the tme such strategy, is applied with various levels in
game apps.
Feature-Diferentated Trials
When the app trial period expires while running, the user can display a message to the customer regarding
the expiry of the trial period or send a notfcaton in prior. The user has to menton these reminders using
the tme-based trial period.
To check the app is in trial license, the user have to write a code as shown in Code Snippet 1.

C
o
n
c
e
p
t
s
Session
V 1.0 Aptech Limited
3
Generatng Revenue Apps
Code Snippet 1:
// function to check the licenseinfo
private async void fnLicenseInfo()
{
//license info is retrieved
var l = CurrentAppSimulator.LicenseInformation;
if (l.IsActive)
{
// check if there is any trial version, and show appropriate message
if (l.IsTrial)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, ()
=>
{
txtDetail.Text = License status: Trial license;
var r = (l.ExpirationDate - DateTime.Now).Days;
txtDetail.Text += System.Environment.NewLine + String.Format(Remaining days:
{1}, l.ExpirationDate, r); });
}
else
//otherwise set message to full version
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, ()
=>
{
txtDetail.Text = License status: Full license;
txtDetail.Text += no expiry;
});
}
}
else
{

C
o
n
c
e
p
t
s
Session
3
V 1.0 Aptech Limited
Generatng Revenue Apps
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, ()
=>
{
txtDetail.Text = License status: license expired. Purchase the app!;
});
}
}
Every tme the app is loaded, the code will check the app and determine whether it is running in trial
period. If the trial period has not expired then it will display days remaining for expiry of the app. These
details are stored in the .confg fle. When the code is executed, the output will be as shown in fgure 3.3.
Figure 3.3: Trial App Demonstratons
The user can get all the app license informaton using the namespace Windows.ApplicationModel.
Store.CurrentApp statc class. The user can set a Boolean value to check if the app is in trial
mode or not. To check this, the developer can check the value returned by the property CurrentApp.
LicenseInformation.IsTrial. To check this conditon the developer must ensure that
CurrentApp.LicenseInformation.IsActive property is set to true.
3.2 Implement In-app Purchases
In-app purchase means the ability of an app to allow sale or purchase of the app with the help of devices
such as a mobile, tablet or a PC. Many tmes such in-app purchase is allowed within games and other
useful apps that allow the users to pay online and start using all the features of the app. The user can
easily purchase such an app without any trouble. The apps are normally actvated immediately afer
in-app purchases. There is no need to download and update a fresh copy of the app that is already
downloaded and is running on the systems. To develop an app with in-app purchase feature, the user has

C
o
n
c
e
p
t
s
Session
V 1.0 Aptech Limited
3
Generatng Revenue Apps
to create a .confg fle that includes all the informaton about the app. This can be done by adding the
code shown in Code Snippet 2 to the appropriate confg fle.
Code Snippet 2:
<?xml version=1.0 encoding=utf-16 ?>
<CurrentApp>
<ListingInformation>
<App>
<AppId>00000000-0000-0000-0000-000000000000</AppId>
<LinkUri>
http://apps.microsoft.com/webpdp/app/00000000-0000-0000-0000-000000000000
</LinkUri>
<CurrentMarket>en-US</CurrentMarket>
<AgeRating>3</AgeRating>
<MarketData xml:lang=en-us>
<Name>LicenseTest</Name>
<Description>Will check the license info</Description>
<Price>10.00</Price>
<CurrencySymbol>$</CurrencySymbol>
<CurrencyCode>USD</CurrencyCode>
</MarketData>
</App>
<Product ProductId=1 LicenseDuration=0>
<MarketData xml:lang=en-us>
<Name>License App</Name>
<Price>1.00</Price>
<CurrencySymbol>$</CurrencySymbol>
<CurrencyCode>USD</CurrencyCode>
</MarketData>
</Product>
</ListingInformation>

C
o
n
c
e
p
t
s
Session
3
V 1.0 Aptech Limited
Generatng Revenue Apps
<LicenseInformation>
<App>
<IsActive>true</IsActive>
<IsTrial>true</IsTrial>
<ExpirationDate>2014-06-30T09:00:00.00Z</ExpirationDate>
</App>
<Product ProductId=1>
<IsActive>true</IsActive>
</Product>
</LicenseInformation>
</CurrentApp>
In Code Snippet 2, the user has to declare two elements, namely ListingInformation and
LicenseInformation. The listng informaton will hold all the details of the app. This listng
informaton will hold the app name, descripton, pricing details; whereas, LicenseInformation will
hold the app license details such as trial details, expiry date (if trial), and product availability.
Code Snippet 3:
private async System.Threading.Tasks.Task fnLoadLicenseInfo()
{
StorageFolder proxyDataFolder = await Package.Current.InstalledLocation.
GetFolderAsync(Data);
StorageFile proxyFile = await proxyDataFolder.GetFileAsync(storelicense.
xml);
await CurrentAppSimulator.ReloadSimulatorAsync(proxyFile);
}
Code Snippet 3 will get the xml fle from the data folder. The xml fle must be saved under a folder called
data folder.
3.3 Setng up In-app Purchases
This is the most important step for setng up the correct license type for an app developed by the user.
To sell an app, the user must analyze and decide the correct pricing that can be charged while selling this
app. Price must be compettve than the other similar apps in the market. Another possibility is that, if
the user is allowed to try an app for a certain period, he/she will be able to utlize the features of the app.
He/she can explore if it is helpful for him/her. It will build confdence in the mind of the customers. Thus,

C
o
n
c
e
p
t
s
Session
V 1.0 Aptech Limited
3
Generatng Revenue Apps
a decision to purchase the app might be taken. This can lead to a beter marketng strategy for the app
owner.
Figure 3.4: In-app Purchase Details
Figure 3.4 shows how to set up the app purchase. There are two possibilites for setng up trial versions
for any app.
Time Based Trial
This is tme based trial version of an app. It will have all the features of the app, but afer a certain
period, i.e. afer the trial period, the app will automatcally expire and stop executon. The user will
not be able to use the app further. The developer of the app can set the period within the range
of 1 day to 365 days. It can be defned or set under product lifetme secton as shown in fgure 3.4.
Feature Based Trial
Featured apps will allow the users to access the app up to a certain level untl user purchases the
full version. For example, if the user installs a trial version of a game app, the app owner will be
restricted and will be able to play the game only up to certain levels. Some of the levels in the game
will be locked so that the user cannot move and play the next levels. Once the user pays and pur-
chases the same, he/she will be allowed to play all the levels and remaining levels will be unlocked
for him/her. This is how the feature based trial works. Here, a specifc tme limit is not given.
3.4 Advertsing in a Windows Store App
More ad platorms are available in Windows Store. The developer can develop an advertsement, which
pays him/her every tme a customer clicks such advertsement. This is known as Pay per Click (PPC). Some
apps will have the advertsement and when the ad is displayed, the developer of such an app is paid
whenever an impression is shown. Such an app is known as Pay per Impression (PPI). To integrate ads in

C
o
n
c
e
p
t
s
Session
3
V 1.0 Aptech Limited
Generatng Revenue Apps
the store app the developer has to register with Microsof pubCenter as shown in fgure 3.5.
Figure 3.5: Create an Account in PubCenter
The developer can manage their account from http://pubcenter.microsoft.com and Windows
Store dashboard. Visual Studio 2013 includes some built-in connecton for pubCenter, as shown in fgure
3.6. The developer has to sign in with his/her details such as Name, Address, Contact Number, Bank
Details, App name and price to be charged. Afer he/she logs in successfully, it is possible to upload the
store app, monetze the same, and start earning revenues from it. This process is known as monetzaton.
Figure 3.6: Manage Ads in PubCenter

C
o
n
c
e
p
t
s
Session
V 1.0 Aptech Limited
3
Generatng Revenue Apps
There are standard ad sizes to implement in the app. Table 3.1 shows the standard ad size and its unit id.
Ad Size Descripton Unit Id
160 x 600 Image Ad 10043136
160 x 600 Video Ad 10043135
160 x 600 Image Ad 10043134
250 x 250 Image Ad 10043107
250 x 250 Image Ad 10043104
300 x 250 Image Ad 10043055
300 x 250 Video Ad 10043056
300 x 250 Image Ad 10043057
300 x 600 Image Ad 10043030
728 x 90 Image Ad 10043000
728 x 90 Video Ad 10042999
728 x 90 Image Ad 10042998
Table 3.1: Ad Size and Unit ID
Note - Advertsing SDK can be downloaded from URL. htp://download.microsof.com/download/A/
B/A/ABA21B24-962A-4DFE-A88C-694BEFFFBBA2/W8AdSDK-ENU.msi
Afer installing SDK, the user can view the ad control tool in the toolbox of visual studio as shown in fgure
3.7.
Figure 3.7: AdControl in Toolbox
The user can use AdControl to display ads in the applicaton. Microsof has provided an applicaton id

C
o
n
c
e
p
t
s
Session
3
V 1.0 Aptech Limited
Generatng Revenue Apps
for the developers to test the ad control. This applicaton id is as follows:
Application ID: d25517cb-12d4-4699-8bdc-52040c712cab
To test the Ad control the user has to write the code as provided in Code Snippet 4.
Code Snippet 4:
<Page xmlns: UI=using:Microsoft.Advertising.WinRT.UI
x:Class=AdvertisementDemo.MainPage
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
xmlns:local=using:AdvertisementDemo
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}>
<UI:AdControl x:Name=AdControl Grid.ColumnSpan=99 Grid.Row=1
ApplicationId=d25517cb-12d4-4699-8bdc-52040c712cab
AdUnitId=10042999 Width=728 Height=90
HorizontalAlignment=Center Margin=0,10,0,0/>
</Grid>
</Page>
When the user executes the code, the advertsing banner will be displayed as shown in fgure 3.8.
Figure 3.8: Ad Displayed in the App

C
o
n
c
e
p
t
s
Session
V 1.0 Aptech Limited
3
Generatng Revenue Apps
Now, let us see how to specify the licensing setng in the app. Following example gives systematc
instructons to set the licensing details.
Licensing an App
Licensing an app in Windows Store is made easy by Microsof. You can do the same through few steps.
Most of the functonalites are in-built in the Store apps framework.
Create a blank new applicaton and add code given in Code Snippet 5 to MainPage.xaml.
Code Snippet 5:
<Page x:Class=TrialApp.MainPage
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
xmlns:local=using:TrialApp
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}>
<TextBlock HorizontalAlignment=Left TextWrapping=Wrap FontSize=18
Text=Trial App VerticalAlignment=Top Margin=603,300,0,0/>
<TextBlock HorizontalAlignment=Left TextWrapping=Wrap FontSize=18
x:Name=txtDetail VerticalAlignment=Top Margin=510,397,0,0/>
<Button x:Name=btnPurchase Content=Purchase HorizontalAlignment=Left
VerticalAlignment=Top Margin=500,455,0,0 Click=btnCalculate_Click/>
<Button x:Name=btnCalculate Content=Details HorizontalAlignment=Left
VerticalAlignment=Top Margin=660,455,0,0 Click=btnDetails_Click/>
</Grid>
</Page>
The code given in Code Snippet 5 adds two TextBlocks and two Butons to the page design. First
TextBlock shows a message Trial App and second TextBlock shows a message txtDetails.
There are two butons also; they are btnCalculate and btnPurchase. The user can click any of
this butons to either purchase it or calculate the price.

C
o
n
c
e
p
t
s
Session
3
V 1.0 Aptech Limited
Generatng Revenue Apps
Create a New Folder as shown in fgure 3.9. Under this folder, create a New Item as shown in fgure 3.10.
Figure 3.9: Create a New Folder
Figure 3.10: Create a New Item

C
o
n
c
e
p
t
s
Session
V 1.0 Aptech Limited
3
Generatng Revenue Apps
Create an xml and give name as StoreLicense.xaml fle to store the license informaton, as shown
in fgure 3.11. This fle will hold all the licensing details.
Figure 3.11: Create a New xml File
Now, add the following details to the fle StoreLicense.xaml. Write the code given in Code Snippet 6 with
tags to store the license informaton.
Code Snippet 6:
<?xml version=1.0 encoding=utf-16 ?>
<CurrentApp> <ListingInformation>
<App> <AppId>00000000-0000-0000-0000-000000000000</AppId>
<LinkUri>
http://apps.microsoft.com/webpdp/app/00000000-0000-0000-0000-000000000000
</LinkUri>
<CurrentMarket>en-US</CurrentMarket>
<AgeRating>3</AgeRating>
<MarketData xml:lang=en-us>
<Name>LicenseTest</Name>
<Description>Will check the license info</Description>
<Price>10.00</Price>
<CurrencySymbol>$</CurrencySymbol>
<CurrencyCode>USD</CurrencyCode>
</MarketData>

C
o
n
c
e
p
t
s
Session
3
V 1.0 Aptech Limited
Generatng Revenue Apps
</App>
<Product ProductId=1 LicenseDuration=0>
<MarketData xml:lang=en-us>
<Name>License App</Name>
<Price>1.00</Price>
<CurrencySymbol>$</CurrencySymbol>
<CurrencyCode>USD</CurrencyCode>
</MarketData>
</Product>
</ListingInformation>
<LicenseInformation>
<App>
<IsActive>true</IsActive>
<IsTrial>true</IsTrial>
<ExpirationDate>2014-06-30T09:00:00.00Z</ExpirationDate>
</App>
<Product ProductId=1>
<IsActive>true</IsActive>
</Product>
</LicenseInformation>
</CurrentApp>
Add the code given in Code Snippet 7 in the code behind fle called MainPage.xaml.cs.
Code Snippet 7:

C
o
n
c
e
p
t
s
Session
V 1.0 Aptech Limited
3
Generatng Revenue Apps
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Store;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;

C
o
n
c
e
p
t
s
Session
3
V 1.0 Aptech Limited
Generatng Revenue Apps
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 TrialApp
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
await this.fnLoadLicenseInfo();
}
private async System.Threading.Tasks.Task fnLoadLicenseInfo()
{
StorageFolder proxyDataFolder = await Package.Current.InstalledLocation.
GetFolderAsync(Data);
StorageFile proxyFile = await proxyDataFolder.GetFileAsync(storelicense.
xml);
await CurrentAppSimulator.ReloadSimulatorAsync(proxyFile);
}
private void btnCalculate_Click(object sender, RoutedEventArgs e)
{
LicenseInformation l = CurrentAppSimulator.LicenseInformation;
if (l.IsTrial)
{

C
o
n
c
e
p
t
s
Session
V 1.0 Aptech Limited
3
Generatng Revenue Apps
txtDetail.Text = The app is currently in Trial license;
}
}
private void btnDetails_Click(object sender, RoutedEventArgs e)
{
LicenseInformation l = CurrentAppSimulator.LicenseInformation;
if (l.IsActive)
{
if (l.IsTrial)
{
fnLicenseInfo();
}
}
}
private async void fnLicenseInfo()
{
var l = CurrentAppSimulator.LicenseInformation;
if (l.IsActive)
{
if (l.IsTrial)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, ()
=>
{
txtDetail.Text = License status: Trial license.;
var r = (l.ExpirationDate - DateTime.Now).Days;
txtDetail.Text += System.Environment.NewLine + String.Format(
Remaining days: {1}, l.ExpirationDate, r);
});
}
else
{

C
o
n
c
e
p
t
s
Session
3
V 1.0 Aptech Limited
Generatng Revenue Apps
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, ()
=>
{
txtDetail.Text = License status: Full license;
txtDetail.Text += no expiry;
});
}
}
else
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
() =>
{
txtDetail.Text = License status: license expired. Purchase the app!;
});
}
}
}
}
When the user executes the app, the output will be as shown in fgure 3.12. Either the user can select to
purchase the app or he/she can just view the details by clicking the appropriate buton.
Figure 3.12: Output When Executed

C
o
n
c
e
p
t
s
Session
V 1.0 Aptech Limited
3
Generatng Revenue Apps
If the user clicks the Purchase buton then the output will be as shown in fgure 3.13.
Figure 3.13: Output When Purchase Buton is Clicked
User can even click the Details buton to see the details of the current applicaton. When the user
executes the app and clicks the Details buton, the output will be as shown in fgure 3.14.
Figure 3.14: Output When Details Buton is Clicked
When user click the Details buton, app will check if the trial period has expired. If the trial period is
expired then the app will stop executon. If the trial period is not expired then the app will show a
message that tells us how many days are remaining. This is how the trial functonality is added in the
store app.

C
o
n
c
e
p
t
s
Session
3
V 1.0 Aptech Limited
Generatng Revenue Apps
3.5 Check Your Progress
1. The ________ will take care of the app as the trial period ends, so the user need not worry about
the usage of the app afer trial period.
(A) Store (C) Developer
(B) User (D) App
2. _____________ class stores the license state in the app property.
(A) Notification (C) Apps license
(B) LicenseInformation (D) Namespace
3. Some app will have an ad and when user clicks this ad, the store will pay the user and this process
is known as ____________.
(A) Integrated ads (C) Pay per click
(B) Ad platform (D) Pay per impression
4. The user can set a _________ value to catch the app is in trial mode or not.
(A) Boolean (C) Ad
(B) Store (D) Purchase
5. Putng some screenshots, ratngs, or reviews in the Store may convince the customers to purchase
the _________.
(A) Ad (C) Store
(B) App (D) Space
Edited by Foxit Reader
Copyright(C) by Foxit Software Company,2005-2008
For Evaluation Only.

C
o
n
c
e
p
t
s
Session
3
V 1.0 Aptech Limited
Generatng Revenue Apps
Summary
When a user selects free trial or tries an app, then the user is allowed to use the app up to a
certain limited period, which may vary from 7 30 days.
To set a trial-based app, the user has to set a tme or date calculaton in the store app.
Trial app can be full-featured, but can have in-app ad banners where the paid-for version does not
have such in-app ad banners. Such banners are completely removed from the paid version.
In the XAML fle, the user declares and assigns some values to two main elements, namely
ListngInformaton and LicenseInformaton.
The user can develop the ad, which pays the user whenever a customer clicks such ads. This is
known as Pay per Click.
To integrate ads in the store app the developer has to register with Microsof pubCenter.
Developing Universal Apps
Session - 4
Welcome to the Session, Developing Universal Apps.
This session will help you to learn how to develop apps for mobile and use it
universally in the Windows Store.
In this Session, you will learn to:
Explain the Windows Phone 8.1 Platorm Features
Explain Universal Apps
Explain the process of Packaging an App
Explain the process of Deploying an App

C
o
n
c
e
p
t
s
Session
V 1.0 Aptech Limited
4
Developing Universal Apps
4.1 Introducton to Windows Phone 8.1
Microsof introduced universal Windows apps for PCs, phones, and tablets with Visual Studio 2013
Update. This Update for Windows Phone 8.1 is named as Cortana and they have targeted mainly for
gamers. For the non-gaming users, the device will be faster and accessible in seconds.
Gain access to conclude a Live Tile, or press the search buton, this update will support most apps, calls,
messages, searches, and music on the user phone. Cortana interacts through the third-party apps, such
as Facebook and Twiter to share the links or test through the post.
4.1.1 Building Windows Store Apps
The user can develop the apps to target the mobile. To develop the app, the user has to follow the steps.
These steps will demonstrate to create a Hello World app.
4.1.2 Hello World in Windows Phone
Step 1: Open Microsof Blend and Select New Project. Select Windows Phone from the lef side menu
and select Windows Phone App from the right side menu as shown in fgure 4.1.
Figure 4.1: Create a Phone App

C
o
n
c
e
p
t
s
Session
4
V 1.0 Aptech Limited
Developing Universal Apps
Step 2: Design the app page as shown in fgure 4.2.
Figure 4.2: Design the App Page
Step 3: Once the page design is completed, connect the Windows mobile to the PC and run the applicaton.
The app will be installed in Windows phone. The user can view and access the app directly from the
device.
4.2 Windows Phone 8.1 Platorm Features
Following are the features of Windows phone 8.1:
y Geolocaton
Geolocatons is upgraded by adding a new class called Geofencing. This API is used to track the device
upto a certain area and sends a notfcaton whenever the device comes within network coverage area.
This API gives details about longitude and lattude. It uses GPS, IP Address, RFID, WiFi, Bluetooth MAC
Address, and GSM/CDMA cell IDs to determine the locaton.
y Maps
Windows Phone 8.1 maps is upgraded with a new feature by viewing the map ofine tles and improved
routng. Using Map API, the developer can create map-based apps and incorporate locaton and search
features in the app.
y Background transfers
Background transfer is used to transfer data in the background by calling the Background Task features.
y Windows Push Notfcaton Services (WNS)
Windows Phone 8.1 includes Windows Push Notfcaton Services (WNS) to send Toast, Tile, and Raw
updates to the user device, which are received from a cloud service.

C
o
n
c
e
p
t
s
Session
V 1.0 Aptech Limited
4
Developing Universal Apps
y Controls
Windows Phone 8.1 is developed using the XAML framework. Similar to store apps, the XAML controls
for Phone 8.1 includes the basic and essental controls such as Buton, TextBlock, CheckBox, FlipView,
GridView, ListView, Password, and Zoom controls.
y Globalizaton
Windows Phone 8.1 supports many internatonal languages, which can be called through the Globalizaton
namespace. Using this feature it is possible to developed apps with support to various internatonal
languages.
y Calendar
Calendar is declared in a diferent way in Windows Phone 8.1 and supports Appointment API. This API is
also available for developing Windows Store apps with calendar features.
y Browser
Internet Explorer 11 is enabled to allow Windows Phone 8.1 apps. This is possible using WebView control
provided in Windows Store apps. WebView supports features of HTML5 apps which is used to display
responsive layouts.
y External display support
Windows Phone enables the external display support by mirroring the phone display to PC through a USB
cable. The contents of phone can easily be displayed directly on the PC screen.
y Data and storage
Windows.Storage API is associated to stream-based fles. It allows the users to store data locally.
This will ask the user where to store the downloaded fle.
y Roaming
Windows Phone 8.1 supports roaming data. Roaming data feature is available when the lock is enabled
and the device is actve. Roaming data fles are stored inside the Roaming data folder. For any app, the
size of the roaming data is restricted upto 100 Kb only.
y Share contact
Windows Phone 8.1 introduces the Share contact that allows sharing fles, images, and videos to any
contact that is present in the current device. The data is generally shared using an e-mail.
y SD card
In Windows Phone 8, only reading SD card was possible. However, now in Windows Phone 8.1, reading
and writng to and from SD card is possible.
4.3 Universal Apps
Microsof has released Windows Phone 8.1 in the month of April 2014 which is named as Cortana. This is
enabled and available in Visual Studio 2013 with Update 2. These new features allows the developers to

C
o
n
c
e
p
t
s
Session
4
V 1.0 Aptech Limited
Developing Universal Apps
build global apps, which works with phones, tablets, and PC as well. Windows 8.1 Update has also added
UI enhancements for mouse and keyboard and other useful features. This developer platorm will expand
to customers using devices like phones, tablets, and PCs.
Windows Phone 8 holds the same set of tools and procedures that are included in Windows 8. In order
to develop universal app the user have to select Universal Apps from the New Project Menu as shown
in fgure 4.3.
Figure 4.3: Create Universal App
Users can develop the Phone 8.1 universal app with the same runtme. This is similar to designing and
developing apps for phones, tablets and PCs.
4.4 Packaging an App
Windows Runtme app package will be created with an extension as .appx, which is ready-to-install app
in the devices.
This package will have following optons:
y App payload : App code fles and assets
y App manifest : App manifest fle (AppxManifest.xml)
y App block map : App packages block map fle (AppxBlockMap.xml)
y App signature : App packages digital signature fle (AppxSignature.p7x)
To create the package the user has to follow some steps. When the developer fnishes developing the app
completely, then it is ready to be packed.

C
o
n
c
e
p
t
s
Session
V 1.0 Aptech Limited
4
Developing Universal Apps
Step 1: Afer developing the app, navigate to Projects Store Create App Packages as shown in
fgure 4.4.
Figure 4.4: Selecton of Create App Packages
Step 2: Afer selectng the menu, the Create App Packages will be displayed as shown in fgure 4.4. To
test the app in the local machine the user recommends selectng No from the opton as shown in fgure
4.5.
Figure 4.5: Create Your Packages Screen
Step 3: In this step, the developer has to provide the version and build number details. This procedure
is same as publishing the Windows applicatons. Afer providing the version numbers click the Create
buton to create the app package as shown in fgure 4.6.

C
o
n
c
e
p
t
s
Session
4
V 1.0 Aptech Limited
Developing Universal Apps
Figure 4.6: Select and Confgure Packages Screen
4.5 Deploying an App
Once the app is published, the user can view the published app in their project folder. To deploy the user
have to CLICK the Package fle as shown in fgure 4.7 and run with PowerShell.
Figure 4.7: Selectng Run with PowerShell Opton

C
o
n
c
e
p
t
s
Session
V 1.0 Aptech Limited
4
Developing Universal Apps
Once the acton menu is selected, the user can view the PowerShell window to confrm whether to install
the app in the device. The user has to type y and press Enter to start deploying as shown in fgure 4.8.
Figure 4.8: Windows PowerShell Screen
The user can see the installaton progress as shown in fgure 4.9.
Figure 4.9: App Deployment Process

C
o
n
c
e
p
t
s
Session
4
V 1.0 Aptech Limited
Developing Universal Apps
Once the app is deployed, the user can view the completon progress of the app as shown in fgure 4.10.
Figure 4.10: App Successfully Installed Screen
Packaging and Deploying Your App
Step 1: Create a blank new applicaton File New Project Blank App.
Step 2: Write the following code as shown in Code Snippet 1 for designing the frontend.
Code Snippet 1:
<Page
x:Class=AppPackageDemo.MainPage
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
xmlns:local=using:AppPackageDemo
xmlns:d=http://schemas.microsoft.com/expression/blend/2008
xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006
mc:Ignorable=d>
<Grid Background={ThemeResourceApplicationPageBackgroundThemeBrush}>
<TextBlock Text=App Packing Demo FontSize=25 Margin=570,368,473,363></
TextBlock>
</Grid>
</Page>

C
o
n
c
e
p
t
s
Session
V 1.0 Aptech Limited
4
Developing Universal Apps
Step 3: The UI is displayed as shown in fgure 4.11.
Figure 4.11: UI Design of the App
Step 4: Afer developing the app, Navigate to Projects Store Create App Packages as shown earlier
in fgure 4.4.
Step 5: Afer selectng the menu, Create App Packages as shown earlier in fgure 4.5
To test the app in the local machine the user recommends selectng No from the given opton, as shown
earlier in fgure 4.5.
Step 6: In this step, the developer has to provide the version and build number details. This procedure is
same as publishing the Windows applicaton. Afer providing the version numbers click the Create buton
to create the app package as shown earlier in fgure 4.6.
Step 7: Once the app is published, the user can view the published fle in the project folder as shown in
fgure 4.12.
Figure 4.12: Published Folder

C
o
n
c
e
p
t
s
Session
4
V 1.0 Aptech Limited
Developing Universal Apps
Step 8: When the user view the published folder, the user can view the app package fle, which can be
opened through PowerShell as shown in fgure 4.13.
Figure 4.13: Applicaton Files
Step 9: To deploy the user has to click the Package fle as shown in fgure 4.14 and run with PowerShell.
Figure 4.14: Click and Select the Acton
Step 10: Once the acton menu selected, the user can view the PowerShell window to confrm whether
to install the app in the device. The user has to type y and press enter to start deploying as shown earlier
in fgure 4.9.

C
o
n
c
e
p
t
s
Session
V 1.0 Aptech Limited
4
Developing Universal Apps
Step 11: The user can view the installaton process like the package fle as shown in fgure 4.15.
Figure 4.15: Process of Installaton
Step 12: Once the app is deployed, the user can view the completon progress of the app as shown earlier
in fgure 4.10.
Step 13: The app will be displayed in the Windows tle as shown in fgure 4.16.
Figure 4.16: Shortcut in the Home Screen

C
o
n
c
e
p
t
s
Session
4
V 1.0 Aptech Limited
Developing Universal Apps
Step 14: The user can open the fle to access the app as shown in fgure 4.17.
Figure 4.17: Output Screen

C
o
n
c
e
p
t
s
Session
V 1.0 Aptech Limited
4
Developing Universal Apps
4.6 Check Your Progress
1. _______________ introduced universal Windows apps for PCs, phones, and tablets with Visual
Studio 2013 Update.
(A) Micro word (C) Intel
(B) Microsoft (D) Linux
2. Geolocatons is upgraded by adding a new class called _____________.
(A) Geoforcing (C) Geofencing
(B) Geographic (D) Geostationary
3. Microsof has released Windows Phone 8.1 in the month of April 2014 that is named as ___________.
(A) Hagens (C) bermin
(B) Jared (D) cortana
4. Once the app is published, the user can view the published app in their _____________.
(A) Project folder (C) Data file
(B) Project file (D) Data folder
5. Windows Runtme app package will be created with an extension as ________, which is ready to
install the app in the device.
(A) .appl (C) .appx
(B) .appr (D) .apps
Edited by Foxit Reader
Copyright(C) by Foxit Software Company,2005-2008
For Evaluation Only.

C
o
n
c
e
p
t
s
Session
V 1.0 Aptech Limited
4
Developing Universal Apps
Summary
Microsof introduced universal Windows apps for PCs, phones, and tablets with Visual Studio 2013
Update.
Geolocatons is upgraded by adding a new class called Geofencing.
Windows Phone 8.1 supports roaming data. Roaming data is enabled when the lock is enabled
and the device is actve.
Microsof has released Windows Phone 8.1 in the month of April 2014 that is named as Cortana.
Windows 8.1 Update structures the UI enhancements for mouse and keyboard and other useful
enrichments.
Windows Phone 8 has stepped ahead with adding new feature and releasing Windows Phone 8.1
and Windows 8.1.
Managing Windows and
Web Authentication
Session - 5
Welcome to the Session, Managing Windows and Web Authentcaton.
This session introduces you to Windows and Web authentcaton in the
Windows Store Apps.
In this Session, you will learn to:
Authentcate using Windows Live Authentcaton
Authentcate using Web authentcaton protocols
Explain and use Group Policies
V 1.0 Aptech Limited
5
Managing Windows and Web Authentcaton
C
o
n
c
e
p
t
s
5.1 Authentcaton
Authentcaton is the process of determining the identty of a user based on the user credentals. Once
the authentcaton is done, then, the authorizaton process starts. Authorizaton means deciding which
resources can be used by the current user and accordingly allowing access rights to the currently logged
in user. Sometmes, impersonaton is also used. Impersonaton means the current user gets access to the
resources by using credentals of another user. In Windows 8.1, users can create their own credentals
to login to their devices. In order to login, the user has to create a Live ID for the devices. This will be
authentcated by the app that connects using LiveID within the Windows Store API. The Windows Store
app allows Live ID authentcatons using one of the following Live ID providers:
y Microsof Account
y Facebook Login
y Twiter Login
y Google Login
y Windows Azure Actve Directory (WAAD)
All the providers mentoned here can be used to authentcate the devices using Live IDs. However, this
session covers authentcaton using Microsof Account Live ID.
In Windows 8, login screen appears as shown in fgure 5.1. It shows the Windows authentcaton page
using Microsof Account Live ID.
Figure 5.1: Windows Authentcaton Page
A user can authentcate the devices through a Microsof account. This feature will be available only when
the user connects with the live account over the cloud from any device. Once the setng is saved, it will
automatcally be loaded in the device from the cloud whenever the device is reset or re-installed.
V 1.0 Aptech Limited
5
Managing Windows and Web Authentcaton
C
o
n
c
e
p
t
s
5.1.1 Managing Windows Authentcaton
CredentialLocker is one of the best optons available for the user authentcaton in Windows 8.
CredentialLocker can be used to store the credentals of a user over the cloud. Microsof has
also revealed many sign in optons for the password. Users can set their password through a Personal
Informaton Number (PIN) or they can set the same through a picture password.
In order to set your picture password or PIN:
y Swipe from the right side of your screen and click Setngs or drag your cursor to the
botom-right corner of the screen, and click.
y Click Change PC setngs.
y Under Account navigate to Sign-in optons.
From this screen, you can change your password, PIN or picture password.
Figure 5.2 shows the Account Details page with Sign-in optons.
Figure 5.2: Windows Sign-in optons
What is Credental Manager?
Credental Manager allows you to store user names and passwords that you use to log on to Web sites or
other computers. Windows can automatcally log you on to Web sites or other computers by storing the
credentals on local machine or on a cloud. Credental manager is used for this purpose.
Store passwords, certfcates, and other credentals for automatc logon
Credental Manager can be used to store credentals, such as user names and passwords that can be
used to log on to Web sites or other computers.
To add a password to Windows vault
Open User Accounts from the Start menu, click Control Panel User Accounts, in the lef pane, click
V 1.0 Aptech Limited
5
Managing Windows and Web Authentcaton
C
o
n
c
e
p
t
s
Manage your credentals. Click Add a Windows credental. In the Internet or network address box, type
the name of the computer that you want to access. This can be the NetBIOS name or DNS name. Enter
the username and password and click OK. This way you can store credentals in the system.
Same way, a user can set certfcates and other credentals for automatc logon. These topics do not fall
within the scope of this book, therefore, certfcate login and other credentals are not covered here.
What is CredentialLocker?
The CredentialLocker provides a way to store user credentals in a secure way for your app. It is
available in Windows.Security.Credentials namespace. CredentialLocker encrypts and
saves the credentals locally. Passwords and authorizaton tokens are used in mobile applicatons for user
authorizaton and connectng apps with services such as Twiter and Facebook. It is apps responsibility
to select secure storage for the credentals, encrypt the password, and provide credentals management
functonality, so user can modify password or revoke granted access.
CredentialLocker is used to simplify this task in Windows 8 and higher versions. The Locker allows
applicatons to store and retrieve users credentals in a secure way. All passwords are encrypted and
stored either locally or in the roaming profles and cannot be accessed by other applicatons.
CredentialLocker can be access using WinRT PasswordVault class. This class allows adding,
retrieving, and removing credentals from the locker. LiveAuthClient class is also used to retrieve
the session data from Microsof Account. In order to use the CredentialLocker, PasswordVault,
or LiveAuthClient, it is necessary to download and install Live SDK. With the help of Live SDK, it
becomes easy to authentcate users using Live IDs.
There are two types of storage mechanism used by CredentialLocker:
Secured storage
The great beneft that CredentialLocker ofers for the app is that, it is used to store the credentals
in a secured area by encryptng the credentals before they are stored. Many tmes, the user makes a
mistake of storing the credentals in plain text format while developing the app. This leads to a security
hole in the app. Therefore, the user has to ensure that the credentals are encrypted and stored, so that it
would have no security hole and user authentcaton will be secured. It is also easy to access and operate
using this type of authentcaton.
Roaming credentals
CredentialLocker provides benefts to the user in many ways. One of them is that, when the device
is in roaming profle, the app stores credentals over the cloud. So, whenever the user is logged in to the
device, it can be authentcated from anywhere as the device is connected to the cloud. Meanwhile, if the
users save the credentals in the device by selectng remember password opton, the device will not ask
for the credentals, rather it just signs-in automatcally without promptng for the credentals every tme
the user connects to the network. The user account details that are stored in the memory are utlized to
authentcate the user.
How to add authentcaton details in a CredentialLocker?
A CredentialLocker can be used easily in two steps to access the authentcaton informaton.
First, use the PasswordVault class and second, use PasswordCredential class. An instance of
V 1.0 Aptech Limited
5
Managing Windows and Web Authentcaton
C
o
n
c
e
p
t
s
PasswordVault class will have a method called Add() which can be used to add the credentals to the
CredentialLocker.
Code Snippet 1 shows how to create an instance of the PasswordVault and how to add the credentals
inside it.
Code Snippet 1:
var vlt = new Windows.Security.Credentials.PasswordVault();
vlt.Add(new Windows.Security.Credentials.PasswordCredential(My App,
username, password));
In Code Snippet 1, a variable called vlt is created as an instance of PasswordVault. Then, Add()
method of PasswordVault is called, where a PasswordCredential object is passed and stored
in the PasswordVault.
Retrieving user credentals
You have several optons for retrieving user credentals from the CredentialLocker afer you have
a reference to the PasswordVault object. You can retrieve all the credentals the user has supplied
for your app in the locker with the PasswordVault.RetrieveAll() method. If you know the
username for the stored credentals, you can retrieve all the credentals for that username with the
PasswordVault.FindAllByUserName() method. If you know the resource name for the stored
credentals, you can retrieve all the credentals for that resource name with the PasswordVault.
FindAllByResource() method. Finally, if you know both the username and the resource name for
a credental, you can retrieve just that credental with the PasswordVault.Retrieve()method.
Let us look at an example where we have stored the resource name globally in an app and we log the user
on automatcally, if we fnd a credental for them. In the case where we fnd multple credentals for the
user, we ask the user to select a default credental to use when logging on.
Code Snippet 2 shows how to retrieve login credentals using CredentialLocker.
Code Snippet 2:
private string resName = MyStoreApp;
private string defaultUName;
private void Login()
{
var loginCredl = GetCredFromLocker();
if (loginCredl != null)
{
loginCredl.RetrievePassword();
}
else
V 1.0 Aptech Limited
5
Managing Windows and Web Authentcaton
C
o
n
c
e
p
t
s
{
loginCredl = GetLoginCredentialUI();
}
ServerLogin(loginCredl.UserName, loginCredl.Password);
}
private Windows.Security.Credentials.PasswordCredential GetCredFromLocker()
{
Windows.Security.Credentials.PasswordCredential cred = null;
var vlt = new Windows.Security.Credentials.PasswordVault();
var credList = vault.FindAllByResource(resName);
if (credList.Count > 0)
{
if (credList.Count == 1)
{
cred = credentialList[0];
}
else
{
defaultUName = GetDefaultUserNameUI();
cred = vlt.Retrieve(resName, defaultUName);
}
}
return cred;
}
In Code Snippet 2, GetCredFromLocker() method is called that retrieves the
PasswordCredential from the PasswordVault. If PasswordCredential is retrieved, then,
object loginCredl is passed to ServerLogin() method which will allow the user to contnue
working. If the loginCredl object is null, then, another method GetLoginCredentialUI()
is called. GetCredFromLocker() method will retrieve the PasswordCredential and return it
into variable called loginCredl.
5.1.2 Managing Web Authentcaton
Windows Store Apps allows Web Authentcaton using Live SDK. To connect the store app over the
V 1.0 Aptech Limited
5
Managing Windows and Web Authentcaton
C
o
n
c
e
p
t
s
Internet or through cloud, the user must download and install the Live SDK from Microsof. Once it is
installed, it can be referred to by the app using the Reference Manager available in the Soluton Explorer.
It can be downloaded from Microsof Web site.
Figure 5.3 shows the Reference Manager-Live Connecton window.
Figure 5.3: Selectng Live SDK Using Reference Manager
As the Live SDK is added, the user can view the reference added to the soluton, as shown in fgure 5.4.
Figure 5.4: Reference is Added to the Soluton
V 1.0 Aptech Limited
5
Managing Windows and Web Authentcaton
C
o
n
c
e
p
t
s
Code Snippet 3 shows how to connect the app over the cloud. Using this code, user can connect to cloud
and retrieve or store the authentcaton informaton in the PasswordVault.
Code Snippet 3:
private async void btnSignin_SessionChanged_2(object sender,
LiveConnectSessionChangedEventArgs e)
{
try
{
LiveAuthClient liveAuthClient; LiveLoginResult liveLoginResult;
liveAuthClient = new LiveAuthClient({Please add your redirect url here});
liveLoginResult = await liveAuthClient.LoginAsync(new string[] { wl.signin,
wl.basic });
if (liveLoginResult.Session != null && liveLoginResult.Status ==
LiveConnectSessionStatus.Connected)
{
LiveConnectClient client = new LiveConnectClient(liveLoginResult.Session);
LiveOperationResult operationResult = await client.GetAsync(me);
dynamic results = operationResult.Result;
lblWelcome.Text = Welcome + results.name;
btnSignin.Content = Sign out;
}
else
{
throw new Exception();
}
}
catch (Exception ex)
{
lblWelcome.Text = ex.Message;
}
}
In Code Snippet 3, a LiveAuthClient, LiveLoginResult, LiveConnectClient,
LiveOperationResult classes are used to retrieve the Live ID. LiveAuthClient is used to check
V 1.0 Aptech Limited
5
Managing Windows and Web Authentcaton
C
o
n
c
e
p
t
s
the user authentcaton. LiveConnectClient is used to establish connecton. LiveLoginResult
and LiveOperationResult are the objects that are used to hold the results.
When the applicaton is executed, it displays the Windows Live screen. The user can login to the applicaton
using Microsof Live account. The applicaton automatcally connects and checks with the Microsof
Live account and authentcates the users. There is no need to keep and store separate database for
the user informaton. Using Microsof Live Accounts, all the applicatons created for Windows can be
authentcated.
5.2 Group Policies
The Group Policy is an essental porton of the operatng system. Group policies are most useful but
complex tools available in any operatng system. These are the rules that can be applied to users having
same profles. Using group policies, user can set the passwords, privileges or user limits. In Windows
8, group policy is available with Windows 8 Pro. In Windows 8.1, Enterprise editon have group policy
opton.
5.2.1 Implementng Password Group Policies
The group policy can limit their password stored in the Windows. To open the Group Policy Editor, the user
has to press the Win + R for the Run command. Type gpedit.msc and click OK as shown in fgure 5.5.
Figure 5.5: Invoking Group Policy Editor through gpedit.msc
V 1.0 Aptech Limited
5
Managing Windows and Web Authentcaton
C
o
n
c
e
p
t
s
When the user clicks OK, the Group Policy Editor window is displayed as shown in fgure 5.6.
Figure 5.6: Group Policy Editor Window
The Group Policy Editor can be used to set policies for various groups. When a new user is created, it is
assigned a group. The rights and privileges of that group are automatcally set to the user added in that
group.
Security Setngs can be used to set the password policy for a group. To do so, navigate to the Security
Setngs to set the password policy as shown in fgure 5.7.
Figure 5.7: Navigatng to Security Setngs
V 1.0 Aptech Limited
5
Managing Windows and Web Authentcaton
C
o
n
c
e
p
t
s
Once the Security Setngs are opened, Password Policy node can be seen. Navigate to Password Policy
and double-click the Enforce password history as shown in fgure 5.8.
Figure 5.8: Navigatng to Password Policy
The user can store the password in the system through the password history. The user can set their own
values to store password as shown in fgure 5.9.
Figure 5.9: Assigning Password History
V 1.0 Aptech Limited
5
Managing Windows and Web Authentcaton
C
o
n
c
e
p
t
s
The user can also lock the system for protectng them from unauthorised access. To set the policy, the
user has to navigate to Account Lockout Policy as shown in fgure 5.10.
Figure 5.10: Account Lockout Threshold
The user can set the number of password atempts that can be made, so that the system will automatcally
lock when it reaches the limit as shown in fgure 5.11.
Figure 5.11: Assigning Invalid Login Atempts
V 1.0 Aptech Limited
5
Managing Windows and Web Authentcaton
C
o
n
c
e
p
t
s
5.2.2 Live Authentcaton
To connect the store app over the Internet or through cloud, the user has to install the Live SDK from
Microsof. Next few sectons will walk you through the steps involved in live authentcaton. In order
to enable Microsof Account Live ID, the user has to set the Packaging informaton of the app from the
Package.appxmanifest fle as shown in fgure 5.12.
Figure 5.12: Setng the Package Informaton
Once the packing informaton is provided, the user can add Live SDK reference installed in the system
through the Reference Manager as shown in fgure 5.13.
Figure 5.13: Adding Reference to Live SDK
From the Windows Extensions, the user has to select Live SDK from the listed libraries in Reference
Manager as shown in fgure 5.13. Figure 5.13 shows how to select the Live SDK from extension library.
V 1.0 Aptech Limited
5
Managing Windows and Web Authentcaton
C
o
n
c
e
p
t
s
Once the library is added, the user can view it in the References folder of the Soluton Explorer as shown
in fgure 5.14. Now, the user can start using the Live SDK for authentcaton purpose. This Live SDK allows
the users to use to use classes required for connectng and accessing Microsof Account Live ID.
Figure 5.14: Reference Added to the Soluton
To connect the cloud service, the user has to write the UI code given in Code Snippet 4. This code
establishes connecton to Microsof Cloud from where the user can get the authentcaton data. Microsof
LiveID automatcally checks for the authentcaton of the users and return the authentcaton status,
which decides whether the user should be allowed to contnue or not?
Code Snippet 4:
<Page x:Class=Liveconnection.MainPage
IsTabStop=false
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
xmlns:local=using:Liveconnection
xmlns:d=http://schemas.microsoft.com/expression/blend/2008
xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006
mc:Ignorable=d
xmlns:live=using:Microsoft.Live.Controls> <Grid
Background={StaticResource ApplicationPageBackgroundThemeBrush}>
<TextBlock x:Name=lblWelcome FontSize=15 FontWeight=Bold>
</TextBlock>
<live:SignInButton x:Name=btnSignin Scopes=wl.signin wl.basic
SessionChanged=btnSignin_SessionChanged_2 />
</Grid>
</Page>
V 1.0 Aptech Limited
5
Managing Windows and Web Authentcaton
C
o
n
c
e
p
t
s
To connect to the cloud service, the user has to write the code given in Code Snippet 5.
Code Snippet 5:
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;
using Microsoft.Live;
using Microsoft.Live.Controls;
namespace Liveconnection
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
}
private async void btnSignin_SessionChanged_2(object sender,
LiveConnectSessionChangedEventArgs e)
V 1.0 Aptech Limited
5
Managing Windows and Web Authentcaton
C
o
n
c
e
p
t
s
{
try
{
LiveAuthClient liveAuthClient; LiveLoginResult liveLoginResult;
liveAuthClient = new LiveAuthClient({Please add your redirect url here});
liveLoginResult = await liveAuthClient.LoginAsync(new string[] { wl.signin,
wl.basic });
if (liveLoginResult.Session != null && liveLoginResult.Status ==
LiveConnectSessionStatus.Connected)
{
LiveConnectClient client = new LiveConnectClient(liveLoginResult.Session);
LiveOperationResult operationResult = await client.GetAsync(me);
dynamic results = operationResult.Result;
lblWelcome.Text = Welcome + results.name;
btnSignin.Content = Sign out;
}
else
throw new Exception();
}
catch (Exception ex)
{
lblWelcome.Text = ex.Message;
}
}
}
}
V 1.0 Aptech Limited
5
Managing Windows and Web Authentcaton
C
o
n
c
e
p
t
s
Once the code is writen, the users have to navigate to Project -> Store -> Associate App with the Store
as shown in fgure 5.15.
Figure 5.15: Select Associate App with the Store
Afer selecton of the menu is done as shown in fgure 5.15, the user has to select the app and click Next
as shown in fgure 5.16.
Figure 5.16: Select an App Name Page
V 1.0 Aptech Limited
5
Managing Windows and Web Authentcaton
C
o
n
c
e
p
t
s
As the app is associated with the app, the user can now execute the code. The output will be displayed as
shown in fgure 5.17. The user has to provide the credentals in order to login over the cloud.
Figure 5.17: Output When Connected over the Cloud
Afer successful login, the user will receive the output as shown in fgure 5.18.
Figure 5.18: Output Afer Successful Login
V 1.0 Aptech Limited
5
Managing Windows and Web Authentcaton
C
o
n
c
e
p
t
s
5.3 Check Your Progress
1. To login, the user has to create a _______________ for the devices.
(A) UniqueID (C) LiveID
(B) Live SDK (D) API
2. A user can authentcate the users through a _______________.
(A) Microsoft account (C) Client account
(B) Service account (D) Google account
3. The app stores the _____________ over the cloud, so that whenever the user is logged in using
the device, it can be authentcated and connected from anywhere.
(A) Secure storage (C) Live connection
(B) Credentials (D) Password
4. _____________ is an essental porton of the operatng system.
(A) CPU (C) Group policy
(B) Microsoft account (D) Authentication
5. To open the Group Policy Editor, the user has to press the Win + R and enter ________.
(A) Gpedit.msc (C) Alt + G
(B) Alt + R (D) Regedit.msc
Edited by Foxit Reader
Copyright(C) by Foxit Software Company,2005-2008
For Evaluation Only.
V 1.0 Aptech Limited
5
Managing Windows and Web Authentcaton
C
o
n
c
e
p
t
s
Summary
In Windows 8.1, users can create their own credentals to login their devices.
Once the setng is saved, it will automatcally be loaded in the device from the cloud whenever
the device is reset or reinstalled.
The beneft of using CredentalLocker for the app is that, it can be used to store the credentals in
a secured area by encryptng it before they are stored.
To connect the store app over the Internet or through cloud, the user must install the Live SDK
from Microsof.
In Windows, Group Policy is available with Windows 8 Pro and Windows 8.1 Enterprise editon.
Securing Windows Store App Data
Session - 6
Welcome to the Session, Securing Windows Store App Data.
This session discusses various ways of securing app data in the Windows
Store.
In this Session, you will learn to:
Explain the process of encryptng and decryptng user informaton
Explain and create an app using the Windows.Security.Cryptography
V 1.0 Aptech Limited
6
Securing Windows Store App Data
C
o
n
c
e
p
t
s
6.1 Security
A Windows Store app needs to store applicaton and user data. Applicaton data is the informaton about
the app that can be created, modifed, or deleted. The data cannot be called without the app, as it
has no logic outside the store app. Modern apps expects to be strong, antcipated, and respectul for
users confdentality. To assist developers, the user has to develop safer apps with secured features. The
security features ofered to the developers by Windows Store are as follows:
y App sandbox - Provides a secure runtme engine that executes the app with a potental
container. This sandbox avoids direct communicatons between Store apps and the system.
The sandbox is a secured environment, which allows your app specifc rights and allows it
execute the code. Here, the atacker cannot take advantages of any security holes in the
security policies of current app.
y App capabilites - All the apps have their own device capabilites, for example, Documents
Library or Webcam.
y Digital signature - All apps are signed. The apps are signed spontaneously through
certfcate that is associated with the developer account, or manually using their own
certfcate.
There are many ways using which security can be applied at diferent levels in the operatng system or
within the Store apps. These ways are explained as follows:
6.1.1 Windows.Security.Cryptography Namespaces
This Windows.Security.Cryptography has a class that is used to encode or decode, hashing
random numbering, byte arrays, and bufer conversion.
Cryptography is used for:
y Authentcaton
y Confdentality
y Data integrity
y Nonrepudiaton
Table 6.1 shows all the classes that can be used to encrypt and decrypt the data. Cryptography namespaces
hold the methods given in table 6.1.
Term Descripton
Encrypton Encrypts the app data
Decrypton Decrypts the app data
Plaintext Data without encrypton (unencrypted data)
Ciphertext Encrypted data with unreadable, text message
Hashing Convertng variable length data into a fxed length
Signature Encrypted hash of digital data
V 1.0 Aptech Limited
6
Securing Windows Store App Data
C
o
n
c
e
p
t
s
Algorithm Procedure for encryptng data
Key A random or pseudorandom
Symmetric Key
Cryptography
Same key is used for encrypton and decrypton
Asymmetric Key
Cryptography
Public key and Private key algorithm, where one key is used for encrypton
and the other key is used for decrypton of data. These keys are
mathematcally related keys
Encoding Encoding digital messages
Algorithm Provider A DLL that implements a cryptographic algorithm
Table 6.1: Methods of Cryptography Namespaces
6.1.2 Encryptng File System (EFS) and BitLocker
Encryptng File System (EFS) is a feature of Windows that can be used to store data on hard disk in an
encrypted format. It is the strongest protecton used to secured data in Windows.
BitLocker Disk Encrypton (BDE) is an encrypton algorithm that was introduced by Microsof with
Windows Vista and Windows 7. It is used to encrypt entre disk drive. It is designed to protect the entre
volume. There are some diferences in BDE and EFS encrypton algorithms.
In order to understand the comparisons between the BitLocker and EFS, it is necessary to understand the
diference between these encrypton algorithms. Table 6.2 provides the diferences between BitLocker
and Encryptng File System.
BitLocker Encryptng File System (EFS)
Encrypts all personal and system
fles
Encrypts personal fles and folders one-by-one
Does not depend on the individual
user accounts
Depends on the user account
BitLocker uses the Trusted Platorm
Module
EFS does not require or use any hardware
Device administrator is required to
turn encrypton on or of the device
Device administrator is not required to turn encrypton on or of
the device
Table 6.2: Diference between EFS and BitLocker
6.1.3 Setng UAC Prompts
User Account Control (UAC) can help users prevent unauthorized changes to the setngs. UAC notfes
the user whenever changes are going to be made. These types of changes can afect the security of the
system. It is recommended to leave UAC enabled so that it keeps the system secured.
User can use the accounts manager to enable or disable User Account Control (UAC). These UAC will
display a confrmaton message whenever an app is called and invoked as shown in fgure 6.1. The UAC
V 1.0 Aptech Limited
6
Securing Windows Store App Data
C
o
n
c
e
p
t
s
shows warnings whenever user is trying to do or perform some operatons that he/she is not authorized
to perform by the system.
Figure 6.1: User Account Control
In order to remove these alerts, the user can change the UAC setngs. To change the UAC setngs, the
user has to open the Control Panel and select User Accounts as shown in fgure 6.2.
Figure 6.2: Control Panel
Afer clicking User Accounts, select Change User Account Control setngs as shown in fgure 6.3. This will
allow the user to make necessary changes in the setngs.
Figure 6.3: Select Change User Account Control Setngs
V 1.0 Aptech Limited
6
Securing Windows Store App Data
C
o
n
c
e
p
t
s
Users can select their desired UAC setngs from Always notfy to Never notfy as shown in fgure 6.4.
Figure 6.4: Notfcaton Type
6.2 Design and Implement Data Caching
When a user develops a new app, it could contain more than one page. These pages can be navigated
by the users. The app has a facility or mechanism to pass a value from one page to another page. During
navigaton within these pages, the user can notce that when pages are navigated in forward as well as
backward directon, the data on those pages is either lost or refreshed. It happens mostly when the user
goes back to previous page. All the felds are reset and they are empty. However, sometmes the user
wants to go back to the previous page with the data retained afer navigatng from another page. In this
case, the user is unable to see the informaton that was in the previous page. To solve this problem, the
user must cache the page contents, so that it will never lose its values during navigaton among pages in
an app.
An app can cache the page data by calling NavigatonCacheMode property of the page, and enable it.
Once the NavigatonCacheMode is enabled, it will automatcally cache the data or informaton of the
page whenever there is navigaton between pages in an App.
The following steps show how to cache data within pages:
y Create a blank new applicaton.
y On Soluton Explorer, navigate to Add New Item BlankPage1.xaml page.
y In the BlankPage1.xaml, write Code Snippet 1 for UI design.
y Create UI as shown in fgure 6.5 by adding Code Snippet 1.
V 1.0 Aptech Limited
6
Securing Windows Store App Data
C
o
n
c
e
p
t
s
Code Snippet 1 shows the code for UI design. This code will generate a screen as shown in fgure 6.5.
Code Snippet 1:
<Page
x:Class=DatacachingDemo.BlankPage1
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
xmlns:local=using:DatacachingDemo
xmlns:d=http://schemas.microsoft.com/expression/blend/2008
xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006
mc:Ignorable=d>
<Grid x:Name=LayoutRoot Background=ForestGreen>
<Grid.RowDefnitions>
<RowDefnition />
</Grid.RowDefnitions>
<Grid.ColumnDefnitions>
<ColumnDefnition />
</Grid.ColumnDefnitions>
<Grid Grid.Column=0 Grid.Row=0 Margin=20,91,0,-71>
<Grid.ColumnDefnitions>
<ColumnDefnition Width=260 />
<ColumnDefnition Width=260 />
</Grid.ColumnDefnitions>
<Grid.RowDefnitions>
<RowDefnition Height=50 />
<RowDefnition Height=50 />
<RowDefnition Height=50 />
<RowDefnition Height=50 />
<RowDefnition Height=100 />
</Grid.RowDefnitions>
<TextBlock Grid.Column=0 Grid.Row=0 Text=Sign Up Form
FontSize=20 FontWeight=Bold Foreground=white Grid.ColumnSpan=2
Margin=53,10,207,40 Grid.RowSpan=2></TextBlock>
V 1.0 Aptech Limited
6
Securing Windows Store App Data
C
o
n
c
e
p
t
s
<TextBlock Text=First Name Margin=10,5,10,5 Grid.Row=1 Grid.
Column=0 FontSize=20 Foreground=White FontWeight=Bold
HorizontalAlignment=Right />
<TextBlock Text=Last Name Margin=10,5,10,5 Grid.Row=2 Grid.
Column=0 FontSize=20 Foreground=White FontWeight=Bold
HorizontalAlignment=Right/>
<TextBlock Text=Email Id Margin=10,5,10,5 Grid.Row=3 Grid.
Column=0 FontSize=20 Foreground=White FontWeight=Bold
HorizontalAlignment=Right/>
<TextBox x:Name=eName Margin=10,5,10,5 Grid.Row=1 Grid.Column=2
FontSize=20 Foreground=Black />
<TextBox x:Name=id Margin=10,5,10,5 Grid.Row=2 Grid.Column=2
FontSize=20 Foreground=Black />
<TextBox x:Name=econt Margin=10,5,10,5 Grid.Row=3 Grid.Column=2
FontSize=20 Foreground=Black />
<HyperlinkButton x:Name=submit Click=click Margin=39,36,0,10
Content=Submit FontSize=20 Background=white Height=54 Width=180
Grid.Column=2 Grid.Row=4 />
</Grid>
</Grid>
</Page>
The output for the UI design code is shown in fgure 6.5.
The UI shown in fgure 6.5 will accept First name, Last name and Email when the user clicks Submit
buton.
Figure 6.5: Output of the App
V 1.0 Aptech Limited
6
Securing Windows Store App Data
C
o
n
c
e
p
t
s
Step 1: Write the code in the backend of the BlankPage1.Xaml.cs page.
Code Snippet 2 shows the code that is to be writen in backend of the BlankPage1.Xaml.cs.
Code Snippet 2:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
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 DatacachingDemo
{
public sealed partial class BlankPage1 : Page
{
public BlankPage1()
{
this.InitializeComponent();
this.NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.
Enabled;
}
private void click(object sender, RoutedEventArgs e)
{
this.Frame.Navigate(typeof(BlankPage2));
}
}
}
V 1.0 Aptech Limited
6
Securing Windows Store App Data
C
o
n
c
e
p
t
s
Step 2: On Soluton Explorer, and Add New Item BlankPage2.xaml page.
Step 3: In the BlankPage2.xaml, write the code given in Code Snippet 3 for UI design.
The UI design code is shown in Code Snippet 3.
Code Snippet 3:
<Page
x:Class=DatacachingDemo.BlankPage2
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
xmlns:local=using:DatacachingDemo
xmlns:d=http://schemas.microsoft.com/expression/blend/2008
xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006
mc:Ignorable=d>
<Grid>
<Button x:Name=bindData Margin=525,351,0,372 Grid.Row=0 Grid.
Column=0 Content=Go Back to Previous Page FontSize=20 Background=black
Click=bindData_Click />
</Grid>
</Page>
The UI design is shown in fgure 6.6.
Figure 6.6: UI Design
Step 4: Write the code in the backend of the BlankPage1.Xaml.cs page.
Step 5: Modify the OnLaunched method in App.Xaml.cs page as shown in Code Snippet 4.
V 1.0 Aptech Limited
6
Securing Windows Store App Data
C
o
n
c
e
p
t
s
Code Snippet 4 shows the code to modify the OnLaunched method in App.Xaml.cs page.
Code Snippet 4:
protected override void OnLaunched(LaunchActivatedEventArgs args)
{
var rootFrame = new Frame();
rootFrame.Navigate(typeof(BlankPage1));
// Place the frame in the current window and ensure that it is active
Window.Current.Content = rootFrame;
Window.Current.Activate();
}
Step 6: Execute the code by pressing F5.
Step 7: Output is executed.
The output of the app is executed which is shown in fgure 6.7.
Figure 6.7: Output of the App
Enter the felds and click Submit buton as shown in fgure 6.8.
Figure 6.8: Fill the Details
V 1.0 Aptech Limited
6
Securing Windows Store App Data
C
o
n
c
e
p
t
s
Step 8: Click Go Back to Previous Page to navigate to frst page.
The second page output is shown in fgure 6.9.
Figure 6.9: Second Page Output
Step 9: Cached data in the previous page remains the same.
The frst page with Data Cached is shown in fgure 6.10.
Figure 6.10: First Page with Data Cached
6.3 Encrypton and Decrypton in Windows Store Apps
Encrypton is a process of convertng the data into Cipher text that will not be able to understand easily
except the app owner. The conversion of Cipher text to plaintext process is called a Decrypton. Encrypton
/Decrypton is the best and oldest way to communicate inside and outside the app. This Cipher text will
have a random alphanumeric character or some special characters that will not be in a readable format.
Encrypton is the process of convertng plain text to byte using Cryptographic Algorithm. To convert an
encrypted plain text, a correct decrypton key is required or else the decrypted data will mismatch and
throws an excepton.
V 1.0 Aptech Limited
6
Securing Windows Store App Data
C
o
n
c
e
p
t
s
6.3.1 Encryptng and Decryptng User Data in Windows Store Apps
In order to encrypt or decrypt the message or text, the user has to write an algorithm to convert the text.
Code Snippet 5 shows the code, which has to be used for encrypton.
Code Snippet 5:
public static byte[] Encrypt(string plainText, string pw, string salt)
{
IBuffer pwBuffer = CryptographicBuffer.ConvertStringToBinary(pw,
BinaryStringEncoding.Utf8);
IBuffer saltBuffer = CryptographicBuffer.ConvertStringToBinary(salt,
BinaryStringEncoding.Utf16LE);
IBuffer plainBuffer = CryptographicBuffer.ConvertStringToBinary(plainText,
BinaryStringEncoding.Utf16LE);
KeyDerivationAlgorithmProvider keyDerivationProvider = Windows.Security.
Cryptography.Core.KeyDerivationAlgorithmProvider.OpenAlgorithm(PBKDF2_
SHA1);
KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.
BuildForPbkdf2(saltBuffer, 1000);
CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(pwBuffer);
IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal,
pbkdf2Parms, 32);
CryptographicKey derivedPwKey = keyDerivationProvider.CreateKey(pwBuffer);
IBuffer saltMaterial = CryptographicEngine.DeriveKeyMaterial(derivedPwKey,
pbkdf2Parms, 16);
string keyMaterialString = CryptographicBuffer.
EncodeToBase64String(keyMaterial);
string saltMaterialString = CryptographicBuffer.
EncodeToBase64String(saltMaterial);
SymmetricKeyAlgorithmProvider symProvider = SymmetricKeyAlgorithmProvider.
OpenAlgorithm(AES_CBC_PKCS7);
CryptographicKey symmKey = symProvider.CreateSymmetricKey(keyMaterial);
IBuffer resultBuffer = CryptographicEngine.Encrypt(symmKey, plainBuffer,
saltMaterial);
byte[] result;
CryptographicBuffer.CopyToByteArray(resultBuffer, out result);
return result;
}
V 1.0 Aptech Limited
6
Securing Windows Store App Data
C
o
n
c
e
p
t
s
Code Snippet 5 will convert the plaintext value to byte array. The encrypton uses PBKDF2_SHA1
encrypton method to encrypt the data.
Code Snippet 6 shows the code, which has to be used for decrypton.
Code Snippet 6:
public static string Decrypt(byte[] encryptedData, string pw, string salt)
{
IBuffer pwBuffer = CryptographicBuffer.ConvertStringToBinary(pw,
BinaryStringEncoding.Utf8);
IBuffer saltBuffer = CryptographicBuffer.ConvertStringToBinary(salt,
BinaryStringEncoding.Utf16LE);
IBuffer cipherBuffer=CryptographicBuffer.CreateFromByteArray(encryptedData);
KeyDerivationAlgorithmProvider keyDerivationProvider = Windows.Security.
Cryptography.Core.KeyDerivationAlgorithmProvider.OpenAlgorithm(PBKDF2_
SHA1);
KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.
BuildForPbkdf2(saltBuffer, 1000);
CryptographicKey keyOriginal=keyDerivationProvider.CreateKey(pwBuffer);
Buffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal,
pbkdf2Parms, 32);
CryptographicKey derivedPwKey=keyDerivationProvider.CreateKey(pwBuffer);
IBuffer saltMaterial=CryptographicEngine.DeriveKeyMaterial(derivedPwKey,
pbkdf2Parms, 16);
string keyMaterialString=CryptographicBuffer.
EncodeToBase64String(keyMaterial);
string saltMaterialString=CryptographicBuffer.
EncodeToBase64String(saltMaterial);
SymmetricKeyAlgorithmProvider symProvider = SymmetricKeyAlgorithmProvider.
OpenAlgorithm(AES_CBC_PKCS7);
CryptographicKey symmKey = symProvider.CreateSymmetricKey(keyMaterial);
IBuffer resultBuffer = CryptographicEngine.Decrypt(symmKey, cipherBuffer,
saltMaterial);
string result=CryptographicBuffer.
ConvertBinaryToString(BinaryStringEncoding.Utf16LE, resultBuffer);
return result;
}
V 1.0 Aptech Limited
6
Securing Windows Store App Data
C
o
n
c
e
p
t
s
Code Snippet 6 will convert the encrypted value to plaintext string. The decrypton uses PBKDF2_SHA1,
the same encrypton method to decrypt the data.
Data Encrypton and Decrypton
Step 1: Create new project from File New Project.
Step 2: Write the code given in Code Snippet 7 to design the page.
Code Snippet 7 shows the code to design the UI page.
Code Snippet 7:
<Page
x:Class=EncryptDecryptDemo.MainPage
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
xmlns:local=using:EncryptDecryptDemo
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}>
<TextBlock HorizontalAlignment=Left TextWrapping=Wrap FontSize=20
Text=Plain Text VerticalAlignment=Top Margin=158,234,0,0/>
<TextBox x:Name=txtText HorizontalAlignment=Left TextWrapping=Wrap
FontSize=20 VerticalAlignment=Top Margin=329,229,0,0 Width=907/>
<TextBlock HorizontalAlignment=Left TextWrapping=Wrap FontSize=20
Text=Encrypted Value VerticalAlignment=Top Margin=158,315,0,0/>
<TextBlock x:Name=txtEncryted HorizontalAlignment=Left
TextWrapping=Wrap FontSize=20 VerticalAlignment=Top
Margin=329,314,0,0 Width=907/>
<TextBlock HorizontalAlignment=Left TextWrapping=Wrap FontSize=20
Text=Decrypted Value VerticalAlignment=Top Margin=158,403,0,0/>
<TextBlock x:Name=txtDecrypted HorizontalAlignment=Left
TextWrapping=Wrap FontSize=20 VerticalAlignment=Top
Margin=329,402,0,0 Width=907/>
<Button Content=Encrypt / Decrypt Value HorizontalAlignment=Left
VerticalAlignment=Top Margin=349,490,0,0 Click=Button_Click/>
<TextBlock HorizontalAlignment=Left TextWrapping=Wrap FontSize=40
Text=Encrypt Decrypt Demo VerticalAlignment=Top Margin=476,118,0,0
Height=63 Width=439/>
</Grid>
</Page>
V 1.0 Aptech Limited
6
Securing Windows Store App Data
C
o
n
c
e
p
t
s
Step 3: The UI design is shown in fgure 6.11.
Figure 6.11: UI Design
Step 4: Write the code given in Code Snippet 8 in the backend.
Code Snippet 8 shows the code, which has to be writen in the backend.
Code Snippet 8:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
using Windows.Storage.Streams;
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;
V 1.0 Aptech Limited
6
Securing Windows Store App Data
C
o
n
c
e
p
t
s
namespace EncryptDecryptDemo
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
//Array of bytes is created
byte[] EncryptedValue;
string encr = ;
//Encrypted value is created by passing password and salt value
EncryptedValue = EncryptionHelper.Encrypt(txtText.Text, pw, salt);
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
encr = encoding.GetString(EncryptedValue, 0, EncryptedValue.Count());
txtEncryted.Text = encr.ToString();
txtDecrypted.Text = EncryptionHelper.Decrypt(EncryptedValue, pw, salt);
}
}
}
public static class EncryptionHelper
{
public static byte[] Encrypt(string plainText, string pw, string salt)
{
//password buffer is created
IBuffer pwBuffer = CryptographicBuffer.ConvertStringToBinary(pw,
BinaryStringEncoding.Utf8);
//salt buffer is created
IBuffer saltBuffer = CryptographicBuffer.ConvertStringToBinary(salt,
BinaryStringEncoding.Utf16LE);
V 1.0 Aptech Limited
6
Securing Windows Store App Data
C
o
n
c
e
p
t
s
IBuffer plainBuffer = CryptographicBuffer.ConvertStringToBinary(plainText,
BinaryStringEncoding.Utf16LE);
KeyDerivationAlgorithmProvider keyDerivationProvider = Windows.Security.
Cryptography.Core.KeyDerivationAlgorithmProvider.OpenAlgorithm(PBKDF2_
SHA1);
//key parameters are passed
KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.
BuildForPbkdf2(saltBuffer, 1000);
//original key is created and stored
CryptographicKey keyOriginal=keyDerivationProvider.CreateKey(pwBuffer);
IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal,
pbkdf2Parms, 32);
CryptographicKey derivedPwKey=keyDerivationProvider.CreateKey(pwBuffer);
IBuffer saltMaterial = CryptographicEngine.DeriveKeyMaterial(derivedPwKey,
pbkdf2Parms, 16);
string keyMaterialString=CryptographicBuffer.
EncodeToBase64String(keyMaterial);
string saltMaterialString =
CryptographicBuffer.EncodeToBase64String(saltMaterial);
//A variable that holds symmetric key provider
SymmetricKeyAlgorithmProvider symProvider = SymmetricKeyAlgorithmProvider.
OpenAlgorithm(AES_CBC_PKCS7);
//Symmetric key is created and stored in symKey
CryptographicKey symmKey = symProvider.CreateSymmetricKey(keyMaterial);
IBuffer resultBuffer = CryptographicEngine.Encrypt(symmKey, plainBuffer,
saltMaterial);
byte[] result;
CryptographicBuffer.CopyToByteArray(resultBuffer, out result);
return result;
}
public static string Decrypt(byte[] encryptedData, string pw, string salt)
{
IBuffer pwBuffer = CryptographicBuffer.ConvertStringToBinary(pw,
BinaryStringEncoding.Utf8);
IBuffer saltBuffer = CryptographicBuffer.ConvertStringToBinary(salt,
BinaryStringEncoding.Utf16LE);
V 1.0 Aptech Limited
6
Securing Windows Store App Data
C
o
n
c
e
p
t
s
IBuffer cipherBuffer = CryptographicBuffer.
CreateFromByteArray(encryptedData);
KeyDerivationAlgorithmProvider keyDerivationProvider = Windows.Security.
Cryptography.Core.KeyDerivationAlgorithmProvider.OpenAlgorithm(PBKDF2_
SHA1);
KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.
BuildForPbkdf2(saltBuffer, 1000);
CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(pwBuffer);
IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal,
pbkdf2Parms, 32);
CryptographicKey derivedPwKey = keyDerivationProvider.CreateKey(pwBuffer);
IBuffer saltMaterial = CryptographicEngine.DeriveKeyMaterial(derivedPwKey,
pbkdf2Parms, 16);
string keyMaterialString = CryptographicBuffer.
EncodeToBase64String(keyMaterial);
string saltMaterialString = CryptographicBuffer.
EncodeToBase64String(saltMaterial);
SymmetricKeyAlgorithmProvider symProvider = SymmetricKeyAlgorithmProvider.
OpenAlgorithm(AES_CBC_PKCS7);
//Symmetric key is created
CryptographicKey symmKey = symProvider.CreateSymmetricKey(keyMaterial);
IBuffer resultBuffer = CryptographicEngine.Decrypt(symmKey, cipherBuffer,
saltMaterial);
//The data is decrypted and stored in result variable
string result = CryptographicBuffer.
ConvertBinaryToString(BinaryStringEncoding.Utf16LE, resultBuffer);
//the result is returned
return result;
}
}
V 1.0 Aptech Limited
6
Securing Windows Store App Data
C
o
n
c
e
p
t
s
Step 5: Execute the app.
Figure 6.12 shows the output of the app with the necessary felds.
Figure 6.12: Output of the App
Step 6: The encrypted and decrypted values are displayed.
Figure 6.13 shows the encrypted and decrypted values. User enters plaintext and clicks Encrypt / Decrypt
Value buton, which executes the code behind and shows both the encrypted as well as the decrypted
values.
Figure 6.13: Encrypted and Decrypted Values
V 1.0 Aptech Limited
6
Securing Windows Store App Data
C
o
n
c
e
p
t
s
6.4 Check Your Progress
1. _______________ provides a secure runtme engine that executes the app with a potental
container.
(A) App sandbox (C) App capabilities
(B) Authentication (D) Digital signature
2. _____________ uses a common key for both encrypton and decrypton.
(A) Asymmetric Key Cryptography (C) Algorithm Provider
(B) Key (D) Symmetric Key Cryptography
3. An app can cache the page data by enabling ___________ property of the page.
(A) Cache mode (C) Blank page
(B) NavigationCacheMode (D) Navigation
4. _____________ does not depend on the individual user accounts.
(A) Encrypted File System (C) BitLocker
(B) Data Integrity (D) Data Folder
5. _________ is a process of convertng the data into Cipher text that will not be able to understand
easily except the app owner.
(A) UI Design (C) Decryption
(B) Encryption (D) Backend
Edited by Foxit Reader
Copyright(C) by Foxit Software Company,2005-2008
For Evaluation Only.
V 1.0 Aptech Limited
6
Securing Windows Store App Data
C
o
n
c
e
p
t
s
Summary
A Windows Store app works with dissimilar data, which works with applicaton and user data.
The Windows.Security.Cryptography has a class, which is used to encode or decode, hashing
random numbering, byte arrays, and bufer conversion.
User can use the accounts manager to enable or disable User Account Control (UAC).
Data can cache the page by calling the NavigatonCacheMode property of the page, and set
NavigatonCacheMode to be Enabled.
Encrypton/Decrypton is the best and oldest way to communicate inside and outside the app.
Diagnosing Problems and
Monitoring Applications
Session - 7
Welcome to the Session, Diagnosing Problems and Monitoring Applicatons.
This session introduces you to the various ways of diagnosing problems faced
during development and testng and teaches how to monitor applicatons in
the Windows Store.
In this Session, you will learn to:
Defne Profling
Create a Performance Report
Explain Diagnostc Tools for Store apps in Visual Studio 2013
V 1.0 Aptech Limited
7
Diagnosing Problems and Monitoring Applicatons
C
o
n
c
e
p
t
s
7.1 Design a Diagnostcs and Monitoring Strategy
Each Store app developed by the user is a client app that performs in a sandboxed and responsive
atmosphere. In some cases, the user can identfy some of the apps that perform slowly. The main reasons
for the app to deliver poor performance are as follows:
An inefectve code that slows down the App
Referring to any third-party libraries
Remote services that takes more tme to load
Writng complex calculatons that takes away too much of CPUs tme and capacity
The best way to solve these problems is to properly diagnose the app during designing, developing,
testng, and deployment phases. If proper diagnosis is done and tmely solutons are implemented, then,
there will be no performance issues when the app is put into the producton mode.
7.1.1 Profling and Collectng Performance Counters
There are two main profling techniques:
Sampling
Instrumentaton
Sampling is the only opton available in Windows Store app, with some limitatons (some sampling
optons, such as setng the sampling event and tming interval, or collectng additonal performance
counter data does not supported for Windows Store apps).
Instrumentaton profler, on the other hand, follows a more invasive approach because it injects specifc
tracing code at the beginning and end of the each functon. This tracing code (also known as tracing
markers or probes) enables the profling tool to record each tme the executon fow enters and exits
an instrumented functon.
Concurrency profling: This profling method collects detailed informaton from the call stack each tme
while the competng threads forced to wait for access to a shared resource (resource contenton). It also
provides useful informaton about how an applicaton interacts with the overall environment, enabling
the user to identfy performance botlenecks, synchronisaton issues, and so on.
.NET memory profling: This profling method collects detailed informaton about memory
allocaton and garbage collecton.
Tier Interacton Profling (TIP):
V 1.0 Aptech Limited
7
Diagnosing Problems and Monitoring Applicatons
C
o
n
c
e
p
t
s
This profling method collects informaton about ADO.NET functon that calls to a SQL Server database.
This profling opton does not exist for Windows Store apps because an app does not have access to the
System.Data.* namespaces and has to rely on remote services (or the local storage) to consume
data.
7.1.2 Tracing and Logging Events
For logging, System.Diagnostics.Tracing namespace delivers types and members, which
allow the user to create strongly typed events. However, Windows Runtme supports only a subset of
the available types. For example, in a Windows Store app, the Windows Runtme does not support the
TraceListener class. This secton shows how to create, trace, and log events that can greatly enhance
the overall quality of the sofware by keeping track of errors and other signifcant events encountered
during the app life cycle.
Each event is marked with an EventAtribute atribute that enables the user to specify additonal event
informaton, which is used by the event listener to flter the event to be traced. The informaton that
specifes for each event is as follows:
EventId - identfer for the event
Keywords - Keywords related to an event
Level - Represents the level of the event
LogAlways - Used by the listener
Critcal - Represents a critcal error
Error - Represents a standard error
Warning - Represents a warning event
Informatonal - Provide additonal informaton on events
Verbose - Adds lengthy events or messages
Message - Message for the event
Opcode - Represents the operaton code for the event
Task - Represents the task for the event
TypeId - Represents unique identfer for this atribute
Version - Represents the version of the event
V 1.0 Aptech Limited
7
Diagnosing Problems and Monitoring Applicatons
C
o
n
c
e
p
t
s
7.2 Monitoring Your Apps
As a developer of Store apps, the user must be aware of the errors and failures such as app hanging,
crashing, service unavailability, and many more conditons. This leads to the app failure and makes the
opponent or competng apps to move ahead in the market. In such a conditon, the developer will have
to sufer a heavy loss for the development of such an app. Therefore, the best way is to develop an app
with minimum errors and bugs, so that fnally the end users do not have to sufer and shif to other
similar competng apps.
Windows Store apps has many ways to monitor such pitalls. These are as follows:
7.2.1 Using Windows Store Reports to Improve the Quality of App
Windows Store provides reportng for the app. Even a perfect app can crash at any tme. Each excepton
is tracked inside the store and they are saved in the app summary as shown in fgure 7.1.
Figure 7.1: App Summary
V 1.0 Aptech Limited
7
Diagnosing Problems and Monitoring Applicatons
C
o
n
c
e
p
t
s
Figure 7.2 shows the Downloaded Exceptons Report.
Figure 7.2: Download Exceptons Expanded View
Each excepton will segregate itself based on the error and stored inside a cab fle. If the user needs to
view the error details, then, the user can download the exceptons in a cab format as shown in fgure 7.2.
To view the error logs, the user has to install WinDbg sofware and using this sofware, the developer
can debug the errors. Once the sofware is installed, open the WinDbg.exe and navigate to File
Open Crash Dump as shown in fgure 7.3.
Figure 7.3: Opening Dump File
V 1.0 Aptech Limited
7
Diagnosing Problems and Monitoring Applicatons
C
o
n
c
e
p
t
s
Now, the user has to select the downloaded cab fle from the app store. Figure 7.4 shows the Open Crash
Dump window.
Figure 7.4: Selectng the Downloaded Cab File
Once the cab fle is loaded, the user has to search c:\symbols and click OK buton as shown in fgure
7.5.
Figure 7.5: Selectng the Cab File
The user can then, view the reason for the error and it can be rectfed or fxed in real tme mode. Such
V 1.0 Aptech Limited
7
Diagnosing Problems and Monitoring Applicatons
C
o
n
c
e
p
t
s
rectfed errors will not refect the next tme the dump fle is opened by using WinDbg.exe.
Figure 7.6 shows the Error descripton as shown by the WinDbg.exe utlity.
Figure 7.6: Error Descripton
7.2.2 Profling Performance
The user can test the app performance at runtme. If the performance of the app is good, then, it is ready
for sale in the market. The customers like only the apps that deliver beter performance and speed.
To test the performance, the user has to navigate to Debug Performance and Diagnosis. Then, the
Performance wizard will open as shown in fgure 7.7. This wizard can be used to check and test the
performance of the currently loaded app. Figure 7.7 shows the CPU Sampling.
V 1.0 Aptech Limited
7
Diagnosing Problems and Monitoring Applicatons
C
o
n
c
e
p
t
s
Figure 7.7: CPU Sampling
Figure 7.8 shows the Sample Profling Report.
Figure 7.8: Sample Profling Report in Graphical Mode
Once the performance test is completed, the detailed report is displayed as shown in fgure 7.8. It also
allows the user to export the reports in various formats, if necessary.
V 1.0 Aptech Limited
7
Diagnosing Problems and Monitoring Applicatons
C
o
n
c
e
p
t
s
7.2.3 Profling Memory Usage
While developing the app, the user can check the memory load. Memory will increase in size whenever
more resource fles are used. Resource includes images, style sheets, scripts, third party DLLs, and many
more. The developer can track the memory usage when the app is running.
Right-click the Taskbar and select Task Manager from the Context Menu as shown in fgure 7.9.
Figure 7.9: Open Task Manager
When the Task Manager is opened, the user can view the memory usage of the app as shown in fgure
7.10. Depending upon the size, the app will be faster and reliable.
Figure 7.10 shows the Task Manager window that shows the details of memory allocated for the app.
V 1.0 Aptech Limited
7
Diagnosing Problems and Monitoring Applicatons
C
o
n
c
e
p
t
s
Figure 7.10: Memory Allocated for the App
7.2.4 Performance and Diagnostics
In order to use the performance and diagnostc tools, perform the following steps:
Step 1: Open the project on which the Performance Test is to be performed. Select Open Project from
the start page. Figure 7.11 shows the Start page to open a New Project.
Figure 7.11: Start Page
V 1.0 Aptech Limited
7
Diagnosing Problems and Monitoring Applicatons
C
o
n
c
e
p
t
s
Step 2: Select the project to check for the performance testng as shown in fgure 7.12.
Figure 7.12: Open Project
Step 3: Navigate to Debug menu and select Performance and Diagnostcs as shown in fgure 7.13.
Figure 7.13: Debug Optons
V 1.0 Aptech Limited
7
Diagnosing Problems and Monitoring Applicatons
C
o
n
c
e
p
t
s
Step 4: The user can view the window as shown in fgure 7.14. The user can select any of the available
tools for testng. Three optons are given by Visual Studio. These are CPU Sampling, Energy Consumpton,
XAML UI Responsiveness, HTML UI Responsiveness, JavaScript Functon Timing, JavaScript Timing, and
Performance.
Figure 7.14: Performance and Diagnostcs
Step 5: This example will show how to process CPU Sampling. To test the CPU sampling, the user has to
select CPU Sampling from the Available Tools as shown in fgure 7.15. Click the Start buton to start the
testng.
Figure 7.15: Test the CPU Sampling
V 1.0 Aptech Limited
7
Diagnosing Problems and Monitoring Applicatons
C
o
n
c
e
p
t
s
Step 6: Once the testng is started, the user can view the progress of the test as shown in fgure 7.16.
Figure 7.16: Progress of the Test
Step 7: As soon as the test is started, the DLLs will be loaded as shown in fgure 7.17.
Figure 7.17: Current View
V 1.0 Aptech Limited
7
Diagnosing Problems and Monitoring Applicatons
C
o
n
c
e
p
t
s
Step 8: Before the completon of the test, the user can view the process as shown in fgure 7.18.
Figure 7.18: Stopping the Diagnostcs Session
Step 9: Afer completon of the selected test, the result or the report is displayed as shown in fgure 7.19.
Figure 7.19: CPU Sampling Profle Report
V 1.0 Aptech Limited
7
Diagnosing Problems and Monitoring Applicatons
C
o
n
c
e
p
t
s
Step 10: To export the report, the user should click the Export Report Data from the Report tab as shown
in fgure 7.20.
Figure 7.20: Exportng a Report
Step 11: While exportng the user can select the details that are to be exported in the report by marking
or checking various optons as shown in fgure 7.21. The optons are Caller, Call Tree, Functons, Header,
and so on.
Figure 7.21: Export Report
V 1.0 Aptech Limited
7
Diagnosing Problems and Monitoring Applicatons
C
o
n
c
e
p
t
s
Step 12: The exported reports in Excel format are saved in the project folder as shown in fgure 7.22.
Figure 7.22: List of Exported Reports in Excel Format
7.3 Diagnostc Tools for Store Apps in Visual Studio 2013
Microsof Visual Studio 2013 had added many diagnostc tools that can be very helpful for the developers
during designing, developing, and testng phase. The new tools are as follows:
CodeLense
Visual Studio Ultmate provides CodeLense that allows the user to view the informaton about code
without leaving the editor. References, unit tests, and other linking informaton can be viewed without
leaving the editor.
Figure 7.23 shows the use of CodeLense.
V 1.0 Aptech Limited
7
Diagnosing Problems and Monitoring Applicatons
C
o
n
c
e
p
t
s
Figure 7.23: CodeLense
Figure 7.23 shows the CodeLense. The popup shows the ready help at the tme of entering the code
or typing the code. References are shown on the top of the methods. As soon as the user clicks the
references on the screen, it shows this CodeLense window that gives more details about the currently
selected method.
Code Maps
Visual Studio Ultmate creates code maps where user can visualize and navigate within the relatonships
in the code. Call stacks also can be viewed while debugging such apps. When the user points on the link
Show on Code Map as shown in fgure 7.23, it shows the Code Map. Figure 2.24 shows the Code Map.
V 1.0 Aptech Limited
7
Diagnosing Problems and Monitoring Applicatons
C
o
n
c
e
p
t
s
Figure 7.24: Code Map
Memory Analysis with Dump Files
Memory issues always arise when the applicaton is put into producton afer the development and
testng phase. Memory analysis tools within Visual Studio 2013 allow the user to check for any memory
leaks, inefcient memory usage, unnecessary allocaton of variables, and so on. This diagnostc tool does
not support Windows Store apps.
IntelliTrace
IntelliTrace allows the user to monitor an app for any exceptons and performance events. Recording
these events in an IntelliTrace log is also possible. Thus, the user can use this log to monitor, diagnose,
and solve these problems during testng and deployment phase.
Unit Tests
Users can now review and run unit tests before the app is actually put in producton mode. This helps in
testng the app by providing certain inputs and checking the given output.
V 1.0 Aptech Limited
7
Diagnosing Problems and Monitoring Applicatons
C
o
n
c
e
p
t
s
Code Analysis
Visual Studio 2013 provides a code analysis window that shows the warnings related to any issues with
the writen code.
Profle Guided Optmizaton
Profle guided optmizaton allow the user to get data from the test runs of .exe and .dll fles. It shows
how the app is likely to perform when deployed in producton mode. These are only available for natve
targets.
V 1.0 Aptech Limited
7
Diagnosing Problems and Monitoring Applicatons
C
o
n
c
e
p
t
s
7.4 Check Your Progress
1. _______________ Profling method collects detailed informaton about memory allocaton and
garbage collecton.
(A) Concurrency (C) TIP
(B) .NET memory (D) None of these
2. _____________ is an atribute used by the listener.
(A) Level (C) Message
(B) Task (D) LogAlways
3. To view the error logs, the user has to install ___________ sofware to debug errors.
(A) WinDbg (C) WinDLL
(B) WinDB (D) WinDg.exe
4. To test the performance, the user has to navigate to _____________.
(A) Debug (C) Debug Export Report Data
(B) Debug CPU Sampling (D) Debug Performance and Diagnosis
5. Depending upon the size, the app will be ________.
(A) Faster (C) Both (A) and (B)
(B) Reliable (D) Unreliable
Edited by Foxit Reader
Copyright(C) by Foxit Software Company,2005-2008
For Evaluation Only.
V 1.0 Aptech Limited
7
Diagnosing Problems and Monitoring Applicatons
C
o
n
c
e
p
t
s
Summary
Sampling is the only opton available in Windows Store app, with some limitatons, such as setng
the sampling event and tming interval, or collectng additonal performance counter data that
does not support Windows Store apps.
An instrumentaton profler follows a more invasive approach because it injects specifc tracing
code at the beginning and end of the each functon.
Each event is marked with an EventAtribute atribute that enables the user to specify additonal
event informaton used by the event listener to flter the event to be traced.
In Windows Store app, each exceptons are tracked inside the store and they are saved in the app
summary.
Memory will increase in size whenever more resource fles are used which includes images, style
sheets, scripts, third party DLLs, and other resources.

Você também pode gostar