CHAPTER 2

image

Windows Runtime Environment

After giving you a complete introduction to the basic principles of Windows Store apps and the related tools that you need to develop an application, we now want to explore the environment and tell you about the new platform architecture and its components. The following list shows the key concepts you need to know before writing a new application:

  • Communication: An introduction to Windows Runtime (WinRT) application programming interfaces (APIs) that enable your applications to communicate with external sources
  • Data: An introduction to all the APIs that allow applications to store and retrieve data
  • Graphics: Classes that you can instantiate to draw something on your application
  • Media: Classes that help you play video and audio in your applications
  • Devices and printers: The support of Windows 8 for devices such as Camera, GPS, Printers, and much more

Windows 8 Platform

Looking toward the future, Windows has been redesigned with a new set of core services shared between the classic desktop applications and the new immersive Windows Store apps. Some of the main problems of Windows operating systems (OSs) were end user problems with installing, uninstalling, searching, and trying applications. Consumers are key (without forgetting business users) to meeting the needs of mobility and touch interactions. To enable developers to create a new experience with Windows for consumer users, Microsoft introduced a new layer in the operating system: Windows Runtime, also called WinRT.

WinRT is the evolution of the Component Object Model (COM) present in previous versions of Windows, with a completely different type of system (no binary string, no variant, and no RegSvr32) and the deletion of the IDispatch interface and connection points. It solves the main problems of actual applications in the absence of a marketplace in which to find and install applications in a secure mode, without administration permission. WinRT improves the performance and memory cost of necessary wrappers for the interoperability scenarios; it then simplifies the use of native language with the managed language (as with C# and VB.NET) and makes not-blocking the call to the input/output (I/O) device (net, disk, and so on). It also provides standard contracts for the data exchange among applications—and among applications and the operating system.

WinRT integrates the .NET Common Language Runtime (CLR) as a subplatform and doesn’t substitute it; it is responsible for many tasks of application memory management through the Garbage Collector, the compilation of the Intermediate Language (IL) code through the just in time (JIT) compiler. Some aspects of the .NET platform influenced many choices of WinRT—for example, the metadata format (ECMA-335), a standard that defines the Common Language Infrastructure (CLI), in which applications written in multiple high-level languages can be executed in different system environments (http://www.ecma-international.org/publications/standards/Ecma-335.htm) and libraries. The type system supports class, methods, properties, delegates, and events such as the .NET languages. The base types are bool, int, float, enum, guid, type, and object. The string, at a binary level, is a value type (not nullable), immutable and compatible with STL (wstring) and .NET (String). The reference types are all types that implement a WinRT interface; the others are value types. There are observable collections and dictionaries, too (Vector and Map). For user interfaces, there is a native implementation of XAML. Windows Presentation Foundation (WPF) and Silverlight don’t run in immersive mode, only in desktop mode, but there is a special portable library that allows the creation of DLL libraries shared between Windows Store apps, Desktop, Silverlight, Windows Phone, and Xbox applications!

Figure 2-1 shows the Windows 8 platform. You can see the WinRT layer as a set of object-oriented class libraries shared across programming languages. This is possible because the WinRT metadata are CLI metadata stored in a separate WINMD file (because native code that is processor-specific can’t contain metadata) and can be reflected like CLI assemblies.

9781430247012_Fig02-01.jpg

Figure 2-1. Windows 8 platform

These WinRT APIs can be grouped into five logical blocks based on their functionalities:

  • Application Model: Provides all functionalities for application life cycle management
  • Communication and Data: Provides all functionalities for data storage and communication between the internal and the external world
  • Graphics and Media: Provides all functionalities for media management
  • Devices: Provides all functionalities for managing available hardware devices
  • Services: Provides all functionalities to connect to services such as Skydrive, Bing, Azure Mobile, and Xbox Live

In Figure 2-2, you see these blocks detailed in subcomponents (discussed later in this chapter). Now we make some observations on application life cycle management, the importance of a responsive user interface (UI), and the sandbox in which the applications run. Notice that some items in the picture contain the suffix *(one asterisk) or ** (double asterisks). The meaning of these asterisks is to show what feature has been updated (*) and what features have been added (**) from the first version of the WinRT application programming interface (API) to version 8.1.

9781430247012_Fig02-02.jpg

Figure 2-2. WinRT functionality blocks

When an application is activated for the first time, its process is created and running, and the user interface is launched in full screen mode. If another application is activated, the first is hidden and is suspended after 5 seconds, sending a message to the application to save the current state. If it is reactivated, the system sends a resume message to the app for loading the saved state, and the process becomes active. If the available memory is too low, all suspended processes will be closed without notification messages to improve performance. Figure 2-3 shows application life cycle management.

9781430247012_Fig02-03.jpg

Figure 2-3. Application life cycle management

One of the problems of the previous version of Windows was installing and uninstalling applications without administration privilege. WinRT solves this problem in a way that doesn’t affect security. All Windows Store applications can be exclusively installed from the Windows 8 Store (the only exception is the installation through Visual Studio for developers’ purposes), the Microsoft Marketplace in which all developers can deploy its applications. The installation package, a zip folder with an .appx extension, contains an application manifest with the required information for the package installation, the application code files, a section called BlockMap with the hashes of all the application files, and a signature for the package validation.

The application manifest is an .xml file named appxmanifest.xml that explicitly declares all the capabilities required by the application: file access, device access, network and identity, file type association, and contracts. Don’t worry; it isn’t necessary to manually edit this file because Visual Studio has a visual editor for this purpose.

When you choose an application from the store for the installation, the system downloads the package, validates it, checks the integrity of all files through the hashes in BlockMap and checks the requirements declared in the manifest file. A component called Security Broker checks this manifest file to ensure that nothing can be used without user authorization (see Figure 2-4).

9781430247012_Fig02-04.jpg

Figure 2-4. Execution application sandbox

To allow compatibility among programming languages and WinRT, the projection mechanism was introduced to remap and fit the libraries’ metadata. For example, it solves the problem of JavaScript that uses CamelCase notation for properties and methods, PascalCase for types, and lowercase for events; while C++ and .NET use PascalCase notation for all. The projections are specific for every language; Microsoft provides projections for C++, JavaScript, and .NET; but in the future, other companies might provide projections for their languages. See Figure 2-5.

9781430247012_Fig02-05.jpg

Figure 2-5. Metadata compatibility through projections

Application Model

The Application Model component of WinRT APIs refers to fundamental components of the library responsible for application management. It’s composed of six main blocks:

  • Application Services
  • Threading & Timers
  • Memory Management
  • Authentication
  • Cryptography
  • Globalization
  • Diagnostics

The application services are located in the Windows.ApplicationModel namespace and contain the entire API for managing the application life cycle and handling operating system events. For example, the window of an immersive application, its thread, and its state changes are managed through the Windows.ApplicationModel.Core classes and interfaces (see Figure 2-6).

9781430247012_Fig02-06.jpg

Figure 2-6. Windows.ApplicationModel.Core classes and interfaces

Another interesting element is the Windows.ApplicationModel.Background namespace, which provides classes that enable an app to manage background tasks. Although the user interfaces of the immersive mode can appear to be monotasking, Windows is a multitasking operating system, so you can execute different applications at the same time and, with the background tasks, also execute more work items that do not require user interaction. Usually you use these kinds of tasks for call services, reacting to a change of a system condition, showing a notification, and so on. Later, we’ll analyze how to use this important feature, but now we are looking for a WinRT API that provides this functionality. Figure 2-7 shows the main classes and interfaces involved in background task management.

9781430247012_Fig02-07.jpg

Figure 2-7. Windows.ApplicationModel Background main classes and interfaces

Like the main object-oriented frameworks, you need to implement an interface that establishes the contract between your implementation and the system that executes your code. This interface is IBackgroundTask, which is required to implement the simple Run() method. Without a user interface, there must be another entry point for the execution of the task implemented, so you need to register your code for triggering an event with the SetTrigger() and Register() methods of the BackgroundTaskBuilder class. SetTrigger() accepts any implementation of the IBackgroundTrigger interface; WinRT offers PushNotificationTrigger, SystemTrigger, and MaintenanceTrigger, which allow you to handle the main events of the Windows 8 system. The Register() method returns an instance of the BackgroundTaskRegistration class, which is useful for handling Completed and Progress events.

With the marketplace system, the programmer can check some conditions of application usage, such as the license state for managing an evaluation version of the app. The reference namespace for this purpose is Windows.ApplicationModel.Store, which exposes the classes shown in Figure 2-8.

9781430247012_Fig02-08.jpg

Figure 2-8. Windows.ApplicationModel.Store classes

The most important item is CurrentApp, a static class that exposes all information that you need: the application identifier, the license information as an instance of the LicenseInformation class, and the link of the Windows Store web catalog. The LicenseInformation class provides two Boolean values, isActive and isTrial, that you can use in your application to enable or disable functionality.

The good news is that you don’t need to wait for the publication of your application for testing these values because the namespace provides the CurrentAppSimulator class, too. You can use this static class to simulate the CurrentApp behavior.

The remaining components of the Windows.ApplicationModel namespace are these:

  • Windows.ApplicationModel.Activation: Defines the items that support event handling for the contracts and extensions supported by Windows
  • Windows.ApplicationModel.Appointments: Defines the items that support the creation of appointments in a calendar
  • Windows.ApplicationModel.Calls: Defines the items that support event handling for the lock screen
  • Windows.ApplicationModel.Contacts: Defines the items that support the use of the Contact Picker to select and acquire information about contacts
  • Windows.ApplicationModel.DataTransfer: Defines the items used for the data exchange among applications such as the Clipboard
  • Windows.ApplicationModel.Resources: Defines the items that simplify access to the application resource, such as strings
  • Windows.ApplicationModel.Search: Defines the items that support the use of the search panel (discussed in the next section)

We will analyze these components in the sample applications, but now we focus on the Windows.Security namespace that provides the items for the authentications and protections of the immersive applications.

Windows 8 natively integrates Windows Live Services for user authentication and provides the API for this purpose in the Windows.Security.Authentication.OnlineId as well as different authentication services, such as OAuth and OpenID with the API in the Windows.Security.Authentication.Web namespace, providing all the mechanisms for the single sign-on (SSO) feature. Figure 2-9 shows the classes for the use of Windows Live services.

9781430247012_Fig02-09.jpg

Figure 2-9. Windows.Security.Authentication.OnlineId classes

The main operations are shown by the OnlineIdAuthenticator class through the AuthenticateUserAsync() and SignOutUserAsync() methods. Note that they are asynchronous operations; you can retrieve the instance of the UserIdentity class, which contains all the information about the user, calling the GetResult() method of the UserAuthenticationOperation retrieved by AuthenticateUserAsync().

Web services authentication is provided by a single static class called WebAuthenticationBroker (see Figure 2-10). The operation is performed by the static asynchronous method AuthenticateAsync(), which returns an instance of the WebAuthenticationResult class.

9781430247012_Fig02-10.jpg

Figure 2-10. Windows.Security.Authentication.Web classes

For storing in a shared and secure way, user identification information can be used for the classes of the Windows.Security.Credentials namespace, whereas encrypt and decrypt information can be used for the classes of the Windows.Security.Cryptography namespace.

Starting from Windows 8.1, new ways of authentication are possible. We can now use fingerprint scans, smart cards, and virtual smart cards to authenticate users.

The marketplace adds possible application customers from all countries that Windows Store supports. We can choose our application to be sold in only a particular country, but why should we close the possibilities of the global market? The System.Globalization namespace (see Figure 2-11) can help manage differences between many target cultures. We can use different types of calendars, different languages, a 12-hour clock instead of a 24-hour clock, and so on.

9781430247012_Fig02-11.jpg

Figure 2-11. Windows.Globalization classes and enumerations

To optimize application performance, you should run all tasks in parallel. For this purpose, WinRT provides the Windows.System.Threading and Windows.System.Threading.Core namespaces (see Figure 2-12), in which the ThreadPool static class exposes two overloads of RunAsync() methods to run the parallelizable codes in separate threads. A thread pool is more efficient than a single thread because it can schedule work items when threads become available. You cannot control the order in which the threads are executed, but you can use a ThreadPoolTimer to delay the execution from the scheduling start and set a WorkItemPriority based on your needs.

9781430247012_Fig02-12.jpg

Figure 2-12. Windows.System.Threading classes and enumerations

You can preallocate a work item before submitting it to the thread pool with the PreallocatedWorkItem class of the Windows.System.Threading.Core namespace. This namespace contains another interesting class, SignalNotifier, which can be used to create parallel work items to respond to named events or semaphores created by the Win32 COM object.

Communication and Data

The Communication and Data components of WinRT APIs are referred to the components of the library responsible for the communication of the application with the operating system and the external world, and support to the local and cloud storage. There are 12 main blocks:

  • Contracts
  • Local and Cloud Storage
  • Networking
  • SMS
  • Streams
  • XML and JSON
  • Background Transfer
  • Syndication
  • HTTP
  • Contacts
  • Appointments
  • PDF

The contracts establish the communication among applications, and among the applications and the operating system by using a publisher/subscriber relation. There are many contracts in Windows 8; we now take a look at the following:

  • Search: Integrates the application data in the search panel
  • Share: Shares documents, video, images, and so on

The goal of the search contract is to reuse the search functionality offered by the operating system, with the result being a centralized and user-friendly feature. Through the contract, the application provides its data, and the user can choose the application in the search criteria, too. The search contract uses the Windows.ApplicationModel.Search classes shown in Figure 2-13 to manage the data exchange.

9781430247012_Fig02-13.jpg

Figure 2-13. Windows.ApplicationModel.Search classes

The main class is SearchPane, which provides the GetForCurrentView() method to retrieve a reference to the search pane that can be used in the application. The Show() method shows the search panel and the property. QueryText contains the search text provided by the user. You can subscribe to the events offered by this class for managing the phases of search operations; for example, QueryChanged for when the user changes the search text, or SuggestionRequested and ResultSuggestionChosen for managing the search suggestions provided to users by the application. In the next chapters, we’ll show you how to use this interesting feature to improve the user experience of your application.

The share contract enables communication between applications using the Share Panel provided by the operating system. In the share contract, the source and the target application in the contract can be internal or external to the operating system (for example, your application and Facebook or Twitter). The namespace that contains the classes for this functionality is Windows.ApplicationModel.DataTransfer (its most important classes are shown in Figure 2-14). In the DataPackage class, we store the data to share, classified according to following types:

  • Plain text
  • Uniform Resource Identifier (URI)
  • HTML
  • Formatted text
  • Bitmaps
  • Files
  • Developer-defined data

9781430247012_Fig02-14.jpg

Figure 2-14. Windows.ApplicationModel.DataTransfer classes

For sharing the data stored in an instance of DataPackage class, we can use the DataTransferManager instance class associated with the current window that can be retrieved using the method GetForCurrentView(). When a user clicks a Share or Connect charm, the DataRequested event of the DataTransferManager fired; now we can share the data with the application selected by the user.

Our application can also be a target of data sharing; we’ll analyze this opportunity in the book sample application.

Each application needs to keep the information; in Windows 8, you can use three main solutions:

  • External services
  • Local storage
  • Cloud storage

External services can usually be applied when your Windows Store app is a client of an external application and the connection availability to the services is a strong requirement for the application. Local storage is a useful solution for applications that need to work also in disconnected mode, using an application reserved space of the device disk. Cloud storage, which includes the use of Skydrive services, is a good solution for saving the application data on the user’s cloud space. The WinRT API provides native objects for local storage; cloud storage is provided through an external API such as Windows Live SDK.

The classes for managing the local storage are located in the Windows.Storage namespace, in which you can find the classes shown in Figure 2-15.

9781430247012_Fig02-15.jpg

Figure 2-15. Windows.Storage main classes

The ApplicationData class provides the local storage access point through the Current property, with which you can retrieve an ApplicationDataContainer class instance using its LocalSettings property and an instance of the StorageFolder class from its LocalFolder property. The LocalFolder class provides asynchronous methods for creating files and folders in local storage.

The web services of the WinRT API are available on the Windows.Web namespace, in which you can find the main classes shown in Figure 2-16. You can iterate with Syndication web standards for exchanging data in XML format.

9781430247012_Fig02-16.jpg

Figure 2-16. Windows.Web main classes

Windows 8 implements the concept of notifications, already introduced in Windows Phone 7, which enable the system to send and receive asynchronous notification from cloud services. There are many types of notifications, including these:

  • Toast notification
  • Raw notification
  • Tile notification
  • Badge notification

These notifications are available starting from the Windows.Networking.PushNotifications namespace that contains the main classes shown in Figure 2-17. The main class is PushNotificationChannel, which exposes the PushNotificationReceived event that fires when a notification occurs. An instance of this class can be created from the PushNotificationChannelManager static class. The enumeration PushNotificationType enumerates the possible type of notification. (Details on the notifications' functionalities and workflow will be explained in Chapter 9.)

9781430247012_Fig02-17.jpg

Figure 2-17. Windows.Networking.PushNotifications main classes

As notifications, all the network functionalities offered by the Windows Runtime API are located in the namespace Windows.Networking, in which you can find the following:

  • Advanced download and upload transfer capabilities (Windows.Networking.BackgroundTransfer)
  • Information about connectivity, usage, and data plan information (Windows.Networking.Connectivity)
  • Mobile broadband account management (Windows.Networking.NetworkOperators)
  • Support connection between devices that are within close range (Windows.Networking.Proximity)
  • Access to socket and WebSocket for network communications (Windows.Networking.Sockets)

Windows 8 also provides the Short Message System (SMS) service, but it is in the Windows.Device.Sms namespace because it’s strictly connected to the device that Windows 8 runs. The SmsDevice class exposes all necessary objects for SMS operations: call SendMessageAsync() to send a SMS and subscribe to SmsMessageReceived to manage SMS receive events. See Figure 2-18.

9781430247012_Fig02-18.jpg

Figure 2-18. Windows.Device.SMS main classes

For reading and writing a sequential and random access stream, you can use the Windows.Storage.Streams namespace, in which specified stream type reader and writer classes usually support you in operations with data. For example, FileInputStream and FileOutputStream enable you to read and write file data. Very useful is the Windows.Data.XML namespace, which provides all the classes for managing XML data with two child namespaces:

  • Windows.Data.Xml.Dom explores the XML data tree
  • Windows.Data.Xml.Xsl transforms XML data in other XML formats through the XSLT transformation process.

Windows 8.1 introduces a new HTTP Client API located in the Windows.Web.Http namespace. This namespace provides the following:

  • HTTP verbs
  • Authentication
  • Support for SSL
  • Cookies management

The main class is HttpClient, which is similar to the ASP.NET version.

Graphics and Media

Graphics and media enable the developer to handle various aspects related to physical display, photos, audio, and video.

The first namespace we will discuss is Windows.Graphics.Display, which contains the objects shown in Figure 2-19.

9781430247012_Fig02-19.jpg

Figure 2-19. Windows.Graphics.Display classes and enumerations

DisplayProperties, which is the main class of the namespace, enables you to get information about the physical display of the device. The most common properties are AutoRotationPreferences, CurrentOrientation, and LogicalDPI, which return the default orientation, the current orientation, and the number of pixels for inches for the current resolution, respectively. Notice that the first one returns an object of the DisplayOrientations enum type. Through public events, we can handle all changes of state for these properties. For example, LogicalDpiChanged is triggered when the LogicalDpi or ResolutionScale properties were modified because of a zoom in/out on the screen or a change to the screen resolution. OrientationChanged is triggered when users change the ways they move devices in their hands (here we are referring to a tablet!).

The Windows.Graphics.Imaging namespace lets you manipulate different image formats (based on system known codecs). Figure 2-20 shows the most useful elements in this namespace.

9781430247012_Fig02-20.jpg

Figure 2-20. Windows.Graphics.Imaging classes and enumerations

ImageStream is a class that allows memorization of image data based on a stream format. It is possible to manage the image data using the ReadAsync() and WriteAsync() methods. Other methods, such as Seek(), GetInputStreamAt(), and GetOutputStreamAt(), can be used to position on the stream. An instance of the ImageStream class can also be used as input for the CreateAsync() method inside the BitmapDecoder and BitmapEncoder classes. These classes allow you to read an image or create, manage, and save an image in a file. The CreateAsync() method (overload included) gets an inherited object of IRandomAccessStream. Moreover, both classes contain the GetDecoderInformationEnumerator() method, which returns an object of the System.Collection.Generic.IReadOnlyList<Windows.Graphics.Imaging.BitmapCodecInformation> type. Finally, GetPreviewAsync() and GetThumbnailAsync() are useful whenever we need a preview or a thumbnail, returning a Windows.Graphics.Imaging.ImageStream object.

Inside the Windows.Graphics namespace is the Windows.Graphics.Printing namespace (discussed later).

Windows.Media contains the classes shown in Figure 2-21.

9781430247012_Fig02-21.jpg

Figure 2-21. Windows.Media interfaces, classes, and enumerations

The MediaControl class allows applications to subscribe to notifications by audio and video systems on the device whenever it is triggered. It is possible to handle events that are triggered whenever a user presses a button related to webcam or audio settings on the device. As shown in Figure 2-21, the MediaControl class contains events such as PlayPressed, StopPressed, and RecordPressed. By managing these events, we can specify what instruction is executed when they’re triggered (e.g., manipulating the AV stream). Other information about playing media can be retrieved using MediaControl properties such as TrackName, ArtistName, IsPlaying, and SoundLevel (the last one is an enumeration; refer to Figure 1-19).

In the same namespace is the MediaExtensionManager class, which enables registering a codec for a specific audio/video stream. But there are some restrictions:

  • Registration is valid only for the lifetime of the MediaExtensionManager instance.
  • Registration is valid only for the current application.
  • A plug-in can override media formats on the device.

Last but not least is the VideoEffects class, which allows a decrease in video shaking by the VideoStabilization property. This property takes as input the name of the effect to apply to the video.

The Windows.Media.Capture namespace contains all the classes for photos, audio recordings, and videos captured (see Figure 2-22).

9781430247012_Fig02-22.jpg

Figure 2-22. Windows.Media.Capture classes and enumerations

The MediaCapture class is used to save audio, videos, and photos. These capabilities are supplied by the following methods:

  • Photo
  • CapturePhotoToStorageFileAsync
  • CapturePhotoToStreamAsync
  • Audio/video
  • StartPreview[ . . . ]Async (where . . . are the different overloads)
  • StartRecord[ . . . ]Async (where . . . are the different overloads)
  • StopPreviewAsync()
  • StopRecordAsync()

In one available overload, stream capture needs to be initialized using the InitializeAsync() method, which takes in input a class of Windows.Media.Capture.MediaCaptureInitializationSettings type that provides initial settings for the capturing object (e.g., StreamingCaptureMode). During the first use, this method will show you a pop-up asking permission to use the device microphone or webcam inside the application. It is a good practice to use InitializeAsync() inside the main UI thread of your app.

The CameraCaptureUI class, which shows a full-screen UI to capture a single video or photo, is in the same namespace. Photo or video can be saved using the CaptureFileAsync() method that takes in input an enumeration of CameraCaptureUIMode type that defines the type of input: audio, video, or photo. All the information related to this class is set using CameraCaptureUIPhotoCaptureSettings and CameraCaptureUIVideoCaptureSettings.

The Windows.Media.Devices namespace has classes to help manage audio, video, and communications such as webcams or microphones (integrated or plugged). Figure 2-23 summarizes the most common classes.

9781430247012_Fig02-23.jpg

Figure 2-23. Windows.Media.Device classes

MediaDevice is the most important class in this namespace. It is a static class that contains five methods:

  • GetAudioCaptureSelector() returns the device ID for capturing audio.
  • GetAudioRenderSelector() returns the device ID for rendering audio.
  • GetDefaultAudioCaptureId() returns the default device ID for capturing audio.
  • GetDefaultAudioRenderId() returns the default device ID for rendering audio.
  • GetVideoCaptureSelector() returns the device ID for capturing video.

GetDefaultAudioCaptureId() and GetDefaultAudioRenderId() return the default device ID for capturing or rendering audio in a specific role: default (e.g., media) or communication.

In the same namespace are the following classes:

  • AudioDeviceController sets properties as Muted or VolumePercent.
  • VideoDeviceController, MediaDeviceControl, and MediaDeviceControlCapabilities retrieve and manage settings related to the camera (e.g., zoom, brightness, focus, and supported encoding properties).
  • CallControl handles calls on a device that provides phone capabilities.

The Windows.Media.MediaProperties namespace (see Figure 2-24) contains classes that allow management of properties related to the media stream. AudioEncodingProperties, ImageEncodingProperties, and VideoEncodingProperties help to set audio, photo, and video properties. The ContainerEncodingProperties class enables setting up properties about media containers. A media container stores information related to a media stream and contains the following:

  • A header with all the properties on a media stream (such as the number and the format type)
  • An index to allow random access to the content
  • Content metadata (artist, title, and so on)

9781430247012_Fig02-24.jpg

Figure 2-24. Windows.Media.MediaProperties classes and enumerations

The word container is more often used than file because it is common to refer to a container in a live streaming context. You can use a container without having to save it to a file.

Figure 2-25 shows the content of Windows.Media.Playlists. This namespace contains only one class, Playlist, which manages different playlist formats. Thanks to the methods LoadAsync()and SaveAsync() of Playlist, you can read and save playlists in different formats using the PlaylistFormat enumeration.

9781430247012_Fig02-25.jpg

Figure 2-25. Windows.Media.Playlists classes and enumerations

The Windows.Media.PlayTo namespace helps to send audio, photo, and video toward remote certified devices. This feature is based on the Digital Living Network Alliance (DLNA) technology that allows streaming media over Wi-Fi (see http://en.wikipedia.org/wiki/Digital_Living_Network_Alliance). An application that needs to use the PlayTo feature has to register with the SourceRequested event inside the PlayToManager class. This event is triggered whenever a user clicks the Device item inside an application on the right. But it is really recommended to use a specific Play To app button inside the application to open up the Play To flyout. This feature can be enabled programmatically by calling the Windows.Media.PlayTo.PlayToManager.ShowPlayToUI() method (supported only in Windows 8.1). The PlayToManager class manages all the settings related to the PlayTo feature.

As a destination for a media stream, you can also choose a specified target using the property DefaultSourceSelection. Using the PlayToReceiver class, you can create a custom software PlayTo receiver that allows you to play (or display), stop, or manage content stored on computers inside the network (see Figure 2-26).

9781430247012_Fig02-26.jpg

Figure 2-26. Windows.Media.PlayTo classes and enumerations

The Windows.Media.Protection namespace provides classes to manage Digital Rights Management (DRM) media contents (see Figure 2-27). The MediaProtectionManager class can be passed as input to the following:

  • A media playback API
  • The msSetMediaProtectionManager attribute inside the tag’s video or audio

9781430247012_Fig02-27.jpg

Figure 2-27. Windows.Media.Protection classes

The last namespace in Windows.Media is Windows.Media.Transcoding (see Figure 2-28), which transcodes audio and video files. Transcoding a media file means converting it from one format to another. But that’s not all! You can also add effects or trim pieces from the file.

9781430247012_Fig02-28.jpg

Figure 2-28. Windows.Media.Transcoding classes and enumerations

Whereas the MediaTranscoder instance stores an object to convert, the PrepareFileTranscodeAsync class is used to transcode an audio or video stream to a target format. This class contains a method called TranscodeAsync() that takes as input an object of MediaEncodingProfile that provides some of the following methods:

  • CreateMp3()
  • CreateMp4()
  • CreateWav()
  • CreateWma()
  • CreateWmv()

PrepareFileTranscodeAsync returns an instance of PrepareTranscodeResult that notifies the operation outcome by FailureReasonProperty (this property returns a value of TranscodeFailureReason enumeration).

Windows 8 is a user-centric operating system that not only helps developers but also supports hardware designers to provide the best UX. With Windows 8, a hardware vendor can customize components in the printing system to give access to all functionalities of the device. Before the arrival of Windows 8, Windows used the v3 printer driver model that functioned in desktop mode until now. Starting with this version, Windows supports a redesigned printer driver model. It’s called the v4 printer driver model and it integrates Windows Store apps to provide a better UX with a customized print UI. The framework of classes that helps device manufacturers create v4 drivers is fully integrated with the Windows.Graphics.Printing namespace (shown in Figure 2-29) that you can use in your apps to participate in printing.

9781430247012_Fig02-29.jpg

Figure 2-29. The Windows.Graphics.Printing namespace

The Windows.Graphics.Printing namespace contains two main classes: PrintManager and PrintTask. PrintManager, which is the entry point for printing, allows you to subscribe to the PrintTaskRequested event that fires when the user selects the Devices charm. This event uses the PrintTaskRequestedEventArgs class as an argument, which enables you to create an instance of PrintTask that contains the content to print and options about the process. For example, accessing the DisplayedOptions property of the Options property contained in PrintTask enables you to easily manage options exposed by the default print UI, such as Copies or PrintQuality (a list of standard print options are exposed by the StandardPrintTaskOptions class).

PrintTask is the core class on which Printing is based. Every PrintTask is a printing operation and can transit through four states:

  • Preview is managed by the Previewing event that occurs when the system makes a print preview.
  • Submit is managed by the Submitting event that fires when the user chooses to print the document.
  • Progress is managed by the Progressing event that fires when pages are submitted to the printer, providing information about the remaining pages to print.
  • Complete is managed by the Completion event that occurs when the process is finished, providing information about the way the process is completed (successful, canceled, or failed).

When we talk about printing in Windows 8, we must talk about the Windows.UI.Xaml.Printing namespace (see Figure 2-30). If you use XAML, you know that through this technology you can prepare UIElements (the base class used by languages based on XAML used as the core for components implementation) to be printed. These functionalities are exposed under the Windows.UI.Xaml.Printing namespace from the PrintDocument class that automatically interacts with PrintManager and allows you to create a page (written with XAML) and prints it as a document.

9781430247012_Fig02-30.jpg

Figure 2-30. PrintDocument class

To conclude, use Windows.Graphics.Printing when you need to print your own document format and you require greater control over the printing process; use Windows.UI.Xaml.Printing when you need to print UIElements.

The Windows 8.1 update brings also supports 3D printing. Two classes are responsible for the communication with a 3D printer: IXpsDocumentPackageTarget3D and IXpsOMPackageWriter3D. The first is the job containing all the details and a print queue. The second contains the methods to send data into the Windows spooler as an Open Packaging Conventions (OPC) package. (You can find more information here: http://msdn.microsoft.com/en-us/magazine/cc163372.aspx). In a few words, this package is based on two containers: parts and contents (see Figure 2-31).

9781430247012_Fig02-31.jpg

Figure 2-31. OPC package

In the content, there is a 3D model component that contains XML markup to define the object to print.

Devices and Printing

Minimum device requirements for Windows 8 are not too restrictive and focus on tablet and hybrid tablet-laptop devices. To install Windows 8 on a tablet, it has to provide the capabilities shown in Table 2-1.

Table 2-1. Device Capability Requirements

Category

Type

Description

Storage

Space

At least 100 GB of free space after the installation of the operating system

Firmware

Firmware type

Unified Extensible Firmware Interface (UEFI) firmware required

Networking

WLAN and Bluetooth 4.0

These two components are required

Graphics

GPU

Direct3D10 support

Graphics

Screen resolution

Minimum 1366 x 768

Touch

Five-finger touch

Requires a touch monitor with five points of touch

Camera

Front/user facing camera

Minimum 720p camera

Sensors

Ambient light sensor

Necessary for auto-adjust screen brightness

Sensors

Magnetometer

Sensors

Accelerometer

Sensors

Gyroscope

Device

USB 2.0

At least one USB 2.0 controller with a port exposed

Output

Speaker

A speaker for audio output is required

In addition to these components, others are available that are not required for the producer, such as the optional A-GPS device that is ready to be managed from the system (and your app). When we talk about the Device and Printing components of the WinRT API, it means the part of the library responsible for management of the following:

  • Geolocation
  • Portable
  • Sensors
  • NFC devices

Although these components are not required, you can write your app to exploit these components, giving the Windows Store the task of managing the installation on the appropriate device.

Geolocation is located under the Windows.Devices.Geolocation namespace (see Figure 2-32) that enables your app to retrieve the device’s geographic location, provided from multiple devices:

  • Wi-Fi triangulation
  • IP Geolocation
  • GPS devices

9781430247012_Fig02-32.jpg

Figure 2-32. Geolocation namespace diagram

Geolocator is the entry point of Geolocation and provides events to track changes of position (identified by the GeoPosition class that exposes the Geocoordinate and CivicAddress linked to the current position) and events to track status changes. (It allows your app to know when the location device is ready to use.)

When you create your app, you’ll find APIs to manage Media Transfer Protocol (MTP) device services through Windows Portable Devices (WPDs) inside the Windows.Devices.Portable namespace (shown in Figure 2-33). WPD offers an infrastructure able to standardize data transfers between applications and portable devices such as portable media players, digital still cameras, and mobile phones.

9781430247012_Fig02-33.jpg

Figure 2-33. Class diagram of the Windows.Devices.Portable namespace

MTP is the evolution of the Picture Transfer Protocol (PTP), with which you can transfer images from digital cameras to computers without installing a driver. MTP allows more types of devices, such as digital audio players and portable media, to communicate with the operating system. The ServiceDevice static class allows you to discover and identify a MTP device service for a WPD. Access through this API to the MTP device service is available only to Windows Store apps, giving privileged access by the device manufacturer. The StorageDevice class enables your apps to access a storage device.

When you think about an app for tablets, you certainly assume that the device can be equipped with sensors (e.g., Accelerometer). The Windows.Devices.Sensors namespace (see Figure 2-34) has several classes that manage sensors.

9781430247012_Fig02-34.jpg

Figure 2-34. Diagram of a subset of the Windows.Devices.Sensors namespace

The Accelerometer class manages the sensors that measure the G-force applied along the three axes. If you come from a Windows Phone platform, note that this class exposes an event called Shaken that occurs when the device is shaken. The Compass class gives you information about true north and magnetic north.

image Note  The measurement of magnetic north is optional and depends on the capabilities of the sensor; only the true north measurement is required. Remember that the Compass sensor is not required.

The Gyrometer class reports the angular velocity with respect to the three axes and enables your app to manage the rotation velocity of the device. Inclinometer manages the inclination of the device and reports information about pitch, roll, and yaw. These terms are usually used for aeronautical, nautical, and automobile purposes:

  • Pitch is the leaning back or forth of the muzzle.
  • Roll is the oscillation around the longitudinal axis.
  • Yaw is the oscillation around a vertical axis passing through the center of gravity of the item.

Through this sensor, you can evaluate how much a user tilts the device compared with the three axes. LightSensor measures the ambient light using LUX as units. Using this sensor (if it’s present), you can personalize the user experience depending on the available light (e.g., you can adaptively change the color of your UI depending on ambient light, with a high-contrast combination if there is too much light, and vice versa).

Finally, you can retrieve information about the orientation of the device using OrientationSensor, which returns a matrix (3 x 3) with rotation values and a Quaternion. You can use this sensor to adjust the in-game prospective of a player, depending on the orientation of the device.

image Note  Avoid using OrientationSensor in your Windows Store apps if it’s not necessary. Windows Store apps already support different orientations that change layouts relative to device orientation.

The last sensor is the simplified version of OrientationSensor called SimpleOrientationSensor. This simplified version allows you to detect the current orientation of the device and its face-up and face-down status. For example, you can use this sensor in a messenger app that shows the user as unavailable when the device is face down and then notifies other users that it has come back when the device is face up.

Near field communication (NFC) is a standard for communication between devices and covers protocol and data format, whereas communication is based on the existing radio-frequency identification (RFID) that regulates close communication (no more than a few centimeters). The Windows.Devices.Proximity namespace (see Figures 2-35 and 2-36) contains APIs to support this standard. Using these APIs, you can write an app that shares content with another computer near a user device. The entry point to use Proximity in order to know when a device enters and leaves proximity is the ProximityDevice class (see Figure 2-35), which exposes two events:

  • DeviceArrived: This event occurs when a compatible device enters the proximate range.
  • DeviceDeparted: This event occurs when a connected device leaves the proximate range.

9781430247012_Fig02-35.jpg

Figure 2-35. Windows.Devices.Proximity namespace: ProximityDevice involved classes

9781430247012_Fig02-36.jpg

Figure 2-36. Proximity namespace: PeerFinder involved class diagram

For example, you can use proximity in a massive multiplayer role playing game (MMRPG), in which a user taps a device to help another user. Or in an app that manages contacts, the user can simply share a business card with a tap. The Windows.Devices.Proximity namespace exposes another interesting class named PeerFinder (see Figure 2-36) that helps you find close devices (using different types of connection technologies, such as Wi-Fi Direct or Bluetooth) that run your application to establish long-term connections.

Windows 8.1 also brings in new APIs to support the following types of device:

  • Human Interface Device (HID)
  • Point of Service (PoS)
  • USB
  • Bluetooth
  • Wi-Fi Direct

HIDs are supported on different type of transport: USB, Bluetooth, Bluetooth LE, and I2C. (Get more information on HID here: http://msdn.microsoft.com/it-it/library/windows/hardware/jj126202.aspx.) There are few limitations to the HID devices API: first, we can only use Windows 8.1 built-in drivers to access the device through the API (unfortunately, vendor drivers are not supported). It might also block top-level collection that can take advantage of the following usage pages:

  • HID_USAGE_PAGE_UNDEFINED
  • HID_USAGE_PAGE_GENERIC
  • HID_USAGE_GENERIC_KEYBOARD
  • HID_USAGE_GENERIC_KEYPAD
  • HID_USAGE_GENERIC_SYSTEM_CTL
  • HID_USAGE_PAGE_KEYBOARD
  • HID_USAGE_PAGE_CONSUMER
  • HID_USAGE_PAGE_DIGITIZER
  • HID_USAGE_PAGE_SENSOR
  • HID_USAGE_PAGE_BARCODE_SCANNER
  • HID_USAGE_PAGE_WEIGHING_DEVICE
  • HID_USAGE_PAGE_MAGNETIC_STRIPE_READER
  • HID_USAGE_PAGE_TELEPHONY

The namespace to access HID devices is Windows.Devices.HumanInterfaceDevice, in which the main classes to retrieve data from a device are HidDevice and HidInputReport (see Figure 2-37). HidDevice enables connection to a device using the GetDeviceSelector() method to create a selector for a HID device and then the FromIdAsync() method to open a connection. Instead, to retrieve data, methods such as GetNumericControl() and GetBooleanControl() in HidInputReport can be used.

9781430247012_Fig02-37.jpg

Figure 2-37. HID main classes inside the Windows.Devices.HumanInterfaceDevice namespace

Because Windows 8 is created to run on different kinds of devices, PoS support can be really useful if you want to create an application to handle payments in a shop. This API is contained in the Windows.Devices.PointOfService namespace and it supports barcode scanners and magnetic stripe readers. Depending on what device you use, you can instantiate a BarcodeScanner class or a MagneticStripeReader class (see Figure 2-38).

9781430247012_Fig02-38.jpg

Figure 2-38. Windows.Devices.PointOfService namespace main classes

For a barcode scanner, use the BarcodeScanner.GetDefaultAsync() method (or BarcodeScanner.ClaimScannerAsync() method for exclusive use) to connect to a device. Then subscribe to the ClaimedBarcodeScanner.DataReceived() event. Finally, use the ClaimedBarcodeScanner.EnableAsync() method to retrieve data.

For a magnetic stripe reader, use the MagneticStripeReader.GetDefaultAsync() method (or MagneticStripeReader.ClaimReaderAsync method for exclusive use) to connect to a device. Then subscribe to the ClaimedMagneticStripeReader.BankCardDataReceived or ClaimedMagneticStripeReader.AamvaCardDataReceived event. Finally, use the ClaimedMagneticStripeReader.EnableAsync() method to retrieve data.

The USB API allows communication to a USB device for which Windows does not provide any built-in drivers. There are few requirements:

  • The USB device has to use the Winusb.sys driver.
  • Information about the device has to be provided in the app manifest (capability).
  • The device has to belong to one of these USB device classes:
  • CDC control class (class code: 0x02; subclass code: any; protocol code: any)
  • Physical class (class code: 0x05; subclass code: any; protocol code: any)
  • PersonalHealthcare class (class code: 0x0f; subclass code: 0x00; protocol code: 0x00)
  • ActiveSync class (class code: 0xef; subclass code: 0x01; protocol code: 0x01)
  • PalmSync class (class code: 0xef; subclass code: 0x01; protocol code: 0x02)
  • DeviceFirmwareUpdate class (class code: 0xfe; subclass code: 0x01; protocol code: 0x01)
  • IrDA class (class code: 0; subclass code: 0x02; protocol code: 0x00)
  • Measurement class (class code: 0xfe; subclass code: 0x03; protocol code: any)
  • Vendor-specific class (class code: 0xff; subclass code: any; protocol code: any)

The Windows.Devices.Usb namespace contains all the classes to interact with a USB device. Figure 2-39 shows the main classes.

9781430247012_Fig02-39.jpg

Figure 2-39. Windows.Devices.USB namespace main classes

To connect to a USB device, we need to use the UsbDevice.GetDeviceSelector() to retrieve the device information and then use the UsbDevice.FromIdAsync() to pass the device information previously retrieved.

Bluetooth APIs are contained inside the Windows.Devices.Bluetooth.RFCOMM and Windows.Devices.Bluetooth.GenericAttributeProfile namespaces (see Figure 2-40). These APIs take advantage of the RFCOMM Protocol or GATT Profile (used for Bluetooth LE devices) to communicate with devices. Notice that the Bluetooth device needs to be discovered and paired before it can be used through the APIs.

9781430247012_Fig02-40.jpg

Figure 2-40. Windows.Devices.Bluetooth.RFCOMM and Windows.Devices.Bluetooth.GenericAttributeProfile namespace main classes

Finally, Wi-Fi Direct APIs enable us to include the possibility to connect to Wi-Fi Direct–supported devices in the app. The WiFiDirectDevice class manages connections through devices using the GetDeviceSelector() method and the FromIdAsync() method. Figure 2-41 shows the Windows.Devices.WiFiDirect namespace classes.

9781430247012_Fig02-41.jpg

Figure 2-41. Windows.Devices.WiFiDirect namespace

Conclusion

Learning about the library that is the basis of the main new features of Windows 8 is essential for understanding how to develop applications that take full advantage of the platform created by Microsoft. This chapter analyzed the main components of Windows Runtime for the development of Windows Store apps, which will be useful in the following chapters, in which you design and implement your first application.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.152.157