Part II

Creating Windows 8 Applications

  • Chapter 5: Principles of Modern Windows Application Development
  • Chapter 6: Creating Windows 8 Style Applications with HTML5, CSS, and JavaScript
  • Chapter 7: Using XAML to Create Windows 8 Style User Interfaces
  • Chapter 8: Working with XAML Controls
  • Chapter 9: Building Windows 8 Style Applications
  • Chapter 10: Creating Multi-Page Applications
  • Chapter 11: Building Connected Applications
  • Chapter 12: Leveraging Tablet Features

Chapter 5

Principles of Modern Windows Application Development

WHAT YOU WILL LEARN IN THIS CHAPTER:

  • Grasping the concepts of the Windows 8 design language
  • Understanding the difference between synchronous and asynchronous programming
  • Using the new asynchronous patterns in C# 5.0
  • Creating asynchronous logic in JavaScript

WROX.COM CODE DOWNLOADS FOR THIS CHAPTER

You can find the wrox.com code downloads for this chapter on the Download Code tab at www.wrox.com/remtitle.cgi?isbn=012680. The code is in the Chapter05.zip download and individually named, as described in the corresponding exercises.

In this part of the book, you learn about creating Windows 8 applications. Windows 8 supports numerous programming languages, including JavaScript, C#, and C++, and you will see all of them in the following chapters.

Before you start to program, however, you first must understand the basic principles of modern Windows application development. In this chapter, you learn about the key concepts of the Windows 8 design language, and then you explore and try out the asynchronous programming patterns in C# and JavaScript.

Windows 8 Style Applications

Before you learn about the principles and characteristics of the new Windows 8 style applications, you must first turn back the clock to understand what brought the Windows 8 design language to life. So, let’s look into the history and talk about retro-style applications.

A long time ago, when people started to use computers, they needed aids to understand how the various computer software worked. To simplify the user’s life, software developers started using metaphors and built their software on concepts that were well-known from real life. Probably the most widely used metaphor is the “desktop.” With modern operating systems that follow this metaphor, users see documents and applications on their computer as very similar to what they might see on their desk in the real physical world.

Although the desktop metaphor is more than 40 years old (according to Wikipedia) it was first introduced by Alan Kay at Xerox PARC in 1970), you can find the same concepts in today’s devices. New devices have much more powerful hardware that has helped to portray objects on the desktop more realistically.

For example, if you look at the home screen of even the smallest cell phone today, you can see icons that are beautifully painted. Numerous colors, shadows, and three-dimensional (3-D) effects make them look like the original objects in the physical world. If you start an e-book reader application, you will probably first see a bookshelf that looks absolutely real with a wooden texture and well-aligned books. Then, when you open an e-book, it opens like a real book, and animations make you feel like you are reading a physical book when you turn the pages.

This is the iconographic design style that uses metaphors from the physical world, and portrays objects with hyper-realistic graphics in the digital world.

However, the world has changed since these concepts were born. A new generation of users has grown up that doesn’t need aids to understand and use computers. Instead of the gorgeous graphics, people now prefer simplicity and productivity. Users don’t care anymore if an application is drawn beautifully or super-beautifully, but they are delighted with applications that can help them to quickly solve their problems. In today’s fast-paced world, consuming information quickly is the key to success. This is called the infographic design style, and the user interfaces (UIs) of Windows 8 style applications follow these principles.

What Is the Windows 8 Design Language?

Microsoft created a new design language for Windows 8 that follows the infographic design principle. Although every application has its own appearance, they have common patterns and common themes that help users to understand and use them in a similar way. By following the same design concepts in your application that the operating system is using, you can help your users to be more productive with your software.

Although the origins of this design language can be found in earlier versions of the Windows Media Center and the Zune media player applications, it was with Windows Phone 7 that Microsoft fully committed to this new direction and made this language prominent. Since then, the dashboard of Xbox 360 has been adapted to this design, and Windows 8 relies heavily on it as well. In the future, you will probably see more and more applications adopting these concepts.


NOTE For Windows 8, you can create two kinds of applications: classic desktop applications and new Windows 8 style applications. You are not forced to use Windows 8. However, the Windows 8 concepts may be much more usable on devices with touch support. Thus, if you are targeting tablets or other devices where users can control the application with touch gestures, consider using Windows 8.

General Design Principles for Windows 8 Applications

Figure 5-1: A Windows 8 style icon with simplified graphic

c05f001.tif

The first thing you probably notice about Windows 8 is that it is definitely different from what you are used to. Windows 8 breaks with the old conventions, and you must be open-minded if you want to accept it.

The first thing you have to take into account is that software and devices are part of a digital world. If you see a photo of a book on your phone or computer, it reminds you of reading, because your brain connects the digital photo to the physical book. But your brain doesn’t need a perfect photo or a realistic image to have that connection, because you know that it is just a digital copy of an analog object on your device. With that, you can simplify the image — as you can see in Figure 5-1 — while keeping its original purpose.

Your software doesn’t need to copy the analog world into the digital world. It doesn’t have to look like something else — it actually is a digital application. Authenticity and simplicity can help users to understand programs faster, which is very important in the infographic design style.

The second thing you have to realize is why you create your applications. It is primarily for producing and consuming information. In this case, you must put the information into the center, and get rid of everything that doesn’t help the production and the consumption of it (remember, simplicity). The focus should be on the content, and not the frame that holds it. If your users are working with the content, then all the windows, borders, lines, and background images — the so-called chrome — are not so important to them. You can use them if they help your original goal, but not simply to make your application look fancy.


NOTE Remember, most people use mobile devices these days, and all the extra chrome you use in your application consumes power and can degrade the precious battery life.

Just take a look at any of the built-in Windows 8 style applications. These are not running within a window, but instead are running in full screen to give space for the content. Windows 8 style applications even hide the classic Windows taskbar to free up some screen real estate (remember, mobile devices have small screens), and help the users to concentrate on the current application.

Today, users are flooded with data from various sources, so they really appreciate when the information is tailored to their needs. On a tablet device, the application may know who you are, where you are, in which position you hold the device, who is around you, and what information are you interested in right now. The application can customize itself to deliver content that is personal, relevant, and connected. If the device supports touch gestures, you can interact directly with the content, which is another level of user experience that rises above using the classic mouse and keyboard combo.

In the Windows 8 design language, content is king, and if you want to use it wisely, you need good typography. Typefaces, font sizes, colors, and whitespace are the keys to displaying the information in a easily readable format. Microsoft provides recommendations about the best practices, and even provides controls and typefaces you can use for free without extra licensing.

Animations are also important in the Windows 8 design language, because motion can further help the user to understand the software. The consistent use of animations makes your application more intuitive, even if the user doesn’t consciously care about them. You can use fast and fluid animations to signal to the user that your application is responsive, and bring the interface to life.

But wait a minute! What happens with the unique appearance of your application if you use the same layout, fonts, animation, and style as any other application? Windows 8 provides a set of design principles that Microsoft believes can make applications better by answering the usability challenges. This set is not a rigorous list of expectations your application should meet in order to run on Windows 8. You can definitely brand your application while you are following the Windows 8 design principles. Just look at the built-in applications or the applications that are available from the Windows Store, and you will see that they are different and reflect the brand of the author. Be inspired by the design language, but balance between Windows 8 and your own style.

Application Structure and Navigation Models

Windows 8 style applications are next-generation software in the sense that they are targeting not only desktop PCs and laptops, but also the latest handheld tablet devices. Tablet devices support touch gestures, and they often come without any other input device (including mouse and keyboard). The Windows 8 operating system is fully prepared for running on tablets (for example, it has a virtual keyboard that enables you to enter text on a touchscreen), and you should also design your application for gesture-based control. In fact, Microsoft recommends designing your Windows 8 style application for touch-first experience, meaning that you should design and optimize for gestures as the primary input method.


NOTE Although touch gestures are the primary input method for Windows 8 style applications, you can use them fully with mouse and keyboard as well.

Unfortunately, gestures present two problems:

  • Users can’t work with their fingers as precisely as they can with a mouse. This means you must enlarge the touch targets on your UI.
  • Touch gestures are not easy to explore. This type of input works beautifully only if the gestures are used consistently across the system, because, in this way, users must learn them once, and can use the same gestures everywhere, even in your applications.

Fortunately, Microsoft developed a navigation system for Windows 8 style applications that solves these problems.


NOTE You can read more about touch gestures in Chapter 14, “Advanced Programming Concepts.”

The basic unit of navigation in a Windows 8 style application is the page. As you may guess, the name comes from the web, because these application pages work very much like web pages. The user works with one page at a time, and navigation means going from one page to another. No windows or pop-ups appear that could break this consistency and complicate the UI.

You can organize your pages into a flat system or into a hierarchical system.

In the flat system, all pages reside at the same hierarchical level. This pattern is best for applications that contain only a small number of pages and the user must be able to switch between the tabs. Games, browsers, or document-creation applications often fall into this category. In these applications, the user can switch between the pages using the navigation bar (or nav bar) on the top of the screen, as shown in Figure 5-2.

You can represent your pages in any way on the navigation bar, but a typical technique is the use of thumbnails.

The hierarchical system is more familiar to people because it follows the same pattern in which website pages are organized. The hierarchical pattern is best for applications that have a large number of pages that can be grouped into multiple sections.

The root of the hierarchy is a hub page, which is the entry point of the application. On the hub page, users can get a glimpse of what is available in the sections of the application, so this first page should engage the users and draw them into the section pages. You can see an example of the hub page in Figure 5-3 from the Bing Finance application. This welcome page is an at-a-glance summary of the most important and relevant data in the application.

Figure 5-2: The Windows 8 style Internet Explorer with the tab navigation bar

c05f002.tif

Figure 5-3: The hub page of the Bing Finance application

c05f003.tif

From the hub page, users can navigate to the second level of the application, the section pages. Section pages often contain lists that can be grouped, sorted, and filtered. In Figure 5-4, you can see the section page of the Bing Finance application that lists the stocks available in the application.

From the list on the section page, users can select a single item and navigate to the third level of the hierarchy, the detail page. Detail pages may contain all information about the selected item, and the layout may vary depending on the type of the content. In Figure 5-5, you can see the detail page of a single stock in the Bing Finance application.

Users can go deeper in the hierarchy by activating (touching) an item on the screen, or can go back by using the Back button at the top of the page. Naturally, if your application is simpler, you can omit the hub page or the section page to make a more shallow hierarchy.

In Chapter 2, “Using Windows 8,” you learned about the charm bar and the app bar. The charm bar can slide in from the right, and the app bar can slide up from the bottom of the screen to display more options to the user. Both bars are extensible, and you can add your application-specific options to them.

The app bar should contain contextual commands, and can even pop-up menus when they have too many commands. The charm bar includes the Settings charm, which provides a single access point to all settings that are relevant in the user’s current context. This means you should add your application’s settings to the settings charm as well. In Figure 5-6, you can see how the built-in Weather application extends the Settings charm to include its options.

Figure 5-4: The Watchlist section page of the Bing Finance application

c05f004.tif

Figure 5-5: The detail page of a stock in the Bing Finance application

c05f005.tif

Figure 5-6: The Settings charm of the Weather application

c05f006.tif

At first, you may think that the navigation concept with the app bar, charm bar, nav bar, hierarchy, and Back button is really complex. Perhaps that’s true. However, if all these concepts are used consistently across the operating system and the applications, there’s no doubt that the users will sooner or later master them, and, at the end of the day, hopefully they will even enjoy them.

Now let’s take a look at how to create a basic Windows 8 style application.


Try It Out: Creating a Basic Windows 8 Application
To create your first Windows 8 style application, follow these steps:
1. Start Visual Studio 2012 by clicking its icon on the Start screen.
2. Select File &menuarrow; New Project (or press Ctrl+Shift+N) to display the New Project dialog box.
3. Select the Installed &menuarrow; Templates &menuarrow; Visual C# &menuarrow; Windows Store category from the left tree, and then select the Grid Application project type in the middle pane, as shown in Figure 5-7.

Figure 5-7: The New Project dialog box

c05f007.tif
4. Click OK. Visual Studio creates an empty project skeleton and opens the main App.xaml.cs file in the code editor.
5. Start the application by clicking the Debug &menuarrow; Start Without Debugging menu item. Visual Studio compiles and starts the application, and you will have a Windows 8 style application running, as shown in Figure 5-8.
6. View the groups in the application by scrolling from left to right.
7. Click one of the group titles to open the group detail page.

Figure 5-8: The default Grid Application type

c05f008.tif
8. Review the content on the group detail page by scrolling from left to right, and then click one of the items to navigate to the item details page.
9. View the content of the item detail page, and then navigate back to the home screen by clicking the Back button twice, which is the big left arrow on the top of the screen.
How It Works
According to the project template you selected, Visual Studio generated an empty skeleton that contains everything you need to start creating your Windows 8 style application in C#. You can open the Solution Explorer window by clicking the View &menuarrow; Solution Explorer menu item (or simply pressing Ctrl+Alt+L), where you can see all the files within your project, as shown in Figure 5-9.
The application contains three pages: the homepage, the group detail page, and the item detail page. In the Solution Explorer window (and also in your project folder), you can find the GroupedItemsPage.xaml, the GroupDetailPage.xaml, and the ItemDetailPage.xaml files that represent these pages.
The generated files also contain code to implement the navigation between the pages. You can locate these code lines by double-clicking the GroupedItemsPage.xaml.cs file. (You may need to open the hierarchy by clicking the arrow triangle on the left of the GroupedItemsPage.xaml file.) Scroll down to the lines that start with this.Frame.Navigate.

Figure 5-9: The content of the project folder in the Solution Explorer window

c05f009.tif
The data displayed in the application (the groups and the items) are hard-coded into the template, because the application doesn’t connect to any data source. You can view the hard-coded data by double-clicking the SampleDataSource.cs file within the DataModel folder in the Solution Explorer window, then scrolling down to the SampleDataSource class as shown in Figure 5-9.

Asynchronous Development Platform

Every year, client applications rely more and more heavily on data they download from the network. Because the amount of transferred data is increasing significantly, the latency of the network more often results in frozen applications that cause serious headaches not only for end users, but also for developers.

As the number of the connecting clients grows on the server side, the server should be able to scale and manage the increased workload. However, clients usually request data that the server must fetch from external services or databases before the requests can be processed. Even while the server is just waiting for the external data, its resources are allocated for the current request, which limits the scalability of the server.

A well-known programming practice, to solve both the UI responsiveness and the server scalability issues, is to design your software to do multiple things simultaneously. For example, while one part of your application is downloading data over the network (which can take a while), another part of your application can be responsible for reacting to mouse and keyboard events (which are generated by the user). If your application can handle these UI events, the user will feel that the application is working and responsive, and he or she will be satisfied, even if the network is slow. Otherwise, your program will appear to be frozen, which definitely ruins the user’s experience.

You have already seen several applications that follow this design. For example, you can browse your favorite website while you are copying files on your hard disk and listening to your favorite music in the background. To achieve this, the operating system is continuously switching over the running applications and giving them a very short time to execute. After this short time-slice has elapsed, the operating system switches to the next application, and lets it execute for the next time slice.

However, if you look under the covers, the operating system is switching not between applications, but between smaller units called threads. A thread is the smallest unit of processing that can be scheduled by the operating system. Every single application can create multiple threads and perform different tasks on them, and the operating system will take care of executing these threads simultaneously. This concept is called multithreading, and you enjoy its benefits when you browse multiple websites on multiple tabs within your web browser, or when you compose a new e-mail in your mailing program while the previous one is being sent in the background.

As you may guess, multithreaded applications are usually more user friendly than classic applications that do all their tasks on a single thread. However, creating multithreaded applications is not easy, and nowadays developers try to avoid these challenges in their code. As you see later in this chapter, the concurrent execution increases the complexity of your application, and makes your code less readable and less maintainable.

Introduction to Asynchronous Programming

You should write code in the same way that you think. When you are thinking logically, your brain creates a continuous series of thoughts that are tightly linked together. Thankfully, programming languages have a long history of supporting developers who express this way of thinking in programming logic — as a sequence of discrete steps that are executed one after the other. This is called synchronous programming, and because this is the simplest way of coding, most developers prefer to write synchronous code.

All programs consist of tasks, which are shorter or longer units of jobs that should be completed. As you can see in the synchronous programming model shown in Figure 5-10, when you arrange your tasks in a synchronous model, the next task can start only when the previous one is fully completed.

Figure 5-10: The synchronous programming model

c05f010.tif

Because the tasks are always completed in a definite order, the output of an earlier task is always available for the later one. In other words, the later tasks depend on the previous tasks.

Problems arise when a task takes too long to complete, because it performs a long-running computation-intensive operation, reads a large file from a slow disk, or connects to a server that has a slow response time. Because, by default, the operating system allocates a single thread to every process, that single thread will be busy waiting for the result of the long-running operation, and will not be able to respond to any (UI) events. In this case, the thread is blocked.

Although the program is actually running (that is, it is very busy doing nothing but waiting), the end user will feel that the program is frozen, which is a very poor user experience. In today’s world of smart mobile devices and touch-driven applications, your users are very sensitive to a rich user experience, and your application must be always responsive, independently of everything — the speed of the network, the disk, or the CPU. To achieve this ideal user experience, you must do your best to avoid blocked threads.

A natural solution to this problem is to move from the single-threaded synchronous model to the threaded model, which you can see in Figure 5-11.

Figure 5-11: The threaded synchronous model

c05f011.tif

In this model, each task is executed on a separate thread, and the underlying operating system takes care of executing them simultaneously. With this model, you can move the long-running task to a background thread and respond to the UI event in a UI thread to keep the application responsive. Because the operating system does the heavy lifting of managing the threads by allocating CPU time slices to them and switching between them, it seems to be a convenient solution, even if you have more threads than CPUs.

Still, it is not.

When you write a multithreaded application, you face some nasty problems. For example, if you have a data structure that is used by multiple threads, how can you ensure that the concurrent access is done safely? In other words, are you sure you can write thread-safe code? Do you know how to marshal data between threads, which means if you have a value on one thread, how can you pass it to another thread? Will the user be able to cancel the long-running process? Propagating an exception is another problem. If you have an error on a background thread, how can you forward it to the UI thread? How can the background thread signal progress to the user?

Although the problems represented by these questions can be properly solved, the solutions require a skilled programmer, and often result in the use of complex logic.

With a slightly simplified model, you can achieve very similar results and get rid of many of those questions. This requires the use of the asynchronous programming model shown in Figure 5-12.

Figure 5-12: The asynchronous programming model

c05f012.tif

In the asynchronous programming model, multiple tasks are executed on the same thread. However, the long tasks are divided into smaller units to make sure they don’t block the thread for a long time. This is a great difference compared to the synchronous model, in which the tasks are executed sequentially as single, complete units. In the synchronous model, the next task can start only after the previous one is completed. But in the asynchronous model, the next task can start as soon as the previous one yields execution to it. The second task does not have to wait until the first task fully completes.

For example, if the task is to download a file from a website, you can send the request (which is a quick operation), and then you can release the thread to respond to UI events. As shown in Figure 5-13, when the network card signals that the response has arrived from the server, you can then process the results. Although the tasks will not be completing faster with this model, your application will produce a much more pleasant user experience.

Figure 5-13: Downloading without blocking

c05f013.tif

Because your tasks are interleaved on a single thread, you have no more problems with thread safety, data marshaling, exception propagation, progress reporting, cancellation, and so on.

Unfortunately, the asynchronous model is still not perfect. The penalty is that after rewriting your synchronous code to the asynchronous model, you will hardly recognize it. It’s your duty to divide your tasks into smaller, non-blocking units, and make sure they release the thread when they no longer need it. This usually means writing code that starts a task, does something else, and then finally processes the results in a callback function. It takes a long time to implement, and the resulting code is difficult to read and difficult to maintain, because you completely lose the continuous flow of control.

The dilemma is obvious. Do you please the user with a responsive system, or do you please the developer with simple code that is joy to write? When you use .NET, you can do both.

Evolution of Asynchronous Programming on the .NET Platform

Since the first release of the .NET Framework, the platform has had built-in support for asynchronous programming. Throughout the numerous versions of the framework over the past ten years, multiple approaches have evolved, and now you have several design patterns you can use to create asynchronous logic in .NET.

With the first .NET Framework, you could use the Asynchronous Programming Model (APM). In the APM, asynchronous operations were implemented with two methods (BeginOperationName and EndOperationName) that started and completed the asynchronous operation (OperationName), respectively. You can see it in action in the following code snippet, which downloads a file asynchronously. (This code may be found in the NetFx NetFxAsyncHistoryAPMForm.cs downloadable code file.)

private void StartDownload( string url )
{
  HttpWebRequest req = (HttpWebRequest) WebRequest.Create( url );
  IAsyncResult result = req.BeginGetResponse( this.OnResponse, req );
}

private void OnResponse( IAsyncResult result )
{
  HttpWebRequest req = (HttpWebRequest) result.AsyncState;
  HttpWebResponse resp = (HttpWebResponse) req.EndGetResponse( result );
  Stream str = resp.GetResponseStream();
  // TODO: process the response stream here
}

The BeginGetResponse method was used to kick off the asynchronous download and to register a callback method to be called by the framework when the asynchronous operation was completed. The BeginGetResponse method returned an IAsyncResult instance that you could use to query the current state of the asynchronous operation. When the download was completed, the framework called the specified AsyncCallback callback, where you could call the EndGetResponse method to get the results and complete the download.

This was all you had in .NET 1.0, and, as you can see, it works, but requires a whole bunch of code. Besides, the APM does not support exception handling, cancellation, and progress-monitoring explicitly. These were all up to you to implement.

The second major version of the .NET Framework focused on the events and the delegates, and introduced the Event-based Asynchronous Pattern (EAP). The advantage of the EAP was that it was implemented with only a single method name (OperationNameAsync) for the asynchronous operation (OperationName). But before calling this method, you had to register the callback method that was called when the operation was completed.

The following code snippet shows how you could use the WebClient class that implemented EAP to download a string. (This code may be found in the NetFxNetFxAsyncHistoryEAPForm.cs downloadable code file.)

private void StartDownload( string url )
{
  WebClient wc = new WebClient();
  wc.DownloadStringCompleted += this.OnCompleted;
  wc.DownloadStringAsync( new Uri( url ) );
}

private void OnCompleted( object sender, 
  DownloadStringCompletedEventArgs e )
{
  string result = e.Result;
  // TODO: Process the string result here.
}

This is much less code and seems much cleaner, right? However, if you were to imagine a whole application built around these few lines of code, you would realize that it is very difficult to understand which code block runs when, even if they run on a single thread asynchronously. You can’t easily follow the path of execution, because your code reflects a totally mixed control flow. What’s more, if you rewrite this code with lambda expressions (that is, a new, compact language syntax introduced in C# 3.0), you get code in which you write down first what will be executed later. (This code may be found in the NetFxNetFxAsyncHistoryEAPForm.cs downloadable code file.)

WebClient wc = new WebClient();
wc.DownloadStringCompleted += ( s, args ) =>
{
  string result = args.Result;
  // TODO: Process the string result here.
};
wc.DownloadStringAsync( new Uri( url ) );

In this example you have only a single callback, but other classes (for example, the BackgroundWorker class) may require multiple callbacks, and when you review your code, the control flow will look completely inside out. And this is only a single operation. Things just get worse if you want to complete multiple tasks asynchronously. In addition, the exception-handling issue is not solved either, because how could you propagate an exception to the caller when that call is already returned?

To solve all these difficulties, the .NET Framework 4.0 introduced a completely new approach, named the Task-based Asynchronous Pattern (TAP). Before TAP, when developers wanted to solve a problem asynchronously, they had to figure out the path of execution, and as you saw previously, it resulted in callbacks and mixed flows of control. The primary goal of TAP is to make developers work with asynchronous code just as they do with synchronous code, and help them clearly see the flow of control.

To achieve this, a new set of classes called the Task Parallel Library (TPL) was added to .NET 4.0. The most important thing in the library is the Task class that gives developers the option to break with the “path of execution” way of thinking and focus on the “unit of work.” An instance of the Task class refers to a value that will be delivered at some point in the future. You don’t have to care about how and on which thread this value is computed. All you have to know is that it takes some time to deliver the result, and you can use the Task object to prevent the blocking of the current execution flow until the result arrives.

With the Task object, you can query the status of the asynchronous execution, wait for its completion, and get the result value. There is even a generic version of this class, Task<TResult>, that you can use to access the result of the asynchronous operation in a strongly typed way.

The following code snippet shows how you can use the Task class to download a web page. (This code may be found in the NetFxNetFxAsyncHistoryTAPForm.cs downloadable code file.)

Task.Factory.StartNew( () =>
{
  WebClient wc = new WebClient();
  string result = wc.DownloadString( url );
  // TODO: Process the string result here.
} );

With tasks, you can write asynchronous logic very similar to your earlier synchronous code. It’s no surprise that Microsoft favors this approach, and .NET 4.5 contains new methods that return Task instances directly. For example, the WebClient class has a new method called DownloadStringTaskAsync (the TaskAsync postfix is the naming convention for methods that return Task objects) that further simplifies your job, as shown here. (This code may be found in the NetFx NetFxAsyncHistoryTAPForm.cs downloadable code file.)

WebClient wc = new WebClient();
var task = wc.DownloadStringTaskAsync( url );
// TODO: Process the task.Result string here.

So far, you have seen several ways to execute code asynchronously, and all of them were provided by the .NET Framework Base Class Library. The benefit of this architecture is that these classes are available for all .NET languages. But because this makes the solution generic, you cannot fully utilize the productivity and cannot enjoy the comfort of your favorite programming language. On the other hand, a language-specific solution could be more convenient for the developers working with that language. However, it would be available only for them.

Microsoft has experience in this area, because it used a similar approach with Language Integrated Query (LINQ) in .NET 3.0. LINQ relies heavily on a set of extension methods that do the heavy lifting on IEnumerable instances, but the language syntax in C# makes the usage of them much cleaner, and results in more readable code. Because this solution has proven advantages, Microsoft did the same again, and as you see later in this chapter, direct language support was added for tasks in C# 5.0. With the new language syntax, you will never write another callback.


NOTE The code snippets in this chapter show how you can initiate and complete an asynchronous operation, but don’t deal with the details of processing the result. That alone can be complex in desktop applications. There is one important rule you should keep in mind when you create a graphical user interface (GUI) application with asynchronous logic: code running on a background thread must not touch the UI directly! For example, this means that you cannot display a value in a window directly from an asynchronous callback. Check the companion code for this chapter available for download from www.wrox.com to see an example of how to solve this issue with the Invoke method in Windows Forms applications.

Asynchronous Programming with C# 5.0

In C# 5.0, Microsoft further simplified asynchronous programming by adding two new keywords to the language. The new keywords were inspired by the await/async pattern in F#, and they unquestionably make your code much cleaner. However, you will definitely need some time to fully understand how they work. But after you become familiar with the new syntax, asynchronous programming turns into a joy!

The two new keywords are the async modifier and the await operator. When you use them, always keep in mind that their primary goal is to cut down the syntactical burden you face with when you use the Task class, just like LINQ does with the select keyword and the extension methods on IEnumerables. With the new keywords, you can transfer to the compiler the mechanical job of turning a synchronous method to asynchronous logic.

Let’s take a look at them in more detail with the help of a short example. The following code snippet shows a synchronous method that contains a WebClient.DownloadString call, which may take a long time to execute. (This code may be found in the CS5CS5AsyncForm1.cs downloadable code file.)

private void DownloadSync( string url )
{
  WebClient wc = new WebClient();
  string result = wc.DownloadString( url );
  this.txtStatus.Text = result;
}

You can convert this code to an asynchronous method by using the new keywords:

private async void DownloadAsync( string url )
{
  WebClient wc = new WebClient();
  string result = await wc.DownloadStringTaskAsync( url );
  this.txtStatus.Text = result;
}

The boldface code indicates the changed parts of the code. First you use the async modifier on a method or a lambda expression to indicate to the compiler that the code block is asynchronous. The method that is marked with the async modifier is referred to as an async method.

Second, within the async method, you probably have multiple lines of code, but at some point, the execution reaches an operation or function call that takes a long time to execute. This is the point where you really want asynchrony to avoid blocking the current thread.


NOTE Traditionally, you would subscribe to a completion event with a callback handler here, and return the control to the caller. The await operator does this. If you apply the await operator to the long-running function call within an asynchronous method, it instructs the compiler to subscribe the rest of this method as the continuation handler of that task, and then returns to the caller immediately. When the task completes, the task invokes the continuation, which runs in the synchronization context of the caller.

Note that the asynchronous methods are for managing asynchrony, and not for creating asynchrony. Asynchronous methods don’t start new threads; instead, they use the well-known callbacks under the hood, but they spare you from the mechanics of creating them. In fact, the compiler does the heavy lifting by generating the code that fully manages the control flow. To make it work, the awaited operation must return a void, a Task, or a Task<T> instance. This looks like a serious restriction at first, but you will realize in practice that it fully serves your needs and helps standardize your code.

In the next “Try It Out” exercise, you create a classic Windows Forms application that downloads content from the network, while keeping the UI responsive using the new async and await keywords in C#.


Getting C# 5.0
To work with the new C# language elements, you need a version of the C# compiler that understands them. If you have Visual Studio 2012 and .NET Framework 4.5, you are ready to go, because they come with C# 5.0. However, you can try the new syntax even if you have only Visual Studio 2010 by installing the Visual Studio Async Community Technology Preview (CTP) available at http://msdn.microsoft.com/en-us/vstudio/gc31uf06360. The Async CTP is essentially a minor patch to Visual Studio that upgrades the C# compiler and code editor to understand the async and await keywords. As of this writing, Version 3 is available, which is compatible with Visual Studio Express, Silverlight 5, Windows Phone SDK 7.1, and the Roslyn CTP.


NOTE You can find the complete code to download for this exercise on this book’s companion website at www.wrox.com in the folder CS5TryItOut within the Chapter05.zip download.


Try It Out: Writing Synchronous Code
To create a desktop application that becomes unresponsive during long operations, follow these steps:
1. Start Visual Studio and create a new Windows Forms Application project.

Figure 5-14: The layout of the controls in the designer

c05f014.tif
2. Open Form1 in the designer and drop a TextBox and a Button onto it from the Common Controls section of the Toolbox. You will use the button to start a long-running operation, and the text box to display messages about the current status of the operation.
3. Open the Properties window, and, for the Name property of the TextBox, enter txtStatus, and for the Name property of the Button, enter btnStart. In the Text property for the Button, enter Start. Change the Multiline property of the text box to true and arrange the controls as shown in Figure 5-14.
4. Double-click the Start button to switch to code view and generate an event-handler stub for it.
5. To make your later code more readable, create the following short method, which adds the specified message to the text box in a new line, to the Form1 class:
private void Write( string message )
{
  this.txtStatus.Text += message + "
";
}
6. Enter the following code to use the new Write method to display some status messages when the application is started and when the event handler is running. This code also changes the mouse cursor to indicate that the application is busy.
public Form1()
{
  InitializeComponent();
  Write( "Ready." );
}

private void btnStart_Click( object sender, EventArgs e )
{
  this.Cursor = Cursors.WaitCursor;
  Write( "Click event handler started." );
  // TODO: The real work comes here...
  Write( "Click event handler ended." );
  this.Cursor = Cursors.Default;
}

Figure 5-15: Displaying the default messages

c05f015.tif
7. Compile and start the application to test that the messages are displayed when you click the Start button, as shown in Figure 5-15.
8. Enter the following code to create the DoWork method after the btnStart_Click method that runs the long-running operation. This method downloads a page from the Internet and returns its length.
private int DoWork()
{
  string result = new WebClient().DownloadString( 
    "http://gyorgybalassy.wordpress.com" );
  return result.Length;
}
To make this code compile, you must add the following using directive to the top of the file:
using System.Net;
9. Replace the TODO comment you entered in Step 6 in the btnStart_Click event handler with the following lines of code, which starts the download and displays the results:
int length = DoWork();
Write( "Download completed. Downloaded bytes: " + length.ToString() );
At this point, your code should look like this:
using System;
using System.Net;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
      Write( "Ready." );
    }

    private void btnStart_Click( object sender, EventArgs e )
    {
      this.Cursor = Cursors.WaitCursor;
      Write( "Click event handler started." );
      int length = DoWork();
      Write( "Download completed. Downloaded bytes: " + length.ToString() );
      Write( "Click event handler ended." );
      this.Cursor = Cursors.Default;
    }

    private int DoWork()
    {
      string result = new WebClient().DownloadString( 
        "http://gyorgybalassy.wordpress.com" );
      return result.Length;
    }

    private void Write( string message )
    {
      this.txtStatus.Text += message + "
";
    }
  }
}

Figure 5-16: Synchronous execution

c05f016.tif
10. Compile and start the application. Click the Start button, and notice that you must wait about 3 seconds before the messages shown in Figure 5-16 are displayed.
How It Works
This code shows you a classic synchronous implementation of downloading content from a network.
The Button on the user interface you created in Step 2 is used to start the download, and the multiline TextBox is used to provide some feedback for you to know what is currently happening.
The Write method you created in Step 5 is a helper method that simplifies adding new lines of messages to the status text box. The string in the Write method takes care of writing the messages in new lines.
When the application starts, the “Ready” message is displayed, and the program is waiting for user actions. When the user clicks the Start button, the btnStart_Click event handler you created in Step 6 is executed, which changes the mouse cursor and displays the “Click event handler started” status message. After that, the DoWork method you created in Step 8 is called, which is the essence of the application because it is performing the download operation by using the DownloadString method of the WebClient class. Note that this is a synchronous method, which blocks the execution until the desired content is fully downloaded from the Internet. While this method is blocking the thread, the application cannot process other UI events, and the window becomes unresponsive.
To keep the example simple, only the length of the downloaded content is returned from the DoWork method and then displayed by the remaining part of the click event handler.

The code you now have as a result of this “Try It Out” exercise is completely synchronous, and the DownloadString call blocks the thread until the content is fully downloaded. Because the call is on the UI thread, the application is totally unresponsive. Notice that you can’t even move or close the window during the download.

The next exercise walks you through how to solve this problem.


NOTE You can find the complete code to download for this exercise on this book’s companion website at www.wrox.com in the folder CS5TryItOut within the Chapter05.zip download.


Try It Out: Using Asynchronous Callbacks
To solve the thread-blocking problem with asynchronous callbacks, follow these steps:
1. Using the final code from the previous “Try It Out” exercise, you will now use the asynchronous version of the DownloadString method. Replace the previous DoWork method from Step 8 of the previous exercise with the following two methods:
private void DoWork()
{
  Write( "DoWork started." );

  WebClient wc = new WebClient();
  wc.DownloadStringCompleted += OnDownloadCompleted;
  wc.DownloadStringAsync( new Uri( "http://gyorgybalassy.wordpress.com" ) );

  Write( "DoWork ended." );
}

private void OnDownloadCompleted( object sender, 
  DownloadStringCompletedEventArgs e )
{
  Write( "Download completed. Downloaded bytes: " + e.Result.Length.ToString() );
}
In this case, you first subscribe to the DownloadStringCompleted event of the WebClient instance with the OnDownloadCompleted event handler, and then start the download asynchronously.
2. Because, in this case, the callback is responsible for displaying the result length on the UI, simplify the method call in the btnStart_Click event handler to this:
DoWork();
At this point your code should look like this:
using System;
using System.Net;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
      Write( "Ready." );
    }

    private void btnStart_Click( object sender, EventArgs e )
    {
      this.Cursor = Cursors.WaitCursor;
      Write( "Click event handler started." );
      DoWork();
      Write( "Click event handler ended." );
      this.Cursor = Cursors.Default;
    }

    private void DoWork()
    {
      Write( "DoWork started." );

      WebClient wc = new WebClient();
      wc.DownloadStringCompleted += OnDownloadCompleted;
      wc.DownloadStringAsync( new Uri( 
        "http://gyorgybalassy.wordpress.com" ) );

      Write( "DoWork ended." );
    }

    private void OnDownloadCompleted( object sender, 
      DownloadStringCompletedEventArgs e )
    {
      Write( "Download completed. Downloaded bytes: " + 
        e.Result.Length.ToString() );
    }

     private void Write( string message )
     {
      this.txtStatus.Text += message + "
";
    }
  }
}

Figure 5-17: Asynchronous execution

c05f017.tif
3. Compile and test your application. Notice that now you can barely see the mouse wait cursor, and the “started” and “ended” messages are displayed almost instantly. The application remains responsive in spite of the fact that the “Download completed” result message is displayed a few seconds later, as you can see in Figure 5-17.
How It Works
The DownloadStringAsync method you entered in Step 1 initiates the download on a background thread, then immediately returns. Because it doesn’t block the UI thread, the rest of the DoWork method and the button event handler can execute. Because the button event handler returns very quickly, the message loop of the application can continue, and the application can respond to further UI messages.
The OnDownloadCompleted method you entered in Step 1 is a callback method that is called when the WebClient object has fully downloaded the content from the given URL. But, before the download is started asynchronously, you must specify which method serves as the callback, and you do that by subscribing to the DownloadStringCompleted event in the following line:
wc.DownloadStringCompleted += OnDownloadCompleted;
When the OnDownloadCompleted callback method is called, it gets the result of the download in the Result property of the e parameter, whose length is then displayed on the UI using the Write method.

The problem with this approach is that your code doesn’t reflect the flow of control. Your click action triggers an event handler that calls a method, then both the method and the handler return. However, the job is not yet completed, because, at some point in the future, the callback will finish it by displaying the results to the user.

Before reading any further, take a moment to think about how you would change your code if you had to download content from another URL if the first download fails, or the result is too small. Yes, you would probably need another callback.


NOTE You can find the complete code to download for this exercise on this book’s companion website at www.wrox.com in the folder CS5TryItOut within the Chapter05.zip download.


Try It Out: Working with the New Asynchronous Keywords in C#
To use new async and await keywords in C#, follow these steps:
1. Locate the DoWork method you entered in the previous “Try It Out” exercise, and replace it with the following code that uses the new async and await keywords:
private async void DoWork()
{
  Write( "DoWork started." );

  WebClient wc = new WebClient();
  string result = await wc.DownloadStringTaskAsync( 
    new Uri( "http://gyorgybalassy.wordpress.com" ) );
  Write( "Download completed. Downloaded bytes: " + result.Length.ToString() );

  Write( "DoWork ended." );
}

NOTE Note that if you use the Visual Studio Async CTP with Visual Studio 2010, you must add a reference to the AsyncCTPLibrary.dll file or your code won’t compile. To add a reference, right-click the References branch in the Solution Explorer window, and then click Add Reference to open the Add Reference dialog box. Click the Browse button and select the AsyncCTPLibrary.dll from the folder where you earlier installed the Visual Studio Async Community Technology Preview.

Figure 5-18: The control flow with an asynchronous method

c05f018.tif
2. Build and test your application. You should see the result shown in Figure 5-18.
3. To further simplify your code, you can even turn the btnStart_Click event handler you created in the previous “Try It Out” exercise to an asynchronous method by using the async and await keywords directly in it.
private async void btnStart_Click( object sender, EventArgs e )
{
  this.Cursor = Cursors.WaitCursor;
  Write( "Click event handler started." );

  WebClient wc = new WebClient();
  string result = await wc.DownloadStringTaskAsync( 
    new Uri( "http://gyorgybalassy.wordpress.com" ) );
  Write( "Download completed. Downloaded bytes: " + result.Length.ToString() );

  Write( "Click event handler ended." );
  this.Cursor = Cursors.Default;
}
4. With the new syntax, it is very easy to examine the results and add a fallback download to your code. You do this the same as you would do with synchronous code, right after the previous download, as shown here:
private async void btnStart_Click( object sender, EventArgs e )
{
  this.Cursor = Cursors.WaitCursor;
  Write( "Click event handler started." );

  WebClient wc = new WebClient();
  string result = await wc.DownloadStringTaskAsync( 
    new Uri( "http://gyorgybalassy.wordpress.com" ) );
  if( result.Length < 100000 )
  {
    Write( "The result is too small, download started from second URL." );
    result = await wc.DownloadStringTaskAsync( 
      new Uri( "https://www.facebook.com/balassy" ) );
  }
  Write( "Download completed. Downloaded bytes: " + result.Length.ToString() );

  Write( "Click event handler ended." );
  this.Cursor = Cursors.Default;
}
How It Works

Figure 5-19: The control flow with an asynchronous event handler

c05f019.tif
After modifying the application in Step 1, and then building and testing the application in Step 2, you can see from the output shown in Figure 5-18 that the control flow is totally different at this time. The DoWork method is started, but when the execution reaches the awaited method, the control is returned to the caller, and the event handler completes. When the awaited method is ready to return its result, the execution is continued with the remaining part of the asynchronous method. The code looks entirely synchronous, because the magic with the callbacks is done fully by the compiler.
In Step 3, you learned how you can get rid of the DoWork method while keeping the same behavior, as shown in Figure 5-19.

Now that you are familiar with the new keywords available in C# 5.0, let’s take a look at how to implement cancellation in C# 5.0.


NOTE You can find the complete code to download for this exercise on this book’s companion website at www.wrox.com in the folder CS5TryItOut within the Chapter05.zip download.


Try It Out: Implementing Cancellation in C# 5.0
To cancel a long-running asynchronous operation using C# 5.0, follow these steps:
1. To support cancellation on the UI, drop a Button control onto Form1 from the Toolbox. For its Name property, enter btnCancel, and for its Text property, enter Cancel. Double-click the Cancel button in the designer to generate an empty btnCancel_Click event-handler method.
2. The preferred pattern to implement cancellation relies on a lightweight object called a cancellation token. Enter the following code to add a CancellationTokenSource object to the Form1 class that you will use later to signal the cancellation to the long-running operation:
private CancellationTokenSource cts;
3. Now you can implement the event handler of the Cancel button you generated in Step 1 to signal the cancellation by entering the following code:
private void btnCancel_Click( object sender, EventArgs e )
{
  Write( "Cancellation started." );
  this.cts.Cancel();
  Write( "Cancellation ended." );
}
4. In the previous “Try It Out” exercise, you already used the DownloadStringTaskAsync method in the btnStart_Click event handler. This method supports cancellation if you supply a cancellation token in its second parameter:
cts = new CancellationTokenSource();
WebClient wc = new WebClient();
string result = await wc.DownloadStringTaskAsync( 
  new Uri( "http://gyorgybalassy.wordpress.com" ), cts.Token );
At this point your code should look like this:
using System;
using System.Net;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
  public partial class Form1 : Form
  {
    private CancellationTokenSource cts;
     
    public Form1()
    {
      InitializeComponent();
      Write( "Ready." );
    }
          
    private async void btnStart_Click( object sender, EventArgs e )
    {
      this.Cursor = Cursors.WaitCursor;
      Write( "Click event handler started." );
  
      cts = new CancellationTokenSource();
      WebClient wc = new WebClient();
      string result = await wc.DownloadStringTaskAsync( 
        new Uri( "http://gyorgybalassy.wordpress.com" ), cts.Token );
      if( result.Length < 100000 )
      {
        Write( "The result is too small, download started from second URL." );
        result = await wc.DownloadStringTaskAsync( 
          new Uri( "https://www.facebook.com/balassy" ) );
      }
      Write( "Download completed. Downloaded bytes: " + result.Length.ToString() );

      Write( "Click event handler ended." );
      this.Cursor = Cursors.Default;
    }
          
    private void btnCancel_Click( object sender, EventArgs e )
    {
      Write( "Cancellation started." );
      this.cts.Cancel();
      Write( "Cancellation ended." );
    }
                    
     private void Write( string message )
     {
       this.txtStatus.Text += message + "
";
     }     
  }
}
5. Compile and test your application by starting and immediately cancelling the download. Notice that the exception shown in Figure 5-20 is thrown.

Figure 5-20: A TaskCanceledException is thrown

c05f020.tif
6. To make your code failsafe, you should wrap the awaited method within the btnStart_Click event handler in a try-catch block:
try
{
  string result = await wc.DownloadStringTaskAsync( 
    new Uri( "http://gyorgybalassy.wordpress.com" ), cts.Token );
  Write( "Download completed. Downloaded bytes: " + result.Length.ToString() );
}
catch( TaskCanceledException )
{
  Write( "Download cancelled." );
}

Figure 5-21: Download with cancel

c05f021.tif
7. Run this code and note that the download is gracefully cancelled this time, as shown in Figure 5-21.
8. You can even use the cancellation mechanism to implement a timeout. For this, you must call the CancelAfter method of the CancellationTokenSource before the asynchronous operation is kicked off with the DownloadStringTaskAsync method call within the try block you created in Step 6:
cts = new CancellationTokenSource();

WebClient wc = new WebClient();
try
{
  cts.CancelAfter( 100 );
  string result = await wc.DownloadStringTaskAsync( 
    new Uri( "http://gyorgybalassy.wordpress.com" ), cts.Token );
  Write( "Download completed. Downloaded bytes: " + result.Length.ToString() );
}
catch( TaskCanceledException ex )
{
  Write( "Download cancelled." );
}
How It Works
The CancellationTokenSource you created in Step 2 is the standard way of implementing cancellation in .NET. When the event handler of the Cancel button you created in Step 3 calls the Cancel method of the CancellationTokenSource, it sets an internal flag that indicates to that asynchronous task that a cancellation is requested. To associate the current cancellation token instance with the current asynchronous method, you pass it as a method parameter to the DownloadStringTaskAsync method in Step 4.
Internally, the DownloadStringTaskAsync method periodically checks the token, and if a cancellation was requested, it then aborts the download. For some reason, the creators of the .NET Framework decided that cancellation is an exceptional operation. Therefore, it always raises a TaskCanceledException, which you can handle gracefully with the try-catch block you added in Step 6. Without this wrapping, the exception would crash the application.
In Step 8, you saw another usage of the CancellationTokenSource object for implementing timeouts. Internally, this code initializes a System.Threading.Timer object with the specified timeout. When the timer fires, it calls the Cancel method of the CancellationTokenSource object. Because this is actually a cancellation, the same TaskCanceledException is thrown, and it’s up to you to detect that a timeout or a user-initiated cancellation has happened.

At this point, you have learned how to create user-friendly applications with asynchronous logic. In the next section, you apply this knowledge to Windows 8 and Windows Runtime.

Asynchronous Development on Windows Runtime

In Windows 8, Windows Runtime gave Microsoft the opportunity to completely redesign the application programming interfaces (APIs) of Windows. Now history repeats itself, because the same thing happened when Microsoft started working on the .NET Framework more than ten years ago. At that time, one of the original goals was to create an advanced, object-oriented API on top of the low-level Win32 functions that you can access easily from any .NET language. This goal was reached. However, the challenges have recently changed.

As you learned earlier in this chapter, asynchronous programming became more and more important during the evolution of rich, interactive UIs. The .NET Framework continuously adapts to this new challenge by providing newer and newer methods to support the asynchronous approach. Although the architects of the .NET Framework at Microsoft do their best to offer more and more simple syntax for creating asynchronous logic, .NET developers remain the same. Microsoft realized that if a developer is given a choice of a synchronous versus an asynchronous API, most developers choose the synchronous one because of its simplicity. Even if there is a clean syntax for asynchronous methods, the synchronous logic is easier to understand.

Microsoft kept this in mind when it designed Windows Runtime, and followed a simple rule: If an API is expected to run more than 50 milliseconds, the API is asynchronous. This means that there is no way to call it synchronously. You must go the asynchronous path, whether you like it or not. The idea behind this serious decision is to ensure that Windows 8 style applications always respond to user input, and never provide a poor user experience.


NOTE You will find asynchronous-only APIs in various parts of Windows Runtime, especially when you are doing a filesystem or a network operation. According to Microsoft, about 15 percent of the full Windows Runtime is an asynchronous-only API. If you have already done some Silverlight or Windows Phone development, you will hardly notice them, because those platforms follow similar rules for network access.

In the next exercise, you learn how to use the new asynchronous file-open dialog box called the File Open Picker.


NOTE You can find the complete code to download for this exercise on this book’s companion website at www.wrox.com in the folder WinRTTryItOut within the Chapter05.zip download.


Try It Out: Using the File Open Picker
Before starting this exercise, ensure that you have JPG image files in your My Pictures folder. You can copy some from the C:WindowsWebWallpaper folder to the My Pictures folder so that your application will be able select them.
To try the new File Open Picker, follow these steps:
1. Start Visual Studio 2012 by clicking its icon on the Start screen.
2. Select File &menuarrow; New Project (or press Ctrl+Shift+N) to display the New Project dialog box.
3. Select the Installed &menuarrow; Templates &menuarrow; Visual C# &menuarrow; Windows Store category from the left tree, and then select the Blank Application project type in the middle pane, as shown in Figure 5-22.

Figure 5-22: The New Project dialog box

c05f022.tif
4. Click OK. Visual Studio creates an empty project skeleton and opens the main App.xaml.cs file in the code editor.
5. Open the Solution Explorer window by clicking the View &menuarrow; Solution Explorer menu item (or by pressing Ctrl+Alt+L).
6. Double-click the MainPage.xaml file to open it in the designer. Note the notification in the middle of the design pane, which indicates that the designer is still loading. Be patient while the designer completely loads and the image of the UI of your application is displayed.
7. Open the Toolbox window by clicking the View &menuarrow; Toolbox menu item (or by pressing Ctrl+Alt+X).
8. Open the Common XAML Controls section in the Toolbox, and then drag and drop a Button control onto the design surface.
9. Double-click the button on the designer surface to generate the event-handler method that is called when the user clicks the button. Visual Studio switches to code view in the MainPage.xaml.cs file, and you can see the newly generated Button_Click_1 event handler.
10. Scroll to the top of the file and add the following using statements:
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.UI.Popups;
11. Scroll down to the Button_Click_1 method and add the async modifier to its signature. Then add the following lines of code to the body of the method:
FileOpenPicker picker = new FileOpenPicker
{
  ViewMode = PickerViewMode.Thumbnail,
  SuggestedStartLocation = PickerLocationId.PicturesLibrary,
};
picker.FileTypeFilter.Add(".jpg");
StorageFile file = await picker.PickSingleFileAsync();
MessageDialog dlg = new MessageDialog(
  "Selected: " + file.Path, "Selection completed");
await dlg.ShowAsync();
At this point, your method should look like this:
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
  FileOpenPicker picker = new FileOpenPicker
  {
    ViewMode = PickerViewMode.Thumbnail,
    SuggestedStartLocation = PickerLocationId.PicturesLibrary,
  };
  picker.FileTypeFilter.Add(".jpg");
  StorageFile file = await picker.PickSingleFileAsync();
  MessageDialog dlg = new MessageDialog(
    "Selected: " + file.Path, "Selection completed");
await dlg.ShowAsync();
}
12. Start the application by clicking the Debug &menuarrow; Start Without Debugging menu item. Visual Studio compiles and starts the application.
13. Click your only button in the application to open the file picker. Select any image file, and then click the Open button. The file picker closes, and the full path of the selected file is displayed in a pop-up dialog box.
How It Works
In this exercise, you created a Windows 8 style application that allows the user to select an image file from his or her My Pictures folder.
In Steps 8 and 9, you added a button control onto the main page of your application, and generated the method that is called by Windows when the user clicks the button.
You can use the Windows.Storage.Pickers.FileOpenPicker class to display the standard Windows 8 style file selection UI to your user. Because its namespace is not included in the source file by default, you added it in Step 10. In this step, you also added two other namespaces that are used in your code.
In Step 11, you added the code that first shows the file picker, and then displays the full path of the selected file in a pop-up dialog box. In the first two statements, you configured the file picker to start in the My Pictures folder of the user, show only JPEG files, and display these files as thumbnails.
The PickSingleFileAsync method displays the file picker. Note that its name ends with Async, which means that it is an asynchronous method. Therefore, you must add the await keyword before the call, and the async keyword to the signature of the hosting function.
The result of the operation is a Windows.Storage.StorageFile object that describes the selected file. Its Path property contains the full path of the selected file, and that is what you display in the pop-up dialog box.
You use the Windows.UI.Popups.MessageDialog class to display a new Windows 8 style pop-up dialog box to the user. Note that the ShowAsync method that you use to accomplish this is also asynchronous, which is why you must use the await keyword before it.

The return value of the PickSingleFileAsync method is of type PickSingleFileOperation that implements the IAsyncOperation<StorageFile> interface. This interface is one the most important interfaces in Windows Runtime because it is the standard for asynchronous APIs, and you will use it very frequently.

Earlier in this chapter, you learned about the Task and Task<T> types in the .NET Framework that refer to a value that will be delivered at some point in the future. Windows Runtime and .NET are very close to each other, but Windows Runtime is not equal to the .NET Framework, and its features must be available for other languages that cannot access the .NET Framework (such as JavaScript) as well.

To abstract the differences, Windows Runtime provides its own future type in the form of the IAsyncOperation interface. All asynchronous APIs in Windows Runtime return an IAsyncOperation or IAsyncOperation<T> object, and you can use its Completed property to set a callback method that is called when the asynchronous operation is completed, and its GetResults method to return the result in the form of an object of type T.

If you recall in an earlier “Try It Out” exercise, there was no IAsyncOperation<StorageFile> in the code. Instead, the PickSingleFileAsync method directly returned a StorageFile object. That’s part of the magic the await keyword does. It not only takes care of the asynchronous execution, but also unwraps the result and returns the raw result object without the packaging.

Because the IAsyncOperation is provided not by the .NET Framework but rather Windows Runtime, you can utilize its power even if you write a Windows 8 style application in JavaScript.

Asynchronous Programming with JavaScript Promises

Earlier in this chapter, you learned how Microsoft made the asynchronous coding patterns first-class citizens in its developer technologies — in the .NET Framework, in C#, and in Windows Runtime. However, Windows Runtime is open for developers who have a web development background, and directly supports JavaScript as well. In this section, you learn how you can apply asynchronous patterns in JavaScript, using a new concept called promises.

JavaScript is a single-threaded language, which means that any long-running or waiting operation that blocks this single thread can make your application look frozen. It’s been a known behavior for a long time in the web world, and it’s no surprise that most of these long-running operations (typically network calls) are implemented using callbacks. However, as you saw earlier in this chapter, callbacks often result in complicated code that is difficult to maintain.

Windows Runtime implements the Common JS Promises/A proposal to overcome these problems. A promise is a JavaScript object that returns a value at some time in the future, just like tasks in C#. All asynchronous Windows Runtime APIs that are exposed to Windows 8 style applications are wrapped in promise objects, so you can work with them in a natural way in JavaScript.

The most frequently used method on a promise object is the then function, which takes three parameters:

then( fulfilledHandler, errorHandler, progressHandler )
  • In the fulfilledHandler parameter, you can specify a callback method that is called when the promise completes successfully, or, in other words, is fulfilled.
  • In the errorHandler parameter, you can optionally specify a callback method that is called when the promise completes with an error.
  • In the progressHandler parameter, you can optionally specify a callback that is called when the promise object provides progress information. Note that not all promise objects can signal progress.

NOTE You can read the original Promises/A proposal at http://wiki.commonjs.org/wiki/Promises/A.

Now that you understand the basic concepts of promises, you can use them in practice. In the next exercise, you create a Windows 8 style application in JavaScript that uses promises to asynchronously search for content on Twitter.


NOTE You can find the complete code to download for this exercise on this book’s companion website at www.wrox.com in the folder JSTryItOut within the Chapter05.zip download.


Try It Out: Creating a Simple Twitter Client with JavaScript Promises
To create a Windows 8 style application in JavaScript, follow these steps:
1. Start Visual Studio 2012 by clicking its icon on the Start screen.
2. Select File &menuarrow; New Project (or press Ctrl+Shift+N) to display the New Project dialog box.
3. Select the Installed &menuarrow; Templates &menuarrow; JavaScript &menuarrow; Windows Store category from the left tree, and then select the Blank App project type in the middle pane, as shown in Figure 5-23.

Figure 5-23: The New Project dialog box

c05f023.tif
4. Click OK. Visual Studio creates an empty project skeleton and opens the main default.js file in the code editor.
5. Start the application by clicking the Debug &menuarrow; Start Without Debugging menu item. Visual Studio compiles and starts the application, and you will have your first JavaScript Windows 8 style application running. You can see that, as its name implies, the application is really blank. It displays only the “Content goes here” text on its surface.
6. Exit the application by pressing ALT+F4, or using the close gesture if you are using a device that supports touch gestures.
7. Return to Visual Studio, and open the Solution Explorer window by selecting the View &menuarrow; Solution Explorer menu item (or by pressing Ctrl+Alt+L).
8. In the Solution Explorer window, you can see the three main files for the application:
  • The default.html file contains the markup that describes the user interface of your application.
  • The default.css file in the css folder defines the look and feel of your application.
  • The default.js file in the js folder contains your application logic.
9. Double-click the default.html file to open it in the code editor. Find the <body> and </body> tags in the code, and replace that content with the following:
<p>Enter a keyword to search for on Twitter:</p>
<div>
  <input type="text" id="txtKeyword" value="Budapest" />
  <button id="btnSearch">Search</button>
</div>
<div id="divStatus">Ready.</div>
<div id="divResult"></div>
10. Double-click the default.css file within the css folder in the Solution Explorer to open it in the code editor. Find the body{ } section at the top of the file, and replace it with the following content:
body { padding: 30px; }
#txtKeyword { width: 500px; }
#divStatus { padding: 10px; }
#divResult { padding: 10px; margin-top: 10px; line-height: 2em; }
11. Double-click the default.js file within the js folder in the Solution Explorer to open it in the code editor. Find the if block within the app.onactivated event-handler function with the “Initialize your application here” comment. Add the following code into it:
var btnSearch = document.getElementById("btnSearch");
btnSearch.addEventListener("click", onSearchButtonClicked);
12. Append the following function code block to the end of the default.js file:
function onSearchButtonClicked(e) {
  var txtKeyword = document.getElementById("txtKeyword");
  var divStatus = document.getElementById("divStatus");
  var divResult = document.getElementById("divResult");

  var url = "http://search.twitter.com/search.json?q=" + txtKeyword.value;

  WinJS.xhr({ url: url })
    .then(
      function complete(result) {
        divStatus.style.backgroundColor = "lightGreen";
        divStatus.innerHTML = "Downloading " + result.response.length + 
                              " bytes completed. <br />";

        var hits = JSON.parse(result.responseText).results;

        for (var i = 0; i < hits.length; i++) {
          divResult.innerHTML += hits[i].text + "<br/>";
        }
      },

      function error(e) {
        divStatus.style.backgroundColor = "red";
        divStatus.innerHTML = "Houston, we have a problem!";
      },

      function progress(result) {
        divStatus.style.backgroundColor = "blue";
        divStatus.innerHTML = "Downloaded " + result.response.length + 
             " bytes. <br />";
      }
    );
  }
13. Start the application by clicking the Debug &menuarrow; Start Debugging menu item (or by pressing F5).
14. Enter any keyword (or accept the default keyword) and click the Search button. The results should resemble those shown in Figure 5-24.

Figure 5-24: The Twitter search application in action

c05f024.tif
How It Works
According to the project template you selected, Visual Studio generated an empty skeleton that contains everything you need to start creating your Windows 8 style application in JavaScript. You reviewed the generated template code in Step 7 and Step 8.
In Step 9, you created the markup that describes the structure of your application page. It contains two input controls, a text field named txtKeyword, and a button named btnSearch. The markup also contains two div elements (divStatus and divResult) that act as placeholders for the output. Note that the id attribute contains the names of the elements that you can use to refer to them in your application code and in style sheets.
In Step 10, you used cascading style sheets (CSS) to define the look and feel of your UI elements.
In the next steps, you added the logic to your application. In Step 11, you subscribed to the click event of the search button with the onSearchButtonClicked event handler. This function is called when the user clicks the Search button. You added this event-handler function in Step 12.
The onSearchButtonClicked event handler you added in Step 12 sends an asynchronous search request to Twitter, and displays the results. In the first three lines of the function, you created shortcut variables for the UI elements. In the fourth line, you built the URL for Twitter search from the keyword the user entered into the text input field.
The WinJS.xhr method is one of the most important functions when creating a Windows 8 style application in JavaScript, because it enables you to communicate asynchronously over the network using promises. The WinJS.xhr function returns a promise object, and you can call its then method to specify the complete, the error, and the progress callbacks. These callbacks are specified as three function type parameters for the then function. Note that you don’t have to name these functions; names are used here only for making the code more readable.
The first callback (complete) is called when the asynchronous download successfully completes. In the first two lines, you set a friendly light green background color and a status message for the user. Then you parsed the text data that was returned by Twitter to a hits object, which is an array that contains the result hits. Then, with the for loop, you iterated through the results, and added them one by one to the results pane.
The second callback (error) is called when the asynchronous download completes with an error. If you want to test it, enter a single apostrophe (') into the search input field and click the Search button. This error handler displays a constant error message on a red background.
The third callback (progress) is called when the WinJS.xhr function reports progress. This function displays the number of downloaded bytes in the status pane with a blue background. On most networks, the download is really fast, so you must really open your eyes to catch it. If you blink, you’ll miss it.

If you have tested the application without attaching the debugger (by using the Debug &menuarrow; Start Without Debugging menu item, or by pressing Ctrl+F5), you have probably realized that sometimes the Search button doesn’t work. The root cause is that the event subscription code is not perfect, but now that you have learned how promises work, you can fix it in the next exercise.


NOTE You can find the complete code to download for this exercise on this book’s companion website at www.wrox.com in the folder JSPromisesTryItOut within the Chapter05.zip download.


Try It Out: Using Promises at Application Initialization
To optimize the application initialization code, follow these steps:
1. Open the default.js file in the code editor and delete the following code that you added in the previous “Try It Out” exercise:
var btnSearch = document.getElementById("btnSearch");
btnSearch.addEventListener("click", onSearchButtonClicked);
2. Find the code line that starts with args.setPromise in the app.onactivated function and change it to the following:
args.setPromise(WinJS.UI.processAll().then(function () {
  var btnSearch = document.getElementById("btnSearch");
  btnSearch.addEventListener("click", onSearchButtonClicked);
}));
3. Start the application without attaching the debugger using the Debug &menuarrow; Start Without Debugging menu item (or by pressing Ctrl+F5), and test the application.
How It Works
The WinJS.UI.processAll function initializes the UI elements you have defined in the HTML markup, and returns a promise that is fulfilled when the initialization is successfully completed. Using the then function, you can ensure that you attach your code that subscribes to the click event of the Search button only after the markup is initialized.

In the previous exercises, you called the then method as a procedure, without using its return value. However, its return value is really valuable, because the then function returns a promise, too, which, of course, also has a then function that returns another promise, and so on. This allows you to chain multiple then functions and even multiple asynchronous operations in a very natural way.

In the previous “Try It Out” exercises, you first created a Windows 8 style application that searches on Twitter. In the next exercise, you extend the previous application and save the search results into a file. Note that now you will have multiple asynchronous operations that should execute in the following order:

1. Download the search results from Twitter.
2. Create a target output file.
3. Write the results to the output file.

Thankfully, Windows Runtime provides asynchronous methods that return promises to achieve this goal.


NOTE You can find the complete code to download for this exercise on this book’s companion website at www.wrox.com in the folder JSChainingPromisesTryItOut within the Chapter05.zip download.


Try It Out: Chaining Promises
To learn how you can chain promises, follow these steps:
1. In Visual Studio, open the project you created in the previous exercise, and open the default.js file.
2. Find the onSearchButtonClicked function and add the following line to its top:
var content;
3. Find the complete function of the then method and add the following line to its end:
content = result.responseText;
4. Remove the semicolon (;) from the end of the then method and replace it with the following lines of code:
.then(
  function () {
    var folder = Windows.Storage.ApplicationData.current.temporaryFolder;
    return folder.createFileAsync("temp.txt",
      Windows.Storage.CreationCollisionOption.replaceExisting); 
  }
 )
.then(
  function (storageFile) {
    divStatus.innerHTML += "Saving the results to " + storageFile.path + "<br />";
    return Windows.Storage.FileIO.writeTextAsync(storageFile, content);
  }
)
.then(
  function () {
    divStatus.innerHTML += "Done.";
  }
);
At this point, your onSearchButtonClicked function should look like this:
function onSearchButtonClicked(e) {
  var content;
  var txtKeyword = document.getElementById("txtKeyword");
  var divStatus = document.getElementById("divStatus");
  var divResult = document.getElementById("divResult");

  var url = "http://search.twitter.com/search.json?q=" + txtKeyword.value;

  WinJS.xhr({ url: url })
.then(
      function complete(result) {
        divStatus.style.backgroundColor = "lightGreen";
        divStatus.innerHTML = "Downloading " + result.response.length + 
                              " bytes completed. <br />";

        var hits = JSON.parse(result.responseText).results;

        for (var i = 0; i < hits.length; i++) {
          divResult.innerHTML += hits[i].text + "<br/>";
        }

        content = result.responseText;
      },

      function error(e) {
        divStatus.style.backgroundColor = "red";
        divStatus.innerHTML = "Houston, we have a problem!";
      },

      function progress(result) {
        divStatus.style.backgroundColor = "blue";
        divStatus.innerHTML = "Downloaded " + result.response.length + 
             " bytes. <br />";
      }
    )
.then(
      function () {
        var folder = Windows.Storage.ApplicationData.current.temporaryFolder;
        return folder.createFileAsync("temp.txt",
          Windows.Storage.CreationCollisionOption.replaceExisting);
      }
    )
.then(
      function (storageFile) {
        divStatus.innerHTML += "Saving the results to " + storageFile.path + 
             "<br />";
        return Windows.Storage.FileIO.writeTextAsync(storageFile, content);
      }
    )
.then(
      function () {
        divStatus.innerHTML += "Done.";
      }
    );
}
5. Start the application by pressing Ctrl+F5 and search for any keyword on Twitter. Note that now the results are not only shown, but also saved to a file whose path is displayed in the green status pane. You can see an example output in Figure 5-25.

Figure 5-25: Saving the results in the Twitter search application

c05f025.tif
6. Use Windows Explorer to browse to the folder that is displayed in the green status pane and verify the content of the temp.txt file.
How It Works
In Step 2, you created a local variable named content, and in Step 3 you saved the raw result that was returned from Twitter into this variable. This is the content that is later written into the output file.
In Step 4, you added three new then blocks to the end of the asynchronous process chain. Note that although the then function can accept up to three parameters, in this simple example, you defined only the first one, which is called when the promise successfully completes. You can omit the error and the progress handler if you don’t want to use them.
In the first new then block, you used the createFileAsync function of Windows Runtime to create a file named temp.txt in the temporary files folder of the application. As you might guess from its name, the createFileAsync function is an asynchronous function, and like all asynchronous functions, it returns a promise object.
The next then block uses this promise object, which will be fulfilled when the file is successfully created. Having the file in place, you used the writeTextAsync function to save the content into it. writeTextAsync is also an asynchronous function that returns a promise object.
The last then block handles the completed event of this promise object and displays a simple message when the whole process successfully completes.

Summary

Windows 8 brings a new generation of applications that are optimized to answer the challenges of today’s execution environments. Modern applications are more often executed on touch-driven devices, and used by people who are expecting the best user experience.

The Windows 8 design language is a key pillar to delivering a great user experience on mobile devices, as well as in the desktop world. The new infographic design concept breaks with the traditional iconographic design style, and focuses on the content instead of the chrome around it. By following the Windows 8 design principles you can create user-friendly applications that fit perfectly into Windows 8.

To have the best user experience, you need applications that are fast and fluid. In a time of large data structures and high-latency network communications, you cannot reach this goal with the classic single-threaded programming model. You must use asynchronous programming techniques, and Windows Runtime forces you to do so, by providing only asynchronous APIs for numerous features.

Thankfully, the top two programming languages in Windows 8 (C# and JavaScript) have direct support for asynchronous programming. In C# 5.0, you have two new keywords (async and await) you can use to create asynchronous methods without using callbacks and breaking the linear flow of control in your source code. In JavaScript, you can use promises to write asynchronous logic that is complex, but easy to read and maintain.

Exercises

1. What is the Windows 8 design language?
2. What types of applications are best for flat and for hierarchical navigation patterns?
3. What is the difference between the threaded and the asynchronous execution model?
4. How does C# 5.0 support asynchronous programming?
5. What are JavaScript promises?

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

What You Learned In This Chapter

TopicKey Concepts
Iconographic design styleThe iconographic design style is a design concept that uses metaphors from the physical world, and portrays objects with hyper-realistic graphics in the digital world.
Infographic design styleThe infographic design style is a design concept that focuses on the information and the content, instead the frame that contains it.
Flat navigation Flat navigation is a navigation pattern in which all pages reside at the same hierarchical level.
Hierarchical navigationHierarchical navigation is a navigation pattern in which the pages of the application are grouped into multiple sections and levels.
ThreadThe thread is the smallest unit of execution that can be scheduled by the operating system.
Asynchronous programming modelIn the asynchronous programming model, multiple tasks are executed on the same thread, but long tasks are divided into smaller units to ensure that they don’t block the thread for a long time.
Task objectA Task is a .NET object that refers to a value that will be delivered at some point in the future.
async and awaitasync and await are two new keywords in C# 5.0 that you can use to create asynchronous methods.
IAsyncOperation<T>The IAsyncOperation<T> interface is the future type used in Windows Runtime.
JavaScript promiseA promise is a JavaScript object that follows the Common JS Promises/A proposal, and returns a value at some time in the future.
..................Content has been hidden....................

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