Thursday, May 31, 2012

Everything You Need to Start Writing Windows 8 Metro Applications Today

I can still remember the day I learned how to program. I was only 7 years old and was staying home with my TI-99/4A that had no games or cartridges available. Bored, I pulled out the BASIC reference guide and tapped in a small program called "Mr. Bojangles" that made some pixelated boxs move across the screen. If you squinted and really stretched your imagination, you could almost pretend it was a little dancing guy. You can even watch this video online to see, although I'd argue the source code I saw there looks way smaller than what I remember typing. From there I moved onto the Commodore 64 and picked up 6502 assembly code:

$C000: LDA #$00
$C002: STA $D020
$C005: STA $D021
$C008: INC $D020 
$C00B: INC $D021
$C00E: JMP $C008 

Then it was onto Windows machines, Win32, MFC, and beyond.

It's amazing when you think about it to see how far Windows has come. I've been preparing a brief history for my Top 10 Metro Features talk (you can also see it live at CodeStock where I'll be handing out a sample chapter from my new book). Developers who have begun writing Windows 8 Metro applications have felt some of the pain of exploring a new platform and refactoring for breaking changes as new releases have come out, but overall I think the experience is phenomenal. Contrary to the fear that was rampant when Windows 8 was initially announced, when everyone speculated that C# and XAML would be dropped completely and everything would either be HTML5 and JavaScript or C++, the platform has rich support for multiple languages (including C# and XAML) and a powerful new runtime that makes it easier to do common tasks like accessing the web cam or connecting to a web site.

When my publisher agreed to my request to write a book about designing Windows 8 Metro applications, I was ecstatic. While my earlier book, Designing Silverlight Business Applications, focused on enterprise development, this new one takes a different approach and tackles designing Metro applications from the ground up. I assume you have some C# and XAML knowledge but I'm really focused on giving you everything you need to get up and running quickly on the new platform. Believe me, there is a lot of content and it covers most of what the Windows Runtime has to offer. Here is a tentative table of contents — I say tentative because it can change based on feedback from editors and you, but it should be very close:

  • Chapter One — The New Windows Runtime — History and context around Windows 8 Metro applications
  • Chapter Two — Getting Started — setting up your environment and building a more advanced "Hello, World" application (templates, tools, and looking underneath the covers at what Windows 8 Metro is)
  • Chapter Three — XAML — a primer on Extensible Application Markup Language (XAML) and how it works in Windows 8 Metro applications
  • Chapter Four — Metro Applications — overview of what is unique about Metro applications, including layouts, views, visual state manager, simulator, view types (snapped, full), semantic zoom, user input and touch, sensors, application bars, icons, and splash screens
  • Chapter 5 — Application Lifecycle — process lifetime management (PLM) including activation, suspension, resume, navigation, and extended splash screens
  • Chapter Six — Data — everything you need to know about data, including application settings, local and romaing file access, collections, buffers, byte arrays, encryption, signing, syndication of content, and web services
  • Chapter Seven — Tiles and Toasts — basic tiles, live tiles, badges, secondary tiles, and push screen notifications
  • Chapter Eight — Charm — all about contracts, including sharing, text selection, search, printing, play to and more
  • Chapter 9 — MVVM and Testing — how MVVM is implemented in Windows 8 Metro applications and coverage of the new unit testing capabilities in Visual Studio 11
  • Chapter 10 — Packaging and Deploying — understanding trial mode, products vs. applications, side-loading and distribution

Once this first comprehensive book comes out about writing the applications, I plan to follow up with a second more advanced title that covers things like authorization and authentication with single sign-on, media, device enumeration, advanced sensors, networking including sockets, accessibility features, background tasks, lock screen applications and advanced debugging and performance optimization.

Here's the best part — all of this is available right now. I don't know if you are familiar with the Safari Rough Cuts program, but it essentially allows you to have early access to the manuscript. One investment in the book will give you the manuscript as it stands today (parts of it not even edited yet) so you can not only read it but provide me with direct feedback to help shape what you would like to see in the final version. Then, as the book is edited and updates are posted, you have unlimited downloads of the latest versions right up to the final release. It's a great way to get your hands on everything you need to develop Windows 8 Metro applications with C# and XAML today, and ensure that it is current and up to date when it is released months from now. You can check out the Rough Cuts for this book by clicking on this link. Please also take some time to visit the Facebook page where I post updates about the progress for the book as well as Windows 8 related articles. You can access that page here.


Jeremy Likness

Saturday, May 19, 2012

How to Debug a Windows 8 Metro Secondary Tile

I've been working on Chapter 7 of my upcoming book, Designing Windows 8 Metro Applications with C# and XAML. This chapter focuses on tiles and toast notifications. In the Windows 8 runtime, it is incredibly easy to prompt the user to pin a secondary tile. This is a tile that has a deep link for content. For example, my reference application contains blogs and blog posts from several Wintellect employees. You can pin a specific blog or even a specific item within a blog. The application bar provides the icon to click to Pin to Start:

The code simply grabs the current "group" that represents a blog, then formats a unique id for the tile, a title, and a special set of arguments that are passed when the tile is tapped:

private void Pin_Click_1(object sender, RoutedEventArgs e)
    var group = DefaultViewModel["Group"] as BlogGroup;
    var title = string.Format("Blog: {0}", group.Title);            
        string.Format("Wintellog.{0}", group.Id.GetHashCode()),
        string.Format("Group={0}", group.Id));

The code on the App class that does the actual work simply sets up some assets for the tile, computes the location of the button that was tapped and then sets up the tile to prompt the user to pin it:

public async void PinToStart(object sender, string id, string shortName, string displayName, string args)
    var logo = new Uri("ms-appx:///Assets/Logo.png");
    var smallLogo = new Uri("ms-appx:///Assets/SmallLogo.png");
    var wideLogo = new Uri("ms-appx:///Assets/WideLogo.png");
    var tile = new SecondaryTile(id, shortName, displayName, args, TileOptions.ShowNameOnLogo | TileOptions.ShowNameOnWideLogo,
    tile.ForegroundText = ForegroundText.Dark;
    tile.SmallLogo = smallLogo;
    tile.WideLogo = wideLogo;            

    var element = sender as FrameworkElement; 
    var buttonTransform = element.TransformToVisual(null);
    var point = buttonTransform.TransformPoint(new Point());
    var rect = new Rect(point, new Size(element.ActualWidth, element.ActualHeight));

    await tile.RequestCreateForSelectionAsync(rect, Windows.UI.Popups.Placement.Left);        

You can see what the prompt looks like here:

When the application launches, it can read the arguments that are passed in and use them to navigate to the deep link:

if (_activationArgs.Arguments.StartsWith("Group"))
    var group = _activationArgs.Arguments.Split('=');
    target = typeof(GroupDetailPage);
    parameter = list.Where(g => g.Id.Equals(group[1])).FirstOrDefault();

The problem that you may encounter when dealing with secondary tiles is that the arguments are read-only when the application is launched. If you launch your Metro application from the debugger, you cannot modify the arguments and they will be passed in as blank. This will cause the application to respond as if it were launched from the primary tile, not a secondary one. Fortunately, the solution to debug secondary tiles is very straightforward. Simply right-click on the Metro project in the Solution Explorer and navigate to the Debug tab. There, you can set the application to get ready for debugging but not actually launch when you start a debugger session. This is what the setting looks like (see Do not launch, but debug my code when it starts):

Once you check this setting, you can launch debug and the application will simply wait. Then, you can press the Windows key to open the start screen and launch the application from a secondary tile. When the application is launched, it will jump into the debugger and you can hit your breakpoints to see the secondary tile arguments passed in and troubleshoot any issues you may have. Please head over to the Facebook page for my upcoming book and "Like" it to receive updates and learn when it will be available for preview online and released to print. I'll be handing out sample chapters at my upcoming speaking events, so I hope to see you there at one of them.

Jeremy Likness

Tuesday, May 15, 2012

The Task: Async and Await in a Windows Runtime World

In my last blog post, I covered how to wrap your arms around the Task class and its relationship to the new async and await keywords. I mentioned that the post was focused on the .NET Framework only because the Windows Runtime handles these operations differently. In this post, I’ll cover what those differences are.

Task is a Task is a Task

First, in the Windows Runtime, a Task is a Task … is a Task. You can write your code to return a Task or Task<T> in your Windows 8 Metro applications. If you are going to expose a Windows Runtime (WinRT) component, however, one of the rules is that you must always return a WinRT type. For asynchronous operations, there are four types allowed:

No Result Returns Results
No Progress or Cancellation IAsyncAction IAsyncOperation<TResult>
Supports Progress and/or Cancellation IAsyncActionWithProgress<TProgress> IAsyncOperationWithProgress<TResult, TProgress>

The type you return depends on whether or not you return a result, and whether or not you support checking progress and/or cancellation.

Task is a IAsyncAction or IAsyncOperation<T>

If you don’t support progress or cancellation, returning the necessary type is easy: simply use a Task and return it using one of the extension methods to convert it to the corresponding WinRT type. For example, the following useless piece of code iterates through all of the available integers and returns nothing:

public static IAsyncAction IterateAsync()
   return Task.Run(() =>
      for(int x = Int.MinValue; x < Int.MaxValue; x++) ;

For a more practical example, consider the multiplication method I used in the last blog post. To convert that to a result, I simply do:

public IAsyncOperation<int> Multiply(int a, int b)
   return Task.Run(() => a * b)

That’s fairly simple and straightforward. What about supporting progress and/or cancellation?

Forget Tasks: The 411 on AsyncInfo

The AsyncInfo class is there to assist you with performing asynchronous actions or operations that support cancellation and reporting progress.

public static IAsyncOperationWithProgress<int, double> Multiply(int a, int b)
   return AsyncInfo.Run<IList<long>, double>((token, progress) =>
      Task.Run<int>(() =>
         var result = a*b;
         return result;
      }, token));

Obviously the operation is a bit contrived as the multiplication operation doesn’t take as long, but hopefully this simple example illustrates the point of what is possible. The IAsyncActionWithProgress will work the same way, it simply doesn’t return a result.

There you have it … the scoop on the new async and await keywords and how they behave both with and without the Windows Runtime. Now that you have the basics, head over to Stephen Toub’s blog post and read the far more in depth Diving Deep with WinRT and await.

Friday, May 11, 2012

The Task: Events, Asynchronous Calls, Async and Await

Almost any software application today will likely contain a long-running process. “Long-running” may be a relative term but in the Windows Runtime it is specifically anything that could take longer than 50ms to execute. That’s a fairly small window, and it means those operations will need to run concurrently to the main application thread. Concurrency is important in both client applications (to keep from blocking the UI) and server applications (to accommodate multiple simultaneous requests).

The new technology referred to as Visual Studio Asynchronous Programming provides a streamlined language syntax for asynchronous development. It does this by providing two new keywords: async and await. While these keywords may simplify asynchronous development, they can still be confusing to developers. There are a lot of materials out there but I thought it might help to take a very simple example and explore just what these keywords are and how they operate. In this post I’ll focus specifically on the .NET Framework 4.5 support. While they are also supported for Metro-style applications, the implementation is slightly different.

The Main Event

In the movie Mission Impossible II, the short-lived protagonist Dr. Nekhorvich says:

“…every search for a hero must begin with something every hero needs, a villain. So in a search for our hero, Bellerophon, we have created a more effective monster: Chimera.”

In the search for an elegant solution to asynchronous programming we must start with some of the rougher implementations that have plagued developers in the past.

The event-based pattern is probably one of the most well-known asynchronous patterns to .NET developers as it is prevalent throughout the base library. Let’s assume I have a method that multiplies two numbers and for some crazy reason (maybe I’m sending it over a 300 baud modem to my Commodore 64 to process the result on the 6502 chip … you know, using a bunch of ROR operations) it takes a bit longer to process than I’d like, so I want to make sure it executes asynchronously. The first thing I’ll do is create an event argument payload for the result:

public class MultiplyEventArgs : EventArgs 
    public int Result
        private set; 

    public MultiplyEventArgs(int result)
        Result = result;

Next, I’ll define an interface:

public interface IMultiplierEvent
    event EventHandler<MultiplyEventArgs> MultiplyCompleted;
    void MultiplyAsync(int a, int b); 

Finally, I’ll implement the class that executes the operation asynchronous and fires the completed event when done.

public class MultiplierEvent : IMultiplierEvent

    public event EventHandler<MultiplyEventArgs> MultiplyCompleted;

    private void RaiseCompleted(int result)
        var handler = MultiplyCompleted;
        if (handler != null)
            handler(this, new MultiplyEventArgs(result));

    public void MultiplyAsync(int a, int b)
        Task.Run(() => RaiseCompleted(a * b));

I can test this in a simple console program with a method call:

class Program
    static void Main(string[] args)
        var p = new Program();


The implementation requires two methods, one to set it up and another to receive the completed event. Not bad, but you can imagine handling a chain of multiple events could get ugly quickly.

public void DoEvent()
    Console.WriteLine("Firing as an event 2 * 3 ..."); 
    IMultiplierEvent eventBased = new MultiplierEvent();
    eventBased.MultiplyCompleted += eventBased_MultiplyCompleted;
    eventBased.MultiplyAsync(2, 3);

void eventBased_MultiplyCompleted(object sender, MultiplyEventArgs e)
    Console.WriteLine("Event result: {0}", e.Result); 

That’s the old world of events.

The Asynchronous Programming Model

Another popular asynchronous model is the Asynchronous Programming Model, or APM. The framework provides the IAsyncResult interface and you specify a pair of methods to Begin and End the operation. The first method always returns the IAsyncResult and the second method always takes the IAsyncResult and returns the result of the call.

In the implementation I create a nested class used to help maintain the state between the calls:

private class AsyncState
    public Delegate MethodToCall { get; private set; }
    public object State { get; private set; }

    public AsyncState(Delegate methodToCall, object state)
        MethodToCall = methodToCall;
        State = state;

Then I implement the methods. Notice that I’m casting the method call to a delegate and taking advantage of the built-in capability to invoke it asynchronously, then wrapping the end call to return the result.

public class MultiplierApm : IMultiplierApm
    private class AsyncState [...]

    public IAsyncResult BeginMultiply(int a, int b, AsyncCallback callback, object state)
        Func<int, int, int> multiply = Multiply;
        var asyncState = new AsyncState(multiply, state);
        return multiply.BeginInvoke(a, b, callback, asyncState); 

    public int EndMultiply(IAsyncResult asyncResult)
        var asyncState = (AsyncState)asyncResult.AsyncState;
        var multiply = (Func<int, int, int>)asyncState.MethodToCall;
        return multiply.EndInvoke(asyncResult); 

    public int Multiply(int a, int b)
        return a * b;

Now that I have an implementation, I can call it like this:

public void DoApm()
    Console.WriteLine("Firing as APM 3 * 4 ..."); 
    IMultiplierApm apmBased = new MultiplierApm();
    apmBased.BeginMultiply(3, 4,
        result =>
            var value = apmBased.EndMultiply(result);
            Console.WriteLine("Apm result: {0}", value);
        }, null);

Note that I might have used two methods for the APM as well, I simplify chose to take a short cut but using a lambda expression instead.

Taking Asynchronous Operations to Task

With the new task library, setting up and calling asynchronous operations is far easier than the previous two approaches. First, I can use a single method signature and simplify specify the need for asynchronous operations by wrapping the result in a Task:

public interface IMultiplier
    Task<int> Multiply(int a, int b); 

For the implementation, I can easily use the built-in methods available in the library to spin off my thread:

public class Multiplier : IMultiplier
    public Task<int> Multiply(int a, int b)
        //return Task.Factory.StartNew(() => a * b);
        return Task.Run(() => a * b); 


Finally, I can use the new keywords to make calling and waiting for the result easy. When I want to do something asynchronously without blocking the thread I’m on, I simply modify the method with the async keyword, then await the asynchronous operaiton. Again, it’s as simple as async to mark the method’s intention of spinning of a separate task to wait for, then await to launch the thread and receive the results in a single line of code.

public async void DoTask()
    Console.WriteLine("Firing as task 4 * 5 ...");
    IMultiplier taskBased = new Multiplier();
    Console.WriteLine("Task result: {0}", await taskBased.Multiply(4, 5));

What happens here is that the current thread runs up until the await operation. There, the operation is spun off on a new thread. The main thread will wait for that thread to complete but will not block – it is not a synchronous operation. When the concurrent thread finishes what it is doing, it will drop the result back on the calling thread and allow me to interrogate the result. Notice that I can even nest the call inside of other operations – here the task must actually complete before it can pass the result to the string formatter which in turn sends the output to the console.

Simple interface design, simple implementation, and simple execution. I like it! But what do I do about those existing events and APM-based interfaces?

Wrapping Events

Fortunately, it’s possible to bundle up any asynchronous operation into a task. For this reason, I almost always declare my interfaces using Task. That way I can hide the underlying implementation. Let’s test this out. How can I take my IMultiplier interface and use it to call my MultiplierEvent class? The trick is to use a TaskCompletionSource. This special class allows me to perform an asynchronous operation using any pattern I prefer and then set a result when I’m done. The token will expose the event as a task that can be awaited. Here is a wrapper class that implements the simple interface:

public class MultiplierEventAsTask : IMultiplier
    private IMultiplierEvent _event;

    public MultiplierEventAsTask()
        _event = new MultiplierEvent();

    public Task<int> Multiply(int a, int b)
        var tcs = new TaskCompletionSource<int>();
        _event.MultiplyCompleted += (sender, args) =>
        _event.MultiplyAsync(a, b); 
        return tcs.Task;

I can then call it the same way I did the task-based implementation.

Wrapping the APM

Wrapping the APM model is even easier because the library provides a set of functions to convert existing operations. The FromAsync method will take most APM-style calls and turn them into tasks:

public class MultiplierApmAsTask : IMultiplier
    private IMultiplierApm _apm;

    public MultiplierApmAsTask()
        _apm = new MultiplierApm();

    public Task<int> Multiply(int a, int b)
        return Task<int>.Factory.FromAsync(_apm.BeginMultiply, 
            _apm.EndMultiply, a, b, null);

Once again, the end result is the same simple interface despite a completely different implementation.

That’s a Wrap!

Using the Task we can now take various implementations and simplify them to a common, easy to use and understand interface. This little piece of code will execute each of the different implementations in order, waiting for the result but without blocking the main thread:

public async void DoAll()
    // convert event to a task 
    Console.WriteLine("Firing all converted events in order ...");
    IMultiplier taskFromEvent = new MultiplierEventAsTask();
    IMultiplier taskFromApm = new MultiplierApmAsTask();
    IMultiplier task = new Multiplier();

    Console.WriteLine("2 * 3 = {0}", await taskFromEvent.Multiply(2, 3));
    Console.WriteLine("4 * 5 = {0}", await taskFromApm.Multiply(4, 5));
    Console.WriteLine("6 * 7 = {0}", await task.Multiply(6, 7));            

There is a lot more you can do than simply await tasks. You can combine tasks, chain tasks, even wait for one or all tasks to complete before moving onto another task. Once you understand that async simply specifies the intention to do something asynchronously without blocking the main thread, and await simply launches a task and returns the result once that task is complete, you should be well on your way to simplifying your asynchronous development.

Download the sample project here.