CHAPTER 1

Windows Store apps are a new kind of application that run on Microsoft’s most recent generation of operating systems. Currently, this includes Windows 8, Windows RT, and Windows Server 2012. When installed, an app can have one or more tiles pinned in user-selected positions on the Windows Start screen. Users can launch the app by simply tapping or clicking one of its tiles. Additionally, some applications can be launched by Windows itself as a result of user interaction with common Windows interface elements, including the charms bar, which provides a focal point for accessing common functions such as in-app searching (Search charm), app-to-app data exchange (Share charm), hardware interaction (Device charm), and configuring settings and preferences (Settings charm). Apps can even be launched as a result of scenarios where they have elected to participate in Windows-brokered interactions that are actually initiated from within other applications.
Windows Store apps and the Windows environment they run in feature a new user experience. Apps occupy a single window, and run either full-screen or in a secondary, fixed-size reduced screen known as the "snapped" view. This user experience follows a set of published Microsoft design principles. A summary of these principles includes:
Windows provides a controlled environment for Windows Store apps to run in—sometimes known as a “sandbox”—which allows Windows to protect system resources and state from defective or malicious programs. Apps submitted to the Windows Store are qualified against a published set of requirements as part of a certification process that helps to ensure that customers’ systems are not adversely affected by defective or malicious apps. Windows Store apps are digitally signed to provide verification of their authenticity and integrity. Apps published to the store can be offered free of charge; include time-based trials, feature-based trials, or both; or be sold for a fee. In-app purchases and subscriptions are also available for Windows Store apps.
As the name implies, most Windows Store apps are made available for purchase from the centralized Windows Store. This provides development efforts of all sizes, from single hobbyist developers to large corporate concerns, the opportunity to reach a global marketplace of customers with their apps to realize revenue or recognition—or both! However, Windows Store app distribution isn’t limited to the Windows Store—several line-of-business deployment scenarios exist, including deployment via enterprise management systems. This process of deploying an app through a means other than the Windows Store is known as “sideloading.”
A thorough overview of Windows Store apps has been published by Microsoft and can be found at http://msdn.microsoft.com/en-us/windows/apps/hh852650.aspx.
Windows Store apps run on top of a new runtime API called the Windows Runtime, or WinRT. This is a fundamental shift in Windows development, where for quite some time development has occurred on top of one version or another of the Win32 APIs (albeit the presence of Win32 has sometimes been abstracted away by development tools and runtimes, such as MFC, Visual Basic 6, or even .NET). In contrast to the C-style approach afforded by Win32, WinRT provides a more modern object-based surface for application development.
In addition to providing a new API surface for developers to build on, the Windows Runtime also contributes to a development approach that strives to put different development technology stacks on similar footing. Developers can choose to write Windows Store apps using UI/code combinations that (at present) include XAML/.NET, HTML/JavaScript, or XAML/C++, depending on their own backgrounds and preferences. While these tools are positioned to be on somewhat equal footing in terms of their ability to deliver Windows Store apps, they each have their strengths (XAML/C++ has access to DirectX for advanced gaming, for example) which also play into the decisions as to which technology should be used.
Note: The only .NET languages that are presently supported include C# and Visual Basic. To use other languages such as F#, Portable Class Library projects can be used. A discussion of Portable Class Libraries is beyond the scope of this book.
Among several innovations related to these multiple development environments is the concept of “language projections.” Windows Runtime components are exposed to each of these environments in a way that is familiar and appropriate to each one. This greatly simplifies the P/Invoke or COM interop process that .NET developers had to go through to access OS APIs. It is important to note that this isn’t limited to the Windows Runtime Components provided by the OS—developers can create their own Windows Runtime components in .NET or C++ that expose their functionality through interfaces built from combinations of the standard Windows Runtime types. These components can then be consumed by any Windows Store app development environment, and are also “projected” into language-specific idioms.
Note: Custom Windows Runtime components can be created in C++, C#, or Visual Basic, but not JavaScript.
Another key feature of the WinRT APIs is a fundamental shift to emphasize the use of asynchronous calls for long-running tasks. API methods that might take longer than 50 ms to execute have been implemented as asynchronous methods, with no corresponding synchronous call (as was sometimes the case in other APIs where asynchronous calls were made available). This focus on asynchrony for long-running operations helps to ensure that the UI is not locked while waiting for these operations to complete.
The following code illustrates using the asynchronous API call for creating a file from both C# and JavaScript. The C# code takes advantage of the new await keyword to support the asynchronous operation, whereas the JavaScript code makes use of JavaScript “promises.”
// Using CreateFileAsync from C#. var folder = ApplicationData.Current.LocalFolder; var file = await folder.CreateFileAsync("NewFileName.txt", // Work with the file that was created. |
// Using createFileAsync from JavaScript. var folder = applicationData.current.localFolder; folder.createFileAsync("NewFileName.txt", .then(function (file) { // Work with the file that was created. }); |
Note: The async and await keywords are new additions to the C# language. When the compiler encounters these keywords, it will actually generate IL code that sets up the necessary state tracking, allowing the method to return control to its caller and handling the logic necessary to wait on the asynchronous operation to continue. When the asynchronous operation completes, the code that was produced by the compiler will resume execution at what was originally the next line of code in the method. This framework greatly simplifies the writing and readability of asynchronous code, allowing the compiler to manage all of the complex details.
Windows Store apps are commonly developed using the development tools that have become familiar to most Windows application developers over the past several years. This includes the Visual Studio 2012 IDE and Expression Blend for Visual Studio 2012, the latter having been enhanced from its roots as a design-centric tool for XAML development to also provide functionality for HTML-based Windows Store app development. As of this writing, Windows Store apps can only be developed on the Windows 8 operating system—when installed on other operating systems, Visual Studio 2012 will not include the options for creating Windows 8 projects.
Tip: You can download Visual Studio Express 2012 for Windows 8 free of charge from Microsoft at http://www.microsoft.com/visualstudio/eng/products/visual-studio-express-for-windows-8.
Note: While C# and Visual Basic can be considered “sibling languages” for .NET development, and much has been done to create functional parity between these two languages, the rest of this book will be focusing exclusively on C#.
In order to develop Windows Store apps, developers must first obtain a (free) developer license. A developer license is installed on the machine being used to write Windows Store apps. These licenses do expire periodically, so they must be renewed. An active Internet connection is required to obtain a developer license. Visual Studio Express 2012 for Windows 8 automates the process of obtaining or renewing a developer license. When Visual Studio Express is launched and a developer license is not available on the machine, users will be prompted to “Get a developer license for Windows 8.” Clicking I Agree will ask users for Microsoft Account credentials to obtain the license. Once the credentials are provided, the license will be installed on the machine.
Note: The prompt-on-launch behavior is specific to the Visual Studio Express for Windows 8 SKU. In the other Visual Studio SKUs, the prompt will appear when a Windows Store project is first opened on a machine without a valid developer license.

There are six default Visual Studio templates available for creating .NET projects for Windows Store apps in Visual Studio 2012 and Expression Blend:

There is a subtle but important difference between the class library and Windows Runtime component projects. The class library project can only be consumed by other .NET Windows Store app projects, including other class library projects. The elements exposed by these libraries can expose WinRT types as well as .NET types included within the .NET subset exposed to Windows Store apps (this distinction will be covered later). Windows Runtime component projects can be consumed by any Windows Store app project, including XAML/C++ and HTML/JavaScript projects. As a result, the elements they can expose are restricted to valid WinRT types and conventions.
There is technically another project type that can be developed for and consumed by XAML/.NET Windows Store app projects—the Portable Class Library. This project allows creating class libraries that can be consumed by multiple .NET framework variants, including .NET 4 and 4.5, Silverlight 4 and 5, Windows Phone 7 and 7.5, and Xbox 360. Details of this library type are outside the scope of this book, but more information can be found at http://msdn.microsoft.com/en-us/library/windows/apps/gg597391.aspx.
Tip: Microsoft has published a vast set of code samples for Windows Store apps (along with various other code samples) in the MSDN Code Gallery, available at http://code.msdn.microsoft.com. Furthermore, support for searching, downloading, and installing these samples has been built directly into Visual Studio’s New Project dialog. In this dialog, under the Online node, there is now a Samples entry. The collection of available samples can be browsed by selecting values under this node, or the contents can be searched by using the Search Installed Samples text box in the upper right-hand corner of the dialog. Selecting a sample template will download the template and open a new Visual Studio project that includes the contents of that sample. Additional information about obtaining online samples can be found at http://msdn.microsoft.com/en-us/library/jj157272.aspx.
The .NET Framework is exposed via a profile that is specific to Windows Store apps, known as “.NET for Windows Store apps.” Much like Silverlight applications have access to a reduced set of available .NET types and members, a similar paring of functionality occurs with the .NET for Windows Store apps profile. This reduction serves two purposes: First, .NET types that overlap WinRT types have been removed to prevent duplication. Second, types and members that would otherwise provide functionality outside of the controlled runtime environment provided by Windows for Windows Store apps have also been removed so as to maintain this sandboxed environment and minimize any potential confusion about their availability.
Tip: The provided Windows Runtime types can often be distinguished from the provided .NET types based on their namespaces. WinRT types are usually located in namespaces that start with “Windows,” such as Windows.Storage, whereas .NET types are often located in namespaces that start with "System,” like System.IO.
A list of supported .NET APIs supported in the .NET for Windows Store apps profile can be found at http://msdn.microsoft.com/en-us/library/windows/apps/br230232.aspx.
An important new addition to the .NET Framework that is included in the .NET for Windows Store apps profile is support for the new async and await keywords, which work with the compiler to greatly simplify writing asynchronous code. In previous incarnations of .NET, it could be tedious to write asynchronous code. The latest popular technique made use of lambda functions and closures to simplify things, but it was still an awkward process that involved hooking the completion callback, providing the completion code in a lambda, and then calling the method that invokes the callback. In rough English, your code would read, “This is what to do when you’ve done your next task. Now do your next task.” This technique could be complex and hard to understand when multiple asynchronous steps were being chained together. The following code illustrates this technique when retrieving the markup for the Syncfusion website:
private void FetchSomething() { var client = new WebClient(); client.DownloadStringCompleted += (sender, args) => { var result = args.Result; // Run your code. }; client.DownloadStringAsync(new Uri("http://www.syncfusion.com")); } |
With the async and await keywords, the natural flow of your code is preserved, and the compiler takes on the task of handling the convoluted details of sequencing the code. The following much simpler code makes a similar web call:
private async void FetchSomething() { var httpClient = new HttpClient(); var result = // Run your code. } |
The key differences start with the use of the await keyword preceding the GetStringAsync call, which instructs the compiler to set things up so that the code following the “Run your code” comment does not execute until the GetStringAsync call returns, while at the same time allowing the calling thread to continue executing. The second difference is that when a method contains an await call, that method’s declaration must specify the async keyword.
The emphasis on asynchronous calls in the WinRT API will lead to frequent use of async and await in most Windows Store app code, including the samples throughout this book, so additional context can be found throughout later chapters. Additional information on asynchronous programming with async and await can be found at http://msdn.microsoft.com/en-us/library/hh191443.aspx.
While the WinRT members generally play nicely with their .NET framework counterparts, there are a few places where the alignment isn’t quite perfect. In these cases, new objects, new methods, or helpers are sometimes provided to bridge some of the gaps. A comprehensive review of all of these is beyond the scope of this book, but there is an important set of extension methods that is worth calling out here, and some others will be mentioned in context within the chapters that follow. For more information, visit http://msdn.microsoft.com/en-us/library/windows/apps/hh694558.aspx.
There are three main sets of extension methods that facilitate conversion between .NET Framework types and WinRT types. These are:
There was a special project type mentioned in the list of available Visual Studio project types: the Windows Runtime component project. As mentioned, this project allows components to be created using .NET that can be referenced from other Windows Store app development languages, including C++ and JavaScript. Because the component that is created is actually a WinRT component, there are some restrictions that need to be followed—these restrictions are similar in concept to the idea of creating CLS-compliant .NET assemblies.
The guidelines that custom WinRT components must follow apply only to outward-facing (public) members, and include:
Note: WinRT types only support absolute URIs, whereas .NET types can support both relative and absolute URIs. When the System.Uri is used to provide values to WinRT components, care must be taken to ensure that the System.Uri object only contains absolute URIs.
Additionally, while WinRT types support method overloading, JavaScript’s weakly typed and type coercion nature will cause it to struggle to determine which method instance to call in situations where a method has overloads with the same number of parameters. In such a case, one of the overloads must be decorated with the Windows.Foundation.Metadata.DefaultOverloadAttribute, and JavaScript code will only be able to access that particular overload. This is illustrated in the following code sample, where JavaScript code will only be able to call the version of DoSomething that takes an Int32 as a parameter:
[DefaultOverload] public void DoSomething(Int32 value) { } public void DoSomething(String value) { } |
Whereas .NET handles asynchronous operations using the Task or Task<T> type, WinRT uses several interfaces: IAsyncAction, IAsyncActionWithProgress<TProgress>, IAsyncOperation<TResult>, or IAsyncOperationWithProgress<TResult, TProgress>. There are two extension methods, WindowsRuntimeSystemExtensions.AsAsyncAction and WindowsRuntimeSystemExtensions.AsAsyncOperation<T>, that allow a Task to be returned as the equivalent IAsyncXXX interfaces that do not involve reporting progress. To report progress, additional steps need to be taken involving the WinRT AsyncInfo class.
Additional information about the restrictions for WinRT components and the mappings that occur between the .NET types and their WinRT counterparts can be found at http://msdn.microsoft.com/en-us/library/windows/apps/br230301.aspx.
Up to this point, a lot of important concepts for developing Windows Store apps with .NET have been presented. It seems to be a good opportunity to close out this introductory chapter by creating an application in the spirit of the ubiquitous "Hello World" application. This will allow an opportunity to touch on some final concepts and show some of the already-presented concepts in action before moving on to content that is more specifically targeted.
To get started, launch Visual Studio 2012 (hereafter just “Visual Studio”) and select New Project either from the start page or from the File menu. In the New Project dialog, select the Visual C# template group and the Windows Store group under it. Select the Blank App (XAML) project template, and enter a name for the project or simply accept the default AppX name that is provided. Congratulations! You have just created a Windows Store app.
Once Visual Studio finishes spinning up the project, the Solution Explorer should contain the following:

The contents of the project shown in Figure 4 include:
Other items in the project include assembly references to the .NET for Windows Store apps Framework profile and the Windows Runtime, and several image files that are used for application configuration.
As indicated previously, the Application Manifest Configuration File contains the settings that govern how your application will integrate with Windows. The file itself is simply an XML settings file, and Visual Studio provides an interactive user interface for making changes to this file. During the build process, this configuration file is copied in order to produce the Application Manifest file.

Visual Studio divides the manifest into four sections: Application UI, Capabilities, Declarations, and Packaging. The Application UI page contains settings that describe the app when it is deployed, including the text and images to use for the application’s tiles and other icon displays, the splash screen content to display when launched, and the screen orientations the application will support.
The Capabilities page indicates system resources that your app intends to access, such as removable storage, webcam, or Internet, to name a few. Failing to declare a capability in the manifest and then trying to access that resource from code will result in an exception. Declaring more capabilities than an app actually needs can result in the app failing the marketplace certification step. When customers download an app from the store, they are first informed of the capabilities that the app has declared. Certain capabilities—specifically enterprise authentication, shared user certificates, and documents library—can only be set for applications that are published by a company account, as opposed to an individual developer account. Capabilities are described in detail at http://msdn.microsoft.com/en-us/library/windows/apps/hh464936.aspx.
The Declarations page configures settings for the system extensibility points—known as contracts and extensions—which the application elects to interact with. The available declarations are described at http://msdn.microsoft.com/en-us/library/windows/apps/hh464906.aspx, and the subjects of contracts and extensions will be discussed more fully later in this book.
The Packaging page allows setting properties that affect the deployment of the project package. This includes the package name which identifies the package on the system. This value will be replaced when the package is uploaded to the Windows Store. The Package Display Name property provides a user-friendly name that is displayed in the Store. This value is also replaced when the app package is uploaded to the Store. Logo specifies the image to use in the Windows Store description page. Version indicates the version of the app that will be used and displayed. The Publisher field allows configuring the digital certificate that is used to authenticate the package. This is also replaced when the app is uploaded to the store. The Publisher Name specifies the value used for that display in the store, and is another field that is updated when the app is uploaded to the store. Finally, Package Family Name is read-only, calculated from the package name and publisher, and is used to identify the package on the system.
It is time to add some content to the simple “Hello” application. This application simply collects some information from users about the characteristics of a random “word” to be requested from the API provided at http://www.random.org. Because of the HTTP calls being made, this simple scenario provides an opportunity to use asynchronous calls within a Windows Store app. The first step will be to add some user interface elements. Adding the following markup between the Page elements of the MainPage.xaml file will provide a title and the relevant controls:
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}"> <Grid.RowDefinitions> <RowDefinition Height="140"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <!-- Page title. --> <Grid Grid.Row="0" Margin="120,0,0,0"> <TextBlock Grid.Column="1" Text="Hello Windows Store apps Succinctly" Style="{StaticResource PageHeaderTextStyle}"/> </Grid> <!-- Page content. --> <Grid Grid.Row="1" Margin="120,0,120,50"> <Grid.Resources> <Style TargetType="TextBlock" BasedOn="{StaticResource BasicTextStyle}"> <Setter Property="VerticalAlignment" Value="Center"/> <Setter Property="Margin" Value="0,0,10,0"/> </Style> </Grid.Resources> <StackPanel> <!-- Specify the length of the word to return. --> <TextBlock Text="Word Length"/> <ComboBox x:Name="LengthSelection" SelectedIndex="0" Width="150" HorizontalAlignment="Left"> <ComboBox.Items> <x:String>5</x:String> <x:String>6</x:String> <x:String>7</x:String> <x:String>8</x:String> </ComboBox.Items> </ComboBox>
<!-- Indicate if the word should contain digits. --> <ToggleSwitch x:Name="IncludeDigits" Header="Include Digits" OnContent="Yes" OffContent="No" IsOn="False"/>
<!-- Indicate the allowable letter cases for the word. --> <TextBlock Text="Letter Case"/> <StackPanel Margin="20,10,0,0"> <RadioButton x:Name="MixedCase" Content="Mixed Case Letters" IsChecked="True"/> <RadioButton x:Name="UpperCaseOnly" Content="Upper Case Letters Only"/> <RadioButton x:Name="LowerCaseOnly" Content="Lower Case Letters Only"/> </StackPanel>
<!-- Button to trigger the fetch. --> <Button Content="Go" Click="GoButton_Click" Width="250" Margin="0,10,0,0"/>
<!-- Display the results.--> <TextBlock x:Name="RandomWordText" Style="{StaticResource SubheaderTextStyle}" /> </StackPanel> </Grid> </Grid> |
Next, a handler is provided for when users click the Go button. In this case, the request URL is built based on the user input and the UI is updated with the results from the call. It is important to note that the call to make the request is asynchronous, requiring the use of the previously mentioned async and await keywords. This code is placed in the MainPage.xaml.cs file.
private async void GoButton_Click(object sender, RoutedEventArgs e) { // Request a random set of letters from http://www.random.org. // For details, see http://www.random.org/clients/http/. // 1 string result. // Variable character length based on UI input. // Variable includes digits based on UI input. // Variable upper and lower alpha based on UI input. // Request unique results. // Request results as plain text. // Request should initiate a new randomization. // Build the Uri from the inputs in the UI. var builder = new UriBuilder("http://www.random.org/strings/"); var lengthArg = String.Format("len={0}", LengthSelection.SelectedItem); var digitsArg = String.Format("digits={0}", IncludeDigits.IsOn ? "on" : "off"); var includeUpper = UpperCaseOnly.IsChecked.Value || MixedCase.IsChecked.Value; var upperAlphaArg = String.Format("upperalpha={0}", includeUpper ? "on" : "off"); var includeLower = LowerCaseOnly.IsChecked.Value || MixedCase.IsChecked.Value; var lowerAlphaArg = String.Format("loweralpha={0}", includeLower ? "on" : "off"); var queryString = String.Format("num=1&{0}&{1}&{2}&{3}&unique=on&format=plain&rnd=new", lengthArg, digitsArg, upperAlphaArg, lowerAlphaArg); builder.Query = queryString; // Make the Http request. var httpClient = new HttpClient(); var results = await httpClient.GetStringAsync(builder.Uri);
// Split the first result off from the (potential) list of results. var resultWord = results .Split(new[]{'\n'}, StringSplitOptions.RemoveEmptyEntries) .First(); // Report the word in the UI. RandomWordText.Text = String.Format("Your random word is: {0}", resultWord); } |
This code will require a using statement for the System.Net.Http namespace.
Note: This is a very simple, contrived example, so much of the error checking and UI niceties that would be part of even the simplest real-world browser apps are being omitted for the sake of brevity.
At this point, the app can be built, deployed, and launched using the facilities provided by Visual Studio. Selecting Start Debugging from the Debug menu will launch the app with the debugger attached. Visual Studio also provides a special simulator environment that enables the app to run within a special window that simulates a tablet. The simulator provides options for:
The simulator is an especially valuable debugging tool since it runs in a window, whereas a Windows Store app would otherwise run full-screen, forcing you to toggle between Visual Studio and the running app in single-monitor environments. Furthermore, it enables enhanced testing of machine facilities—such as touch or orientation—that may not be readily available or may otherwise be inconvenient on a traditional development machine. To run an app within the simulator, the simulator option can be selected from the Target Device drop-down list in the standard Visual Studio toolbar.

Note: The simulator is not actually running in a virtual machine or another isolated environment like other systems’ simulators, including the emulator provided in the Windows Phone 7 SDKs. The Visual Studio simulator actually runs as a remote desktop connection back to the current machine.
Debugging a Windows Store app remotely on another Windows 8 machine is also an available option, though it will not be covered in this book. For more information on the remote machine option, see http://msdn.microsoft.com/en-us/library/windows/apps/hh441469.aspx.
Running the “Hello World” app within the simulator should resemble the following:

This chapter presented several of the core concepts underlying development for Windows Store apps. This included an overview of Windows Store apps and a discussion of the new Windows Runtime. The fundamentals of using Visual Studio to develop a Windows Store app with .NET were discussed, and a sample “Hello World” app was created and run within the Visual Studio simulator.
The rest of this book will focus on several key areas that are important to understand for developing a Windows Store app. These include: