developing advanced windows store apps -ii_intl.pdf

175
Advanced Windows Store Apps Development - II

Upload: il-louis

Post on 22-Nov-2015

44 views

Category:

Documents


9 download

TRANSCRIPT

  • Advanced Windows Store Apps Development - II

  • Advanced Windows Store Apps Development - II

    Learners Guide

    2014 Aptech Limited

    All rights reserved.

    No part of this book may be reproduced or copied in any form or by any means graphic, electronic or mechanical, including photocopying, recording, taping, or storing in information retrieval system or sent or transferred without the prior written permission of copyright owner Aptech Limited.

    All trademarks acknowledged.

    APTECH LIMITED

    Contact E-mail: [email protected]

    First Edition - 2014

  • Dear Learner,

    We congratulate you on your decision to pursue an Aptech course.

    Aptech Ltd. designs its courses using a sound instructional design model from conceptualization to execution, incorporating the following key aspects:

    Scanning the user system and needs assessment

    Needsassessmentiscarriedouttofindtheeducationalandtrainingneedsofthelearner

    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.

    Theskill requirementsarethenmappedwith the learnerprofile(usersystem)toderivetheLearning 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 (trainingmethodology),instructionalactivitiesandinstructionalmaterials.

    TheareaofITisfastchangingandnebulous.Henceconsiderableflexibilityisprovidedintheinstructional 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 theaspects, which are incorporated, in the instructional process.

    Assessment of learning

    The learning is assessed through different modes tests, assignments & projects. The assessmentsystemisdesignedtoevaluatethelevelofknowledge&skillsasdefinedbythelearning objectives.

    Evaluation of instructional process and instructional materials

    The instructional process is backed by an elaborate monitoring system to evaluate - on-time delivery, understanding of a subject module, ability of the instructor to impart learning. As an integral part of this process, we request you to kindly send us your feedback in the reply pre-paid form appended at the end of each module.

    *TAG Technology & Academics Group comprises members from Aptech Ltd., professors from reputed Academic Institutions, Senior Managers from Industry, Technical gurus from Software Majors & representatives from regulatory organizations/forums.

    Technology heads of Aptech Ltd. meet on a monthly basis to share and evaluate the technology trends. The group interfaces with the representatives of the TAG thrice a year to review and validate the technology and academic directions and endeavors of Aptech Ltd.

    IndustryRecruitmentProfileSurvey -The IndustryRecruitmentProfileSurveywasconductedacross 1581 companies in August/September 2000, representing the Software, Manufacturing, Process Industry, Insurance, Finance & Service Sectors.

  • Scanning the user system and needs

    assessment

    Evaluation of Instructional Processes and

    Material

    Need Analysis and design of curriculum

    Assessment of learning

    Design and development of instructional

    material

    Strategies for delivery of

    instructions

    Key Aspects

    Aptech New Products Design Model

    1

    2

    34

    5

    6

  • The book aims to provide students with the skills to develop basic and advanced Windows Store apps.

    This book begins with introducing Windows Store app development and describes animations and transitions. The book also describes, transforms and the advantage of using Windows Runtime animation library. The concept and implementation of localization is also covered in the book. The book also explains about extending splash screens. The book further discusses creating and using custom controls and WinRT controls. The book then moves on to the concepts of contracts, printing settings, and PDF conversion classes. It also teaches speech synthesis and acquaints the users with speech synthesis classes.

    With Windows 8 and later versions, Microsoft had added some of the cloud computing features such as NotificationServiceandMicrosoftWindowsNotificationServiceChannel.Usingthesefeatures,theuserscancreate,send,request,andsavesuchnotificationsonthecloud.Intodaysworld,multimediaisatthebase of all. Pictures, audio, and video are very much in demand. Windows Store apps allows the users to embed these multimedia features in their applications. This book provides the knowledge about all these multimedia extensions to the existing programming world.

    This book is the result of a concentrated effort of the Design Team, which is continuously striving to bring you the best and the latest in Information Technology. The process of design has been a part of the ISO 9001certificationforAptech-ITDivision,EducationSupportServices.AspartofAptechsqualitydrive,this team does intensive research and curriculum enrichment to keep it in line with industry trends.

    We will be glad to receive your suggestions.

    Design Team

    Preface

  • Sessions1. Background Task

    2. Device Capabilities

    3. Generating Revenue Apps

    4. DevelopingUniversalApps

    5. Managing Windows and Web Authentication

    6. Securing Windows Store App Data

    7. Diagnosing Problems and Monitoring Applications

    Table of Contents

  • Background Task

    Session - 1

    Welcome to the Session, Background Task.

    This session introduces you to creating and consuming background tasks for the Windows Store Apps.

    In this Session, you will learn to:

    Create a Background Task

    Consume a Background Task

  • V 1.0 Aptech Limited

    1Background Task

    Con

    cept

    s

    1.1 What is Background Task?In old Windows versions, it was possible to run multiple applications on the desktop without disturbing each other. However, with Windows Store Apps, things have changed. If an app is not running actively and is not currently visible on the screen, it is suspended by the operating system. Windows automatically suspends the app that is not active at present. If an app needs to perform certain periodic activities after an interval, it is very difficult to keep such application running and alive in the memory. To overcome this difficulty, the WinRT libraries include a collection of classes called background tasks. These tasks can be used to construct a workflow that will work with the new life cycle of an app. Background Tasks are used when no user interaction is needed.

    A background task is a class that implements an interface called IBackgroundTask which is available in the namespace called Windows.ApplicationModel.Background.The IBackgroundTask includes a single method called Run. This method returns an object called IBackgroundTaskInstance and it allows the task to interact with the current running process. This task remains alive in the memory as a thread that can communicate with app when it is reloaded in the memory. Thus, using BackgroundTask, it becomes easy to share the data or continuously run an activity in the background without requiring the app to remain active on the screen.

    There are certain conditions or options that can be set for a background tasks. Using these options, the developer can control the behavior of the task that is running in the background. These conditions are defined by an enumerator class known as SystemConditionType. The SystemConditionType has following options available in it:

    InternetAvailable/InternetNotAvailable Checks if the Internet is available or not

    SessionConnected/SessionNotConnected Checks if the session connected or disconnected

    UserPresent/UserNotPresent Checks if user available or unavailable To understand the Background Tasks, it is necessary to understand the concept of threading in Windows Store apps. Users might be aware of what is threading, but to recap the knowledge here is brief introduction to threading.

    1.2 What is Threading?Threading allows running multiple tasks within a single process. The main thread can be forked into multiple sub threads called tasks. The two types of thread concepts available to execute in the app are a UI thread and a background thread. The thread pool will queue the threads and are configured and designed to start execution automatically whenever the processor needs it. The thread pool is same as the asynchronous programming, which is available under Windows Runtime. The next thread in the queue will start when the execution of first thread is complete. The user can use timer inside the app to specify the interval time to the thread through code.

  • V 1.0 Aptech Limited

    1Background Task

    Con

    cept

    s

    Figure 1.1 shows the life cycle of a thread in the Windows Store App.

    Figure 1.1: Thread Life Cycle

    As shown in figure 1.1, it can be seen that when an app is launched, initialized and the control is passed on to the UI thread. After UI thread is over, the control will be passed to background task if it exists. Either the termination stage can close the app or it again reloads the app by going to initialize stage.

    Note - The developer can use CreatePeriodicTimer to run the thread repeatedly.

    1.2.1 Create and Register a Background Task Similar to a thread, a background task is a function that runs in the memory of an app without disturbing the normal execution of other apps. Background task can execute the code in the memory without making the app active. This is not possible to execute using UI tasks. Therefore, the background tasks are very important when it comes to running some tasks that will perform some actions in the background after certain interval.

    Background tasks will be necessary in the following situations:

    When some streaming audio is to be played.

    A Live Tile needs to update new data from the server.

    A Push Notification pops up when the notification is sent or received.

    A Lock screen updates when a device is locked or unlocked.

    In case of such situations, it is not possible to launch an app and keep it running continuously on the screen. This activity needs to run in the background without coming to front end or without showing the UI. In these cases the best solutions is to create and run a background task. The user can create a class based on interface IBackgroundTask and implements its method called Run().

  • V 1.0 Aptech Limited

    1Background Task

    Con

    cept

    s

    Here is a basic implementation of IBackgroundTask:public class SimpleBgTask : IBackgroundTask{ public void Run(IBackgroundTaskInstance taskInstance) { // Insert code to perform some activities here }}When an app is registered to run in the background at a periodic interval, it is necessary to assign such an app to a single trigger that will decide when and how often this app should be executed in the background. There are five types of triggers that can be assigned to the current task. These triggers will automatically start execution of the background task. These triggers are shown in table 1.1.

    Trigger DescriptionControl channel This is activated when Incoming message is received on a control channel

    (socket)

    Push notification It is activated when the Raw notification is received from Windows Push Notification Services

    Audio This is a trigger for Audio eventsTimer This activates when the Timer event occursSystem event This is activated and responds to a predefined system eventLocation This activates when the user location changes or updates

    Table 1.1: Types of Triggers for Background Tasks

    To register a background task in an app, the user has to enable background tasks in the Package.appxmanifest file as shown in figure 1.2.

    Figure 1.2: Selecting Background Tasks from the Declarations Tab

  • V 1.0 Aptech Limited

    1Background Task

    Con

    cept

    s

    Select the System Event property as shown in figure 1.3.

    Figure 1.3: Enable System event inside Background Tasks

    1.2.2. Respond to System Events with Background Tasks The background task can made to respond to the user through system events. The user has to declare the Entry point in the app manifest file by selecting the background task from the declaration tab as shown in figure 1.4.

    Figure 1.4: Selecting the Background Task from the Declaration Tab

  • V 1.0 Aptech Limited

    1Background Task

    Con

    cept

    s

    To register the Background Task the user has to write the code shown in Code Snippet 1.

    Code Snippet 1:

    private void RegisterBackgroundTask(string n, string p){ BackgroundTaskBuilder b = new BackgroundTaskBuilder(); b.Name = n; b.TaskEntryPoint = p; b.SetTrigger(new SystemTrigger(SystemTriggerType.InternetAvailable, false)); BackgroundTaskRegistration t = b.Register();}

    Create a function fnChkReg() to check whether the task is registered or unregistered by writing the code shown in Code Snippet 2.

    Code Snippet 2:

    private void fnChkReg() { foreach (var task in BackgroundTaskRegistration.AllTasks) { if (task.Value.Name == Update) { isRegistered = true; break; } } if (isRegistered) { RegisterButton.Content = Unregister; lblResult.Text = Task Registered; } else if (!isRegistered) { RegisterButton.Content = Register; lblResult.Text = Task UnRegistered; } }

  • V 1.0 Aptech Limited

    1Background Task

    Con

    cept

    s

    1.2.3 Set Conditions for Running a Background TaskThe user has to know how to check the conditions and apply them for the background task. These conditions are checked by using a trigger in the app. For example, if the user has to set the Internet connectivity inside the app, then use the SystemTriggerType called InternetAvailable and set it to either true or false. If the InternetAvailable trigger is set to false, then it minimizes the battery usage. Code Snippet 3 shows how to set the SystemTriggerType for the background task.Code Snippet 3:

    BackgroundTaskBuilder builder = new BackgroundTaskBuilder();builder.Name = nameofbktask;builder.TaskEntryPoint = programname;builder.SetTrigger(new SystemTrigger(SystemTriggerType.InternetAvailable, false));BackgroundTaskRegistration t = builder.Register();

    1.2.4 Handle a Cancelled Background TaskThe background tasks are short running processes, which executes the code and restarts automatically for executing the task again using a timer. The user can cancel any running background tasks if it is not necessary to run at that time. In order to cancel the background task the user has to register for cancellation handler. As the handler is registered, the system stops the async tasks running in the background. To cancel the task the user has to declare the CancellationTokenSource by writing code as shown in Code Snippet 4.

    Code Snippet 4:

    CancellationTokenSource c = new CancellationTokenSource();

    On the OnCancelled method write c.Cancel() to stop the task by writing Code Snippet 5.Code Snippet 5:

    private void OnCancelled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) { c.Cancel(); }

  • V 1.0 Aptech Limited

    1Background Task

    Con

    cept

    s

    1.2.5 Monitor Background Task Progress and CompletionTasks can be monitored by displaying a message in the UI of the app. The user can set the trigger to update the status of the task running. For example, if the user needs to execute task continuously then for every completion of the task, there must be a notification in the UI in the form of a message displayed in a TextBlock as shown in Code Snippet 6.Code Snippet 6:

    if(isRegistered) { RegisterButton.Content = Unregister; lblResult.Text = Task Registered; }if(!isRegistered) { RegisterButton.Content = Register; lblResult.Text = Task UnRegistered; }

    The code displays the status of the task to the user. If the task is registered then the result will display as Task Registered in a TextBlock of the UI.

    1.2.6 Run a Background Task Using a TimerIf the user wants to run the task repeatedly after some interval, then the task can be called using a timer. A class called TimeTrigger is available for this purpose. Create an instance of this class and set necessary properties to make it work. The timer has to be declared in the function as shown in Code Snippet 7.

    Code Snippet 7:

    TimeTrigger t = new TimeTrigger(15, false);

    The user has to set the time to restart the task, as mentioned in Code Snippet 7, the task will execute after every 15 minutes.

    1.3 TriggersTriggers are created in the background task to keep the app stable and to execute the code without disturbing the UI. These triggers are declared with some duration. Thus, the triggers can execute the code periodically after an interval from the background of the app.

  • V 1.0 Aptech Limited

    1Background Task

    Con

    cept

    s

    1.3.1 Maintenance TriggersAs the maintenance trigger occurs, the device will update the task periodically as set by the user in the code. This MaintenanceTrigger can be declared by writing code as shown in Code Snippet 8.Code Snippet 8:

    MaintenanceTrigger t = new MaintenanceTrigger(15, false);

    Note - MaintenanceTrigger will execute only when the device plugged into AC power

    The code shown in Code Snippet 8 will execute the trigger after every 15 minutes.

    1.3.2 Declare Background Tasks in the Application ManifestThe user has to declare the background task in the Package.appxmanifest file. To do so, the user has to right-click the manifest file and select View Code or Press F7 as shown in figure 1.5.

    Figure 1.5: View App Manifest File Code

  • V 1.0 Aptech Limited

    1Background Task

    Con

    cept

    s

    In the application node, write the code to mention the extension for the background task.

    To apply the Background Task extension in the manifest file, the user has to write the code as shown in Code Snippet 9 in the application tag.

    Code Snippet 9:

    The code declares a background task with an entry point as Tasks.Update.

    1.3.3 Guidelines and Checklists for Background TasksGuidelines:

    The user has to follow the guidelines while developing the app.

    1. CPU and Network Quotas

    The user has to maintain the CPU or Network usage limit, as it should not exceed.

    2. Manage Background Tasks

    The app must be written in such a way that each task must be updated in the event entry, so that the system log helps the user to find error in the app.

    3. Update App Manifest

    The user has to ensure that all the background tasks are declared in the app manifest file whenever they are created along with the trigger type.

  • V 1.0 Aptech Limited

    1Background Task

    Con

    cept

    s

    Checklist:

    1. Point the correct trigger for each background task.

    2. Maintain conditions to check the status while the background tasks are running.

    3. Except Tile, Toast or Badge notifications, the user need not display any info in the UI of the app.

    4. There should not be any user interaction in the background task.

    5. The background task should not be dependable on the user.

    6. Using Maintenance Trigger, check for Registration errors.

    1.3.4 How to Debug a Background Task?The user can debug the code to check the status of the code, if the code is successfully executing or intervening errors in the task. To check, the user has to select the desired option such as suspend, resume, suspend and shutdown, update as shown in figure 1.6.

    Suspend option halts the task at that point of time and can be resumed as the user selects the resume option as shown in figure 1.6.

    Figure 1.6: Debug Menu

    As the code is suspended, the user can navigate to Event Viewer to view the system logs of the tasks. Press Win + R key to open the run command. Type eventvwr.exe and press Enter to open the event viewer as shown in figure 1.7.

    Figure 1.7: Run Command

  • V 1.0 Aptech Limited

    1Background Task

    Con

    cept

    s

    When the Event Viewer window is opened the user has to navigate to

    Application and Services Logs Microsoft Windows BackgroundTaskInfrastructure

    To view the debug logs, the user has to select Show Analytic and Debug Logs option from the view menu as shown in figure 1.8.

    Figure 1.8: Enable Show Analytic and Debug Logs

    The user can now view the Diagnostic menu in the left tree menu as shown in figure 1.9. Select the Diagnostic Menu and select Enable Log option to record all the logs of the background task.

    Figure 1.9: Enable Log

  • V 1.0 Aptech Limited

    1Background Task

    Con

    cept

    s

    Now, run the code by resuming and click the Register button to register the background task as shown in figure 1.10.

    Figure 1.10: Register the App

    Open the event viewer and refresh the diagnostic menu to view the log created inside. To view the log, select the log created and then the user can view the description of the log, as shown in figure 1.11.

    Figure 1.11: View the Event Description

  • V 1.0 Aptech Limited

    1Background Task

    Con

    cept

    s

    Exercise 1: Register Background Task

    Step 1: Create a blank new project as shown in figure 1.12.

    Figure 1.12: Create a Blank New Application

    Step 2: Open the app manifest file and navigate to Declaration tab. Now, select the Background Task from the available declarations as shown in figure 1.13.

    Figure 1.13: Select the Declaration

  • V 1.0 Aptech Limited

    1Background Task

    Con

    cept

    s

    Step 3: Enable the System event from the Background Task Declaration as shown in figure 1.14.

    Figure 1.14: Enable System Event

    Step 4: Declare the entry point for the app to run the Background Task as shown in figure 1.15.

    Figure 1.15: Declare the Entry Point

  • V 1.0 Aptech Limited

    1Background Task

    Con

    cept

    s

    Step 5: Write Code Snippet 10 to create a button and a Text Block.

    Code Snippet 10:

  • V 1.0 Aptech Limited

    1Background Task

    Con

    cept

    s

    Step 6: Write Code Snippet 11 in the code behind file.

    Code Snippet 11:

    bool isRegistered = false; protected override void OnNavigatedTo(NavigationEventArgs e) { fnChkReg(); }// To check the status of the task whether registered or unregistered private void fnChkReg() { foreach (var task in BackgroundTaskRegistration.AllTasks) { if (task.Value.Name == Update) { isRegistered = true; break; } }

    if (isRegistered) { RegisterButton.Content = Unregister; lblResult.Text = Task Unregistered; } else if (!isRegistered) { RegisterButton.Content = Register; lblResult.Text = Task Registered; } }

  • V 1.0 Aptech Limited

    1Background Task

    Con

    cept

    s

    Step 7: Write Code Snippet 12 to register the Background Task using System Event.

    Code Snippet 12:

    private void RegisterBackgroundTask(string n, string p) { BackgroundTaskBuilder b = new BackgroundTaskBuilder(); b.Name = n; b.TaskEntryPoint = p; b.SetTrigger(new SystemTrigger(SystemTriggerType.InternetAvailable, false)); BackgroundTaskRegistration t = b.Register(); } private void UnregisterBackgroundTask(string name) { foreach (var t in BackgroundTaskRegistration.AllTasks) { if (t.Value.Name == name) { t.Value.Unregister(true); } } } private void RegisterButton_Click(object sender, RoutedEventArgs e) { if (isRegistered) { UnregisterBackgroundTask(Update); isRegistered = false; } else { RegisterBackgroundTask(Update, BackgroundTasks.Update); } fnChkReg(); }

  • V 1.0 Aptech Limited

    1Background Task

    Con

    cept

    s

    Step 8: Output screen is seen when the app is executed by pressing F5 button, as shown in figure 1.16.

    Figure 1.16: Output When Executed

    Step 9: When the user clicks the Register button, the task is registered in the system event and is ready to execute the background process, as shown in figure 1.17.

    Figure 1.17: Output When Task is Registered

  • V 1.0 Aptech Limited

    1Background Task

    Con

    cept

    s

    Step 10: When the user clicks the UnRegister button, the task is unregistered by creating a log in the system event, as shown in figure 1.18.

    Figure 1.18: Output When Task Is Unregistered

    Exercise 2: Background Task Timer

    Step 1: Create a blank new project as shown in figure 1.19.

    Figure 1.19: Create a Blank New Application

  • V 1.0 Aptech Limited

    1Background Task

    Con

    cept

    s

    Step 2: Write Code Snippet 13 to create a button and a Text Block.

    Code Snippet 13:

  • V 1.0 Aptech Limited

    1Background Task

    Con

    cept

    s

    Step 3: Write Code Snippet 14 in the code behind.

    Code Snippet 14:

    using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Runtime.InteropServices.WindowsRuntime;using Windows.Foundation;using Windows.Foundation.Collections;using Windows.UI.Xaml;using Windows.UI.Xaml.Controls;using Windows.UI.Xaml.Controls.Primitives;using Windows.UI.Xaml.Data;using Windows.UI.Xaml.Input;using Windows.UI.Xaml.Media;using Windows.UI.Xaml.Navigation;

    namespace BackgroundProcessTimer{ public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent(); }DispatcherTimer tmr; int timesTicked = 1; int timesToTick = 100; public void DispatcherTimerSetup() {tmr = new DispatcherTimer(); tmr.Tick += tmr_Tick; tmr.Interval = new TimeSpan(0, 0, 0, 0, 200);

  • V 1.0 Aptech Limited

    1Background Task

    Con

    cept

    s

    tmr.Start(); TimerStatus.Text = tmr.IsEnabled = + tmr.IsEnabled + \n;} void tmr_Tick(object sender, object e) { TimerLog.Text = timesTicked.ToString() + %; if (timesTicked == timesToTick) { TimerStatus.Text = Calling tmr.Stop()\n; tmr.Stop(); TimerStatus.Text = tmr.IsEnabled = + tmr.IsEnabled + \n Process Completed Successfully; } timesTicked++; } private void tmrStart_Click(object sender, RoutedEventArgs e) { TimerStatus.Text = Calling tmr.Start()\n; DispatcherTimerSetup(); } private void tmrStop_Click(object sender, RoutedEventArgs e) { TimerStatus.Text = Calling tmr.Stop()\n; tmr.Stop(); TimerStatus.Text = tmr.IsEnabled = + tmr.IsEnabled + \n; } private void Page_Loaded_1(object sender, RoutedEventArgs e) { TimerStatus.Text = tmr.IsEnabled = False; } }}

  • V 1.0 Aptech Limited

    1Background Task

    Con

    cept

    s

    Step 4: The output of the app when executed, is as shown in figure 1.20.

    Figure 1.20: Output of the App

    Step 5: The output of the app when the user clicks Start button, as shown in figure 1.21.

    Figure 1.21: Create a Blank New Application

    Step 6: The output of the app completes the background task, as shown in figure 1.22.

  • V 1.0 Aptech Limited

    1Background Task

    Con

    cept

    s

    Figure 1.22 Blank New Application Created

  • V 1.0 Aptech Limited

    1Background Task

    Con

    cept

    s

    1.4 Check Your Progress1. The user can use timer in the app to execute the ________ through code.

    (A) UI (C) Tab

    (B) Background Task (D) Thread

    2. Background Task executes the code, which cannot be executed by _______.

    (A) Entry point (C) UI task

    (B) Suspend Option (D) App

    3. To register a background task, the user has to enable the device inside the ____________ file.

    (A) Package.appxmanifest (C) Declarations

    (B) Web.Config (D) Application

    4. ____________ option halts the task at that point of time, and can be restarted when the user selects the resume option.

    (A) Play (C) Stop

    (B) Suspend (D) Pause

    N56Line

    N56Line

    N56Line

    N56Line

    Edited by Foxit ReaderCopyright(C) by Foxit Software Company,2005-2008For Evaluation Only.

  • V 1.0 Aptech Limited

    1Background Task

    Con

    cept

    s

    Summary The two types of thread concepts available in the app are - UI thread and BackgroundTask.

    The user has to declare the Entry point in the app manifest file by selecting the background task from the declaration tab.

    The user must know how to check the conditions and apply them for the background task.

    The user can cancel any running background tasks if it is not needed.

    Triggers are created in the background task to make the app stable and to execute the code without disturbing the UI.

    Suspend option halts the task at that point of time and can be resumed as the user selects the resume option.

  • Device Capabilities

    Session - 2

    Welcome to the Session, Device Capabilities.

    This session introduces users to device connectivity through Enumerating Devices, Plug and Play Devices, Sensors, and Location Services with the Windows Store Apps.

    In this Session, you will learn to:

    Enumerate Devices

    Describe the Plug and Play (PnP) devices

    Troubleshoot Asynchronous errors

    Describe Sensors

    Explain Location Services

  • V 1.0 Aptech Limited

    Con

    cept

    s

    2Device Capabilities

    2.1 DevicesMicrosoft insists their manufacturers and operators to create devices with better connectivity so that the device can be tracked anywhere. The manufacturers also implement and follow these guidelines in case of internal as well as external devices they create. Operators will provide the Geopositioning service to locate the device. This session explains the structures in Windows 8.1 that support Store apps, mobile apps, Storage, and Printers.

    Whenever a user develops a store apps, they can also integrate it as a device app. With device metadata, apps can automatically set up the device connected for the first time and provide more features than normal apps. Apps can make use of features and utilize the variety of functionalities provided by devices. The app can also grant or deny various privileges to the user at runtime.

    2.1.1. Enumerating DevicesWindows.Devices.Enumeration and Windows.Devices.Enumeration.Pnp are the two namespaces to enumerate the devices connected or disconnected. This Windows.Devices.Enumeration class provides two methods, namely FindAllAsync and CreateWatcher to enumerate the devices.

    FindAllAsync - This will search the device only once as the device is connected. This will not update whenever the user adds or delete the devices.

    CreateWatcher This will always enumerate devices by raising notification as the user adds or deletes the devices.

    To enumerate devices the user has to first identify the GUID class for the device to be tested. Microsoft has released the common GUID class with Windows 7, which is called and tested for enumeration.

    Note - The default class GUID for

    Printer: {0ECEF634-6EF0-472A-8085-5AD023ECBCCD}

    Webcam: {E5323777-F976-4F5B-9B55-B94699C46E44}

    Portable Devices: {6AC27878-A6FA-4155-BA85-F98F491D4F33}

  • V 1.0 Aptech Limited

    Con

    cept

    s

    2Device Capabilities

    Step 1: To get the GUID class of a device, the user has to insert any portable device such as pen drive, printer, or webcam. Right-click the device and go to properties as shown in figure 2.1.

    Figure 2.1: Properties

    Step 2: Go to Hardware tab, select the device, and go to properties as shown in figure 2.2.

    Figure 2.2: Select the Device

  • V 1.0 Aptech Limited

    Con

    cept

    s

    2Device Capabilities

    Step 3: In the properties window, select events, and select the device to view the Class GUID as shown in figure 2.3.

    Figure 2.3: Navigate to Events and Select the Device

    2.1.2. Using DeviceWatcherThe DeviceWatcher class is in charge for device enumeration; floating exact events each time the devices are added, removed, or altered after the initial enumeration is finished. The events of DeviceWatcher class are:

    Added Occurs when new device is found and added by the DeviceWatcher class

    EnumerationCompleted Occurs when the device enumeration is completed

    Removed Occurs when a device is removed

    Stopped Occurs when enumeration process is stopped

    Updated Occurs when enumeration process is modified

    2.1.3. Plug and Play (PnP) DevicesPlug and Play (PnP) is a mixture of hardware and software that enables a system to identify, setup, and get used to hardware structure modifications when any new device is connected by the user. A user can connect or disconnect any number of devices to/from the computer. The system will automatically adjust

  • V 1.0 Aptech Limited

    Con

    cept

    s

    2Device Capabilities

    the configuration whenever such devices with plug and play capability are connected to the system.

    Some of the competence acknowledged in the app manifest file such as microphone, camera, and the location can expose private information (For example, Current location). For the app to be able to access devices acknowledged in the app manifest, the user needs to grant access privileges in order to access the feature of the device.

    These devices can be made available in the app by enabling the device in the app manifest file as shown in figure 2.4.

    Figure 2.4: Enable Device Capabilities in the Manifest File

    2.1.4. Handling Device Capability Errors To deliver a good user experience the app needs access to sensitive devices, its required to handle the errors that can occur when trying to access a disabled device.

    Reasons for not being able to access a device includes:

    The user may not have proper permissions to access the device.

    The user may revoke the permission in the settings.

    The device capability is not available on the system.

  • V 1.0 Aptech Limited

    Con

    cept

    s

    2Device Capabilities

    2.2. SensorsWindows.Devices.Sensors namespace is used to capture motion, device orientation, or light sensors.Windows.Devices.Geolocation is the namespace for finding the location of the device through GPS or Location Provider. If the user is trying to access the map for the first time, the app will automatically request the user for permission as shown in figure 2.5.

    Figure 2.5: Location Access Permission

    Figure 2.5 shows the dialog box shown when user tries to open the map for the first time. It will prompt the user to either allow or block the access to map on the system. If the user selects Allow option, he/she is allowed to view the map. If he/she clicks Block then it will restrict the app from accessing the map.

    2.2.1. Working with SensorsWindows 8 supports many sensors. In order to work with these sensors, the user must enable the capabilities in the app manifest file. If the capabilities are not enabled or properly set in the manifest file, then the user will receive an exception message stating that there is no sensor available in the device.

    SimpleOrientationSensorThe SimpleOrientationSensor is used to sense the device orientation. Many devices have rec-ognized the necessity that when the user rotates the device, the display shall also rotate to the new orientation. The images or screen should be adjusted accordingly. The view of the screen should remain original even if the device is rotated by the user. User may change the position of or rotate the device vertically or horizontally, the images should remain in the same position.

  • V 1.0 Aptech Limited

    Con

    cept

    s

    2Device Capabilities

    LightSensorThe LightSensor is used to increase or decrease the brightness of the device. This light sensor will automatically turn Off the display after a certain period of time. It also adjusts the display bright-ness or contrast according to the environment.

    CompassTo detect the magnetic position towards the north to navigate the user using GPS. It keeps details of directions. Moreover, always points the direction indicator towards the north direction. This al-lows the user to know the directions in which he/she is moving.

    Inclinometer This sensor provides the rotation values by showing the pitch, roll, and yaw values. It monitors the surface movements and deformations if any.

    2.2.2. Using the SimpleOrientationSensorTo make use of the device orientation sensor, the user has to write the code to make the screen rotate whenever the user rotates the device. To make use of this orientation the user has to select the supported rotations from the application tab in the app manifest file as shown in figure 2.6.

    Figure 2.6: Supported Rotations

  • V 1.0 Aptech Limited

    Con

    cept

    s

    2Device Capabilities

    To check and determine the current position of the device, the user has to check the device by writing the code shown in Code Snippet 1.

    Code Snippet 1:

    switch (SimpleOrientation) { case SimpleOrientation.NotRotated: AlertBox.Text = Not Rotated; break; case SimpleOrientation.Rotated90DegreesCounterclockwise: AlertBox.Text = 90 Degrees Rotated; break; case SimpleOrientation.Rotated180DegreesCounterclockwise: AlertBox.Text = 180 Degrees Rotated; break; case SimpleOrientation.Rotated270DegreesCounterclockwise: AlertBox.Text = 270 Degrees Rotated; break; case SimpleOrientation.Facedown: AlertBox.Text = Face Down; break; case SimpleOrientation.Faceup: AlertBox.Text = Face Up; break; default: AlertBox.Text = Unknown; break; }

    The code given in Code Snippet 1, checks for various orientation positions of the current device using the switch case block and accordingly takes the action.

    This code will only work on the device that has the orientation sensor. If there is no device orientation sensor present on the device, then this orientation detection code will not work. The app will ignore the rotate event and will not show any effect on the screen.

  • V 1.0 Aptech Limited

    Con

    cept

    s

    2Device Capabilities

    2.3. Location Services Location providers can control the location of a device through:

    Wi-Fi

    Tracking IP Address

    Tracking mobile Network

    Global Position System (GPS)The user has to use the Windows Location Provider for developing the apps. The Location Provider calculates the latitude and longitude; based on the calculated location, the device finds the accuracy of the position in which the device is located. If there is no network available, the Location Provider automatically captures IP Address of the device with an accuracy of 50 kilometers. The Location Provider retrieves latitude, longitude, and device information based on accuracy. This information can be used to determine the exact location of the device. This is very helpful for tracking the device or the person that is holding this device. The namespace Windows.Devices.Geolocation will provide the necessary classes and providers needed to access the location information.

    2.3.1. Using Location ServicesTo access the location of the device the user has to write the code given in Code Snippet 2.

    Code Snippet 2:

    g = new Geolocator();Geoposition p = await g.GetGeopositionAsync();txtLatitude.Text = Latitude: + p.Coordinate.Point.Position.Latitude.ToString();txtLongitude.Text = Longitude: + p.Coordinate.Point.Position.Longitude.ToString();txtAccuracy.Text = Accuracy: + p.Coordinate.Accuracy.ToString();

  • V 1.0 Aptech Limited

    Con

    cept

    s

    2Device Capabilities

    The code given in Code Snippet 2 is used to track the Geo position of a device. This GeoPosition will show the latitude and longitude point, which shows the exact place where the device is located. When the code is executed, the output will request user to access the device location as shown in figure 2.7.

    Figure 2.7: Output Requesting to Access Device Location

    As the user allows to access the device location permission, the app will display the device latitude, longitude, and the accuracy as shown in figure 2.8.

    Figure 2.8: Output Displaying the Location Information

    2.3.2. Using GeofencingGeofencing provides an API to track the device and generate a trigger when the user enters or leaves a particular location or area. Store apps support hundreds of Geofencing options. If more than one Geofencing is triggered then the app will automatically notify the location that is active. The

  • V 1.0 Aptech Limited

    Con

    cept

    s

    2Device Capabilities

    GeofenceStateChanged event is called, as one or more objects in the collection are changed. As soon as the Geofencing is triggered, the ReadReports() method is called to return the Geofencing list, which is modified. The user has to check the entry and exit state when the device is identified in the defined location by showing a notification by setting the ID in CreateGeofence()method.GeofenceMonitor will save the Geofencing list automatically and it will be active until the app is executed. The user has to use the Remove() method to clear the list.

    2.4 Troubleshooting Async ErrorsWhenever users creates any app, they have to handle the errors if it occurs at runtime. If an app is developed without handling errors, then the error will be reflected in the app. This will also close the app abruptly or abnormally. This will lead to bugs in the app. To overcome these types of errors, the user can use the try - catch block to handle such errors or to capture these exceptions. An appropriate exception can be handled and an error message can be thrown without stopping the current running app. The app continues execution without an interruption.

    The code shows how the try catch block is used to capture or handle certain error occurred in the app. Method fnErrorHandle() will handle an exception or error thrown by the app. async void fnErrorHandle(){ try { Int i; int j, int k; i=5; j=Test; k=i+j; } catch (Exception ex){ new MessageDialog(ex.Message).ShowAsync();}}The code given here, declares three integer value and when adding those two values it throws casting error so, to handle this the user can throw a message using the catch block.

  • V 1.0 Aptech Limited

    Con

    cept

    s

    2Device Capabilities

    Device Enumeration

    Step 1: Create a blank new application from File New Project Blank App

    Step 2: Write the code given in Code Snippet 3 to create the design view of the page.

    Code Snippet 3 shows how to create a layout with components as shown in figure 2.9.

    Code Snippet 3:

    Webcams

  • V 1.0 Aptech Limited

    Con

    cept

    s

    2Device Capabilities

    Portable DevicesPrinters

    When the user writes the code given in Code Snippet 3 in the design mode, the UI will be displayed as shown in figure 2.9.

    Figure 2.9: UI Design Layout Created

  • V 1.0 Aptech Limited

    Con

    cept

    s

    2Device Capabilities

    Step 3: Add following code given in Code Snippet 4, in the code behind file, MainPage.xml.cs.Code Snippet 4:

    using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Runtime.InteropServices.WindowsRuntime;using Windows.Devices.Enumeration;using Windows.Foundation;using Windows.Foundation.Collections;using Windows.UI.Xaml;using Windows.UI.Xaml.Controls;using Windows.UI.Xaml.Controls.Primitives;using Windows.UI.Xaml.Data;using Windows.UI.Xaml.Input;using Windows.UI.Xaml.Media;using Windows.UI.Xaml.Navigation;using Windows.Devices.Enumeration;using Windows.Devices.Enumeration.Pnp;

    namespace DeviceTesting{ public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent();lstDevices.SelectionChanged += new SelectionChangedEventHandler(lstDevices_SelectionChanged); }

  • V 1.0 Aptech Limited

    Con

    cept

    s

    2Device Capabilities

    Step 4: Write Code Snippet 5 to call the function, when the device is selected from the list.

    Code Snippet 5:

    void lstDevices_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (lstDevices.SelectedItem == Printer) { txtClassGuid.Text = {0ECEF634-6EF0-472A-8085-5AD023ECBCCD}; } else if (lstDevices.SelectedItem == Webcam) { txtClassGuid.Text = {E5323777-F976-4F5B-9B55-B94699C46E44}; } else if (lstDevices.SelectedItem == PortDevices) { txtClassGuid.Text = {6AC27878-A6FA-4155-BA85-F98F491D4F33}; } }

    Code given in Code Snippet 5 creates a class called Device Testing, this class then uses switch-case to identify the device that was selected for enumeration.

  • V 1.0 Aptech Limited

    Con

    cept

    s

    2Device Capabilities

    Step 5: Write the code given in Code Snippet 6 to call the function when the user clicks Enumerate button.

    Code Snippet 6:

    async void btnEnumerate_click(object sender, RoutedEventArgs eventArgs) { btnEnumerate.IsEnabled = false; lstResult.Items.Clear(); try { var s = InterfaceClassGuid:=\ + txtClassGuid.Text + \; var i = await DeviceInformation.FindAllAsync(s, null); txtResult.Text = i.Count + device found\n\n; foreach (DeviceInformation d in i) { fnDeviceInfo(d); } } catch (ArgumentException) { txtResult.Text = Exception: Verify interface class GUID.; } btnEnumerate.IsEnabled = true; }

  • V 1.0 Aptech Limited

    Con

    cept

    s

    2Device Capabilities

    Code Snippet 7 shows how to use the enumeration devices and how to generate the list. The device information is shown in the result box, as shown in Code Snippet 7.

    Code Snippet 7:

    async void fnDeviceInfo(DeviceInformation d) { var id = Id: + d.Id; var name = d.Name; var isEnabled = IsEnabled: + d.IsEnabled; var item = id + is \n + name + and \n + isEnabled; lstResult.Items.Add(item); } }}

    When the user executes the application by pressing F5 or Run option, the output will be displayed as shown in figure 2.10.

    Figure 2.10: List of Devices

  • V 1.0 Aptech Limited

    Con

    cept

    s

    2Device Capabilities

    Step 6: When the user clicks the enumerate button the device information will be displayed as shown in figure 2.11.

    Figure 2.11: Output After Clicking Enumerate Button

    Using DeviceWatcher

    Step 1: Create a blank new application

    Step 2: Write the code given in Code Snippet 8, to create the design view of the page.

    Code Snippet 8:

  • V 1.0 Aptech Limited

    Con

    cept

    s

    2Device Capabilities

  • V 1.0 Aptech Limited

    Con

    cept

    s

    2Device Capabilities

    Step 3: Write Code Snippet 9 in the code behind of the page.

    Code Snippet 9:

    using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Runtime.InteropServices.WindowsRuntime;using Windows.Devices.Enumeration;using Windows.Foundation;using Windows.Foundation.Collections;using Windows.UI.Xaml;using Windows.UI.Xaml.Controls;using Windows.UI.Xaml.Controls.Primitives;using Windows.UI.Xaml.Data;using Windows.UI.Xaml.Input;using Windows.UI.Xaml.Media;using Windows.UI.Xaml.Navigation;namespace DeviceWatcherTest{ public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent();} Windows.UI.Core.CoreDispatcher d; public static DeviceWatcher w = null; public static int c = 0; public static DeviceInformation[] i = new DeviceInformation[1000]; public static bool isComplete = false; public static string Status = null;

  • V 1.0 Aptech Limited

    Con

    cept

    s

    2Device Capabilities

    Code Snippet 10 function is to start the enumeration.

    Code Snippet 10:

    async void fnDevicesWatch(object sender, RoutedEventArgs eventArgs){ try { d = Window.Current.CoreWindow.Dispatcher; w = DeviceInformation.CreateWatcher(); w.Added += watcher_Added; w.Removed += fnRemovedwatcher; w.Updated += watcher_Updated; w.EnumerationCompleted += fnEnumComplete; w.Stopped += fnStoppedwatcher; w.Start(); txtResult.Text = Enumeration started.; } catch (ArgumentException) { txtResult.Text = Caught ArgumentException. Failed to create watcher.; } }

  • V 1.0 Aptech Limited

    Con

    cept

    s

    2Device Capabilities

    Code Snippet 11 function is to stop the enumeration.

    Code Snippet 11:

    async void StopWatcher(object sender, RoutedEventArgs eventArgs) { try { if (w.Status == Windows.Devices.Enumeration.DeviceWatcherStatus.Stopped) { Status = The enumeration is already stopped.; } else { w.Stop(); } } catch (ArgumentException) { txtResult.Text = Caught ArgumentException. Failed to stop watcher.; } }

  • V 1.0 Aptech Limited

    Con

    cept

    s

    2Device Capabilities

    Code Snippet 12 is to display the device list if the enumeration is completed.

    Code Snippet 12:

    async void watcher_Added(DeviceWatcher sender, DeviceInformation deviceInterface) { i[c] = deviceInterface; c += 1; if (isComplete) { await d.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { fnDisplayDeviceList(); }); } }

    Code Snippet 13 is used to update the device list if the enumeration is completed.

    Code Snippet 13:

    async void watcher_Updated(DeviceWatcher sender, DeviceInformationUpdate devUpdate) { int count2 = 0; foreach (DeviceInformation deviceInterface in i) { if (count2 < c) { if (i[count2].Id == devUpdate.Id) { //Update the element. i[count2].Update(devUpdate); } } count2 += 1;

  • V 1.0 Aptech Limited

    Con

    cept

    s

    2Device Capabilities

    } await d.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { txtResult.Text = Enumeration updated. ; fnDisplayDeviceList(); }); }

    Code Snippet 14 is used to remove the existing device list if the enumeration is completed.

    Code Snippet 14:

    async void fnRemovedwatcher(DeviceWatcher sender, DeviceInformationUpdate devUpdate) { int count2 = 0; //Convert interfaces array to a list (IList). List interfaceList = new List(i); foreach (DeviceInformation deviceInterface in i) { if (count2 < c) { if (i[count2].Id == devUpdate.Id) { //Remove the element. interfaceList.RemoveAt(count2); } } count2 += 1; } //Convert the list back to the interfaces array. i = interfaceList.ToArray(); c -= 1; await d.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => {

  • V 1.0 Aptech Limited

    Con

    cept

    s

    2Device Capabilities

    txtResult.Text = Enumeration device was removed. ; fnDisplayDeviceList(); }); } async void fnEnumComplete(DeviceWatcher sender, object args) { isComplete = true; await d.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { txtResult.Text = Enumeration complete. ; fnDisplayDeviceList(); }); }

  • V 1.0 Aptech Limited

    Con

    cept

    s

    2Device Capabilities

    Code Snippet 15 is used to stop the enumeration.

    Code Snippet 15:

    async void fnStoppedwatcher(DeviceWatcher sender, object args) { if (w.Status == Windows.Devices.Enumeration.DeviceWatcherStatus.Aborted) { Status = Enumeration stopped.; } } async void fnDisplayDeviceList() { lstResult.Items.Clear(); int count2 = 0; foreach (DeviceInformation deviceInterface in i) { if (count2 < c) { fnDisplayDeviceInterface(deviceInterface); } count2 += 1; } }

  • V 1.0 Aptech Limited

    Con

    cept

    s

    2Device Capabilities

    Code Snippet 16 is used to display device information.

    Code Snippet 16:

    async void fnDisplayDeviceInterface(DeviceInformation deviceInterface) { var id = Id: + deviceInterface.Id; var name = deviceInterface.Name; var isEnabled = IsEnabled: + deviceInterface.IsEnabled; var item = id + is \n + name + and \n + isEnabled; lstResult.Items.Add(item); } }}

    Step 4: The output screen to display the page when the user executes the app as shown in figure 2.12.

    Figure 2.12: Output Screen

  • V 1.0 Aptech Limited

    Con

    cept

    s

    2Device Capabilities

    Step 5: The output screen to display the device information when the user clicks watch all device button as shown in figure 2.13.

    Figure 2.13: Output

  • V 1.0 Aptech Limited

    Con

    cept

    s

    2Device Capabilities

    2.5 Check Your Progress1. ___________ will search the device only once as the device is connected.

    (A) CreateWatcher (C) GUID class

    (B) FindAllAsync (D) Enumerate devices

    2. Microsoft has released the common GUID class with __________, which is called and tested for enumeration.

    (A) Windows 8 (C) Windows 7

    (B) Windows 8.1 (D) Windows 9

    3. ________________ is a mixture of hardware and software that enables a system to identify and get used to hardware structure modifications by the user.

    (A) Plug and Play (C) Sensitive devices

    (B) App manifest (D) GPS

    4. _________ supports many sensors.

    (A) Windows 8.1 (C) Windows Vista

    (B) Windows 8 (D) Windows XP

    5. The LightSensor is used to increase or decrease the __________ of the device.

    (A) Colour (C) Sensor

    (B) Resolution (D) Brightness

    N56Line

    N56Line

    N56Line

    N56Line

    N56Line

    Edited by Foxit ReaderCopyright(C) by Foxit Software Company,2005-2008For Evaluation Only.

  • V 1.0 Aptech Limited

    Con

    cept

    s

    2Device Capabilities

    Summary Windows.Devices.Enumeration and Windows.Devices.Enumeration.Pnp are the two namespaces

    to enumerate the devices connected or disconnected.

    To enumerate devices the user has to first identify the GUID class for the device to be tested.

    The DeviceWatcher class is in charge for device enumeration with passion; floating exact events each time the devices are added, removed, or altered after the initial enumeration is finished.

    Some of the competence acknowledged in the app manifest file such as microphone, camera, and the location can expose private information.

    Windows.Devices.Sensors namespace is used to capture motion, device orientation or light sensors.

    To make use of this orientation the user has to select the supported rotations from the application tab in the app manifest file.

  • V 1.0 Aptech Limited

    Con

    cept

    s

    2Device Capabilities

  • Generating Revenue Apps

    Session - 3

    Welcome to the Session, Generating Revenue Apps.

    This session introduces you to concepts of generating revenue apps in the Windows Store. Users can earn money by developing apps that generate revenue. This session shows the user how to develop and distribute the apps through Windows Store.

    In this Session, you will learn to:

    Explain Trial Functionality

    Describe the process of In-app Purchase

    Explain the process of Advertising in Windows Store apps

  • Con

    cept

    s

    Session

    V 1.0 Aptech Limited

    3Generating Revenue Apps

    3.1 Implementing Trial Functionality in a Windows Store AppWhen users selects free trial or try from an app, then the user is allowed to use the app upto certain period, which may vary from 7 to 30 days. If the trial period ends, same user cannot use that app anymore unless the app is purchased. For example, if the user wants to buy the chess challenger app as shown in figure 3.1, the user can try for a certain period and if the app is as per the expectations of the user, then the user can purchase the same app.

    Figure 3.1: Trial App

    Implementing the trial functionality for an app will help the user for marketing the app, and Microsoft Apps Store recommends it. It is recommended to implement these trial functionalities in an app so that user can get a chance to evaluate the app. If the user finds the app to be useful then he/she may purchase the same from the Windows Store and get full benefits. If the developer uploads an app that costs high and does not provide any trial functionality in it, then it will be more difficult to sell or market the app. The customers will think before they purchase an app for higher cost. Putting some screenshots, ratings, or reviews in the store may convince the customers to purchase the app. This will lead to increase in the sale of an app.

    Time-Based TrialsTo set a trial-based app, the user has to set a time or date calculation mechanism in the store app. The store will take care of the app as the trial period ends, so the user need not worry about the usage of the app after trial period. While submitting the app in the store the developer has to specify the trial period in days for the app as shown in figure 3.2. The trial period will starts when the user downloads and installs the app from the store. When the trial expires, Windows Store will automatically prompt the user to pay for the app if he/she wishes to continue using the app or else the app will stop execution.

  • Con

    cept

    s

    Session3

    V 1.0 Aptech Limited

    Generating Revenue Apps

    No special programming skills are required to do the same. Windows Store will take care of tracking the trial period.

    Figure 3.2: Set Trial Period for the App

    In Windows Store apps, LicenseInformation class stores the license state in the app property. The user has to create functions that depend on the license state. The developer has to decide how to handle changes to the apps license while the app is running. The trial app can be full-featured version. Such version of the app can have in-app ad banners, whereas the paid-for version should not have such in-apps or ad banners. Other alternative is that the trial app can disable certain features, or display regular messages asking the user to buy it. To make a good trial app, the developer can create the app by removing the some features or setting up to various levels of the app. Each level will have certain features installed in it, while others will not have these features. Even the developer of the app can charge different prices for different level. Most of the time such strategy, is applied with various levels in game apps.

    Feature-Differentiated TrialsWhen the app trial period expires while running, the user can display a message to the customer regarding the expiry of the trial period or send a notification in prior. The user has to mention these reminders using the time-based trial period.

    To check the app is in trial license, the user have to write a code as shown in Code Snippet 1.

  • Con

    cept

    s

    Session

    V 1.0 Aptech Limited

    3Generating Revenue Apps

    Code Snippet 1:

    // function to check the licenseinfoprivate async void fnLicenseInfo() {//license info is retrieved var l = CurrentAppSimulator.LicenseInformation; if (l.IsActive) {// check if there is any trial version, and show appropriate message if (l.IsTrial) {await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { txtDetail.Text = License status: Trial license; var r = (l.ExpirationDate - DateTime.Now).Days; txtDetail.Text += System.Environment.NewLine + String.Format(Remaining days: {1}, l.ExpirationDate, r); });}else//otherwise set message to full version {await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>{ txtDetail.Text = License status: Full license; txtDetail.Text += no expiry; });}}else{

  • Con

    cept

    s

    Session3

    V 1.0 Aptech Limited

    Generating Revenue Apps

    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>{txtDetail.Text = License status: license expired. Purchase the app!;});}}

    Every time the app is loaded, the code will check the app and determine whether it is running in trial period. If the trial period has not expired then it will display days remaining for expiry of the app. These details are stored in the .config file. When the code is executed, the output will be as shown in figure 3.3.

    Figure 3.3: Trial App Demonstrations

    The user can get all the app license information using the namespace Windows.ApplicationModel.Store.CurrentApp static class. The user can set a Boolean value to check if the app is in trial mode or not. To check this, the developer can check the value returned by the property CurrentApp.LicenseInformation.IsTrial. To check this condition the developer must ensure that CurrentApp.LicenseInformation.IsActive property is set to true.

    3.2 Implement In-app PurchasesIn-app purchase means the ability of an app to allow sale or purchase of the app with the help of devices such as a mobile, tablet or a PC. Many times such in-app purchase is allowed within games and other useful apps that allow the users to pay online and start using all the features of the app. The user can easily purchase such an app without any trouble. The apps are normally activated immediately after in-app purchases. There is no need to download and update a fresh copy of the app that is already downloaded and is running on the systems. To develop an app with in-app purchase feature, the user has

  • Con

    cept

    s

    Session

    V 1.0 Aptech Limited

    3Generating Revenue Apps

    to create a .config file that includes all the information about the app. This can be done by adding the code shown in Code Snippet 2 to the appropriate config file.

    Code Snippet 2:

    00000000-0000-0000-0000-000000000000

    http://apps.microsoft.com/webpdp/app/00000000-0000-0000-0000-000000000000

    en-US3

    LicenseTestWill check the license info10.00$USD

    License App1.00$USD

  • Con

    cept

    s

    Session3

    V 1.0 Aptech Limited

    Generating Revenue Apps

    truetrue 2014-06-30T09:00:00.00Z

    true

    In Code Snippet 2, the user has to declare two elements, namely ListingInformation and LicenseInformation. The listing information will hold all the details of the app. This listing information will hold the app name, description, pricing details; whereas, LicenseInformation will hold the app license details such as trial details, expiry date (if trial), and product availability.

    Code Snippet 3:

    private async System.Threading.Tasks.Task fnLoadLicenseInfo(){StorageFolder proxyDataFolder = await Package.Current.InstalledLocation.GetFolderAsync(Data);StorageFile proxyFile = await proxyDataFolder.GetFileAsync(storelicense.xml);await CurrentAppSimulator.ReloadSimulatorAsync(proxyFile);}

    Code Snippet 3 will get the xml file from the data folder. The xml file must be saved under a folder called data folder.

    3.3 Setting up In-app PurchasesThis is the most important step for setting up the correct license type for an app developed by the user. To sell an app, the user must analyze and decide the correct pricing that can be charged while selling this app. Price must be competitive than the other similar apps in the market. Another possibility is that, if the user is allowed to try an app for a certain period, he/she will be able to utilize the features of the app. He/she can explore if it is helpful for him/her. It will build confidence in the mind of the customers. Thus,

  • Con

    cept

    s

    Session

    V 1.0 Aptech Limited

    3Generating Revenue Apps

    a decision to purchase the app might be taken. This can lead to a better marketing strategy for the app owner.

    Figure 3.4: In-app Purchase Details

    Figure 3.4 shows how to set up the app purchase. There are two possibilities for setting up trial versions for any app.

    Time Based TrialThis is time based trial version of an app. It will have all the features of the app, but after a certain period, i.e. after the trial period, the app will automatically expire and stop execution. The user will not be able to use the app further. The developer of the app can set the period within the range of 1 day to 365 days. It can be defined or set under product lifetime section as shown in figure 3.4.

    Feature Based TrialFeatured apps will allow the users to access the app up to a certain level until user purchases the full version. For example, if the user installs a trial version of a game app, the app owner will be restricted and will be able to play the game only up to certain levels. Some of the levels in the game will be locked so that the user cannot move and play the next levels. Once the user pays and pur-chases the same, he/she will be allowed to play all the levels and remaining levels will be unlocked for him/her. This is how the feature based trial works. Here, a specific time limit is not given.

    3.4 Advertising in a Windows Store AppMore ad platforms are available in Windows Store. The developer can develop an advertisement, which pays him/her every time a customer clicks such advertisement. This is known as Pay per Click (PPC). Some apps will have the advertisement and when the ad is displayed, the developer of such an app is paid whenever an impression is shown. Such an app is known as Pay per Impression (PPI). To integrate ads in

  • Con

    cept

    s

    Session3

    V 1.0 Aptech Limited

    Generating Revenue Apps

    the store app the developer has to register with Microsoft pubCenter as shown in figure 3.5.

    Figure 3.5: Create an Account in PubCenter

    The developer can manage their account from http://pubcenter.microsoft.com and Windows Store dashboard. Visual Studio 2013 includes some built-in connection for pubCenter, as shown in figure 3.6. The developer has to sign in with his/her details such as Name, Address, Contact Number, Bank Details, App name and price to be charged. After he/she logs in successfully, it is possible to upload the store app, monetize the same, and start earning revenues from it. This process is known as monetization.

    Figure 3.6: Manage Ads in PubCenter

  • Con

    cept

    s

    Session

    V 1.0 Aptech Limited

    3Generating Revenue Apps

    There are standard ad sizes to implement in the app. Table 3.1 shows the standard ad size and its unit id.

    Ad Size Description Unit Id160 x 600 Image Ad 10043136

    160 x 600 Video Ad 10043135

    160 x 600 Image Ad 10043134

    250 x 250 Image Ad 10043107

    250 x 250 Image Ad 10043104

    300 x 250 Image Ad 10043055

    300 x 250 Video Ad 10043056

    300 x 250 Image Ad 10043057

    300 x 600 Image Ad 10043030

    728 x 90 Image Ad 10043000

    728 x 90 Video Ad 10042999

    728 x 90 Image Ad 10042998

    Table 3.1: Ad Size and Unit ID

    Note - Advertising SDK can be downloaded from URL. http://download.microsoft.com/download/A/B/A/ABA21B24-962A-4DFE-A88C-694BEFFFBBA2/W8AdSDK-ENU.msi

    After installing SDK, the user can view the ad control tool in the toolbox of visual studio as shown in figure 3.7.

    Figure 3.7: AdControl in Toolbox

    The user can use AdControl to display ads in the application. Microsoft has provided an application id

  • Con

    cept

    s

    Session3

    V 1.0 Aptech Limited

    Generating Revenue Apps

    for the developers to test the ad control. This application id is as follows:

    Application ID: d25517cb-12d4-4699-8bdc-52040c712cabTo test the Ad control the user has to write the code as provided in Code Snippet 4.

    Code Snippet 4:

    When the user executes the code, the advertising banner will be displayed as shown in figure 3.8.

    Figure 3.8: Ad Displayed in the App

  • Con

    cept

    s

    Session

    V 1.0 Aptech Limited

    3Generating Revenue Apps

    Now, let us see how to specify the licensing setting in the app. Following example gives systematic instructions to set the licensing details.

    Licensing an App

    Licensing an app in Windows Store is made easy by Microsoft. You can do the same through few steps. Most of the functionalities are in-built in the Store apps framework.

    Create a blank new application and add code given in Code Snippet 5 to MainPage.xaml.Code Snippet 5:

    The code given in Code Snippet 5 adds two TextBlocks and two Buttons to the page design. First TextBlock shows a message Trial App and second TextBlock shows a message txtDetails. There are two buttons also; they are btnCalculate and btnPurchase. The user can click any of this buttons to either purchase it or calculate the price.

  • Con

    cept

    s

    Session3

    V 1.0 Aptech Limited

    Generating Revenue Apps

    Create a New Folder as shown in figure 3.9. Under this folder, create a New Item as shown in figure 3.10.

    Figure 3.9: Create a New Folder

    Figure 3.10: Create a New Item

  • Con

    cept

    s

    Session

    V 1.0 Aptech Limited

    3Generating Revenue Apps

    Create an xml and give name as StoreLicense.xaml file to store the license information, as shown in figure 3.11. This file will hold all the licensing details.

    Figure 3.11: Create a New xml File

    Now, add the following details to the file StoreLicense.xaml. Write the code given in Code Snippet 6 with tags to store the license information.

    Code Snippet 6:

    00000000-0000-0000-0000-000000000000

    http://apps.microsoft.com/webpdp/app/00000000-0000-0000-0000-000000000000

    en-US3

    LicenseTest Will check the license info 10.00 $ USD

  • Con

    cept

    s

    Session3

    V 1.0 Aptech Limited

    Generating Revenue Apps

    License App 1.00 $ USD

    true true 2014-06-30T09:00:00.00Z true

    Add the code given in Code Snippet 7 in the code behind file called MainPage.xaml.cs.Code Snippet 7:

  • Con

    cept

    s

    Session

    V 1.0 Aptech Limited

    3Generating Revenue Apps

    using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Runtime.InteropServices.WindowsRuntime;using Windows.ApplicationModel;using Windows.ApplicationModel.Store;using Windows.Foundation;using Windows.Foundation.Collections;using Windows.Storage;

  • Con

    cept

    s

    Session3

    V 1.0 Aptech Limited

    Generating Revenue Apps

    using Windows.UI.Xaml;using Windows.UI.Xaml.Controls;using Windows.UI.Xaml.Controls.Primitives;using Windows.UI.Xaml.Data;using Windows.UI.Xaml.Input;using Windows.UI.Xaml.Media;using Windows.UI.Xaml.Navigation;namespace TrialApp{ public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent(); } protected async override void OnNavigatedTo(NavigationEventArgs e) { await this.fnLoadLicenseInfo(); }private async System.Threading.Tasks.Task fnLoadLicenseInfo(){StorageFolder proxyDataFolder = await Package.Current.InstalledLocation.GetFolderAsync(Data);StorageFile proxyFile = await proxyDataFolder.GetFileAsync(storelicense.xml);await CurrentAppSimulator.ReloadSimulatorAsync(proxyFile);}private void btnCalculate_Click(object sender, RoutedEventArgs e){ LicenseInformation l = CurrentAppSimulator.LicenseInformation; if (l.IsTrial) {

  • Con

    cept

    s

    Session

    V 1.0 Aptech Limited

    3Generating Revenue Apps

    txtDetail.Text = The app is currently in Trial license; }}private void btnDetails_Click(object sender, RoutedEventArgs e){LicenseInformation l = CurrentAppSimulator.LicenseInformation;if (l.IsActive) { if (l.IsTrial) { fnLicenseInfo(); } }}private async void fnLicenseInfo() { var l = CurrentAppSimulator.LicenseInformation; if (l.IsActive) {if (l.IsTrial) { await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => {txtDetail.Text = License status: Trial license.; var r = (l.ExpirationDate - DateTime.Now).Days; txtDetail.Text += System.Environment.NewLine + String.Format( Remaining days: {1}, l.ExpirationDate, r); }); }else{

  • Con

    cept

    s

    Session3

    V 1.0 Aptech Limited

    Generating Revenue Apps

    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { txtDetail.Text = License status: Full license; txtDetail.Text += no expiry; }); } } else { await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { txtDetail.Text = License status: license expired. Purchase the app!; }); } } }}

    When the user executes the app, the output will be as shown in figure 3.12. Either the user can select to purchase the app or he/she can just view the details by clicking the appropriate button.

    Figure 3.12: Output When Executed

  • Con

    cept

    s

    Session

    V 1.0 Aptech Limited

    3Generating Revenue Apps

    If the user clicks the Purchase button then the output will be as shown in figure 3.13.

    Figure 3.13: Output When Purchase Button is Clicked

    User can even click the Details button to see the details of the current application. When the user executes the app and clicks the Details button, the output will be as shown in figure 3.14.

    Figure 3.14: Output When Details Button is Clicked

    When user click the Details button, app will check if the trial period has expired. If the trial period is expired then the app will stop execution. If the trial period is not expired then the app will show a message that tells us how many days are remaining. This is how the trial functionality is added in the store app.

  • Con

    cept

    s

    Session3

    V 1.0 Aptech Limited

    Generating Revenue Apps

    3.5 Check Your Progress1. The ________ will take care of the app as the trial period ends, so the user need not worry about

    the usage of the app after trial period.

    (A) Store (C) Developer

    (B) User (D) App

    2. _____________ class stores the license state in the app property.

    (A) Notification (C) Apps license

    (B) LicenseInformation (D) Namespace

    3. Some app will have an ad and when user clicks this ad, the store will pay the user and this process is known as ____________.

    (A) Integrated ads (C) Pay per click

    (B) Ad platform (D) Pay per impression

    4. The user can set a _________ value to catch the app is in trial mode or not.

    (A) Boolean (C) Ad

    (B) Store (D) Purchase

    5. Putting some screenshots, ratings, or reviews in the Store may convince the customers to purchase the _________.

    (A) Ad (C) Store

    (B) App (D) Space

    N56Line

    N56Line

    N56Line

    N56Line

    N56Line

    Edited by Foxit ReaderCopyright(C) by Foxit Software Company,2005-2008For Evaluation Only.

  • Con

    cept

    s

    Session3

    V 1.0 Aptech Limited

    Generating Revenue Apps

    Summary When a user selects free trial or tries an app, then the user is allowed to use the app up to a

    certain limited period, which may vary from 7 30 days.

    To set a trial-based app, the user has to set a time or date calculation in the store app.

    Trial app can be full-featured, but can have in-app ad banners where the paid-for version does not have such in-app ad banners. Such banners are completely removed from the paid version.

    In the XAML file, the user declares and assigns some values to two main elements, namely ListingInformation and LicenseInformation.

    The user can develop the ad, which pays the user whenever a customer clicks such ads. This is known as Pay per Click.

    To integrate ads in the store app the developer has to register with Microsoft pubCenter.

  • Developing Universal Apps

    Session - 4

    Welcome to the Session, Developing Universal Apps.

    This session will help you to learn how to develop apps for mobile and use it universally in the Windows Store.

    In this Session, you will learn to:

    Explain the Windows Phone 8.1 Platform Features

    Explain Universal Apps

    Explain the process of Packaging an App

    Explain the process of Deploying an App

  • Con

    cept

    s

    Session

    V 1.0 Aptech Limited

    4Developing Universal Apps

    4.1 Introduction to Windows Phone 8.1Microsoft introduced universal Windows apps for PCs, phones, and tablets with Visual Studio 2013 Update. This Update for Windows Phone 8.1 is named as Cortana and they have targeted mainly for gamers. For the non-gaming users, the device will be faster and accessible in seconds.

    Gain access to conclude a Live Tile, or press the search button, this update will support most apps, calls, messages, searches, and music on the user phone. Cortana interacts through the third-party apps, such as Facebook and Twitter to share the links or test through the post.

    4.1.1 Building Windows Store AppsThe user can develop the apps to target the mobile. To develop the app, the user has to follow the steps. These steps will demonstrate to create a Hello World app.

    4.1.2 Hello World in Windows PhoneStep 1: Open Microsoft Blend and Select New Project. Select Windows Phone from the left side menu and select Windows Phone App from the right side menu as shown in figure 4.1.

    Figure 4.1: Create a Phone App

  • Con

    cept

    s

    Session4

    V 1.0 Aptech Limited

    Developing Universal Apps

    Step 2: Design the app page as shown in figure 4.2.

    Figure 4.2: Design the App Page

    Step 3: Once the page design is completed, connect the Windows mobile to the PC and run the application. The app will be installed in Windows phone. The user can view and access the app directly from the device.

    4.2 Windows Phone 8.1 Platform FeaturesFollowing are the features of Windows phone 8.1:

    y GeolocationGeolocations is upgraded by adding a new class called Geofencing. This API is used to track the device upto a certain area and sends a notification whenever the device comes within network coverage area. This API gives details about longitude and latitude. It uses GPS, IP Address, RFID, WiFi, Bluetooth MAC Address, and GSM/CDMA cell IDs to determine the location.

    y MapsWindows Phone 8.1 maps is upgraded with a new feature by viewing the map offline tiles and improved routing. Using Map API, the developer can create map-based apps and incorporate location and search features in the app.

    y Background transfersBackground transfer is used to transfer data in the background by calling the Background Task features.

    y Windows Push Notification Services (WNS)Windows Phone 8.1 includes Windows Push Notification Services (WNS) to send Toast, Tile, and Raw updates to the user device, which are received from a cloud service.

  • Con

    cept

    s

    Session

    V 1.0 Aptech Limited

    4Developing Universal Apps

    y ControlsWindows Phone 8.1 is developed using the XAML framework. Similar to store apps, the XAML controls for Phone 8.1 includes the basic and essential controls such as Button, TextBlock, CheckBox, FlipView, GridView, ListView, Password, and Zoom controls.

    y GlobalizationWindows Phone 8.1 supports many international languages, which can be called through the Globalization namespace. Using this feature it is possible to developed apps with support to various international languages.

    y CalendarCalendar is declared in a different way in Windows Phone 8.1 and supports Appointment API. This API is also available for developing Windows Store apps with calendar features.

    y BrowserInternet Explorer 11 is enabled to allow Windows Phone 8.1 apps. This is possible using WebView control provided in Windows Store apps. WebView supports features of HTML5 apps which is used to display responsive layouts.

    y External display supportWindows Phone enables the external display support by mirroring the phone display to PC through a USB cable. The contents of phone can easily be displayed directly on the PC screen.

    y Data and storageWindows.Storage API is associated to stream-based files. It allows the users to store data locally. This will ask the user where to store the downloaded file.

    y RoamingWindows Phone 8.1 supports roaming data. Roaming data feature is available when the lock is enabled and the device is active. Roaming data files are stored inside the Roaming data folder. For any app, the size of the roaming data is restricted upto 100 Kb only.

    y Share contactWindows Phone 8.1 introduces the Share contact that allows sharing files, images, and videos to any contact that is present in the current device. The data is generally shared using an e-mail.

    y SD cardIn Windows Phone 8, only reading SD card was possible. However, now in Windows Phone 8.1, reading and writing to and from SD card is possible.

    4.3 Universal AppsMicrosoft has released Windows Phone 8.1 in the month of April 2014 which is named as Cortana. This is enabled and available in Visual Studio 2013 with Update 2. These new features allows the developers to

  • Con

    cept

    s

    Session4

    V 1.0 Aptech Limited

    Developing Universal Apps

    build global apps, which works with phones, tablets, and PC as well. Windows 8.1 Update has also added UI enhancements for mouse and keyboard and other useful features. This developer platform will expand to customers using devices like phones, tablets, and PCs.

    Windows Phone 8 holds the same set of tools and procedures that are included in Windows 8. In order to develop universal app the user have to select Universal Apps from the New Project Menu as shown in figure 4.3.

    Figure 4.3: Create Universal App

    Users can develop the Phone 8.1 universal app with the same runtime. This is similar to designing and developing apps for phones, tablets and PCs.

    4.4 Packaging an AppWindows Runtime app package will be created with an extension as .appx, which is ready-to-install app in the devices.

    This package will have following options:

    y App payload : App code files and assets y App manifest : App manifest file (AppxManifest.xml) y App block map : App packages block map file (AppxBlockMap.xml) y App signature : App packages digital signature file (AppxSignature.p7x)

    To create the package the user has to follow some steps. When the developer finishes developing the app completely, then it is ready to be packed.

  • Con

    cept

    s

    Session

    V 1.0 Apte