Professional Documents
Culture Documents
Development – II
Windows Store Apps Development – II
© 2014 Aptech Limited
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.
APTECH LIMITED
Contact E-mail: ov-support@onlinevarsity.com
Edition 1 - 2014
Dear Learner,
Aptech Ltd. designs its courses using a sound instructional design model – from conceptualization
to execution, incorporating the following key aspects:
Needs assessment is carried out to find the educational and training needs of the learner
Technology trends are regularly scanned and tracked by core teams at Aptech Ltd. TAG*
analyzes these on a monthly basis to understand the emerging technology training needs for
the Industry.
The skill requirements are then mapped with the learner profile (user system) to derive the
Learning objectives for the different roles.
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.
The content outlines are developed by including additional topics that are required for the
completion of the domain and for the logical development of the competencies identified.
Evaluation strategy and scheme is developed for the subject. The topics are arranged/organized
in a meaningful sequence.
The detailed instructional material – Training aids, Learner material, reference material, project
guidelines, etc.- are then developed. Rigorous quality checks are conducted at every stage.
Careful consideration is given for the integral development of abilities like thinking, problem
solving, learning-to-learn etc. by selecting appropriate instructional strategies (training
methodology), instructional activities and instructional materials.
The area of IT is fast changing and nebulous. Hence considerable flexibility is provided in the
instructional process by specially including creative activities with group interaction between the
students and the trainer. The positive aspects of Web based learning –acquiring information,
organizing information and acting on the basis of insufficient information are some of the
aspects, which are incorporated, in the instructional process.
¾¾ Assessment of learning
The learning is assessed through different modes – tests, assignments & projects. The
assessment system is designed to evaluate the level of knowledge & skills as defined by the
learning objectives.
*TAG – Technology & Academics Group comprises of members from Aptech Ltd., professors from
reputed Academic Institutions, Senior Managers from Industry, Technical gurus from Software
Majors & representatives from regulatory organizations/forums.
Technology heads of Aptech Ltd. meet on a monthly basis to share and evaluate the technology
trends. The group interfaces with the representatives of the TAG thrice a year to review and
validate the technology and academic directions and endeavors of Aptech Ltd.
Aptech New Products Design Model
Key Aspects
1
2 Need Analysis 6
and design of Assessment
curriculum of learning
3 Design and 5
Strategies for
development of 4 delivery of
instructional instructions
material
Preface
Windows Store Apps also known as Metro-styled Apps is a mobile app that runs on Smartphones, tablet,
computers, and other mobile devices running Windows 8 or Windows 8.1. Windows Store App is a
new application that runs on Windows 8 devices. Users can create their own apps using programming
language such as C#. Apps have one Window that supports multiple views that interact with each other.
The book, Windows Store Apps Development – II begins with creating a UI with XAML Designer. This
book introduces the working with tiles, data and files. It also allows to connect to networks and Web
services. It also covers the launching, debugging and publishing Windows Store Apps.
This book is the result of a concentrated effort of the Design Team, which is continuously striving to bring
you the best and the latest in Information Technology. The process of design has been a part of the ISO
9001 certification for Aptech-IT Division, Education Support Services. As part of Aptech’s quality drive,
this team does intensive research and curriculum enrichment to keep it in line with industry trends.
Design Team
Table of Contents
Sessions
1. Creating a UI Using XAML Designer
2. Adding Personality to UI
The session will discuss how to work with the XAML designer and use
various options such as elements and resources. The session will also
discuss the binding of data in the designer.
1.1 Introduction
Microsoft Visual Studio 2012 offers the XAML Designer that a user can use to design the Windows Store
Apps. Users will be able to customize User Interfaces (UIs). You could edit the XAML code in the XAML
view to customize or you could drag and drop the required controls from the Toolbox menu and modify
the properties in the Properties window.
A layout is a way of positioning and arranging the various elements of a UI. The user has to keep in mind
to arrange the elements within a layout panel.
A panel is made of StackPanel, Canvas, and a Grid. The user can use these child elements as layout
containers and position and re-arrange the elements. A Grid panel is the default top-level layout container
in a page document. They can add layout panels, other elements, and controls to the top-level page
layout.
The user can access a Visual Studio project and perform one of these steps:
ÎÎ Drag and drop an element from the Toolbox to the Layout window
The user can use the <Button> element to develop a Button control. A <Grid> element is created
when a user develops a new Windows Store App.
ÎÎ Click the property marker, then, click Convert to New Resource in the Properties window. A
dialog box to create a resource is displayed.
Figure 1.3 shows the Create Brush Resource dialog box.
Concepts
ÎÎ Click OK.
To apply resource to a property or element,
yy Select the element to apply the resource.
yy To map a resource and a property, click the property marker for the property value, in the
Properties window. Click Locate Resource and then, select Available Resources.
Right-click a control and point to Edit Template. Then, select Apply Resource to apply a style or control
template resource to a control.
{
get { return “Software Developer”; }
set { value = “Software Developer”; }
}
public string Pay
{
get { return “$6000”; }
set { value = “$6000”; }
}
public string CityName
{
get { return “Texas”; }
set { value = “Texas”; }
}
}
3. From the MainPage.xaml page, click Grid. Point to the Properties window as shown in figure 1.4.
Concepts
4. In the Properties window, click Common, and then, click New as shown in figure 1.5.
6. Add a TextBlock control from the artboard by double-clicking it from the Toolbox.
7. Select a TextBlock control, and go to its Properties window. In Properties window select Text
Binding under Common option and click Create Data Binding as shown in figure 1.7.
display with this control, for example, here it is the Name field. Then, click OK.
ÎÎ Access keys
The users can use these keys to access a menu command or any area within a dialog box. These
keys are identified by underscores.
For example, in XAML Designer, if you press Alt, an underline will appear under F in the File menu
so that you can recognize it as access key. If you press and hold Alt and then, press F, the File menu
is shown expanded. Then, press O and later, P key. A project dialog box with a list of projects is
opened.
ÎÎ Shortcut keys
Shortcut keys will speed up the users task rate. These keys reduce the time taken to do an action.
They can use these keys to perform repetitive actions such as modify a tool’s behavior, by pressing
a combination of keys.
For example, the Cut command on the Edit menu displays Ctrl+X which is the keyboard shortcut.
Concepts
ÎÎ Modifier Keys
You cannot discover certain shortcut keys that are not in the menu item.
ÎÎ Project Keys
The following are the project based shortcut keys in XAML Designer.
Table 1.2 lists the project shortcut keys.
Items Description
Items Lists all the items in the collection.
Remove item Removes the items that are selected.
Up arrow Moves the selected item up, to the top of the list, in the collection.
Down arrow The selected item are moved down to the bottom of the list in the
collection.
itemType Allows to choose the type of item that can be added to the
collection.
Add Enables to add a new item to the collection. The new item is given
a default name and added to the bottom of the list. You can edit
name and similar properties in the Properties pane.
Properties Displays the properties that you can update for the item that is
selected.
Table 1.6: Controls
The Select Object dialog box is used in the designer when they need to select a Common Language
Concepts
Runtime (CLR) type. The Select Object dialog box appears in many contexts. For example, they can use
it in the Collection Editor when they want to choose an item type.
Figure 1.9 shows the Select Object dialog box for a row definition opened in the Collection Editor.
Items Description
Search box Here you can search for a CLR type by name.
Select Type list This is a tree view with which you can choose the CLR
type to match with the current property or element.
Show all assemblies All framework assemblies in the Visual Studio project
are shown with the option to include or exclude them.
Table 1.7: Items
A value converter helps the user modify data. They can create value converters using the
IValueConverter interface. When the users perform data binding, they can select a converter from
the Converter drop-down list. They can also select <Add value converter> to create a new one.
Concepts
Concepts
3. The user can use grouping to create a ______________ and place related elements in it.
5. The users can use ______________ keys to access a menu command or any area within a dialog
box.
1.7.1 Answers
1. A
2. A
3. A
4. A
5. D
Concepts
Summary
ÎÎ The user can use the XAML designer to add elements.
ÎÎ The user can also modify the margin and the way the elements are layered or aligned.
ÎÎ The styles and properties set for a particular element are stored in a reusable entity called
resources.
ÎÎ To create a custom element layer order, drag and drop elements in the Document Outline
window.
ÎÎ The users can use the Reset Layout command to revert the element to its default layout
properties values.
ÎÎ A panel is made of StackPanel, Canvas, and a Grid. The user can use these child elements as layout
containers and position and re-arrange the elements.
ÎÎ When a user adds an element to existing layout container, the element will get placed in the front
of other elements.
Concepts
2.1 Animations
List animation is used to show the inserting or deleting an item in a collection of identical items and
named for their simplest use. Animations are used in collections of other forms such as group of photos
in a grid.
ÎÎ Fade in
ÎÎ Fade out
Concepts
ÎÎ Crossfade
Using FadeInThemeAnimation and FadeOutThemeAnimation methods, the XAML animation library
implements these animations.
ÎÎ Fade in
Fade in animation is used to place an item into place. Fade in animation can be viewed in the app
bar, where new controls can appear as the result of user interaction. While transiting from an
appeared item to the real item, fade in animation also can be used. Here, content dynamically
loads or shows a custom tooltip or dialog control.
ÎÎ Fade out
To delete an item, the fade out animation can be used. For example, in transient controls such as
scroll bar or panning indicator, which are faded out after some time is lost and no input has been
identified.
ÎÎ Cross fade
Fade in and fade out animations can be simultaneously used to carry out a substitution of an existing
item with an entering item. While animating the existing items fades away as the replacement
items fades into the same space.
ÎÎ PopInThemeAnimation
ÎÎ PopOutThemeAnimation
ÎÎ PopupThemeTransition
ÎÎ
Concepts
enterPage
ÎÎ exitPage
Following are the points which help you to know about animations:
ÎÎ Outgoing objects
ÎÎ Incoming objects
ÎÎ How far and from which angle the incoming content is entering
ÎÎ enterContent
ÎÎ exitContent
It is not mandatory that original content and the replacement content need not have the same layout or
size.
Following are the points which help to know about animations:
ÎÎ Outgoing objects
ÎÎ Incoming objects
ÎÎ How far and from which angle the incoming content is entering
ÎÎ pointerUp
ÎÎ pointerDown
Note - When the user is moving the object, use the drag and drop animations otherwise use the
reposition animations.
Following APIs are consisted by the set of animations:
ÎÎ DragItemThemeAnimation
ÎÎ DropTargetItemThemeAnimation
ÎÎ DragOverThemeAnimation
ÎÎ Drag Start
With a drag start (DragItemThemeAnimation), every drag and drop animation sequence begins.
This animation customizes the look of the Drag Source and affected objects.
Figure 2.1 shows the drag object and its next objects before the user drag the object.
Concepts
When the object is selected and it is dragged, the affected objects become smaller and the dragged
object becomes larger as shown in figure 2.2.
ÎÎ Drag End
With the drag end animation (DropTargetItemThemeAnimation), drag and drop animation
sequence ends. Once the Drag Start animation is used, the Drag End animation is used to end it.
The same affected object is used to call DragItemThemeAnimation. Figure 2.4 shows the effect
of the drag source to its changed item in the end of drag animation.
Concepts
In the first image, it is shown that before a user drops an object in a set of changed item. The drag
object becomes larger than its normal size, and aligned down from the list. The affected objects
become smaller than their original size.
Figure 2.5 shows the Drag Source is larger and aligned down from the affected objects, and these
are in their original size.
ÎÎ Drag Between
When it is required by the user to drag an item in the two other objects, then the Drag Between
animation (DragOverThemeAnimation) is used. In this animation, when the user drops the Drag
Source in required position, the affected objects will move aside to make space for the Drag Source.
Concepts
In the following images, the movement of the affected objects with respect to the drag source is
shown.
Figure 2.7 shows that before a user triggers Drag Source into a set of affected objects, enter
animation is used.
The drag and drop animations in behavior of Windows Runtime control consist of ListViewItem
and GridViewItem templates which define visual states for drag and multidrag.
ÎÎ Swipe Hint
The swipe hint animation (SwipeHintThemeAnimation) supports the user. When the items is
pressed and hold by a user, which supports the swipe interaction, the animation presses the object
down and brings it back up, conveying that the item supports the swipe interaction.
ÎÎ Swipe Select
The XAML will not have a swipe select animation, since selection is performed by different models.
This each has its self visual simile that will not involve animation.
ÎÎ Swipe Deselect
When the user drags a present selected object and wants to deselect it or release the item, then
the swipe deselect animation is used. This swipe deselect animation deletes the chosen identifier
from the object and moves the object to its rest position.
The swipe gesture animations in behavior of Windows Runtime control consist of ListViewItem and
GridViewItem which defines visual states for selection hinting.
a storyboarded animation.
Linear, and Discrete variation of its KeyFrame class. For example, key frames to declare an
animation that targets a Double and uses key frames such as DiscreteDoubleKeyFrame,
LinearDoubleKeyFrame, SplineDoubleKeyFrame, and EasingDoubleKeyFrame. Any one
or all of these types can be used within a single KeyFrames collection.
The Timeline based properties can be set on a key-frame animation.
<StackPanel1>
<StackPanel1.Resources>
<myStoryboard x:Name=”mynewStoryboard”>
<DoubleAnimationUsingKeyFrames
Storyboard.TargetName=”mynewRectangle”
Storyboard.TargetProperty=”(UIElement.RenderTransform).
(ScaleTransform.ScaleY)”>
<LinearDoubleKeyFrame Value=”1” KeyTime=”0:0:0” />
<LinearDoubleKeyFrame Value=”1.2” KeyTime=”0:0:4” />
<LinearDoubleKeyFrame Value=”2” KeyTime=”0:0:5” />
</DoubleAnimationUsingKeyFrames>
</myStoryboard>
</StackPanel1.Resources>
</StackPanel1>
Concepts
In this example, for the first four seconds, linearly operates an animation in which the height of the
rectangle gets increased slightly. For the last second, scales rapidly till the rectangle is two times
the starting height.
2.4.1 Prerequisites
Using Visual Studio 2012 quickstart can be done.
5. Set the background color displayed with the splash screen image in the Background Color field of
the Splash Screen section. Either the color name or ‘#’ and the hex value of a color can be entered
in this field.
ÎÎ 620 x 300 pixel image size should be used by the enlarged splash screen page.
ÎÎ The enlarged splash screen should use a background color which is specified for the splash screen
in the app manifest.
ÎÎ To position the apps splash screen image, the code should use the SplashScreen class. This
should happen at that screen coordinates in which Windows positions the image while displaying
the splash screen.
ÎÎ Using the SplashScreen class to reposition items on the enlarged splash screen, the code should
respond to window resize events.
Following are the steps to create an enlarged splash screen:
Step 1: Adding a Blank Page item to your existing app
yy In Visual Studio 2012, open your app.
yy In the menu bar, press or open Project and click Add New Item. Now, an Add New Item
dialog box will appear.
yy From this Add New Item dialog box, add a new Blank Page to your app. Two files are
generated by adding a Blank Page item and they are as follows:
1. For markup (ExtendedSplash.xaml)
2. For code (ExtendedSplash.xaml.cs).
Step 2: Essential XAML for an extended splash screen
Following are the steps to add an image and progress controls to the extended splash screen:
yy By default, the splash screen color is a light gray. Change the default Grid element of
Background property to match the background color for the apps splash screen in the app
manifest.
yy To the Grid element, add a Canvas element. To position your enlarged splash screen
image, the Canvas will be used.
Concepts
yy To the Canvas, add an Image element. For the enlarged splash screen, use the 600 x 320
pixel image which you select for the splash screen displayed by Windows.
{
bool loadStatestatus = (args.PreviousExecutionState ==
ApplicationExecutionState.Terminated);
ExtendedSplash = new ExtendedSplash(args.SplashScreen, loadStatestatus);
Window.Current.Content = extendedSplash;
}
Window.Current.Activate();
}
ÎÎ To clearly identify it, label the entry point in the Settings pane as, ‘Help’.
1. Guidelines for Help Settings
yy Help page should be short and simple to refer.
yy If Help content will not be suitable on a single page or if it is required to include dynamic
content, then connect to a support Website or add an online page in the Help flyout.
While creating Help content, following are some things to prevent:
ÎÎ From the Help entry points, don’t directly link to a Website. In place of this, link to online content
in the connected Help flyout.
ÎÎ Help should be provided for quick, basic reference not for every feature in the app.
ÎÎ Help should not be used to notify availability of newer version of the app.
2. Guidelines for App Settings
Concepts
For every Windows Store App, Windows provides a Settings pane by default. Each entry point
displays the Settings options themselves and it opens a Settings flyout. In this section, you will learn
the good practices to create and display app settings.
ÎÎ In the Settings pane, create entry points for all the app settings.
ÎÎ Number of settings should be kept minimum, simple, and define smart defaults.
ÎÎ As soon as the user changes a setting, immediately the change should be reflected by the app.
ÎÎ Ellipse
By specifying a Width, Height, and a Brush for the Fill, a basic Ellipse can be created.
The following example creates an Ellipse whose Width is of 200 and a Height is of 200, and
Fills with SolidColorBrush as colored using SteelBlue.
Example: XAML
ÎÎ Rectangle
A Rectangle has a four sides’ shape whose opposite sides are equal. By specifying a Width, a
Height, and a Fill, a basic Rectangle can be created. A Rectangle corners can be rounded. By
specifying a value for the RadiusX and RadiusY properties, a round cornered rectangle can be
created.
The following example creates a Rectangle whose Width is of 210 and Height is of 110. For
its Fill it uses a Blue value of SolidColorBrush and for its Stroke it uses a Black value of
SolidColorBrush. StrokeThickness is set to 4. The RadiusX property is set to 60 and the
RadiusY property is set to 20, to get Rectangle rounded corners.
Example: XAML
<Rectangle Fill=”SteelBlue”
Width=”210”
Height=”110”
Stroke=”Green”
StrokeThickness=”4”
RadiusX=”60”
RadiusY=”12” />
ÎÎ Line
A Line is simply a line which connects two points. For a Line, values for the Stroke and
StrokeThickness properties should be mentioned. Instead of using a Point values to specify a
Line shape, you use discrete Double values for X1, Y1, X2, and Y2.
ÎÎ Stretching an Image
By default, the Width or Height of the image is displays specified by the Source. Using the
Stretch property, image is filled by the containing area. Following are the Stretch properties
which accept the values, as shown in table 2.2.
ÎÎ Cropping an Image
Clip property is used to trim off an area from the output by setting the Clip property to Geometry.
The following example shows how to use a RectangleGeometry as the clip region for an image.
Here, it is defined an Image object with a Height of 200.
XAML
ÎÎ Prerequisites
yy Microsoft Visual Studio 2012
yy Windows 8
Example:
XAML
ÎÎ MediaElement Basics
By creating a MediaElement object in XAML, add media to your app. Then, set the Source to a
Uniform Resource Identifier (URI) which points to an audio or video file.
Concepts
Property Description
AutoPlay It indicates whether the MediaElement initiate playing
automatically. By default, it displays true.
IsMuted It indicates whether the volume is muted. By default, it
displays false.
IsFullWindow Present in Windows 8.1.
IsFullWindow property should be used to enable
and disable full window rendering.
AreTransportControlsEnabled Present in Windows 8.1. It allows or blocks the built in
transport controls.
Volume It indicates the audio volume. The range varies from 0
to 1.
Balance It indicates the ratio of stereo speaker’s volume. The
range varies from -1 to 1.
Stretch Present in Windows 8.1.
How the MediaElement fills the space of the container
is defined by the MediaElement.Stretch property.
The Stretch states are similar to settings pictures on
many TV sets. You can allow the user to choose their
own setting.
Table 2.3: MediaElement Properties
You will learn to transcode a video file to MP4 format. It explains how to open a video file from the system
to use the FileOpenPicker class, and then, transcode the MediaTranscoder class to video file to the
MP4 format.
1. Create new project
Create a blank Windows Store App using C# by initiating.
2. Selecting a source file and creating a destination file
To select a source file, use the FileOpenPicker and to create the destination file, use the
FileSavePicker class. Then, set the SuggestedStartLocation and FileTypeFilter
properties on the FileOpenPicker. On the FileSavePicker object, set the
SuggestedStartLocation, DefaultFileExtension, SuggestedFileName, and
FileTypeChoices properties as shown in the example.
Example:
C#
MediaEncodingProfile encodeprofile =
MediaEncodingProfile.CreateMp4(VideoEncodingQuality.HD720p);
MediaTranscoder medtranscoder = new MediaTranscoder();
The static CreateMp4 method creates an MP4 encoding profile whose parameter gives the target
resolution for the video. In the example, 1280 x 720 pixels is the VideoEncodingQuality.hd720p
at 30 frames per second.
By using the Windows.Media.MediaProperties.MediaEncodingProfile.
CreateFromFileAsync method, a profile can be created which matches an existing media file.
4. Transcode the file
To create a new MediaTranscoder object, transcode the file, then call the MediaTranscoder.
PrepareFileTranscodeAsync method. Now, pass in the encoding profile, the destination file,
and the source file. Then, call the TranscodeAsync function on the PrepareTranscodeResult
object.
Concepts
3. _____________________ can be used to transit between pages within an app or to display the
first page of a newly launched app.
5. ___________________ are required to place users objects when they move it with their fingers,
or with an input device
Concepts
2.9.1 Answers
1. C
2. D
3. D
4. A
5. A
Concepts
Summary
ÎÎ List animation is used to show the inserting or deleting an item in a collection of identical items
and named for their simplest use.
ÎÎ Fade animations can be used to view an item or take items out of a view.
ÎÎ The popup animations can be used to show and hide popup UI.
ÎÎ To provide visual feedback of pressing an object, the pointer animations are used.
ÎÎ Animating repositions in default Windows Runtime control behavior are progress bar which uses
RepositionThemeAnimation in a VisualTransition to its ‘Determinate’ state.
ÎÎ With the drag end animation (DropTargetItemThemeAnimation), for drag and drop animation
sequence ends.
ÎÎ When the user drags a present chosen object and wants to deselect it or release the item then,
the swipe deselect animation is used.
ÎÎ The static CreateMp4 method creates an MP4 encoding profile whose parameter gives the target
resolution for the video.
Concepts
The session will discuss how to work with the Tiles and Badges in addition
to creating and delivering notifications. The session will also discuss about
adding a search to an App.
XmlDocument myTileXml =
TileUpdateManager.GetTemplateContent(TileTemplateType.
TileWide310x150
ImageAndText01);
This code retrieves the XML content using the GetTemplateContent method. Code Snippet
1 is the retrieved XML code.
Code Snippet 1:
<tile>
<visual version=”2”>
<binding template=”TileWide310x150ImageAndText01”
fallback=”TileWideImageAndText01”>
<image id=”1” src=””/>
<text id=”1”></text>
</binding>
</visual>
</tile>
3. Code Snippet 2 retrieves all the elements in the XML template with the tag name ‘text’.
Code Snippet 2:
5. It is always best practice to use both square and wide version of tile notification as the user
may resize the tile at any time. Code Snippet 4 uses both versions of tile notification.
Code Snippet 4:
Then, to the wide tile’s payload, add the medium tile. The user then, retrieves the binding
element, which defines the medium tile in the newSquareTileXml payload. This binding
element is then, appended as a sibling of the wide tile. Code Snippet 5 displays the binding
element.
Code Snippet 5:
Code Snippet 6 shows result in two binding elements for a single visual element in the XML
payload.
Code Snippet 6:
Concepts
<tile>
<visual version=”2”>
<binding template=”TileWide310x150ImageAndText01”
fallback=”TileWideImageandText01”>
<image id=”1” src=”ms-appx:///images/blueWide.png”/>
6. Code Snippet 7 creates the XML content for the XML code, the user has specified.
Code Snippet 7:
7. The user then, sends the notification to the app tile as shown in Code Snippet 8.
Code Snippet 8:
TileUpdateManager.CreateTileUpdaterForApplication().
Update(myTileNotification);
Figure 3.3 shows the output image of square and wide tile notification.
2. A batch can display numbers 0-99 or system-defined status glyphs. A glyph is nothing but a
graphical form that provides appearance or form for a character.
For example, an e-mail program may display a number of unread mails or a new message
glyph to indicate new messages is there in the inbox.
Numbers and glyphs in badges are updated through different XML and hence, you need to
retrieve the appropriate XML. Following example retrieves a template for the numeric badge:
Example:
3. Assigning value to the batch is to be done separately for numeric and glyph values. Following
example retrieves a batch template and assigns it a numeric value:
Example:
<Page
x:Class=”tiles.MainPage”
IsTabStop=”false”
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
xmlns:local=”using:tiles”
xmlns:d=”http://schemas.microsoft.com/expression/blend/2008”
xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006”
mc:Ignorable=”d”>
<StackPanel>
<Button x:Name=”PinTileButton” Content=”Pin a Secondary Tile “
Margin=”100,50” Click=”PinTileButton_Click”/>
<TextBlock x:Name=”Status” FontSize=”40” Foreground=”red”></TextBlock>
</StackPanel>
</Grid>
</Page>
1. You set some properties to create a Secondary tile and then, you define the SecondaryTile class with
its constructor as shown in Code Snippet 10.
Code Snippet 10:
2. Now, you create an object of the SecondaryTile Class and call its constructor as shown in Code
Snippet 11.
Code Snippet 11:
3. You call a method of the SecondaryTile class that pins the tile to the start screen after user confirmation
and returns a status as a boolean value as shown in Code Snippet 12.
Code Snippet 12:
Windows.UI.Popups.Placement.Below);
4. You check the boolean result returned by the RequestCreateForSelectionAsync method and show a
status message to the user as shown in Code Snippet 13.
Code Snippet 13:
if (isPinned)
{
Status.Text = “Secondary tile successfully pinned.”;
}
else
{
Status.Text = “Secondary tile is not pinned.”;
}
Now, you can run the application to see an output as shown in figure 3.5.
Type the name of the secondary tile and click Start button to see the secondary tile added to the Start
screen as shown in figure 3.7.
<toast>
<visual>
<binding template=”ToastImageAndText01”>
<image id=”1” src=””/>
<text id=”1”></text>
</binding>
</visual>
</toast>
3. Add the message you want to notify to the user through toast notification as shown in Code Snippet
15.
Code Snippet 15:
4. Next, the user needs to add an image to the toast notification by retrieving the image tag and
assigning the required image to it as shown in Code Snippet 16.
Code Snippet 16:
5. When a user clicks the notification, the application is launched. You use the launch attribute of the
toast notification. The attribute value is app-defined string as shown in Code Snippet 17.
Code Snippet 17:
Concepts
((XmlElement)toastNode).SetAttribute(“launch”,
“{\”type\”:\”toast\”,\”param1\”:\”12345\”,\”param2\”:\”67890\”}”);
6. Finally, you create and send the toast notification as shown in Code Snippet 18.
Code Snippet 18:
ÎÎ Delivering Notifications:
This topic discusses about delivery mechanism of Scheduled, Periodic, and Push notifications.
ÎÎ Scheduled Notification:
The user can schedule notification so that it can appear at a specific time. They are going to schedule
the toast notification created in the earlier section.
Code Snippet 19 sets the DateTime object so that the toast notification appears in three hours.
Code Snippet 19:
Int16 dueTimeInHours = 3;
DateTime dueTime = DateTime.Now.AddHours(dueTimeInHours);
You then, create the scheduled toast notification object with the notification content and time
scheduled as shown in Code Snippet 20.
Code Snippet 20:
You can then, create an ID for the scheduled notification. This ID can be used to cancel the
notification later and it can be 16 characters long as shown in Code Snippet 21.
Code Snippet 21:
scheduledToast.Id = “Future_Toast”;
You can then, add the toast notification to the schedule as shown in Code Snippet 22.
Code Snippet 22:
ToastNotificationManager.CreateToastNotifier().
AddToSchedule(myScheduledToast);
Concepts
ÎÎ Periodic Notifications:
Periodic notifications also known as ‘polled notifications’ used to update live tiles and badges at a
specified interval.
To use periodic notification, the client code should have the following two elements:
1. The Uniform Resource Identifier (URI) of the Web location, the app polls for the badge or live tile
update
2. The time interval with which the given URI needs to be polled
The app should host a cloud service to use periodic notification. Cloud services provide easy,
scalable access to resources, applications and services, and a cloud services provider manages
them. The users of the app will poll this cloud service periodically. At each polling period, for
example, an hour, Windows will send an HTTP GET request to the specified URI, download the
requested badge or tile content (as XML) which is the response to the request, and displays the
downloaded content on the tile.
Following are the steps involved in creating a periodic notification:
1. Identify a Web service to host the live content
At specific intervals, Windows polls the Web service for updated content of App’s tile.
Only the Web services that support HTTP must be choose. During testing, the user can use
Microsoft Internet Information Services (IIS) on the user’s local machine to test the XML.
2. Tile’s XML file needs to be placed in a Web-accessible location
The user needs to place the XML content in a file named Tile.xml and place it in a Web-
accessible location in server (for example, http://www.fabrikam.com/tile.xml). UTF-8
encoding must be used in the XML document and follow the tile schema. Code Snippet 23
shows the XML code.
Code Snippet 23:
<tile>
<visual version=”2”>
<binding template=”TileWide310x150Text03”
fallback=”TileWideText03”>
<text id=”1”>This is periodic notification</text>
</binding>
</visual>
</tile>
hour.
Code Snippet 24:
using Windows.UI.Notifications;
PeriodicUpdateRecurrence newRecurrence = PeriodicUpdateRecurrence.
Hour;
This code uses already defined variable namely polledUrl, which is a string that contains
the URL to be polled.
4. Start the periodic updates with multiple URLs
The user can also allow up to five different URLs to be polled by Windows and supply a set
of content that are displayed one after another in the tile’s notification queue.
Following example polls content once an hour.
Example:
using Windows.UI.Notifications;
TileUpdateManager.CreateTileUpdaterForApplication().
EnableNotificationQueue(true);
PeriodicUpdateRecurrence newPeriodicRecurrence =
PeriodicUpdateRecurrence.Hour;
TileUpdateManager.CreateTileUpdaterForApplication().
StartPeriodicUpdateBatch(urisToPoll, newPeriodicRecurrence);
In this code, the notification queue must be enabled if was not enabled previously. i.e. the
call to EnableNotificationQueue is made only once after the user creates a secondary
tile or installs the App. A previously defined variable named urisToPoll, an array of URL
objects, each representing a different URL is used to get polled content.
ÎÎ Push Notifications:
Push notification enables third-party developers to send tile, badge, toast, and raw updates from
their own cloud service.
Following are the steps involved in sending a push notification:
1. Following are the namespace declarations:
using System.Net;
using System.IO;
using System.Runtime.Serialization;
Concepts
using System.Runtime.Serialization.Json;
using System.Web;
using System.Text;
request.Headers.Add(“X-WNS-Type”, newNotificationType);
request.ContentType = newContentType;
request.Headers.Add(“Authorization”, String.Format(“Bearer {0}”,
accessToken.AccessToken));
Concepts
The user adds a SearchBox Control using the MainPage.xaml file in XAML editor. The search control is
named searchBoxNewSearchBox.
Now, the XAML code will be as shown in Code Snippet 29.
Code Snippet 29:
The QuerySubmitted event handler must store the user’s search term. The user adds a TextBox and
TextBlock control for this and the equivalent XAML code as shown in Code Snippet 30.
Code Snippet 30:
Add the following code by double-clicking the QuerySubmitted event handler as shown in Code Snippet
31.
Code Snippet 31:
The user then, adds a list of bike names for suggestion as shown in Code Snippet 32.
Code Snippet 32:
“Vespa”,”Suzuki”,”Honda”
}
Now, run the application and give it any bike name like ’Honda’ to test it out.
Figure 3.9 displays the output showing SearchBox control.
Concepts
<SearchBox x:Name=”mySearchBox”
FocusOnKeyboardInput=”True”
QuerySubmitted=”SearchBoxEventsQuerySubmitted”
Height=”35”/>
ÎÎ The user may define them. For example, the user can create a list of bike manufacturers.
ÎÎ The user can fetch them from Windows, if the search is based on local files.
3. When the user enters a query in the SearchBox, it fires the event ______________.
QuerySubmitted (C) SearchSubmitted
(A)
(B) SearchActivated (D) QueryProcessed
5. The ________________ method is called by the system when the user searches the App that is
not in the running state.
Concepts
3.5.1 Answers
1. B
2. C
3. A
4. D
5. C
Concepts
Summary
ÎÎ Tiles are icons representing applications on Windows 8 Start screen.
ÎÎ Badges are displayed on tiles representing App’s state or status.
ÎÎ Notifications are of three type such as Scheduled, Periodic, and Push notifications.
ÎÎ Scheduled notifications appear at a specified time.
ÎÎ Periodic notifications used to update status at specified interval of time.
ÎÎ Push notifications allow tile, badge, and toast updates to be send from a cloud service.
ÎÎ Troubleshooting steps and processes involved in delivering notifications were discussed.
ÎÎ Search contract is used to create a search pane with SearchBox control with search suggestions
and displaying results.
Concepts
The session will discuss how to work with Data and Files. Methods involved
in sharing and protecting data will discuss.
ÎÎ Key/value pairs: In programming languages, this is recognized as object, record, hash table,
struct, or associative array.
ÎÎ Ordered list: In programming languages, this is recognized as array, list, sequence, or vector.
Code Snippet 1 is a sample JSON data representing a person object.
Code Snippet 1:
{
“firstName”: “John”,
“lastName”: “Adams”,
“isAlive”: true,
“height_cm”: 167.64,
“age”: 45,
“address”: {
“streetAddress”: “32 6th Street”,
“city”: “Texas”,
“state”: “TX”,
“postalCode”: “10031-4100”
},
Concepts
“phoneNumbers”: [
{ “type”: “home”, “number”: “312 555-3234” },
{ “type”: “fax”, “number”: “645 545-4568” }
]
}
The entire data is enclosed within an object named person within braces {}. Data in this object is called
member and each member may contain a pair, array, or another object. In the example, sample shown in
each entity separated by comma are members. The pair contains data in the format key:value. Here,
key must be a string value and distinct from other keys in the object. Keys are separated by a colon from its
corresponding value. “firstName”: “John” is an example of the key:value pair. Array contains values or
otherwise known as elements enclosed within square brackets [] separated by comma. Elements, in turn,
may contain values or other elements. The values for phoneNumbers are enclosed within an array. The value
may be any value with data type such as string, number, object, array, true, false, or null.
In Windows 8 Store Applications, the user needs to use the HttpClient class to retrieve the response
from the Web server. The GetAsync method will return an HttpResponseMessage that contains the
response headers, status code, and content. Code Snippet 2 demonstrates the process of retrieving the
JSON response from the Web server.
Code Snippet 2:
Code Snippet 4 creates a new JsonObject and populates it with new name/JsonValue pairs
using the JsonObject::Insert method. Then, the user calls JsonObject::Stringify to
serialize the JsonObject as JSON text.
Code Snippet 4:
Code Snippet 6 creates a new JsonArray object and populates it with JsonValue objects using
the JsonArray::Append method. The user then, calls the JsonArray::Stringify to serialize
the json array as JSON text.
Code Snippet 6:
jsonArray.Add(JsonValue.CreateNumberValue(2.14149));
jsonArray.Add(JsonValue.CreateBooleanValue(true));
jsonArray.Add(JsonValue.CreateStringValue(“sample”));
string jsonArrayString = newJsonArray.Stringify();
Code Snippet 8 serializes a number value as JSON text and creates a new Json value and assign
preferred value with JsonValue::CreateNumberValue.
Code Snippet 8:
Code Snippet 10 allows the user to serialize a string value as JSON text and create a new Json value.
Then, the user can assign preferred value with JsonValue::CreateStringValue.
Code Snippet 10:
used in Apps that support sharing. Users of an App can launch Share Charm through touch gesture or
programmatically.
Figure 4.1 displays the Share charm.
users whose App has the right hardware, and only shows in the Devices charm, when there is something
to share in the App. Usually, the user starts the Devices charm and chooses Tap and Send by a touch
gesture or click of mouse.
using Windows.Security.Cryptography;
Concepts
using Windows.Storage.Streams;
namespace Random
{
sealed partial class GenerateRandomDataCrypt : Application
{
public GenerateRandomDataCrypt()
{
// Initialize the app.
this.InitializeComponent();
// Creates a buffer with random data.
String strRandomHex = this.GenerateRandomData();
// Create a random integer.
UInt32 unsignedIntRandom = this.GenerateRandomNumber();
}
public String GenerateRandomData ()
{
// Defines the length of the buffer in bytes
UInt32 newLength = 32;
// Generate random number and copy to buffer.
IBuffer newBuffer = CryptographicBuffer.GenerateRandom(newLength);
// Encode buffer to hexadecimal string to display
String hexRandom = CryptographicBuffer.EncodeToHexString(newBuffer);
return hexRandom;
}
public UInt32 GenerateRandomNumber()
{
// Generates new random number.
UInt32 Random = CryptographicBuffer.GenerateRandomNumber();
return Random;
}
}
Concepts
ÎÎ Comparing Buffers
Code Snippet 13 shows how to compare buffer for equality.
Code Snippet 13:
The two buffers are equal when each code point matches the corresponding code point in another buffer.
Concepts
{
// Creates string to convert.
String strInput = “Input String”;
// Convert the string to UTF16BE binary data.
IBuffer bufferUTF16BE = CryptographicBuffer.
ConvertStringToBinary(strInput, BinaryStringEncoding.Utf16BE);
// Convert the string to UTF16LE binary data.
IBuffer bufferUTF16LE = CryptographicBuffer.
ConvertStringToBinary(strIn, BinaryStringEncoding.Utf16LE);
// Convert the string to UTF8 binary data.
IBuffer bufferUTF8 = CryptographicBuffer.
ConvertStringToBinary(strInput, BinaryStringEncoding.Utf8);
}
ÎÎ Hashing Objects
The CryptographicHash object is used to hash different data repeatedly without having to
create the object again for each use. The Append method adds new data to a buffer that needs is
to be hashed. The GetValueAndReset method hashes the data and resets the object as shown
in Code Snippet 15.
Code Snippet 15:
objHash.Append(buffMsgOne);
IBuffer buffHashOne = objHash.GetValueAndReset();
// second Hash message
String strMsgTwo = “This is message Two.”;
IBuffer buffMsgTwo = CryptographicBuffer.
ConvertStringToBinary(strMsgTwo, BinaryStringEncoding.Utf16BE);
objHash.Append(buffMsgTwo);
IBuffer buffHashTwo = objHash.GetValueAndReset();
// Hash message three
String strMsgThree = “This is message three”;
IBuffer buffMsgThree = CryptographicBuffer.
ConvertStringToBinary(strMsgThree, BinaryStringEncoding.Utf16BE);
objHash.Append(buffMsgThree);
IBuffer buffHashThree = objHash.GetValueAndReset();
// Convert the hashes to string values (for display);
String strHashOne = CryptographicBuffer.
EncodeToBase64String(buffHashOne);
String strHashTwo = CryptographicBuffer.
EncodeToBase64String(buffHashTwo);
String strHashThree= CryptographicBuffer.
EncodeToBase64String(buffHashThree);
}
ÎÎ The user can use a SID to make the data safe on an Active Directory (AD). Any member belonging
to the group can decrypt data.
Concepts
ÎÎ The user can protect data to the credentials used during sign-in to a Website.
When the user creates a DataProtectionProvider object, they must specify a protection descriptor
to protect data before calling ProtectAsync or ProtectStreamAsync.
<Capabilities>
<Capability Name=”sharedUserCertificates” />
</Capabilities>
Concepts
<Extensions>
<!--Certificates Extension-->
<Extension Category=”windows.Certificates”>
<Certificates>
<Certificate StoreName=”Root” Content=”Certificates\Root\myrootone.
cer”/>
<Certificate StoreName=”Root” Content=”myroottwo.cer”/>
<Certificate StoreName=”TrustedPeople” Content=”mypeerone.sst”/>
<Certificate StoreName=”Issuer” Content=”myissuer.cer”/>
<TrustFlags ExclusiveTrust=”true”/>
<SelectionCriteria HardwareOnly=”true” AutoSelect=”true”/>
</Certificates>
</Extension>
</Extensions>
KeyProtectionLevel KeyProtectionLevel.NoConsent
KeyStorageProviderName KeystorageProviderNames.SoftwareKeyStorageProvider
<Extensions>
<!--Certificates Extension-->
<Extension Category=”windows.certificates”>
<Certificates>
<Certificate StoreName=”Root” Content=”myroot.cer” />
<Certificate StoreName=”CA” Content=”mystandca.cer”/>
<TrustFlags ExclusiveTrust=”true” />
</Certificates>
</Extension>
</Extensions>
Concepts
4. In public key cryptography, ___________________ are used to bind a public key to computer.
5. ________________ is used to protect e-mails, credit card information, and corporate data.
Concepts
4.4.1 Answers
1. D
2. A
3. C
4. A
5. A
Concepts
Summary
ÎÎ JSON data format is a lightweight and language independent data exchange format used on the
Web.
ÎÎ JSON data is based on two data structures namely Key/Value pairs and Ordered list.
ÎÎ Data sharing formats discussed include Share Charm, Tap and Send, and Copy and Paste.
ÎÎ Manipulating cryptographic data and hashing data were discussed.
ÎÎ Methods involved in creating certificate files were discussed.
ÎÎ Process involved in data protection were discussed.
Concepts
The session will discuss how to connect to networks and Web services, how
to authenticate resources, concepts of data caching, and how to connect
to sockets and Web sockets.
5.1 Introduction
This session will teach the users how to create connected apps. The user can use a connected app, also
called a network-aware app, that will help them to use a network for multiple purposes such as playing
games, getting feeds, games, and interacting with other devices close by.
ÎÎ Windows.Web.AtomPub: Helps a user access any Web resources by using the protocol called
AtomPub.
ÎÎ Windows.Web.Http: Provides a user with an API based on a HTTP client to connect to Web
services.
ÎÎ System.Net.Http: Enables a user to connect to Web services by using a Web client with only
C#/VB languages.
ÎÎ Prerequisites
The apps written in JavaScript will be affected apart from those written in languages such as C#,
VB.NET, and C++ based on .NET Framework 4.5.
yy Find out the direction of the network access that is required by the app. These requests
could be inbound unsolicited, outbound client-initiated, or it could be a combination.
yy Identify the network resources that will communicate with the app. The resources could be
trusted resources available on the Home/Office network, or on the Internet.
yy The user must also configure the minimum applicable networking isolation capabilities.
yy They should configure and test the app by using the network isolation tools.
Items Description
Home\Work Network This is the local home or office network. Internet proxies are not
included. Within a domain, the boundary includes subnets and
Active Directory sites ranges.
Internet This does not include either the Office or Home network. This
comprises proxy servers that give access to the Internet. A
network that is not part of Home\Work Network is considered as
the Internet.
Table 5.1: Network Boundaries
The app should have some capabilities related to networking for the app to get access to the network.
The capabilities are called Security Identifiers (SIDs). These are enabled by the OS to implement the
boundaries.
Table 5.2 lists the security identifiers.
yy Internet gateways
Interprocess communication (between two apps) cannot use network communications using an IP
loopback address as it is restricted due to the concept of network isolation.
Network communication that happens in any app inside a communication process is allowed using
IP loopback address.
ÎÎ Windows.Networking.Sockets
ÎÎ Windows.Networking.BackgroundTransfer
ÎÎ Windows.Web.Syndication
ÎÎ Windows.Web.AtomPub
value for completing the initial handshake, which is like an initial sign.
API Mapping
Concepts
WebSockets MessageWebSocketControl.ServerCredential
MessageWebSocketControl.ProxyCredential
StreamWebSocketControl.ServerCredential
StreamWebSocketControl.ProxyCredential
API Mapping
Background BackgroundDownloader.ServerCredential
Transfer BackgroundDownloader.ProxyCredential
BackgroundUploader.ServerCredential
BackgroundUploader.ProxyCredential
Syndication SyndicationClient(PasswordCredential)
SyndicationClient.ServerCredential
SyndicationClient.ProxyCredential
AtomPub AtomPubClient(PasswordCredential)
AtomPubClient.ServerCredential
AtomPubClient.ProxyCredential
Folder Descriptions
Local Files get saved on the local machine. The files are not
Concepts
Folder Descriptions
Roaming Such files get synchronized with all the devices that they sign
is with connected accounts. Roaming is not instantaneous.
They should be sure to keep the usage lower than the quota
as defined by the property RoamingStorageQuota. If not,
the roaming of data can get suspended. If an app is writing to
a file, such files cannot be roamed. They should close the file
objects when they are not required.
Table 5.6: Folder Details
Initially, they define a reference to the Roaming folder. Then, the cacheResponse file helps to
create a new file in the Roaming folder. It shows that an existing file with a same name, as the
previous one must be overwritten. After a file is created, the new serverResponse.txt file is
created based on the file originally returned from the response of the server.
Code Snippet 1 shows the caching of the response from a server.
Code Snippet 1:
return Windows.Storage.FileIO.readTextAsync(file);
}).done(function (response) {
print(response);
}, function () {
// getFileAsync or readTextAsync failed.
// No cached response
});
}
The code shows the caching of the response from a server as a .txt file from a network operation.
The code also shows the retrieval of cached data by using the relevant file name.
If the app terminates or is relaunched, caching content, or the app data, that is available in the
server response will allow quicker access and display.
Item Description
IXMLHTTPRequest2 This allows access to the Web resources that use an
extension to the XMLHttpRequest object.
System.Net.Http This enables connections made to Web services by using
a modern Web client.
Table 5.7: Technologies
ÎÎ Prerequisites
They will apply the information given here to a connected resource or to an app. The connection
depends solely on the network connections.
yy Background tasks
yy System trigger for SessionConnected
yy Time triggers
yy Windows Notification Services (WNS)
yy Raw push notifications
The features support continuous connectivity for apps that must receive raw push notifications
when an app is suspended. Such apps are also always available. Many other tasks that run in the
background features may also be used by the app. Other triggers that can be used by the app are
as follows:
yy Triggers for Maintenance (These are periodic time events to signal maintenance activity)
yy Triggers from a system for users and sessions (online ID change, user session is connected or
disconnected, and user is present or away)
yy System triggers for the network status (change in network state, Internet available or
unavailable)
yy System triggers for locking the screen (app add or delete)
They can use a time trigger if the app must run for a short time at an interval. They can use a system
trigger when an app must keep tabs on events.
They can combine multiple triggers in an app to enable different scenarios. Many apps do not use
raw push notifications. Apps may give an impression that they are always running in the background
through a live tile. Their app need not be a lock screen app or even run in the background.
WNS is hosted by Windows 8 and can help them to update a live tile, run a code, and send
notifications. To use the WNS service, their local machine should be connected to the Internet.
Only then, the WNS service will be able to communicate.
An app that is running in the foreground can use the WNS service to send notifications, update live
tiles, or even update the badges. Apps need not be on the lock screen to be able to use the WNS
service.
They should use WNS if they must run a code to respond to a push notification. For the apps which
need not be available on the lock screen, WNS provides an update on the live tile.
The use of the WNS service can help improve the power efficiency rather than using the available
network triggers in the apps that are written in C++/XAML and the apps that use the .NET Framework
4.5. These apps are written in C#, VB.NET languages. These could be managed using languages such
as C++ on Windows 8 and Windows Server 2012.
They get the following benefits by using the WNS service:
yy It offers a very powerful solution to deliver notifications for lock screen apps.
yy It makes the developer model for the app simpler.
yy They need not maintain a persistent socket connection between a client app and a remote
server. Windows OS maintains the connection to the WNS service.
yy It can support most apps available on the local machine.
yy It reduces the server side operational cost as there is no necessity to maintain the TCP
socket connections between a client and a remote server.
yy Their app need not be available in the computer’s memory all the time. The app can be
stopped and the WNS can still update the tile and do other things.
It is recommended that developers of apps for Instant Messengers, VoIP services, and e-mail
messages should use the WNS notifications for lock screen apps.
ÎÎ Add XAML UI
The user first defines the app layout in XAML. They specify the size and the position of each object.
They complete the app’s UI and add controls and content.
The sample here uses the following simple XAML UI elements:
yy A horizontal StackPanel containing a TextBlock for a Label, a TextBox for the input URI
address, and a Button used to start the asynchronous request.
yy A horizontal StackPanel containing a TextBlock for a Label and a TextBox for the current
status. This is where status and error messages will be displayed.
yy A StackPanel containing a TextBox where the output received from the Web service is
displayed. In this sample, the result of the HTTP GET operation is displayed as plain text
containing HTML markup. You can change the output display from plain text to a WebView
by using a WebView instead of a TextBox.
Concepts
The user must open the cs or the cpp folder. Then, they must open an existing BlankPage.xaml
file and rename the file as, MainPage.xaml.
<Page
x:Class=”HttpClientGet.MainPage”
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
xmlns:local=”using:HttpClientGet”
xmlns:d=”http://schemas.microsoft.com/expression/blend/2008”
xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006”
mc:Ignorable=”d”>
<Grid Background=”{ThemeResource ApplicationPageBackgroundThemeBrush}”>
<StackPanel Orientation=”Vertical”>
<StackPanel Orientation=”Horizontal”>
<TextBlock Text=”URI Address:” FontSize=”24” Height=”28”
Margin=”30,30,0,0” />
<TextBox x:Name=”inputAddress” Text=”http://www.contoso.com”
FontSize=”13”
Height=”41” Width =” 471” Margin=”31,31,0,0” />
<Button Content=”Start” Click=”Start_Click” Margin=”51,21,0,0”
FontSize=”25” Height=”81” Width=”121” />
</StackPanel>
<StackPanel Orientation=”Horizontal”>
<TextBlock Text=”Status:” FontSize=”23” Height=”29” Margin=”30,20,0,0” />
<TextBox x:Name=”statusText” Text=”Idle” FontSize=”17” Height=”Auto”
Width=”700”
TextWrapping=”Wrap” Margin=”31,31,0,0” />
</StackPanel>
Concepts
<StackPanel Orientation=”Horizontal”>
<TextBox x:Name=”outputView” FontSize=”17” Margin=”30,30,0,0”
TextWrapping=”Wrap”
Height=”401” Width=”801” ScrollViewer.
VerticalScrollBarVisibility=”Visible”/>
</StackPanel>
</StackPanel>
</Grid>
</Page>
using System;
using Windows.Web.Http;
using Windows.Web.Http.Headers;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Navigation;
namespace HttpClientGet
{
public sealed partial class MainPage : Page
{
private HttpClient httpClient;
private HttpResponseMessage resp;
public MainPage()
{
this.InitializeComponent();
httpClient = new HttpClient();
Concepts
// The safe way to check a header value from the user is the TryParseAdd method
// Since you know this header is okay, you use ParseAdd with will throw an
exception
// with a bad value
headers.UserAgent.ParseAdd(“ie”);
headers.UserAgent.ParseAdd(“Mozilla/5.0 (compatible; MSIE 10.0; Windows NT
6.2; WOW64; Trident/6.0)”);
}
}
}
outputView.Text = responseBodyAsText;
}
}
The class Windows.Web.Http.HttpClient will use WinInet to send HTTP and Web service
requests and to get responses. For an HTTP connect operation, the default timeout value is only
60 seconds.
HRESULT hr = S_OK;
DWORD dwStatus = 0;
BOOL fAbort = TRUE;
ComPtr<IXMLHTTPRequest2> spXHR;
ComPtr<CXMLHttpRequest2Callback> spXhrCallback;
The user will create and then, initialize the instances of the objects, IXMLHTTPRequest2 and
IXMLHTTPRequest2Callback as shown in Code Snippet 6.
Code Snippet 6:
//
// Create and initialize an IXMLHTTPRequest2 object
//
Concepts
hr = CoCreateInstance(CLSID_FreeThreadedXMLHTTP60,
NULL,
CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&spXHR));
//
//Create and initialize an IXMLHTTPRequest2Callback object
//
hr = MakeAndInitialize<CXMLHttpRequest2Callback>(&spXhrCallback);
//The developer will first configure a GET request and then, send the request to a
server.
C++
hr = spXHR->Open(L”GET”, // Method.
pcwszUrl, // Url.
spXhrCallback.Get(), // Callback.
NULL, // Username.
NULL, // Password.
NULL, // Proxy username.
NULL); // Proxy password.
//
//Send the GET request
//
hr = spXHR->Send(NULL, 0);
Wait for the completion of the request.
C++
hr = spXhrCallback->WaitForComplete(&dwStatus);
HRESULT hr = S_OK;
Concepts
DWORD dwStatus = 0;
ULONGLONG ullFileSize = 0;
BOOL fAbort = TRUE;
ComPtr<IXMLHTTPRequest2> spXHR;
ComPtr<CXMLHttpRequest2Callback> spXhrCallback;
ComPtr<CXMLHttpRequestPostStream> spXhrPostStream;
//Initialize IXMLHTTPRequest2Callback
hr = MakeAndInitialize<CXMLHttpRequest2Callback>(&spXhrCallback);
if (FAILED(hr))
{
goto Exit;
}
// Create an object of the CXMLHttpRequestPostStream class
spXhrPostStream = Make<CXMLHttpRequestPostStream>();
if (spXhrPostStream == NULL)
{
hr = E_OUTOFMEMORY;
goto Exit;
}
The user will attempt to open a file to understand its size as shown in Code Snippet 9.
Code Snippet 9:
//
//Open the file
//
hr = spXhrPostStream->Open(pcwszFileName);
//
//Get file size
//
Concepts
hr = spXhrPostStream->GetSize(&ullFileSize);
The developer must send a POST request to a server as shown in Code Snippet 10.
Code Snippet 10:
//
//Configure the POST request
//
hr = spXHR->Open(L”POST”, // Method.
pcwszUrl, // Url.
spXhrCallback.Get(), // Callback.
NULL, // Username.
NULL, // Password.
NULL, // Proxy username.
NULL); // Proxy password.
if (FAILED(hr))
{
goto Exit;
}
//
//Send the POST request
//
hr = spXHR->Send(spXhrPostStream.Get(), ullFileSize);
if (FAILED(hr))
{
goto Exit;
}
Wait till the request is completed as shown in Code Snippet 11.
Code Snippet 11:
hr = spXhrCallback->WaitForComplete(&dwStatus);
Concepts
if (FAILED(hr))
{
goto Exit;
}
fAbort = FALSE;
ÎÎ Add XAML UI
The user will learn about layout of an app in XAML to understand the size and the position of each
object within an app. The given sample includes XAML UI elements:
yy The horizontal StackPanel has a TextBlock as a label, the input URI address is a TextBox,
and a Button used helps start an asynchronous request.
yy The horizontal StackPanel contains a TextBlock for a label. It also contains a TextBox for
its current status. The status and the error messages are displayed.
Concepts
The output from the Web service displays in the Grid. The user should open the folder called cs.
Then, they must open the blankPage.html file.
<Page
x:Class=”HttpClientBasic.BlankPage”
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
xmlns:local=”using:HttpClientBasic”
xmlns:d=”http://schemas.microsoft.com/expression/blend/2008”
xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006”
mc:Ignorable=”d”>
<Grid Background=”{StaticResource ApplicationPageBackgroundBrush}”>
<StackPanel Orientation=”Vertical”>
<StackPanel Orientation=”Horizontal”>
<TextBlock Text=”URI Address:” FontSize=”16” Height=”20” Margin=”15,0,0,0”
/>
<TextBox x:Name=”InputAddress” Text=”http://www.contoso.com”
FontSize=”16” Height=”20” Margin=”15,0,0,0” />
<Button Content=”Start” Click=”Start_Click” Margin=”280,0,0,0” />
</StackPanel>
<StackPanel Orientation=”Horizontal”>
<TextBlock Text=”Status:” FontSize=”16” Height=”20” Margin=”15,0,0,0” />
<TextBox x:Name=”StatusText” Text=”Idle” FontSize=”16” Height=”Auto”
TextWrapping=”Wrap” Margin=”15,0,0,0” />
</StackPanel>
<Grid
Grid.Column=”1” Margin=”15,0,0,0”>
<Grid.RowDefinitions>
<RowDefinition Height=”Auto” />
Concepts
</Grid>
</StackPanel>
</Grid>
</Page>
<StackPanel>
<TextBlock x:Name=”TitleText” HorizontalAlignment=”Left”
Margin=”10,10,0,0”
TextWrapping=”Wrap” Text=”Connect to Bing Maps Web Service using the C++ REST
SDK”
VerticalAlignment=”Top” Height=”52” Width=”1356” FontSize=”36”/>
<StackPanel HorizontalAlignment=”Left” Height=”204” Margin=”20,25,0,0”
VerticalAlignment=”Top” Width=”922”>
<StackPanel Orientation=”Horizontal”>
<TextBlock Padding=”0,0,10,0” FontSize=”14” Text=”Enter a valid latitude:”
Concepts
Width=”152”></TextBlock>
<TextBox x:Name=”Latitude” TextWrapping=”Wrap” Text=”47.640194”
Height=”28” Width=”149”/>
</StackPanel>
<StackPanel Orientation=”Horizontal”>
<TextBlock Padding=”0,0,10,0” FontSize=”14” Text=”Enter a valid
longitude:”></TextBlock>
<TextBox x:Name=”Longitude” TextWrapping=”Wrap” Text=”-122.129865”
Height=”28.519”
UseLayoutRounding=”False” Width=”149.021” d:LayoutRounding=”Auto”/>
</StackPanel>
<Button x:Name=”LocationButton” Content=”Get Location” Height=”50”
Width=”304” Click=”Button_Click”/>
<StackPanel Orientation=”Horizontal” Margin=”0,20,20,20”>
<TextBlock Padding=”0,0,10,10” FontSize=”14” Text=”Bing Maps Response:”></
TextBlock>
<TextBlock x:Name=”BingMapsResponse” FontSize=”14”
HorizontalAlignment=”Left” TextWrapping=”Wrap”
VerticalAlignment=”Top” Width=”744”/>
</StackPanel>
</StackPanel>
</StackPanel>
The user must add a button handler for the class LocationButton.
The user will learn to manage exceptions while they use networking APIs in apps that are written in
languages such as VB.NET, C#, or C++.
ÎÎ Windows.Web.Http: It provides a modern client API for apps based on HTTP and REST.
ÎÎ Exceptions in Windows.Networking.Sockets
The constructor used with the class HostName that is useful for sockets can give an error if the string
is not valid. If their app has an input from any user for the class HostName, then, the constructor
also should be part of a try/catch block. If there is an exception, the app will tell the user and ask
for a new host name.
Concepts
ÎÎ Exception in Windows.Networking.BackgroundTransfer
There will be a failure when any invalid string for a URI is sent to a constructor for the object called
as, Windows.Foundation.Uri.
ÎÎ Define WebSockets
WebSocket is a two-way communication method, which is very fast and happens over the Internet
between a server and a client machine.
Data transfer is almost immediate and happens over a full-duplex single socket connection. The
messages can be sent/received from both the endpoints. A WebSocket is perfect for an apps that
includes real-time games, social networking, and so on.
For getting a connection, the client and server exchange an HTTP handshake. If the handshake is
successful, the protocol in the application-layer changes to WebSockets.
They must remember that a client cannot transfer data to a server unless the server uses WebSockets.
If there is a mismatch, they should use some other method.
The Windows.Networking.Sockets namespace supports these two types of WebSockets,
MessageWebSocket and StreamWebSocket.
Table 5.9 lists the two types of WebSockets.
MessageWebSocket StreamWebSocket
It can be used very large It can be used to transfer large files such as media
messages. files.
It enables a notification that says It permits few sections of any message to be read in
that the complete WebSocket is each read operation.
received.
It supports binary and UTF-8 It supports only binary type of messages.
messages.
It is similar to a DatagramSocket This is similar to a StreamSocket or TCP socket.
or a UDP socket.
Concepts
<Page
x:Class=”StreamSocketBasic.BlankPage”
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
xmlns:local=”using:StreamSocketBasic”
xmlns:d=”http://schemas.microsoft.com/expression/blend/2008”
xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006”
mc:Ignorable=”d”>
<Grid Background=”{StaticResource ApplicationPageBackgroundBrush}”>
<StackPanel Orientation=”Vertical”>
<StackPanel Orientation=”Horizontal”>
<TextBlock Text=”Hostname:” FontSize=”16” Height=”20” Margin=”15,0,0,0” />
<TextBox x:Name=”ServerHostname” Text=”www.contoso.com” FontSize=”16”
Height=”20” Margin=”15,0,0,0” />
<TextBlock Text=”Port:” FontSize=”16” Height=”20” Margin=”15,0,0,0” />
<TextBox x:Name=”ServerPort” Text=”http” FontSize=”16” Height=”20”
Margin=”15,0,0,0” />
<Button Content=”Connect” Click=”Connect_Click” Margin=”220,0,0,0” />
</StackPanel>
<StackPanel Orientation=”Horizontal”>
Concepts
</StackPanel>
<StackPanel Orientation=”Horizontal”>
<TextBlock Text=”Status:” FontSize=”16” Height=”20” Margin=”15,0,0,0” />
<TextBox x:Name=”StatusText” Text=”Idle” FontSize=”16” Height=”Auto”
TextWrapping=”Wrap” Margin=”15,0,0,0” />
</StackPanel>
<Grid
Grid.Column=”1” Margin=”15,0,0,0”>
<Grid.RowDefinitions>
<RowDefinition Height=”Auto” />
</Grid.RowDefinitions>
<TextBlock x:Name=”OutputView” FontSize=”16” Height=”Auto”
Margin=”15,0,0,0” TextWrapping=”Wrap” />
</Grid>
</StackPanel>
</Grid>
</Page>
The variables help track if a client socket is connected or closed. It will also define the hostname
apart from defining the service name. The values for the hostname and service name are default
values.
yy Create a StreamSocket.
yy Use the StreamSocket.Control property to get the StreamSocketControl instance
associated with a StreamSocket object.
yy Get or set a property on the StreamSocketControl to set an advanced socket option.
ÎÎ DatagramSocket Controls
A DatagramSocket helps communication over a network by using the UDP DatagramSocket. Many
advanced options that are available on a DatagramSocket.
DatagramSocketControl.QualityOfService – This defines the Quality of Service (QoS) for
a DatagramSocket.
The QOS will affect the thread priority for receiving packets on an object. The QOS can be configured
to any value for SocketQualityOfService. By default, normal setting is used to create the
object. The code sample given here helps them develop a DatagramSocket. It also sets the
DatagramSocketControl.QualityOfService to LowLatency.
ÎÎ StreamSocket Controls
The StreamSocket supports communication over a network by using the TCP StreamSocket.
Following are the advanced options:
yy StreamSocketControl.KeepAlive – It shows when the keep-alive packets get sent to
any destination that is remote.
yy StreamSocketControl.NoDelay – This shows whether Nagle’s algorithm is used or not.
yy StreamSocketControl.OutboundBufferSizeInBytes – This helps control the size of
the sent buffer.
yy StreamSocketControl.QualityOfService – This denotes the QOS of the object.
ÎÎ StreamSocketListener Controls
This will support them to listen for any incoming network connection by using the TCP StreamSocket.
The StreamSocketListener.QualityOfService is the QOS that must be configured on the
object while receiving a connection from the StreamSocketListener object.
Windows Runtime supports Syndication APIs. They can use these APIs to enable their app in retrieving/
creating latest and popular content for the Web. They can use RSS feeds that are generated as per the
RSS and Atom standards.
ÎÎ Web Feed
It is a document containing many entries of text, hyperlinks, and/or images. Any updates that are
made to a Web feed will be in the form of new entries. These entries will promote the current
content across the Internet.
Consumers use an app that reads feeds to collect and view content from many individual authors.
They get access to latest content almost immediately.
yy Supported Feed Format Standards
Windows Runtime supports these feed retrieval standards:
RSS standards: 0.91 to 2.0
Atom standards: 0.3 to 1.0
The classes called Windows.Web.Syndication help define these feeds. The feed items can
represent both elements to both Atom and RSS standards.
Moreover, feeds from Atom 1.0 and RSS 2.0 formats include elements not defined in official
specifications. Such customized elements and attributes help define any domain-specific
information.
Concepts
3. _________________ helps a user listen for any incoming network connection by using the TCP
StreamSocket.
(A)
Windows.Networking. (C) StreamSocketListener
Sockets
StreamSocketListener (D) listenSocket.Control.
(B) QualityOfService
Socket Controls
5.9.1 Answers
1. A
2. A
3. B
4. A
5. A
Concepts
Summary
ÎÎ The user can use a connected app, also called a network-aware app.
ÎÎ The network-aware app will help the user to use a network for multiple purposes such as playing
games, getting feeds, games, and interacting with other devices close by.
ÎÎ A user can isloate a network and map network capabilities.
ÎÎ The apps written in JavaScript will be affected apart from those written in languages such as C#,
VB.NET, and C++ based on .NET Framework 4.5.
ÎÎ The user must also configure the minimum applicable networking isolation capabilities.
ÎÎ They can use the checklist to determine if the network isolation is available for their app.
ÎÎ The user can include a network endpoint as a part of the Home\Work Network.
ÎÎ The system checks the capabilities that are enabled for an app in the manifest and decides to
block/allow an outbound request.
ÎÎ Even if one capability is available, the system allows the app to listen on a port.
ÎÎ When the sockets close, any pending operations halt and exceptions are thrown.
ÎÎ The classes DatagramSocket, StreamSocketListener, and StreamSocket are similar and follow one
model to use advanced controls.
Concepts
ÎÎ Credential Locker
App uses to connect to services such as mail, messaging, Twitter, Facebook, and so on. The
Credential Locker is a comfortable and safe way to store these user credentials. The user name and
password can be stored in the Credential Locker. When user uses the app, using credential locker,
you can automatically log them on to services. With a user’s Microsoft Account stored credentials
can automatically roam in the Credential Locker.
Some of the user’s Microsoft account tasks can be simplified with the Credential Locker such as
storing and retrieving user credentials safely.
For example, if there is an app to connect that provides assistance for taking protected resources
such as social networking, mail, or media files. Then, each user should be provided with login
information and password. So, a User Interface (UI) should be built in such a way that the app that
takes the user name and password for the user, should then, be used to login the user into the app.
With the online identity provider, the app should be registered which you want to connect.
Once registered, the online provider gives an ID for the app.
yy Build the authentication request URI
The authentication request is sent to the online provider to an address included by request
URI. It is supplemented with other necessary information, such as a redirect URI and app ID.
In this code, the beginURL is a string value which is an authentication request including the
parameters such as client_id, scope, and response_type. The finalURL is the redirect url to
which the App is redirected, once the authentication request is successful. Both the beginURL and
finalURL are initialized using System.URI class to have the url of same type.
JavaScript
string res;
try
{
var webAuthenticationRes =
await Windows.Security.Authentication.Web.WebAuthenticationBroker.
Concepts
AuthenticateAsync(
Windows.Security.Authentication.Web.WebAuthenticationOptions.None,
beginURI,
finalURI);
switch (webAuthenticationResult.ResponseStatus)
{
case Windows.Security.Authentication.Web.WebAuthenticationStatus.
Success:
// Authentication is successful.
res = webAuthenticationRes.ResponseData.ToString();
break;
case Windows.Security.Authentication.Web.WebAuthenticationStatus.
ErrorHttp:
// HTTP error.
res = webAuthenticationRes.ResponseErrorDetail.ToString();
break;
default:
// Other error.
res = webAuthenticationRes.ResponseData.ToString();
break;
}
}
catch (Exception ex)
{
// Authentication has failed. Handle any SSL/TLS, parameter, and Network
Unavailable errors here.
res = ex.Msg;
}
In this code, the AuthenticateAsync method is called with request uri, in this case, the finalURL
and beginURL, to connect to the online service provider. The status of this connection is retrieved
from webAuthenticationResult.ResponseStatus which is run through a switch case. If the
connection is successful or failed, the appropriate messages are displayed.
Web authentication broker will not provide cookies to preserve by default. Since, user have to login
each time when they need to access resources for the provider. The online identity provider should
allow SSO for Web authentication broker to login with SSO. The app must call the overload of
AuthenticateAsync function which does not take a parameter callbackUri.
string res;
try
{ var webAuthenticationRes =
await Windows.Security.Authentication.Web.WebAuthenticationBroker.
AuthenticateAsync( Windows.Security.Authentication.Web.
WebAuthenticationOptions.None,
beginURI);
switch (webAuthenticationRes.ResponseStatus)
{
case Windows.Security.Authentication.Web.WebAuthenticationStatus.
Success:
// Authentication is successful.
res = webAuthenticationRes.ResponseData.ToString();
break;
case Windows.Security.Authentication.Web.WebAuthenticationStatus.
ErrorHttp:
// Returns the http error.
res = webAuthenticationRes.ResponseErrorDetail.ToString();
break;
default:
// Other error is returned.
res = webAuthenticationRes.ResponseData.ToString();
break;
}
}
catch (Exception ex)
Concepts
{
// Authentication has failed. Handle any SSL/TLS, parameter, and Network
Unavailable errors here.
res = ex.Msg;
}
In this code, the AuthenticateAsync method is called without the callbackuri i.e the finalURL
parameter. It takes only two parameters, options and authentication request (beginURL). The
result is then, run through switch case and appropriate messages are displayed.
case Windows.Security.Credentials.UI.UserConsentVerifierAvailability.
Available:
returnMsg = “You can use fingerprint verification.”;
break;
// Request the consent of the logged on user, using the fingerprint swipe
mechanism
var consentRes = await Windows.Security.Credentials.
UI.UserConsentVerifier.RequestVerificationAsync(userMsg);
switch (consentRes)
{
case Windows.Security.Credentials.UI.UserConsentVerificationResult.
Verified:
returnMsg = “Fingerprint has been verified.”;
break;
case Windows.Security.Credentials.UI.UserConsentVerificationResult.
DeviceBusy:
returnMsg = “The biometric device is busy.”;
break;
case Windows.Security.Credentials.UI.UserConsentVerificationResult.
DeviceNotPresent:
returnMsg = “Unable to find the biometric device.”;
break;
case Windows.Security.Credentials.UI.UserConsentVerificationResult.
DisabledByPolicy:
returnMsg = “Biometric verification is disabled by a policy.”;
break;
case Windows.Security.Credentials.UI.UserConsentVerificationResult.
NotConfiguredForUser:
returnMsg = “The user does not have any fingerprints registered. Try again
after adding a fingerprint to the “ +
“fingerprint database.”;
break;
case Windows.Security.Credentials.UI.UserConsentVerificationResult.
RetriesExhausted:
Concepts
Windows.Security.Credentials.UI.UserConsentVerificationResult.
Canceled:
returnMsg = “Fingerprint authentication cancelled.”;
break;
default:
returnMsg = “Fingerprint authentication currently not available.”;
break;
}
}
catch (Exception ex)
{
returnMsg = “Fingerprint authentication failed: “ + ex.ToString();
}
return returnMsg;
}
ÎÎ Prerequisites
The following example refers the Windows 8.1 Smart card sample. Not only it refers the new
Concepts
Windows.Devices.SmartCards namespace, but also refers the creation of virtual smart cards of
admin keys for which it contains some APIs defined by the Windows.Security.Cryptography
namespace.
In this code, the method DeviceInfo.FindAllAsync returns all the card readers associated
with the given device. Then, we iterate through each card reader and get the associated cards for
the given reader.
On card insertion by implementing a method to handle app behavior, an app should be allowed to
observe for CardAdded events. Following is the syntax for SmartCardReader:
Syntax:
{
// A card is inserted into the sender SmartCardReader.
}
if (challenge == null)
throw new ArgumentNullException(“challenge”);
if (newAdminkey == null)
throw new ArgumentNullException(“adminkey”);
SymmetricKeyAlgorithmProvider newAlg = SymmetricKeyAlgorithmProvider.
OpenAlgorithm(SymmetricAlgorithmNames.TripleDesCbc);
var newSymmetricKey = objAlg.CreateSymmetricKey(newAdminkey);
var newBuffEncrypted = CryptographicEngine.Encrypt(newSymmetricKey,
challenge, null);
return newBuffEncrypted;
}
}
In this code, the authentication is successful if the admin key generated data on the card (‘challenge’) is
same, as the admin key data allowed by the server or management tool (‘adminkey’).
await newProvisioning.GetChallengeContextAsync())
{
IBuffer bufferResponse = ChallengeResponseAlgorithm.CalculateResponse(
context.Challenge,
rootPage.AdminKey);
verifyResponse = await context.VerifyResponseAsync(bufferResponse);
}
In this code, the smart card is retrieved from the GetSmartCard method and the associated
smart card provisioning is retrieved using the method SmartCardProvisioning.
FromSmartCardAsync(newCard). The challenge value is retrieved using the
GetChallengeContextAsync method. This challenge value and the admin key are used to
calculate the challenge response algorithm using the method ChallengeResponseAlgorithm.
CalculateResponse. If the response is true then, the smart card authentication is successful.
[WebMethod]
public string Login()
{
// Verify certificate using Certificate Authentication
var cert = new System.Security.Cryptography.X509Certificates.
X509Certificate2(
this.Context.Request.ClientCertificate.Certificate);
bool test_cert = cert.Verify();
return test_cert.ToString();
}
7. Choose the default Web site in the IIS Manager. Click Add in the Actions section, select
Binding and then, choose https as the type. Then, set the port to “443”, and type the IIS
server’s full host name ’<server-name>.<domain-name>’. Set the SSL certificate to
ContosoBank. Click OK and then, Click Close in the Site Bindings window.
8. In the IIS Manager, choose the FirstContosoBank Web service. Double-click the SSL
Settings. Check Require SSL. Select Require under Client certificates. Click Apply in the
Actions section.
9. Now, check if the Web service is configured correctly by opening the Web browser and typing
the following Web address: ‘https://<server-name>.<domain-name>/FirstContosoBank/
Service1.asmx’.
For example, ’https://myserver.example.com/FirstContosoBank/Service1.asmx’.
10. If the Web service is configured correctly, then, you will be allowed to select a client certificate
in order to access the Web service.
To create multiple Web services, the previous steps can be repeated that can be got using the
certificate of same client.
315
0
0” VerticalAlignment=”Top” Height=”66” Width=”261” Click=”Import_Click”
FontSize=”16”/>
<Button x:Name=”Login” Content=”Login” HorizontalAlignment=”Left”
Margin=”611
305
0
0” VerticalAlignment=”Top” Height=”74” Width=”245” Click=”Login_Click”
FontSize=”15”/>
<TextBlock x:Name=”Result” HorizontalAlignment=”Left” Margin=”345
398
0
0” TextWrapping=”Wrap” VerticalAlignment=”Top” Height=”143” Width=”550”/>
<PasswordBox x:Name=”PfxPassword” HorizontalAlignment=”Left” Margin=”473
271
0
0” VerticalAlignment=”Top” Width=”219”/>
<TextBlock HorizontalAlignment=”Left” Margin=”345
278
0
0” TextWrapping=”Wrap” Text=”PFX password” VerticalAlignment=”Top”
FontSize=”19” Height=”39” Width=”123”/>
<Button x:Name=”Browse” Content=”Browse for PFX file”
HorizontalAlignment=”Left” Margin=”352
189
0
0” VerticalAlignment=”Top” Click=”Browse_Click” Width=”489” Height=”68”
FontSize=”19”/>
<TextBlock HorizontalAlignment=”Left” Margin=”717
271
0
0” TextWrapping=”Wrap” Text=”(Optional)” VerticalAlignment=”Top”
Concepts
3. Add the following statements in the MainPage.xaml.cs file as shown in Code Snippet 10.
Code Snippet 10:
using Windows.Web.Http;
using System.Text;
using Windows.Security.Cryptography.Certificates;
using Windows.Storage.Pickers;
using Windows.Storage;
using Windows.Storage.Streams;
4. Add the following variables to the MainPage class in the MainPage.xaml.cs file as shown
in Code Snippet 11.
Code Snippet 11:
C#
They give the address for the safe ‘Login’ method of the FirstContosoBank Web service. Also,
they specify the address for the global variable which keeps a PFX certificate to import in the
certificate store. For your IIS server then, update the <server-name> to the fully-qualified server
name.
5. Add the following click event handler for the login button in the MainPage.xaml.cs file, and
method to access the secured Web service as shown in Code Snippet 12.
Code Snippet 12:
Windows.Web.Http.HttpClient();
resp = await newHttpClient.GetAsync(reqUri);
if (resp.StatusCode == HttpStatusCode.Ok)
{
res.Append(“It’s successful”);
}
else
{
res = res.Append(“ failed with “);
res = res.Append(resp.StatusCode);
}
}
catch (Exception ex)
{
res = res.Append(“ failed with “);
res = res.Append(ex.Msg);
}
Res.Text = res.ToString();
}
6. Add the following click event handlers in the MainPage.xaml.cs file. To browse and import
a selected PFX file into the certificate store as shown in Code Snippet 13.
Code Snippet 13:
store....”;
await CertificateEnrollmentManager.UserCertificateEnrollmentManager.
ImportPfxDataAsync(
pfxCertificate,
PfxPassword.Password,
ExportOption.Exportable,
KeyProtectionLevel.NoConsent,
InstallOptions.DeleteExpired,
“Imports Pfx”);
Res.Text = “Certificate import succeeded”;
}
catch (Exception error)
{
Res.Text = “Certificate import failed with “ + error.Msg;
}
}
private async void Browse_Click(object newSender, RoutedEventArgs
eventArgs)
{
StringBuilder strBuilderresponse = new StringBuilder(“Pfx file selection
“);
FileOpenPicker pfxFileOpenPicker = new FileOpenPicker();
pfxFileOpenPicker.FileTypeFilter.Add(“.pfx”);
pfxFileOpenPicker.CommitButtonText = “Open”;
try
{
StorageFile pfxStorageFile = await pfxFileOpenPicker.
PickSingleFileAsync();
if (pfxStorageFile!= null)
{
IBuffer newBuffer = await FileIO.ReadBufferAsync(pfxStorageFile);
Concepts
PfxPassword.Password = string.Empty;
res.Append(“succeeded”);
}
}
else
{
res.Append(“ failed”);
}
}
catch (Exception error)
{
res.Append(“ failed with “);
res.Append(error.Msg); ;
}
Res.Text = res.ToString();
}
ÎÎ Windows.Security.Cryptography
ÎÎ Windows.Security.Cryptography.Core
Concepts
ÎÎ Windows.Security.Cryptography.Certificates
ÎÎ Windows.Security.Cryptography.DataProtection
Methods Description
DecodeFromBase64String It decodes a string from base 64.
DecodeFromHexString It decodes from a hexadecimal string.
EncodeToBase64String It encodes data to a base 64 string.
EncodeToHexString It encodes data to a hexadecimal string.
Table 6.1: Encode and Decode Methods
(0x80070005)
earlier example. Using the ProtectAsync method if a folder is protected, then, same protection
is inherited by all files in that folder. Code Snippet 15 demonstrates how to use selective wipe.
C#
Code Snippet 15:
// How to use Selective Wipe to Add a folder and protect the folder
private async Task<StorageFolder> AddnewFolder(string newfolderName)
{
StorageFolder newFolder = await newappRootFolder.LocalFolder.
CreateFolderAsync(newfolderName);
var status = await ProtectItem(newFolder, newenterpriseIdentity);
return newFolder;
}
// How to use selective wipe to add a file and protect it.
private async Task<StorageFile> AddnewFile(string newfileName,
StorageFolder newfolder)
{
StorageFile newFile = await newfolder.CreateFileAsync(newfileName);
var status =
await Windows.Security.EnterpriseData.FileRevocationManager.
GetStatusAsync(newFile);
if (status != Windows.Security.EnterpriseData.FileProtectionStatus.
Protected)
{
status = await ProtectItem(newFile, newenterpriseIdentity);
}
return newFile;
}
private async Task<Windows.Security.EnterpriseData.FileProtectionStatus>
Concepts
ProtectAsync(item, newenterpriseIdentity);
return status;
}
}
return newstream;
}
// Delete the items that are revoked using Selective Wipe.
{
// You must add code to handle exception.
return finalresult;
}
newcontactPicker.CommitButtonText = “Choose”;
newcontactPicker.SelectionMode =
Windows.ApplicationModel.Contacts.ContactSelectionMode.Fields;
contactPicker.desiredFieldsWithContactFieldType.append(Windows.
ApplicationModel.Email
Code Snippet 20 uses the PickContactsAsync to enable the use to select one or multiple contacts.
C#
Code Snippet 20:
if (newcontact != null)
{
OutputName.Text = newcontact.FirstName;
Concepts
if (contactslist.Count > 0)
{
foreach (Contact newcontact in contactslist)
{
// Add code here to work on the contact information.
}
}
Concepts
(A) UserConsentVerifier.CheckAvailabilityAsync
(B) Windows.Security.Credentials.UI
(C) UserConsentVerifier
(D) System.Threading.Tasks
4. _________________ can be revoked when an app is not authorized to the app data.
6.6.1 Answers
1. B
2. C
3. A
4. D
5. D
Concepts
Summary
ÎÎ Authentication challenges defined can be communicated using the reader to get the smart card or
can also access a virtual smart card for authentication.
ÎÎ Certificate authentication is used for high level authentication of user.
ÎÎ Certificate authentication provides secured authentication beyond a user name and password
combination.
ÎÎ Selective Wipe can be used to identify protected files in your app.
ÎÎ The GetStatusAsync method can be used to decide the file’s Selective Wipe protection status or a
folder to check whether the file is protected or not.
ÎÎ Different authentication APIs can be used to verify the identity of a user as well as verify user
agreement for purchases.
ÎÎ The contact picker is configured by SelectionMode property which retrieves only the required app
data fields.
Concepts
The session will discuss how to launch, resume, and multitask. It will also
discuss the debugging and testing and packaging the Windows Store App.
ÎÎ Debug and test Visual Studio and DLL load failures with
the Event Viewer
XAML
<App xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
Concepts
x:Class=”AppName.App” >
Whenever the user launches the app, the OnLaunched method is called. The previous state of the app
and the activation arguments are stored in LaunchActivatedEventArgs parameter.
using System;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;
namespace Myapplication
{
public partial class NewApp
{
async protected override void OnLaunched(LaunchActivatedEventArgs newArgs)
{
MainPageCreateAndActivate();
}
// Creates the MainPage if not already created. This also activates
// the window to focus on foreground and input.
private MainPage MainPageCreateAndActivate()
{
if (Window.Current.Content == null)
{
Window.Current.Content = new MainPage();
}
Window.Current.Activate();
return Window.Current.Content as MainPage;
}
}
}
Concepts
Step 2: If app was suspended (later, it gets terminated), then restore application data
The system sends the Activated event when the user switches to the terminated app. Here, Kind is set
to Launch and PreviousExecutionState is set to Terminated or ClosedByUser. The displayed
content should be refreshed and app should store its saved application data.
In this code, the app has failed to save its application data, if the value of PreviousExecutionState
is NotRunning. In this case, the app should start from were being initially launched.
using System;
Concepts
using Windows.UI.Xaml;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
This code indicates that before the system suspends it, the app is required to save its application data.
Step 2: Before suspension, application data should be saved.
While app is handling the Suspending event, in the handler function, it has got an opportunity to save its
important application data. To save simple application data, the app should use the Local Settings storage
API synchronously. Code Snippet 5 demonstrates how to save the application data.
Code Snippet 5:
C#
yy After a short period of time to resume an app, take users to the state from where they had
left.
yy After a long period of time if user wants to resume then, take users to default landing page.
yy Provides users to select if they want to restore their app to its earlier state or start fresh.
yy When the app is being suspended then, save its data. To ensure the restore of an app state,
save app data. Since suspended apps will not receive notification, when Windows
terminates them.
yy To restore app, use saved app data.
yy When the app gets suspended, try to release plenty of resources and file handles.
yy Update the UI if content has changed as it was last visible to the user. It should look like as if
it was working when the user was not present there.
yy When the app moved off screen, don’t terminate it.
yy During app crash, the app gets terminated then, do not restore its state.
yy Do not provide users Close buttons or other ways to terminate the app in its UI. They
should feel that Windows is taking care of their apps for them.
XML
<Package xmlns=”http://schemas.microsoft.com/appx/2010/manifest”
xmlns:m2=”http://schemas.microsoft.com/appx/2013/manifest”>
<Apps>
<App Id=”AutoLaunch.App”>
<Extensions>
<Ext Category=”windows.fileTypeAssociation”>
<FileTypeAssociation Name=”alsdk”>
<DispName>SDK Type</DispName>
<Icon>image\Icon.png</Icon>
<Tip>SDK tip </Tip>
<EditFlags OpenIsSafe=”true” />
<SupportedFileTypes>
<FileType ContentType=”image/jpeg”>.alsdk</FileType>
</SupportedFileTypes>
</FileTypeAssociation>
</Ext>
</Extensions>
</App>
Concepts
</Apps>
</Package>
This code adds an Extension element to the package manifest. The windows.fileTypeAssociation category
indicates that the app handles files with the .alsdk extension. The extension element declares an
extensibility point for the app.
ÎÎ File picker
Concepts
Note: The received file could have come from an untrustworthy source. So before taking action on it,
one should validate the content of a file.
<Package xmlns=”http://schemas.microsoft.com/appx/2010/manifest”
xmlns:m2=”http://schemas.microsoft.com/appx/2013/manifest”>
<Apps>
<App Id=”AutoLaunch.App”>
Concepts
<Extensions>
<Ext Category=”windows.protocol”>
<Protocol Name=”alsdk” m2:DesiredView=”useLess”/>
<Icon>images\logo.png</Icon>
</Extensions>
</App>
</Apps>
</Package>
The code snippet is used to add an Extension element to the package manifest. The windows.protocol
category indicates that the app handles the alsdk URI scheme name.
Step 2: Proper icons should be added.
The default app for a URI scheme name will be displayed in various places in the system.
Following are some guidelines:
1. Include appropriate icons in project to give a good look to logo.
2. Folder 16/32/48/256 px should be included for the small logo and icon sizes in the image.
3. The icons should be tested on white background which should be suitable for the look of the app
tile logo and the color plate.
Step 3: Handle the Activated event.
All activation events are received by the OnActivated event handler. The type of activation is indicated
by the event Kind property. Code Snippet 8 demonstrates how to set up to handle URI activation events.
Code Snippet 8:
C#
Setting Value
Verb Show
Action Display Name Show Pictures
Content Event ShowPicturesOnArrival
Table 7.1: Settings
The string which is AutoPlay displays for the application is identified by the ActionDisplayName setting.
For the selected option, the Verb setting identifies a value which is passed to the application. The multiple
launch actions for an AutoPlay event can be specified and use the Verb setting to identify which option a
user has selected for the application. The activation event arguments is passed to the application and by
checking this Verb property, you can identify which option the user has selected. You can use any value
for the Verb setting except, open, which is reserved.
9. In the Launch Actions section for the AutoPlay Content item, to add a second launch action, click
Add New. For the second launch action, enter the following values. Table 7.2 lists the values of the
second launch action.
Setting Value
Verb Copy the content
Action Display Name Copy Pictures Into Library
Content Event ShowPicturesOnArrival
Table 7.2: Values of Second Launch Action
10. Choose File Type Associations from the Available Declarations drop-down list and click Add.
11. Set the Display Name field to ‘AutoPlay Copy or Show Images’ and the Name field to ‘image_
association1’ from the Properties of the new File Type Associations declaration.
12. Set the File Type field of the default supported file type to .jpg from the Supported File Types
section. Then, click Add New in the Supported File Types section.
13. From the new file association, set the File Type field to .png. Then, save and close the manifest file.
Steps for the XAML page are as follows:
1. Open the MainPage.xaml file and to the default <Grid> section and add the following XAML code.
Code Snippet 9 demonstrates the XAML UI code.
Code Snippet 9:
XAML
In this code, the columns and rows consisted by the grid class defines a flexible grid area.
2. Child elements to the row/column assignments of Grids are arranged and measured.
3. Initialization code should be added.
The verb value in the Verb property is checked by in this step. During this step, the startup arguments
are passed to the application during the OnFileActivated event. A user selected method related
to the option is called by the code. To the application for the camera memory event, the root folder
of the camera storage is passed by the AutoPlay. From the first element of the Files property, this
folder can be retrieved.
a. Add the following code to the App class by opening the App.xaml.cs or App.xaml.vb file.
Code Snippet 10 demonstrates the App class code.
Code Snippet 10:
C#
protected override void OnFileActivated(FileActivatedEventArgs
fileActivatedArgs)
{
if (fileActivatedArgs.Verb == “show”)
{
Frame firstRootFrame = (Frame)Window.Current.Content;
MainPage newPage = (MainPage) firstRootFrame.Content;
// Call DisplayImages with root folder from the camera storage.
newPage.DisplayImages((Windows.Storage.StorageFolder)
fileActivatedArgs.Files[0]);
}
if (fileActivatedArgs.Verb == “copy”)
{
Frame firstRootFrame = (Frame)Window.Current.Content;
MainPage newPage = (MainPage) firstRootFrame.Content;
// Call CopyImages with root folder from the camera storage.
newPage.CopyImages((Windows.Storage.StorageFolder)
fileActivatedArgs.Files[0]);
}
base.OnFileActivated(fileActivatedArgs);
Concepts
of the initial arguments passed to the application while the OnFileActivated event. The
method is then called which is related to the user selected option.
4. Add code to display images.
In the MainPage.xaml.cs or MainPage.xaml.vb file, add the following code to the MainPage
class. Code Snippet 11 demonstrates to display images.
Code Snippet 11:
C#
Windows.Storage.Streams.IRandomAccessStreamnewIimageStream =
await newStorageFile.OpenAsync(Windows.Storage.FileAccessMode.
Read);
Windows.UI.Xaml.Media.Imaging.BitmapImage newImageBitmap =
new Windows.UI.Xaml.Media.Imaging.BitmapImage();
newImageBitmap.SetSource(imageStream);
var newElement = new Image();
newElement.Source = imageBitmap;
newElement.Height = 100;
Thickness elementMargin = new Thickness();
elementMargin.Top = index * 100;
element.Margin = elementMargin;
FilesCanvas.Children.Add(newElement);
}
catch (Exception error)
{
WriteMsgText(error.Message + “\n”);
}
}
// Write a message to MessageBlock on the UI thread.
private Windows.UI.Core.CoreDispatcher messageDispatcher = Window.
Current.CoreWindow.Dispatcher;
private void WriteMsgText(string message, bool overwrite = false)
{
messageDispatcher.InvokeAsync(Windows.UI.Core.
CoreDispatcherPriority.Normal,
(s, a) =>
{
if (overwrite)
FilesBlock.Text = newMessage;
else
FilesBlock.Text += newMessage;
Concepts
}, this, null);
}
The code snippet is used to display all the images specified in the GetFolderAsync method.
This method gets a single sub folder from the current folder using the specified folder name.
The InvokeAsync method executes the specified delegate asynchronously on the thread the
Dispatcher is associated with.
5. To copy images, code should be added.
In the MainPage.xaml.cs or MainPage.xaml.vb file, add the following code to the MainPage class.
Code Snippet 12 demonstrates how to copy images.
Code Snippet 12:
C#
{
WriteMsgText(“Failed to copy images.\n” + error.Message + “\n”);
}
}
In this code, the images are copied from the first folder in the DCIM folder to the new image folder.
6. Build and execute the application. Press F5 to build and deploy the application in debug mode.
To run your application, insertion of a camera memory card or any other storage camera device
into the machine is necessary. From the AutoPlay list of options, choose one of the content event
options which you specified in your package.appxmanifest file. The camera memory card in
the DCIM folder, the sample code displays or copies pictures. The camera memory card stores
pictures in a PRIVATE\ACHD or AVCHD folder which is required to update the code accordingly. In
case of unavailability of camera memory card, a flash drive can be used as long as it has a folder
named DCIM in the root.
the Windows Store App with advanced upload features and file download that run in the background
during App suspension, Operation lifecycle management, and persistence beyond app termination.
The Background Transfer feature works as follows:
ÎÎ Each transfer operation is managed individually by the system and through an app UI progress
information is available for display.
understand exactly how your app works. Executing code is displayed by the visual studio when the
execution in the debugger gets suspended. The change of values of the program can be seen by
executing the program one statement at a time.
ÎÎ Windows App Certification Kit version 3.1 must be installed which appears along with the
Windows Software Development Kit (SDK) for Windows 8.1.
Note: When the app package is created in Visual Studio, run the Windows App Certification Kit.
The installation of Windows App Certification Kit version 3.1 or higher version will replace any earlier
version of the kit that is installed on the system.
Windows Store project or item based on a template then, the packaging process gets started. When
Windows Store App is created, Visual Studio creates a source file for the app package.
3. Specify one in the Short Name text box on your main logo.
4. For the main logo, indicate a logical name in the Square 150 x 150 Logo text box and the
default value is Assets\Logo.png.
5. In the Scaled Assets area of the page, choose the Browse button next to the Scale 80 box,
move to the Assets folder, show the file that contains the image that’s scaled to 80%, and then,
<Properties>
<Property>
<DisplayName>ms-resource:calculator</DisplayName>
<Desc>ms-resource:numbers</Desc>
<Icon>tile.png</Icon>
</Property>
</Properties>
8. Update Design view by switching to Source view if the resource changes are not displayed, and
then, switch back to Design view.
For additional languages to create resource files, copy the file from Solution Explorer or in Windows
Explorer, and then, rename it using name.language.resx or using name.language-culture.resx
patterns.
ÎÎ If Windows Store is associated with the app or the Create App Package command is invoked
then, sign in with a developer account, from the associated app on the Store, the value of the field
is restored.
ÎÎ If you have invoked the Create App Package command but not signed into the account of
Microsoft developer, then from the source manifest, the value of this field is taken.
1. Before choosing the Reserve button, type a name in the Reserve a new app name text box.
2. Choose the Next button after selecting the app name for which you want to create this package.
Wizard’s Select and Configure Packages page appears.
ÎÎ The default value of the Publisher attribute is your user name if you create a local package.
ÎÎ The Publisher attribute is set to the Publisher ID which is either created by a package for the
Concepts
Windows Store or associates your app with it. When you sign in during package creation, it is
obtained from your developer account at the Store.
<PackageCertificateKeyFile>
RisingStar_TemporaryKey.pfx
</PackageCertificateKeyFile>
The connected path or full path of the source certificate itself is the value of the PackageCertificateKeyFile.
The values of following properties are set when the Visual Studio creates a certificate.
ÎÎ The value of the Basic Constraints extension is set to Subject Type=End Entity.
ÎÎ The value of the Enhanced Key Usage (EKU) extension is set to Code Signing.
Certification validity gets over for one year from the date when they were created.
Modifying installed apps
If installed package files are modified, launching the app may prevented by signing verification. Make the
changes in the original source files using a developer license to modify a package, and then redeploy the
modified package.
File=”$(AppxPackagingInfoFile)”>
<Output TaskParameter=”Lines”
PropertyName=”AppxPackagingOutputForWinACK” />
</ReadLinesFromFile>
3. In report, the output file ValidationResult.xml, will be written. Make sure that the directory exists
before you queue the build, if you specify a static location rather than $(outdir). Also, ensure that
before you queue the build again, delete the output file. Build should be automated.
4. When the build finishes, examine the test results in the ValidationResult.htm file. In the last entry of
the PostPackageEvent target, the test results appear which is previously pasted into the
ValidationResult.htm file.
3. App should be designed in such a way that, it should get _________________ and should resume
when the user switches back to it.
5. The app receives activation events for the __________________ scheme names, listed in the
package manifest.
7.4.1 Answers
1. D
2. A
3. C
4. B
5. A
Concepts
Summary
ÎÎ Windows 8 suspends your app in memory when users move your app off-screen and enables
another app to have the foreground.
ÎÎ The system sends the Activated event when the user switches to the Terminated app.
ÎÎ By releasing exclusive resources and file handles which helps other apps can access them while
this app is not using them.
ÎÎ As a default app, the chosen app will be activated every time when that type of file is launched.
ÎÎ URI scheme name should be registered to handle all URI launches for that type of URI scheme.
ÎÎ User connects a device to their computer auto play to provide your application as an option.
ÎÎ A set of testing and debugging tools are included in the Visual Studio which helps to ensure that
the Windows Store App is of the highest quality.
ÎÎ Using Visual Studio Windows Store can be accessed and Windows Store App can be packaged for
distribution.
Concepts