Chapter 3

Windows 8 Architecture from a Developer’s Point of View

WHAT YOU WILL LEARN IN THIS CHAPTER:

  • Understanding the separate technology stacks for Windows 8 style applications and desktop applications
  • Grasping the role of Windows Runtime in developing Windows 8 style applications
  • Getting to know which programming languages can be used to access Windows Runtime application programming interfaces (APIs)
  • Understanding the new features of .NET Framework 4.5
  • Choosing the appropriate programming language and technology stack to create your own Windows 8 applications

When you develop applications, you generally use a set of technologies that work together. The Windows development platform provides a plethora of tools, techniques, and technologies. In the last decade, the number of these components increased tremendously. Windows 8 provides a new development model via a new kind of application — Windows 8 style apps — that support several programming languages (C++, C#, Visual Basic, JavaScript), and still keeps the number of related technology components low. Windows 8 still allows developing traditional desktop applications.

In this chapter, you learn about the architecture of components that help you to develop Windows 8 apps. You start with getting to know the difference between desktop and Windows 8 app development technology stacks. As you will learn, the key component of Windows 8 app development is the Windows Runtime, so you will learn about its structure and benefits. Choosing the appropriate technology for a particular application is not easy. This chapter concludes with a section that helps you to make this decision easier.

Windows 8 Development Architecture

As you have learned, Windows 8 enables you to develop a new kind of application — Windows 8 style applications — while traditional desktop applications still run on Windows. Moreover, you can still use your favorite tools and technologies to develop Windows 8 style applications.

The architects of Windows 8 made an important decision when they created a new stack of architecture layers for Windows 8 style applications. Therefore, in Windows 8, you have two fundamental stacks of technologies (one for Windows 8 style applications, and one for desktop applications) that can be used side-by-side, as shown in Figure 3-1.


NOTE An architecture layer is a set of components having the same role (for example, communicating with the operating system). A stack of architectural layers mirrors how the services of those layers are built on each other.

Figure 3-1: Windows 8 has separate stacks of architectural components for Windows 8 style applications and desktop applications

c03f001.eps

Although these Windows 8 style applications and desktop applications use the same operating system kernel, you have some important things to consider when it comes to application development. Table 3-1 provides a comparison of the two kinds of applications.

Table 3-1: Desktop Applications and Windows 8 Style Applications

Desktop ApplicationsWindows 8 Style Applications
Desktop applications can be programmed either on top of the Win32 application programming interface (API) that dates back to 1995 (and many of its parts even to 1991), or with the .NET Framework that uses managed base classes. As you learned in Chapter 1, “A Brief History of Windows Application Development,” you have a wide variety of language, tool, and technology choices for desktop applications. Although the richness of options is a great thing, from an application development point of view, it can be a disadvantage. Depending on the aim of your application — or your intention — you may pick up a mix of languages or technologies to program the expected functionality.Windows 8 style applications represent a new approach. They are about providing a first-class user experience with multi-touch and sensors, and they are very sensitive in terms of user interface (UI) responsiveness. Imagine an application where you can drag an object on the screen with your finger, rather than experiencing a choppy response as you move the object across the screen with your mouse. To ensure the perfect experience, the API used for Windows 8 style applications should support UI responsiveness natively. Of course, Windows 8 style apps still support perfect mouse and keyboard integration.
Most desktop applications display windows and dialog boxes on the screen, and wait for user input, response, or confirmation. Sometimes these applications show more than one modeless dialog box (that is, dialogs that let you you switch back to the main applications without closing the dialog) over the main window. While working, the user must shift from one window to another, often focusing on distinct tasks simultaneously, sometimes unconsciously.Windows 8 style application development is about providing an intuitive UI where the application owns the full screen. This approach does not encourage using dialog boxes popped up on the screen, but rather suggests using application pages, just as web applications running in the browser do. Windows 8 style applications can be deployed through Windows Store, and must conform with UI and user experience guidelines published by Microsoft in order to pass the certification process.
Desktop applications generally require a standard setup procedure that incorporates a few screens that guide the user through the installation steps. The whole process may take a minute (or even more) while all files and resources are copied to the computer, and necessary registrations take place. Removing an application also follows a standard procedure, and it requires the user to start with the Control Panel.Windows 8 style applications are for consumers who are not necessarily familiar with concepts like files, the registry, and setup procedures. These users expect to be able to add an application to their portfolio with a simple touch or click, and all the other steps are automatically done by the system. These users want to be able to remove programs with the same ease — not caring how Windows implements this procedure behind the scenes.

As you can see, as a result of a consumer-centric approach to this information technology, expectations for Windows 8 style applications are very different compared to traditional desktop applications. The Windows architect team decided to create a separate subsystem for Windows 8 style applications, and also a distinct API to build them.

Before diving into the details of this new API, let’s first take a look at the architectural components of traditional desktop applications.

Desktop Application Layers

To build traditional desktop applications, the developer has available a wide variety of application types with related component stacks. It is funny (but not surprising) how the word “traditional” now has a totally different meaning than it used to have a few years ago (say, perhaps five years ago). Although, with the emergence of Windows 8, you can call all the application stacks shown in Figure 3-2 “traditional,” the managed application stack was quite new in 2002, and the Silverlight stack is the youngest, available since 2008.

Figure 3-2: Desktop application layers

c03f002.eps

NOTE Do not feel intimidated if you do not know all the technologies depicted in Figure 3-2. The aim of this figure is to show you the variety of technology components related to desktop application development. If you are interested any of them in particular, search the MSDN (http://msdn.microsoft.com) using their names.

Notice in Figure 3-2 the relationship between the Language Layer and the UI Layer. As you can see, the chosen programming language fundamentally determines the stack of technologies you can use to create your desktop application.

For native applications, choosing C or C++ (or other native languages such as Visual Basic, Object Pascal, and so on) that are compiled directly to CPU-specific code means that you must use graphics device interface (GDI) or GDI+ technologies for the UI.

With managed applications, you could still use GDI and GDI+. (In .NET, they are used under the alias of Windows Forms.) A more modern and powerful choice is Windows Presentation Foundation (WPF)—which is based on eXtensible Application Markup Language (XAML)—or its younger (but not less powerful) sibling, the Silverlight XAML.


NOTE While native applications are compiled directly to CPU-specific code, managed applications are translated to an intermediate language (IL). When you run a managed application, the IL is transformed to CPU-specific code by a just-in-time (JIT) compiler.

Though it is not common to create desktop applications with HTML and related technologies, you can create them using HTML Applications (HTAs).

Your language preference also determines the available runtime libraries and environments you can use while programming (the Runtime Layer shown in Figure 3-2). These libraries contain operations that are natively used by the language to access operating system services, such as displaying values, managing files, or communicating through the network. With native applications, each language used to have in its own language run time, such as Microsoft Foundation Classes (MFC) and Active Template Library (ATL) for C/C++, VB Runtime for Visual Basic (the good old Basic language before the emergence of .NET), or Visual Component Library (VCL) for Delphi (Object Pascal).

.NET eliminated this by introducing its own Base Class Library that is available in all .NET languages, including C# and Visual Basic (as well as other popular .NET languages such as F#, IronPython, IronRuby, and others). Nonetheless, this uniform picture got a bit blurred with the release of Silverlight, which has yet another .NET run time available both in browser applications (such as Internet Explorer, Firefox, Safari, and in a few others) and in desktop applications. The Silverlight Base Class Library is only a subset of runtime types available in .NET.

The runtime libraries of native applications are built on top of the Win32 API (shown in the API Layer in Figure 3-2), which is a flat API with tens of thousands (actually unrelated) entry points that invoke Windows Core OS Services (the Kernel Layer in Figure 3-2). In contrast, .NET has its own runtime environment — called Common Language Runtime (CLR)—that provides a better abstraction of the Win32 API in forms of objects that package related data structures and operations into reusable types.

Imagine that you’re an architect who wants to create the development component stack for Windows 8 style applications. Would you merge it with the existing desktop application technologies? Perhaps, but nonetheless, the architect team at Microsoft decided to create a new, independent set of APIs to get rid of the technology fragmentation.

Windows 8 Style Application Layers

With the consumer-centric approach of the Windows 8 operating system, Microsoft now faces new challenges. Creating an intuitive, multi-touch-enabled, always-responsive UI is only one of the challenges. A bigger challenge is establishing a platform that supports developers the right way, allowing them to use the technology and tools they know, and most importantly of all, to be productive.

The Challenge

Microsoft has a very strong development community working with Windows. A vast number of developers have experienced the “consumerization” of IT through web application development. However, only a very small number of developers are familiar with Windows-based consumer devices, namely Windows Phone developers. For a long time, Windows Phone was the only real consumer device from Microsoft.

Many web developers and hobbyists around the world — more than the whole Microsoft community camp — have experience with consumer application development for the Android (Google) or iOS (Apple) platforms. Windows 8 is intended to be an operating system that attracts not only professional Windows developers, but also those who are not closely related to the Microsoft community.

Microsoft seems to have begun gearing up very late in the competition for winning over consumers. Creating new devices and their operating systems is one important step to meeting the competition, but without having a great development platform and strategy, it would not be possible to provide quality applications that were good enough to strengthen Windows, and provide quality alternatives to consumers.

Microsoft has always provided great development tools that have been continuously evolving over time, tools that have offered great productivity. Instead of betting on only one programming language for its platform (such as what Apple and Google do), Microsoft accommodates a plethora of programming languages, and lets its developers choose the one they intend to work with. Providing the best platform for creating consumer applications is definitely a key factor to attaining a better market position.

Microsoft has answered this challenge with the development platform for Windows 8 style applications.

Architecture Layers Overview

By creating an independent stack of layered components for Windows 8 style applications, Microsoft has introduced a new concept that casts off the issues of traditional desktop application development, and reimages the idea of Windows API and language run times. This new concept embraced the support for multiple languages over a single programming API, as shown in Figure 3-3.

Figure 3-3: Windows 8 style application technology layers

c03f003.eps

You can derive a few important things from Figure 3-3.

All Windows 8 style applications have one ultimate API layer — Windows Runtime — to talk to Windows Core OS Services, and there is no other API a program would need to access them. Independently of the programming language used, every service is available without any limitation, so that you can access from C++, C#, Visual Basic, and JavaScript, too.

HTML and CSS are used by millions of developers all around the world to create websites and web pages. These developers use JavaScript to add (sometimes complex) UI logic to their web pages. In the Windows 8 style application model, Microsoft augmented the potential for JavaScript to access the full set of APIs offered through Windows Runtime.

The newest standard of HTML (HTML5), combined with Cascading Style Sheets 3 (CSS3) and JavaScript, is more powerful than its predecessors. HTML5 sites can natively play multimedia and display vector graphics — leveraging the hardware acceleration of the graphics processing unit (GPU) in the computer. Over the past couple of years, thousands of new websites have been built with HTML5 to provide the user experience of a new era. All this power can be immediately used by developers familiar with HTML and JavaScript technologies to create Windows 8 style applications.

In Windows 8, the core of the XAML-based WPF and Silverlight technologies has become a part of the operating system — rewritten in native code. The UI of C++, C#, and Visual Basic applications can be defined in XAML. The same XAML produces the exact same UI in every language — without constraints or barriers. Because of the uniform UI technology and the same APIs providing access to the operating system services, application models are the same for C++, C#, and Visual Basic.

If you compare the desktop application architecture layers in Figure 3-2 with Windows 8 style application layers in Figure 3-3, you can immediately see that the latter is simpler by means of runtime, API, and UI technology choices. Independent of whether you are a web developer, a C++ fan, or a .NET programmer, the entry barrier for creating Windows 8 style applications is actually lowered when compared to creating traditional desktop applications.

Your preference of programming language determines only the UI technology you must utilize in your programs. JavaScript is tied to HTML, whereas other languages (C++, C#, and Visual Basic) are bound to XAML. Generally, developers use more than one programming language and markup language, and they are used to being multilingual, so to speak. Learning a new language should be a motivating rather than a restraining force, however, dealing with separate runtime libraries and components is pretty cumbersome.

Windows 8 style application development strides over this issue. Regardless of your programming language of choice, you must learn only a single set of APIs — provided by Windows Runtime.

Understanding Windows Runtime

Without a doubt, Windows Runtime is the key component in the Windows 8 style application architecture. It represents a big leap in the evolution of the programming model, similar to what the .NET Framework did in 2002. The Microsoft team responsible for this great architectural piece describes Windows Runtime as “the solid, efficient foundation for building great Windows 8 style apps.”

In Chapter 1, you learned that the Win32 API contains a flat set of operations and data structures. The language run times utilized before .NET provide libraries that conceal most of the API operations, and expose a simpler set of objects and functions to make common programming tasks easier. The .NET Framework adds a runtime environment to these objects with extra features like garbage collection, exception handling, communication support between applications, and much more.

Although language runtime libraries and the .NET Framework have been continuously evolving for a long time, they still do not expose all data structures and operations proffered by the Win32 API. The main reason for this plight is that the runtime components utilizing Win32 are created separately from the services of the operating system.

This situation totally changed with Windows 8. Windows Runtime is an organic part of the operating system. It is not an additional component to be installed separately, such as the Windows Software Development Kit (Windows SDK). Every time a new Windows 8 build is created, the APIs and Windows Runtime are built together with the other parts of the operating system. Let’s take a closer look at the power of this great new component.

Windows Runtime Architecture Overview

Just as Windows 8 was designed with the user experience in mind, Windows Runtime was designed with a focus on the developer experience. Modern development environments such as Visual Studio (which you learn more about in Chapter 4, “Getting to Know Your Development Environment”) provide great tooling to make developers more productive.

Windows Runtime Design Principles

A good example of a productive tool is IntelliSense, which watches the context as you are typing the code, and automatically offers a list of possible continuations. As shown the example in Figure 3-4, IntelliSense provides a list of expressions that may follow the this member in the context of the MainPage method. IntelliSense not only displays the list of appropriate members, but it also displays a short explanation of the selected member (AllowDrop) in a tooltip. The team responsible for the design of Windows Runtime continuously kept in mind that the new API should be very easy to use with powerful tools like IntelliSense.

Figure 3-4: IntelliSense makes developers more productive

c03f004.tif

The smooth user experience of Windows 8 can be delivered only by applications that keep the UI responsive. In the past, the biggest issues with Windows were bound to the lazy and rugged behavior of the operating system and its applications. For example, the user started to drag an object on the screen by moving the mouse fluently, but the object moved in a “bitty” fashion.

The asynchronous programming model provides a great remedy for this kind of issue. The model does not block the UI while performing long or resource-intensive computations in the background. The APIs of Windows Runtime were established with asynchrony in the mind. The design team made a tough decision: All operations that may take more than 50 milliseconds are implemented as asynchronous operations. The new versions of the C# and Visual Basic programming languages shipped with Visual Studio 2012 and support this programming model, as you will learn in Chapter 5.


NOTE Do not be intimidated by concepts you are unfamiliar with, such as “asynchronous programming” or “UI blocking.” Chapter 5, “Principles of the Modern Windows Application Development,” provides a detailed overview of these concepts. For now, understand that asynchrony provides a way to push long operations into the background, while letting the UI remain responsive.

The Windows team has always invested a lot in providing backward application compatibility with every new Windows release. Windows Runtime is designed and established so that applications keep running in new Windows versions. If an API changes an operation in a new version of the operating system, the older operation versions still remain available in parallel with the new one, so they can be used side-by-side. Each application uses the version of the operation with which it was created.

The Building Blocks of Windows Runtime

Reflective of Microsoft’s design principles, Windows Runtime is not simply a set of APIs. It is a real runtime environment that binds the operating system services with the Windows 8 style applications built on them, independently of the programming language used to implement a particular application. This runtime environment is composed from several building blocks, as shown in Figure 3-5.

Figure 3-5: The building blocks of Windows Runtime

c03f005.eps

Windows OS are exposed to Windows 8 style applications through the Windows Runtime core block, which (as its name suggests) is the essence of the runtime environment. This core block wraps the low-level services into types and interfaces. On top of the core are many APIs, each of which is responsible for a certain kind of common operating system task. Although in Figure 3-5 only a few of them are shown, more than two dozen APIs are available.

You do not have to remember each type, interface, or even the API in which a certain type or functionality can be found, because Windows Runtime has its own metadata describing information about them. Moreover, the elemental types are grouped into hierarchical namespaces — such as objects in the .NET Framework, or in the Java Runtime — so it is quite easy to find them.


NOTE You learn more about Windows Runtime shortly.

Programming languages have different characteristics, and they use disparate conventions. At the top of the APIs and the metadata block, there is a thin layer, Language Projection, which is responsible for exposing the APIs in a language-specific way. Windows 8 style applications access Windows Runtime APIs through this layer.


NOTE You learn more about this layer later in this chapter.

A few other components shown in Figure 3-5 complete the environment where Windows 8 style applications can fully exploit the capabilities of the operating system through Windows Runtime:

  • Your application might access specific system resources (such as the webcam, the microphone, or the Internet) where the user’s permission is required. These resources can be accessed only through the Runtime Broker component that asks the user whether he or she allows the access to the resource — the first time an operation tries to use it. For example, if you create an application that picks up the user’s photo from the webcam, Runtime Broker does not let the system capture the photo unless the user explicitly enables it.
  • As you already learned, you can use HTML5 and JavaScript to create Windows 8 style applications. These apps — because of their web nature — run in a web host.
  • Each language has some specific runtime support (for example, runtime libraries that support the language, such as the printf C++ function, or append JavaScript method, or the String.Split operation available from C# and Visual Basic). These can be found in the Language Support building block that cooperates with the Language Projection layer.

Some of the building blocks shown in Figure 3-5 play an important role in everyday programming activities. In the next few sections, you learn more details about them.

Metadata in Windows Runtime

Providing a way to use metadata in Windows Runtime is a very important feature in Windows 8 style application development. It is an indispensable resource to make the architecture more robust, the APIs more discoverable, and, in the long run, developers more productive. Well, the different development technologies behind Windows are a bit scattered by means of metadata format they utilize:

  • The Win32 API is a large collection of data structures and operations that can be accessed through Dynamic Link Libraries (DLLs) sitting in the System32 folder under your Windows installation directory. These libraries include kernel32.dll, user32.dll, netapi32.dll, avicap32.dll, and many more. DLLs have many operation entry points. However, having only plain .dll files, you cannot tell what operations they contain, and how to invoke them, because they are not self-descriptive.
  • The component object model (COM) that Microsoft introduced in 1993 was a binary standard that allowed developers to write the interfaces of objects in Interface Definition Language (IDL). An .idl file can be compiled into a Type Library (.tbl file) that represents metadata related to COM objects.
  • The .NET Framework promoted type metadata into a first-class citizen. In .NET, types are the objects that provide you with utilizable operations, and type metadata describes the available operations. Assembly files (the binary files resulting from the compilation of the source code written in any of the .NET languages) are self-descriptive. They contain the metadata about types and operations encapsulated into the assembly.

The way .NET handles metadata is magnificent! However, metadata can be bound only to managed types. Many Win32 operations simply do not have a .NET type wrapping them. Using these types from managed code requires creating a definition that substitutes the missing metadata. Such definitions are laborious to describe, and you need documentation about the operation you intend to use. One such an example is the definition of the capCreateCaptureWindow operation that can be found in the avicap32.dll:

[DllImport("avicap32.dll", EntryPoint="capCreateCaptureWindow")]
static extern int capCreateCaptureWindow(
  string lpszWindowName, int dwStyle, 
  int X, int Y, int nWidth, int nHeight, 
  int hwndParent, int nID);

If you create a wrong definition (for example, you use double X instead of int X), your source code will compile, but will raise a runtime error, causing you to spend a lot of effort to find and troubleshoot this issue.

Metadata Format

The designers of Windows Runtime were inspired by the .NET Framework when architecting the metadata subsystem. They decided to use the metadata format utilized by .NET assemblies, which has already proven its adequacy over the past ten years. The designers chose the format used by .NET Framework 4.5 (the newest version of .NET, released in tandem with Windows 8).

Metadata files provide information about each of the APIs available in Windows Runtime. They are installed with Windows 8, and so they can be found on each computer with Windows 8 independently, even if that machine is used for development or just for another business. These files are machine-readable, and you can examine their content, as you learn in the following exercise.


Try It Out: Peeking into Windows Runtime Metadata
Windows Runtime metadata files are located under the Windows installation folder. They have a.winmd extension, and you can examine their content with the ILDASM utility.
To examine the metadata files, follow these steps:
1. In the Start screen, click the Desktop tile, and then, from the taskbar, select Windows Explorer.
2. Navigate to the System32WinMetadata folder under your Windows installation directory. If your operating system is installed to the default location, you can find this folder under C:Windows. If you provided a different location during the setup of Windows, choose that folder.
3. This folder lists more than a hundred files, each with a name starting with Windows, and having the .winmd extension, as shown in Figure 3-6. These files represent the metadata information of Windows Runtime APIs.

Figure 3-6: Windows Runtime metadata files in the System32WinMetadata folder

c03f006.tif
4. Scroll down to the Windows.Graphics file. Right-click it and select the Open With command from the context menu. A pop-up appears on the screen, and there you can associate an application with the .winmd file type. Scroll down to the bottom of the pop-up, and select, “Look for an app on this PC,” as shown in Figure 3-7.
5. The Open With dialog box pops up on the screen. In the File Name text box, type the C:Program Files (x86)Microsoft SDKsWindowsv8.0AinNETFX 4.0 Tools path (or navigate to this path using the Open With dialog box). Click Open. The dialog box is populated with the files in this folder. Scroll down to ildasm and click Open again.
6. The ILDASM utility opens and displays the metadata tree of the Windows.Graphics.winmd file. Expand the Windows.Graphics.Display node, and then the Windows.Graphics.Display.ResolutionScale node. You can discover all types defined in this metadata file, and also the enumeration values of the ResolutionScale type, as shown in Figure 3-8.

Figure 3-7: Associating .winmd files with an application

c03f007.eps

Figure 3-8: Windows.Graphics.Display metadata information in the ILDASM utility

c03f008.tif
7. In the ILDASM application window, double-click the MANIFEST node. A new window opens to display the manifest information of the metadata file, as shown in Figure 3-9.

Figure 3-9: The manifest information of the Windows.Graphics metadata file

c03f009.tif
The manifest of a metadata file carries important information about the file and about the types described in the file. In Figure 3-9, you can see that there is a .module Windows.Graphics.winmd entry with several lines following it. These items describe information about the metadata file. You see three entries starting with .assembly extern, and these are references to other metadata information related to types used within the Windows.Graphics metadata file. The first reference, mscorlib, is the main system component of the .NET 4.5 Common Language Runtime (CLR). The other two, Windows.Foundation and Windows.Storage, respectively, are other .windm files — as can be inferred from the windowsruntime modifier tag they have.
8. Open other metadata files from the System32WinMetadata folder, and examine their structure. When you have finished, close all open ILDASM instances.
How It Works
The System32WinMetadata folder contains essential .windm files. In Step 5, you associated the .winmd file extension with the ILDASM utility. In Step 6, you peeked into the metadata of the Windows.Graphics.Display.ResolutionScale type. In Step 7, you examined how the .winmd manifest describes dependencies on external metadata files.

Namespaces

As you experienced in the previous exercise, Windows Runtime types have hierarchical names. For example, the enumeration with the resolution scale values has the full name of Windows.Graphics.Display.ResolutionScale. The last tag of this name is the type’s simple name, and prefix tags form the namespace hierarchy. The top-level namespace is Windows. It has an embedded namespace, Graphics, and Graphics embeds Display.


NOTE .NET, Java, and C++ programmers are familiar with the concept of namespaces. Windows Runtime uses the namespace with exactly the same semantics as applied in .NET.

Namespaces are important concepts when managing the vast amount of types you utilize while creating your applications. If you had only type names poured into a big pool, it would be very difficult to find them and guess what type is the appropriate one for a certain task.

Another issue would be naming types. You cannot guarantee that no one else uses the same type name that you use. For example, when you name your type Circle, there is a great likelihood that someone else will use the same name. If you buy a package of custom UI components, there already may be a Circle type. How will your application know which Circle type to use at a certain location of the source code, and whether you intend to use your own Circle or the purchased one?

Namespaces are great constructs that help you to group objects into categories. Using well-designed namespace hierarchies makes you more productive, because you can find appropriate types for a certain task easily. For example, when you are about to display images on the screen, first you will look them in the Windows.Graphics.Imaging namespace, because its name suggest that such types exist there.

Namespaces also help you avoid conflicting type names. If you put your own types into their own namespaces (for example, you put Circle into the MyCompany.Shapes namespace), they won’t clash with types from other programmers or companies.

Types can have pretty long full names. Fortunately, all programming languages that manage the concept of namespaces offer some kind of constructs to avoid full names, and allow writing only the simple names. Let’s take a look at a few examples.

C# offers the using clause to help resolve type names:

using Windows.UI.Xaml;

namespace MyAppNamespace
{
  class MyClass: UserControl
  {
    public MyClass()
    {
      // ...
      selectedItem = this.FindName(itemName) as ListBoxItem;
      // ...
    }
  }
}

Visual Basic offers the same construct with the Imports keyword:

Imports Windows.UI.Xaml

Namespace MyAppNamespace

  Class MyClass
    Inherits UserControl

    Public Sub New()
      ' ...
      selectedItem = TryCast(Me.FindName(itemName), ListBoxItem)
      ' ...
    End Sub
  End Class
End Namespace

It is not surprising that C++ offers the same concept with the using namespace clause, too:

using namespace Windows::UI::Xaml;

namespace MyAppNamespace
{
  class MyClass: UserControl
  {
    public MyClass()
    {
      // ...
      selectedItem = dynamic_cast<ListBoxItem^>(this->FindName(itemName);
      // ...
    }
  }
}

The using, Imports, and using namespace constructs in C#, Visual Basic, and C++, respectively, instruct the compiler that type names should be looked up in the specified namespaces. This mechanism allows writing only ListBoxItem type names in your programs, because the compiler will check the Windows.UI.Xaml namespace as well. Otherwise, you would have to write the full Windows.UI.Xaml.ListBoxItem name.


NOTE Of course, objects in Windows Runtime namespaces can be accessed from JavaScript programs, too. In JavaScript, you can use a different mechanism, as you learn in Chapter 6, “Creating Windows 8 Style Applications with HTML5, CSS, JavaScript, and jQuery.”

Language Projections

Programming languages have their own characteristics. Fans of a particular programming language like to work with the language because of its attributes, such as readability, high-performance constructs, functionality, low syntax noise, and so on. When creating Windows 8 style applications, you can use several languages — with different syntax and semantic approaches. However, it was a challenge for Windows Runtime designers to allow using all services from these very different languages.

The Language Projections layer is responsible for transforming Windows Runtime APIs to the shape of the language. Because of this transformation, programmers can use the APIs as if those were the part of the language’s native runtime libraries.

The best way to understand what the Language Projection layer does is to take a look at a simple example. The Windows.Storage.Pickers namespace contains a type named FileOpenPicker that enables you to select a file from a folder. Using the C# programming language, you can use the following code to configure this dialog box for picking up picture files:

using Windows.Storage.Pickers;
// ...
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".png");

The same task can be rewritten using JavaScript, as shown in this code snippet:

var openPicker = new Windows.Storage.Pickers.FileOpenPicker();
openPicker.viewMode = Windows.Storage.Pickers.PickerViewMode.thumbnail;
openPicker.suggestedStartLocation = 
    Windows.Storage.Pickers.PickerLocationId.picturesLibrary;
openPicker.fileTypeFilter.replaceAll([".png", ".jpg", ".jpeg"]);

The identifiers highlighted in bold represent Windows Runtime API types. All of them start with an uppercase letter and use Pascal case, both in C# and JavaScript. The identifiers with italic typeface are members of Windows Runtime types. As you can see, they use Pascal case in C# and Camel case in JavaScript. This is done by the Language Projection layer! Whereas the C# language projection renders member names with Pascal case, the JavaScript language projection uses Camel case — according to JavaScript conventions.


NOTE Using Pascal case and Camel case means writing identifiers in which words are joined without spaces, with each element’s initial letter capitalized within the compound, respectively. Whereas Pascal case uses uppercase for the first letter (such as “P” in “PicturesLibrary”), Camel case has a lowercase letter (such as “v” in “viewMode”).

The task of the Language Projection layer does not stop at syntax sugar. In Windows Runtime API, the FileFilterType property of the FileOpenPicker type is a vector (or array) of string elements (FileExtensionVector). The C# language projection renders this property as a List<string> (list of strings), and so the file extensions can be added with the Add method of the List<string> type, as shown here:

openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".png");

The JavaScript language projection renders the fileFilterType property to an array of strings, and so the replaceAll function can be used to set up the content of the array, as shown here:

openPicker.fileTypeFilter.replaceAll([".png", ".jpg", ".jpeg"]);

Visual Studio also leverages the features of the Language Projection layer. As shown in Figure 3-10 and Figure 3-11, respectively, IntelliSense in C# and in JavaScript proffers the appropriate continuations, depending on the language.

Figure 3-10: IntelliSense proffers members of the List<string> type in C#

c03f010.tif

Figure 3-11: IntelliSense proffers array operations in JavaScript

c03f011.tif

With language projection, you do not need to utilize different tools to access and seize the operating system services depending on the programming language. You perceive all Windows Runtime services as if those were the part of the chosen programming language’s runtime environment.

Benefits of Windows Runtime

As you have learned, Windows Runtime is a new modern API over Windows Core OS Services, and it is more natural to use from many programming languages, including C++, C#, Visual Basic (.NET), and HTML/JavaScript. This modernization allowed Windows Runtime architects to rethink how a contemporary operating system should support application development:

  • Windows Runtime provides an easy access to hardware such as a Global Positioning System (GPS) unit, sensors, camera, or other modern hardware devices — with a few lines of code. Although, in the past, you had to write a several dozen lines of code to create the first “Hello, world” program in C with Windows 3.1, Windows Runtime enables you to take a picture with the built-in camera in about five lines of code.
  • Applications run in a security sandbox. This means that only those operations are executed that are deemed safe within the current security context. For example, if an application wants to turn on the microphone, this operation is thought unsafe unless the user explicitly confirms that he or she allows using the microphone.
  • The old Win32 API was a separate layer over the core operating system services. Windows Runtime is an integral part of the operating system tuned for developer experience. Windows Runtime is not only easier to use than Win32, but it is more stable and has improved memory management to allow less memory consumption and faster memory management.
  • Modern hardware devices and the always-responsive UI cannot work without an asynchronous programming model. Windows Runtime supports asynchrony natively.

What’s not in Windows Runtime

By now, you have learned that Windows Runtime is the key component to developing Windows 8 style applications. All services of the operating system exposed through Windows Runtime can be consumed from C++, C#, Visual Basic, and JavaScript. Before you put an equation sign between Windows 8 style applications and Windows Runtime, you should know that Windows 8 style applications can leverage other operating system components that are not available in Windows Runtime.

Applications written in the C or C++ programming languages are compiled directly to CPU-specific machine instructions that can be directly executed on the CPU. These applications can directly access the native operating system components responsible for rendering the UI, controlling input devices, managing sensors, communicating with the GPU, and much more. Most of these components may add extra value to Windows 8 style applications. For example, game programmers can leverage the high-performance graphics capabilities of DirectX APIs, such as Direct2D, Direct3D, DirectWrite, XAudio2, and XInput.


NOTE Microsoft DirectX is a collection of multimedia and game APIs. These APIs eliminate several additional layers between applications and the hardware hosting the specific function to provide the high performance required by multimedia and game applications. Direct2D is the two-dimensional graphics API, and Direct3D is designed for three-dimensional graphics game development. DirectWrite is a text-layout and glyph-rendering API that was shipped with Windows Vista first, and is still available in Windows 8.
When Microsoft set out to develop its gaming console, the X was used as the basis of the name “Xbox” to indicate that the console was based on DirectX technology.

These APIs provide a very thin layer between your application and the hardware they access, and use low-level data structures to move information to and from the app and the hardware. Although services available through Windows Runtime are safe with regard to UI responsibility and system stability, these APIs are tuned for performance — requiring more control within your application.

Using C++, you can create Windows 8 style applications that leverage DirectX API features. For example, you can create great calligraphic texts with DirectWrite, as shown in Figure 3-12.

Figure 3-12: Windows 8 style application using the DirectWrite API

c03f012.tif

Although these components are not available through Windows Runtime, and you can access them directly only from C++, mechanisms in C# and Visual Basic utilize these APIs in managed code. As of this writing, you can find a few open source projects on CodePlex (http://www.codeplex.com) that target using DirectX on Windows 8 from C#. Although these are in a very initial state, in a few months they may improve a lot.

.NET Framework 4.5

Two programming languages that support Windows 8 style applications — C# and Visual Basic — run over the .NET Framework. Windows 8 has been released with a new version of .NET Framework — version 4.5. The development architecture picture would not be complete without understanding what’s new in this version, and how .NET Framework cooperates with Windows Runtime.

The Installation Model of .NET Framework 4.5

Since 2002 (when .NET 1.0 was released), there have been several ways for a new .NET Framework release to cooperate with previous releases, as shown in Figure 3-13. Although the first three versions (1.0, 1.1, and 2.0) were shipped with different CLR versions that could run side-by-side on the same computer, subsequent versions followed a different path.

Figure 3-13: The relation of .NET versions

c03f013.eps

When .NET Framework 3.0 was released in 2006, it did not install its own CLR. It was simply an addition to version 2.0 and used its runtime core. The same thing happened with .NET 3.5 in 2007. It was an addition to .NET 3.0, and still used the CLR released with .NET 2.0.

In 2010, .NET 4.0 was released, again with its own CLR, encapsulating the enhanced forms of Base Class Libraries coming from .NET 3.5. Theoretically, in 2010, you could install four CLR versions side-by-side on your computer: CLR 1.0, CLR 1.1, CLR 2.0, and CLR 4.0. The newest .NET Framework, version 4.5, added more salt to the installation models used before. Instead of adding a new CLR side-by-side or new Base Class Libraries on top of the CLR 4.0 runtime, .NET 4.5 is an in-place update (that is, an update that not only adds new files, but overwrites existing ones) that changes both the CLR 4.0 runtime (it upgrades it to CLR 4.5) and also extends the prior Base Class Libraries.


NOTE An in-place operating system update or .NET CLR update is always a big risk from a compatibility point of view. With the .NET Framework 4.5 release, Microsoft undertook this risk, and spent much effort to cope with potential incompatibility issues. Microsoft set up a compatibility lab, reviewed all bug fixes and new features, and ran old tests unchanged.

Window Runtime Integration

The .NET CLR has always had integration features with other legacy technologies, such as COM and P/Invoke (Platform Invoke to access the Win32 API). With .NET Framework 4.5, the CLR natively integrates with Windows Runtime. C# and Visual Basic programmers now can use Windows Runtime types with the same ease, as if those were .NET types.

Windows Runtime types are native types. They actually use a new and modern version of COM that does not require object registration, and so their operations cannot be called directly from managed code. However, the .NET CLR and the language compilers arrange everything behind the scenes, and you do not need to deal with the details of calling the native Windows Runtime object from your managed code.

If you take a look back at Figure 3-2 and Figure 3-3, you can see that both the desktop application and Windows 8 style application development stacks contain a .NET Runtime box. You may think this means that two different .NET Frameworks exist, one for the desktop applications and one for Windows 8 style applications. Fortunately, there is only one.

The Base Class Library available to Windows 8 style applications (Windows Runtime applications) is restricted to services that are considered “safe” for a Windows 8 application to use. When you try to build your existing .NET source code, some parts would not compile, because those might be using some .NET Base Class Library functions that are not found in Windows Runtime, or are not thought “safe” in Windows 8 apps.


NOTE Generally, all operations are taken into account as “safe” that do not jeopardize UI responsiveness.

Asynchrony Support

As you have learned, asynchronous programming is a key technique to provide UI responsiveness, and Windows Runtime was designed with asynchrony in mind. The results of the Windows Runtime design process inspired the .NET Framework team, and they added asynchrony support to many components of the framework. The .NET Base Class Libraries contain hundreds of changes and improvements, including the following most significant ones:

  • The key interfaces of the Base Class Library (for example, file I/O operations) support asynchrony.
  • Data access procedures in ADO.NET (the foundational data access technology in .NET), and network communication components in Windows Communication Foundation (WCF), also handle asynchronous constructs as first-class operations.
  • ASP.NET supports asynchronous pipelines when processing requests and creating responses. ASP.NET MVC 4 provides asynchronous controllers.
  • The Task Parallel Library — introduced in .NET Framework 4.0 — was designed with asynchronous programming in mind. In .NET Framework 4.5, its thread-management was improved with new types managing synchronization and various timeout scenarios.

Although the asynchronous programming patterns provide better UI responsiveness and improved throughput, it is quite difficult to apply them, and they are pretty error-prone. With .NET Framework 4.5, the C# and Visual Basic compilers provide two new keywords (async and await in C#, Async and Await in Visual Basic) that take over all complexity related to these patterns.


NOTE You learn more about these keywords in Chapter 6.

Other New Features

Although the main novelty of .NET Framework 4.5 is Windows Runtime integration and enhanced support of asynchronous programming, many other tiny improvements make developers more productive. There are many new features in .NET Framework 4.5, but explaining them is far beyond the scope of this book. If you would like to obtain more information about them, the best starting point is the .NET Framework Development Center on MSDN at http://msdn.microsoft.com/netframework.

Picking the Appropriate Technology for Your Project

This chapter has shown you a wide variety of technologies and programming languages that you can use to create Windows 8 applications. Sometimes the most difficult decision is choosing the appropriate language and technology stack for your project. This section contains a few hints to help you make the optimal decision.

In addition to the programming language and development technology, there is another important consideration scarcely mentioned before. Windows 8 totally changes not only the way users work with applications, but also the way they discover, install, and remove programs. This new installation model may inspire you to create Windows 8 style applications instead of desktop apps, so this might be a good time to take a brief overview of it.

The Windows Store

In previous Windows operating systems, you had to create installation kits and deploy your applications by running those kits on the target computers. Your users had to understand a few technical details of the installation process, such as selecting the target folder, installing prerequisites, adding shortcuts to the desktop, and so on. Often, the installation process was a source of fear — will this installation override something on your computer to prevent other applications from running properly? Further, unnecessary applications had to be removed and often cleanup utilities were needed to remove the garbage heap left by those apps.

The consumer-centric approach cannot work without a significantly easier way of obtaining and releasing applications. Windows 8 style applications can be installed only from the Windows Store, which is an online service. As a developer, you can upload your application to the Windows Store, where it goes through an approval process before users can discover and install it. As a user, you can find an application in the Windows Store and, after buying it (or choosing to try it free, or even using it free when the application allows it), let the operating system install the app for you. If you do not need the application any more, Windows 8 will instantly uninstall it and take care of the cleanup process — releasing all resources held by the app.


NOTE Using the Windows Store is very easy for consumers who want to buy and run Windows 8 style applications. However, developers need to know more details about uploading their programs and leveraging Windows Store features in order to monetize them. Chapter 16, “Introducing the Windows Store,” is dedicated entirely to this topic.

Windows 8 or Desktop Applications?

The first thing you should decide is whether you want to create Windows 8 style applications or desktop applications. Table 3-2 helps with your decision by distinguishing a few points of consideration.

Table 3-2: Helping Points to Choose between Windows 8 Style and Desktop Applications

Use Windows 8 Style Applications When…Use Desktop Applications When…
You have no, or very little, experience in Windows programming.You have more experience in Windows programming — moreover, you’re a seasoned Windows programmer.
You’re focusing on applications with a superior user experience.You’re focusing on applications where you intend to utilize the UI technologies (Windows Forms, WPF, or Silverlight) you already know.
You have a relatively small UI codebase to reuse.You have a large amount of code related to the UI, and you want to reuse the knowledge carried by that codebase.
Your application works on a single Windows computer. Your application’s primary focus is providing a UI for services and remote components accessed through the Internet (or company intranet).Your application is distributed into several components, including UI, business services, and databases. UI application components use legacy, vendor-specific, or proprietary communication technologies to access other services.
Your application intends to leverage the user experience and device features offered by mobile devices, such as a tablet.Your application is primarily used on desktop computers and/or integrates with existing applications.
You want to leverage the easy application deployment model offered by the Windows Store.You need a more complex deployment model than provided by the Windows Store.
You can use (that is, you are allowed to use) C++, C#, Visual Basic, or JavaScript programming languages to create your application.Besides the set of C++, C#, Visual Basic, and JavaScript, you need to use other programming languages heavily to create your application.

If you participate in a complex project, you obviously cannot use the Windows 8 style technology stack for the entire project — often you need to do server-side development. However, it is worth examining the UI components of your system that you can put through and that might be implemented as Windows 8 style applications.


NOTE This book is dedicated to Windows 8 style application development, and does not intend to cover traditional desktop development technologies such as WPF and Silverlight. If you are also interested in these technologies, Wrox offers you a wide selection of great books. Visit the Wrox website (www.wrox.com) for more information.

Choosing a Programming Language

As you learned earlier in this chapter, you can use several languages for Windows 8 style application development — C++, C#, Visual Basic, and JavaScript. If you prefer any of them, do not hesitate to start using that language.

If you have no or very little experience with Windows programming, or are uncertain which language would have the shortest learning curve, here are several clues to help with your decision:

  • If you have experience with web page design and website creation, you certainly know HTML, and probably have experience with CSS and JavaScript. Start creating your first Windows 8 style programs with JavaScript.
  • If you have used macros in Microsoft Word and Excel, Visual Basic is probably the language you should start with.
  • If your experience is about programming algorithms rather than UI, then C++ and C# are your best choices. C# is probably easier to learn; C++ provides more control over low-level programming constructs.

One of the best things about Windows 8 style application programming is that you are not obligated to stick to only one language! You can even use more than one programming language within an application. For example, if you have web programming experience with JavaScript, you may create your UI with HTML and JavaScript, but still consume more complex application logic written in C# and high-performance algorithms programmed in C++.

Even if you start application development with one of these languages, it is worth learning other ones — because each of them has its own strength. When you have short deadlines or want to be more open toward other platforms, knowing several languages and getting used to mixing them reasonably is invaluable.

Summary

Windows 8 provides a new application development model called the Windows 8 style application model. However, you can still leverage the technology stack of desktop application development used with previous Windows versions.

Windows 8 style applications have their own technology stack. Four programming languages — C++, C#, Visual Basic, and JavaScript — can be used to create Windows 8 apps. Independently of the language used, all operating system services required by these apps can be accessed through a new component called Windows Runtime — and, from this perspective, languages are co-equal.

Windows Runtime is a modern programming surface over the core Windows services. Although it is implemented in native code, it provides namespaces, object metadata, and asynchronous operations. Each programming language has a Language Projection layer that mimics Windows Runtime. This layer was created with the particular language in mind.

C# and Visual Basic use the .NET Framework 4.5, which integrates with Windows Runtime natively, so types in Windows Runtime can be used as easily as any .NET Base Class Library types.

In Chapter 4, you learn the fundamental tools that you can use to create Windows 8 style applications. You are going to create a few simple apps to whet your appetite.

Exercises

1. List the programming languages that can be used to create Windows 8 style applications in Windows 8.
2. Which UI technologies are supported in Windows 8 style applications?
3. What is the component that allows accessing Windows core services from all Windows 8 programming languages?
4. Why is Windows Runtime superior over the traditional Win32 APIs?
5. What is the application deployment model offered by the Windows Store?

NOTE You can find answers to the exercises in Appendix A.

What You Learned In This Chapter

TopicKey Concepts
Windows 8 programming languagesWindows 8 style applications can be created with the following languages: C/C++, C#, Visual Basic, JavaScript.
XAMLIn Windows 8, eXtensible Application Markup Language (XAML) is used to declare and implement the user interface (UI) of apps programmed in C++, C#, and Visual Basic.
HTMLIn Windows 8, the newest HyperText Markup Language (HTML) version, HTML5, is used in tandem with Cascading Style Sheets 3 (CSS3) to create application UI with the JavaScript programming language.
Windows RuntimeWindows Runtime is the application programming interface (API) that Windows 8 style applications can use to access the underlying operating system services.
Windows Runtime objectsIn contrast to Win32 (which uses flat operations), Windows Runtime provides meaningful objects with related operations and data structures. These objects are self-descriptive. They provide metadata information about themselves. Using this metadata, applications can easily consume the exposed operations.
NamespacesWindows Runtime objects are organized into hierarchical namespaces. Objects in separate namespaces can use the same simple name.
Language Projection layerWindows Runtime objects and operations can be accessed from each Windows 8 programming language as if Windows Runtime were tied to that particular language. This behavior is provided by the Language Projection layer.
Asynchronous programming modelWindows Runtime offers an asynchronous programming model to provide UI responsiveness. Operations that may block the UI are implemented in an asynchronous manner — they push the processing to a background thread while keeping the UI responsive.
.NET Framework 4.5.NET Framework 4.5 is the newest version of the .NET Framework released in tandem with Windows 8. It provides native integration with Windows 8, and adds asynchrony to many Base Class Libraries.
Windows StoreWindows 8 style applications can be installed only from the Windows Store, which is an online service. Developers can upload their applications to the Store, where they go through an approval process before users can buy and install them.
..................Content has been hidden....................

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