1. The New Windows Runtime

The Windows Runtime (WinRT) is an entirely new framework for Windows that provides developers a multi-language API for creating applications on Windows 8. Windows Store applications are full-screen applications that are tailored for specific devices, touch interactions, and the new Windows 8 user interface. Windows Store applications are also referred to as tailored applications because they adapt to the target device. It is also possible to build traditional desktop applications on Windows 8. The term “Windows 8 application” in this book will refer to the non-desktop, Windows Store version of applications that use WinRT. The introduction of WinRT is one of the largest paradigm shifts in the Windows development world since the introduction of .NET in late 2000.

In this chapter, you will look back at prior development frameworks for Windows and learn how the rising popularity of Natural User Interfaces (NUI) prompted Microsoft to respond with the bold new Windows 8 platform. You will learn about Windows 8 applications and the various languages in which they are written. I will also share how existing XAML-based technologies like WPF and Silverlight fit into the new Windows runtime.

Looking Back: Win32 and .NET

“I can change my mind faster than Bill Clinton.”

—Jay Leno at the Windows 95 Launch Party, referring to the new Windows task bar

In 1985, the first version of Windows was released without much fanfare. It wasn’t a full operating system, but a layer that sat on top of the console-based MS-DOS and was called MS-DOS Executive, as shown in Figure 1.1. A decade later, things changed dramatically with the launch of Windows 95. Bill Gates appeared on a massive stage in front of the now iconic “Start button” for Windows with talk show host Jay Leno and demonstrated the powerful new operating system. It caught on quickly to the tune of the Rolling Stones’ song “Start Me Up” and left close competitors like Apple behind in its wake.

Image

Figure 1.1. MS-DOS Executive

To write software for Windows 95, shown in Figure 1.2, developers used an Application Programming Interface (API) that had been developed several years earlier known as Win32. At the time, Microsoft was bridging the gap between legacy 16-bit systems and the newer 32-bit machines and conveyed the new support in the name of their API. Win32 exists today (now more appropriately referred to as the Windows API) at the core of all Windows operating systems despite the introduction of newer frameworks and platforms that abstract it away. The API was considered extremely powerful and flexible at the time it was introduced but placed a tremendous burden on the developer to handle many low-level operations required to display a form and interact with the user.

Image

Figure 1.2. Windows 95

The following code is all that is required to print the text “Hello, World” using the C++ programming language:

#include<iostream.h>
int main()
{
    cout << "Hello World" << endl;
    return 0;
}

Compare that with the code in Listing 1.1 required to perform the same task in C++ for the Win32 API (this example uses the Microsoft Foundation Class Library or MFC).

Listing 1.1. Win32 MFC Version of Hello, World


#include <afxwin.h>
class HelloApplication : public CWinApp
{
public:
 virtual BOOL InitInstance();
};

HelloApplication HelloApp;

class HelloWindow : public CFrameWnd
{
 CButton* m_pHelloButton;
public:
 HelloWindow();
};

BOOL HelloApplication::InitInstance()
{
 m_pMainWnd = new HelloWindow();
 m_pMainWnd->ShowWindow(m_nCmdShow);
 m_pMainWnd->UpdateWindow();
 return TRUE;
}

HelloWindow::HelloWindow()
{
 Create(NULL,
  "Hello World!",
  WS_OVERLAPPEDWINDOW|WS_HSCROLL,
  CRect(0,0,140,80));
 m_pHelloButton = new CButton();
 m_pHelloButton->Create("Hello World!",WS_CHILD|WS_VISIBLE,CRect(20,
 20,120,40),this,1);
}


The API was used heavily for decades in software that was written for Windows machines. It demonstrates the trade-off that has always been a part of developing software for Windows machines: The ability to deliver a comprehensive user interface with rich graphics requires a steeper learning curve. For many years, it also meant knowing either C or C++ because although other options existed, both languages dominated the market for what is now referred to as unmanaged code. Unmanaged code is compiled directly to native instructions that the target machine can read.

The first version of the Visual Basic programming language (referred to more commonly as VB) was introduced in 1991. VB was based on concepts that date to an older language designed for teaching called BASIC, an acronym for Beginner’s All-purpose Symbolic Instruction Code. VB allowed developers to structure their code in logical components that work together. Although VB also generated native, unmanaged code, it did this with the assistance of special runtime libraries that the code would interact with to create the target application.

VB 4.0 was released in 1995 and could create 16-bit and 32-bit Windows programs. The Interactive Development Environment (IDE) packaged with VB made it extremely popular with developers, along with the existing components and the ability to design user interfaces by dragging and dropping controls. VB also integrated well with the Common Object Model (COM), a standard for creating software components that was introduced by Microsoft in 1993.

COM was designed to enable communication between processes and for its ability to dynamically create software components (referred to as objects) that could be accessed from various programming languages. COM allows developers to use components without having to understand how they are internally implemented. This is done through externally exposed interfaces. COM was also an important milestone in the evolution of Windows and, as you will learn later, influences the Windows 8 platform even today.

The typical architecture of a Win32 application is illustrated in Figure 1.3.

Image

Figure 1.3. The component stack of a Win32 application

Although the Win32 API still exists today, many developers write productive software without even knowing it exists because in the 1990s Microsoft began working on a new framework. It was codenamed Next Generation Windows Services (NGWS). The beta for this new framework was released in late 2000 under its public name: .NET 1.0. It allowed for a new type of software called managed code.

The traditional approach to building applications is called unmanaged because it compiles directly to native instructions that the target machine can read. Although this has several advantages, it also forces the developer to understand the host machine at a level very close to the underlying kernal. Developers must learn how to allocate memory directly and how to release memory when it is no longer being used. Tasks such as drawing graphics require understanding the display drivers and how to render the pixels into internal buffers that are used to draw the onscreen display.

The .NET Framework introduced managed code to Windows platforms. The code is called managed because a new layer called the Common Language Runtime (CLR) was introduced. The CLR manages memory for the developer, provides a consistent way to interact with various libraries and resources, and also ensures more secure code. The CLR also provides a language-agnostic layer of code, referred to as Microsoft Intermediate Language or MSIL (sometimes simply referred to as IL) that all programs compile to. The runtime interprets this code and translates it to the native operations required to run on a target machine.

The concept of managed code existed well before the .NET Framework. In the 1960s and 1970s when mainframes were prevalent, it was common to write emulators to port code from one system to another. An early game company that wrote what they referred to as “interactive fiction,” and is best known for their title “Zork,” was founded in 1979 and released titles to various platforms including the Commodore 64 and Apple IIe by creating a “Z-machine” interpreter. Java technology began development in 1991 and featured the Java Virtual Machine (JVM) to manage code written in the Java programming language.

The advantages this model provides include opening the platform to a variety of languages and enabling stronger cross-platform and operating system support. Programs written with unmanaged code often target a specific version of the operating system or have special libraries designed to keep them compatible with multiple flavors (such as Windows XP, Windows Vista, and Windows 7). Managed code can for the most part target a specific version of the .NET Framework, and the framework itself will handle the differences between operating systems it is installed on.

The original version of the .NET Framework supplied an API known as Windows forms (WinForms) for developing graphical user interfaces. The API was based on the Graphics Device Interface (GDI) that provided direct methods for accessing the underlying graphics hardware. The .NET Framework 3.0 was released in 2006 and included the Windows Presentation Foundation (WPF). This new technology was significant because it was based on Extensible Markup Language (XAML) as a declarative way to design user interfaces. XAML enables vector-based graphics and fluid layouts that scale to various display form factors and introduced the concept of data-binding that you will learn about later.

The architecture for an application written with the .NET Framework is illustrated in Figure 1.4. This example uses the WPF framework that is layered on top of the core runtime. The developer is able to use a variety of languages and technologies like Extensible Application Markup Language (XAML) to generate code that takes advantage of the framework and the underlying set of base classes that are part of the Base Class Library (BCL) and provide common services such as file system access and networking capabilities. The languages all generate MSIL that is compiled during execution to native code by the CLR.

Image

Figure 1.4. The component stack of a .NET Framework application

Technologies based on the .NET Framework and the Win32 API have dominated software written for Windows machines for the past decade. Although frameworks like WPF revolutionized the user interface of Windows Applications and Silverlight extended the reach of the platform, Windows suffered a major blow from what was once considered an unlikely competitor: a tablet PC. In April of 2010, fifteen years after the Windows 95 launch party, Apple retaliated by selling almost 15 million units of the iPad in its first year alone. This bold new product embraced a revolution that had began years earlier to give consumers what is known a Natural User Interface (NUI).

Looking Forward: Rise of the NUI

The typewriter was invented in the early 1800s. The original models featured an alphabetically arranged set of keys that would often jam when the operator typed quickly. Christopher Sholes, a newspaper editor, addressed this issue in the early 1870s by devising a keyboard layout that ensured the most common letter combinations were not located close to each other. A misconception is that this was devised to slow the speed of the typist when in fact the goal was to avoid jams and therefore allow faster typing speeds (Weller, 1918).

The keyboard served a very mechanical function: It connected a letter with a bar that was used to strike the paper and apply the ink to represent the letter. Typewriters have now become a novelty, and the majority of keyboards are electrical. Keyboards exist today that can be rolled into tiny cylinders for easy transport and connect wirelessly to their host machines. Despite major advances in technology, the keyboard look and feel has remained mostly unchanged for the past century.

The keyboard was first augmented by the invention of the mouse in the late 1960s. Bill English and Douglas Engelbart were working for Xerox at the Palo Alto Research Center (PARC) when they developed the early prototypes of the mouse (Edwards, 2008). The original mouse was so-named because it was connected by a cord that resembled a tail. Today you can purchase wireless mice that use infrared or lasers to track movement instead of a mechanical ball.

The combination of a keyboard and mouse may be the most common way to interact with computers today, but it is hardly intuitive. I’m assuming you are a developer if you are reading this, so there is a good chance you are treated as “support central” by your friends and family. You’ve probably had to wait patiently while a relative hunted and pecked on her keyboard to type out some text with agonizing slowness, then explain the differences between a click, a double-click, and a right-click as she attempted to navigate.

Research into a different way to interact with computers began nearly the same time the mouse was being perfected in the early 1970s. The idea of a “natural” interface focuses on a method of interaction that is intuitive and therefore easy to learn. If you watched the movie Minority Report with Tom Cruise, you probably marveled at the holographic images he could easily manipulate simply by moving and rotating his hands. Manipulating an object with your hands is something natural that you begin to master at a very young age, so it’s easier to use those gestures to move a document on a computer screen than it is to learn how to point, click, and drag with mouse.

The Natural User Interface (NUI) began to make its mark shortly after 2000 when the majority of smart phones began to ship with touch screens. This made it easy to simply point, tap, pinch, and swipe your way through various menus and options on the phone. Apple released the touch-only iPhone in 2007 with an interface that was extremely easy to learn and use. I believe this more natural interface is one of the key reasons the iPhone became popular so quickly: It was the first phone non-technical users could get along with.

Around the same time the iPhone was gaining popularity, Nintendo released the Wii console. The console features special remotes that contain sensors so that users can interact with the console by moving their arms and twisting their hands. This interface makes it easy to translate actions you’ve already learned like tossing a bowling ball or swinging a golf club to video games by incorporating these same movements. The console was an instant hit and broke several records for velocity of sales, including best-selling console in a single month in the United States (http://en.wikipedia.org/wiki/Wii).

In 2009, the public began hearing whispers about a Microsoft initiative codenamed Project Natal. In the fall of 2010, Project Natal was released as the Kinect for Xbox 360 and took the Wii concept a step further by eliminating the need for a remote. The Kinect sensor uses special cameras to combine image and depth perception to analyze objects in the room, including players. These cameras allow you to interact through body movements without any type of controller. An array of microphones is also able to pinpoint to sound to a high degree of accuracy and enables you to issue voice commands in a normal voice from across the room.

The popularity of the Kinect led to several open source projects devoted to creating drivers and software to enable its use on computers. After several different competing (and unofficial) products went to market, Microsoft responded by releasing the official Kinect for Windows SDK in June 2012. Version 1.5 includes drivers that are compatible with Windows 8.

The NUI revolution has exploded over the past few years. Sales of slate and tablet PCs have surged. The rapid adoption of these devices has created a phenomenon referred to as the “Consumerization of IT.”1 Employees are refusing to lug around their giant work laptops in lieu of the lighter, easier-to-use touch-based slates that they are willing to purchase with their own cash and bring from home. IT departments are responding by embracing these types of devices in the workplace.

The Windows 7 operating system (shown in Figure 1.5) contains a touch API that allows developers to write software that responds to touch-based interactions and gestures. The problem is that the majority of software written for the platform is still based on the old combination of keyboard and mouse. Many of these programs respond to touch simply by replacing a finger tap with a mouse click. This makes it unwieldy to interact with programs because they don’t provide the right surface to manipulate content. Users with “fat fingers” (compared to the size of a stylus or touchpad pen) find it nearly impossible to select text or check radio buttons crammed into tight spaces on the screen.

Image

Figure 1.5. Windows 7

I believe when consumers realized how easy it is to interact with a NUI, they began to push away from the more traditional models of mouse and keyboard. Microsoft responded in the entertainment space with Kinect and the smartphone space with the release of the new Windows Phone. They realized they needed a better story in the computer space for Windows machines that didn’t simply include a touch interface. What was needed was a touch-optimized operating system designed to make it easy for non-technical users to pick up a slate and become productive immediately. Unlike Apple and Android, they also had to tackle this without the benefit of building a fresh platform. There are 1.25 billion Windows machines worldwide (500 million with Windows 7) running software written over the past several decades that can’t be forgotten and left behind when the new version is released (http://articles.businessinsider.com/2011-12-06/tech/30481049_1_android-apps-ios).

Microsoft responded to the challenge with Windows 8. A revolutionary operating system, Windows 8 is built on the familiar Windows architecture that enables it to run the same software you are used to operating on your Windows 7, Windows Vista, and Windows XP machines. The platform has been reimagined to provide a first-class touch-based NUI experience through a new style of application—the tailored Windows Store app.

Introducing the Windows Store Application

Windows 8 addresses the challenge of maintaining backwards compatibility across a massive consumer install base while embracing natural user interfaces and tablet form factors. The key to Windows 8 is a special type of application that is written for the new Windows Runtime (WinRT). These applications are most commonly referred to as Windows Store applications, hereafter referred to as “Windows 8 applications” in this book.

Windows 8 applications are tailored specifically for the user running them. They leverage special hardware features and can adapt based on the context they are run in. They scale to various screen resolutions and orientations and adapt easily to the mouse and keyboard when touch is not available. They can tap into various sensors to determine the user’s location and respond to the motion of the device they are running on.

The goal for these applications is to keep them alive, fast, and fluid. Applications built for the platform should easily interface with other applications, social networks, and the cloud. They should be easy to learn and intuitive to use because they take advantage of natural gestures and interactions. The Windows 8 application experience extends to the development lifecycle. With the tools provided, it should be fast and easy to build quality applications using the language of your choice.

The Windows 8 application platform runs with help from a special layer called the Windows Runtime or WinRT. Using a technique called projection, WinRT maps operating system APIs to objects in your chosen programming language. In C# the interaction looks and feels like interaction between classes. This technique makes it easy to interface without compromising performance because the compiled code invokes the APIs directly as if you are writing raw unmanaged C/C++. There is no intermediary translation or mapping, and the APIs are compiled directly into the Windows 8 OS to access the operating system directly. Unlike the Win32 API, the Windows Runtime is an object-oriented API.

The WinRT APIs are exposed using the same technique as the .NET framework. The Common Language Infrastructure (CLI) is used to provide metadata about the APIs that the compiler can use to project the signature to your language of choice and compile it to native code. The metadata follows the ECMA-335 standard and is stored in files with the .winmd extension for Windows Metadata. You can learn more about the standard online on the ECMA website at http://www.ecma-international.org/publications/standards/Ecma-335.htm.

Figure 1.6 illustrates the architecture you will use when you build Windows 8 applications. There are a large number of APIs provided “out of the box” by Windows 8 to perform actions related to graphics, devices, security, networking, interacting with the operating system, and communicating with other applications. There are currently four languages supported by the Windows Store development platform with two different graphics markup engines, one that is XAML-based (both via unmanaged code and the CLR) and another that is based on HTML5 (using the internal “Trident” engine for rendering and “Chakra” engine for interpreting JavaScript that is built into Internet Explorer 10).

Image

Figure 1.6. The component stack for a Windows 8 application

It is important to familiarize yourself with the specific traits of Windows 8 applications. The primary graphics interface for these applications is DirectX, and there is no direct access to the older Graphics Device Interface (GDI). Windows 8 applications have no overlapped windows. They execute in a special “Application container” that features various states. Windows 8 applications can be suspended when they are not active and may be terminated when system resources such as memory become scarce.

WinRT APIs come in two flavors: direct calls to the underlying kernel and brokered API calls. Brokered API calls are special calls that may impact data integrity, user integrity, or security concerns. To use these special APIs, the Windows 8 application must “declare intent” by flagging the proposed calls in an application manifest. The user is often prompted to give permission (opt-in) for the calls to be made before the application is allowed to run.

Jensen Harris, the Director of Program Management for Windows User Experience at Microsoft, presented a session at Microsoft’s Build conference that covered eight specific traits of well-written Windows 8 applications.2 Microsoft was very secretive with the details of Windows 8 until the Build conference, when they formally announced the operating system and released the developer preview to the general public. It was at that event in a keynote session that Jensen shared the following traits as guidelines to follow when writing software for the Windows 8 platform.

Windows 8 Design

Windows 8 applications have a consistent look and feel. To make it easy for the user to intuitively learn how to interact with your application, you should follow the design guidelines for Windows 8 applications as closely as possible. Several templates are provided with the development environment to make this easy for you. You will learn about various practices and guidelines throughout this book.

You can read Microsoft’s guidelines for Windows 8 applications online at http://msdn.microsoft.com/en-us/library/windows/apps/hh465427.

Fast and Fluid

All Windows 8 applications should be fast and fluid. The framework helps manage the responsiveness of the application by only allowing asynchronous access to APIs that may run slowly. For Windows 8 applications, the definition of “slow” is any operation that may take longer than 50 milliseconds to complete. Examples of potentially slow operations include file system and network access. Asynchronous operations avoid blocking the UI while the operation completes in the background of your application. Several enhancements to the C# language and underlying framework make it easier to manage, wait for, and respond to the result of asynchronous calls in your code.

The Visual Studio 2012 templates and IDE contain built-in animations to provide a fluid user interface. Most displays easily pan from side to side and provide the user with the ability to zoom in when they require further detail. You will learn how the different templates provide fluid transitions in Chapter 2, Getting Started, and how to apply more advanced transitions in Chapter 3, Extensible Application Markup Language (XAML).

Snap and Scale

Windows 8 applications can easily snap to a region on the display to run side-by-side with another application if the display resolution is great enough (this requires a minimum width of 1344 pixels). This is a built-in gesture users can invoke to manage their running Windows 8 applications. The applications also easily scale to the space that is provided, changing their configuration when the available space becomes larger or smaller or when the user rotates the tablet between landscape and portrait orientations. Once again the templates in Visual Studio 2012 provide built-in capabilities to accommodate these features that you can build upon for your own applications.

Use of Right Contracts

Windows 8 applications and WinRT introduce a new concept called contracts. Think of Contracts as a language-agnostic way to express assumptions about capabilities in code. The Share contract, for example, is like a clipboard on steroids because it manages multiple types including HTML content and bitmap images. Contracts allow the developer to expose services that interact with the operating system directly or can be invoked by the user through charms. Charms are a UI feature and part of the Windows 8 platform that allows the user to invoke contracts through a consistent user interface. An example contract and corresponding charm is Search.

When the user selects the Search charm from a Windows 8 application, he is presented with an operating system dialog with a text box that he can use to enter search terms. Beneath the search box, the operating system will display all of the programs that support the Search contract. The operation system will pass the search terms to whatever program is selected, so that it can process the term in the appropriate context. A movie application can apply the search term to movie titles, and a Windows 8 application that aggregates RSS feeds can search the content of recent news items. This process is illustrated in Figure 1.7.

Image

Figure 1.7. Charms and contracts

Other charms include Settings, Devices, and the Share charm for sending data between applications. You will learn more about charms and contracts in Chapter 8, Giving Your Application Charm.

Great Tiles

Microsoft introduced the concept of tiles with Windows Phone 7. Unlike application icons that take up space on the start screen solely to provide something to click to launch the application, tiles are live, interactive spaces that can provide dynamic information and context to the user. A weather tile will summarize the current temperature and forecast. A Twitter tile may animate between the most recent tweets that mentioned you. An email tile will display your current count of unread messages.

The use of live tiles transforms the start menu into an executive dashboard that provides rich “at a glance” information. Often you can get the information you need without even launching the application the tile is connected to. This is similar to the experience provided by earlier versions of Windows through the Active Desktop (http://en.wikipedia.org/wiki/Active_Desktop) and Desktop Gadgets (http://msdn.microsoft.com/en-us/library/windows/desktop/dd834142.aspx). Tiles, however, are an integral part of the Windows 8 platform and directly connected with your application.

You can see an example of an old, static desktop in Figure 1.8. About the only “active” information is the date and time in the lower left. Everything else is static, and the icons only serve as placeholders to launch applications. Notice the massive amount of unused “white space” on the right side of the desktop.

Image

Figure 1.8. A static desktop

Now take a look at Figure 1.9. This is the Windows 8 Start screen. Notice how all of the space is used. In addition, each tile provides relevant content and information. The weather application shows the current weather at a glance (yes, it is a beautiful day here in Woodstock, Georgia). The photo application rotates through the latest images. All of this gives me quick information at a glance. On the right side, I’ve opted to use smaller tiles or turn off the live updates. Almost everything about the Windows 8 experience is configurable.

Image

Figure 1.9. The Windows 8 Start screen

The infrastructure for updating tiles is designed to conserve resources such as network usage and the battery life of your host device. You’ll learn more about tiles in Chapter 7, Tiles and Toasts.

Connected and Alive

Windows 8 applications should remain connected and alive. This means they are constantly providing the latest information through tiles, notifications, and content. Through the use of contracts and charms, they can connect seamlessly to social networks, cloud storage, and local devices. In addition to charms and contracts, this is achieved through the integration of data from multiple sources (learn more about options for data in Chapter 6, Data) and through syndication of rich network-based content.

Embrace Windows 8 Design Principles

The final trait of a great Windows 8 application is that it embraces the Windows 8 design principles. This trait really encompasses everything. When you design your application, make it fast and responsive. Do more with less. Focus on the key tasks and don’t add distractions. Remove anything that is not necessary and always focus on the ease of the end user. How quickly and easily can they complete tasks? How fast can they get to the information they need?

This book will focus on these principles throughout. Fortunately, Microsoft has clearly defined what makes a good Windows 8 application and has integrated these principles into their various development tools and templates. You will learn more about these tools in the next section.

Windows 8 Tools of the Trade

The new runtime requires new tools to build Windows 8 applications. Windows 8 was released to manufacturing on August 15th, 2012 and will be available to the general public at the end of October 2012. Visual Studio 2012 was released to production in August 2012. The next version of Microsoft’s flagship development environment is capable of building and deploying the new Windows Store applications. Traditional desktop applications allow you to execute the program immediately after it is compiled. Like Windows Phone applications, Windows 8 applications must be packaged and then deployed before you can run or debug them.

Visual Studio 2012 is the main tool you will use for building Windows 8 applications. You can download the tool online from http://dev.windows.com/.

When you have Visual Studio 2012 installed, you can create new Windows 8 projects directly from the IDE. Figure 1.10 shows the various options you have to choose from when you start a new project. The templates are grouped by language, followed by a subsection for the Windows Store environment. Several templates exist for Windows 8 applications to help jumpstart your UI.

Image

Figure 1.10. Built-in templates for building Windows 8 applications

Blend for Visual Studio

Blend is another tool for building Windows 8 applications. It will work for both HTML and XAML-based applications. Visual Studio 2012 focuses on the developer-centric elements of the application. Blend focuses on the more designer-centric elements. Unlike previous versions of Visual Studio that used a separate rendering engine codenamed “Cider” for the designer, the core engine for Blend is embedded within the Visual Studio 2012. The majority of design-related actions can be performed without leaving the IDE.

The specific designer-centric activities that exist in Blend include a UI for designing animations and manipulating visual states. You will learn about animations in Chapter 3 and visual states in Chapter 4, Windows 8 Applications. Figure 1.11 shows the start screen for the Blend application.

Image

Figure 1.11. Blend for Visual Studio 2012

Although the focus of this book is the combination of C# and XAML for building Windows 8 applications, a brief overview of the other language options and an introduction to C# follows.

HTML5 and JavaScript

The JavaScript option is unique because it also includes a different graphics markup engine than the other options. With JavaScript for Windows 8 applications, you create applications using HTML5 for markup (including CSS support) and JavaScript for programming. The HTML5 uses the same rendering engine as Internet Explorer, code-named “Trident.” The advantage to this method is that it makes it easy for you to pull in HTML-based content from the Web to parse and render. It allows you to leverage existing knowledge of HTML, CSS, and JavaScript. You can take advantage of existing tools like jQuery (http://www.jquery.com/) to select and modify elements on the page.

The WinRT APIs are projected to the JavaScript runtime as JavaScript objects. With these classes you can interface directly with devices, receive input from the built-in camera, and react to the various sensors on the host device directly from JavaScript. Asynchronous calls are handled using JavaScript “promises.” You can learn more about promises online at http://msdn.microsoft.com/en-us/library/windows/apps/Hh700339.aspx.

The HTML5/JavaScript stack integrates directly with a powerful tool for building your Windows 8 applications: Microsoft Expression Blend. This tool was traditionally used by Silverlight and WPF developers and designers to manipulate the XAML-based user interface. With Visual Studio 2012 the tool has been enhanced to allow designers to also work with HTML5 and CSS.

When should you use this option?

• You are an experienced web developer with HTML5, CSS, and JavaScript skills you wish to leverage for your Windows 8 applications.

• You are working with a design team that prefers to use HTML5 and CSS.

• You are building an application that interacts heavily with HTML content.

The markup for a JavaScript “Hello, World” application requires only a few lines of code, as shown in Listing 1.2.

Listing 1.2. Windows 8 “Hello, World” in JavaScript


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>HelloWorldJavaScript</title>

    <!-- WinJS references -->
    <link href="//Microsoft.WinJS.1.0.RC/css/ui-dark.css"
        rel="stylesheet" />
    <script src="//Microsoft.WinJS.1.0.RC/js/base.js"></script>
    <script src="//Microsoft.WinJS.1.0.RC/js/ui.js"></script>

    <!-- HelloWorldJavaScript references -->
    <link href="/css/default.css" rel="stylesheet" />
    <script src="/js/default.js"></script>
</head>
<body>
    <div id="helloText" />
</body>
</html>


To update the contents of the helloText element, you can reference the identifier and set the innerText attribute from JavaScript in default.js like this:

helloText.innerText = 'Hello, World.';

The JavaScript templates provide an almost identical application experience to the other options. You will find it very hard to identify what language was used to produce an application based on the look and feel it provides.

C++ and XAML

The C++ option is exciting for many developers who have traditionally worked with unmanaged code. It allows you to build Windows 8 applications using C++ in conjunction with XAML. The UI elements declared in XAML are projected to the applications as C++ objects and can be accessed and manipulated directly from the code.

The XAML for the C++ “Hello, World” application simply declares a TextBlock element to populate:

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
    <TextBlock x:Name="HelloText"/>
</Grid>

The code-behind simply sets the Text property of the element:

MainPage::MainPage()
{
    InitializeComponent();
    HelloText->Text = "Hello, World.";
}

You can use the native C++ option to build Windows 8 games that interface directly to DirectX. Take full advantage of the graphics hardware by using High Level Shading Language (HLSL), a feature that is needed by many image processing applications as well as games. This option also allows you to reference existing projects and libraries written in C++ to use with your Windows 8 applications.

When should you use this option?

• You are an experienced C++ developer and you want to leverage this skill for your Windows 8 applications.

• You are working with a design team that is familiar with XAML.

• You don’t want to take on the additional overhead of the web browser engine (HTML5/JavaScript) or the CLR (C#/XAML).

• You are interested in writing native C++ code and/or using high performance features like the HLSL engine.

VB/C# and XAML

The final available option is to use the managed VB and C# languages. The unique WinRT framework allows these applications to access APIs directly through projections that appear as native CLR entities. This book will focus on the C# option, but the API calls and templates are almost identical for the VB.NET version; only the language option itself is different.

The XAML for the “Hello, World” application is the same for C# as it was in the C++ example. The code-behind looks like this in C#:

public MainPage()
{
    InitializeComponent();
    HelloText.Text = "Hello, World.";
}

When should you use this option?

• You are an experienced C# developer and want to continue to leverage your skills for building Windows 8 applications.

• You are a Silverlight and/or WPF developer and wish to continue your investment in XAML knowledge.

• You are working with a design team that is familiar with XAML.

The examples in this book will focus on C# with XAML. You can download the sample “Hello, World” applications online at http://windows8applications.codeplex.com/.

There are two ways you can obtain the source code through CodePlex. The first is by clicking the big Download button in the upper right. This will download a compressed package containing all of the latest source files. The second is by navigating to the Source Code tab where you can browse code online or download a specific version by clicking the Download link. Finally, you can follow the project by clicking a link in the upper right of the home page to be notified of any changes or corrections as they are made.

Behind the Scenes of WinRT

WinRT components are COM objects. They adhere to an Application Binary Interface (ABI) that is a low-level interface between the component and the operating system and other components. The components also implement a special interface called IInspectable that in turn implements IUnknown.

The JavaScript interpreter will use the IInspectable interface to generate the dynamic language bindings. The interpreter grabs the class name, requests the metadata for the component from Windows, and then projects the appropriate interfaces. The end result is that your JavaScript can access the WinRT projections and the interpreter will marshal requests to the underlying components. The interpreter has its own garbage collector responsible for cleaning up instances as they go out of scope.

In the .NET versions, the projected classes actually implement COM Interopability. The .NET application interacts with a CLR class that interfaces to the underlying WinRT (COM) component using a runtime callable wrapper (RCW). The calls are simply marshaled using the project layer to the underlying component. The projection manages the component along with the projected type, so again the native garbage collection in the .NET Framework will take care of objects that are out of scope.

What’s important to note for the C# and XAML combination is that the full .NET Framework is being used. There is a special profile for .NET Windows Store applications that restricts usage to a small set of core Base Class Libraries (BCL) and the projection layers. Applications written using the managed language set will take a dependency on the .NET Framework runtime. The overhead for projection is minimal so there should not be concerns about major performance hits when choosing this option.

The C++ option interfaces with WinRT through a set of language extensions. This enables the compiler to map the WinRT components to familiar language patterns with constructors, destructors, methods, and exceptions. Memory management in C++ is usually done through something called “reference counting,” but for WinRT components this is generated behind the scenes, so references are managed automatically.

WPF, Silverlight, and the Blue Stack

Silverlight 5 was released in December of 2011, several months after Windows 8 was officially announced at the inaugural //Build conference in 2011. Before //Build, many developers speculated on the future of Silverlight, and it was rumored that both Silverlight and even .NET in general would be not be supported in the new operating system. This was not the case, and Windows 8 machines can run the full .NET framework along with Silverlight applications, both in browser and out-of-browser (OOB).

Is there a place for these applications on the new platform? The answer I believe is definitely, “Yes.” There is a substantial amount of time and resources invested in existing applications that run in Silverlight and on the .NET framework using WPF. Many of these applications can run “as is” on Windows 8 machines, especially if they have already been built to integrate touch features. Windows 8 provides two distinct environments that can run side-by-side: Windows Store and Desktop. These are sometimes referred to as “green stack” for Windows 8 applications and “blue stack” for desktop applications because of the colors that were used in the initial diagrams presented by Microsoft to illustrate the Windows 8 platform.

Windows Store, or the green stack, is the focus of this book. (Whenever you see “Windows 8 application,” I am referring to this special non-desktop application type.) The Desktop environment, or the blue stack, is the one many developers are already familiar with. It supports the .NET Framework along with various frameworks including WPF and Silverlight. You can continue to write software targeting that environment using the languages and tools of your choice. The decisions developers face is whether to build or migrate to Windows 8 or to continue to support the desktop.

Some applications probably don’t make sense in the Windows Store environment. Though a Windows Store version of Outlook would be very welcome, I can’t imagine editing a large and complex Excel spreadsheet using the same user interface. I also can’t imagine developing software using the Windows Store environment, which is why Visual Studio 2012 runs in the Desktop environment. For those scenarios, it’s better to attach the mouse and keyboard and pound out code because building enterprise applications using gestures and touch probably isn’t something that will happen in the near future.

Many applications may benefit from versions that support both modes. The main application may run in the Desktop environment while a streamlined version that provides an executive dashboard of information with alerts and news feed is built for the Windows Store environment. For example, Internet Explorer 10 runs as a Windows Store application within the Windows Store environment. From the desktop, you can launch a different version that uses the traditional desktop interface and supports plug-ins. There is no reason to restrict your efforts to one target, and the fact that Windows 8 applications support languages like C# provides an opportunity to share key libraries of code among your various targets.

One special version of Windows 8 that doesn’t support the blue stack is referred to as Windows RT. This version runs exclusively on devices with ARM-based chipsets. ARM devices use a special chip that is optimized for low power and to generate little heat. Slates, tablets, and smart phones built using ARM chips can have smaller form factors because they don’t require fans to cool the main microprocessor. The chip uses a different native instruction set than traditional Intel machines, and therefore the special version of Windows written for ARM devices will only support Windows 8 applications.

Summary

This chapter covered a brief history of Microsoft and the Windows operating systems along with the various APIs and platforms used to build software. You learned about the new Windows Store platform and related tools for building touch-friendly applications that run on Windows 8. I covered a few different ways to build the applications and reviewed the selection of languages and graphics markup engines that are available.

Windows 8 applications share common traits that are intended to provide a consistent, elegant, and compelling user experience. They are seamlessly integrated, tailor themselves to fit target devices, and are built using the same languages and tools C# and XAML developers are used to. If you can’t wait to get started building applications for this amazing new platform, all you need to do is turn the page!

Works Cited

Edwards, B. The Computer Mouse Turns 40. Macworld: December 9, 2008.

Weller, C.E. The Early History of the Typewriter. La Porte: Chase & Shepard, 1918.

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

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