Showing posts with label WinRT. Show all posts
Showing posts with label WinRT. Show all posts

Tuesday, May 22, 2012

Async VII: WinRT class library

In the previous post I talked about async from JavaScript. Now, for this I had to make a WinRT class library for my asynchronous RestCaller class, so this functionality could be used from a HTML5 JavaScript WinRT application. Now, once you do this, there are some things you need to know and some restrictions on the types you use for your publicly visible methods.

First of all you need to create a class library. Pretty simple, but once it's created, you need to change its' project type to WinMD file. This stands for Windows MetaData file.


Also, in the first version, my class library was called BlitzHiker.Lib. This name gave me runtime errors when called from JavaScript. At compile time everything was fine, but at runtime it would just crash for no reason. Removing the point from its' name fixed this.

Once I had the class library ready, I copied my RestCaller class to it and started compiling. The errors this gave were quite abundant. For starters, you are not allowed to use a return type of Task or Task<T> in a WinMD file. This forced me to define all of my existing methods as private. Which made it all compile just fine. But then again, you're nothing with private methods, you need some public ones as well.

private async Task PublishHikeRequestTaskAsync(CancellationToken token)
{
    var hikeRequest = GetHikeRequest();

    try
    {
        var client = new HttpClient();

        var url = string.Format("{0}/HikeRequest", BASE_URL);
        var response = await client.PostAsync(url, await BuildJsonContent(hikeRequest), token);
        response.EnsureSuccessStatusCode();
    }
    catch (HttpRequestException exc)
    {
        var dialog = new MessageDialog(exc.Message);
        dialog.ShowAsync();
    }
}

For each of these private methods I needed to define a public wrapper. The return types you are allowed to use on them are AsyncAction (as a replacement for Task) and AsyncOperation<T> (as a replacement for Task<T>).

The original method gets called by using AsyncInfo.Run (this changed in the recent CTP, the original type used was AsyncInfoFactory, but that one's gone. If you watch the Build sessions on async, you'll see them use the AsyncInfoFactory, but that just won't work anymore).

public IAsyncAction PublishHikeRequestAsync()
{
    return (IAsyncAction)AsyncInfo.Run((ct) => PublishHikeRequestTaskAsync(ct));
}

You can also see me sending along a CancellationToken. Since it's not passed along to the PublishHikeRequestAsync method, you will have to use a different way of cancelling than I showed in one of the previous posts.

protected async override void OnNavigatedTo(NavigationEventArgs e)
{
    cts = new CancellationTokenSource();

    try
    {
        await _restCaller.PublishHikeRequestAsync().AsTask(cts.Token);

        var driverIds = await _restCaller.GetDriversAsync().AsTask(cts.Token);

        if (driverIds != null)
            await ShowDriversOnMap(driverIds, cts.Token,
                new Progress<int>(p => statusText.Text = string.Format("{0} of {1}", p, driverIds.Count)));
    }
    catch (OperationCanceledException exc)
    {
        statusText.Text = exc.Message;
    }
}

Since you get an AsyncAction, and not a Task, you can call AsTask on this. With AsTask, you can send along your CancellationToken. This shows that before you all start using WinMD class libraries, just keep in mind that you are working with different types and that the usage will be different (more verbose) as well.

As for the AsyncOperation, that's pretty much the same as AsyncAction.

public IAsyncOperation<UserModel> GetUserAsync(Guid userId)
{
    return (IAsyncOperation<UserModel>)AsyncInfo.Run((ct) => GetUserTaskAsync(userId, ct));
}

And that's it. I hope you found these posts on async useful. Just keep in mind that all info given here is still based on a preview version of this library and things can still change a bit in the eventual release.

There are some drawbacks on using async. As with a lot in the .NET Framework, they make things really simple for you. The danger is that it's easy to forget what you are actually doing, defining callbacks. Just keep that in mind and you'll be fine.

Friday, May 18, 2012

Async VI: JavaScript Promises

The previous posts (Async basics, Exception handling, Cancellation, Progress reporting, void methods) all talked about async from a C# point of view. But let's not forget there is another very important language coming to WinRT and that's JavaScript in combination with HTML5. The cool thing is you can use more or less the same async capabilities here that you find in C#. Big difference is the syntax you will be using. Since the async syntax will be closer to what you are used to in JavaScript.

The UI in the JavaScript BlitzHiker application looks pretty much the same as its C# counterpart. It also has a page to publish a hikerequest, which does three big things, initialize the Bing map we use, find my own location and publish my hikerequest.

function initialize() {
    initializeBing();
    findMe();
    publish();
}

The findMe function has the first bit of asynchrony.

function findMe() {
    if (myPosition) {
        setMePushpin(myPosition)
    }
    else {
        if (!loc) {
            loc = Windows.Devices.Geolocation.Geolocator();
        }
        if (loc) {
            loc.getGeopositionAsync()
            .then(setMePushpin, errorHandler);
        }
    }
}

The call to GetGeopositionAsync is an asynchronous call. We can subscribe a callback to this method by using the then function. So no special keywords like await and async here, but more JavaScript style callbacks. You also see me using an error handler. In the JavaScript case, it is not with try catch that you handle exceptions, but with an extra error handler function you can send along.

I also made use in this function of the loc variable, that I defined globally. My original version of this method looked like this:

function findMe() {
    if (myPosition) {
        setMePushpin(myPosition)
    }
    else {
        Windows.Devices.Geolocation.Geolocator()
            .getGeopositionAsync()
            .then(setMePushpin, errorHandler);
    }
}

But funny enough only one times out of 10 the pushpin for my position was set correctly. This had me puzzled. Apparently, my local Geolocator had already gone out of scope before the callback came in. That is why I altered this to a global variable.

Another place where I used asynchronous callbacks, is in the publish method, which publishes a hikerequest, gets all the drivers and shows those on the Bing map.

function publish() {
    var caller = new BlitzHikerLib.RestCaller();
    caller.publishHikeRequestAsync()
    .then(function () {
        caller.getDriversAsync()
        .then(function (driverIds) {
            if (driverIds == null || driverIds.length == 0)
                return;
            for (var i = 0 ; i < driverIds.length && i < 200 ; i++) {
                var driverId = driverIds[i];
                caller.getUserAsync(driverId)
                .then(showDriver);
            }
        });
    });
}

You see me use then three times, each time sending a callback function along. Now, in my humble opinion, this syntax doesn't make this code the most readable code in the world. You need to look at it a couple of times to see what's going on. Now, you can actually improve on this by use of a little trick.

function publish() {
    var caller = new BlitzHikerLib.RestCaller();
    cancellable =
        caller.publishHikeRequestAsync()
        .then(function () {
            return caller.getDriversAsync()
        })
        .then(function (driverIds) {
            if (driverIds == null || driverIds.length == 0)
                return;
            for (var i = 0 ; i < driverIds.length && i < 200 ; i++) {
                var driverId = driverIds[i];
                caller.getUserAsync(driverId)
                .then(showDriver);
            }
        })
        .then(null, errorHandler);
}

You can see that for all but one, all then statements are nicely aligned. This can be done since we return the actual asynchronous call from the callback.

The reason I don't use this trick with GetUserAsync, is that, if I were to do that, I would jump out of the for loop that's processing each driver and only the first driver would be shown on the map.

The last then statement is special as well, since it defines a global error handler. Whatever error occurs in whatever callback, this error handler will catch it. Another useful trick.

I also extended this method a bit and actually caught the asynchronous calls in a variable, I called cancellable. Cancellation in JavaScript as well is done a bit differently. Once you define a global variable like this, you can call cancel on it.

function cancelHike() {
    if (cancellable != null) {
        cancellable.cancel();
        var errorDiv = document.getElementById("errorText");
        errorDiv.innerText = "operation cancelled";
    }
}

With this you have more or less the exact same application as I showed in the C# examples. But I do have to say I did need to alter some things in the RestCaller to get all this working for JavaScript. That is something I'll show you in the next (and last) blog post.

Thursday, May 17, 2012

Async V: void methods

In the previous post on async, I told you, we would go a bit deeper into void methods, since they behave differently than methods returning a Task or Task<t>. The difference is that, where non-void returning methods give you callback behavior, void methods give you fire and forget behavior. This can give you confusing results if you don't know how to spot and use them.

Let's take a look again at our OnNavigatedTo method.

protected async override void OnNavigatedTo(NavigationEventArgs e)
{
    await _restCaller.PublishHikeRequest();

    var driverIds = await _restCaller.GetDrivers();

    if (driverIds != null) 
        await ShowDriversOnMap(driverIds);

    var hikerIds = await _restCaller.GetHikers();

    if (hikerIds != null) 
        await ShowHikersOnMap(hikerIds);
}

Now, the original version of this code looked a bit different, I actually altered it to get the entire explanation on async right for you. The original version was actually written as follows:

protected async override void OnNavigatedTo(NavigationEventArgs e)
{
    await _restCaller.PublishHikeRequest();

    var driverIds = await _restCaller.GetDrivers();

    if (driverIds != null) 
        ShowDriversOnMap(driverIds);

    var hikerIds = await _restCaller.GetHikers();

    if (hikerIds != null) 
        ShowHikersOnMap(hikerIds);
}

The difference here is that I didn't use await on the calls to ShowDriversOnMap and ShowHikersOnMap. The reason for this is that while writing this code, I had made these two methods void. You are not allowed to use the await keyword on a void method.

private async void ShowDriversOnMap(List<Guid> driverIds)
{
    foreach (var driverId in driverIds)
    {
        var driver = await _restCaller.GetUser(driverId);
        var pushpin = new Pushpin();
        pushpin.Text = "D";
        pushpin.Tapped += async (s, args) =>
        {
            MessageDialog dialog = 
                new MessageDialog(string.Format("This is {0}.", driver.FullName));
            await dialog.ShowAsync();
            MessageDialog secondDialog = 
                new MessageDialog("I am shown only after the previous dialog finishes.");
            await secondDialog.ShowAsync();
        };

        MapLayer.SetPosition(pushpin, 
            new Location(driver.LatitudeFrom, driver.LongitudeFrom));
        MyMap.Children.Add(pushpin);
    }
}

The usage of void for these methods makes very much sense to me. You are just showing something on a UI, no need for these two methods to return anything, right? Well, indeed, right, but what I didn't expect was that the behavior of these void methods was completely different from the Task returning methods. That is, void methods behave as fire and forget methods. You can't even use await on them, that is why those keywords when calling these methods are missing, not because I forgot them, but because you're not even allowed to use them. Your compiler will complain if you do.

The behavior you get in this case, is that, while the drivers are being shown on the map, since this call is fire and forget, the processing already continues with fetching all the hikers and showing those on the map as well. So you actually get parallel behavior and not callback behavior. In the case of showing the drivers and hikers on the map simultaneously, this might not seem such a big of a problem, but I can imagine cases in which it does present a problem.

What is even a bigger problem is that for void methods you don't even have a clue that you are calling an async method. With Task and Task<T> returning methods you get a nice tooltip that says you are using an awaitable.


With void returning async methods, you get none of this. The tooltip just says it's a void method, you have no clue of the fire and forget behavior.


That is why, as far as async goes, it is recommended you always use Task or Task<T> returning methods, these ones give you callback behavior. The void returning methods are recommended for use only on event handlers.

If using Task returning methods, you can also get parallel behavior. For this, you can use the WhenAll method on the Task class.


protected async override void OnNavigatedTo(NavigationEventArgs e)
{
    await _restCaller.PublishHikeRequest();

    var driverIds = await _restCaller.GetDrivers();

    var hikerIds = await _restCaller.GetHikers();

    var showDriversTask = ShowDriversOnMap(driverIds);

    var showHikersTask = ShowHikersOnMap(hikerIds);

    Task.WhenAll(showDriversTask, showHikersTask);
}

Both tasks will be executed in parallel and execution of the rest of the method will continue when both tasks are finished. Another handy method on the Task class is the WhenAny method. It behaves more or less the same as WhenAll, but it continues with the rest of the method body as soon as one of tasks you give it as a parameter finishes.

Next post we will look at using async methods from JavaScript in WinRT.

Friday, May 4, 2012

Async IV: Progress Reporting

In the previous post, I already told you that progress reporting for asynchronous calls can be done by using the IProgress interface. This interface has a Report method with which you can report progress. You probably already saw me using the IProgress interface in the previous post, but now let's explain what actually happens.


protected async override void OnNavigatedTo(NavigationEventArgs e)
{
    cts = new CancellationTokenSource();

    try
    {
        await _restCaller.PublishHikeRequest(cts.Token);

        var driverIds = await _restCaller.GetDrivers(cts.Token);

        if (driverIds != null)
            await ShowDriversOnMap(driverIds, cts.Token,
                new Progress<int>(p => statusText.Text = string.Format("{0} of {1}", p, driverIds.Count)));

        var hikerIds = await _restCaller.GetHikers(cts.Token);

        if (hikerIds != null)
            await ShowHikersOnMap(hikerIds, cts.Token);

    }
    catch (OperationCanceledException exc)
    {
        statusText.Text = exc.Message;
    }
}

The Progress class is an implementation of the IProgress interface. The integer generic type parameter I send along is the type of progress I want reported. In this case I just want an integer value, but you can even have progress reported in a type you have specially defined for this purpous. The constructor of the Progress class takes in a lambda expression for the progress reporting. In this case I just show the number of drivers already shown on the map in the text of a TextBox.

The reporting of progress itself is done in the ShowDriversOnMap method.

private async Task ShowDriversOnMap(List<Guid> driverIds, CancellationToken token = default(CancellationToken), IProgress<int> progress = default(IProgress<int>))
{
    var count = 0;
    foreach (var driverId in driverIds)
    {
        if (progress != null && count % 10 == 0)
            progress.Report(count);

        var driver = await _restCaller.GetUser(driverId, token);
        var pushpin = new Pushpin();
        pushpin.Text = "D";
        pushpin.Foreground = new SolidColorBrush(Colors.Green);
        pushpin.Tapped += async (s, args) =>
        {
            MessageDialog dialog = new MessageDialog(string.Format("This is {0}.", driver.FullName));
            await dialog.ShowAsync();
        };
        MapLayer.SetPosition(pushpin, new Location(driver.LatitudeFrom, driver.LongitudeFrom));
        MyMap.Children.Add(pushpin);

        count++;
    }
}

I report progress in steps of 10. Since the IProgress in this case takes an int generic type parameter, I just send along an integer value to the Report method.

With the techniques you've seen so far (basics, exception handling, cancellation and progress reporting), you can get started with using async. In the next posts we will go some steps further, though, we will look at what void asynchronous methods do and start using async calls from JavaScript code. For this we will also create a WinMD library, which changes some things, both for defining asynchronous methods as for using them.

But before you move on to that, let me first give you a couple of pointers to watch out for.

Using the asynchronous features is made extremely easy for you. This implies that often you use them, without really thinking about what you are actually doing (hey, you're defining a callback, remember). I have found that once you start using async, you really need to think about how your users will be using your application. This implies thinking about cancellation, so you don't keep processing unnecessary calls.

Also, at the end of the day you end up with quite some async methods in your code. Since every time you use await, you need to make your method async. And whatever calls you method, must use await and be made async as well, and so on.

Thursday, May 3, 2012

Async III: Cancellation

The previous posts in this series talked about the basics of async and exception handling. In this post we will take a look at cancellation and the beginnings of progress reporting.

For cancellation you can make use of a CancellationToken. This is an extra parameter that can be send to an asynchronous method call, most asynchronous methods you find in the .NET framework provide an overload with cancellation. You can extend your own asynchronous methods as well to take in a CancellationToken.

For progress reporting the IProgress interface can be used. This interface defines a Report method that can be used to report progress from within an asynchronous method. Asynchronous calls again can define overloads that take in a IProgress interface.

Let's first take a look at cancellation.

protected async override void OnNavigatedTo(NavigationEventArgs e)
{
    cts = new CancellationTokenSource();

    try
    {
        await _restCaller.PublishHikeRequest(cts.Token);

        var driverIds = await _restCaller.GetDrivers(cts.Token);

        if (driverIds != null)
            await ShowDriversOnMap(driverIds, cts.Token,
                new Progress<int>(p => statusText.Text = string.Format("{0} of {1}", p, driverIds.Count)));

        var hikerIds = await _restCaller.GetHikers(cts.Token);

        if (hikerIds != null)
            await ShowHikersOnMap(hikerIds, cts.Token);

    }
    catch (OperationCanceledException exc)
    {
        statusText.Text = exc.Message;
    }
}

As you can see, I added a datamember cts of type CancellationTokenSource to my class. A CancellationTokenSource gives you a CancellationToken through its Token property. This token can be send along to all you asynchronous methods. Once the operation gets cancelled, each asynchronous method using the token will be notified of cancellation. The result of cancellation will be an OperationCanceledException that you can catch.

Cancelling an operation is as simple as calling Cancel on the CancellationTokenSource.

protected void Cancel_Click(object sender, RoutedEventArgs e)
{
    if (cts != null)
    {
        try
        {
            cts.Cancel();
        }
        catch (AggregateException exc)
        {
            exc.Handle((ex) => {
                return true;
            });
        }
    }
}

The AggregateException I catch here, is necessary since the REST calls in the RestCaller class tend to throw additional exceptions on cancellation (this only happens occasionally). I just swallow these kinds of exceptions, since they don't add any important information.

The nice thing about cancellation is that you can have it bubble down in your code. I create the CancellationToken in the top layer of my appllication, but it's send along to different methods, which again can send it to other asynchronous methods they call. For instance the GetDrivers method sends it along with its asynchronous REST call.

public async Task<List<Guid>> GetDrivers(CancellationToken token = default(CancellationToken))
{
    List<Guid> drivers = null;

    try
    {
        var client = new HttpClient();
        var request = new HttpRequestMessage();
        request.Headers.Add("Accept", MESSAGE_TYPE);
        request.RequestUri = new Uri(string.Format("{0}/Hiker/{1}/DriverIdsNearby", BASE_URL, MY_ID));
        var response = await client.SendAsync(request, token);
        response.EnsureSuccessStatusCode();
        var content = await response.Content.ReadAsStringAsync();
        drivers = await JsonConvert.DeserializeObjectAsync<List<Guid>>(content);
    }
    catch (HttpRequestException exc)
    {
        var dialog = new MessageDialog(exc.Message);
        dialog.ShowAsync();
    }

    return drivers;
}


This makes it very easy to cancel something. Whatever your code is executing at the moment, it gets cancelled.

In the next post we will look at progress reporting.

Wednesday, May 2, 2012

Async II: Exception Handling

In the previous blog post, we looked at the basics of async. In this post, we will look at exception handling. You need exception handling the moment something goes wrong in an asynchronous call. When this happens, the Task that comes out of the asynchronous call will have an error status and you won't be able to get the result from the method.

Handling these kinds of error situations is actually really simple. The only thing you need to do is wrap your asynchronous call in a try - catch statement, just like you would do with synchronous code. Let's take a look at an example:

public async Task PublishHikeRequest()
{
    var hikeRequest = GetHikeRequest();

    try
    {
        var client = new HttpClient();

        var url = string.Format("{0}/HikeRequest", BASE_URL);
        var response = await client.PostAsync(url, await BuildJsonContent(hikeRequest));
        response.EnsureSuccessStatusCode();
    }
    catch (Exception exc)
    {
        var dialog = new MessageDialog(exc.Message);
        dialog.ShowAsync();
    }
}

This method can be found in the RestCaller class, the one that's being used in the OnNavigatedTo from the previous blog post. In this method we post a message to a REST service in an asynchronous way. There are a couple of points where this code can give us error situations. The REST service can be down or for some reason our Json message can't be build as expected. For this we use a try catch clause to wrap the asynchronous calls.

Simpler than this, they can't make it for you. I just want to point out one more thing. Don't do as I did and show a MessageDialog in your catch clause. I just put it there for demoing purposes, but it can really bite you in the butt. Let me explain: If the REST service is down, it will take a while for the timeout of the call, giving a HttpRequestException, to kick in (this is about one minute). By this time, it is very well possible that the user of your application has already performed 10 other actions. The MessageDialog will only get him confused, because it's a reaction to an action he performed a minute ago. For this it is important that you know how to cancel actions that were kicked off, but are no longer relevant in the current user context.

That is why, in the next blog post, we will look at cancellation (and progress reporting).

And just another small thought on asynchronous calls I want to add. After the Visug session I got a question asking if you don't need to keep track of your background threads and if in the PublishHikeRequest method I can do stuff with my UI (for instance alter text in a TextBox). The answer is: yes you can. Your code actually executes synchronously until you get an await. This means all code in PublishHikeRequest is synchronous up until the PostAsync call. This is a framework call that actually does some stuff with threadpools or async I/O. But we don't need to worry about that. All of our code is still synchronous. And the callback that is being build for us, with the rest of our message body, will again be called on the UI thread. So, to sum up, nothing to worry about, go ahead and alter the text of that TextBox.

Monday, April 30, 2012

Async I: The Basics

In the recent talk I gave for Visug, we looked at the new async capabilities in the next version of the .NET Framework. The slides of this session can be found here. In this series of posts, I would like to walk you through the different demo's I showed during this talk.

The demo's were actually a rewrite of an existing application, the Blitzhiker application, we've developed for Windows Phone. The rewrite is a port of this application to the Windows 8 runtime.

The Blitzhiker application itself tries to bring hikers (people looking for a ride) and drivers (people with a car) closer together.


Hikers can publish hikerequests and get an overview of drivers and other hikers nearby. Below you can see a screen shot after a hiker has published his request. A Bing map is shown with pushpins for each driver nearby. Since all calls are done asynchronously, the entire user interface stays responsive while pushpins are shown on the map.



First thing we will take a look at, is the basics of asynchronous calls. What makes up an asynchronous call and how does it affect the execution of your program.

The code to publish the hikerequest, show the drivers on the map and after that show the hikers on the map, looks like this:

protected async override void OnNavigatedTo(NavigationEventArgs e)
{
    await _restCaller.PublishHikeRequest();

    var driverIds = await _restCaller.GetDrivers();

    if (driverIds != null) 
        await ShowDriversOnMap(driverIds);

    var hikerIds = await _restCaller.GetHikers();

    if (hikerIds != null) 
        await ShowHikersOnMap(hikerIds);
}

What happens is that we publish a hikerequest, after that, ask for all of the drivers on our route, next, show these guys on our map, then, get all of the hikers near us and show these on the map as well. The ShowDriversOnMap is a call that usually takes some time when there are a lot of drivers nearby. What we notice though is, that while showing the drivers, the entire application stays responsive, which is actually what we want from asynchronous calls.

You can spot the use of several awaits in the OnNavigatedTo method. What happens is that an await kicks of the execution of an asynchronous method and turns the rest of your method body into a callback. So in this piece of code several callbacks will be created at compile time, without you needing to mess up your code for this, you can keep on writing as if you are writing synchronous code.

What is also interesting about awaiting code this way, is that each callback will be executed in the same execution context that kicked of the asynchronous call. So, if you were on a UI thread, your callback will be executed on the UI thread. No need for Dispatcher.Invoke!

You probably noticed as well the use of the async keyword. This tells the compiler that the current method contains asynchronous calls and that there will probably need to be some extra compiler effort to create the necessary callbacks. Once you use the await keyword in a method, you need to put the async keyword in the method header. If you don't, your code won't compile. An async method can either have a void return type (as is the case in our piece of code) or can have a Task or Task<T> return type. Let's take a look at the ShowDriversOnMap method, which has a Task return type.

private async Task ShowDriversOnMap(List&lt;Guid> driverIds)
{
    foreach (var driverId in driverIds)
    {
        var driver = await _restCaller.GetUser(driverId);
        var pushpin = new Pushpin();
        pushpin.Text = "D";
        pushpin.Tapped += async (s, args) =>
        {
            MessageDialog dialog = 
                new MessageDialog(string.Format("This is {0}.", driver.FullName));
            await dialog.ShowAsync();
            MessageDialog secondDialog = 
                new MessageDialog("I am shown only after the previous dialog finishes.");
            await secondDialog.ShowAsync();
        };

        MapLayer.SetPosition(pushpin, 
            new Location(driver.LatitudeFrom, driver.LongitudeFrom));
        MyMap.Children.Add(pushpin);
    }
}

Again the await keyword is used, kicking of an asynchronous method and automatically turning the rest of the method body into a callback. You can also spot the use of the await keyword inside of a lambda expression. In WinRT there is no more DialogBox, but a MessageDialog. This one doesn't have a Show method, but a ShowAsync method, so, again, you can use await on this. Once you do this, you need to mark the lambda expression with the async keyword as well. I actually show 2 MessageDialogs with an await keyword. If you would set breakpoints in this lambda, you would spot the first dialog being shown and your code not starting to create the second dialog until you close the first one. That's the callback kicking in.

That's it for the basics of asynchronous calls. In a next post, we will go into exception handling and take a look at the RestCaller class that is being used in the code examples of this blog post.

Sunday, March 4, 2012

Adding navigation to WinRT JavaScript

In the previous post we looked at the anatomy of a basic WinRT JavaScript navigation application. In this post we will add 2 additional pages and navigate between them. I will use the same fragment navigation as used in default.html and homePage.html.

First thing I'll do - just to spare me some typing work - is make two copies of homePage.html and call these page2.html and page3.html. Next, I'll alter the default content of homePage.html (there where it says 'content goes here') and replace it with two link tags. I'll add the same content to page2 and 3 as well, so as to easily navigate between all three pages.

<section role="main" aria-label="Main content">
    <p>
        <div>Navigate to: &lt;/div>
        <div>
            <a href="page2.html">Page 2</a>
            <a href="page3.html">Page 3</a>
        </div>
    </p>
</section>

When you try this out, you can actually navigate to page2 and 3. That wasn't too hard to do, now was it. Only downside with this app is, that the back button is not functioning (it stays disabled both on page2 and page3). The appbar as well is not popping up when you click your right mouse button. Also, when you look at it, the contents of pages 2 and 3 are not shown right, they are shown too far to the left. Obviously we need to add some extra code to fix all this.

So I started to play around with this little application, to see what could be done to get it functioning correctly. First thing I did, was add some breakpoints to the default.js file's navigated function. This showed me that, when clicking the page2 or page3 link, the navigated event was not being hit. Apparently, using a simple a tag with an href attribute doesn't trigger navigation. This had to be done some other way then.

For this I added some extra code to the homePage.js file.

function fragmentLoad(elements, options) {
    WinJS.UI.processAll(elements)
        .then(function () {
            // TODO: Initialize the fragment here.
            var page2Nav = document.getElementById('page2Nav');
            if (page2Nav) {
                page2Nav.addEventListener('click', function () {
                    WinJS.Navigation.navigate('/html/page2.html');
                }, false);
            }
        });
}

The fragmentLoad function is called when the homePage gets loaded. When this happens, we get hold of the page2Nav element (I added an id to the link element). If we find this element, we add an eventlistener for its click event. When clicked, we should navigate to page2.html. A similar piece of code can be added to navigate to page3.

After adding this, you will notice that after you click the page2 link, the navigated event in default.js is being hit. That's what we wanted. But wait, as it gets hit, the application doesn't find our back button, its value stays null. That's not right, it should be able to find the back button.

The thing that's wrong here is the fact I added an href to my a tags. If you remove this and let WinJS just handle all of the navigation, you will see the back button is being found. Now, if you land on page2, the back button can be used to navigate back to the homePage. Even the appbar is functioning as expected.

As cool as this is (hey, I can navigate), the downside of using these techniques is that you get an awfully big buy-in into the WinRT way of building apps. When you choose to develop your applications with HTML5 and JavaScript, I think one of the reasons for your choice is portability, the fact that you can take this same code and run it on a different machine with minimal effort. That is why you should think twice when using WinRT functionality. Or, you'd better start writing wrappers for platform specific libraries. But than still ... Hey, I can navigate.

Saturday, March 3, 2012

Navigating with WinRT JavaScript

I am currently playing around with WinRT JavaScript applications. Starting out with a navigation application written from scratch, just to find out how it all fits together. The MSDN library is actually quite scarce when it comes to resources on WinRT. They give you the overall picture of how Metro style apps work, but, for JavaScript applications, the actual information is a bit meager. So I thought it would be nice to dissect a Metro style navigation app and see what code you need to get it up and running. Also beware that the information I will be giving here is based on the first developer preview of Windows 8 and Visual Studio 2011 Express Edition. Things are still very likely to change in the next couple of months.

What I did, was create two Metro style JavaScript applications, one based on a blank project template and one based on the navigation application project template. Let's first see what the navigation application gives us.



When you look at the project of the navigation application, you will see it gives you a couple of predefined html, JavaScript and css files. There are two html files present, a default.html and a homepage.html file. First let's take a look at the homepage.html file. In the head section it includes the JavaScript files you find in the solution, so nothing new or fancy there. In the body there is a div defined with content.

<!-- The content that will be loaded and displayed. -->
<div class="fragment homePage">
    <header role="banner" aria-label="Header content">
        <button disabled class="win-backbutton" aria-label="Back">&lt;/button>
        <div class="titleArea">
            <h1 class="pageTitle win-title">Welcome to NavApp!&lt;/h1>
        </div>
    </header>
    <section role="main" aria-label="Main content">
        <p>Content goes here.&lt;/p>
    </section>
</div>

The main div has a couple of classes defined on it, fragment and homePage. The fragment class we will come back to later on, when we take a look at the JavaScript files of the project. Just remember that it's there on the main div of the homepage.

Within the main div there is a header tag defined. This shows that WinRT JavaScript applications make use of new HTML5 features. The header tag has a role attribute, with a value of banner. There is also a role defined on the section tag a bit further down the homepage, with a value of main. These role attributes are primarily used as selectors in the css and JavaScript files. There is no real functionality associated with them.

The last peculiar attribute values can be found on the button and the h1 tags. Their classes are set to win-backbutton and to win-title respectively. With WinRT JavaScript applications you will find there are a lot of these win-something attribute values. You would think these give you out of the box functionality. Well, they don't. You will find that all magic is really just JavaScript doing it's thing. Those win-something attributes again, are just selectors for the css and JavaScript files. When you run the appication, you will see that the win-backbutton is actually an arrow with a circle around it. That's just plain css:

.win-backbutton::before
{
    font-family: "Segoe UI Symbol";
    content: "\E0D5";
    vertical-align: 50%;
}

So, let's take a look at the default.html page. The header again is just JavaScript and css file includes. The body is more interesting.

<body data-homePage="/html/homePage.html">
    <div id="contentHost">&lt;/div>
    <div id="appbar" data-win-control="WinJS.UI.AppBar" aria-label="Command Bar" data-win-options="{position:'bottom', transient:true, autoHide:0, lightDismiss:false}">
        <div class="win-left">
            <button id="home" class="win-command">
                <span class="win-commandicon win-large">&#xE10F;&lt;/span>&lt;span class="win-label">Home&lt;/span>
            </button>
        </div>
    </div>
</body>

There is a data-homePage attribute on the body tag and it is set to our homePage.htm file. You will also find a contentHost and appbar div. The contentHost makes you suspect that the default.html page is actually the start page of your application and that other html pages will actually be loaded as fragment into it. That is indeed the case here. But then, why, as you run the application, don't I see the appbar that is defined at the bottom. You do get to see all the content of the homePage, but the appbar is nowhere in site. The reason is that, to see the appbar, you need to swipe up, or, if that doesn't work on your device, perform a right mouse click. There's the appbar for you.


So, where does all the magic happen? In the JavaScript files of course. Let's first take a look at the default.js file. There are a couple of functions defined here. Let's not start at the top, but at the bottom.

WinJS.Navigation.addEventListener('navigated', navigated);
WinJS.Application.start();

An eventlistener for the navigated event gets added and the application is started. That's simple, right. Right above these two statements we find the handler for activating the mainwindow.

WinJS.Application.onmainwindowactivated = function (e) {
    if (e.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
        homePage = document.body.getAttribute('data-homePage');

        document.body.addEventListener('keyup', function (e) {
            if (e.altKey) {
                if (e.keyCode === WinJS.Utilities.Key.leftArrow) {
                    WinJS.Navigation.back();
                }
                else if (e.keyCode === WinJS.Utilities.Key.rightArrow) {
                    WinJS.Navigation.forward();
                }
            }
        }, false);

        WinJS.UI.process(document.getElementById('appbar'))
            .then(function () {
                document.getElementById('home').addEventListener('click', navigateHome, false);
            });

        WinJS.Navigation.navigate(homePage);
    }
}

This code says as much as, when we launch the application, do the following things:
  • Our homepage is set to the attribute value of the data-homePage attribute of the body element.
  • If a user presses the alt key and the left or right button, navigate forward and backward. 
  • Find the appbar and attach a click handler to the home element. The navigateHome function is defined at the top of the JavaScript file and contains pretty straightforward code.
  • And last, but not least, navigate to the homePage.
Right abobe this function, you will find another function definition. 

function navigated(e) {
    WinJS.UI.Fragments.clone(e.detail.location, e.detail.state)
        .then(function (frag) {
            var host = document.getElementById('contentHost');
            host.innerHTML = '';
            host.appendChild(frag);
            document.body.focus();

            var backButton = document.querySelector('header[role=banner] .win-backbutton');
            if (backButton) {
                backButton.addEventListener('click', function () {
                    WinJS.Navigation.back();
                }, false);
                if (WinJS.Navigation.canGoBack) {
                    backButton.removeAttribute('disabled');
                }
                else {
                    backButton.setAttribute('disabled', 'true');
                }
            }
            WinJS.Application.queueEvent({ type: 'fragmentappended', location: e.detail.location, fragment: host, state: e.detail.state });
        });
}

This tells us what happens when we navigate (remember, the previous function actually navigated to the homePage, so this gets called at the start of the application).

  • It clones the current fragment state (I am guessing this remembers where we are coming from and in what state the page is at the moment).
  • And, hey, next bit is some asynchrony. After the cloning is done, a function gets executed for the fragment.
  • It finds the contentHost on the default.html page and appends the fragment to it. There you have masterview (default.html)- detailview (homePage.html) behavior.
  • The backbutton also gets some extra functionality. Based on the fact whether we can go back or not, the button gets disabled or enabled and the click handlers get attached.
  • Last bit is queuing the fact that the fragment got appended, so the WinRT runtime can do its thing.
On the one hand, that's all simple JavaScript code. On the other hand, if you are used to working with the regular .NET languages, this seems like quite some code you need to write for some basic functionality. 

Let's find out, in a next post, what we need to do to navigate to a new page in our application.