Developing Mobile Applications Using Windows Phone Learner’s Guide © 2014 Aptech Limited All rights reserved. No part of this book may be reproduced or copied in any form or by any means – graphic, electronic or mechanical, including photocopying, recording, taping, or storing in information retrieval system or sent or transferred without the prior written permission of copyright owner Aptech Limited. All trademarks acknowledged.
APTECH LIMITED
Contact E-mail:
[email protected] Edition 1 - 2014
Dear Learner, We congratulate you on your decision to pursue an Aptech course. Aptech Ltd. designs its courses using a sound instructional design model – from conceptualization to execution, incorporating the following key aspects: ¾¾
Scanning the user system and needs assessment Needs assessment is carried out to find the educational and training needs of the learner Technology trends are regularly scanned and tracked by core teams at Aptech Ltd. TAG* analyzes these on a monthly basis to understand the emerging technology training needs for the Industry. An annual Industry Recruitment Profile Survey is conducted during August - October to understand the technologies that Industries would be adapting in the next 2 to 3 years. An analysis of these trends & recruitment needs is then carried out to understand the skill requirements for different roles & career opportunities. The skill requirements are then mapped with the learner profile (user system) to derive the Learning objectives for the different roles.
¾¾
Needs analysis and design of curriculum The Learning objectives are then analyzed and translated into learning tasks. Each learning task or activity is analyzed in terms of knowledge, skills and attitudes that are required to perform that task. Teachers and domain experts do this jointly. These are then grouped in clusters to form the subjects to be covered by the curriculum. In addition, the society, the teachers, and the industry expect certain knowledge and skills that are related to abilities such as learning-to-learn, thinking, adaptability, problem solving, positive attitude etc. These competencies would cover both cognitive and affective domains. A precedence diagram for the subjects is drawn where the prerequisites for each subject are graphically illustrated. The number of levels in this diagram is determined by the duration of the course in terms of number of semesters etc. Using the precedence diagram and the time duration for each subject, the curriculum is organized.
¾¾
Design & development of instructional materials The content outlines are developed by including additional topics that are required for the completion of the domain and for the logical development of the competencies identified. Evaluation strategy and scheme is developed for the subject. The topics are arranged/organized in a meaningful sequence.
The detailed instructional material – Training aids, Learner material, reference material, project guidelines, etc.- are then developed. Rigorous quality checks are conducted at every stage. ¾¾
Strategies for delivery of instruction Careful consideration is given for the integral development of abilities like thinking, problem solving, learning-to-learn etc. by selecting appropriate instructional strategies (training methodology), instructional activities and instructional materials. The area of IT is fast changing and nebulous. Hence, considerable flexibility is provided in the instructional process by specially including creative activities with group interaction between the students and the trainer. The positive aspects of Web based learning –acquiring information, organizing information and acting on the basis of insufficient information are some of the aspects, which are incorporated, in the instructional process.
¾¾
Assessment of learning The learning is assessed through different modes – tests, assignments & projects. The assessment system is designed to evaluate the level of knowledge & skills as defined by the learning objectives.
¾¾
Evaluation of instructional process and instructional materials The instructional process is backed by an elaborate monitoring system to evaluate - on-time delivery, understanding of a subject module, ability of the instructor to impart learning. As an integral part of this process, we request you to kindly send us your feedback in the reply prepaid form appended at the end of each module.
*TAG – Technology & Academics Group comprises members from Aptech Ltd., professors from reputed Academic Institutions, Senior Managers from Industry, Technical gurus from Software Majors & representatives from regulatory organizations/forums. Technology heads of Aptech Ltd. meet on a monthly basis to share and evaluate the technology trends. The group interfaces with the representatives of the TAG thrice a year to review and validate the technology and academic directions and endeavors of Aptech Ltd.
Aptech New Products Design Model Key Aspects
1 Scanning the user system and needs assessment
2
Evaluation of Instructional Processes and Material
Need Analysis and design of curriculum
3
Design and development of instructional material
6
Assessment of learning
4
Strategies for delivery of instructions
5
Preface The book, Developing Mobile Applications Using Windows Phone, introduces you to the basic and important aspects of creating mobile apps in Windows Phone 8. Mobile app development is the order of the day in this modern era. Thus, creating mobile apps offer tremendous scope for all those who have a passion for User Interface (UI) design or application programming or both. With Windows Phone 8, learning to design mobile apps becomes much more convenient and faster because of various developer-friendly programming tools and front-end tools. The IT software giant, Microsoft, began its journey of mobile operating systems in the year 2000, with its introduction of Windows Mobile. In tune with the constant changing times, Microsoft introduced a much more sophisticated mobile operating system called Windows Phone in the year 2010. Windows Phone 7 was the first of its series, which was packed with a whole lot of exciting features in a UI design called Metro. Windows Phone 8 was later introduced in 2012 as the successor of Windows Phone 7 and is currently one of the most popular mobile Operating Systems (OS) in the consumer world. This book begins by introducing to you an overview of Windows Phone 8 and its unique features. As you progress, you will learn all the important aspects of effective UI design through eXtensible Application Markup Language (XAML) and implementation of key functionality in C#. Later on, you will explore the various ways to enhance app development through integration with various .NET languages and Application Programming Interfaces (APIs). Finally, you will learn about the range of operations pertaining to data handling, management, and storage in Windows Phone 8. This book is the result of a concentrated effort of the Design Team, which is continuously striving to bring you the best and the latest in Information Technology. The process of design has been a part of the ISO 9001 certification for Aptech-IT Division, Education Support Services. As part of Aptech’s quality drive, this team does intensive research and curriculum enrichment to keep it in line with industry trends. We will be glad to receive your suggestions.
Design Team
Table of Contents
Sessions 1.
Introduction to Windows Phone 8
2.
Overview of Windows Phone 8 User Interface
3.
Working with Windows Phone 8
4.
Implementing Notifications and Live Tiles
5.
Working with Platform APIs, Tasks, and Choosers
6.
Data Management in Windows Phone 8
Session - 1
Introduction to Windows Phone 8 Welcome to the Session, Introduction to Windows Phone 8. This session describes about the basics of Windows Phone 8, Windows Phone Software Development Kit (SDK) 8, and some of the important terminologies used in Windows Phone 8. You will also learn about some basic operations in Windows Phone 8 and development as well as deployment of mobile applications in Windows Phone 8. At the end of this session, you will be able to: ÎÎ Describe the important features of Windows Phone 8 ÎÎ List the hardware and software requirements of Windows Phone 8 ÎÎ Explain the important terminologies in Windows Phone 8 ÎÎ Identify the purpose of Windows Phone SDK 8 ÎÎ List the system requirements for Windows Phone SDK 8 ÎÎ Describe launching and closing applications in Windows Phone 8 ÎÎ Explain the process to deactivate and reactivate applications ÎÎ Explain the steps involved in developing, executing, and deploying a Windows Phone application
Session
1 Introduction to Windows Phone 8
1.1 Introduction A few years earlier, spending on a Personal Computer (PC) was considered a big investment. With the introduction of Tablet PCs and Smartphones at affordable prices, packaged with mobility, convenience, and attractive utilities, personal computing has become more of a way of life rather than a luxury. Nowadays, people are able to perform a range of operations both online and offline through mobile applications on Smartphones, while being on the move. Thus, mobile application development offers tremendous scope and holds the key to our current and future growth in Information Technology. Today, there are a number of mobile operating systems available, one among which is Windows Phone 8.
1.2 Overview of Windows Phone 8 Windows Phone 8 is one of the most popular and innovative mobile operating systems offered by Microsoft. It is, in fact, the successor to Windows Phone 7, with enhanced features and utilities. Nokia, Samsung, HTC, and Huawei are some of the important manufacturers of Windows Phone 8-based mobile phones.
Concepts
Figure 1.1 shows the opening screen of Windows Phone 8 in a Smartphone.
Figure 1.1: Windows Phone 8 Opening Screen
V 1.0 © Aptech Limited
Session
1 Introduction to Windows Phone 8
Note – A mobile operating system is an operating system that is specific to a range of mobile devices,
such as Smartphones and Tablet PCs. Apart from Windows Phone 8, the other popular mobile operating systems available in the market are Google Android and Apple iOS.
1.2.1 Features of Windows Phone 8 Microsoft is always known for providing a powerful and an easy-to-use, or rather an addictive interface in its products to its users; Windows Phone 8 is no exception. Some of the important features that make Windows Phone 8 a popular mobile operating system both for developers as well as for consumers in the mobile world are as follows: ÎÎ
Powerful Operating System Windows Phone 8 is based on Windows NT kernel architecture, similar to Windows 8 operating system. This provides for enhanced security, file storage, memory, and graphics. It also provides for multi-tasking capability, which enables developers to run an application in parallel as a background process, without affecting regular mobile operations. Note – Windows 7 was developed by using Windows CE-based architecture. Hence, the upgrade
option is not available from Windows Phone 7 to Windows Phone 8. Mobile applications created specifically for Windows 7 cannot be used in Windows Phone 8 as the compilation processes of both the mobile operating systems are different. However, mobile applications created in Windows Phone 7.1 can be upgraded to Windows Phone 8. ÎÎ
Attractive User Interface The User Interface (UI) of Windows Phone 8 is called the Modern UI. It is simple, intuitive, and carefully planned to suit the limited display of Smartphones. Commonly used options and features are organized in the form of tabs and rounded graphic icons, which make navigation simpler and faster for the users.
ÎÎ
Social Networking
Internet Explorer 10 is the default browser for Windows Phone 8. Note – Integration of data stored locally in Windows Phone 8 and online data available in social
networking sites is done through a feature called Hub.
V 1.0 © Aptech Limited
Concepts
Windows Phone 8 provides ample support for social networking through E-Mail, Chat, and Skype conversations. Windows Phone 8 also creates and maintains contact pages in People Hub by integrating all the contact groups in various social networking sites, such as Facebook and Twitter.
Session ÎÎ
1 Introduction to Windows Phone 8
Support for Media Files Windows Phone 8 provides applications to create and store photos, videos, and music files. You could also share the media files on social networking sites and store them both locally as well as in the Microsoft cloud, SkyDrive. Exclusive Hubs, such as Music + Videos Hub and Photos Hub, are available for managing media files effectively.
ÎÎ
Office Hub You can use the Microsoft Office applications in the Windows Phone 8 to create documents, spreadsheets, and presentations on the move. You could also store and manage the files locally as well as in the cloud.
ÎÎ
Data Sense This feature is available only with selected Windows Phones. This feature lets you keep a tab on your data download by notifying you in advance whenever your download limit is about to get exhausted. Apart from the features discussed, there are loads of other features, such as Kid’s Corner, Games, and data transfer between two Windows devices, which provide the Windows Phone 8 users a truly rewarding experience.
1.2.2 Windows Phone 8 Specifications
Concepts
Hardware specifications for Windows Phone 8 include: ÎÎ
Memory – 180 MB for running applications
ÎÎ
WVGA (800 x 480) 15:9, WXGA (1280×768) 15:9, 720p (1280×720) 16:9 format display
ÎÎ
4-point multi-touch screen
ÎÎ
Sensors for A-GPS and accelerometer
ÎÎ
Start, Search, and Back buttons
ÎÎ
Support for data connectivity using cellular networks and Wi-Fi
ÎÎ
256 MB of RAM and 8 GB of flash storage
ÎÎ
A front-facing and a back-facing camera
V 1.0 © Aptech Limited
Session
1 Introduction to Windows Phone 8
ÎÎ
NFC-enabled (Near Field Communication) chip
ÎÎ
Compass
ÎÎ
Gyroscope
With these hardware specifications as the base, you will be able to develop mobile applications in Windows Phone 8. To develop mobile applications in Windows Phone 8, the following software specifications are also required: ÎÎ
Development Environment PC with Windows 8 or Windows 8 Pro OS
ÎÎ
Windows Phone SDK 8
1.2.3 Important UI Elements and Terminologies in Windows Phone 8
Concepts
In order to develop Windows Phone apps in Windows Phone 8, you need at first to be familiarized with its UI elements and some of its important terminologies. Figure 1.2 shows a Windows Phone 8 screen with some of the important terminologies highlighted.
Figure 1.2: Important Terminologies in a Windows Phone 8 Screen
V 1.0 © Aptech Limited
Session
1 Introduction to Windows Phone 8
Table 1.1 lists some of the important Windows Phone 8 terms along with their purpose.
Terminology
Purpose
Start Screen
The opening screen, Start screen, of the Modern UI provides flexible customization capabilities through which you can organize your favorite applications and options.
Live Tiles
Live Tiles are shortcuts to various mobile applications. They provide you with updates and notifications from all your favorite Web sites.
Live Apps
Live Apps are a range of mobile applications, such as E-Mail and Calendar, developed specially for Windows Phone 8.
Status Bar
Status Bar is available on the top of the screen and provides the status of various mobile operations.
Application Title
Application Title displays the title of the currently running application.
Page Title
Page Title displays the title of the page inside an application, which may or may not be available for each application.
On-screen keyboard Application Bar Back, Start, Search
On-screen keyboard is a context-sensitive feature that appears whenever the user performs any typing operation. Application Bar is specific to each app with additional menu and navigation options. Depending on the operations, it may or may not appear for each app. These hardware buttons are mandatorily available in all Windows Phones to perform the required navigation or search operations.
Table 1.1: Important Terminologies in Windows Phone 8
1.2.4 Windows Phone SDK 8
Concepts
Mobile applications that are specifically developed for Windows are called Windows Phone apps. To develop apps for Windows Phone 8, the first step is to download a development suite called the Windows Phone SDK 8. Windows Phone SDK is available as a free download for all those users who own a licensed copy of Windows 8 Operating System. Windows Phone SDK 8 provides a collection of tools and features which aid the developers to build robust applications. Some of the noteworthy tools and features available in SDK 8 are as follows: ÎÎ
Support for C++, HTML 5, Direct 3D applications, Third-party gaming frameworks, and native C++ game development
ÎÎ
The Wallet feature for digitally storing credit cards and managing online financial transactions
V 1.0 © Aptech Limited
Session
1 Introduction to Windows Phone 8
ÎÎ
Enhanced multi-lingual support
ÎÎ
Templates for Windows Phone 8 UI options
ÎÎ
Coding and Designing Tools
Windows Phone SDK 8 provides the following tools for creating Windows Phone apps: ÎÎ
Microsoft Visual Studio Express 2012 for Windows Phone Visual Studio Express 2012 This Integrated Development Environment (IDE) provides all the necessary development tools as well as integration testing tools to aid in comprehensive development of mobile applications. An app developer could use C# and VB .NET languages to develop Windows Phone apps in Visual Studio Express.
ÎÎ
Blend for Visual Studio Yet another development tool is Blend for Visual Studio. It is a stand-alone application. This tool was formerly known as Expression Blend. This tool provides a powerful visual design environment for designing the UI of your application. Note – In general, app developers can choose Visual Studio Express for developing complex
applications that involve extensive coding and functionality. If the app requires a powerful and visually appealing UI design with limited coding, it is best to go in for Blend for Visual Studio. ÎÎ
Design library for Windows Phone The Design library provides a set of guidelines to develop applications based on design principles.
ÎÎ
Debugging Tools After the app is developed, it needs to be tested and debugged. Windows Phone SDK 8 provides a tool called Windows Phone (WP) Emulator to run, debug, and test Windows Phone apps. WP Emulator is a desktop application, which simulates a Windows Phone device, to facilitate testing and debugging of Windows Phone apps. Testing and Validation Tools Windows Phone SDK 8 provides a collection of testing and validation tools to test and evaluate the quality and performance of a Windows Phone app, such as Simulation Dashboard for Windows Phone and Windows Phone Application Analysis.
ÎÎ
Deployment Tools Windows Phone SDK 8 provides two tools to aid in deployment of Windows Phone apps to Windows Phone device, namely, Windows Phone Developer Registration Tool and Application Deployment Tool. You can also use command prompt and Visual Studio to deploy the Windows Phone app.
V 1.0 © Aptech Limited
Concepts
ÎÎ
Session
1 Introduction to Windows Phone 8
1.2.5 Windows Phone SDK 8 System Requirements In order to use Windows Phone SDK 8 for developing Windows Phone apps, you need to have the following system requirements in place: ÎÎ
Windows 8 or Windows 8 Pro or Windows 8 64-bit client version
ÎÎ
64-bit CPU
ÎÎ
4 GB Free hard disk space
ÎÎ
4 GB RAM
1.3 Operating Windows Phone Apps Most of the operations in Windows Phone 8 revolve around Windows Phone apps. When a Windows Phone app is launched, it goes through different stages of Application lifecycle in Windows Phone 8. The Application lifecycle comprises operations, such as launching, running, activating, deactivating, and closing of Windows Phone apps. Note – Remember that at any point in time, you can keep only one app active and running in Windows
Phone 8.
1.3.1 Launching and Closing Applications ÎÎ
Launching an Application To launch an application, you can use either the Live Tiles or the Live Apps list. You could also launch an application by tapping its associated notification icon in the Start screen.
Concepts
Figures 1.3 and 1.4 show how an application is launched through the respective option.
V 1.0 © Aptech Limited
Session
Introduction to Windows Phone 8
Figure 1.3: Launching an Application Through Live Tiles
Concepts
1
Figure 1.4: Launching an Application Through Live Apps
V 1.0 © Aptech Limited
Session
1 Introduction to Windows Phone 8
The launching action calls the Launching event, which in turn opens the UI screen of the selected application. ÎÎ
Closing an Application To completely close an application and remove it from memory, you need to keep pressing the BACK navigation button until it goes beyond the first page of the application. The closing action calls the closing event, which saves some basic changes and exits the application. Note – Remember that only those changes, which would be required throughout the application
lifetime, such as data related to History, will be stored every time the Closing event is called.
1.3.2 Deactivating and Reactivating Applications Once an application is launched, it will be activated and available in the Running state. To move to a different application or operation, you need to deactivate the current application and reactivate it at some other time. ÎÎ
Deactivating an Application To deactivate an application, you can either click the Start button or launch another application from Live Tiles or Live Apps. This navigation action calls the deactivated event, which usually saves the recent changes made in the current session either in the application itself or in a dictionary called the State.
ÎÎ
Reactivating an Application To reactivate an application, you need to navigate to it by clicking its respective icon in Live Tiles or in Live Apps. You could also launch it by using the list of recent applications in the Start screen or by long pressing the BACK button until it reaches the required application. This will bring the application back to its activated state.
Concepts
1.4 Developing and Deploying Windows Phone Apps To develop Windows Phone apps, you need to make use of the tools available under Windows Phone SDK 8. Once you install Windows Phone SDK 8 in your system, you can create apps by using the available tools, such as Visual Studio or Blend for Visual Studio, test the apps in WP Emulator, perform validation by using the testing and validating tools (if required), and finally deploy the app on the Windows Phone device.
V 1.0 © Aptech Limited
Session
1 Introduction to Windows Phone 8
1.4.1 Writing the First Windows Phone 8 ’Hello World’ Application This section describes how to create a simple Windows Phone app by using C# in Visual Studio and Blend for Visual Studio, run it on the WP Emulator, and deploy it on the Windows Phone 8 device. The steps to perform this are as follows: 1.
Creating a ‘Hello World’ Program You can create a Windows Phone app either in Visual Studio or in Blend for Visual Studio. A. Using Visual Studio Express 2012 i.
Click Start and then go to the All Apps screen by clicking the arrow at the bottom of the Start screen. Then, select Windows Phone SDK 8.0 → Microsoft Visual Studio Express 2012 for Windows Phone.
ii.
Click File → New Project as shown in figure 1.5.
Figure 1.5: Opening Screen of Microsoft Visual Studio Express 2012 for Windows Phone 8
V 1.0 © Aptech Limited
Concepts
To create a ‘Hello World’ application using C# in Visual Studio:
Session
1 Introduction to Windows Phone 8 The New Project window appears as shown in figure 1.6.
Figure 1.6: New Project Window iii.
Click Templates and select Windows Phone under Visual C#.
iv.
Type a suitable name for the project in the Name box.
v.
Click OK.
Concepts
The New Windows Phone Application dialog box appears as shown in figure 1.7.
Figure 1.7: New Windows Phone Application Dialog Box vi.
Select Windows Phone OS 8.0 in the Target Windows Phone OS Version drop-down box.
V 1.0 © Aptech Limited
Session
1 Introduction to Windows Phone 8
A new project is created as shown in figure 1.8.
Figure 1.8: Design View of the New Project The design page is displayed with default text on the left side and the code page with its associated Extensible Application Markup Language (XAML) code is displayed right next to the design page. You can also add or modify controls in the Design page, through drag-and-drop action from the Toolbox in Visual Studio. Note – XAML is used to design and define user interfaces for Windows Phone apps. The XAML
code is automatically generated whenever there is any change in the UI. vii. Click the code page to maximize the code window. viii. Press ALT + ENTER to invoke the Properties window.
Rename the text value of the TextBlock control to Welcome in the Properties window.
Concepts
ix.
V 1.0 © Aptech Limited
Session
1 Introduction to Windows Phone 8
Figure 1.9 shows the details of the changes made in the Visual Studio.
Figure 1.9: TextBlock with Modified Value x.
Click Save Project. The app file created in Visual Studio is saved with the .cs extension.
B.
Using Blend for Visual Studio
Concepts
To create a ‘Hello World’ application by using Blend for Visual Studio: i.
Open Blend for Visual Studio.
ii.
Click File → New Project.
V 1.0 © Aptech Limited
Session
1 Introduction to Windows Phone 8
The New Project window appears as shown in figure 1.10.
Figure 1.10: New Project Window in Blend for Visual Studio Enter a suitable name of the project, for example, ‘Hello World’ in the Name box.
iv.
Select 8.0 in the Version box.
v.
Click OK.
Concepts
iii.
V 1.0 © Aptech Limited
Session
1 Introduction to Windows Phone 8
The Design page appears as shown in figure 1.11.
Figure 1.11: Design Page in Blend for Visual Studio vi.
Click Mainpage.xaml in the left panel to invoke the code window.
vii. Press ALT + ENTER to invoke the Properties window.
Concepts
viii. Change the text value of the TextBlock control in the Properties window.
V 1.0 © Aptech Limited
Session
1 Introduction to Windows Phone 8
Figure 1.12 shows the Code View with the changes made.
Figure 1.12: Code View of the Application in Blend for Visual Studio ix. 2.
lick Save Project. The file created in Blend for Visual Studio is saved with the .xaml C extension.
Running a Windows Phone App in Windows Phone Emulator The UI for the ‘Hello World’ application is complete. Next, you need to run the app in the WP Emulator. Running the app implies deploying it on the WP Emulator and viewing its output.
I.
Open the ‘Hello World’ application from either Visual Studio or Blend for Visual Studio.
II.
Select the required Emulator, for example, ‘Emulator WVGA 512 MB’ from the drop-down box under the menu bar as shown in figure 1.13.
V 1.0 © Aptech Limited
Concepts
To run the ‘Hello World’ application:
Session
1 Introduction to Windows Phone 8
Figure 1.13: Emulator Option in Visual Studio
Concepts
The Emulator WVGA 512MB is launched as shown in figure 1.14.
V 1.0 © Aptech Limited
Session
1 Introduction to Windows Phone 8
Concepts
Figure 1.14: Windows Phone Emulator
V 1.0 © Aptech Limited
Session
1
III.
Introduction to Windows Phone 8 Press F5.
The output is displayed in the Emulator as seen in figure 1.15.
Concepts
Figure 1.15: Output of the ‘Hello World’ App You can also deploy or run an application from Blend by using the following steps: 1. Open the required app file. 2. Click Window → Device → Deploy Target → Emulator WVGA (512 MB). 3. Press F5.
V 1.0 © Aptech Limited
Session
1 Introduction to Windows Phone 8
Note – It is highly recommended that you first test and deploy the app in the Emulator before deploying
it on the Windows Phone 8. This will ensure protecting the core mobile operations and other applications installed in Windows Phone from crashing, in case there are any issues with your app. 3.
Deploying the Windows Phone App on the Windows Phone 8 Device
Once the app is completely tested and validated, the final step is to deploy the app in the Windows Phone 8 device. Deployment of the app in Windows Phone 8 includes two steps: Registration
I.
Before deploying the app, you need to register the phone for development. Once the phone is registered, you can perform all app operations, such as installing, debugging, and running the app on the actual Windows Phone 8 device. To register the device, you need to use the Windows Phone Developer Registration Tool available under Windows Phone SDK 8 in your Windows Phone 8 device. For this, you would require Windows Phone SDK 8, a device with Windows Phone 8 Operating System, a Microsoft account, and a unique name for the device. You can invoke this tool in Windows Phone 8 device by performing the following step and completing the registration process: yy II.
Click Start → All apps → Windows Phone SDK 8.0 → Windows Phone Developer registration.
Deployment
Once the phone is registered, you can deploy the app on the device. To deploy the ‘Hello World’ app, you can use the Application Deployment tool. To deploy the Windows Phone app by using the Application Deployment tool: Connect the Phone device with the host computer, which contains the app through the USB cable.
yy
Unlock the Phone screen.
yy
Click Start → All apps → Windows Phone SDK 8.0 → Application Deployment.
Concepts
yy
V 1.0 © Aptech Limited
Session yy
1 Introduction to Windows Phone 8 The Application Deployment dialog box appears as shown in figure 1.16.
Figure 1.16: Application Deployment Dialog Box Select the required device in the Target drop-down box.
yy
Click Browse and select the app file in the host computer that you want deploy.
yy
Click Deploy.
Concepts
yy
V 1.0 © Aptech Limited
Session
1 Introduction to Windows Phone 8
The app is deployed and the Status field will display ‘XAP Deployment Complete’, if there are no errors in the deployment process as shown in figure 1.17.
Figure 1.17: Completion of Deployment Process
Concepts
The output of the ‘Hello World’ app on the Windows Phone device would be similar to the output in WP Emulator that was shown earlier in figure 1.15.
V 1.0 © Aptech Limited
1
Session
Introduction to Windows Phone 8
1.5 Check Your Progress 1.
2.
The name of the User Interface used in Windows Phone 8 is called the _____________ UI. (A)
Metro
(C)
C Modern
(B)
Vista
(D)
D Mobile
Which of these statements is true and which is false? Statement A: Windows Phone 8 uses Windows NT kernel. Statement B: Windows Phone apps developed for Windows 7 can run on Windows 8.
(A) (B) 3.
Statement A is TRUE Statement B is FALSE. Statement A is FALSE Statement B is TRUE.
and and
(C)
Both the statements are TRUE.
(D)
Both the statements are FALSE.
Which feature lets you store music and video in Windows Phone 8? (A)
Media Hub
(C)
Music Hub
(B)
Music+Videos Hub
(D)
Videos Hub
4.
Concepts
5.
What happens if you have accidentally deleted an important document created in Office Hub from the local Windows Phone 8 device? (A)
You cannot retrieve the document at (C) all.
You can retrieve the document from the Microsoft Cloud SkyDrive.
(B)
You can retrieve the document from the ‘Recent Documents’ option in (D) MS Word.
You may be able to retrieve the document by using the ‘Recovery’ utility in Office Hub.
Which of the following hardware specifications satisfy the requirements for Windows Phone 8? a.
180 MB of RAM and 8 GB of flash storage
b.
Start, Search, and Back buttons
c.
Support for Wi-Fi and cellular networks
d.
600 x 480 format display
e.
Front-facing and back-facing camera and compass
V 1.0 © Aptech Limited
Session
6.
7.
8.
1 Introduction to Windows Phone 8
(A)
All the options are suitable for (C) Windows Phone 8.
Except option a, all the other options are suitable for Windows Phone 8.
(B)
Only options b, c, and e are (D) applicable.
Except option d, all the other options are suitable for Windows Phone 8.
To develop Windows Phone apps for Windows Phone 8, you need to have __________ CPU and ________ OS. (A)
32-bit, Windows 7
(C)
32-bit, Windows 8 Pro
(B)
64-bit, Windows Vista
(D)
64-bit, Windows 8
Live Tiles and Live Apps of Windows Phone 8 are part of _________________.
(A)
Windows Phone SDK 8
(C)
Start screen
(B)
People Hub
(D)
Data Sense
Which of these statements is true and which is false? Statement A: You can launch an application by using Live Tiles or Live Apps in Windows Phone 8. Statement B: You can close an application by pressing the BACK button just once in case you are in the opening page of the application.
(A)
Both the statements are TRUE. Both the statements are FALSE.
Concepts
(B)
Statement A is TRUE and Statement (C) B is FALSE. Statement A is FALSE and Statement (D) B is TRUE.
V 1.0 © Aptech Limited
Session 9.
1 Introduction to Windows Phone 8
Match the SDK tool with its associated step under development of Windows Phone apps.
Tool
Windows Phone app Development
(a)
Blend for Visual Studio
1. Prerequisite tool needed for deployment
(b)
Windows Phone Emulator
2.
(c)
Windows Phone Application 3. Designing UI for Windows Phone apps Analysis
(d)
Windows Phone SDK 8
(e)
Windows Phone Developer 5. Testing and debugging Windows Phone apps Registration Tool
(A)
a-3, b-5, c-4, d-2, e-1
(C)
a-5, b-3, c-4, d-1, e-2
(B)
a-3, b-5, c-2, d-4, e-1
(D)
a-5, b-3, c-4, d-2, e-1
Prerequisite tool for developing Windows Phone apps
4. Validating Windows Phone apps
10. Which of the following key combinations is used to invoke the Properties window in Visual Studio? CTRL+ENTER
(C)
ALT+ENTER
(B)
SHIFT+F1
(D)
ALT+F1
Concepts
(A)
V 1.0 © Aptech Limited
Session
1 Introduction to Windows Phone 8
1.5.1 Answers C
2.
A
3.
B
4.
C
5.
B
6.
D
7.
C
8.
C
9.
A
10.
C
Concepts
1.
V 1.0 © Aptech Limited
Session
1 Introduction to Windows Phone 8
Summary Windows Phone 8 is one of the most popular and innovative mobile operating systems offered by Microsoft.
ÎÎ
You can launch an application in Windows Phone 8 through Live Tiles, Live Apps, or even by tapping the respective notification icon on the Start screen.
ÎÎ
To develop Windows Phone apps, Windows Phone 8 provides a development suite called the Software Development Kit (SDK).
ÎÎ
You can create Windows Phone apps in Visual Studio or Blend for Visual Studio.
ÎÎ
You can test, debug, and run Windows Phone apps in Windows Phone Emulator.
ÎÎ
You need to register the device for development before deploying the Windows Phone 8 app through the Windows Phone Developer Registration Tool available under Windows Phone SDK.
ÎÎ
Once your device is registered, you can use any of the following ways to deploy your Windows Phone app on the device - command prompt, Visual Studio, or Application Deployment Tool.
Concepts
ÎÎ
V 1.0 © Aptech Limited
Session - 2 Overview of Windows Phone 8 User Interface Welcome to the Session, Overview of Windows Phone 8 User Interface. In this session, you will learn about the basics of Extensible Application Markup Language (XAML), the various User Interface (UI) elements of Windows Phone 8 and their associated event handlers. You will also learn about resources, styles, and templates in Windows Phone 8. At the end of this session, you will be able to: ÎÎ Describe the use of XAML in Microsoft Platform and Windows Phone 8 ÎÎ Explain layouts in Windows Phone 8 ÎÎ List the various controls in Windows Phone 8 ÎÎ Describe the procedure to create controls in XAML for Windows Phone 8 ÎÎ Describe event handling in Windows Phone 8 ÎÎ Explain a routed event and a user-initiated event in Windows Phone 8 ÎÎ Explain the use of back stack in Windows Phone 8 ÎÎ Describe the purpose of resources, styles, and templates in Windows Phone 8
Session
2 Overview of Windows Phone 8 User Interface
2.1 Designing User Interfaces in Windows Phone 8 The growth of mobile apps, ever since they first came in vogue in the year 2008 as features of Apple’s iPhone -has been spectacular. Today, apps are no longer restricted to the iPhone, but are also available on various other platforms as well. There are a huge number of mobile apps that are being downloaded and used by people all over the world. Despite the large repository of mobile apps available to the consumers, only some of them are globally popular and most extensively used in the consumer world, namely social networking apps, such as Facebook and Twitter, Skype, MSN Messenger, and Google Maps. These apps have been successful because of their novelty, convenience, powerful UI, and excellent functionality. To aid in developing such apps that truly stand out from the rest of the crowd, Windows Phone 8 provides a range of tools and features. To enable developers to design powerful UI for Windows Phone apps, Windows Phone 8 provides various Graphical User Interface (GUI) elements, such as layouts, controls, utilities, and many other resources. Microsoft also offers a markup language called XAML to aid in the creation of visual interfaces for Windows Phone apps.
2.1.1 Brief Overview of XAML XAML is a markup language available as part of Microsoft Windows Presentation Foundation (WPF) in Microsoft .NET framework. The functionality of XAML in .NET framework is akin to the functionality of HTML and XML in Web applications. Note – WPF is a rich GUI-based programming model, which is used to create powerful standalone
applications as well as browser-based applications on the Microsoft platform.
XAML is the default language used in Windows Phone 8 for UI creation. It is also the primary language for applications created in Microsoft Blend for Visual Studio, which is a rich IDE. With XAML, you can define the UI for your apps and include basic coding on the functionality of the various UI controls through the use of namespaces, objects, and properties. A brief explanation of each of these terminologies is included here. ÎÎ
Namespace: A namespace is a type definition for the elements in XAML. You can either use the pre-defined collection of namespaces or create your own namespaces for your project. For example, there is a pre-defined namespace called Systems.Windows.Controls, which you can use to create UI control objects in Windows Phone 8.
using the xmlns tag in XAML. There are a huge number of pre-defined namespaces available as part of Windows Phone libraries as well as XAML.
In case you want to use XAML namespaces, you need to use a prefix, such as x: along with the xmlns tag, as follows: xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
V 1.0 © Aptech Limited
Concepts
Note – To use a pre-defined namespace for your app project, you need to declare that namespace
Session
2 Overview of Windows Phone 8 User Interface
In case you want to use namespaces from Windows.Phone assembly, you can directly call them using the xmlns tag, as follows: xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation” ÎÎ
Object: An object is a programmatic representation of a UI control in Windows Phone 8. For example, there are objects, such as Button and TextBox, which you can use to create UI controls in Windows Phone 8.
ÎÎ
Property: A property is an attribute or an element associated with an object. For example, the properties for a Button object include height and width.
Note – You can also import .NET libraries (reusable components) and their associated (Application
Programming Interfaces (APIs) in XAML and use them for providing functionality in Windows Phone 8.
Code Snippet 1 shows the default XAML program generated for a new Windows Phone project named PhoneDemoApp. Code Snippet 1:
V 1.0 © Aptech Limited
Session
2 Overview of Windows Phone 8 User Interface
Code Snippet 1 shows the creation of a default namespace, which contains the same name as that of a new project. It also contains the creation of a class definition called PhoneDemoAppClass.MainPage. Inside the class definition, the list of pre-defined namespaces to be used for this project is declared using the xmlns tag. The default font, orientation, and foreground specifications to be used for the project are declared after the namespace declaration. Finally, the UI screen with the container objects, Grid and StackPanel, and a default title TextBlock object for the page, along with their properties, are created for the project. Note – You can also integrate XAML with various tools and languages in .NET framework. For example,
you could create a UI in XAML and code its functionality in Visual C-#.NET, VB.NET, VC++.NET, and so on. XAML is thus a first of its kind markup language of Microsoft, which provides an independent UI layer that can be adapted in all .NET applications.
2.1.2 Basics of UI Design
For example, look at the images shown in figures 2.1 and 2.2 respectively. Both the images show the opening screen of an application. All the functionalities related to the application are similar in both the images. However, as you can see, the UI available in the second image is much more appealing than the UI in the first image. This is because of a better organization and presentation of UI elements with more relevant details and functionality, to enable easier user interaction.
V 1.0 © Aptech Limited
Concepts
Before starting with the development of Windows Phone apps by using XAML, you need to get familiarized with how to organize the content in Windows Phone 8.
Session
2 Overview of Windows Phone 8 User Interface
Concepts
Figure 2.1: Sample UI Screen – I
Figure 2.2: Sample UI Screen – II
V 1.0 © Aptech Limited
Session
2 Overview of Windows Phone 8 User Interface
UI Design Guidelines To create an effective design for your Windows Phone Apps, you need to follow a few basic design guidelines: ÎÎ
Simplistic Design The UI should be simple in terms of usage of language and organization of content with adequate spacing in between the UI elements.
ÎÎ
Consistency The UI should be based on the same set of standards as that of the other Windows Phone Apps in terms of background, font, color, image, and icon, installed in Windows Phone 8 for consistency of appearance.
ÎÎ
Minimum Typing Effort The design of the UI should be such that it minimizes the typing effort of the users.
ÎÎ
Attention to Detail The UI should accommodate even the minute detail, which a user might require while using the app.
ÎÎ
Signature Presentation With the UI’s presentation of title, format, and style of language, the users should be able to understand the purpose of the app and thus, relate with its context.
ÎÎ
Support for Global Audience The UI should provide a common platform for use by a global audience, through careful presentation of language that does not have any regional references.
Note – Before creating your own apps for Windows Phone 8, you could glance through the existing
collection of apps in the Windows Phone store. These apps will give you a fair idea about the various aspects involved in creating apps.
Designing an app in Windows Phone 8 involves creating various controls and elements on the app screen to facilitate user interaction. Before creating controls in your app, you need to first determine the process of organizing the UI elements on the Windows Phone 8 screen. All the UI elements in an app should be positioned based on the screen size and the screen resolution of the Windows Phone 8 screen.
V 1.0 © Aptech Limited
Concepts
Basics of UI Organization - Layout
Session
2 Overview of Windows Phone 8 User Interface
To enable such appropriate positioning and sizing of UI elements, Windows Phone 8 provides layouts. In a layout, you can organize the UI elements in a hierarchical manner by including container controls, such as Panel controls, and the main controls that interact with the user, such as Button and Textbox, under the container controls. Windows Phone 8 offers two types of layouts, namely Absolute layout and Dynamic layout. ÎÎ
Absolute Layout In an Absolute Layout, you need to provide the exact positioning of various UI controls through X and Y coordinates. In this mode, the controls will be held in a fixed position on a Windows Phone 8 screen.
ÎÎ
Dynamic Layout In a dynamic layout, you need to provide the relative positioning of various UI controls on a Windows Phone 8 screen. In this mode, the controls in the UI will be automatically adjusted according to the varied screen resolutions available in Windows Phone 8.
2.2 Different Controls in Windows Phone 8 Controls are the main UI elements of an app, which enable app developers to display information to the users and also accept inputs from them. Windows Phone 8 provides a wide collection of controls to enable the developers to design a powerful GUI.
2.2.1 Basic Controls in Windows Phone 8 Some of the important controls provided by Windows Phone 8 for app design are as follows: ÎÎ
Navigation Controls Any app that contains multiple pages should provide for page navigation as one of its core functionalities. To provide for navigation between pages, the app to be designed should follow a hierarchical organization as follows – frame, page, and content.
Concepts
A frame is the main container of the app, which in turn will contain a set of pages. Each page will in turn have a layout with parent containers and other UI controls.
V 1.0 © Aptech Limited
Session
2 Overview of Windows Phone 8 User Interface
Figure 2.3 shows a Windows Phone 8 screen with all these three Navigation controls.
Figure 2.3: Example of a Windows Phone 8 App with Navigation Controls By default, whenever you create a UI control in XAML, a frame and a page are created automatically. The frame is the first object to be loaded in any XAML-based project. It occupies the entire Windows Phone 8 screen. For example, Code Snippet 1 that was discussed earlier contains the default creation of frame and page for a project. As the frame object is the top-most parent container, there is no explicit declaration of the same in a XAML program. The page object is created under the frame, which occupies the entire frame area. For example, PhoneDemoAppClass.MainPage is the default page created in the default XAML program, as shown in Code Snippet 1. However, if you still want to customize the creation of frame and page controls, you need to make use of the classes called PhoneApplicationFrame and PhoneApplicationPage, which are part of Microsoft.Phone assembly. ÎÎ
Layout and Grouping Controls Controls that serve as containers for other controls are called Layout and grouping controls. These controls are the first to be included while designing the page of an app. Some of the important controls under layout and grouping controls include the following: A Grid provides a layout in rows and columns. You can specify the accurate positioning of each child element in the Grid through its row and column coordinates. It is one of the most flexible controls in Windows Phone 8, which enables the developers to arrange child objects in varied formats across multiple rows and columns.
V 1.0 © Aptech Limited
Concepts
Grid
yy
Session
2 Overview of Windows Phone 8 User Interface Code Snippet 2 shows a partial program that contains the creation of a Grid control in XAML. Code Snippet 2:
Concepts
Figure 2.4 shows a Windows Phone 8 screen, which contains the Grid control in Grey background.
Figure 2.4: Example of a Windows Phone 8 App with Grid Control
V 1.0 © Aptech Limited
Session
2 Overview of Windows Phone 8 User Interface
Canvas
yy
A Canvas is used to specify the accurate positioning of a child element with X and Y coordinates. This container is especially useful for those child elements, which should remain fixed in the same position in the UI irrespective of the screen resolution and format. Code Snippet 3 shows a partial program that contains the creation of a Canvas control in XAML. Code Snippet 3: Figure 2.5 shows a Windows Phone 8 screen, which contains the Canvas control in a Grid.
Figure 2.5: Example of a Windows Phone 8 App with Canvas Control A StackPanel is typically used in situations where the child elements are to be organized horizontally or vertically in a single line. By default, in a StackPanel, the child elements are organized vertically. You can use the Orientation property in XAML code to change the arrangement of elements to horizontal. Code Snippet 4 shows a partial program that contains the creation of a StackPanel control in XAML. The StackPanel contains a TextBlock control to display text with a particular style. A style is a property used to customize the appearance of a control in a
V 1.0 © Aptech Limited
Concepts
StackPanel
yy
Session
2 Overview of Windows Phone 8 User Interface XAML. You can use standard styles as well as customized styles for a UI control. Code Snippet 4: Figure 2.6 shows a Windows Phone 8 screen, which contains the StackPanel control.
Figure 2.6: Example of a Windows Phone 8 App with StackPanel Control
Concepts
yy
Panorama
A Panorama control is used whenever the width of the screen spans across multiple pages and cannot be viewed in a single physical screen. This control provides a lengthy horizontal area in which you can create other container controls and child controls. As and when the user swipes the screen horizontally, the Panorama control displays the specific portion of the screen according to the visible screen area of the mobile device. Generally, a hint on the continuity of the details on the next part of the screen is displayed through one or two alphabets or words of the next section, in the current display screen
V 1.0 © Aptech Limited
Session
2 Overview of Windows Phone 8 User Interface
itself, to the user. Code Snippet 5 shows a partial program that contains the creation of a Panorama control in XAML. Code Snippet 5:
Concepts
V 1.0 © Aptech Limited
Session
2 Overview of Windows Phone 8 User Interface Figure 2.7 shows a Windows Phone 8 screen, which contains the Panorama control.
Figure 2.7: Example of a Windows Phone 8 App with Panorama Control yy
Pivot
A Pivot control serves as a replacement of tabs in Windows Phone 8. It is used in scenarios where an application needs to provide sub screens or sub sections, as multiple views or multiple pages in an app. This control presents information in parts to the user, thus enabling smoother navigation of content view as well as page view. By default, in a Pivot control, the navigation to the next page or content occurs whenever the user performs the following actions – tapping, dragging, swiping, or scrolling on the large data. Code Snippet 6 shows a partial program that contains the creation of a Pivot control in XAML.
Concepts
Code Snippet 6:
V 1.0 © Aptech Limited
Session
2 Overview of Windows Phone 8 User Interface
Figure 2.8: Windows Phone 8 App Showing a Pivot Control
V 1.0 © Aptech Limited
Concepts
Figure 2.8 shows two Windows Phone 8 screens, which depict the Pivot control. In these screens, the Pivot control contains two items, item1 and item2, which are similar to tabs. The first screen shows the part of the page with the contents of item1 visible. The second screen shows the part of the page with the contents of item2 visible.
2
Session
Overview of Windows Phone 8 User Interface
Note – Panorama and Pivot controls are similar in their approach of displaying scrollable information
to the users. However, the difference lies in the purpose of these two controls.
You can use the Panorama control whenever you need to provide different sections of an app on the same topic or heading in a single screen. For example, you can create a Panorama control in an app that provides information on the list of services offered by an organization, such as Software services, Hardware services, BPO services, and so on. All these sections can be displayed as part of a single screen itself and the user can navigate to each section by swiping to the next section horizontally. You use Pivot control whenever you need to create content in the form of sub sections. For example, you can create a Pivot control for calendar applications with different views to provide data to the users. ÎÎ
Text Controls You can use Text controls to either display information to the users or get inputs from the users in a string format. There are three types of Text controls, namely: yy
TextBlock: This control is used to display static information to the users.
yy
TextBox: This control is used to get both smaller as well as larger amounts of textual
yy
PasswordBox: This control is used to get password inputs from the users. The characters
information from the users.
that the user enters are displayed in the form of a bullet character (default) to promote confidentiality.
Code Snippet 7 shows a partial program that contains the creation of Text controls in XAML. Code Snippet 7:
Concepts
Figure 2.9 shows a Windows Phone 8 screen, which contains all the three Text controls.
V 1.0 © Aptech Limited
Session
2 Overview of Windows Phone 8 User Interface
Figure 2.9: Example of a Windows Phone 8 App with Text Controls ÎÎ
List Controls You can use List controls to display a list of options to the users and enable them to select a single option or even multiple options. There are two types of List controls, namely: yy
ListBox: This control is used to display a small list of options from which the user can
yy
LongListSelector: It is used to display information in the form of large list(s) to the
select by clicking the required option(s).
users, as in the case of an address book. This control enables the users to either scroll through the list of options or directly navigate to a specific option through the use of index or search criteria.
Code Snippet 8 shows a partial program that contains the creation of List controls in XAML.
V 1.0 © Aptech Limited
Concepts
Code Snippet 8:
Session
2 Overview of Windows Phone 8 User Interface
Concepts
Figure 2.10 shows a Windows Phone 8 app, which contains the List controls.
V 1.0 © Aptech Limited
Session
2 Overview of Windows Phone 8 User Interface
Figure 2.10: Example of Windows Phone 8 App with List Controls ÎÎ
Button and Selection Controls You can use Button and selection controls to enable the user to quickly select or specify options on the screen, instead of typing.
Concepts
Table 2.1 provides a brief explanation of some of the important controls available under Button and selection controls.
V 1.0 © Aptech Limited
Session
2 Overview of Windows Phone 8 User Interface
Button and Selection Control Button
CheckBox
RadioButton
Slider
HyperlinkButton
Purpose
Sample Image
A Button control is used when the user submits the details to the app or proceeds to a different part of the app by performing a Click action. A CheckBox control is used to provide two states to the user – an option select state or an option clear state. A RadioButton control provides a group of options to the user under a common heading. The user would be allowed to select only a single option from the group of options. A Slider control enables to the user to select a value from the range of values displayed in a bar. The selected value indicates a proportion of the given range in the Slider. A HyperlinkButton control is used whenever the user needs to navigate to either a different page in the same app, or a Web page in the same app, or an external Web link outside the current app.
Table 2.1: Important Controls under Button and Selection Controls Code Snippet 9 shows a partial program that contains the creation of Button and selection controls in XAML. Code Snippet 9:
Concepts
2.2.2 Creating a UI in Windows Phone 8 Using XAML Once you plan your design for the UI of the app, you can create the UI in XAML by using Visual Studio or Blend for Visual Studio. There are two ways to create a UI in XAML: ÎÎ
Drag the required UI controls to the Design view and the XAML code will be automatically generated in the Code view of Mainpage.xaml in Visual Studio or Blend for Visual Studio. (Or) Directly create the code in the Code view of Mainpage.xaml file in Visual Studio or Blend for Visual Studio. This approach is more time-consuming and complex.
The complete step-by-step procedure to create a single UI control and attach some specific attributes to it in Blend for Visual Studio is as follows: To create a button control: 1.
Open Blend for Visual Studio.
2.
Click File → New Project.
3.
Enter a suitable name of the project in the Name box.
V 1.0 © Aptech Limited
Concepts
ÎÎ
Session
2 Overview of Windows Phone 8 User Interface
4.
Select 8.0 in the Version box. Click OK.
5.
The Design page of the project is displayed.
6.
Click the option, Mainpage.xaml in the left side of the window to invoke the Code window.
7.
Click Assets → Controls → Button. Figure 2.11 shows the Assets tab and its associated options in Blend for Visual Studio.
Figure 2.11: Assets Tab in Blend for Visual Studio 8.
Drag the Button control to the Design window in Blend for Visual Studio.
9.
Change the Content property of the Button to ’Click me’.
Concepts
10. Set the background of the Button by using the Background property given in the Properties window. For example, you can type the value, #FFBF7A7A to set the background to Reddish-brown.
V 1.0 © Aptech Limited
Session
2 Overview of Windows Phone 8 User Interface
The Button control is created in the new project in Blend for Visual Studio as shown in figure 2.12.
Figure 2.12: Adding a Button Control in Blend for Visual Studio
Concepts
You can repeat this procedure to create various UI controls by using their associated UI objects, to design the complete UI for your app. A sample UI designed using XAML is displayed for your reference in figure 2.13.
V 1.0 © Aptech Limited
Session
2 Overview of Windows Phone 8 User Interface
Figure 2.13: A Sample Windows Phone App UI Code Snippet 10 shows a partial XAML program that contains the creation of a UI given in figure 2.13. Code Snippet 10:
Concepts
V 1.0 © Aptech Limited
Session
2 Overview of Windows Phone 8 User Interface
V 1.0 © Aptech Limited
Concepts
Session
2 Overview of Windows Phone 8 User Interface
2.3 Event Handling in Windows Phone 8 Once you create the UI controls in XAML, the next step is to create their associated functionality for enabling user interaction. To code the functionality for UI controls, you need to capture their associated events and provide event handlers. An event is an action that is generated on the UI control by any of the following - user, app, system, or even another event or UI control. For example, in a Button control, the user generates a Click event. An event handler is a method that contains the functionality for handling the event. For example, btnOK. Click can be the event handler to handle the functionality of the Click event of a button named btnOK. The event handler code will be written using C#. The following sections explore the two categories associated with events namely, routed events and user-initiated events.
2.3.1 Routed Events As you already know, the UI controls in Windows Phone 8 are organized in a hierarchical manner in frames, pages, and container controls. When an event is triggered on an UI control, it gets routed through various levels of its parent containers till it reaches the frame, which is the main or the root page. Such an action is termed as a Bubbling effect in event handling. For example, if an app contains a form with a Button, the event triggered on the Button control, such as a Click event, will travel from the Button through its parent containers up to its root UI container. Such events that are routed right from the child UI control to the main parent UI are called Routed events. Routed events are associated with most of the controls that provide user interaction and input, such as a TextBox and a ListBox.
Concepts
Some of the important events associated with routed events are as follows: ÎÎ
Click
ÎÎ
KeyDown
ÎÎ
KeyUp
ÎÎ
MouseLeftButtonDown
ÎÎ
MouseLeftButtonUp
ÎÎ
MouseMove
Note – XAML code presents the hierarchical list of objects in an object tree, which in turn maps to the
physical UI controls available as part of any Windows Phone 8 app.
V 1.0 © Aptech Limited
Session
2 Overview of Windows Phone 8 User Interface
Figure 2.14 shows a demonstration of the functionality of a routed event.
Figure 2.14: An Example of a Routed Event Code Snippet 11 demonstrates a routed event handler for the btnOK’s Click event. The purpose of this event handler is to display the text ‘Welcome to routed event handling’ when the Button control is clicked. Notice that the parameter System.Windows.RoutedEventArgs is used to denote the routed event on this control. Code Snippet 11: private void btnOK_Click(object sender, System.Windows.RoutedEventArgs e) MessageBox.Show(“Welcome to routed event handling”); }
2.3.2 User-initiated Events User-initiated events refer to all those events that are triggered by the user either on the app or outside it. For example, a KeyDown event on a TextBox control in an app needs to be captured and handled in
V 1.0 © Aptech Limited
Concepts
{
Session
2 Overview of Windows Phone 8 User Interface
the event handler code of the app. Such user-initiated events may in turn call routed events, when called within an app. Some user-initiated events may be triggered outside the current active app. For example, the user might use a MouseLeftButtonUp event on the Start menu outside the app screen. In such a case, the current app should hand over the control to the main Windows Phone 8 screen, which in turn, should handle that event. Note – Some user-initiated events may even be forced by the system. For example, while using the
app, there is a possibility that the user may be forced to attend an incoming call, which will temporarily generate a LostFocus event on the app.
Concepts
Figure 2.15 shows a demonstration of the functionality of a user-initiated event.
Figure 2.15: An Example of a User-initiated Event
V 1.0 © Aptech Limited
Session
2 Overview of Windows Phone 8 User Interface
Thus, as an app developer, you need to plan for all the possible events that could be triggered on an app and accordingly handle them or pass them on to the parent window. Code Snippet 12 demonstrates a user-initiated event handler for the btnOK’s Hold event. The purpose of this event handler is to display the text ‘Welcome to user-initiated event handing’ on the Hold event of the Button control. Notice that the parameter System.Windows.Input.GestureEventArgs is used to denote the user-initiated event on this control. Note – A Click event is a compound event that includes the events, MouseButtonUp and
MouseButtonDown. Thus, this event consists of both the pressing event and the releasing event.
A Hold event is an event that is generated when the user long-presses the UI control for some time before releasing it. Code Snippet 12: private void btnOK_Hold(object GestureEventArgs e) { }
sender,
System.Windows.Input.
MessageBox.Show(“Welcome to user-initiated event handling”);
The following are the two external events need to be compulsorily handled in user-initiated events: ÎÎ
When the user navigates to a Web page using a HyperlinkButton control (Or)
ÎÎ
When the user accesses the Windows Phone Clipboard API for performing edit operations, in the app
In case of such events, the app developer should initiate API calls immediately or within a maximum of one second in the event handler code, failing which there will be loss of functionality of the app operation.
2.3.3 Creating Event Handlers in Windows Phone 8
To create the event handlers for the Button control: 1.
Open the required project that contains the Button control.
2.
Open the Properties window.
3.
In the Event section of the Properties window, type the required name of the event handler, for example, btnOK _ Click in the Click box, for routed event.
V 1.0 © Aptech Limited
Concepts
You can create an event handler in XAML by manually typing the code in the .xaml.cs file or by selecting the required event under the Event section in the Properties window of Blend for Visual Studio or in Visual Studio.
Session 4.
2 Overview of Windows Phone 8 User Interface
Similarly, type the required name of the event handler, for example, btnOK _ Hold in the Hold box, for user-initiated event.
Figure 2.16 shows the names of the events in the Properties window.
Figure 2.16: Creating an Event Handler in Blend for Visual Studio To type the code for these two event handlers, double-click the name of each event handler.
Concepts
5.
V 1.0 © Aptech Limited
Session
2 Overview of Windows Phone 8 User Interface
The event handlers are auto-generated in the Code page (.xaml.cs page) as shown in figure 2.17.
Figure 2.17: Event Handling Code for the Button Control Type the required code in each event handler. For example, you can type the code shown earlier in Code Snippet 11 and Code Snippet 12.
7.
Press F5.
Concepts
6.
V 1.0 © Aptech Limited
Session
2 Overview of Windows Phone 8 User Interface
The project will be executed with the Button control and will display two message boxes depending on the event initiated on the control, as shown in figure 2.18.
Figure 2.18: Sample Output of Events Generated on the Button Control
Concepts
Once you create an event handler in C#, you can also attach or bind it to its associated object in XAML. You can bind an event handler to its associated object in XAML code through the following steps: 1.
Type the name of the event in the object tag right next to its Name attribute. When you start typing the name of the event, the list of available events for that object is displayed in an IntelliSense window.
2.
Select the required event to be handled and double-click the name of the event. The associated event handler with the default name of the event appears in the IntelliSense window.
3.
Select the default event handler or type a new name for the event handler. This will bind the event to its associated event handler.
V 1.0 © Aptech Limited
Session
2 Overview of Windows Phone 8 User Interface
Note – An IntelliSense window is a context-sensitive drop-down menu that appears whenever the
developer types the first few letters of keywords in XAML or C# Code page.
Code Snippet 13 demonstrates a Button control with its event bound with the respective event handler. Notice that the second parameter contains the event handler as an attribute of the Button object. Code Snippet 13:
2.3.4 Navigation Navigation is one of the important functionalities required for any app operation. There are three ways of navigation available in Windows Phone 8, namely, navigation between pages, navigation within a page, and navigation outside the current app. ÎÎ
Navigation between pages As you are already aware, an app contains three levels of navigation – frame, page, and content. The frame is the root container of the app. It maintains the pages of the app, application bar, and status bar. It provides navigation between pages of the app for the user.
ÎÎ
Navigation within a page Navigation within a page is achieved through the container UI elements, such as Panorama and Pivot, which provide information to the users in scrollable form.
ÎÎ
Navigation outside the current app To provide for navigation to external apps, you can use the UI control HyperlinkButton in the current app. There is also another control namely the WebBrowser control, which you can use, to display HTML content in the current app.
Note – A WebBrowser control is a HTML control available under Windows.Phone.Controls
2.3.5 Navigation History or Back Stack When you create an app that runs for multiple pages in Windows Phone 8, you need to provide navigation events, such as Back, Front, and Home to the users. To enable the users to navigate backward and forward in the app, Windows Phone 8 provides a structure known as a back stack, also called a stack. The stack stores the pages of the app, one below the other, in sequential order. When the user navigates forward, the new page is stored on the top of the stack and the already existing current page is pushed to the last but one page.
V 1.0 © Aptech Limited
Concepts
assembly. You can use this control to display both static as well as dynamic Web content in an app.
Session
2 Overview of Windows Phone 8 User Interface
When the user moves back from the current page, the current page is removed from the stack and the page on top of the stack (previous page of the app) is displayed to the user. Adding a page to the stack by way of navigating to it is called the push operation and removing a page from the stack by way of moving back is called the pop operation. Figure 2.19 shows the demonstration on the functionality of the stack.
Figure 2.19: Sample Stack Structure
2.4 Styles, Resources, and Templates Windows Phone 8 provides an array of options for app development to create standard functionalities that can be used in an app or across a range of apps to maintain uniformity and convenience. The most important of these options are as follows:
Concepts
ÎÎ
Styles You can create controls in UI that follow your customized specifications, such as margin, height, and color. For example, you may want to create a ListBox that should always follow a standard format of size and color. To create such custom specifications for your UI controls, you can use styles in Windows Phone 8.
V 1.0 © Aptech Limited
Session
2 Overview of Windows Phone 8 User Interface
Code Snippet 14 shows a partial program that contains the creation of a style in XAML. Code Snippet 14:
Code Snippet 14 shows the creation of ListBox style with some customized property settings, such as background, foreground, vertical scrollbar, and horizontal scrollbar. The name of the style is set using the x:Key property, the UI control that needs to be customized is set using the TargetType property, and the customized property settings for the control is specified using Setter Property. To reuse styles across all your applications, you need to embed them into a resource. ÎÎ
Resources You can create resources in Windows Phone 8, which will serve as a common dictionary for a range of app operations. Each resource can contain a collection of classes, styles, and properties, which can be reused in multiple applications. Code Snippet 15 shows a partial program that contains the creation of a resource with the ListBox style discussed in Code Snippet 14, inside a Grid control.
V 1.0 © Aptech Limited
Concepts
Code Snippet 15:
Session
2 Overview of Windows Phone 8 User Interface
Once you create a resource with the required specifications, you can reuse the resource and its associated style by using its name directly in the current application, as shown in Code Snippet 16. Code Snippet 16:
Concepts
Code Snippet 16 shows the creation of two identical ListBox controls adapted from the style property created in the resource. Figure 2.20 shows two list boxes, which follow the same style with some sample data.
V 1.0 © Aptech Limited
Session
2 Overview of Windows Phone 8 User Interface
Figure 2.20: Sample List Boxes Notice that creating a resource enables reusability of functionality in various scenarios. Thus, you can pre-determine the number of controls, color, size of the controls, and other common text as part of a resource and reuse it in all the apps that follow the same pattern. For example, if you are creating apps for displaying marks of the students in schools and colleges, you can create a common resource and only change the relevant details in each app. Note – If you want to use the resource for the entire app, you need to include the code for the resource
ÎÎ
Templates Template is yet another XAML tool, which you can use to create sophisticated custom specifications for UI controls. In fact, templates provide much more customization features than a style. With the use of templates, you can create UI controls with customized shapes and properties. For example, you can create a TextBox control with an oval-shaped border instead of the regular rectangular settings.
V 1.0 © Aptech Limited
Concepts
in the main application in App.xaml code page. To use the resource for a particular page, you need to include the code in the respective page. To use the resource for a particular UI control, you need to include the code in the respective UI control. Thus, the scope of using the resource is determined based on where it is created in an application.
Session
2 Overview of Windows Phone 8 User Interface
There are two categories of templates namely, ControlTemplate and DataTemplate. Using ControlTemplate, you can create UI controls based on customized properties that are related to appearance. However, the behavior or the functionality of the controls will not be affected by the ControlTemplate settings. Using DataTemplate, you can create UI controls with customized display of content. Code Snippet 17 shows a partial program that contains the creation of a template with a Button control in oval along with a customized background color and size. Code Snippet 17:
Concepts
V 1.0 © Aptech Limited
Session
2 Overview of Windows Phone 8 User Interface
Figure 2.21 shows the Button control with an oval border applied using the template as given in Code Snippet 17.
Concepts
Figure 2.21: Customized Button Control
V 1.0 © Aptech Limited
Session
2 Overview of Windows Phone 8 User Interface
2.5 Check Your Progress 1.
2.
The first step in creating the UI for an app is to determine the __________ for the app screen. (A)
controls
(C)
layout
(B)
navigation
(D)
page design
Which of these statements is true and which is false? Statement A: To create a UI control in Windows Phone, you need to make use of its associated object in XAML. Statement B: It is not possible to create custom-defined namespaces in XAML.
3.
4.
(A)
Statement A is TRUE and Statement B is FALSE.
(C)
Both the statements are TRUE.
(B)
Statement A is FALSE and Statement B is TRUE.
(D)
Both the statements are FALSE.
Which of the following order provides the correct hierarchy of UI organization in Windows Phone 8? (A)
Layout, page, content
(C)
Frame, layout, content
(B)
Frame, layout, page, content
(D)
Frame, page, layout, content
Match the UI control with its associated scenario in app for Windows Phone 8.
Concepts
Control
Example Scenario in app
Canvas
To get input from the user on whether he/she requires the Word Wrap feature or not, for the textual content
Panorama
To display four choices of exercise equipment to the user
LongListSelector
To display a set of photographs in a gallery based on various categories to the user
List Box
To display a large set of lengthy addresses to the user
CheckBox
To display a ‘captcha’ box to prevent entry of virus programs in the app, in the bottom-right corner, at a fixed location to the user
(A) a-5, b-3, c-4, d-1, e-2
(C)
a-3, b-5, c-2, d-4, e-1
(B) a-5, b-3, c-4, d-2, e-1
(D)
a-5, b-3, c-4, d-2, e-1
V 1.0 © Aptech Limited
Session 5.
2 Overview of Windows Phone 8 User Interface
Which of these statements is true and which is false? Statement A: Routed events are not user-initiated events. Statement B: User-initiated events that occur outside the current app cannot be handled by the app. Statement A is TRUE and (C) Statement B is FALSE. Statement A is FALSE and (B) (D) Statement B is TRUE. (A)
6.
7.
Both the statements are TRUE. Both the statements are FALSE.
Which of the following contains the navigation history in Windows Phone 8? (A)
Back button
(C)
Stack
(B)
Navigator
(D)
Forward button
Which of these statements is true and which is false? Statement A: You can use a resource in Windows Phone 8 to create a dictionary of custom values for an object to be used in all your apps. Statement B: You can apply a style to all the radio buttons in your app to follow a common pattern of color and size. (A) Statement A is TRUE and Statement B is FALSE. (B) Statement A is FALSE and Statement B is TRUE.
(D)
Both the statements are FALSE.
Which one of the following code snippets should be used in XAML to create a textbox control that displays the text ‘My First Sample Application’ with a specific margin value and a background color? (A) (B) (C) (D)
Both the statements are TRUE.
V 1.0 © Aptech Limited
Concepts
8.
(C)
Session
2 Overview of Windows Phone 8 User Interface
2.5.1 Answers C
2.
A
3.
D
4.
B
5.
B
6.
C
7.
C
8.
B
Concepts
1.
V 1.0 © Aptech Limited
Session
2 Overview of Windows Phone 8 User Interface
Summary XAML is the default language used in Windows Phone 8 for UI creation. It is also the primary language for applications created in Blend for Visual Studio.
ÎÎ
Designing an app in Windows Phone 8 involves creating various controls and elements on the app screen to facilitate user interaction.
ÎÎ
Windows Phone 8 provides layouts to enable appropriate positioning and sizing of UI elements in an app.
ÎÎ
Windows Phone 8 provides a wide collection of controls to enable the developers to design a powerful GUI.
ÎÎ
Some of the important controls available in Windows Phone 8 are Navigation controls, Layout and grouping controls, Text controls, List controls, and Button and selection controls.
ÎÎ
You need to define event handlers in your code to contain the functionality for the events associated with each UI control. There are two categories of event handlers namely, routed events and user-initiated events.
ÎÎ
Windows Phone 8 provides resources, styles, and templates to create standard functionalities that can be used in apps or across a range of apps, to maintain uniformity and convenience.
Concepts
ÎÎ
V 1.0 © Aptech Limited
Session - 3 Working with Windows Phone 8 Welcome to the Session, Working with Windows Phone 8. In this session, you will learn about creating sophisticated Windows Phone 8 apps by using some of the advanced UI controls, objects, and visual elements of Windows Phone 8. At the end of this session, you will be able to: ÎÎ Describe the procedure to create images and shapes in Windows Phone 8 ÎÎ Explain the various categories of the Brush object ÎÎ Describe the procedure to use Brushes to paint an app area ÎÎ Describe the procedure to create text in different fonts ÎÎ Describe the procedure to set themes for an app ÎÎ Describe the procedure to animate an app ÎÎ Describe the procedure to create a tilt effect on a UI control ÎÎ Explain the purpose of an App Bar ÎÎ Describe the procedure to create an App Bar in XAML ÎÎ Explain the purpose of a Web Browser control ÎÎ Describe the procedure to create a Web Browser control ÎÎ Explain the concept of data binding ÎÎ Describe the procedure to bind a UI control to data
Session
3 Working with Windows Phone 8
3.1 Advanced Elements and Controls in Windows Phone 8 Windows Phone 8 offers an array of options in the form of advanced UI controls, tools, and utilities to provide sophisticated app development for the end-users. For example, consider the following scenario: ÎÎ
A business executive, who is successful in his business of selling a variety of products for home needs, wants to cater to a wide range of customers by introducing mobile shopping. He requires a mobile app with the following features: yy
The Home page should display a gallery of recent products with thumbnail images in a colorful background.
yy
It should contain an attractive display of text and images with animation effects.
yy
It should display custom-effects on the items that provide user-interaction to the user, such as when the user selects a particular item from the gallery the item should be enlarged a bit with a visible motion effect instead of providing a regular click effect.
yy
It should provide user-friendly display of messages to the user from time-to-time whenever the user performs a selection of any item from the app page.
yy
The app should provide smooth navigation facility to the users to and from the Home page to other parts of the app.
yy
It should also display relevant news and articles on the current list of products from other Web sites at the right corner of the Home page.
To create a mobile app with such functionalities, Windows Phone 8 provides UI controls and objects, such as Images, Brushes, Shapes, Web Browser, App Bar, and so on. It also provides various themes, animations, and control tilt effects to aid in visually stunning UI development.
3.2 Creating a UI with Attractive Visual Elements Once you create the basic UI for an app, you need to concentrate on the ways to make it visually appealing for the end-users. Windows Phone 8 provides various options to enhance the appearance of an app.
3.2.1 Images for Windows Phone 8
Concepts
You can add images, such as pictures, charts, diagrams, and logos to provide an attractive visual interface for the Windows Phone 8 apps. To include images, you can use the Image control available in Windows Phone 8. Note – Windows Phone 8 supports most of the common image file formats, such as Joint Photographic
Experts Group (JPEG), Graphic Interchange Format (GIF), and Portable Network Graphics (PNG).
The Image control in XAML is used to display the required image in Windows Phone 8 from the source location. You can specify either a Uniform Resource Locator (URL) that contains the image online or the path of the image in the local hard disk, by using the Source property in the Image control.
V 1.0 © Aptech Limited
Session
3 Working with Windows Phone 8
You can also customize the appearance of the image in Windows Phone 8 by using the following properties: ÎÎ Height and Width When the image is created without any size specifications, the original dimensions of the image are applied in Windows Phone 8 as well. In case you want to change the height and the width of the image, you can specify them explicitly. The image will then be displayed in a rectangular container area with the specified size. ÎÎ
Stretch
This property is used to specify how the image will be filled within the container area, set using Height and Width. Table 3.1 lists the possible values of this property along with their description. Description
None
The image is not stretched to accommodate the container area.
Uniform
This is the default value. The image is adjusted uniformly according to the dimensions of the container area. The original aspect ratio of the image is maintained in this option.
The image is adjusted uniformly to fill the dimensions of the entire container area. UniformToFill The original aspect ratio of the image is maintained in this option.
Fill
Sample Image
The image is stretched to fill the dimensions of the entire container area. The original aspect ratio of the image is not maintained in this option. Thus, there is a possibility that the quality of the image might diminish due to irregular stretching and filling. Table 3.1: Possible Values of the Stretch Property
V 1.0 © Aptech Limited
Concepts
Value of the Stretch Property
Session
3 Working with Windows Phone 8
ÎÎ Clip This property is used to crop or cut down the unnecessary spacing in an image. You need to specify a geometric shape, such as Oval or Ellipse, which will fit the image to the given shape and crop the remaining areas. Note – You can also provide a masking or a fading effect to the selected portions of the image
display, by using the OpacityMask property. This property, when included in an image, will create an additional layer on top of the image and you can adjust the color settings of this new layer to provide various effects, such as transparent and opaque, on the image. Code Snippet 1 demonstrates the use of the Image control in XAML. Code Snippet 1:
Concepts
Figure 3.1 shows a Windows Phone 8 screen, which contains the Image control.
Figure 3.1: Example of a Windows Phone 8 App with Image Control
V 1.0 © Aptech Limited
Session
3 Working with Windows Phone 8
3.2.2 Shapes for Windows Phone 8 Windows Phone 8 provides the Shape object to create or draw geometric shapes on the app. With the Shape object, you can create the required shapes, such as Rectangle, Line, Polygon, and Ellipse, by using a brush. The brush is used to render the shape with a particular fill or thickness. There are various properties associated with the Shape object. Table 3.2 lists some of the important properties of the Shape object along with their description.
Property for the Shape object
Description
Height, Width
These properties are used to specify the size of the shape.
Fill
This property is used to specify the brush for the shape. The values could include the color required for the fill, such as Blue or Green, of the brush.
RadiusX, RadiusY
These properties are used to create rounded edges for a shape.
Stroke
This property is used to create a border for a shape. The values include the color required for the fill of the brush.
StrokeThickness
This property is used to specify the thickness for the border set using the Stroke property. Table 3.2: Properties of the Shape Object
Note – There is another object called Geometry, which is also used to create geometric shapes in
Windows Phone 8. This object can also be used to crop an image to fit the required geometrical shape. However, it does not render the image, as it does not use the brush and its associated properties, such as Fill and Stroke.
Code Snippet 2 demonstrates the creation of multiple Rectangle objects with different property settings in XAML.
V 1.0 © Aptech Limited
Concepts
Code Snippet 2:
Session
3 Working with Windows Phone 8
Concepts
Figure 3.2 shows a Windows Phone 8 screen, which contains the Rectangle controls.
Figure 3.2: Example of a Windows Phone 8 App with Rectangle Controls
V 1.0 © Aptech Limited
Session
3 Working with Windows Phone 8
3.2.3 Brushes for Windows Phone 8 Apart from creating images and other objects, you can also paint them in Windows Phone 8. To paint a specific area in the app, such as an image, a text area, or even a UI control, you can use the Brush object. There are four categories available under the Brush object. Table 3.3 lists the categories of the Brush object along with their description.
Category of the Brush object
Description
SolidColorBrush
It is used to paint an area with a single color. You can specify the color for the brush using the actual color name, hexadecimal color value or property element syntax in the Fill property.
LinearGradientBrush
It is used to paint an area with multiple colors in gradient line along a linear axis.
RadialGradientBrush
It is used to paint an area with multiple colors in gradient pattern along a circular gradient axis.
ImageBrush
It is used to paint an area with an image. The location of the image is specified using the ImageSource property. Table 3.3: Categories of the Brush Object
Code Snippet 3 demonstrates the use of the RadialGradientBrush object applied for a rectangle in XAML. Code Snippet 3:
V 1.0 © Aptech Limited
Concepts
Session
3 Working with Windows Phone 8
Figure 3.3 shows a Windows Phone 8 screen with a rectangle painted using RadialGradientBrush.
Concepts
Figure 3.3: A Rectangle Painted Using RadialGradientBrush
V 1.0 © Aptech Limited
3
Session
Working with Windows Phone 8
3.2.4 Text and Fonts Windows Phone 8 provides various font options to display text in the Text controls with rich formatting. Some of the important font properties include FontFamily, FontStretch, FontStyle, and FontSize. These font definitions are available as part of Windows.Phone.Controls namespace. Code Snippet 4 demonstrates the use of the Font property in a TextBox in XAML. Code Snippet 4:
Concepts
Figure 3.4 shows a Windows Phone 8 screen, which contains the customized TextBox control.
Figure 3.4: Example of a Windows Phone 8 App with Customized TextBox Control
V 1.0 © Aptech Limited
Session
3 Working with Windows Phone 8
Windows Phone 8 also provides various other properties and elements to customize the display of text. Some of the important properties associated with the Text controls are as follows: ÎÎ TextWrap By default, text wrapping is not enabled in any of the Text controls. To enable text wrapping, you need to set the value of the TextWrap property to Wrap. If the text control has a width limit, the text is wrapped according to the width. If the width is not explicitly set, the text wrap is set according to the width limit followed in the layout of the UI. Code Snippet 5 demonstrates the use of this property in a TextBlock control. Code Snippet 5:
Concepts
Figure 3.5 displays the text with the wrapping property enabled.
Figure 3.5: A TextBlock Control with Text Wrapping ÎÎ Run and LineBreak In general, when the text is displayed with multiple lines, the same formatting would be applied to the entire text. In order to display multiple lines in a Text control with varied formatting options, you can use the Run and LineBreak elements.
V 1.0 © Aptech Limited
Session
3 Working with Windows Phone 8
The LineBreak is used to leave a blank line in a TextBlock. The Run element is used to specify each part of text in a Text control, which can have its own format setting. Code Snippet 6 demonstrates the use of these elements in a TextBlock control. Code Snippet 6: Figure 3.6 displays a block of text in different formats.
Figure 3.6: A TextBlock Control with Multiple Formatting ÎÎ Transform
yy
RotateTransform: It is used to rotate the text in a particular angle.
yy
SkewTransform: It is used to provide a distorted fancy transformation to the text by changing the default angle of X and Y co-ordinates. It can be used for animation of text as well.
yy
ScaleTransform: It is used to display text with larger fonts, which cannot be specified using the Font property.
V 1.0 © Aptech Limited
Concepts
You can also change the way the text is displayed in a Text control by using the Transform property. The various values for the property include:
Session
3 Working with Windows Phone 8
yy
TranslateTransform: It is used to provide a shadow effect.
Code Snippet 7 demonstrates the use of the Transform property in a TextBox in XAML. Code Snippet 7: Figure 3.7 shows a Windows Phone 8 screen, which contains the customized TextBox control.
Figure 3.7: Example of a TextBox Control with Transformation Note – The Transform property is also available for most of the UI controls in Windows Phone 8.
3.3 Enhancing the Appearance of the UI There are various ways to enhance the appearance of the UI in Windows Phone 8.
Concepts
3.3.1 Themes for Windows Phone An app, in order to maintain a consistent look-and-feel, needs to align with the appearance of the Windows Phone 8 UI. To promoter such a uniform appearance, Windows Phone 8 provides themes. A theme is a collection of resources, which provides a consistent background and style for the app and its UI controls. It offers two categories of settings, background color and accent color. You can use two shades of color for the background of your app – Dark and Light. The accent color is applied for all the UI controls and other visual elements in an app. You can use varied combinations of Red-Green-Blue (RGB) values to set the accent color for the UI.
V 1.0 © Aptech Limited
Session
3 Working with Windows Phone 8
To change the theme for the Windows Phone 8 Phone: 1.
Swipe the Home Screen of the Windows Phone 8 to the left. The Phone Apps list is displayed.
2.
Click Settings, and then click Theme. The list of available themes is displayed.
3.
Click the required theme.
4.
The new theme is set for the Windows Phone UI.
If a user changes a theme in Windows Phone 8, the theme settings will be globally updated for all the apps. Figure 3.8 displays the Windows Phone 8 screen with the standard theme applied to an app.
Figure 3.8: Windows Phone 8 App Screen with Standard Theme Remember that the theme has an impact only on the background color and the color of the visual elements and it does not affect the specifications related to font and sizing of UI controls. In case there are some closed apps, the new theme will be applied to them the next time they are invoked. In some situations, as a developer, you might have a requirement to maintain a customized theme that may not match with the standard Windows Phone 8 theme. For example, the app that you create should align to a standard color combination followed in your organization. In such a case, you have to override the global theme settings for your app at the time of programming it.
V 1.0 © Aptech Limited
Concepts
Note – When you change the theme, the list of all running apps will reflect the new theme immediately.
Session
3 Working with Windows Phone 8
3.3.2 Animations for Windows Phone Windows Phone 8 provides various ways to animate an app to enhance the user experience. For example, you can animate the color, the size, or the transformation of the angle of the UI controls and other visual elements in an app. Such an animation is achieved through manipulating the property values of a UI control. In general, the start of an animation is associated with an event. The step-by-step procedure to create an animation effect on the Opacity property of an ellipse after the user generates a Click event on the ellipse is as follows: 1.
Creating the Ellipse image The first step in animation is to identify the object to be animated and declare it in XAML. In this example, you will create an ellipse with a name, a particular size and a color. Code Snippet 8 contains the code to create the Ellipse object. Code Snippet 8:
2.
Creating the Storyboard Windows Phone 8 provides a container object called the Storyboard to store all the animated objects. You need to declare the Storyboard as a resource in the root container of your app so that it is available for all the animated objects in the app. Code Snippet 9 contains the code to declare the storyboard as a resource in the StackPanel, which is the root container. Code Snippet 9:
Concepts
3.
Adding the animated object to the storyboard After creating the Storyboard, you need to add the animated object to it. An animated object specifies the name of the object to be animated and its behavior.
V 1.0 © Aptech Limited
Session
3 Working with Windows Phone 8
Code Snippet 10 contains the code to create the animated object. Code Snippet 10: In Code Snippet 10, the animated object is DoubleAnimation. It is called so because the value of the property to be animated is the Opacity of the ellipse, which is represented as a Double. The name of the object to be animated using DoubleAnimation is specified in the TargetName parameter. In Code Snippet 10, the functionality or the behavior of the DoubleAnimation is set using the following parameters: ÎÎ TargetProperty specifies the property to be animated. ÎÎ From and To specify the value to be set during the start of the animation and the value to be set during the end of the animation. ÎÎ Duration specifies the duration of the animation in ‘hour:minute:second’ format. In this example, the animation is set for one second. ÎÎ AutoReverse specifies whether the object goes back to its original state after the animation is stopped. In this example, the value is set to ‘True’ and thus the shape goes back to its original form after the animation.
Concepts
ÎÎ RepeatBehavior specifies how long the animation should continue after its start. In this example, the value is set to ‘5’, which will run the animation for five times.
V 1.0 © Aptech Limited
3
Session
Working with Windows Phone 8 Note – Apart from DoubleAnimation, there are other types of animations in Windows Phone
8, such as the following:
ColorAnimation: This type of animation is used to animate a UI control or a visual element through multiple colors. You can specify the change of colors by passing the color names as values in From and To properties. PointAnimation: This type of animation is used to animate a pixel or a point in a UI control or a visual element. For example, you can use PointAnimation to enlarge the center point of a Polygon shape. 4.
Adding the event for the animation You need to create the event that will serve as the starting point for the animation, in C#. In this example, the animation is started immediately after the page is loaded on the screen. To start the animation, you need to first start the Storyboard in the app file. To start the storyboard, you need to use the Begin method in .MainPage.xaml. cs page as shown in Code Snippet 11. Code Snippet 11 contains the event handler code in C#. Code Snippet 11: private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e) { StoryBoard1.Begin(); } Note – You can also use the methods Pause, Resume, and Stop of the Storyboard, to
Concepts
perform the respective operations of pausing, resuming, and stopping the animation in their appropriate event handlers.
V 1.0 © Aptech Limited
Session
3 Working with Windows Phone 8
Code Snippet 12 contains the complete code for animation on the Opacity property of the ellipse object in XAML and C#. Code Snippet 12: private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e) { StoryBoard1.Begin();
Concepts
}
V 1.0 © Aptech Limited
Session
3 Working with Windows Phone 8
Figure 3.9 displays the animated set of images with the Opacity property of the ellipse.
Figure 3.9: Ellipse with Animation Effects
3.3.3 Control Tilt Effect Yet another sophisticated feature closely associated with animation, for app user interaction, is the Control Tilt effect. In general, whenever an event is generated on a UI control, such as Click, the control shows only a dotted line and a pressing effect to the users. Instead of this regular effect, you can show a visual motion of the control, whenever the event is generated, using the Control Tilt. The tilt effect is a property that you can use for a UI control, such as a Button or a ListBox. The code definition for the tilt effect is available in TiltEffect.cs, a sample download file in the Microsoft Web site. Note – To download the TiltEffect.cs, you need to use the following link: go.microsoft.com/
fwlink/?LinkId=200720.
Concepts
TiltEffect.cs provides two properties to set or remove the Tilt effect on a UI control as follows: ÎÎ IsTiltEnabled – This property accepts a Boolean value to set the tilt effect on the app for either a single control or multiple controls. ÎÎ SuppressTilt – This property accepts a Boolean value to disable the Tilt effect on either a single control or multiple controls.
V 1.0 © Aptech Limited
Session
3 Working with Windows Phone 8
The steps to create the Tilt effect on a Button control are as follows: 1.
Copy the TiltEffect.cs file from the sample project and paste it on the current app project.
2.
Create the reference of the TiltEffect.cs file in the declaration of namespaces in XAML by typing the following code: xmlns:local=clr-namespace:ControlTiltEffect.
3.
Create a Button control in XAML.
4.
Type the code given in Code Snippet 13 to provide tilt effect on the Button control. Code Snippet 13:
5.
Press F5.
Note – You can also create a Tilt Effect on a control by using the file
Microsoft.Phone.Control.toolKit.dll, which needs to be downloaded via Nuget. Once you import this toolkit in your project, you can create the Tilt Effect on the Button control by using the following code:
Concepts
Figure 3.10 displays the Windows Phone 8 app with the tilt enabled Button control and a default Button control with the text ‘Click me’ to highlight the difference in the two controls.
Figure 3.10: Tilt Enabled Button Control and a Default Button Control
V 1.0 © Aptech Limited
Session
3 Working with Windows Phone 8
3.4 Creating Advanced Windows Phone 8 App Functionality The app that you create should enable the user to perform various UI manipulations with limited effort. To provide for such functionality, Windows Phone 8 provides various UI controls and data manipulation techniques.
3.4.1 App Bar An Application Bar, in short, an App Bar, appears as a band at the bottom of an app. It provides shortcuts for the commonly used operations, such as Save, Delete, and Help, in the form of icons and menu items. By default, only the icons and the menu items are displayed without any label in the App Bar. When the user clicks the ellipsis (…) on the top-right corner of the App Bar, the labels of the respective icons and menu items are also displayed, provided they are specified in the App Bar code. Figure 3.11 displays a sample App Bar with the labels. Notice that the App Bar contains the icons in the first row and the menu items below the icons.
Figure 3.11: Sample App Bar with Labels Note – An App Bar can change into a vertical band if the orientation of the Windows Phone is changed
Concepts
to landscape.
The simplest way to create an App Bar for your project is through XAML. However, if you want to perform advanced customizations for the App Bar, you could use C# or Visual Basic. ÎÎ
Creating an App Bar in XAML In general, the App Bar code is available as part of all the projects in XAML in a commented form. To create the App Bar for your project, you need to simply uncomment the code and thus enable its visibility.
V 1.0 © Aptech Limited
Session
3 Working with Windows Phone 8
The steps to create an App Bar are as follows: 1.
Open the project in XAML.
2.
Switch to design view of the project.
3
Search for the text ‘ApplicationBar’ in the XAML code.
4.
Uncomment the code given for ApplicationBar by removing the tag ‘’.
Code Snippet 14 shows the uncommented code that is originally available as commented in XAML by default. Code Snippet 14: Note – An AppBar will not be available as a commented code in case the app page contains
5.
Make necessary customizations as required for your project, such as properties, menu items, and icons. For example, if you want to show three icons and three menu items, you can modify the code as shown in Code Snippet 15.
V 1.0 © Aptech Limited
Concepts
a Panorama control. In such a scenario, you need to create the AppBar code shown in Code Snippet 14 just before the last line of the XAML code ( private void btnSubmit_Click(object sender, RoutedEventArgs e) { string site; site = TextBox1.Text; WebBrowser1.Navigate(new Uri(site,UriKind.Absolute));
Concepts
} In Code Snippet 18, the first part demonstrates the creation of the required UI controls in XAML. The second part contains the event handler code in C# for the Click event of the button. It uses a string object called site to store data that would be entered by the user in the text box. The string value captured is then passed as the first parameter to the Navigate method of the WebBrowser object, to display the required Web page to the user. The second parameter of the Navigate method is the type of URL, which is specified as UriKind.Absolute. It refers to the URL that contains the complete path of the Web page address.
V 1.0 © Aptech Limited
Session
3 Working with Windows Phone 8
Figure 3.13 displays the output of the sample Web Browser program discussed in Code Snippet 18.
Figure 3.13: Sample Windows Phone 8 App with Web Browser Control
3.4.3 Data Binding Generally, an app displays a collection of UI controls and visual elements to display and accept data from the users. Such data could be in the form of text or images.
There could also be a need to retrieve the data entered by the user and display the same data in a customized form in a different UI control or in a message box. For example, if the user has selected an item from a list, you might want to display the selected item back to the user in a label in a customized form, such as ‘You have selected this ’. You might also need to perform some validations on the data entered by the user in a UI control, such as checking the input and generating an error message in case of invalid input. Windows Phone 8 provides data binding to promote such data manipulations. Data binding consists of two objects, a source and a target. The source would be the data to be retrieved and the target would
V 1.0 © Aptech Limited
Concepts
There might be a requirement to display data to the users from a different source, such as an object created in C# or Visual Basic, in the app.
Session
3 Working with Windows Phone 8
typically be a UI control in the app. You can bind a control to either a single item or a list of items. ÎÎ
Binding a UI Control to a Single Item In general, the text entered in a TextBox control can be bound to another UI control, such as a Label or TextBlock. For example, Code Snippet 19 contains the code to create data binding on a TextBlock control based on the text entered by the user in a TextBox control. Code Snippet 19:
Note – There are different modes to bind a control to a source as follows:
Onetime: In this mode, the binding between the source and the target occurs at the time of creating it.
yy
OneWay: In this mode, the binding of the source to the target occurs at the time of creating it and every time when the data is modified in the source. This is the default mode.
yy
TwoWay: In this mode, the binding of the source to the target occurs every time the data is modified either in the source or in the target. There is one exception in this mode. When the binding occurs in the Text property of a TextBox, the update occurs when the TextBox loses focus in the app.
Concepts
yy
V 1.0 © Aptech Limited
Session
3 Working with Windows Phone 8
Figure 3.14 displays a sample output for the partial code given in Code Snippet 19.
Figure 3.14: Data Binding on a Single Item ÎÎ
Binding a UI Control to a List of Items
Code Snippet 20:
V 1.0 © Aptech Limited
Concepts
In case of a ListBox control or any other control that accepts multiple inputs, you might need to bind it to multiple items. For example, Code Snippet 20 contains the code to create a data binding on a ListBox control based on the values set in an object named Furniture. The Furniture object is created in C# with a list of items.
3
Session
Working with Windows Phone 8 public partial class MainPage : PhoneApplicationPage { public ObservableCollection MyFurniture = new ObservableCollection(); public MainPage() { InitializeComponent(); MyFurniture.Add(newFurniture(“Table”)); MyFurniture.Add(newFurniture(“Chair”)); ListBox1.DataContext = MyFurniture; } } public class Furniture { public Furniture(stringfurnitureType) { this.FurnitureType = furnitureType; } publicstringFurnitureType { get; set; }
Concepts
publicoverridestringToString() { returnFurnitureType; } }
V 1.0 © Aptech Limited
Session
3 Working with Windows Phone 8
Figure 3.15 displays a sample output for the partial code given in Code Snippet 20.
Figure 3.15: Data Binding on Multiple Items ÎÎ
Data Validation You can also validate data using data binding. For example, consider that an app contains a UI control to accept the phone number from the user. You can create a validation to display a customized error message when the user types a text value or a numeric value with less than ten numbers in the PhoneNumber control. 1.
Create the class in C# for the object to be validated. In this example, the object is the phone number.
V 1.0 © Aptech Limited
Concepts
The steps to create the code for data validation based on the discussed scenario are as follows:
Session 2.
3 Working with Windows Phone 8 Code Snippet 21 contains the creation of the class for data validation. Code Snippet 21: public class PhoneClass { private string _Phone; public string Phone { get { return _Phone; } set { int res; if (value.Length != 10||int.TryParse(value,out res)) throw new Exception(“Invalid Phone number.”); _Phone = value; } } }
3.
Create the validation event handler code in C# as shown in Code Snippet 22. In this method, whenever the user types in a wrong phone number, the background of the text area turns into red color. If the user types the correct value for the phone number, the text area remains the same. Code Snippet 22:
Concepts
private void ContentPanel_BindingValidationError(object sender, ValidationErrorEventArgs e) { if (e.Action == ValidationErrorEventAction.Added) { TextBox1.Background = new SolidColorBrush(Colors.Red);
V 1.0 © Aptech Limited
Session
3 Working with Windows Phone 8 } else if (e.Action == ValidationErrorEventAction.Removed) { TextBox1.Background = new SolidColorBrush(Colors.White); } }
4.
Create the UI in XAML and bind the data and the event handler to its respective object and the event handler created in C#, shown in Code Snippet 21 and Code Snippet 22. The UI comprises the container object, the StackPanel, a TextBlock control, a TextBox control, and a Button control, as shown in Code Snippet 23. Code Snippet 23:
Session
3 Working with Windows Phone 8 Figure 3.16 and Figure 3.17 display the sample outputs of Windows Phone 8 screens with validation errors. Figure 3.18 displays the sample output of Windows Phone 8 screen with no validation error.
Concepts
Figure 3.16: Data Binding on Multiple Items – Sample Screen 1
V 1.0 © Aptech Limited
Session
3 Working with Windows Phone 8
Concepts
Figure 3.17: Data Binding on Multiple Items – Sample Screen 2
V 1.0 © Aptech Limited
Session
3 Working with Windows Phone 8
Concepts
Figure 3.18: Data Binding on Multiple Items – Sample Screen 3
V 1.0 © Aptech Limited
Session
3 Working with Windows Phone 8
3.5 Check Your Progress 1.
The __________ property of the Image control is used to crop down extra spacing in an image. (A) shape (B) clip
2.
Which of the following properties is/are used to create rounded edges for a Shape object? (A) Fill, UniformFill (B) Stroke
3.
(C) crop (D) fill (C) X, Y Co-ordinates (D) RadiusX, RadiusY
Which of these statements is true and which is false? Statement A: You need to use the Brush object to paint a UI control of an app. Statement B: You can use the ImageBrush property to paint an area with multiple colors in straight lines. Statement A is TRUE and State(C) Both the statements are TRUE. ment B is FALSE. Statement A is FALSE and State(B) (D) Both the statements are FALSE. ment B is TRUE.
(A)
4.
Which of the following elements can you use in a TextBlock control to specify multiple formatting options for a single text? (A) Transform (B) Run, LineBreak
5.
(C) Font (D) Run, TextWrap
Which of these statements is true and which is false? Statement A: There are two shades of accent color – dark and light, which the user can set for a theme. Statement B: If a user changes a theme in Windows Phone 8, the active apps will reflect the new theme immediately.
6.
Both the statements are FALSE.
The __________ object is the container that stores all the animated objects for an app. (A) Media (B) AnimationHub
Both the statements are TRUE.
(C) Root (D) Storyboard
V 1.0 © Aptech Limited
Concepts
Statement A is TRUE and State(C) ment B is FALSE. Statement A is FALSE and State(B) (D) ment B is TRUE. (A)
Session 7.
3 Working with Windows Phone 8
The ______________ effect is used to provide a visual motion of the UI control whenever an event is generated on it. (A) Tilt (B) AutoReverse
8.
(C) ColorAnimation (D) Transform
Which of these statements is true and which is false? Statement A: The code for creating the AppBar is available by default as a commented code in .xaml.cs. Statement B: The labels of the menu items and icons for an AppBar appear by default at the bottom of the respective item or icon. Statement A is TRUE and State(C) Both the statements are TRUE. ment B is FALSE. Statement A is FALSE and State(B) (D) Both the statements are FALSE. ment B is TRUE.
(A)
9.
Which of the following scenarios is NOT applicable for data binding in Windows Phone 8? (A)
Binding a UI control to a single (C) Binding a UI control to a list of items item (D) Data conversion
Concepts
(B) Data validation
V 1.0 © Aptech Limited
Session
3 Working with Windows Phone 8
3.5.1 Answers C
2.
D
3.
A
4.
B
5.
B
6.
D
7.
A
8.
D
9.
D
Concepts
1.
V 1.0 © Aptech Limited
Session
3 Working with Windows Phone 8
Summary Windows Phone 8 provides various objects, such as images and shapes to insert images and shapes in app.
ÎÎ
Windows Phone 8 provides the Brush object to paint an area of the app with a particular image or a color.
ÎÎ
Windows Phone 8 provides various text and fonts objects to display text in varied formatting styles and patterns.
ÎÎ
A theme is a collection of resources that provides a consistent background and style for app and its UI controls in Windows Phone 8.
ÎÎ
Windows Phone 8 provides various ways to animate an app through objects, such as DoubleAnimation, ColorAnimation, and PointAnimation.
ÎÎ
Storyboard is a container object that stores all the animated objects required for an app.
ÎÎ
Windows Phone 8 provides control Tilt Effect to provide visual motion on a UI control whenever an event is generated.
ÎÎ
An App Bar in Windows Phone 8 provides shortcuts to commonly-used operations in an app.
ÎÎ
A Web Browser control in Windows Phone 8 is used to display static as well as dynamic Web content in an app.
ÎÎ
Windows Phone 8 provides data binding of a UI control to a single item or a list of items to promote data validation and other manipulations.
Concepts
ÎÎ
V 1.0 © Aptech Limited
Session - 4 Implementing Notifications and Live Tiles Welcome to the Session, Implementing Notifications and Live Tiles. This session introduces you to Tiles and notifications and describes how they are implemented in Windows Phone 8 apps. At the end of this session, you will be able to: ÎÎ Explain the purpose of Tiles in Windows Phone 8 ÎÎ List and explain the categories of Tiles ÎÎ Describe the procedure to create static Tiles and live Tiles ÎÎ Explain the purpose of notifications ÎÎ Differentiate between a local notification and a push notification ÎÎ Describe the types of notifications that can be sent using local notifications ÎÎ Describe the types of notifications that can be sent using push notifications ÎÎ Describe the mechanism followed in push notifications ÎÎ Explain the procedure to set up an app to receive push notifications ÎÎ Explain the procedure to send and receive raw notifications, Tile notifications, and toast notifications in Windows Phone 8 apps
Session
4 Implementing Notifications and Live Tiles
4.1 Introduction to Tiles The success of a mobile app is largely determined by its attractive UI, excellent functionality, ease of use, and the frequency at which the end-user is using it. Windows Phone 8 provides various exciting features that can compel the users to use an app on a regular and a continuous basis. One such feature is the Tile option of Windows Phone 8. Tiles are visual representations of apps that are present in the Apps list on the Start screen. Each Tile, when tapped, launches the respective app on the screen. Thus, a Tile is similar to that of an icon yet provides much more sophistication than it. A Tile can either be a static Tile or a live Tile that can be dynamically updated from time to time.
4.1.1 Categories of Tiles There are two types of Tiles namely, primary Tile and secondary Tile. An app, by default, has one primary Tile pinned to the Apps list in Start screen. The primary Tile is the default Tile that typically contains an image depicting the personality of the app along with some information about the app, such as the Title of the app and other properties of the app. For example, if the app is an Insurance Portal, its Tile can include the details, such as the name of the Insurance Portal, an image that serves as a representation of Insurance, and updates to the portal, such as a new Policy or a relevant newsfeed. A secondary Tile is available as a Button or an Icon on the app UI, which contains some additional information about the app. The user can choose to pin the secondary Tile present in the app to the Start screen as part of the primary Tile. Continuing with the example of an Insurance Portal, an app could include secondary Tiles for additional details, such as newsfeed relevant to each zone or type of policy, which can be displayed along with the primary Tile. Note – It is possible to create a reference of an app in the Apps list of the Start screen without a Tile
image. Such an app would appear with the title of the app and a generic icon provided by Windows Phone 8, in the Apps list. A Tile can be displayed in three sizes, namely small, medium, and wide depending on the amount of information presented in each Tile.
4.1.2 Creating Tiles in Windows Phone 8 ÎÎ
Using Static Tile You can create a static Tile by using the default code available in the manifest file in Visual Studio.
V 1.0 © Aptech Limited
Concepts
You can create a Tile in one of the following ways:
Session
4 Implementing Notifications and Live Tiles Note – The manifest file contains some important details about the app, such as the app ID
and the app’s capabilities and functionality, such as the language used, the supported screen resolution, and deployment details. To set the static Tile with an icon image for an app: Open the app project in Visual Studio.
2.
Open the Solution Explorer window.
3.
Click the file, WMAppManifest.xml in the Properties folder. The manifest file appears.
4.
Select the path of the icon file to be used as a Tile image in the App Icon box as shown in figure 4.1. The selected icon will be displayed as a Tile in the Apps list of the Start screen.
Concepts
1.
Figure 4.1: App Icon Option in Manifest File
V 1.0 © Aptech Limited
Session ÎÎ
4 Implementing Notifications and Live Tiles
Using Visual Templates You can create a sophisticated Live Tile or Static Tile by using visual templates in Visual Studio. There are three types of visual templates for Windows Phone 8 apps: yy
Flip Template You can use the flip template when you want to display information in two surfaces, foreground, and background, of the Tile to the user. This template provides two sizes, small and medium. For example, you can create a Tile using a flip template if the app should display the list of ingredients to design a product in the background and the image of the actual product in the foreground.
yy
Iconic Template You can use the iconic template when you want to display an image in the center of the Tile, which would reflect the nature of the app. Most of the social networking apps and encyclopaedia portals can be best represented through this iconic Tile. A count of relevant details is also displayed in the template. For example, in case of a mail app, the count could include the number of new e-mails or messages received at a particular point in time. Note – The information of the count value in a Tile can hold a value in the range of 0 to 99
only. In case the count of the property goes beyond the value 99, only the value 99 will be displayed irrespective of the actual count. yy
Cycle Template You can use the cycle template in case the app needs to display a range of images, one by one, in the Tile. A maximum of nine images can be included in this template, which will display each image in rotation, to the users. For example, you can use this cycle template for an app of an organization that provides multiple services to the customers or for an app that displays a photo gallery to the users.
The steps to create a Tile using a visual template are as follows: 1.
Open the file, WMAppManifest.xml.
2.
Select the required template in the Tile Template box, as shown in figure 4.2.
3.
Type the title for the Tile in the Tile Title box.
4.
Set the required properties for the Tile according to the selected template.
Concepts
The selected Tile will be displayed in the Apps list of the Start screen.
V 1.0 © Aptech Limited
Session
4 Implementing Notifications and Live Tiles
Figure 4.2: Tile Template Option in Manifest File
4.1.3 Updating Tiles in Windows Phone 8
Concepts
In case of a Live Tile, you can update it from time to time to keep the users informed of the changes in the app, when the app is not running. Such changes to the Tiles will motivate the user to invoke the app to check for updates. To update Live Tiles on the Start screen, Windows Phone 8 provides a feature called notifications.
4.2 Introduction to Notifications Yet another feature of Windows Phone 8 that motivates the user to keep interacting with the app is the notification. A notification is an intuitive interactive mechanism, which keeps the user abreast of the latest happenings in his/her areas of interest. A notification provides a non-intrusive update to the end-user on information regarding an app or the system. There are two categories of notifications available in Windows Phone 8 namely, local notifications and push notifications.
V 1.0 © Aptech Limited
Session
4 Implementing Notifications and Live Tiles
4.2.1 Local Notifications Local notifications refer to the notifications for the apps that are scheduled and set internally in Windows Phone 8. You can use local notifications to update Tiles and toasts, and set alarms and reminders at specific time intervals. ÎÎ
Tile Notifications Tile notifications are used to refer to the non-disruptive changes that occur to the various Tiles on the Start screen, such as the list of apps and change in the property settings of each app. These notifications are used to keep the users informed of the changes occurring on the Live Tiles even when the app is not active. Figure 4.3 shows an example of a Live Tile notification in Windows Phone 8.
Figure 4.3: Live Tile Notification in Windows Phone 8 Note – You need to use the ShellTileSchedule class, which belongs to the Windows.Phone.Shell namespace to create local Tile notifications. ÎÎ
Toast Notifications
Toast notifications are toast messages received from a Web service on a certain app, which require some action from the user. They are also non-disruptive and are displayed to the user for ten seconds, within which time the user needs to take action on the notifications. An example of a toast notification could be an e-mail or a message sent to the user via an app. The user can either choose to see the notification by tapping on it to launch the required app or ignore the notification.
V 1.0 © Aptech Limited
Concepts
A toast is a message that appears at the top of the Windows Phone 8 screen in an opaque bar with a title and an optional sub title.
Session
4 Implementing Notifications and Live Tiles
Figure 4.4 shows an example of toast notification in Windows Phone 8.
Figure 4.4: Toast Notification in Windows Phone 8 Note – A toast notification is carried out as a background task for an app, through the use of a
background agent. A background agent is part of an app, which takes care of executing some tasks, such as notifications and scheduling, as a background process, irrespective of whether the app is active or not. You need to use the ShellToast class, which belongs to the Windows.Phone.Shell namespace to create a local toast notification. ÎÎ
Alarms and Reminder Notifications Alarms and Reminder notifications can be scheduled to occur locally at specific time intervals to aid the user in managing tasks effectively. You can set these notifications to occur only once or in recurrent mode for a set duration. You need to use the Alarm and Reminder classes, which are in turn part of ScheduledNotification class of Windows.Phone.Scheduler namespace, to create alarm and reminder notifications. Code Snippet 1 contains the partial code to set an alarm in a Windows Phone 8 app. Code Snippet 1: Alarm alarm = new Alarm(Guid.NewGuid().ToString()); alarm.BeginTime = DateTime.Now.AddMinutes(0.5D); alarm.ExpirationTime = DateTime.Now.AddMinutes(10.0D); alarm.Content = “Test Content”; alarm.RecurrenceType = RecurrenceInterval.None;
Concepts
ScheduledActionService.Add(alarm); In Code Snippet 1, an instance of the Alarm class is created and assigned to a String value. Then, the properties of the Alarm object are specified. Lastly, the Add() method of the ScheduledActionService is used to register the reminder with the Windows Phone 8 system.
V 1.0 © Aptech Limited
Session
4 Implementing Notifications and Live Tiles
Figure 4.5 shows the output of Windows Phone 8 app created in Code Snippet 1.
Figure 4.5: An Alarm App in Windows Phone 8 Code Snippet 2 contains the partial code to set a reminder in a Windows Phone 8 app. Code Snippet 2: Reminder reminder = new Reminder(Guid.NewGuid().ToString()); reminder.BeginTime = DateTime.Now.AddMinutes(0.5D); reminder.ExpirationTime = DateTime.Now.AddMinutes(10.0D); reminder.Content = “Test Content”; reminder.RecurrenceType = RecurrenceInterval.None; ScheduledActionService.Add(reminder);
Concepts
In Code Snippet 2, similar to the Alarm class in Code Snippet 1, an instance of the Reminder class is created and its associated properties are set.
V 1.0 © Aptech Limited
Session
4 Implementing Notifications and Live Tiles
Figure 4.6 shows the output of the Windows Phone 8 app created in Code Snippet 2.
Figure 4.6: Reminder App in Windows Phone 8
4.2.2 Push Notifications Push notifications refer to the scheduled notifications received from a Cloud service to the Windows Phone 8 apps. Similar to local notifications, you can update Tiles and toasts by using push notifications as well. In addition, you can send another type of notification called a raw notification by using a push notification.
Concepts
ÎÎ
Raw Notifications Raw notifications are used to refer to the action requests generated within the app for the user to respond. For example, a raw notification could include a warning message to the user to immediately close or save the app when there is a contingency, such as a network outage or low memory. In case of a raw notification, the app needs to be active and running in the foreground.
Note – A push notification cannot be used to set alarms and reminders as they are purely based on the
fixed schedules according to the Windows Phone 8 local time.
V 1.0 © Aptech Limited
Session
4 Implementing Notifications and Live Tiles
4.3 Understanding the Mechanism of Push Notifications The following components are required to enable push notifications in Windows Phone 8: ÎÎ
MPNS – To facilitate push notifications in Windows Phone 8 apps, Microsoft offers Microsoft Push Notification Service (MPNS). MPNS is a service provider, which provides an asynchronous mode for communication and data transfer from the cloud service of a Third Party (non-Microsoft Cloud service) to the Windows Phone 8 app. Note – In an asynchronous channel, the user is informed of the updates in a non-disruptive
mode through notifications, after the required change, such as data relating to Tiles and toasts, is transferred from a Cloud service. ÎÎ
Push-enabled app – It is the app that needs to receive push notifications in Windows Phone 8.
ÎÎ
Cloud service – It is the push server that provides the required notifications to the push-enabled app.
ÎÎ
A push client service – It subscribes to the various communication details offered by the cloud service to receive notifications. A generic example of a client service would be an e-mail client, such as Microsoft Outlook subscribing to the email server, such as Microsoft Live server, to get the required data in the form of e-mails and chat messages.
ÎÎ
Push notification Uniform Resource Identifier (URI) – It is the channel that receives all the push notification communications from the server.
1.
An app places a request with the push client service for a Push notification URI.
2.
The push client service contacts the MPNS.
3.
MPNS provides a push notification URI to the Push client service.
4.
The push client service submits the push notification URI to the app.
5.
The app passes on the push notification URI to the cloud service.
6.
The cloud service waits till the data is updated.
7.
When there is data update, the cloud service sends a push notification via the push notification URI.
8.
The push notification URI sends the updated data back to MPNS.
9.
MPNS presents the updated data to the push client service.
10. The push client service in turn sends the updated data to the app.
V 1.0 © Aptech Limited
Concepts
You will now understand the procedure used to implement the push notifications mechanism in Windows Phone 8. The sequence of this is as follows:
Session
4 Implementing Notifications and Live Tiles
The updated data could be a Tile notification or a toast notification, which will be displayed on the Windows Phone 8 device. Note – MPNS does not provide an end to end confirmation of the status between the push-enabled
app and the cloud service. However, once the push notification is sent from the cloud service, MPNS returns a response to the cloud service confirming the receipt of the push notification URI that would be delivered to the app in the near future. The response could be a confirmation message or an error code depending on whether the push notification URI could be submitted to the app or not. Figure 4.7 shows a diagrammatic representation of the push notification mechanism based on the discussed procedure.
Figure 4.7: Push Notification Mechanism
Concepts
4.3.1 Setting up an App for Receiving Push Notifications To convert an app into a push-enabled app, you need to first ensure that the app satisfies the requirement criteria listed in Windows Phone 8 Certification Requirements and Windows Phone 8 App Policies.
V 1.0 © Aptech Limited
Session
4 Implementing Notifications and Live Tiles
Note – The requirements and the policies to be followed for a push-enabled app are provided for your
reference in the following MSDN links:
http://msdn.microsoft.com/en-us/library/windowsphone/develop/ hh184843%28v=vs.105%29.aspx http://msdn.microsoft.com/en-us/library/windowsphone/develop/ hh184841%28v=vs.105%29.aspx Once the app adheres to these guidelines, you need to perform the following tasks to enable push notifications for the app: 1.
Creating the Push Channel ÎÎ Create a push channel to receive Tile and toast notifications to notify the user when the app is completely closed in Windows Phone 8. ÎÎ To create the push channel, you need to create an instance of the HttpNotificationChannel class, which belongs to the Microsoft.Phone.Notification namespace. ÎÎ In case the app needs to receive only raw notifications, the push channel should be made available only when the app is active and running in the foreground. Once the app is closed, the push channel should also be removed along with it.
2.
Enabling Push Notifications Every time the app is invoked by the user, you need to send the push notification URI along with the device ID from the push channel to the respective cloud service. This will initiate the process for the app to receive or wait for notifications. Sending a device ID to the cloud service will ensure that the cloud service will be able to send the data only to the specified device ID even when the URI changes from time to time.
3.
Receiving Notifications To receive the required notifications, you need to use the following methods and events, which are part of HttpNotificationChannel class of the Microsoft.Phone.Notification namespace.
Use the following methods given, to bind the notifications to their respective push channels:
•
Toast notification: BindToShellToast
•
Tile notification: BindToShellTile to access local resources to be used on the device, BindToShellTile(Collection URI) to access images from remote resources to be used on the device.
V 1.0 © Aptech Limited
Concepts
ÎÎ Methods
Session
4 Implementing Notifications and Live Tiles Note – You can specify a range of domain URIs in the Collection URI parameter of the
BindToShellTile. Each domain URI can be of a maximum length of 256 characters. ÎÎ Events
Use the following events to handle the push notifications in the app, which are part of HttpNotificationChannel class of the Microsoft.Phone.Notification namespace: yy ConnectionStatusChanged, to keep checking if the connection to the MPNS is proper from time to time yy ChannelUriUpdatedEvent, for Tile and toast notifications to notify the app whenever there is any change in the URI yy HttpNotificationReceived, to retrieve data for the app from the raw notification yy ShellNotificationReceived, to retrieve data for the app from the toast notification, when the app is not active yy ErrorOccuredEvent, to handle errors, if any, encountered during the push operation for all types of notifications Note – There are various errors and exceptions that can be handled by passing the respective
parameters in the ErrorOccuredEvent. To name a few such parameters:
Concepts
4.
yy
PushErrorTypeChannelOpenFailed – The channel is not available and cannot be opened. Create the channel and try to open it again.
yy
PushErrorTypeMessageBadContent – The specified URL is incorrect or not specified as part of the domain.
yy
PushErrorTypeUnknown – The error is due to some internal failure of the device and a reboot might be expected to solve it.
yy
PushNotificationChannelExists – This type of exception occurs when channel is already open and hence, cannot be reopened.
yy
PushNotificationChannelQuotaExceeded – This type of exception occurs when number of channels already opened for the push operation has exceeded the maximum limit.
Closing the Push Channel Use the Close method to close the push channel and perform the clean-up operations, if any, whenever the user turns off the notifications for the app from the app’s Settings page.
4.3.2 Good Practices for Communication You can follow the guidelines listed to enable proper communication mechanism between the push-enabled app and the cloud service.
V 1.0 © Aptech Limited
Session
4 Implementing Notifications and Live Tiles
ÎÎ
The app should first establish a reliable and an authentic communication channel with its respective cloud service.
ÎÎ
The URI should be encrypted for security reasons before sending it to the cloud service.
ÎÎ
The cloud service, after receiving the URI, should validate the same and store it in a secured manner for further communication.
ÎÎ
The cloud service should generate a status code and send it across to the push-enabled app, whenever a new notification channel for the URI needs to be initiated.
4.3.3 Sending Push Notifications to the App in Windows Phone 8 Once the app is set up as a push-enabled app and registered for receiving push notifications, you can start sending push notifications to it. In general, an app requires a push client service to get the push notifications from the cloud service. Such a client service provides an authentic HTTPS line for secured transfer of data. The push client service could be any Web service, such as a .NET Web service, a Java Web service, or Windows Communication Framework (WCF) Web service, which can connect to the MPNS, and provide the required service. Note – A push-enabled app can also send notifications directly to the MPNS, if it is registered for such a
service. Such an app would then be sending the notifications via an unsecured channel, which may not be authentic and safe. When you send notifications via the app itself instead of a Web client service, you need to adhere to a maximum subscription limit of sending only 500 push notifications in one day. The steps to send push notifications from either the app or the push client service are as follows: Compose a POST message for the Windows Phone 8 device, which contains the push-enabled app. Typically, this message should include a custom HTTP header with the following details: i.
A message ID – the notification message ID related to the response.
ii.
Notification Class – the interval at which the notifications will be sent to the app; it accepts a numeric value, which is in turn mapped to seconds.
iii.
Notification Type – the type of notification, such as Tile notification, toast notification, or raw notification; Remember that at a time, you can send only one type of notification by using a single POST message. In case you want to send multiple types of notifications, create as many number of POST messages accordingly.
2.
Send the message to the MPNS.
3.
Wait for the response from the MPNS.
4.
Respond according to the information received from the MPNS.
V 1.0 © Aptech Limited
Concepts
1.
Session
4 Implementing Notifications and Live Tiles
Code Snippet 3 contains the partial code to create a POST message for a sample toast notification. Code Snippet 3: HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest. Create(subscriptionUri); sendNotificationRequest.Method = “POST”; string toastMessage = “” + “” + “” + “Title” + “Sample Text” + “/Page2.xaml?NavigatedFrom=Toast Notification”+ “ “ + “”; byte[] notificationMessage = Encoding.Default.GetBytes(toastMessage); sendNotificationRequest.ContentLength = notificationMessage.Length; sendNotificationRequest.ContentType = “text/xml”; sendNotificationRequest.Headers.Add(“X-WindowsPhone-Target”, “toast”); sendNotificationRequest.Headers.Add(“X-NotificationClass”, “2”);
4.3.4 Sending and Receiving Raw Notifications in Windows Phone 8 App You will now understand the complete procedure to send and receive a raw notification in the app. The steps for this are as follows:
Concepts
1.
Creating a push-enabled app i.
Create a new Windows Phone 8 app.
ii.
Add the code given in Code Snippet 4 at the beginning of the MainPage.xaml.cs page. Code Snippet 4: using Microsoft.Phone.Notification;
iii.
Create the raw notification channel in the constructor of the code, as shown in Code Snippet 5.
V 1.0 © Aptech Limited
4
Session
Implementing Notifications and Live Tiles
Code Snippet 5 contains the code to create a new push channel (if it does not exist) or open the existing push channel (if it is already available). Once the push channel is created or opened, you need to specify the code for registering the events associated with the notification. Code Snippet 5: public MainPage() { // Holds the push channel that is created or found. HttpNotificationChannel pushChannel; // The name of our push channel. string channelName = “RawSampleChannel”; InitializeComponent(); // Try to find the push channel. pushChannel = HttpNotificationChannel.Find(channelName); // If the channel was not found, then create a new connection to // the push service. if (pushChannel == null) { pushChannel = new HttpNotificationChannel(channelName); pushChannel.ChannelUriUpdated += new EventHandler(PushChannel_ChannelUriUpdated); pushChannel.ErrorOccurred += new EventHandler(PushChannel_ErrorOccurred); pushChannel.HttpNotificationReceived += new Eve ntHandler(PushChannel_ HttpNotificationReceived); } else { pushChannel.ChannelUriUpdated += new EventHandler (PushChannel_ ChannelUriUpdated);
V 1.0 © Aptech Limited
Concepts
pushChannel.Open();
Session
4 Implementing Notifications and Live Tiles pushChannel.ErrorOccurred += new EventHandler(PushChannel_ErrorOccurred); pushChannel.HttpNotificationReceived += new Eve ntHandler(PushChannel_ HttpNotificationReceived); System.Diagnostics.Debug.WriteLine(pushChannel. ChannelUri.ToString()); MessageBox.Show(String.Format(“Channel Uri is {0}”, pushChannel.ChannelUri.ToString())); } }
iv.
Create the event handlers registered for the push channel, as shown in Code Snippet 6. Code Snippet 6: void PushChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e) { Dispatcher.BeginInvoke(() => { System.Diagnostics.Debug.WriteLine(e.ChannelUri. ToString()); MessageBox.Show(String.Format(“Channel Uri is {0}”, e.ChannelUri.ToString())); }); }
Concepts
// code for handling the ErrorOccured event void PushChannel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e) { // Error handling logic for your particular application // would be here.
V 1.0 © Aptech Limited
Session
4 Implementing Notifications and Live Tiles Dispatcher.BeginInvoke(() =>
MessageBox.Show(String.Format(“A push notification {0} error occurred. {1} ({2}) {3}”, e.ErrorType, e.Message, e.ErrorCode, e.ErrorAdditionalData)) ); } // code for handling the HttpNotificationReceived event void PushChannel_HttpNotificationReceived(object sender, HttpNotificationEventArgs e) { string message; using (System.IO.StreamReader reader = new System. IO.StreamReader(e.Notification.Body)) { message = reader.ReadToEnd(); } Dispatcher.BeginInvoke(() => MessageBox.Show(String.Format(“Received Notification {0}:\n{1}”, DateTime.Now.ToShortTimeString(), message)) ); } v.
Save the project.
Concepts
The push-enabled app is created successfully and the push channel URI is displayed, as shown in figure 4.8.
V 1.0 © Aptech Limited
Session
4 Implementing Notifications and Live Tiles
Figure 4.8: A Sample Message in the Push-enabled App
Concepts
2.
Creating a Push Client Service using ASP.NET i.
Create an app in Visual Studio using the template, ASP.NET Empty Web Application in the Web C# categories.
ii.
Save the project.
iii.
Right-click the name of the project, click Add, point to Add Item, and then, click Web Form. A Web form is created for the project.
iv.
Right-click the name of the Web form page in the Solutions Explorer and click Set as First Page, to set this Web form page as the start page of the project.
V 1.0 © Aptech Limited
Session v.
4 Implementing Notifications and Live Tiles
Add the required controls for the form. For example, you can add two TextBox controls for accepting the URI and displaying the response, and a Button control to send the notification, in this form, as shown in Code Snippet 7. Code Snippet 7: // creating the Web form page in ASP.NET Enter URI: Include using statements for relevant namespaces at the beginning of the SendRaw. aspx.cs page.
vi.
V 1.0 © Aptech Limited
Concepts
Response:
4
Session
Implementing Notifications and Live Tiles Create the event handler for the Button control as shown in Code Snippet 8. Code Snippet 8 contains the code to retrieve the URI entered in the text box, create the message for the raw notification, and send it as the POST message to the MPNS.
vii.
Code Snippet 8: protected void ButtonSendRaw_Click(object sender, EventArgs e) { try { string subscriptionUri = TextBoxUri.Text.ToString(); HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest. Create(subscriptionUri); sendNotificationRequest.Method = “POST”; // Create the raw message. string rawMessage = “New job for: Don Funk”; byte[] notificationMessage = Encoding.Default.GetBytes(rawMessage); // Set the Web request content length. sendNotificationRequest.ContentLength = notificationMessage.Length; sendNotificationRequest.ContentType = “text/xml”; sendNotificationRequest.Headers.Add(“X-NotificationClass”, “3”); using (Stream requestStream = sendNotificationRequest. GetRequestStream()) { requestStream.Write(notificationMessage, 0, notificationMessage. Length); }
Concepts
// Send the notification and get the response. HttpWebResponse response = (HttpWebResponse)sendNotificationRequest. GetResponse(); string notificationChannelStatus = response.Headers[“XSubscriptionStatus”];
V 1.0 © Aptech Limited
Session
4 Implementing Notifications and Live Tiles
string deviceConnectionStatus = response.Headers[“XDeviceConnectionStatus”]; TextBoxResponse.Text = notificationStatus + “ | “ + deviceConnectionStatus + “ | “ + notificationChannelStatus; } catch (Exception ex) { TextBoxResponse.Text = “Exception caught sending update: “ + ex.ToString(); } } The push client service is created successfully. 3.
Running the Project The steps are as follows: i.
Run the push-enabled app in Windows Phone (WP) Emulator. The app displays the message with the created notification URI indicating that the notification channel has been created and is open for communication.
ii.
Select the notification URI and copy it by pressing CTRL+C.
iii.
Next, open the push client service project.
iv.
Run the project.
v.
Press CTRL + V to paste the copied URI from the push-enabled app to the respective text box in the Web form.
vi.
Enter the required information to be published as a raw notification in the respective text boxes.
vii. Click the required button control to send the raw notification data to the push-enabled app.
Concepts
The raw notification message is displayed in the push-enabled app in the WP Emulator, if it is active and running, as shown in figure 4.9.
V 1.0 © Aptech Limited
Session
4 Implementing Notifications and Live Tiles
Figure 4.9: Sample Raw Notification Output
Concepts
4.3.5 Sending and Receiving Tile Notifications in Windows Phone 8 App The steps to create a Tile notification are similar to a raw notification. However, in case of a Tile notification, you need to create some graphic image files, which are to be used to update the image for the Tile, along with the other properties, such as Title of the Tile, and the count. You can also use image files from a remote URL to update the Tile. You will now understand the complete procedure to send and receive a tile notification in the app. The steps for this are as follows: 1.
Creating a push-enabled app i.
Create a new Windows Phone 8 app.
V 1.0 © Aptech Limited
Session
4 Implementing Notifications and Live Tiles
ii.
Include using statements for relevant namespaces at the beginning of the MainPage. xaml.cs page.
iii.
Right-click the name of the project, point to Add, and then click Existing Item, and add the required image icon files, which can be used as Tiles to the project.
iv.
Select the name of the graphic file in the Solution Explorer.
v.
Invoke the Properties window.
vi.
Set the Build Action to Content to include the image as part of the .xap file. Repeat these steps to include other graphic files as part of the .xap file.
vii. Create the Tile notification channel in the constructor of the code, as shown in Code Snippet 9. The push channel is created or opened in case it is already available. It is then made to bind to the Tile notifications. Once the binding is complete, the required events are registered for this notification. Code Snippet 9: public MainPage() { HttpNotificationChannel pushChannel; string channelName = “TileSampleChannel”; InitializeComponent(); pushChannel = HttpNotificationChannel.Find(channelName); if (pushChannel == null) { pushChannel = new HttpNotificationChannel(channelName); pushChannel.ChannelUriUpdated += new EventHandler(PushChannel_ChannelUriUpdated);
pushChannel.Open(); pushChannel.BindToShellTile(); } else {
V 1.0 © Aptech Limited
Concepts
pushChannel.ErrorOccurred += new EventHandler (PushChannel_ErrorOccurred);
4
Session
Implementing Notifications and Live Tiles pushChannel.ChannelUriUpdated += new EventHandler(PushChannel_ChannelUriUpdated); pushChannel.ErrorOccurred += new EventHandler(PushChannel_ErrorOccurred); System.Diagnostics.Debug.WriteLine(pushChannel. ChannelUri.ToString()); MessageBox.Show(String.Format(“Channel Uri is {0}”, pushChannel.ChannelUri.ToString())); } }
viii.
Create the event handlers required for the push channel, as shown in Code Snippet 10.
Code Snippet 10: void PushChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e) { Dispatcher.BeginInvoke(() => { // Display the new URI for testing purposes. Normally, the URI would be passed back to your Web service at this point. System.Diagnostics.Debug.WriteLine(e.ChannelUri.ToString()); MessageBox.Show(String.Format(“Channel Uri is {0}”, e.ChannelUri.ToString())); }); }
Concepts
void PushChannel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e) { // Error handling logic for your particular application would be here. Dispatcher.BeginInvoke(() => MessageBox.Show(String.Format(“A push notification {0} error occurred. {1} ({2}) {3}”,
V 1.0 © Aptech Limited
Session
4 Implementing Notifications and Live Tiles
e.ErrorType, e.Message, e.ErrorCode, e.ErrorAdditionalData)) ); }
Save the project.
ix.
The push-enabled app is created successfully. 2.
Creating a Push Client Service using ASP.NET i.
Create an ASP.NET Empty Web Application and add a Web Form.
ii.
Add the required controls for the form. For example, you can add TextBox controls for accepting the URI, displaying the title in the foreground and the background of the Tile, displaying information on the count, and the response message, and a Button control for sending the Tile notification, in this form, as shown in Code Snippet 11.
Code Snippet 11: // Creating the Web form page in ASP.NET Enter URI: Enter Front Title: Enter Front Background Image:
V 1.0 © Aptech Limited
Concepts
Session
4 Implementing Notifications and Live Tiles Enter Front Count: Enter Back Title: Enter Back Background Image: Enter Back Content:
Concepts
Response:
V 1.0 © Aptech Limited
Session
4 Implementing Notifications and Live Tiles
iii.
Include using statements for relevant namespaces at the beginning of the SendTile. aspx.cs page.
iv.
Create the event handler for the Button control as shown in Code Snippet 12. Code Snippet 12 contains the code to retrieve the URI entered in the TextBox, create the message for the Tile notification, and send it as the POST message to the MPNS.
Code Snippet 12: protected void ButtonSendTile_Click(object sender, EventArgs e) { try { string subscriptionUri = TextBoxUri.Text.ToString(); HttpWebRequest sendNotificationRequest = (HttpWebRequest) WebRequest. Create(subscriptionUri); sendNotificationRequest.Method = “POST”; sendNotificationRequest.Headers.Add(“X-MessageID”, “”); // Create the tile message. string tileMessage = “” + “” + “” + “” + TextBoxBackgroundImage.Text + “” + “” + TextBoxCount.Text + “” + “” + TextBoxTitle.Text + “” + “” + TextBoxBackBackgroundImage. Text + “” +
byte[] notificationMessage = Encoding.Default. GetBytes(tileMessage);
V 1.0 © Aptech Limited
Concepts
“” + TextBoxBackTitle.Text + “” + “” + TextBoxBackContent.Text + “” + “ “ + “”;
Session
4 Implementing Notifications and Live Tiles
// Set the Web request content length. sendNotificationRequest.ContentLength = notificationMessage.Length; sendNotificationRequest.ContentType = “text/xml”; sendNotificationRequest.Headers.Add(“X-WindowsPhone-Target”, “token”); sendNotificationRequest.Headers.Add(“X-NotificationClass”, “1”); using (Stream requestStream = sendNotificationRequest. GetRequestStream()) { requestStream.Write(notificationMessage, 0, notificationMessage.Length); } // Send the notification and get the response. HttpWebResponse response = (HttpWebResponse)sendNotificationRequest. GetResponse(); string notificationStatus = response.Headers[“XNotificationStatus”]; string notificationChannelStatus = response.Headers[“XSubscriptionStatus”]; string deviceConnectionStatus = response.Headers[“XDeviceConnectionStatus”]; TextBoxResponse.Text = notificationStatus + “ | “ + deviceConnectionStatus + “ | “ + notificationChannelStatus; } catch (Exception ex) {
Concepts
TextBoxResponse.Text = “Exception caught sending update: “ + ex.ToString(); } } The push client service is created successfully. 3.
Running the Project i.
Run the push-enabled app in Windows Phone (WP) Emulator.
V 1.0 © Aptech Limited
Session
4 Implementing Notifications and Live Tiles
ii.
Next, open the push client service project.
iii.
Run the project.
iv.
Set the Tile for your application to Start by tapping and holding the name of the app in the apps list and then choosing pin to Start. The selected Tile will be updated through the Tile notification.
v.
Press CTRL + V to paste the copied URI from the push-enabled app to the respective text box in the Web form.
vi.
Enter the required properties to be updated in the Tile, such as count, name of the image file, and a title, in the respective text boxes.
vii.
Click the required Button to send the Tile notification data to the push-enabled app.
Concepts
The Tile notification will be updated on the push-enabled app’s Tile pinned to the Start, in the WP Emulator, as shown in figure 4.10. Notice that figure 4.10 shows the Tile updates in foreground as well as background because of the use of the flip template.
Figure 4.10: Sample Tile Notification Output
V 1.0 © Aptech Limited
4
Session
Implementing Notifications and Live Tiles
4.3.6 Sending and Receiving Toast Notifications The steps to create a toast notification are similar to that of a Tile notification and a raw notification. You will now understand the complete procedure to send and receive a toast notification in the app. 1.
Creating a push-enabled app i.
Create a new Windows Phone 8 app. In case of a toast notification, you need to create two pages in the app to show the navigation details from one page to another during the notification process.
ii.
Include using statements for relevant namespaces at the beginning of the MainPage. xaml.cs page.
iii.
Create the toast notification channel in the constructor of the code, as shown in Code Snippet 13.
Code Snippet 13: public MainPage() { HttpNotificationChannel pushChannel; string channelName = “ToastSampleChannel”; pushChannel = HttpNotificationChannel.Find(channelName); if (pushChannel == null) { pushChannel = new HttpNotificationChannel(channelName); pushChannel.ChannelUriUpdated += new EventHandler(PushChannel_ChannelUriUpdated); pushChannel.ErrorOccurred += new EventHandler(PushChannel_ErrorOccurred);
Concepts
pushChannel.ShellToastNotificationReceived += new EventHandler(PushChannel_ShellToastNotificationReceived); pushChannel.Open(); pushChannel.BindToShellToast(); }
V 1.0 © Aptech Limited
Session
4 Implementing Notifications and Live Tiles
else { pushChannel.ChannelUriUpdated += new EventHandler(PushChannel_ChannelUriUpdated); pushChannel.ErrorOccurred += new EventHandler(PushChannel_ErrorOccurred); pushChannel.ShellToastNotificationReceived += new EventHandler(PushChannel_ShellToastNotificationReceived); System.Diagnostics.Debug.WriteLine(pushChannel.ChannelUri. ToString()); MessageBox.Show(String.Format(“Channel Uri is {0}”, pushChannel.ChannelUri.ToString())); } } iv.
Create the event handlers registered for the push channel, as shown in Code Snippet 14.
Code Snippet 14: void PushChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e) { Dispatcher.BeginInvoke(() => { // Display the new URI for testing purposes. // Normally, the URI would be passed back to your Web service at this point. System.Diagnostics.Debug.WriteLine(e.ChannelUri.ToString()); e.ChannelUri.ToString())); }); } void PushChannel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
V 1.0 © Aptech Limited
Concepts
MessageBox.Show(String.Format(“Channel Uri is {0}”,
4
Session
Implementing Notifications and Live Tiles { // Error handling logic for your particular application //would be here. Dispatcher.BeginInvoke(() => MessageBox.Show(String.Format(“A push notification {0} error occurred. {1} ({2}) {3}”, e.ErrorType, e.Message, e.ErrorCode, e.ErrorAdditionalData)) ); } void PushChannel_ShellToastNotificationReceived(object sender, NotificationEventArgs e) { StringBuilder message = new StringBuilder(); string relativeUri = string.Empty; message.AppendFormat(“Received Toast {0}:\n”, DateTime.Now. ToShortTimeString()); // Parse out the information that was part of the message. foreach (string key in e.Collection.Keys) { message.AppendFormat(“{0}: {1}\n”, key, e.Collection[key]); if (string.Compare( key, “wp:Param”, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.CompareOptions.IgnoreCase) == 0) {
Concepts
relativeUri = e.Collection[key]; } } Dispatcher.BeginInvoke(() => MessageBox.Show(message.ToString()) ); }
V 1.0 © Aptech Limited
Session v.
4 Implementing Notifications and Live Tiles
Create the event handler for the second page of the push-enabled app to facilitate navigation, as shown in Code Snippet 15.
Code Snippet 15: // Page2.cs protected override void OnNavigatedTo(System.Windows.Navigation. NavigationEventArgs e) { base.OnNavigatedTo(e); // If we navigated to this page // from the MainPage, the DefaultTitle parameter will be “FromMain”. If we navigated here // when the secondary Tile was tapped, the parameter will be “FromTile”. textBlockFrom.Text = “Navigated here from “ + this.NavigationContext. QueryString[“NavigatedFrom”]; } }
vi.
Save the project. The push-enabled app is created successfully.
Creating a Push Client Service using ASP.NET i.
Create an app in Visual Studio using the template, ASP.NET Empty Web Application in the Web C# categories.
ii.
Save the project.
iii.
Right-click the name of the project, Click Add, point to Add Item, and then, click Web Form. A Web form is created for the project.
iv.
Right-click the name of the Web form page in the Solutions Explorer and click Set as First Page, to set this Web form page as the start page of the project.
v.
Add the required controls for the form. For example, you can add TextBox controls for accepting the URI, displaying the title and the sub title, and the response message, and a Button control for sending the toast notification, in this form, as shown in Code Snippet 16.
V 1.0 © Aptech Limited
Concepts
2.
4
Session
Implementing Notifications and Live Tiles
Code Snippet 16: Response: vi.
Include using statements for relevant namespaces at the beginning of the SendToast. Aspx.cs page.
vii. Create the event handler for the Button control as shown in Code Snippet 17. Code Snippet 17 contains the code to retrieve the URI entered in the TextBox, create the message for the toast notification, and send it as the POST message to the MPNS. Code Snippet 17: protected void ButtonSendToast_Click(object sender, EventArgs e) { try { string subscriptionUri = TextBoxUri.Text.ToString();
Concepts
HttpWebRequest sendNotificationRequest = (HttpWebRequest) WebRequest.Create(subscriptionUri); sendNotificationRequest.Method = “POST”; sendNotificationRequest.Headers.Add(“X-MessageID”, “”); // Create the toast message. string toastMessage = “” + “” +
V 1.0 © Aptech Limited
4
Session
Implementing Notifications and Live Tiles “” + “” + TextBoxTitle.Text.ToString() + “” +
“” + TextBoxSubTitle.Text.ToString() + “” + “/Page2.xaml?NavigatedFrom=Toast Notification” + “ “ + “”; byte[] notificationMessage = Encoding.Default. GetBytes(toastMessage); sendNotificationRequest.ContentLength = notificationMessage.Length; sendNotificationRequest.ContentType = “text/xml”; sendNotificationRequest.Headers.Add(“X-WindowsPhone-Target”, “toast”); sendNotificationRequest.Headers.Add(“X-NotificationClass”, “2”); using (Stream requestStream = sendNotificationRequest. GetRequestStream()) { requestStream.Write(notificationMessage, 0, notificationMessage.Length); } HttpWebResponse response = (HttpWebResponse) sendNotificationRequest.GetResponse(); string notificationStatus = response.Headers[“XNotificationStatus”];
string deviceConnectionStatus = response.Headers[“XDeviceConnectionStatus”]; TextBoxResponse.Text = notificationStatus + “ | “ + deviceConnectionStatus + “ | “ + notificationChannelStatus; }
V 1.0 © Aptech Limited
Concepts
string notificationChannelStatus = response.Headers[“XSubscriptionStatus”];
4
Session
Implementing Notifications and Live Tiles catch (Exception ex) { TextBoxResponse.Text = “Exception caught sending update: “ + ex.ToString(); } }
The push client service is created successfully. 3.
Running the Project i.
Run the push-enabled app in Windows Phone (WP) Emulator. The app displays the message with the created notification URI indicating that the notification channel has been created and is open for communication.
ii.
Select the notification URI and copy it by pressing CTRL+C.
iii.
Next, open the push client service project.
iv.
Run the project.
v.
Press CTRL + V to paste the copied URI from the push-enabled app to the respective text box in the Web form.
vi.
Enter the title and the sub title for the toast.
Concepts
vii. Click the required Button to send the toast notification data to the push-enabled app.
V 1.0 © Aptech Limited
Session
4 Implementing Notifications and Live Tiles
In the app that is running in the WP Emulator, you will receive the toast notification as a message box in the app UI itself.
Figure 4.11: A Sample Toast Notification Output
V 1.0 © Aptech Limited
Concepts
In case the app is not running, the toast notification will be displayed at the top of the screen, as shown in figure 4.11. You need to tap the notification to go to the required page on the app. Figure 4.12 shows the navigated page in the Windows Phone 8 App after tapping the toast notification.
Session
4 Implementing Notifications and Live Tiles
Concepts
Figure 4.12: The Navigated Page
V 1.0 © Aptech Limited
Session
4 Implementing Notifications and Live Tiles
4.4 Check Your Progress 1.
A _________ Tile is a button or an icon on the app UI, which can be pinned to the Start screen. (A) Static (B) Primary
2.
(C) Live (D) Secondary
The default code to create a static Tile is available in ________ file in Visual Studio. (A) .manifest (B) .cs
3.
(C) .xaml (D) .xap
Which of these statements is true and which is false? Statement A: A local notification cannot be used to set alarms and reminders in Windows Phone 8. Statement B: Both local notifications and push notifications can be used to send raw notifications.
4.
(A)
Statement A is TRUE and Statement B is FALSE.
(C)
Both the statements are TRUE.
(B)
Statement A is FALSE and Statement B is TRUE.
(D)
Both the statements are FALSE.
Which type of notification would be ideal to use to send information to an inactive app on the online purchase request sent by a customer in the app? (A) Toast notification using push notification
(C)
Raw notification using push notification
(B) Tile notification using local notification
(D)
Reminder notification notification
using
local
Which type of notification would be ideal to use to send information to the running app on the emergency server shut down due to an unknown virus attack? (A) Toast notification using local notification
(C)
(B) Tile notification using local notification
(D) Tile notification using push notification
Raw notification using push notification
V 1.0 © Aptech Limited
Concepts
5.
4
Session 6.
Implementing Notifications and Live Tiles
Which of the following are required for sending local notifications? a.
MPNS
b.
Cloud service
c.
Push notification URI
d.
Push client service
e. Windows.Phone.Shell namespace
7.
(A) All the options are required.
(C)
Except option A, all the other options are required.
(B) Only option E is required.
(D)
Except option E, all the other options are required.
You need to create an instance of the _____________ class available as part of the ____________ namespace to create a push channel. HttpsNotificationChannel, Microsoft.Phone.Shell HttpsNotificationChannel, (B) Microsoft.Phone. Notification
(A)
HttpNotificationChannel, Microsoft.Phone.Shell
(D)
HttpNotificationChannel, Microsoft.Phone.Notification
Which method needs to be used under push notifications if the user turns off the notifications for the app in the Settings page? (A) Close
(C)
End
(B) ConnectionStatusChanged
(D) ErrorOccuredEvent
Concepts
8.
(C)
V 1.0 © Aptech Limited
Session
4 Implementing Notifications and Live Tiles
4.4.1 Answers D
2.
A
3.
B
4.
A
5.
C
6.
B
7.
D
8.
A
Concepts
1.
V 1.0 © Aptech Limited
Session
4 Implementing Notifications and Live Tiles
Summary Tiles are visual representations of apps that are present in the Apps list on the Start screen.
ÎÎ
There are two types of Tiles namely, primary Tile and secondary Tile.
ÎÎ
You can create a Tile as a static Tile or as a Live Tile using visual templates.
ÎÎ
A notification is an intuitive interactive mechanism, which keeps the user abreast of the latest happenings in his/her areas of interest.
ÎÎ
There are two categories of notifications available in Windows Phone 8 namely, local notifications and push notifications.
ÎÎ
You can use notifications to update Tiles and toasts, send raw notifications, and set alarms and reminders at specific time intervals.
ÎÎ
The components required to enable push notifications for a Windows Phone 8 app include MPNS, push-enabled app, cloud service, push client service, and a push notification URI.
Concepts
ÎÎ
V 1.0 © Aptech Limited
Session - 5 Working with Platform APIs, Tasks, and Choosers Welcome to the Session, Working with Platform APIs, Tasks, and Choosers. In this session, you will learn about the various Windows Platform Application Programming Interfaces (APIs) available for Windows Phone 8. You will also learn about the various Launchers and Choosers that you can use in Windows Phone 8. At the end of this session, you will be able to: ÎÎ List and describe the important APIs available for Windows Phone 8 ÎÎ Describe the procedure to include an API in Windows Phone 8 ÎÎ Differentiate between Launchers and Choosers in Windows Phone 8 ÎÎ Describe the procedure to use Launchers for email, connection setting, and maps ÎÎ Describe the procedure to use Launchers for phone call and SMS ÎÎ Describe the procedure to use Launchers for Web Browser and search ÎÎ Describe the procedure to use Choosers for address and other contact details ÎÎ Describe the procedure to use Choosers for camera, photo, and ringtone
Session
5 Working with Platform APIs, Tasks, and Choosers
5.1 Introduction to Windows Platform API Windows Phone SDK 8 offers immense flexibility and reusability for mobile app development by enabling the developers to create apps through a combination of technologies, tools, and languages. Thus, you can integrate XAML with programs created in other languages, such as C++, Visual Basic, and C#, which will help reduce your development effort. To facilitate such integration of languages for building apps, Windows Phone 8 provides a range of Windows Platform APIs. APIs are a collection of pre-defined functions, routines, and tools, which aid in speeding up the development process of any application. There are three types of APIs available for Windows Phone 8: ÎÎ
.NET API for Windows Phone 8
ÎÎ
Windows Phone 8 Runtime API
ÎÎ
Win 32 and COM API for Windows Phone 8
5.1.1 .NET API for Windows Phone 8 .NET APIs for Windows Phone 8 are managed APIs that let you build apps by integrating technologies, languages, and tools in .NET environment. You can import various namespaces available under Windows Phone and System of .NET. Some of the important namespaces that are part of .NET APIs are as follows: ÎÎ Microsoft.Devices ÎÎ Microsoft.Phone ÎÎ Microsoft.Phone.Controls ÎÎ Microsoft.Phone.Shell ÎÎ System.Data
There are also some newly-added .NET APIs with functionality specifically for Windows Phone 8 app development. This includes namespaces, such as Windows.Phone.Wallet and functionality for Lock Screen for Windows Phone 8.
V 1.0 © Aptech Limited
Concepts
ÎÎ System.Resources
Session
5 Working with Platform APIs, Tasks, and Choosers
Note – There are two types of APIs namely managed APIs and native APIs.
ÎÎ
Native APIs are directly loaded into the OS of any device. They are available in binary form and will directly interact with the OS. Managed APIs are placed as a top layer or a wrapper around the native APIs. These APIs can interact only with the native APIs and cannot communicate to the OS directly.
ÎÎ
Managed APIs are managed by the .NET runtime environment in Windows OS while native APIs are managed directly by the Windows OS.
5.1.2 Windows Phone 8 Runtime API Windows Phone 8 Runtime APIs are a collection of native APIs and managed APIs that can be used for building apps. Thus, you have a choice to develop apps in high-level languages or develop Windows Runtime (also called as WinRT) components through languages including C++. Windows Phone 8 Runtime APIs offer a huge collection of over two thousand APIs that include: ÎÎ
A subset of the Windows Runtime APIs that is relevant to Phone development
ÎÎ
A range of new APIs created exclusively for Windows Phone 8
Some of the important namespaces that are part of Windows Phone 8 Runtime APIs are as follows: ÎÎ Windows.ApplicationModel ÎÎ Windows.Devices ÎÎ Windows.Foundation ÎÎ Windows.Networking ÎÎ Windows.UI
Concepts
Note – You need to check the Requirements section of the Windows Phone API Documentation to
identify the APIs that are supported in Windows Phone 8. If an API is supported in Windows Phone 8, there would be an entry available in the Requirements section as ‘Minimum supported phone’ with the required mobile OS version. This verification is very important before using any API in app programming as there are some APIs, which would be supported in Windows Phone 8 but cannot be implemented in a Windows Phone 8 device. Such a scenario will throw an exception at the time of executing the program in the device.
V 1.0 © Aptech Limited
Session
5 Working with Platform APIs, Tasks, and Choosers
5.1.3 Win 32 and COM API for Windows Phone 8 Win 32 and COM APIs are a set of native APIs that enable you to create low-level networking and other features in Windows Phone 8. Direct 3D APIs for gaming applications, Microsoft Media Foundation APIs, Camera APIs, and Audio-related APIs are some of the important APIs available under this category. These APIs, which are already available for the various versions of Windows Desktop OS have been extended in purpose for Windows Phone 8 as well. ÎÎ
Using Windows API in Windows Phone 8 Programming – An Example To call the managed APIs in XAML or C#, you need to declare them in the Windows Phone project through ‘using ’ and then start directly accessing the various classes and methods available under the required API for the app. In case of a native API, you cannot directly call it in XAML or C#. Instead, you will use C++ to call the Windows native API and then use the C++ component in your Windows Phone program. You will now learn the procedure to call a native API in Windows Phone project with the help of an example. The steps to call a native API are as follows: 1.
Create the required UI in Visual Studio or Blend for Visual Studio. In this example, you will create a Windows Phone 8 app with a Button control in XAML.
2.
Create a Windows Runtime Component (WinRT) in C++ using the following steps: i.
Click File New Project and select Windows Phone Runtime Component template in the right pane after selecting Visual C++ and Windows Phone on the left.
ii. Name the project as Wp8RT.
iii. Include the code shown in Code Snippet 1 in Wp8RT.cpp. Code Snippet 1: // Creating a C++ program with the WinRT component #include “pch.h” #include “Wp8RT.h” #include using namespace Platform; WindowsPhoneRuntimeComponent::WindowsPhoneRuntimeComponent() { }
V 1.0 © Aptech Limited
Concepts
using namespace Wp8RT;
Session
5 Working with Platform APIs, Tasks, and Choosers Platform::String^ WindowsPhoneRuntimeComponent:: GetGuid() { GUID result; String^ guid;
HRESULT hr = CoCreateGuid(&result);
if (SUCCEEDED(hr))
{
Guid gd(result);
guid=gd.ToString();
return guid;
}
throw Exception::CreateException(hr);
} Code Snippet 1 provides the partial program in Managed C++, which contains a method to create a GUID for identifying an entity in the Windows OS. It starts with the declaration of the headers, which contain the required class definitions, to be used in the program. The required namespaces to be used for creating the WinRT component for Windows Phone 8 are declared immediately after the headers. Next, the Constructor for the class is defined. Finally, a method called GetGuid is defined, which contains the code to invoke a native API function called CoCreateGuid for creating a new GUID. As this method is used to invoke the native API, it is called an API Wrapper method. Note – A Managed C++ program is a program compiled in a.NET environment to generate
an executable file in .NET.
A GUID refers to a string that contains a globally unique identifier, which is used to identify an entity, every time it is called in a program.
Concepts
3.
Add a reference to the WinRT component in the TestWp8RT.h file, as shown in Code Snippet 2.
V 1.0 © Aptech Limited
Session
5 Working with Platform APIs, Tasks, and Choosers
Code Snippet 2: // Creating the header file #include #pragma once namespace Wp8RT { public ref class WindowsPhoneRuntimeComponent sealed { public: WindowsPhoneRuntimeComponent();
Platform::String^ GetGuid(); };
}
Code Snippet 2 contains the code to create the namespace, Wp8RT, with the required class and its associated constructor and GetGuid method. Build the project Wp8RT.
4.
Create a Windows Phone app project named TestWinRT and add a Button control in XAML. Name the button as btnOK.
5.
Add a reference to the Wp8RT project in the TestWinRT project.
6.
Write a using statement to import the namespace Wp8RT.
7.
Call the API wrapper method of the Wp8RT project in the Windows Phone project’s TestWinRT. xaml.cs file, as shown in Code Snippet 3.
8.
Code Snippet 3: // Calling the API wrapper method in the event handler of the // Button control in .xaml.cs file { WindowsPhoneRuntimeComponent rt = new WindowsPhoneRuntimeComponent(); string guid = rt.GetGuid();
V 1.0 © Aptech Limited
Concepts
private void button1_Click(object sender, RoutedEventArgs e)
5
Session
Working with Platform APIs, Tasks, and Choosers MessageBox.Show(guid); }
Figure 5.1 shows the output of the Windows Phone 8 app.
Figure 5.1: Sample Output of the Windows Phone 8 App with a GUID
5.2 Different Tasks and Choosers for Windows Phone 8 Concepts
Windows Phone 8 provides a range of built-in APIs that are readily available for use for the developers. The most important among them are Launchers and Choosers. Both these types of APIs enable the developers to provide a separate application window for commonlyused tasks, such as sending e-mails and saving contact address information, which can be called from any app. Thus, the developers have the advantage to focus only on the main UI creation and functionality and use Launchers and Choosers for the rest of the common tasks in the app.
V 1.0 © Aptech Limited
Session
5 Working with Platform APIs, Tasks, and Choosers
In short, Launchers and Choosers provide the following benefits to the developers: ÎÎ
Reusability of code
ÎÎ
Easier and faster implementation of common tasks
ÎÎ
Consistency in the implementation of common tasks that adhere to Windows Phone framework standards
To use Launchers and Choosers in Windows Phone 8, you need to declare the Microsoft.Phone. Tasks namespace, which is part of the .NET APIs, in the app program.
5.2.1 Launchers A Launcher invokes a separate application window for the end-user, from the main app, to perform some common tasks that are independent of its parent app. In the new application window, the user can perform the required task or choose to ignore or cancel it. Once the user completes the task or cancels the task and closes its window, the main app gets back its control. Some examples of Launchers include e-mail and search tasks. To use a Launcher in an app, you need to use the following generic steps: 1.
Create an instance of the Launcher to be used.
2.
Set the required properties for the Launcher.
3.
Call the respective Launcher by using the Show method.
As the Launcher is an independent application, it does not return any data or status to its parent app. Windows Phone 8 provides a wide range of Launchers that can be used for various purposes. Some of the important Launchers are discussed as follows: ÎÎ
Email Compose Task The e-mail compose task is used to enable the user to send an e-mail from the app.
This task works only when the mail server configuration is enabled in the device. If it is not enabled, the user would be asked to first configure the mail server by using a wizard. Once the e-mail settings are intact, you can use this task to perform the required operation. The Launcher is implemented using the EmailComposeTask class. Note – The e-mail compose task should be tested directly in the Windows Phone device and
cannot be tested in the Windows Phone (WP) Emulator.
V 1.0 © Aptech Limited
Concepts
This Launcher invokes the e-mail application window with the To field, an optional list of recipients and a subject. The on-screen keyboard is also displayed to enable the user to type the email. A Send button is provided to send the message to the respective recipient(s).
5
Session
Working with Platform APIs, Tasks, and Choosers
Code Snippet 4 contains the partial code in C# to include the e-mail composer task on the Click event of the Button control in the main app. Code Snippet 4: // Declaration of the required API for the Launcher using Microsoft.Phone.Tasks; // Creating the task and invoking it on the Button Click event private void button1_Click(object sender, RoutedEventArgs e) { EmailComposeTask emailComposeTask = new EmailComposeTask(); emailComposeTask.Subject = “message subject”; emailComposeTask.Body = “message body”; emailComposeTask.To = “
[email protected]”; emailComposeTask.Cc = “
[email protected]”; emailComposeTask.Bcc = “
[email protected]”; emailComposeTask.Show(); }
Concepts
Figure 5.2 shows the e-mail compose Task window with the list of configured mail server accounts in a Windows Phone 8 app.
V 1.0 © Aptech Limited
Session
5 Working with Platform APIs, Tasks, and Choosers
Figure 5.2: E-mail Compose Task in Windows Phone 8 – Screen 1
Concepts
Once the user chooses the required mail server, the e-mail compose task will provide the options to compose an e-mail in the respective mail server, as shown in figure 5.3.
V 1.0 © Aptech Limited
5
Session
Working with Platform APIs, Tasks, and Choosers
Figure 5.3: E-mail Compose Task in Windows Phone 8 – Screen 2 ÎÎ
Connection Setting Task The connection setting task is used to enable the user to change the settings of the network connections for the phone device. This Launcher invokes the Settings window with the required options for the user to make the necessary changes. The Launcher is implemented using the ConnectionSettingsTask class. Code Snippet 5 contains the partial code in C# to include the connection setting task on the Click event of the Button control in the main app.
Concepts
Code Snippet 5: // Declaration of the required API for the Launcher using Microsoft.Phone.Tasks; // Creating the task and invoking it on the Button Click event private void button1_Click(object sender, RoutedEventArgs e) {
V 1.0 © Aptech Limited
Session
5 Working with Platform APIs, Tasks, and Choosers
ConnectionSettingsTask connectionSettingTask = new ConnectionSettingsTask(); connectionSettingTask.ConnectionSettingsType = ConnectionSettingsType.Bluetooth; connectionSettingTask.Show(); } Figure 5.4 shows the connection setting task window in a Windows Phone 8 app.
ÎÎ
Maps Direction Task The Maps directions task displays a map to the user for retrieving the details of the direction between a starting point and an ending point. This Launcher invokes the Maps window with the required options regarding the starting point and the ending point. The user can either specify one location point or both the location points for start and end.
V 1.0 © Aptech Limited
Concepts
Figure 5.4: Connection Setting Task in Windows Phone 8
5
Session
Working with Platform APIs, Tasks, and Choosers
In case the user specifies only one point, the location of the other point will be automatically mapped to the current location. The Launcher is implemented using the MapsDirectionsTask class. Code Snippet 6 contains the partial code in C# to include the Maps direction task on the Click event of the Button control in the main app. Code Snippet 6: // Declaration of the required APIs for the Launcher using Microsoft.Phone.Tasks; using System.Device.Location; // Creating the task and invoking it on the Button Click event private void button1_Click(object sender, RoutedEventArgs e) { MapsDirectionsTask mapDirectionTask = new MapsDirectionsTask(); mapDirectionTask.Start = new LabeledMapLocation(“New York, New York, USA”, new System.Device.Location.GeoCoordinate(40.7142700, -74.0059700)); mapDirectionTask.End = new LabeledMapLocation(“Ocean City, New Jersey, USA”, new System.Device.Location.GeoCoordinate(39.2776200, -74.5746000)); mapDirectionTask.Show();
Concepts
}
V 1.0 © Aptech Limited
Session
5 Working with Platform APIs, Tasks, and Choosers
Figure 5.5 shows the Maps direction task window in a Windows Phone 8 app.
Concepts
Figure 5.5: Maps Direction Task in Windows Phone 8
V 1.0 © Aptech Limited
5
Session
Working with Platform APIs, Tasks, and Choosers
Note – Windows Phone 8 also provides other Launchers associated with maps as follows:
ÎÎ
ÎÎ
Maps task: This Launcher is used to invoke the Maps application with which you can search or mark locations.
ÎÎ
MapDownloader task: This Launcher is used to save a map or a part of it for offline use.
ÎÎ
MapUpdater task: This Launcher is used to update the map in the Maps application with the changes made offline in the downloaded map.
ÎÎ
Bing Maps task: This Launcher is used to invoke the Bing Maps application with which you can search or mark locations. The Bing Maps application is part of Bing, the search engine of Microsoft.
ÎÎ
Bing Maps directions task: Similar to Maps directions task, this Launcher invokes the Bing Maps application to get the direction details between two points.
Phone Call Task The phone call task is used to enable the user to make phone calls from the app. This Launcher invokes the phone application window with the name of the caller and the phone number. The user should click the Call button to enable the phone call. The Launcher is implemented using the PhoneCallTask class. Code Snippet 7 contains the partial code in C# to include the phone call task on the Click event of the Button control in the main app. Before the code is executed, ensure that the ID_CAP_ PHONEDIALER capability is enabled in the WMAppManifest file. To do this, in the Solution Explorer, double-click WMAppManifest.xml and then in the Capabilities tab, select the ID_ CAP_PHONEDIALER capability. Code Snippet 7: // Declaration of the required APIs for the Launcher using Microsoft.Phone.Tasks; // Creating the task and invoking it on the Button Click event
Concepts
private void button1_Click(object sender, RoutedEventArgs e) { PhoneCallTask phoneCallTask = new PhoneCallTask(); phoneCallTask.PhoneNumber = “8995614560”; phoneCallTask.DisplayName = “George”;
V 1.0 © Aptech Limited
Session
5 Working with Platform APIs, Tasks, and Choosers
phoneCallTask.Show(); } Figure 5.6 shows the phone call task window in a Windows Phone 8 app.
Figure 5.6: Phone Call Task in Windows Phone 8 ÎÎ
Search Task This Launcher invokes the search application window with the required search query and furnishes the results of the search to the user. The SearchTask class is used to implement this Launcher.
V 1.0 © Aptech Limited
Concepts
The search task is used to enable the user to search for information on a particular topic in Web.
5
Session
Working with Platform APIs, Tasks, and Choosers
Code Snippet 8 contains the partial code in C# to include the search task on the Click event of the Button control in the main app. Code Snippet 8: // Declaration of the required APIs for the Launcher using Microsoft.Phone.Tasks; // Creating the task and invoking it on the Button Click event private void button1_Click(object sender, RoutedEventArgs e) { SearchTask searchTask = new SearchTask(); searchTask.SearchQuery = “Aptech”; searchTask.Show(); }
Concepts
Figure 5.7 shows the search task window in a Windows Phone 8 app.
Figure 5.7: Search Task in Windows Phone 8
V 1.0 © Aptech Limited
Session ÎÎ
5 Working with Platform APIs, Tasks, and Choosers
Short Messaging Service (SMS) Compose Task The SMS compose task is used to enable the user to send a message to the required recipients. This Launcher invokes the Messaging application window with the SMS text, to be sent to the recipients. An optional list of recipients and a message body can also be specified in the task. A Send button is provided to send the message to the respective recipient(s). The SmsComposeTask class is used to implement this Launcher. Code Snippet 9 contains the partial code in C# to include the SMS compose task on the Click event of the Button control in the main app. Code Snippet 9: // Declaration of the required APIs for the Launcher using Microsoft.Phone.Tasks; // Creating the task and invoking it on the Button Click event private void button1_Click(object sender, RoutedEventArgs e) { SmsComposeTask smsComposer = new SmsComposeTask(); smsComposer.Body = “Test SMS”; smsComposer.To = “9716640953”; smsComposer.Show();
Concepts
}
V 1.0 © Aptech Limited
Session
5 Working with Platform APIs, Tasks, and Choosers
Figure 5.8 shows the SMS compose task window in a Windows Phone 8 app.
Figure 5.8: SMS Compose Task in Windows Phone 8 ÎÎ
Web Browser Task
Concepts
The Web Browser task is similar in purpose to the WebBrowser control in XAML. This Launcher invokes the Web Browser application window with the required URL for the user. The WebBrowserTask class is used to implement this Launcher.
V 1.0 © Aptech Limited
Session
5 Working with Platform APIs, Tasks, and Choosers
Code Snippet 10 contains the partial code in C# to include the Web Browser task on the Click event of the Button control in the main app. Code Snippet 10: // Declaration of the required APIs for the Launcher using System; using Microsoft.Phone.Tasks; // Creating the task and invoking it on the Button Click event private void button1_Click(object sender, RoutedEventArgs e) { WebBrowserTask wbBrowserTask = new WebBrowserTask(); wbBrowserTask.Uri = new Uri(“http://www.google.com”, UriKind. Absolute); wbBrowserTask.Show();
Concepts
}
V 1.0 © Aptech Limited
Session
5 Working with Platform APIs, Tasks, and Choosers
Figure 5.9 shows the Web Browser task window in a Windows Phone 8 app.
Figure 5.9: Web Browser Task in Windows Phone 8
5.2.2 Choosers
Concepts
A Chooser, similar to a Launcher, invokes a separate application window for the end-user, from the main app, to perform some common tasks. However, unlike a Launcher, a Chooser can communicate the status or the data back to its parent app. In the new application window of the Chooser, the user can perform the required task. Once the user completes the task and closes its window, the parent app gets back its control along with the data or the status. Some examples of Choosers include Address Chooser and Camera Capture Chooser.
V 1.0 © Aptech Limited
Session
5 Working with Platform APIs, Tasks, and Choosers
Windows Phone 8 provides a wide range of Choosers that can be used for various purposes. Some of the important Choosers are discussed are as follows: ÎÎ
Address Chooser Task The address Chooser task is used to retrieve the physical location or the contact address of the user from the Contacts list. This Chooser invokes the Contacts application window with the list of addresses from which the user can select the required address. The selected address would then be returned in the specified event handler to its parent app. The AddressChooserTask class is used to implement this Chooser. Code Snippet 11 contains partial code in C# to include the address Chooser task on the Click event of the Button control in the main app. Code Snippet 11: // Declaration of the required APIs for the Chooser using Microsoft.Phone.Tasks; // Initializing the task object and retrieving the event // handler that would be generated after the task is // completed. private void button1_Click(object sender, RoutedEventArgs e) { AddressChooserTask addressChooserTask; AddressChooserTask addressChooser = new AddressChooserTask(); addressChooser.Completed += addressChooser_Completed; addressChooser.Show(); }
void addressChooserTask_Completed(object sender, AddressResult e) { if (e.TaskResult == TaskResult.OK) {
V 1.0 © Aptech Limited
Concepts
// Adding the code in the completed event handler to fetch the // required address details
5
Session
Working with Platform APIs, Tasks, and Choosers MessageBox.Show(e.DisplayName + “\t” + e.Address); } }
Figure 5.10 shows the address Chooser task window in a Windows Phone 8 app.
Concepts
Figure 5.10: Address Chooser Task in Windows Phone 8 ÎÎ
Save Contact Task The save contact task is used to enable the user to save the contact details, such as Name and Phone Number, from the application. This Chooser invokes the Contacts application with the list of contact properties and the user can save the details. The contact details would then be returned in the specified event handler to its parent app. The SaveContactTask class is used to implement this Chooser.
V 1.0 © Aptech Limited
Session
5 Working with Platform APIs, Tasks, and Choosers
Code Snippet 12 contains the partial code in C# to include the save contact task on the Click event of the Button control in the main app. Code Snippet 12: // Declaration of the required APIs for the Chooser using Microsoft.Phone.Tasks; // Adding the event handler code to initialize the save // contact task and save the contact details private void button1_Click(object sender, RoutedEventArgs e) { SaveContactTask saveContactTask = new SaveContactTask(); saveContactTask.FirstName = “Test Name”; saveContactTask.MobilePhone = “9716640953”; saveContactTask.Show(); }
Concepts
Figure 5.11 shows the save contact task window in a Windows Phone 8 app.
Figure 5.11: Save Contact Task in Windows Phone 8
V 1.0 © Aptech Limited
5
Session ÎÎ
Working with Platform APIs, Tasks, and Choosers
Phone Number Chooser Task The phone number Chooser task is used to retrieve the phone number of the user from the Contacts list. This Chooser invokes the Contacts application window with all the contact details from which the user can select the required phone number. The selected phone number would be returned in the specified event handler to its parent app. The PhoneNumberChooserTask class is used to implement this Chooser. Code Snippet 13 contains the partial code in C# to include the phone number Chooser task on the Click event of the Button control in the main app. Code Snippet 13: // Declaration of the required APIs for the Chooser using Microsoft.Phone.Tasks; // Adding the event handler code to initialize the phone // number Chooser task and fetch the phone number details private void button1_Click(object sender, RoutedEventArgs e) { PhoneNumberChooserTask phoneNumberChooser = new PhoneNumberChooserTask(); phoneNumberChooser.Completed += phoneNumberChooser_Completed; phoneNumberChooser.Show(); } // Adding the code in the completed event handler to fetch the // required phone number details void phoneNumberChooser_Completed(object sender, PhoneNumberResult e) {
Concepts
MessageBox.Show(e.DisplayName + “\t” + e.PhoneNumber); }
V 1.0 © Aptech Limited
Session
5 Working with Platform APIs, Tasks, and Choosers
Figure 5.12 shows the phone number Chooser task window in a Windows Phone 8 app.
Figure 5.12: Phone Number Chooser Task in Windows Phone 8 ÎÎ
Save Phone Number Task
This Chooser invokes the Contacts application with the list of phone numbers and the user can save the required details. The details of the phone number would then be returned in the specified event handler to its parent app. The SavePhoneNumberTask class is used to implement this Chooser. Code Snippet 14 contains the partial code in C# to include the save phone number task on the Click event of the Button control in the main app.
V 1.0 © Aptech Limited
Concepts
The save phone number task is used to enable the user to save the phone number from the application.
5
Session
Working with Platform APIs, Tasks, and Choosers
Code Snippet 14: // Declaration of the required APIs for the Chooser using Microsoft.Phone.Tasks; // Adding the event handler code to initialize the save // phone number task and save the phone number private void button1_Click(object sender, RoutedEventArgs e) { SavePhoneNumberTask savePhoneNumberTask = new SavePhoneNumberTask(); savePhoneNumberTask.PhoneNumber = “9716640953”; savePhoneNumberTask.Show(); }
Concepts
Figure 5.13 shows the save phone number task window in a Windows Phone 8 app.
Figure 5.13: Save Phone Number Task in Windows Phone 8
V 1.0 © Aptech Limited
Session ÎÎ
5 Working with Platform APIs, Tasks, and Choosers
Save E-mail Address Task The save e-mail address task is used to enable to user to save the e-mail address from the application. This Chooser invokes the Contacts application window with the list of e-mail addresses and the user can save the required email address. The selected e-mail address would then be returned in the specified event handler to its parent app. The SaveEmailAddressTask class is used to implement this Chooser. Code Snippet 15 contains the partial code in C# to include the save e-mail address task on the Click event of the Button control in the main app. Code Snippet 15: // Declaration of the required APIs for the Chooser using Microsoft.Phone.Tasks; // Adding the event handler code to initialize the save // email address task and save the required email address private void button1_Click(object sender, RoutedEventArgs e) { SaveEmailAddressTask saveEmail = new SaveEmailAddressTask(); saveEmail.Email = “
[email protected]”; saveEmail.Show();
Concepts
}
V 1.0 © Aptech Limited
Session
5 Working with Platform APIs, Tasks, and Choosers
Figure 5.14 shows the save e-mail address task window in a Windows Phone 8 app.
Figure 5.14: Save E-mail Address Task in Windows Phone 8 ÎÎ
Camera Capture Task
Concepts
The camera capture task is used to enable the user to take a photograph by using the Windows Phone Camera. This Chooser invokes the Camera application and lets the user take the photograph. The photograph would then be returned in the specified event handler to its parent app. The CameraCaptureTask class is used to implement this Chooser. Code Snippet 16 contains the partial code in C# to include the camera capture task on the Click event of the Button control in the main app. In the code, CameraImage is the name of the Image control that will show the image taken from camera or chosen from SD card.
V 1.0 © Aptech Limited
Session
5 Working with Platform APIs, Tasks, and Choosers
Code Snippet 16: // Declaration of the required APIs for the Chooser using Microsoft.Phone.Tasks; // Adding the event handler code to initialize the camera // capture task private void button1_Click(object sender, RoutedEventArgs e) { CameraCaptureTask cameraCapturetask = new CameraCaptureTask(); cameraCapturetask.Completed += cameraCapturetask_Completed; cameraCapturetask.Show(); } // Adding the code in the completed event handler to fetch the // required bitmap image and return to the parent app void cameraCapturetask_Completed(object sender, PhotoResult e) { BitmapImage bitmapImage = new BitmapImage(); bitmapImage.SetSource(e.ChosenPhoto); CameraImage.Source = bitmapImage;
Concepts
}
V 1.0 © Aptech Limited
Session
5 Working with Platform APIs, Tasks, and Choosers
Figure 5.15 shows the camera capture task window in a Windows Phone 8 app.
Figure 5.15: Camera Capture Task in Windows Phone 8 If you are using the WP Emulator to test the output of this task, you need to press F7 in the camera capture task window to take a photograph.
Concepts
Note – Once the photograph is transferred to the main app, it is immediately saved in the
Windows Phone camera roll as well. In case the user has set the upload option to automatic in OneDrive, the photo is automatically published in the cloud and would thus be made available to every one in the shared community. If, as a developer, you do not want the photograph taken via the app to be shared with everyone, you need to create a customized camera UI app through a different API called CameraAPI, instead of this CameraCaptureTask API. ÎÎ
Photo Chooser Task The photo Chooser task is used to enable the user to choose a photograph from a saved album, such as a Windows Phone camera roll.
V 1.0 © Aptech Limited
Session
5 Working with Platform APIs, Tasks, and Choosers
This Chooser invokes the Photo Chooser application with the collection of photographs and lets the user select the required photograph. The photograph would then be returned in the specified event handler to its parent app. The PhotoChooserTask class is used to implement this Chooser. Code Snippet 17 contains the partial code in C# to include the photo Chooser task on the Click event of the Button control in the main app. Code Snippet 17: // Declaration of the required APIs for the Chooser using Microsoft.Phone.Tasks; // Adding the event handler code to initialize the photo // Chooser task private void button1_Click(object sender, RoutedEventArgs e) { PhotoChooserTask photoChooserTask = new PhotoChooserTask(); photoChooserTask.Completed += photoChooserTask_Completed; photoChooserTask.Show(); } // Adding the code in the completed event handler to fetch the // required photo and return to the parent app void photoChooserTask_Completed(object sender, PhotoResult e) { BitmapImage bitmapImage = new BitmapImage(); bitmapImage.SetSource(e.ChosenPhoto); CameraImage.Source = bitmapImage;
Concepts
}
V 1.0 © Aptech Limited
Session
5 Working with Platform APIs, Tasks, and Choosers
Figure 5.16 shows the photo Chooser task window in a Windows Phone 8 app.
Figure 5.16: Photo Chooser Task in Windows Phone 8 Note – In case you need to test this task in the WP Emulator, you need to have the Photos Hub
open with a sample set of photographs before starting the testing process. ÎÎ
Save Ringtone Task
Concepts
The save ringtone task is used to enable the user to save a ringtone in the form of an audio file to the existing list of ringtones in Windows Phone. This Chooser invokes the Ringtones application and the user can save the ringtone audio file to it. The audio file would then be returned in the specified event handler to its parent app. The SaveRingToneTask class is used to implement this Chooser. Once the ringtone is saved, it can be either set as a default ringtone for the device or for individual contacts in the Contacts list.
V 1.0 © Aptech Limited
Session
5 Working with Platform APIs, Tasks, and Choosers
Note – An audio file, in order to be saved as a ringtone, should adhere to the following criteria:
ÎÎ
The file format should belong to one of these categories - WMA, M4R, or MP3.
ÎÎ
The size of the audio file should be less than 30 MB.
ÎÎ
The file should not be Digital Rights Management (DRM) protected.
Code Snippet 18 contains the partial code in C# to include the save ringtone task on the Click event of the Button control in the main app. Code Snippet 18: // Declaration of the required APIs for the Chooser using Microsoft.Phone.Tasks; // Adding the event handler code to initialize the save // ringtone task private void button1_Click(object sender, RoutedEventArgs e) { SaveRingtoneTask saveRingtone = new SaveRingtoneTask(); saveRingtone.Source = new Uri(“appdata:/107928.mp3”); saveRingtone.DisplayName = “Test Ringtone”; saveRingtone.Completed += saveRingtone_Completed; saveRingtone.Show();
Concepts
}
V 1.0 © Aptech Limited
5
Session
Working with Platform APIs, Tasks, and Choosers // Adding the code in the completed event handler to display a // message when the ringtone is saved successfully void saveRingtone_Completed(object sender, TaskEventArgs e) { if (e.TaskResult == TaskResult.OK) MessageBox.Show(“Ringtone saved”); }
Figure 5.17 shows the save ringtone task window in a Windows Phone 8 app.
Concepts
Figure 5.17: Save Ringtone Task in Windows Phone 8 Note – For tasks that involve selection of the required data, such as Camera Capture task and
Address Chooser task, the completed event handler of the last action of the Chooser would return the selected data to the main app. For other tasks that involve saving data, such as Save Ringtone task and Save Contact task, the completed event handler of the last action of the Chooser can be used to display an optional status message to the user, before returning to the main app.
V 1.0 © Aptech Limited
Session
5 Working with Platform APIs, Tasks, and Choosers
5.3 Check Your Progress 1.
2.
The Microsoft.Phone.Controls namespace is part of __________________ API, which can be used in Windows Phone 8. (A) C++ Native API
(C)
Windows Phone 8 Runtime API
(B) Win 32 and COM API
(D) .NET API for Windows Phone 8
Which of these statements is true and which is false? Statement A: Windows Phone 8 uses both native APIs and managed APIs. Statement B: Managed APIs cannot interact with the Windows OS directly. Statement A is TRUE and (C) Both the statements are TRUE. Statement B is FALSE. Statement A is FALSE and (B) (D) Both the statements are FALSE. Statement B is TRUE.
(A)
Which of the following features is NOT provided by Launchers in Windows Phone 8? (A) Code reusability (B)
4.
Return of status to the calling app
(B) Activate
(D) Independent application window
(C)
Call
(D) Display
The _____________ API should be necessarily declared in a Windows Phone project to call Launchers or Choosers. (A)
Microsoft.Phone. Controls
(B) System.Device
Standard and consistent implementation of common tasks
The _____________ method is used to launch most of the Launchers and Choosers.
(A) Show
5.
(C)
(C)
Microsoft.Phone.Tasks
(D) System.Runtime
V 1.0 © Aptech Limited
Concepts
3.
Session 6.
5 Working with Platform APIs, Tasks, and Choosers
Which of these statements is true and which is false? Statement A: You cannot test the camera capture task in WP Emulator. Statement B: You have to press F7 to test the e-mail composer task in WP Emulator.
7.
(A)
Statement A is TRUE and Statement B is FALSE.
(C)
(B)
Statement A is FALSE and Statement B is TRUE.
(D) Both the statements are FALSE.
Both the statements are TRUE.
Match the Launcher/Chooser with its associated description.
Launcher/Chooser
Concepts
8.
Description
(a)
Email composer task
1.
Enables storing of contact details from the Contacts application
(b)
Maps Directions task
2.
Works only when the mail server is enabled in the device
(c)
Address Chooser task
3.
The selected email address will be returned to the respective event handler
(d)
Save email address task
4.
The API System.Device.Location to be included
(e)
Save contact task
5.
Enables selection of contact address from the Contacts list
(A) a-3, b-4, c-5, d-2, e-1
(C)
a-4, b-3, c-1, d-2, e-5
(B) a-2, b-4, c-5, d-3, e-1
(D) a-5, b-3, c-4, d-2, e-1
Which task is used to enable the user to take a photograph using the Windows Phone Camera? (A) Camera capture task
(C)
(B) Photo Chooser task
(D) Photo capture task
Camera Chooser task
V 1.0 © Aptech Limited
Session
5 Working with Platform APIs, Tasks, and Choosers
5.3.1 Answers D
2.
C
3.
B
4.
A
5.
C
6.
D
7.
B
8.
A
Concepts
1.
V 1.0 © Aptech Limited
Session
5 Working with Platform APIs, Tasks, and Choosers
Summary Windows Phone 8 provides a range of Windows Platform APIs to integrate various languages and tools for building apps.
ÎÎ
There are three types of APIs available for Windows Phone 8 - .NET API, Windows Phone 8 Runtime API, and Win 32 and COM API.
ÎÎ
Windows Phone 8 provides built-in APIs called Launchers and Choosers, which can be called from any app, for performing common tasks.
ÎÎ
Though the functionality of Launchers and Choosers are similar, the main difference is that the Launchers do not return status or data to the main app, whereas Choosers return status or data to the main app.
ÎÎ
Some of the important Launchers in Windows Phone 8 are e-mail compose task, connection setting task, maps direction task, phone call task, SMS Compose task, and Web Browser task.
ÎÎ
Some of the important Choosers in Windows Phone 8 are address Chooser task, save contact task, phone number Chooser task, camera capture task, photo Chooser task, and save ringtone task.
Concepts
ÎÎ
V 1.0 © Aptech Limited
Session - 6 Data Management in Windows Phone 8 Welcome to the Session, Data Management in Windows Phone 8. This session introduces you to the basics of data management in Windows Phone 8. You will also learn about application life cycle, Idle detection, Fast App Resume, and Simulation Dashboard in Windows Phone 8. At the end of this session, you will be able to: ÎÎ List the storage areas used to manage data in Windows Phone 8 ÎÎ Explain how data is stored in Windows Phone 8 ÎÎ Describe the procedure to save settings in an app ÎÎ Describe the procedure to read data from a SD card ÎÎ Describe the procedure to save and access data in files, folders, and local databases ÎÎ Explain the procedure to access external data from a Web service ÎÎ Describe the Application Life Cycle in Windows Phone 8 ÎÎ Describe the procedure to disable idle detection in Windows Phone 8 ÎÎ Explain the procedure for fast application resume ÎÎ Explain the purpose of Simulation Dashboard in Visual Studio
Session
6 Data Management in Windows Phone 8
6.1 Introduction to Data Management in Windows Phone 8 The ultimate purpose of creating apps in Windows Phone 8 is to promote effective data management. Data for the app could include localized data that is available on the phone or external data from Web services and external storage media. Windows Phone 8 provides various tools, storage areas, and APIs to save as well as access both these types of data easier and faster.
6.1.1 Data in Windows Phone 8 One of the main functionalities in app management is to save persistent data in Windows Phone device. Persistent data refers to any data that needs to be available permanently for an app even after the app is deactivated or closed. The persistent data that needs to be stored for an app could include information, such as history and settings. Before understanding how to store or access persistent data for the app, you need to first get familiarized with where data is stored in Windows Phone 8. The storage areas or containers that are used to store data are as follows: ÎÎ
Installation folder: All the files of the app package are stored in this read-only folder. To access the contents of this folder, Windows Phone 8 provides various APIs.
ÎÎ
Local folder: All the persistent data pertaining to the app are stored in this folder. The local folder serves as an isolated storage area for each app. It provides both a generic data storage container as well as a special purpose folder called a Shared folder to store media, tile images, and files transferred through background processing. To access the contents of the local folder, Windows Phone 8 provides a range of Win32 Storage APIs as well as other APIs.
ÎÎ
Media library: This folder is a virtual storage container in Windows Phone 8. All the media files, such as Photos, Videos, and Music albums are stored in this folder. To access these files for the app, you need to first specify the capability to access a particular media file format in the Manifest file of the app and then use the relevant APIs.
ÎÎ
Secure Digital (SD) Card: Apart from internal storage containers, you can also access data from an external storage area, such as a SD card.
While loading an app or exiting out of it, you might have a requirement to save important data as objects in the app’s local folder. Such saving of key information would be very helpful during circumstances when the app is closed accidentally due to network failure or low memory. The app data to be saved in the form of an object or a string as a key/value pair is called setting. The key contains a unique identifier of the data as a string and the value contains the actual value to be stored, similar to a hash table. To save as well as retrieve settings, you need to use a dictionary class called IsolatedStorageSettings, which is part of System.Windows assembly.
V 1.0 © Aptech Limited
Concepts
6.1.2 Persistent Data - Settings
Session
6 Data Management in Windows Phone 8
You will now understand the complete procedure to create a setting, read the setting, and remove the setting in an app. For this purpose, you need to create a UI with a text box for the setting, three buttons to perform the desired operation, and a text block to display the status in XAML, as shown in figure 6.1.
Concepts
Figure 6.1: Example App for Settings ÎÎ
Creating a Setting Code Snippet 1 contains the code to create a setting for the value that would be entered by the user in the text box, in the event handler of the button, Add Setting.
V 1.0 © Aptech Limited
Session
6 Data Management in Windows Phone 8
Code Snippet 1: private void btnAddSetting_Click(object sender, RoutedEventArgs e) { IsolatedStorageSettings settings = IsolatedStorageSettings. ApplicationSettings; if (!settings.Contains(“settingKey”)) { settings.Add(“settingKey”, txtSettingValue.Text); } else { settings[“settingKey”] = txtSettingValue.Text; } settings.Save(); }
Concepts
In Code Snippet 1, an instance of the IsolatedStorageSettings class is created using the ApplicationSettings property. A key called settingKey is created and the value for the key is assigned to the input data from the text box. The Save method is then called to save the setting.
V 1.0 © Aptech Limited
Session
6 Data Management in Windows Phone 8
Figure 6.2 shows the input entered by the user in the text box. Once the user clicks the Add Setting button, the input value is saved as a setting.
Figure 6.2: Creating a Setting ÎÎ
Accessing a Setting
Concepts
Code Snippet 2 contains the code to retrieve the setting, in the event handler of the button, Show Settings.
V 1.0 © Aptech Limited
Session
6 Data Management in Windows Phone 8
Code Snippet 2: private void btnShowSetting_Click(object sender, RoutedEventArgs e) { tbSetting.Text = “settingKey Value: “; if (IsolatedStorageSettings.ApplicationSettings. Contains(“settingKey”)) { tbSetting.Text += IsolatedStorageSettings.ApplicationSettings [“settingKey”] as string; } }
Concepts
In Code Snippet 2, the setting is read directly from the ApplicationSettings property. The retrieved setting is then displayed back to the user in the text block, settingKey Value: that is right below all the button controls, as shown in figure 6.3.
Figure 6.3: Reading a Setting
V 1.0 © Aptech Limited
Session ÎÎ
6 Data Management in Windows Phone 8
Deleting a Setting Code Snippet 3 contains the code to delete the saved setting, in the event handler of the button, Remove Data. Code Snippet 3: private void btnRemoveSetting_Click(object sender, RoutedEventArgs e) { if (IsolatedStorageSettings.ApplicationSettings. Contains(“settingKey”)) { IsolatedStorageSettings.ApplicationSettings. Remove(“settingKey”); } } In Code Snippet 3, the saved setting is accessed directly from the ApplicationSettings property and the Remove method is called to delete it.
6.1.3 Reading from Secure Digital (SD) Card You can enable a Windows Phone 8 app to read data from a SD card. To read a specific file format in the SD card, you need to use the Microsoft.Phone.Storage API. Note – SD card is a memory card, which you can use to store digital data. It is used in portable devices,
such as Digital Camera, Tablet PC, and a mobile phone.
The procedure to enable the app to read from a SD card is as follows: 1.
Create a UI in XAML with a Button control named btnGetFileList and a LongListSelector control named LongList1.
2.
Open the Code page of the manifest file, WMAppManifest.XML and add an entry to enable reading from the SD card, as shown in Code Snippet 4.
Concepts
Code Snippet 4: 3.
Register the required file formats to be read from the SD card in the Manifest file, as given in Code Snippet 5. For example, in Code Snippet 5, the file format to be registered is Media Data eXtended (MDX). Note – MDX is a binary file format used for 3D model objects.
V 1.0 © Aptech Limited
Session
6 Data Management in Windows Phone 8
The code in Code Snippet 5 needs to be placed in between the Extensions tag, which is available right below the Tokens element in the Manifest file. Code Snippet 5:
Assets/Route_Mapper_ Logo33x33.png
Assets/Route_Mapper_ Logo69x69.png Assets/Route_Mapper_ Logo176x176.png
.mdx
4.
In the event handler of the button control, provide the code to read the list of files and folders from the SD card, as shown in Code Snippet 6. Code Snippet 6: // Code for accessing the files and folders at the root of SD card private async void btnGetFileList_Click (object sender, RoutedEventArgs e) { ExternalStorageDevice sdCard = (await ExternalStorage. GetExternalStorageDevicesAsync()).FirstOrDefault(); { ExternalStorageFolder sdrootFolder = sdCard.RootFolder; if (sdrootFolder != null) {
V 1.0 © Aptech Limited
Concepts
if (sdCard != null)
6
Session
Data Management in Windows Phone 8 var files = await sdrootFolder.GetFilesAsync(); var folders = await sdrootFolder.GetFoldersAsync(); LongList1.ItemsSource = folders.Select(x => x.Name).ToList(); if (files != null) { foreach (ExternalStorageFile file in files) { LongList1.ItemsSource.Add(file.Name); } } } else { MessageBox.Show(“Failed to get root folder on SD card”); } } else { MessageBox.Show(“SD Card not found on device”); }
Concepts
} In Code Snippet 6, an instance of the class, ExternalStorageDevice is created to establish a connection to the SD card. If the SD card is available, an instance of the class, ExternalStorageFolder, is created and is made to point to the root folder of the SD card. If the root folder is not empty, the folders and the files under the root folder are retrieved one by one. If the root folder is empty or there is no SD card, the required error messages are displayed to the end-user accordingly.
V 1.0 © Aptech Limited
Session
6 Data Management in Windows Phone 8
Figure 6.4 shows the output of the list of folders and files retrieved from the SD card in the Windows Phone 8 app.
Figure 6.4: Reading from a SD Card
In Windows Phone 8, the app can store persistent data in folders, files, and local databases as part of the local folder.
6.2.1 Folders and Files Data, when entered in UI controls, such as a TextBlock in an app, are restricted in scope in terms of size and format. To enable reading or writing large data in different formats, Windows Phone 8 enables
V 1.0 © Aptech Limited
Concepts
6.2 Storing and Accessing Data
Session
6 Data Management in Windows Phone 8
the use of files and folders in the app, which can be stored in the app’s local folder. You can create folders and files in an app and enable input and output operations on them. To perform such file operations in an app, you need to use the StorageFolder class, StreamWriter and StreamReader class, which are part of the System.Windows assembly. The steps to create a folder and a file in Windows Phone 8 are as follows: 1.
Create the UI for the app with two text box controls to accept a folder name and a file name respectively. Create another text box control to accept the textual content for the file. In addition, create a button control and a text block control to display the contents of the file.
2.
Declare the required namespaces to be used for the app project in MainPage.xaml.cs page, as given in Code Snippet 7. Code Snippet 7: using System.IO; using System.Threading.Tasks; using Windows.Storage;
3.
Create the required code for file operations in the event handler of the button control named btnCreateAndReadFile, as shown in Code Snippet 8. Code Snippet 8 contains the code to create a folder and a file. Once the file is created, reading and writing operations are enabled for the file. Code Snippet 8: private void btnCreateAndReadFile_Click(object sender, RoutedEventArgs e) { IsolatedStorageFile isolatedArea = IsolatedStorageFile. GetUserStoreForApplication(); if (!isolatedArea.DirectoryExists(txtFolderName.Text)) isolatedArea.CreateDirectory(txtFolderName.Text); StreamWriter Writer = null;
Concepts
try { Writer = new StreamWriter(new IsolatedStorageFileStream(txt FolderName.Text + “\\” + txtFileName.Text, FileMode.OpenOrCreate, isolatedArea)); Writer.WriteLine(txtFileContent.Text);
V 1.0 © Aptech Limited
Session
6 Data Management in Windows Phone 8 Writer.Close();
} catch { MessageBox.Show(“File could not be created!”); } StreamReader Reader = null; try { Reader = new StreamReader(new IsolatedStorageFileStrea m(txtFolderName.Text + “\\” + txtFileName.Text, FileMode.Open, isolatedArea)); string textFile = Reader.ReadToEnd(); tbFileData.Text = textFile; Reader.Close(); } catch { MessageBox.Show(“File is not created”); } In Code Snippet 8, an instance of the class IsolatedStorageFile is created to store the new folder and the file. The new folder and the file are created based on the inputs entered by the user in the text boxes, txtFolderName and txtFileName. Once the file is created, it is opened for editing/writing using the StreamWriter object and the text entered by the user in the text box, txtFileContent, is written onto it. Finally, the contents of the file are accessed using the StreamReader object and displayed to the user in a text block.
V 1.0 © Aptech Limited
Concepts
}
Session
6 Data Management in Windows Phone 8
Figure 6.5 shows the output of the app based on Code Snippet 8.
Figure 6.5: Folder and File Operations in an App
Concepts
6.2.2 Using the Local Database Most of the applications that deal with relational data would require a back-end database to connect to for saving, retrieving, or updating various details. To facilitate such data operations for an app, Windows Phone 8 provides a local database as part of the local folder for each app. The local database, though similar to SQL Server, provides only limited capabilities according to the restrictions of Windows Phone 8 in terms of resource usage and space availability.
V 1.0 © Aptech Limited
Session
6 Data Management in Windows Phone 8
Note – Unlike other client server databases, a local database is available only for exclusive use of a
particular app. In addition, the local database cannot run separately as a background task, since it is part of the app’s process. Hence, any database-related operation should be performed only when the app is in the running state.
To create a local database and perform querying of data for the app, you need to use the object model, Language-Integrated Query (LINQ) to Structured Query Language (SQL). LINQ to SQL is available as part of .NET framework 3.5, which enables other .NET languages to interact with a database. LINQ to SQL provides an object called data context, which is used to represent a database. The data context contains Table objects that map to the tables in the database. The Table objects in turn have entities that represent rows and attributes or properties that represent the columns in a table. In short, a data context object is used for the following purposes: ÎÎ
To establish a connection with the database
ÎÎ
To submit and retrieve objects to and from the database
ÎÎ
To convert objects to SQL queries and vice versa
You will now understand the complete procedure to create a local database, add data, and display the details to the end-user. In this example, the local database is used to store a few basic details of employees in an organization. 1.
Create the UI for the app with a Button control named btnGetEmployees and a LongListSelector control named LongList1.
2.
Create a namespace and a class in MainPage.xaml.cs that maps to the table in the database, as shown in Code Snippet 9. Code Snippet 9: // Declare the required namespaces for using Linq to SQL using System.Data.Linq; using System.Data.Linq.Mapping; using System.ComponentModel; using System.Collections.ObjectModel;
Concepts
namespace Session6 { [Table] public class Employee { public Employee() { }
V 1.0 © Aptech Limited
Session
6 Data Management in Windows Phone 8 public Employee(int id, string name) { this.EmpId = id; this.EmpName = name; } private int _empId; [Column(IsPrimaryKey = true, IsDbGenerated = true, DbType = “INT NOT NULL Identity”, CanBeNull = false, AutoSync = AutoSync.OnInsert)] public int EmpId { get { return _empId; } set { if (_empId != value) { _empId = value; } } } private string _empName; [Column]
Concepts
public string EmpName { get
{
return _empName;
}
set { if (_empName != value)
V 1.0 © Aptech Limited
6
Session
Data Management in Windows Phone 8 { _empName = value;
} } } } 3.
Create a data context class to establish a communication with the database, as shown in Code Snippet 10. Code Snippet 10: public class EmployeeDataContext : DataContext { public static string DBConnectionString = “Data Source=isostore:/ Employee.sdf”; public EmployeeDataContext(string connectionString) : base(connectionString) {} public Table Employees; } }
4.
Add the code given in Code Snippet 11 in the constructor of the app class to create a new database. Code Snippet 11: using (EmployeeDataContext db = new EmployeeDataContext(EmployeeData Context.DBConnectionString)) { if (!db.DatabaseExists()) db.CreateDatabase(); } } In Code Snippet 11, a new database is created for the app, if it is not already available.
V 1.0 © Aptech Limited
Concepts
{
Session 5.
6 Data Management in Windows Phone 8
Declare the object reference of the data context, EmployeeDataContext, in the main app class, as shown in Code Snippet 12. Code Snippet 12: private EmployeeDataContext empDB;
6.
Add the code for the event handler of the button control in MainPage.xaml.cs, as shown in Code Snippet 13. Code Snippet 13: private void btnGetEmployees_Click(object sender, RoutedEventArgs e) { employees = new List(); empDB = new EmployeeDataContext(EmployeeDataContext. DBConnectionString); List employees = new List(); employees.Add(new Employee(1, “Frank”)); employees.Add(new Employee(2, “Dan”)); empDB.Employees.InsertAllOnSubmit(employees.AsEnumerable()); empDB.SubmitChanges(); var employeesInDB = from Employee emp in empDB.Employees select emp; LongList1.ItemsSource = employeesInDB.Select(x => x.EmpId. ToString() + “\t” + x.EmpName).ToList(); }
Concepts
In Code Snippet 13, a sample list of employee names and their IDs are added to the table in the database. This list of employee details is then retrieved from the database and displayed to the end-user in the app.
V 1.0 © Aptech Limited
Session
6 Data Management in Windows Phone 8
Figure 6.6 shows the output of the app based on the discussed procedure.
Figure 6.6: Creating a Local Database in an App
Besides accessing persistent data, an app can access external data from other apps or Web servers through the use of Web services. In order to transfer such data from a Web server to a Windows Phone 8 app, there are various standard language formats available, such as Extensible Markup Language (XML) and JavaScript Object Notation (JSON). These language formats enable smooth interchange of data over Internet. Note – A Web service is a software function that is created and exposed for use over the Internet. The
Web service runs on a Web server and uses a standard language format, such as XML, for transfer of data. You will now understand how to use a Web service named Weather to retrieve external data and display in the app by using XML format.
V 1.0 © Aptech Limited
Concepts
6.3 Consuming Data from Web Services
Session
6 Data Management in Windows Phone 8
The steps to consume a Web service for the app are as follows: 1. Create the UI for the app with a button control named btnInvokeService. 2. Right-click the name of the project and click Add Service Reference. The Add Service Reference dialog box appears. 3. Enter the URL of the required Web service to be used. Here, you will enter http://wsf.cdyne. com/WeatherWS/Weather.asmx. Note – CYDNE is a Website that provides various free and commercial Web services to the
global audience. The ‘CYDNE Weather’ is one of the free Web services offered by the Website to provide weather information for the United States of America (USA) based on the Zip code. The Web service retrieves the weather information from the National Oceanic and Atmospheric Administration’s weather service and converts it into XML format for easy use over the Internet. 4. Click Go. 5. Type the name of the service reference as WeatherService in the Namespace box. 6. Click OK.
7. Add the code for the event handler of the button control in MainPage.xaml.cs, as shown in Code Snippet 14. Code Snippet 14: private void btnInvokeService_Click(object sender, RoutedEventArgs e) { WeatherService.WeatherSoapClient client = new WeatherService. WeatherSoapClient(); client.GetCityForecastByZIPCompleted += new EventHandler(client_GetCityForecastByZIPCompleted); client.GetCityForecastByZIPAsync(“32007”); } void client_GetCityForecastByZIPCompleted(object sender, WeatherService.GetCityForecastByZIPCompletedEventArgs e)
Concepts
{ tbWebserviceData.TextWrapping = TextWrapping.Wrap; tbWebserviceData.Text = “City : “ + e.Result.City + “\n” + “Zip : 32007 \nWeather Description : “ + e.Result.ForecastResult. FirstOrDefault().Description; }
V 1.0 © Aptech Limited
Session
6 Data Management in Windows Phone 8
In Code Snippet 14, a Web client service is created for the Web service reference, WeatherService, based on Simple Object Access Protocol (SOAP) service. The data from the Web service, such as City, Zip code, and Weather Description are retrieved from the Web service and displayed to the end-user in the app. Note – SOAP is an XML-based protocol that specifies how data can be transmitted from a Web
service in a structured form.
Figure 6.7 shows the output of the app.
6.4 Overview of Windows Phone 8 Application Life Cycle Once an app is complete in terms of UI creation, functionality, and data management, you need to test and deploy the same in a Windows Phone 8 device. For this purpose, you need to understand how an app functions in Windows Phone 8. The various stages that an app goes through right from the time it is launched on the Windows Phone 8 screen till the time it is closed out of memory are referred to as the Application Life Cycle.
V 1.0 © Aptech Limited
Concepts
Figure 6.7: Using Web Service in Windows Phone 8 App
Session
6 Data Management in Windows Phone 8
At any point in time, only one app will be active and running in the foreground in Windows Phone 8 device. All the other tasks will be in background in a deactivated state. It is because the mobile Operating System (OS) has a limited memory when compared to the regular OS and hence, most part of the memory would be made available to the single active app to enable faster user experience. An app goes through three different states in the Application Life Cycle depending on the events generated on it. The states in the Application Life Cycle are as follows: 1.
Running State When the app is launched, it is available in the Running state. It will continue in this state when the user navigates forward or backward, within the pages of the app.
2.
Dormant State When the app is deactivated, it usually gets into the dormant state. In this state, the app moves to the background with all the changes saved intact. It will remain in the memory until it is brought back to activation.
3.
The Tombstoned State When the user performs any high intensive resource consuming tasks after deactivating an app, there is a possibility that the deactivated dormant app might move to the tombstoned state. In this state, the app would be terminated after saving the changes to the app in an object called the State. The State object is a dictionary that serves as a storage area to store the state of an app.
The events associated with the Application Life Cycle are as follows: 1.
Launching Event When the user invokes an app in Windows Phone 8 through Live Tiles, or Live Apps, or by tapping a Notification icon, it will lead to the Launching event of the app. The Launching event displays the app’s Home Page to the user.
Concepts
2.
3.
As a developer, you need to avoid loading network files and other resources that take a longer time to be uploaded on the screen in this event handler. This event sets the app in its Running state. Deactivated Event
When the user navigates away from the app by moving forward or by moving backward beyond the app’s first page or by launching another application, it will lead to the Deactivated event of the app. This event will also be generated when the lock screen is enabled after a set idle time in Windows Phone 8. This event sets the app in its dormant or tombstoned state. Activated Event
When the user returns to the app at a later point in time, it will lead to the Activated event of the app. As a developer, you need to provide the code to retrieve the saved changes either from the app’s saved data in case of dormant state or from the State dictionary in case of tombstoned state, in this event handler.
V 1.0 © Aptech Limited
Session 4.
6 Data Management in Windows Phone 8
Closing Event When the user navigates beyond the first page of the app, it will lead to the Closing event of the app. When this event is raised, the app is terminated and the state of the app is not preserved in memory. As a developer, if you want to save some persistent data that should be made available for all the future instances of the app, you need to code the data to be saved, in this event handler. Note – The Closing event will not be called when the app is terminated directly from the
Figure 6.8: Application Life Cycle
V 1.0 © Aptech Limited
Concepts
tombstoned state. Figure 6.8 shows a diagrammatic representation of the various stages and the events that are part of the Application Life Cycle of an app.
Session
6 Data Management in Windows Phone 8
6.5 Modifying Idle Detection Behavior The lock screen mode of Windows Phone 8 is similar to the ‘Screen Saver’ option in Windows Desktop. The lock screen mode is used to save power consumption when the device is not in use. Idle detection in Windows Phone 8 is automatically enabled when the user has set the lock screen mode to ‘ON’. As an app developer, you need to check if such idle detection and lock screen will interfere with the app’s functionality while it is running in foreground or background. This check is especially useful for apps that need to run continuously without interruption, such as music app, video app, and app that accesses network content. There are two types of idle detection – app-based idle detection and user-based idle detection. ÎÎ
App Idle Detection In the current version of Windows Phone 8, the app idle detection is enabled whenever the lock screen is engaged in the device. During idle detection, Windows Phone 8 will identify all the apps that are not up and running (deactivated state) and will push them into the idle state. As a developer, if you want to disable app idle detection for the app, you need to change the value of the property, ApplicationIdleDetectionMode to Disabled in C#. This property is part of an app’s PhoneApplicationService class of the Microsoft.Phone assembly. Note – Do not use app idle detection for faster recovery of the app from the deactivated state.
Remember that this option has no impact on the performance of the app while on the contrary, will only lead to unnecessary battery drain and memory wastage. ÎÎ
User Idle Detection In the current version of Windows Phone 8, the user idle detection is enabled whenever the user does not interact with the device for a certain period. The idle detection timeline is set in the Settings page of the device. During user idle detection, Windows Phone 8 will identify all the apps that are not up and running (deactivated state) and will push them into the idle state.
Concepts
To disable user idle detection for the app, you need to change the value of the property, UserIdleDetectionMode to Disabled in C#. This property is part of an app’s PhoneApplicationService class of the Microsoft.Phone assembly. You can disable this option for some of the gaming apps and apps with multiple pages that require constant user intervention for input and navigation. This option, similar to app idle detection, should be used with caution, as it will lead to unnecessary drain of the resources. Note – Disabling idle detection in Windows Phone 8 will ensure that the app continues to run even
when the lock screen is engaged and consumes more Phone memory. However, the app might still close if there is low memory, low battery, and such other unplanned scenarios.
V 1.0 © Aptech Limited
Session
6 Data Management in Windows Phone 8
6.6 Enabling Fast Resume for Apps One of the very first criteria to promote best user experience in Windows Phone 8 is to load an app selected by the user, at a great speed. In general, when a user loads an app for the first time, the time taken to create a new instance of the app would be a little longer based on various factors associated with memory and network access of the device. However, the same app, when it is resumed from a Dormant state or a Tombstoned state, the reloading of the existing instance of the app back to its active state is much faster. Such a process is referred to as Fast Application Switching (FAS). There is a possibility to provide FAS experience right at the first time an app is launched. Such a feature is called Fast Resume. This feature is available for XAML-based apps, Direct3D apps, and Direct3D with XAML apps. To enable Fast Resume for the app: 1. Open the required project in Visual Studio. 2. Right-click WMAppManifest.xml. A shortcut menu is displayed. 3. Click Open with, and then select XML (Text) Editor. The WMAppManifest.XML will be opened for editing. 4. Include the ActivationPolicy attribute as part of the DefaultTask XML element and set its value to ‘Resume’ as shown in Code Snippet 15. Code Snippet 15:
The Fast Resume feature is enabled for the selected app with this simple procedure. ÎÎ
Optimal Considerations for Fast Resume for Apps Generally, Windows Phone 8 stores the navigation history of the pages in an app visited by the user, in memory. While launching an app in Fast Resume, as a developer, you can use two choices:
1. Launching a new instance of the app based on the previous navigation history stored in back stack
To decide which choice would be ideal, you need to determine the time difference between the old launch and the new launch. If the duration is very short, you can load the app by including the new instance of the Home page on the top of the previous back stack. If the duration is long, you can load the app as a fresh instance with its Home page by clearing the back stack. As a developer, you also need to consider how the user launches the app in Windows Phone 8, to load a particular page in an app. There are two different launch points available to launch an app
V 1.0 © Aptech Limited
Concepts
2. Launching a new instance of the app without reference to the previous navigation history by clearing the back stack
Session
6 Data Management in Windows Phone 8
as follows: yy
The primary launch point is used when the user launches an app from the Start screen, Live Tiles, or Live Apps. In this case, a new instance of the app is created and displayed to the user. Based on the time lapse, you can determine to present the user with the following choices of app launch:
yy
The resumed instance of the previous state of the app, which would be the last active page of the previous session
A fresh instance of the Home page of the app, which would still maintain the previous navigation history at the bottom of the back stack
The deep link is used when the user navigates to a specific page in an app from a secondary menu, such as a secondary tile icon or a notification icon. In this case, it is advisable to load a fresh instance of the specific page of the app as the user wants to move to the respective page directly. The new instance should be loaded in the back stack and the previous navigation history stored in the back stack should be cleared. Note – In some cases, the page to be loaded as a fresh instance may coincidentally be
the same as the page saved in the back stack of the previous instance. This will only lead to reloading the previous instance of the same page from the top of the stack and a new instance will not be created. However, the page after being reloaded will be refreshed once to provide a better user experience. To navigate to the respective page of the app for creating a new instance in Fast Resume, you can use the various navigation methods available as part of the PhoneApplicationPage class in C#.
6.7 Simulation Dashboard The final step in Windows Phone 8 app development is to test and deploy the app for individual use or commercial use.
Concepts
Windows Phone (WP) Emulator is one way to test and debug apps created in XAML and C#. However, WP Emulator does not test an app for any real-world contingent scenarios, such as low memory and slow network connection. If such contingencies are not tested and the app is directly deployed on the Windows Phone device, there is a possibility that the app could crash or could lead to loss of the desired functionality. This will lead to bad user experience and the resultant negative feedback on the app’s popularity. To simulate such real-world problem scenarios for testing an app, you need to use the Simulation Dashboard available in Visual Studio. The Simulation Dashboard provides various options to validate the app based on various real-world conditions. With the result of such validation, you can modify the app’s functionality or UI to promote a better performance for the end-users.
V 1.0 © Aptech Limited
Session ÎÎ
6 Data Management in Windows Phone 8
Testing an App using Simulation Dashboard
1. To invoke the Simulation Dashboard in Visual Studio, click Simulation Dashboard on the Tools menu.
Figure 6.9: Simulation Dashboard Window 2.
Open the desired project to be tested in Visual Studio.
3.
Press F5 to test the app in debugging mode. Otherwise, press CTRL+F5 to test the app in normal mode.
4.
Select the required options to be tested.
V 1.0 © Aptech Limited
Concepts
The Simulation Dashboard window is launched as shown in figure 6.9 and is available for all the projects in Visual Studio. Notice that the options related to network speed, Internet signal strength, and lock screen are available as part of the window to perform the required real-world scenario testing.
Session
6 Data Management in Windows Phone 8
Concepts
According to the results of the testing, you need to make necessary changes to the code for performance tuning, after which the app would be ready to be deployed and used.
V 1.0 © Aptech Limited
Session
6 Data Management in Windows Phone 8
6.8 Check Your Progress 1.
The _______________ is the read-only folder that contains all the files of the app package. (A) Local folder (B) Media library
(C) Installation folder (D) Shared folder
2.
The ___________ class is used to access data from a text file. (A) StorageFolder
(C)
(B) StreamReader
3.
StreamWriter
(D) CreateDirectory
Which of these statements regarding local database is true and which is false? Statement A: A local database is commonly shared by all the apps in Windows Phone 8. Statement B: A Data Context object is used to represent a local database in LINQ to SQL. Statement A is TRUE and (C) Both the statements are TRUE. Statement B is FALSE. Statement A is FALSE and (B) (D) Both the statements are FALSE. Statement B is TRUE.
(A)
4.
5.
To consume a Web service, you need to create a _____________ in the required Windows Phone 8 project. (A) Web service URI
(C)
Service reference
(B) Web server URI
(D) Shared folder
Which of the following options would you change to ‘disabled’ to disable user idle detection in Windows Phone 8? (A)
The Lock Screen mode in Phone settings
UserIdleDectionProperty in XAML
(D) AppIdleDetectionMode in C#
Concepts
(B) UserIdleDetectionMode in C#
(C)
V 1.0 © Aptech Limited
Session 6.
6 Data Management in Windows Phone 8
Which of these statements regarding Fast Resume for apps is true and which is false? Statement A: You can enable Fast Resume feature for your app by changing the property setting in the WMAppManifest.XAML file. Statement B: You can disable app idle detection to promote Fast Resume for the app. (A)
Statement A is TRUE and Statement B is FALSE.
(C)
(B)
Statement A is FALSE and Statement B is TRUE.
(D) Both the statements are FALSE.
Concepts
Both the statements are TRUE.
V 1.0 © Aptech Limited
Session
6 Data Management in Windows Phone 8
6.8.1 Answers C
2.
B
3.
B
4.
C
5.
B
6.
D
Concepts
1.
V 1.0 © Aptech Limited
Session
6 Data Management in Windows Phone 8
Summary A Windows Phone 8 app can use persistent data that resides on the phone or external data from a Web service or an external storage medium.
ÎÎ
Windows Phone 8 provides various tools, storage areas, and APIs to save as well as access data easier and faster.
ÎÎ
The app data to be saved in the form of an object or a string as a key/value pair is called setting.
ÎÎ
You can create files, folders, and local databases for saving and accessing data for the app.
ÎÎ
The various stages that an app goes through right from the time it is launched on the Windows Phone 8 screen until the time it is closed completely are referred to as Application Life Cycle.
ÎÎ
Windows Phone 8 idle detection behavior for app and user can be disabled for certain apps that need to continuously run without interference of the lock screen.
ÎÎ
Fast Resume is a feature that can be used to load the app every time at high speed to promote better user experience.
ÎÎ
The Simulation Dashboard provides various options to validate the app based on various realworld conditions.
Concepts
ÎÎ
V 1.0 © Aptech Limited