Browse by Tags

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);            
    ((App)Application.Current).PinToStart(this,
        string.Format("Wintellog.{0}", group.Id.GetHashCode()),
        title,
        title,
        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,
        logo);
    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

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++) ;
   }).AsAsyncAction();
}
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

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)
      .AsAsyncOperation();
}

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>(() =>
      {
         progress.Report(0);
         var result = a*b;
         token.ThrowIfCancellationRequested();
         progress.Report(100.0);
         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. .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

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
    {
        get;
        private set; 
    }

    public MultiplyEventArgs(int result)
    {
        Result = result;
    }
}
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

Next, I’ll define an interface:

public interface IMultiplierEvent
{
    event EventHandler<MultiplyEventArgs> MultiplyCompleted;
    void MultiplyAsync(int a, int b); 
}
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

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));
    }
}
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

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

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

        Console.ReadLine();
    }
}
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

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); 
}
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

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;
    }
}
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

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;
    }
}
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

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);
}
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

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); 
}
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

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); 

    }
}
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

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));
}       
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

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) =>
                {
                    tcs.SetResult(args.Result);
                };
        _event.MultiplyAsync(a, b); 
        return tcs.Task;
    }
}
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

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);
    }
} 
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

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));            
}
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

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.

I've received a few emails regarding the book that the code files are not available from the publisher website. I've spoken with the publisher about this and they are working to correct it, but I wanted to provide a link for those of you who have been patiently waiting. As a backup to the main website, I've posted all of the sample applications online to SkyDrive and you can download them by clicking on this link. I appreciate you patience and hope you will take the time to post a review on the site you purchased the book from once you have read and worked through the examples to help others who are considering picking it up for themselves.

Jeremy Likness

Thanks for everyone's support and votes. I have been selected to present two sessions at CodeStock 2012.

Per the CodeStock website:

CodeStock is a two day event for technology and information exchange. Created by the community, for the community — this is not an industry trade show pushing the latest in marketing as technology, but a gathering of working professionals sharing knowledge and experience.

This is always a great conference. I have the added bonus of getting close to the corporate headquarters for Wintellect and visiting company co-founder Jeff Prosise. This year there were quite a few Wintellect employees selected to speak. I'll be there with Mitch Harpur (Come Get a Message at the SPA), Rik Robinson (CSS3: How to Fake It While They Bake It and Touring the jQuery UI Widget Factory), John Garland (Putting the Cloud in Your Pocket: A Guide to Using Windows Azure to Build Cloud-Enabled Windows Phone Apps), and our Technical Director Steve Porter.

I'll be doing two sessions:

MVVM for Modern Application Development

The Model-View-ViewModel pattern was introduced for Windows Presentation Foundation applications (WPF) and later exploded in popularity with the introduction of various frameworks to support development on additional platforms including Silverlight and Windows Phone. The release of KnockoutJS the pattern has extended MVVM to the web and exposed it to the JavaScript stack, while the new Windows 8 Metro platform embraces the same XAML and C#-based technologies that WPF and Silverlight pioneered. In this talk, Jeremy Likness takes a deep dive into the history of the pattern, describes its benefits, and discusses how it relates to modern application development. Is it a bad fit for web applications? Does it belong in the Metro space? Learn the benefits and trade-offs to help decide if this pattern makes sense in your projects moving forward.

Top 10 Developer Features in Windows 8 Metro

Windows 8 presents a new platform for application development called Metro. This platform is specifically focused on the tablet and slate market and provides many advanced features including touch-friendly interfaces and advanced power management features. Metro also introduces a new runtime known as WinRT that exposes some incredible contracts and interfaces that make it easier than ever before to build connected, collaborative, touch-friendly applications. Jeremy Likness shares the top 10 features developers will love about this platform. This is based on my recent article here with live code samples and demos.

It should be a very good conference and I hope you are able to make it. I'm always happy to connect with blog readers and Twitter followers so please don't hesitate to pop over and say "Hello" even if you can't make my sessions. It's tough putting together a schedule for this event because there are so many good talks. If you think you may be going, why not drop a line in the comments or ping me on Twitter? I look forward to seeing some of you there.

Jeremy Likness

 

slbookcover

In June of 2011 I started the journey of writing a Silverlight book. The Silverlight team was about to release version 5 with an incredible set of new features that would revolutionize how it can be used in the enterprise. I knew there were already a number of books available to use a reference for fundamentals and controls, so I wanted to dig deeper and hit the topics I was challenged with in my job as a consultant as well as those questions that continually seem to surface on blogs and forums. I began with an introduction that analyzed client technologies available at the time, especially focusing on how HTML5 was evolving but not yet mature. The focus of the book is my “sweet spot” as I have been developing Silverlight applications for the enterprise since it’s version 3 release in 2008.

No one could have realized just how much change would take place over the following year. Silverlight 5 was released but without a roadmap for version 6 and Windows 8 was announced. Fortunately it was soon discovered that Windows 8 provides a path to build applications using C# and XAML, has full support for running Silverlight 5, and through the Portable Class Library even provides a path to create code that can be used to target both present state and future state applications.

I had the privilege of working with a phenomenal team at Addison-Wesley Professional along with two very experienced Silverlight developers as technical editors who helped shape the book to contain the depth and quality of information that is available today.

The book is in stock at Amazon.com as of today. There are a number of ways you can order the book:

The publisher’s website provides you with the table of contents and provides a sample chapter to download that covers the Model-View-View Model (MVVM) pattern.

The book also features the Jounce MVVM Open Source Framework I developed along with a sample application that covers quite a few features.

Is this book relevant? I believe it is if you’ll accept my biased opinion because companies have Line of Business applications today, they are not releasing Windows 8 applications right now, and Silverlight remains a very viable solution for these applications. The majority of concepts covered in this book translate to the C#/XAML stack used for Windows 8 Metro applications and apply to building enterprise applications in general. There has been tremendous support for this and I’ve included some of the most difficult patterns and problems to tackle with solutions that translate to other platforms as well.

I want to thank the community for their incredible support as it has been an amazing journey. I also would ask that if you have invested in the Rough Cuts, eBooks, paperback, or other editions, that once you’ve had time to read this book you take the time to post your review and comments online. It is your reviews and comments that other developers will trust when they are making the decision to invest, so honest feedback helps them decide whether or not this is a resource that will provide them with value. It also helps me improve how I deliver content to make it the best possible quality for you.

So what’s next for me? I’m already several chapters into my next book. It will cover Building Windows 8 Metro Applications with C# and XAML, and I’ll include information about how Silverlight developers today can take advantage of the Metro platform for tomorrow’s applications. This book will be available for early access to read, review, and provide feedback through the Safari Rough Cuts program. Stay tuned and I’ll announce when more information becomes available.

Thanks again!

Windows 8 Metro is a new platform for developing applications that are tailored to the devices on which they run. These devices may include traditional desktops and laptops as well as the new tablet and slate form factors. In this article I cover the top ten features developers will love about the new development environment. This is part of my work on the upcoming book, Building Windows 8 Metro Applications with XAML and C#.

Read the full article online at InformIT.

Jeremy Likness

Many developers tend to look at Windows 8 as a completely new platform and even question whether it heralded the imminent demise of managed code. After spending many months digging into the Windows Runtime (WinRT), Metro style or “tailored” applications, and exploring how they related to the .NET Framework, I’ve come to the conclusion that the two work very closely together and in fact are engineered to integrate. That means good news for managed developers. The .NET Framework 4.5 is very much “Metro-aware” while the Windows Runtime knows how to shake hands with the CLR. The purpose of this post is to elaborate on this a bit more than what I covered in my Portable Class Library series.

Metadata

The first thing to note is that WinRT components, regardless of what language they were written in, share the same metadata format as .NET Framework assemblies. This is what allows you to navigate to the metadata folder at c:\windows\system32\WinMetadata and be able to use ildasm.exe to expose the definitions of WinRT components that are part of the Windows 8 operating system. The standard is documented as ECMA-335 and you can check this link to learn more.

As part of this metadata, types and assemblies can be tagged with a new Intermediate Language (IL) keyword called windowsruntime. This keyword tags the type as a WinRT component. The .NET Framework uses this to know when to marshal parameters because the WinRT type system is not the same as the one supported by the CLR. Fortunately, this is supported “under the covers” as you’ll see in the next section. When an assembly is tagged with the keyword, it instructs the .NET Framework to use a special APIs like the one called RoResolveNamespace to load references. This is a way that all supported WinRT languages can access underlying components.

Type Conversion

As I mentioned, the .NET Framework does some magic with type conversion. This happens in both directions (calls into and values received from WinRT components). This is not new – this has been supported for awhile and you can see a list of Default Marshaling for Value Types in the MSDN documentation. A System.Int32 becomes a ELEMENT_TYPE_I4 and vice versa. These are what are referred to as “fundamental types.”

In addition, however, the CLR performs implicit mapping to more complex types. If you’ve been doing any Windows 8 development, you are probably familiar with conversions that look like this:

Windows.Foundation.Collections.IVector<T> <= => System.Collections.Generic.IList<T>

You can read the list of WinRT collection types, then drill into the detail to see the corresponding .NET map.

Here is a list of commonly mapped types:

Windows Runtime .NET Framework
IIterable<T> IEnumerable<T>
IIterator<T> IEnumerator<T>
IVector<T> IList<T>
IVectorView<T> IReadOnlyList<T>
IMap<K, V> IDictionary<TKey, TValue>
IMapView<K, V> IReadOnlyDictionary<TKey, TValue>
IBindableIterable IEnumerable
IBindableVector IList
Windows.UI.Xaml.Data.INotifyPropertyChanged System.ComponentModel.INotifyPropertyChanged
Windows.UI.Xaml.Data.PropertyChangedEventHandler System.ComponentModel.PropertyChangedEventHandler
Windows.UI.Xaml.Data.PropertyChangedEventArgs System.ComponentModel.PropertyChangedEventArgs

There are other mapped types that you may not be as familiar with, such as the map from a Windows.Foundation.Uri to a System.Uri.While this is done “automatically” it does have side effects. The WinRT Uri does not support anything but absolute Uris, so any attempt to pass a relative Uri into a WinRT component will fail.

Any other types are projected automatically without conversion. A good example of this is the built-in XAML controls for building Metro applications. Windows.UI.Xaml.Controls.Button appears as a CLR class to your .NET code, but it also appears as a C++ class to developers using the C++ option. There is no map or conversion, the type remains the same but the projection provides all of the plumbing necessary for it to act and feel like a type native to the environment you are working in. Any necessary wrappers are created behind the scenes – you’ll learn more about that later.

Because special types can have side effects, it’s important to know what they are and what restrictions exist. Here is a short list:

  • Array – If you still use this construct for collections it’s important to note that WinRT does not support the class being passed by reference as in the CLR. Arrays can either be provided as input parameters to a WinRT component, where they can be referenced but not modified, or as output parameters, where what you pass in is really just regarded as a buffer and not inspected but populated by the component.
  • DateTimeOffset – in the Windows Runtime, this becomes a Windows.Foundation.DateTime value which does not contain time zone information. The CLR will convert your time to UTC before passing it to the WinRT component, and will convert any result from UTC to local time. To resolve this, you should be prepared to convert the value to local time before passing it to a WinRT component and back from local time to the target time zone when you receive values back.
  • String – this becomes a HSTRING which does not support null values. You should not pass a null string into a WinRT component, nor should you ever see a null value returned back. Instead, use String.Empty.
  • Uri – this is converted to Windows.Foundation.Uri which only accepts absolute Uris. Attempting to pass a relative Uri will result in an exception.

In addition, it’s important to note some WinRT types and how they impact the CLR. Understanding these types is more important if you plan to write WinRT components in C++ for consumption by the .NET Framework – otherwise most of this happens behind the scenes for you.

  • ELEMENT_TYPE_OBJECT – on the surface, this is mapped as System.Object in the .NET Framework. It is used to pass back other types from APIs. What’s important to note is how it is mapped on the .NET side. This type represents a pointer to the COM IInspectable interface. It is responsible for projecting WinRT components into all supported languages and all WinRT interface types must derive from it. One important method that it declares is GetRuntimeClassName. If this passes back a value, the CLR will create a strongly-typed Runtime Callable Wrapper (RCW) for the projection. Otherwise, it will create a weakly-typed wrapper that simply resolves to System.__ComObject regardless of the actual backing type.
  • IReference<T> – this is an interesting type because it handles two features in the Windows Runtime. First, it is a way of providing a nullable type. While it maps loosely to Nullable<T> the mechanism is slightly different. The pointer itself will be null if the value passed is null, otherwise it will point to an implementation that returns the actual value when the get_Value method is called. Conversely, a null pointer results in a Nullable<T> instance created with HasValue set to false. The type also facilitates boxing. Instead of returning a direct value, a WinRT component can return an ELEMENT_TYPE_OBJECT (System.Object to the CLR) and implement IInspectable to return IReference<Int32> as the type. When that happens, the CLR will call the method to obtain the value, then box it on the managed heap and pass the reference back into the managed stack.

Events

In the CLR, managed events can have multiple delegates assigned and removed. Removing an event is as simply as using the operator to remove it and passing the delegate that handles the event callbacks. In WinRT, the event system is token-based. When you add a delegate to handle an event, you receive a unique token. To remove your delegate from the event, you call a method to remove and pass in the token, not the delegate.

Events are mapped between the CLR and WinRT by the compiler. If you decompile your code you will see this in action. The CLR uses the helper classes:

System.Runtime.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler

System.Runtime.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler

The compiler will emit code that maps the events through these classes. The classes will maintain the dictionary of tokens and delegates, so you can code your familiar remove operation and have it automatically pass the correct token behind the scenes.

Summary

For the most part, you don’t have to worry about any of the magic happening behind the scenes because it is done for you. However, the purpose of this was to show how much thought and engineering went into actually working with both .NET and WinRT to ensure the two could work closely together. This to me is evidence that .NET is not a second-rate citizen in Windows 8, but an important factor that was carefully considered as part of the overall strategy to create a flexible new platform with reach.

I finally managed to update and upload my To-Do List Reference Application. This is a Silverlight 5 application based on my Jounce framework that demonstrates a number of different features. I built it as part of my book, Designing Silverlight Business Applications. There are several chapters devoted specifically to the construction of this example application. It is a demonstration application, so while it contains a lot of different components designed to illustrate various points, it's not intended to be a "production application." I won't even call it an "enterprise application" because it falls far short of what you might typically build for the enterprise, but this one has a lot more code than your typical two-page blog post program.

Specifically, it demonstrates the following concepts:

  • The Jounce framework (of course)
  • The MVVM pattern
  • Using a shared view model to display non-shared data (this is a common misconception, that if you edit five records you need five instances of the same view model)
  • Jounce-specific navigation and parameter-passing
  • Use of the Visual State Manager (VSM)
  • Design-time support
  • The Managed Extensibility Framework
  • Theme management (i.e. storing a theme in a separate project and referencing it)
  • WCF RIA Services
  • Mapping (auto-mapping properties from one entity to another)
  • Event aggregator messaging
  • Repository pattern
  • The Sterling NoSQL database (the example uses both a server-side and client-side instance)
  • Synchronization between the client and server when the client is offline
  • p/Invoke
  • Concurrency management
  • Offline Out-of-Browser (OOB) including UI for installation and removal
  • Use of behaviors
  • Extensions for fluent interfaces
  • Region management
  • Validation
  • Printing
  • Localization (version "as is" has Spanish text substituted in the edit dialog)
  • COM Interop (exports items to Excel)
  • HTML DOM interaction (application works with JavaScript to warn the user if they edit a record and try to navigate in the browser) and updates the title whether in browser or OOB mode)
  • Tracking dirty records using the entity view model
  • Filtering and sorting
  • Touch interaction using the LightTouch library
  • Out-of-Browser child windows
  • Toast notifications
  • Testing

I'm sure there are some items I left out. I hope this helps answer a lot of questions I receive and I also hope it is taken as guidance and an example, not a "final architecture" or production-ready module as again, the key intent is to provide examples of a lot of different features. There is only one thing I ask: that if you have questions about the application, you first invest in the book and ask me only if you don't find your answers there. Jounce is an open source community project and I'm sharing this example application as well, but the book is how I spent the better part of a year compiling all of the information I know about enterprise Silverlight development into one comprehensive resource. It's not a rehash of blog posts and contains a lot of content. However, if you've got the book, have worked through the examples and still have some questions or issues, please don't hesitate to contact me through the Jounce discussion forums or by replying in the comments section below.

Simply head over to the Jounce website and click the download icon when browsing the latest source to grab the application. Thanks, and enjoy!

Jeremy Likness

Part 1: Creating the Portable Library (this post)
Part 2: Portability in Silverlight and WPF: a Tale of Type Forwarders
Part 3: Portability in Metro: A CLR and WinRT Love Affair (this post)

Portability in Metro: A CLR and WinRT Love Affair

In this series we’ve covered the portable library and reviewed how it allows you to create assemblies that can be shared without recompilation across multiple platforms. You created a portable assembly with a view model and a command in it, then successfully integrated it in a WPF and a Silverlight project. Now it’s time to code for the future and go Metro.

Create a new C# Metro application using the blank page template. Reference the PortableCommandLibrary project. Open the BlankPage.xaml file and drop in the same XAML you used for WPF and Silverlight. First, fix up a reference:

xmlns:portable="using:PortableCommandLibrary"

Next, add the XAML inside of the main grid:

<Grid.DataContext>
    <portable:ViewModel/>
</Grid.DataContext>
<Button Content="{Binding Text}" Command="{Binding ClickCommand}"
        HorizontalAlignment="Center"
        VerticalAlignment="Center"
        Margin="10"/>
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

Now compile, deploy, and run the application. It will work just as it did for WPF and Silverlight.

First the button:

portablelibmetro1

Then the disabled button:

portablelibmetro2

What’s interesting for this example is that you know when you want to wire a command, you have to use a completely separate namespace from Silverlight. In fact, the namespace implies that you are accessing a WinRT component that is part of the operating system and not even a managed object. How do we pull that off with an assembly that isn’t modified?

To begin the journey, start with the assembly that is referenced directly by the portable library. This is System.Windows.dll only this time you’ll inspect it in the .NETCore folder, which is the smaller profile allowed for Metro applications. Once again, the assembly contains no implementation. Opening the manifest, you will find a series of type forwarders. This time the ICommand interface is redirected to System.ObjectModel.dll.

portablelibmetro3

What’s next? You guessed it. Pop open the System.ObjectModel.dll assembly and you’ll find:

portablelibmetro4

So there it is … but there’s a problem. When you specify your own command implementation, you have to reference the Windows.UI.Xaml.Input namespace. So how will this reference work? This is where Metro works a little bit of magic.

It turns out the platform maintains an internal table that maps CLR namespaces to the WinRT equivalents. This allows seamless integration between the types. For example, the CLR may be exposed to the type Windows.Foundation.Uri when dealing with a WinRT component. When this happens, it automatically maps this to the .NET System.Uri. When the CLR passes System.Uri to a WinRT component, it is converted to a Windows.Foundation.Uri reference.

In our case, the code references:

System.Windows.Input.ICommand

The platform will automatically map this to the WinRT counterpart,

Windows.UI.Xaml.Input.ICommand

This is a very powerful feature because it enables compatibility between legacy code and the new runtime with minimal effort on the part of the developer. If your type maps to an actual object that can have an activated instance, rather than just an interface, the CLR will automatically instantiate a Runtime Callable Wrapper (RCW) to proxy calls to the underlying WinRT (essentially COM) component.

The whole portable path looks like this in the end:

portablelibmetro5

If you want to see the “projected” types you can use ildasm.exe with the /project switch and in theory, if you run this against one of the .WinMD files (such as Windows.UI.Xaml.Input.WinMD) located in %windir%\winmetdata you should see .NET projected types instead of Windows Runtime types … I have yet to get this to work but if you have, please post the details here.

And that’s it – you’ve learned how to create an assembly that is completely portable between .NET Framework 4.5 (WPF), Silverlight 4.0 and 5.0, and Windows 8 Metro, and learned a bit about how it works by chasing down ICommand under the covers. Hopefully this helps with understanding the library and also with planning out how to map future projects that need to share code between existing implementations and future Metro targets.

Part 1: Creating the Portable Library
Part 2: Portability in Silverlight and WPF: a Tale of Type Forwarders (this post)
Part 3: Portability in Metro: A CLR and WinRT Love Affair

Portability in Silverlight and WPF: a Tale of Type Forwarders

In the last post, I walked through creating a portable assembly that will target Silverlight 4.0 and above, .NET Framework 4.5, and Windows 8 Metro. In the assembly were a few classes that handled commands and property change notification for a simple view model. In this post I’ll show you how to reference the assembly in Silverlight and WPF and explain why it works.

The first step is to create a new Silverlight 5.0 project (just using that because it’s the latest version, I know the library will technically support 4.0). Just make a simple application (no need to have a web project as well). The project will be created with the default App.xaml and MainPage.xaml. In the solution explorer, right-click on the References node and add a reference to the PortableCommandLibrary project. Now open up the XAML for the main page. At the top, add a namespace declaration for the view model:

xmlns:portable="clr-namespace:PortableCommandLibrary;assembly=PortableCommandLibrary"

Next, paste the following XAML inside the main grid called LayoutRoot (you’ll use the exact same snippet for all of the projects in this series).

<Grid.DataContext>
  <portable:ViewModel/>
</Grid.DataContext>
<Button Content="{Binding Text}" Command="{Binding ClickCommand}"
        HorizontalAlignment="Center"
        VerticalAlignment="Center"
        Margin="10"/>
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

Now compile and run the application. You should see something like this:

portablelibsilverlight1

If you follow the instructions, you should end up with this:

portablelibsilverlight2

I’d love to show you how this worked with the portable library, but the answer is pretty boring. As I showed you in the last post, the portable assembly points to an ICommand interface that lives in the System.Windows.Input namespace in the System.Windows.dll assembly. If you peek inside Silverlight’s assemblies and run ildasm.exe you’ll see:

portablelibsilverlight3

The reference can be visualized like this:

portablelibsilverlight4

Really no magic at all – Silverlight is a lowest common denominator here. So let’s try something a little more interesting. Create a new WPF project and reference the same portable library. Add the same namespace declaration to the MainWindow.xaml file and drop in the XAML inside the Grid tag. Run the application – look familiar?

portablelibwpf1

Click it.

portablelibwpf2

OK, so it works the same way, but we noted earlier that the ICommand interface lives someplace different. How does this work? If you recall, the reference to System.Windows.dll in the portable library was tagged as retargetable. This tells the runtime that the target may really exist somewhere else. In fact, if you look at the references available for the .NET Framework 4.5 (here’s a tip: forget that old %windir%\Microsoft.NET\Framework\ stuff … instead, try the newer %programdir%\Reference Assemblies\Microsoft\Framework\.NETFramework\ folder), you’ll find there is a System.Windows.dll file. Pop it open with ildasm.exe and you’ll see there is no implementation in the file, only metadata. Read the manifest and you’ll come across this little gem:

portablelibwpf3

Ah-hah! The portable library people have been planning this for longer than most readers suspect. There’s a nice reference now that politely invites the CLR to look somewhere else for the implementation, specifically in System.dll. If you open that assembly, you’ll see the interface is indeed defined there. So, what really happened looks a little like this for the .NET Framework 4.5:

portablelibwpf4

If you’re turning pale at the thought of so many hops, don’t get worried. These tables are loaded into memory and represent very miniscule lookups. The portable team assured me that any performance cost due to a little indirection is negligible.

What I love about the approach is that it uses a lot of pieces that have been already in place but in a clever way that gives us this powerful functionality of using the same assembly in Silverlight (web) or WPF (desktop). In the next post, we’ll take it even further and see how it relates to the brand new platform of the Windows Runtime (WinRT) for a Windows 8 Metro application. How on earth do we go from this to an unmanaged code base?

Part 1: Creating the Portable Library (this post)
Part 2: Portability in Silverlight and WPF: a Tale of Type Forwarders
Part 3: Portability in Metro: A CLR and WinRT Love Affair

The portable library tools have been available for several months now. The goal for this add-in to Visual Studio 2010 was to enable you to create special portable assemblies that can run on various platforms, ranging from XBox and Windows Phone 7 to various versions of the .NET Framework and Windows 8, without having to recompile them. That’s a pretty amazing feat and allows developers to avoid some crazy practices like linking source code.

With Visual Studio 11, the tools are no longer an add-in but are a built-in part of the product. You can directly create portable class libraries and build these magic assemblies that can be reused without recompiling. For many users, this is incredibly important because it means they can not only reuse their libraries between platforms like the phone and the desktop, but also can build insurance for the future. Think about it: you can build a Silverlight application today, share your libraries with a Metro application you are developing for tomorrow, and only have to branch the parts of the code that are necessary.

You may be surprised to learn just how much functionality can be shared. Property change notification, commands, even the network stacks can be shared across targets. The purpose of this post is to summarize some of the capabilities, show you how to build a project that shares portable libraries, and then get into the dirty details of how the magic really works. How can we possibly have an assembly that Silverlight recognizes today work without modification or recompilation in our Windows 8 Metro application of the future? Keep on reading if you want to uncover the answer.

For this example I’ll walk you through creating a view model that executes a command and changes some text. The view model will be reused without modification in a Silverlight, WPF, and Windows 8 Metro project, along with property change notification and the implementation of ICommand. What makes this interesting is the fact that ICommand lives in very different places on these platforms.

In Silverlight and WPF, ICommand lives in the System.Windows.Input namespace. While the namespace is the same, the assemblies are not. The definition exists in System.Windows.dll for Silverlight but in WPF and the .NET Framework 4.5 it is defined in System.dll. On Windows 8 Metro, the namespace for ICommand is Windows.Xaml.UI.Input. There, it doesn’t even live in an assembly but is defined through metadata and projected by the underlying OS. How does the portable library reconcile these differences?

If you want to follow along and have Visual Studio 11 Beta Ultimate (this won’t work with Express) simply create a new solution called PortableCommandLibrary and with a project of type Visual C# –> Windows –> Portable Class Library.

portablelib1

Now you can modify the target frameworks. As you may imagine, the platforms you wish to target will limit your options. For example, if you want to target the phone, you won’t be able to use the Managed Extensibility Framework (MEF). If you want to target the XBox, you won’t have the networking stack available. The combination of targets will limit the portable APIs available for you to use in your portable library. The beauty is that you don’t have to figure out what’s compatible as the team has figured this out for you and will automatically restrict your options based on what you select.

Right-click the project node and go into Properties (ALT+ENTER). Click on the Change button.

portablelib2

This will give you the option to select the profile you wish to use. For this example, we’ll build a library that targets .NET Framework 4.5 for WPF, Silverlight 4.0 and higher, and Metro.

portablelib3

Great! Now take a look at the Solution Explorer under References. What is that? “Portable Subset”?

portablelib4

Look at the properties for the reference and you’ll see a path. Navigate to the path. Wow, now this is interesting! There are the DLLs you can safely use between the targets. You can see a redistribution list and a set of supported frameworks as well.

portablelib5

The magic here is worked by a new Visual Studio 11 feature called Extension SDKs. This feature allows you to use a “reference” that is actually a package of files. It solves the problem of deploying custom controls with assets and also helps us write portable code. The portable team was kind enough to figure out all of the available permutations of framework combinations and package them as specific extensions to make a seamless reference experience in Visual Studio 11. You can read Microsoft’s documentation on how to create your own SDKs here.

OK so now we’ve learned a little bit about the magic that makes this work. The SDK reference constrains what we can do to code that is portable between the target runtimes. So what next? How about create a command that can perform a single action and then disables itself? You’ll need to add a using statement for System.Windows.Input:

public class ClickOnceCommand : ICommand 
{
    public ClickOnceCommand(Action action)
    {
        _action = action;
    }

    private Action _action; 
    private bool _canClick = true;

    public bool CanExecute(object parameter)
    {
        return _canClick;
    }

    public event EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
        _canClick = false;
        _action();
        var handler = CanExecuteChanged;
        if (handler != null)
        {
            handler(this, EventArgs.Empty);
        }
    }
}
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

Great! Next, let’s create a view model that exposes a text property. The property invites the user to click. The view model will expose a command and feed it the action to change the text (to admonish the user not to click). The view model looks like this:

public class ViewModel : INotifyPropertyChanged 
{
    public ViewModel()
    {
        ClickCommand = new ClickOnceCommand(() => Text = "Don't Click Me");
        _text = "Click Me";
    }

    private string _text;

    public string Text
    {
        get { return _text; }
        set
        {
            _text = value;
            RaisePropertyChanged("Text");
        }
    }

    public ICommand ClickCommand { get; private set; }

    protected void RaisePropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

Here’s the interesting part: we’ve now created a functional view model and command that will work on multiple platforms from a single assembly without recompilation. If you’re concerned about your path from now to Windows 8, consider Silverlight 5 or WPF as an interim because the following XAML will work without a single modification across all of these targets (Silverlight, WPF, and Windows 8 Metro):

<Grid>
    <Grid.DataContext>
        <portable:ViewModel/>
    </Grid.DataContext>
    <Button Content="{Binding Text}" Command="{Binding ClickCommand}"
            HorizontalAlignment="Center"
            VerticalAlignment="Center"
            Margin="10"/>
</Grid>
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

Obviously it won’t always be that simple but there is a lot of opportunity for sharing code here. Don’t worry about using the XAML just yet – I’ll walk through that in the next post. You don’t have to be an expert to figure out what the goal is: we want to show a button that invites the user to click. When clicked, it will disable itself and tell the user not to click it. Simple, no?

You can build the portable library and inspect it with ildasm.exe. What I want you to notice is that the ICommand reference points to the System.Windows.dll assembly:

portablelib6

For Silverlight, this is fine … that’s exactly where it lives. In the .NET Framework 4.5, however, it lives in System.dll. Windows 8 Metro defines it in a different namespace: Windows.UI.Xaml.Input. So how can this single assembly work in those environments without being rebuilt?

I’ll explore the answer for WPF and the .NET Framework 4.5 in the next post. For now, take a look at the manifest that was generated for our portable assembly. Note the special tag on the external references.

portablelib7

More to come!

Here’s a quick and easy tip for developing Windows 8 Metro applications. Are you looking for decent icons to use in your Application Bar? Windows 8 makes it incredibly easy by using the built-in Segoe UI Symbol font. There are tons of icons embedded in the font that are perfect for using in your applications.

Take a look at the following XAML snippet from the Microsoft quick start for adding an app bar:

<StackPanel Orientation="Vertical" Margin="0,14,0,5" Grid.Column="1">
   <Button Style="{StaticResource AppBarButtonStyle}"
       FontFamily="Segoe UI Symbol" FontSize="18.667" 
       Padding="8,8,0,0" Margin="0,0,0,10"
       Content="&#xE112;"/>
   <TextBlock Text="Back" />
</StackPanel>
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

It defines the section of the application bar you see below:

back

The key is in the content tag that specifies the arcane text &#xE112; – this is simply a notation that references the location of the symbol in the font (you can see the “font family” is set to the appropriate font). So how do you go about finding these icons? Fairly simple: on the Windows 8 machine, press the Windows Start Button (that button that has the Windows logo on it) or open the start menu and type “Character Map.” This will give you access to launch the Character Map application. Switch the font to Segoe UI Symbol and scroll down to the bottom until you see something like this:

segoeuisymbol

Now you can simply select the icon you wish to include. For this example I’ve selected the camera icon. Note the code at the bottom: U+E114. That is the code I need to know I can use &#xE114; in text for the Segoe UI Symbol font to make the camera icon appear.

How cool is that? You’ll find the font covers most of the icons you would need for your application. By using the icons from the font set, you also ensure consistency with other Metro applications. Users will be familiar with the fonts and it will make it easier for them to choose the right one for the task they intend to perform.

It’s finally here! Unless you’ve been hiding under a rock, you have heard the buzz around the Windows 8 Consumer Preview. If you haven’t had the opportunity to grab it and install it, I suggest you browser over to this link now and download your copy! There are many exciting new features, and this post will guide you through a few of them.

It is a Beta After All

There has been much buzz around whether or not the name “Consumer Preview” means it is not a beta and therefore the final release will be delayed. There is a lot of speculation around why the word “beta” is being avoided. Here is an article explaining some of these ideas. When you install the Consumer Preview – in fact, any time it loads or wakes up – you are presented with an image of, well, a Beta.

addmef

The Green Stack Isn’t Only Green

A common name for Metro-style applications you may hear is the “green stack.” This is named because the Developer Preview sported a green background. That’s no longer the case. You can now customize the color and design of the background for your Metro experience. I proudly present the Metro palette:

personalize

Where is the Start Button?

Twitter, Facebook, and blogs were going crazy over the rumors that the start button was going away. As a few people quickly pointed out, that isn’t really the case. True, there is no long a pervasive Start Button sitting on the corner of your task bar. But do you need it? First, most hardware and keyboards have a Start Button already – new tablets for Windows will feature this, so you can use the version on your device (this is similar to the way Windows Phone comes with hardware Back, Home, and Search buttons).

Even if you think resorting to the hardware is a cop-out, there is hope. Simply swipe your thumb in from the right edge of the screen or move your mouse pointer over to the right edge, and you will be greeted with … well … it’s a button, and I’m pretty sure it takes you to the screen you’re looking for.

startmenu

Lots of New Tiles

One thing you’re sure to notice immediately is the number of new tiles. Microsoft has been working hard to add additional functionality to the Metro stack and it shows. Just take a look.

start

Does that look busy or what? This snapshot was from a new install because I didn’t want to share too much personal information, but once you log into the various tools, the tiles will begin to update. I’ll go into some more interesting features below. You can see that instead of Windows Live, you have applications integrated into the platform for things like Mail and Messaging. What else can you see?

  • XBox Live Games – along with all of the fun integration with your account and avatar
  • Bing Maps – yes, it will find your current location and give you driving directions
  • Calendar – once you link your accounts, the Calendar works very similar to the way the Windows Phone does and aggregates your calendars together with a live tile announcing upcoming events
  • XBox Live Companion – yes, you can link to your favorite console and control it from your tablet
  • Store – everyone has a store, right?

These are just some of the highlights. Let’s dive a layer deeper.

Mail

Mail is an integrated feature. I like having mail right there, but it feels a bit raw. I was not able to hook into my hosted Exchange (soon to be Office 365) account and once I closed and came back, lost the ability to add a new account. Still, it allows me to browse mails quickly and easily and demonstrates the potential of where the platform can go.

mail

Music and Videos

Ah, now this one was fun! I wondered whether or not I would have to install Zune. When you first pop in, you get some encouraging sections like this:

music

What? No music? Do I have to go online and grab it? On a whim, I decided to copy over my Zune library from another laptop. This was just a straight file system copy, but guess what? It worked. Once I had the music moved over, it was instantly recognized and available to shuffle, play, and enjoy from my tablet. My tile turned into this:

music-tile

Previewing just a cross-section of some of the albums I have digitized. As for videos, I have lots of DVDs. Anyone have a good, um, ripper they can recommend?

People

This is by far my favorite feature. Like mail, it has a lot of work left to be done. The interface is not great and in fact scanning updates is tedious. However, the potential is what excites me the most. I love this feature on my Windows Phone. Basically, add connections to social networks, mail, etc. and all of your contacts meld together into one place. You get tile notifications, seamless history between messages, emails, and phone calls, and updates and notifications all in one place. The potential exists here for the same integration, it just needs to mature more.

Below you can see some of the potential – the cut off portion has contact names and pictures (I don’t think they’d be happy if I shared them here, hence the crop).

people

Closing Applications

Oh, remember how everyone complained that app swapping was a pain because there was no easy way to close applications? Not any more. There is a new gesture to take care of this. With your finger you can simply swipe downward from the top of the tablet display. This will shrink the current application. From there you can release and have it snap back, or continue to swipe down off the bottom and this action will close the application. Using a mouse? No problem. Hover near the top of the application until the pointer turns into a little hand. Click to grab, then drag it down and toss it off the bottom of your screen to close it.

Conclusion

I think there is a huge step forward between the Developer Preview and the Consumer Preview. It seems Microsoft is working hard and listening to feedback. There is a lot of work to do, however.

Did you install the Consumer Preview? If so, what are your thoughts? Ping back with the comments below.

It seems there is quite a bit of anticipation surrounding the imminent release of the Windows 8 Consumer Preview. I've read the speculation about what it will actually include, or not include, and if this release really means anything in the larger scheme of things.

The release will coincide with the Mobile World Congress. What I find interesting is that the same week, thousands of Microsoft MVP awardees will descend on Bellevue, Washington (close to the campus in Redmond) for the Global MVP Summit. I know as a Silverlight MVP I am very interested in what I will learn that week — unfortunately it is often NDA so I'm not always able to share. I'll be keeping a close eye on the MWC and the release of the Windows 8 preview.

If you are in Seattle next week, why not drop by our Wintellect tweetup? Use the link to register. I'll be there along with the debugging master John "Bugslayer" Robbins, CLR expert Jeffrey Richter, and fellow MVP Steve Porter. We'll be discusing several topics ranging from Windows 8 to the new look for Visual Studio 11.

My book Designing Silverlight Business Applications is very close to final release. You can pre-order for 42% off at Amazon as of the date of this blog post. I am working on my second book about Windows 8 Metro Applications and am learning more and more how the fundamental skills and concepts we learned for Silverlight apply in this new environment. As I read the buzz about the new version coming out, I wonder how many people are actually hands-on with the Developer Preview bits and what your expectations are for the Consumer Preview that is right around the corner. What are your thoughts? What do you think Microsoft needs to demonstrate with this release? What do you see as the major hurdles they will need to overcome in order to successfully gain a foothold in the consumer market? What is your general feedback from using the current version? Please use the comments below to share your thoughts as this important conversation gains momentum moving into next week.

Jeremy Likness

More Posts Next page »