Thursday, November 1, 2012

Unit Testing a Windows 8 Application

I am a big fan of test driving an application. That's why I write almost no code without writing a test for it.

I recently began writing a Windows Store application for Windows 8 and again wanted to test drive this app.   If you look at MSDN at how to add a test project to you Windows 8 app, you will see, you can add a Windows Store test project to your solution. Now, handy as this is, the down sight is that this test project is as well a Windows Store project type, meaning you won't be able to add a whole bunch of references to it. I wasn't able to add RhinoMock or Moq to it, nor was I able to add MSpec. The problem being these frameworks were build to the wrong version of the .Net framework.

Now, I could have made my own builds of the frameworks I am happy working with, but I started looking if there is no other way, like using a simple class library for unit testing a Windows Store app. Now, when you try this, the problem is, you can't get a reference of your Windows Store app added to your class library for testing.

To get this fixed, I tried out a couple of things. First I tried adding the same references to my class library project as were in the Unit Test Library for Windows Store apps. This didn't work, however. Also, I couldn't find the '.NET for Windows Store apps' reference dll. I also tried playing around with the output type of my project. Changing it to something different than class library. But then again, adding the necessary unit testing references became a problem. I also played around with the conditional compilation symbols (hey, I was trying to find where the differences lay between my own class library and a Unit Test Library for Windows Store apps).

After trying all that, I unloaded my project from solution explorer and started editing it, comparing it to the Unit Test Library for Windows Store apps and trying out different combinations. Now, after a couple of tries, the setting in your project file, you need is the following:

<Import Project="$(MSBuildExtensionsPath)\Microsoft\WindowsXaml\v$(VisualStudioVersion)\Microsoft.Windows.UI.Xaml.CSharp.targets" />

You can put this line as a replacement of the other csharp.targets file at the bottom of your project file. Once you have added this, you can add a reference of your Windows Store app to your class library. You will even see the '.NET for Windows Store apps' reference show up in your references. You will even be able to add all the additional references you want, like NUnit, Moq or RhinoMock, ...

One additional problem I had was with the System.Data dll, which was build to a different framework. Since I didn't need it in my test project, I happily removed it.


Monday, September 3, 2012

WCF on IIS and Windows 8

Just spend some time getting a simple WCF service up and running under IIS on my Windows 8 machine. Apparently, if you install IIS after installing the last .NET framework (ie. installing Visual Studio 2012), not all necessary handlers, adapters and protocols for WCF are installed on your IIS.

First time I tried to reach the WCF service it gave me an error that said 'The page you are requesting cannot be served because of the extension configuration.' This means you need to run Servicemodelreg.exe to reregister WCF (same kind of registration you needed from time to time for ASP .NET on previous versions of IIS, remember aspnet_regiis). You can find this tool at C:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation for version 3.0 or at C:\Windows\Microsoft.NET\Framework\v4.0.30319 for version 4.0.

Now looking at the MSDN site, they will tell you to run the 3.0 version. After doing so, however, you won't have the necessary handlers installed for a WCF service created with Visual Studio 2012, since they are all version 4.0. So that won't work.

Running the 4.0 version however won't work either. If you try Servicemodelreg.exe -i it will tell you to register with the -c option (register a component). If you try the -i -c option you will get the error (and the solution!) that this tool cannot be used on this version of windows. What you can use, though, is the 'Turn Windows Features On/Off' dialog.

So simply open this up from your control panel (I pinned my control panel to my start page on day one of installing Windows 8, otherwise I wouldn't be able to find it again) and check the necessary WCF features you want to have available on your WCF. In most cases, just flagging HTTP will do. You can find the WCF features under .NET Framework 4.5 Advanced Services.


And that's what you need to get yuor WCF service running under IIS on Windows 8. Hope this was helpful.

Addendum: This fix recently also solved the issue of a 'HTTP Error 400. The request hostname is invalid' error of a colleague when trying to run a WCF service on Windows 8.

Saturday, July 14, 2012

Knockout an MVC Ajax call

I recently needed to build an Ajax data search, showing the result of the search in an MVC web page. Great opportunity, I thought, to give Knockout.js a try. Knockout.js lets you apply databindings to a web page and for this it uses an MVVM (Model View ViewModel) approach.

On the knockout site, you can find some great examples to get started, even give it a try in jsFiddle. But since my solution is a bit different from their tutorials, I wanted to share it with you.

The actual problem at hand was a page on which I needed to link a scanned in document to a dossier. Most of the times the number of the dossier can be picked up from the scanned in document, but this is not always the case. In case where the number of the dossier can't be determined from the scan, we want our users to go look for the dossier and link the dossier manually to the scanned in document.


The page to do this more or less looks like this (I rebuild the solution without most of the formatting we have in the initial application).



The initial setup for this contains a ScanController that gives you this Scan Detail page.

public class ScanController : Controller
{
        public ActionResult Detail(int id)
        {
            var scan = new Scan
                        {
                            Id = id,
                            File = "This is the file",
                            DossierId = 0,
                            DossierNumber = string.Empty
                        };
            return View(new ScanViewModel(scan, new Dossier()));
        }
}

This uses the Detail view, which consists of two divs for the accordion. The top div looks like this:

@using (Html.BeginForm("Link", "Scan"))
{
  &lt;div>
    &lt;fieldset>
      &lt;dl>
        &lt;h2>Scan info&lt;/h2>
        @Html.Label("Receipt date") 
        @Html.TextBox("receiptdate", string.Empty, new { @class = "date"  })                
      &lt;/dl>
      &lt;h2>Dossier info&lt;/h2>
      &lt;div>
        @Html.Hidden("file", Model.Scan.File)

        &lt;div id="linkDiv" @(Model.Scan.DossierId == 0 ? "class=hidden" : "")>
          &lt;div>Dossier: &lt;span id="dossierNumberText">@Model.Scan.DossierNumber&lt;/span>&lt;/div>
          @Html.Hidden("dossierNumber", Model.Scan.DossierNumber)
          &lt;input type="submit" value="Link Scan to this dossier"/>
        &lt;/div>
        &lt;div id="message" @(Model.Scan.DossierId == 0 ? "": "class=hidden")>
          There is no dossier to link to. You should search for one.
        &lt;/div>
      &lt;/div>
  &lt;/fieldset>
  &lt;/div>      
}

The bottom div looks like this:


&lt;div id="search">
    @using(Html.BeginForm("Search", "Dossier", FormMethod.Post, new { @id = "dossierForm" }))
    {
        &lt;fieldset>
            &lt;dl>
                @Html.LabelFor(m => m.Dossier.DossierNumber) 
                @Html.TextBoxFor(m => m.Dossier.DossierNumber)
            &lt;/dl>
            &lt;dl>
                @Html.LabelFor(m => m.Dossier.OwnerLastName) 
                @Html.TextBoxFor(m => m.Dossier.OwnerLastName)
            &lt;/dl>
            &lt;dl>
                @Html.LabelFor(m => m.Dossier.OwnerFirstName) 
                @Html.TextBoxFor(m => m.Dossier.OwnerFirstName)
            &lt;/dl>
            &lt;dl>
                &lt;input type="submit" value="Search"/>
            &lt;/dl>
        &lt;/fieldset>
    }
&lt;/div>
&lt;div id="searchResult" class="hidden">
    &lt;table id="resultTable">
        &lt;thead>
            &lt;th>DossierNumber&lt;/th>
            &lt;th>OwnerLastName&lt;/th>
            &lt;th>OwnerFirstName&lt;/th>
            &lt;th>Detail&lt;/th>
            &lt;th>Link&lt;/th>
        &lt;/thead>
        &lt;tbody>
                    
        &lt;/tbody>
    &lt;/table>
&lt;/div>

It's this bottom div that we are most interested in. The top form (Search Dossier) will be used to perform an Ajax search. The result of this search will have to be shown in the table of the bottom searchResult div.

For this search I already added a Dossier controller with a Search action:

public class DossierController : Controller
{
  public ActionResult Search(DossierSearchViewModel searchVm)
  {
    return Json(new
                  {
                    Success = true,
                    Message = "All's ok",
                    Data = new List&lt;Dossier>
                            {
                              new Dossier
                                  {
                                    DossierNumber = "123abc",
                                    OwnerFirstName = "John",
                                    OwnerLastName = "Doe"
                                   },
                              new Dossier
                                  {
                                    DossierNumber = "456def",
                                    OwnerFirstName = "Jeff",
                                    OwnerLastName = "Smith"
                                  },
                              new Dossier
                                  {
                                    DossierNumber = "789ghi",
                                    OwnerFirstName = "Peter",
                                    OwnerLastName = "Jackson"
                                  },
                              new Dossier
                                  {
                                    DossierNumber = "321jkl",
                                    OwnerFirstName = "Carl",
                                    OwnerLastName = "Turner"
                                  },
                             }
                   });
  }
}

If you click the Search button you will be get to see the Json result in the Dossier/Search page. This is not what we want, this form should perform an asynchronous Ajax post. That's not yet the case. For this I used the JQuery forms plugin. Which has a handy ajaxForm method you can add to your form. (you could also use the mvc ajax extensions for this, they should already be in your initial MVC setup).

&lt;script type="text/javascript">
    $(function () {
        $("#dossierForm").ajaxForm({
            success: render_dossier_grid
        });
    });

    function render_dossier_grid(ctx) {
    }
&lt;/script>

All of the knockout magic can now be added in the render_dossier_grid function. Before we can do this, make sure to add the knockout.js files to your solution. This can be easily done using nuget. Reference them in your _layout file, so you can use them.

First, let's create a viewmodel. This will be nothing more than a list of dossiers we get back from our dossier search. Since we want to be able to add and remove items from this list and at the same time have our table automatically show the new items, we will use a knockout observable array. To have the databindings applied to your view, you should call applyBindings for your viewmodel.

$(function () {
    $("#dossierForm").ajaxForm({
        success: render_dossier_grid
    });

    ko.applyBindings(viewModel);
});

function render_dossier_grid(ctx) {
}

var viewModel = {
    dossiers: ko.observableArray([])
};

This viewModel can now be filled when we get the result of our Ajax call.

function render_dossier_grid(ctx) {
    $("#searchResult").removeClass("hidden");
    viewModel.dossiers.removeAll();
    viewModel.dossiers(ctx.Data);
    myAccordion.accordion("resize");
}

That's pretty easy. I just reset the dossiers observable array of the viewmodel and add the dossiers that come from the Ajax call. Last bit is having the JQuery accordion control perform a resize, just to get rid of any scroll bars.

Next step is actually binding this viewmodel to something. So, we need to specify in our view what data needs to go where. For this we will extend the table we have on our page.

&lt;table id="resultTable">
    &lt;thead>
        &lt;th>DossierNumber&lt;/th>
        &lt;th>OwnerLastName&lt;/th>
        &lt;th>OwnerFirstName&lt;/th>
        &lt;th>Detail&lt;/th>
        &lt;th>Link&lt;/th>
    &lt;/thead>
    &lt;tbody data-bind="foreach:dossiers">
        &lt;tr>
            &lt;td data-bind="text:DossierNumber">&lt;/td>
            &lt;td data-bind="text:OwnerLastName">&lt;/td>
            &lt;td data-bind="text:OwnerFirstName">&lt;/td>
            &lt;td>
                &lt;a data-bind="attr: {href: DetailLink}">Detail&lt;/a>
            &lt;/td>
            &lt;td>
                &lt;a href="#" data-bind="click: $parent.useDossier">Use this file for linking&lt;/a>
            &lt;/td>
        &lt;/tr>
    &lt;/tbody>
&lt;/table>

Adding the databindings is not that hard. I added a foreach binding, which will make a new table row for each dossier in the dossiers observable array. Each table row has its own binding for each td element. The first three are quite obvious. You can databind to the names of the properties of your domain (or MVC viewmodel) object.

For the second to last binding I added a databinding to the href attribute of an a tag. The DetailLink is a property on the Dossier domain object that gives you a link to Dossier/Detail/id.

The last one is a special binding to the click event of an a tag. It is bound to the useDossier function of the parent of the binding. The parent of our binding is the actual viewmodel. We still need to add this useDossier function:

var viewModel = {
    dossiers: ko.observableArray([]),

    useDossier: function (dossierVM) {
        var dossierNumber = dossierVM.DossierNumber;
        myAccordion.accordion({ active: 0 });
        $("#dossierNumber").val(dossierNumber);
        $("#dossierNumberText").text(dossierNumber);

        $("#linkDiv").removeClass('hidden');
        $("#message").addClass('hidden');
    }
};

In this function I use the viewmodel. In this case this is the actual row/dossier of the table. I take the DossierNumber of the current dossier and use it to set the value of the dossierNumber and dossierNumberText fields in the top piece of the accordion. I also do some extra bits to update the UI accordingly.

That's it, not much to it. I really like this knockout framework. I did have some trouble to get started at first, but once you know your way around the viewmodel, it's pretty easy to use.

The full code can be found on github.

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&lt;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&lt;T> (as a replacement for Task&lt;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&lt;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&lt;UserModel> GetUserAsync(Guid userId)
{
    return (IAsyncOperation&lt;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 &lt; driverIds.length && i &lt; 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 &lt; driverIds.length && i &lt; 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.

Friday, April 13, 2012

JSON POST with ASP .NET Web API

I have been struggling a bit with porting existing Json calls to the new ASP .NET Web API framework. I actually got the GET request working pretty quickly, but it were the POST (and DELETE en PUT) requests that were giving me headaches. Problem is the current brevity and lack of practical examples for the Web API framework. So here goes a short example of getting a Json POST up and running.

For these examples I used the Visual Studio 2011 beta version.

Let's first start with the GET request. What you need for this is the HttpClient class, which can be found in the System.Net.Http namespace. This class provides methods like GetAsync, PutAsync, DeleteAsync and PostAsync. The 'Async' extensions let you know that you can use the new async and await keywords to get this up and running. A GET requests with the HttpClient consists of only two lines of code.

var client = new HttpClient();
var response = await client.GetAsync("http://some_url/resource_name/resource_id");
response.EnsureSuccessStatusCode();

All of this is contained in a method that has the extra async keyword. I also added the EnsureSuccessStatusCode call to verify my call to the REST service didn't fail. If the call fails the EnsureSuccessStatusCode will throw an exception. So you can easily wrap this piece of code in a try catch block.

So, that was quite easy. The GET call should work immediately.

On to the POST call. I actually want to post an object to our REST service. The previous version of the code I was porting to the Web API used the RestSharp (performs REST calls) and NewtonSoft.Json  (serializes from and to Json) frameworks to perform REST calls (both are available via NuGet). I started out reusing only NewtonSoft.Json, since the HttpClient class removes the need for the RestSharp framework. But is turned out I couldn't get the serialized Json object send to the service in a acceptable format. The service kept giving me 400 Bad Request messages. So I was doing something wrong.

After some searching I found there are a couple of different content class types you can use when performing a PostAsync. I used StringContent up untill then, but I needed a ObjectContent. The HttpRequestMessage class can create one for you. Moreover, the Web API contains its own Json formatters, so the need for the NewtonSoft library became obsolete.

var anObject = new MyObjectType
{
    SomeProperty = "some value"
};

try
{
    var client = new HttpClient(); 
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var requestMessage = new HttpRequestMessage();
    var content = requestMessage.CreateContent&lt;MyObjectType>(
        anObject,
        MediaTypeHeaderValue.Parse("application/json"),
        new MediaTypeFormatter[] { new JsonMediaTypeFormatter() },
        new FormatterSelector());

    var response = await client.PostAsync("http://some_url/resource_name", content);
    response.EnsureSuccessStatusCode();
}
catch (Exception exc)
{
    Console.WriteLine(exc.Message);
}


And there you have it, my first successful Json POST message.

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. 

Thursday, February 23, 2012

SvcUtil and Https

A service I need to use for data retrieval recently changed its endpoint definition. The service switched from an HTTP endpoint to an HTTPS endpoint. Since the interface of the service changed as well, I needed to regenerate the interface definitions used to connect to the service.

So, I got out my favourite wsdl tool, svcutil.exe and tried to regenerate the interface definitions as I had done millions of times before. Only to find that the https endpoint was holding me back.


As my command prompt couldn't accept or reject the server's SSL certificate, the wsdl file could not be downloaded.

As a solution for this, you can do the following: Fire up Fiddler and change it's options to decrypt HTTPS traffic. This will add a Fiddler certificate to your certificate store, which is just fine by me.


I did not check the 'Ignore server certificate errors' option, since I still want to know what's going on when some process is going to an HTTPS site.

After setting these options and while Fiddler was silently running in the background, I tried out the svcutil command again. This gave me one more pop up (since I did not check the certificate errors option).



And my classes got generated just fine.

Wednesday, February 22, 2012

Fitnesse, MSpec and SpecFlow

On one of my last projects, I started using Fitnesse tests, primarily to give the business the opportunity to specify their test cases. After playing around with these tests for about 4 days, I, however, threw them out. The main reason for this was the fact that I had to write a whole lot of complementary code to get the Fitnesse tests to run properly.

With Fitnesse, you first need to specify input and output data for your test case. This means edditing a web page with data and writing fixtures in code to process this data. This takes some getting used to and, in my opinion, requires quite some coding. I am also used to refactoring (and renaming) quite a bit during development. But sadly, your Fitnesse test cases don't get refactored, since they live in a separate web application. I also gave myself some extra work by switching over from the slim test runner to the fit test runner. Apparently if you do this, your previously written test fixtures aren't compatible anymore. Something I found very disturbing.

After 4 days of writing Fitnesse tests, I had about 3 test cases finished, I had only a small bit of business code and a huge headache. So, I threw them out.

Instead, I started using MSpec, or Machine Specifications. It is used to write business driven tests, or employ BDD in your code. Now, although MSpec is good for doing BDD, I have noticed it's not because you are using MSpec, that you are doing BDD. You can still write tests the way you used to with NUnit for instance. MSpec is actually just a semantic layer on top of that. But still, it makes it easier to move towards a BDD kinda style of programming.

I must say I really like the way in which you write you MSpec tests, although it does have some downsides and some bits take getting used to as well. I don't think the MSpec tests are always as readable as you would wish. On the one hand, it's nice they make use of lambda expressions a lot, on the other hand, the indentation on those lambdas is just plain awful. It does make you follow an AAA style of testing. Although with MSpec they don't call is Arrange, Act, Assert, but Establish, Because and It. That's just different naming, in essence it's the same thing, right. Another downside is, you can't give these tests to your business users to write them up. It's still developer testing.

This had me looking at SpecFlow, another framework I tried out a couple of weeks later. The test cases you write are more in a business kind of style. They are also easier to write by a business representative (with some additional explanation that is). Once you read the SpecFow documentation you would think you can only test web apps with it in combination with Selenium, but actually, I found it's dead easy to test plain business code with it as well. As with Fitnesse, your SpecFlow tests require you to write some additional code to link your test cases with the actual code, but the good thing is, SpecFlow helps you a lot with this. I used it in combination with my good friend ReSharper and found that this goes very smoothly. If I haven't written any code for a SpecFlow test case, ReSharper suggests a dummy implementation for it which you can copy paste and alter as much as you'd like. That's neat. Only downside I see for now is it's inability to use it for real technical tests. It's not technically impossible, but that's not what it was designed for. Your SpecFlow tests should always be backed up by technical NUnit test cases. That's why it's recommended that you read the Cucumber backgrounder on how to write test cases. The do's and dont's are pretty important here.

I'm actually still playing around with SpecFlow for now. MSpec has already proven it's worth, as did plain NUnit tests. But I think it would actually help a lot to write even more SpecFlow test cases in close communication with the business. I think this is a framework that can deliver.

Tuesday, February 7, 2012

Moving PostSharp to another project

I am currently using PostSharp to add logging and exception handling aspects (to name a few) to an application. PostSharp does this very well and my code has become quite a bit more readable thanks to it. PostSharp actually weaves in extra functionality during your build process. And it can be easily added to an existing project using a nuget package installer.

A recent change in the application however had me refactor out some of the classes I'd added aspects to, to another assembly in the same application. After the refactoring I also added the PostSharp dll to the new project and realized my aspects weren't added/weaved in during the build. This had me thinking, since I did add the PostSharp dll to the new project. After some searching, I found the source of the problem.

Since PostSharp adds extra functionality during your build, you'll need to tell your project (or the C# compile process, that is) to execute this extra PostSharp funcationality. The nuget package actually added this to my original project, but not to any other project in the same solution. So, to solve this, either rerun the nuget package installer on the other project, or, just as easy, add the following xml tag to your csproj file (somewhere at the bottom).

  <Import Project="..\packages\PostSharp.2.1.5.1\tools\PostSharp.targets" />

You get this explanation as well in your projects' properties. You will notice an extra PostSharp tab there, that is either enabled - if PostSharp is doing its' thing - or disabled - if it is not, which was the case for me.

Tuesday, January 10, 2012

SvcUtil and imports

Recently I had to generate a client proxy for a WCF service. As the service was being developed by another team and was running as a local service on their machines, the only thing they could give me to generate my client proxy were the generated wsdl and xsd files of the service. I had no access to the actual service.

So, I started up svcutil.exe and tried to generate the client proxy. This didn't work as expected, however. Since the wsdl file generated by WCF uses imported xsd files. When you run svcutil with access to the actual service, the tool automatically downloads the necessary extra xsd files for you. When, however, you don't have access to the WCF service, you need to specify the extra xsd files in your call to svcutil.

So the following call:

SvcUtil.exe /noconfig the_wsdl_file.xml

Which gives errors on wsdl:portType and wsdl:binding, can be changed to this:

SvcUtil.exe /noconfig the_wsdl_file.xml first_import.xsd second_import.xsd

And that second call works just fine. No errors, my client proxy got nicely generated.

Another must-know about svcutil is that when you want to have your list types generated as a generic list in stead off an array type, you need to use the following extra switch:

/collectionType:System.Collections.Generic.List`1

Beware of the quote there, it's a tricky one. And you do need the entire namespace as well or svcutil won't recognize the type.