All posts by Damian Schenkelman

Please read! Blog moved.

After more than 6 years working at Southworks I have decided to start a new adventure. I’ll provide more information about this soon in my new blog, where I’ll continue to write about code stuff.

The new blog uses the magic of Jekyll + Github Pages and is hosted at http://dschenkelman.github.io/ and the RSS feed is http://dschenkelman.github.io/feed.xml.

[Spanish] Desarrollo multi-plataforma con Visual Studio 2013 e introducción a Xamarin (en español)

For those who don’t read Spanish, this blog post provides details about the Visual Studio 2013 launch for Latin America, particulary a cross-platform development talk that included Xamarin.

El Miércoles 11 de Diciembre, en las oficinas de Microsoft Argentina, se realizó el lanzamiento de Visual Studio 2013. Las sesiones del mismo fueron filmadas para hacerlas disponibles a toda latinoamérica (aquí están las otras #1, #2). Junto con mis amigos Ariel Schapiro y Mariano Converti tuvimos la oportunidad de presentar una sesión relacionada con el desarrollo multi-plataforma.

pic

Durante la misma hicimos un repaso por los pasos por los que una aplicación multi-plataforma puede ir evolucionando, desde el uso de ASP.NET MVC con CSS media queries, pasando por opciones como PhoneGap o Titanium y llegando finalmente a una aplicación nativa.

En esta última parte realizamos una introducción bastante completa sobre Xamarin que me parece un recurso muy útil para la comunidad hispanoparlante (comienza en 25:11 para aquellos solo interesados en Xamarin). Algunos de los temas discutidos, entre diapositivas y varias demos, fueron los siguientes:

  1. Qué es Xamarin?
  2. Cuáles son sus beneficios?
  3. Cómo funciona?
  4. Cómo empezar a desarrollar una aplicación?
  5. Cuáles son las posibilidad y recomendaciones para compartir código?

Al final de la charla hubo una sesión de preguntas y respuestas en la cual hubo preguntas muy interesantes. Esperamos que les pueda ser útil en caso de estar comenzando a aprender sobre Xamarin.

scriptcs: Acceptance tests with XBehave.net

One of the challenges we face when merging pull requests in scriptcs is making sure all features are still working. Executing our unit tests for every pull request definitely helps as it helps catch many mistakes, but some others go unnoticed due to integration issues (different components, the file server, assembly versions).

Fortunately, scriptcs is something that can be easily tested as it does not have any external dependencies (other than NuGet) such as databases, web services, etc. That’s why we decided to create some acceptance tests.

An initial approach

Running scriptcs –install takes a packages.config in the current working directory and installs all the packages specified in it. The first attempt at testing this was the following one:

[gist id=8124109 file=InitialTest.cs]

The above sample uses XUnit, takes advantage of the Dispose method to do cleanup and verifies that the correct packages are installed. Nevertheless, we can take this for another spin to see if we can get a test that is even easier to read.

Enter XBehave

After making the above sample available through Twitter for feedback @glennblock brought XBehave into the table, which is being used in his (and other’s) Web API book:

From its GitHub site XBehave is A BDD/TDD framework based on xUnit .net and inspired by Gherkin. The goal of this blog post is not to explain how to use XBehave, but if you are interested this site has a quickstart page and some useful docs to get you started with it.

The nice thing about it, is that you can write a spec using plain text and then map that to actual code. For example, the spec for this feature could be something like this:

Given a current working directory
And a packages.config file located in the current directory
   When the packages are installed
       Then the program executes successfully
And a packages directory is created inside the working directory
And a directory for the package and each of its dependencies is created

The resulting test case is the following one:

[gist id=8124109 file=XBehaveTest.cs]

Benefits

The things I like better about the XBehave test are:

  1. The Teardown method is closer to the code that creates the items that must be cleaned up.
  2. Each line of code is placed within the related spec string. Before they could be anywhere, but having the strings in there helped me realized where it made better sense to put them.
  3. The scenario under test is easier to understand for everyone reading the test.

scriptcs: Reducing startup time by caching compiled .dlls

A couple of weeks ago we introduced a new scriptcs feature (available through the nightly builds) that allows you to execute your scripts, compile them to a .dll, and store it in a hidden folder for caching purposes. This greatly reduces start-up time (although there is still room for improvement) as we execute the .dll if it is available, thus avoiding some steps that we would need to perform otherwise.

We have created an article in the wiki that explains how the feature works and goes over some ideas for future improvements.

If you get the chance, please try the feature out as we would like to:

  • Get your feedback as to how you are using it to keep improving the experience
  • Know if there are any bugs/issues that you encounter

If you have any ideas go ahead and create a new issue.

Have fun scripting!!

Asynchronous I/O in C#: Why tasks (a.k.a. promises, futures)?

In previous posts I provided an introduction to asynchronous I/O in C#, and also dug a bit deeper into I/O completion ports, which is one of the possible mechanisms that the .NET frameworks uses to accomplish this.

In this blog post we are going to go over the benefits of using the Task abstraction to represent asynchronous operations. Before I get started, I recommend that if you have never watched this video you should go ahead and do it. Michael Jackson (@mjackson) and Domenic Denicola (@domenic) do a great job explaining the benefits of promises.

What are tasks?

A Task is an object oriented abstraction that represents an asynchronous operation. It does not carry any special connotation as to how that operation is being performed (see my previous post). The concept of task is similar to the concept of promise or future and, as a matter of fact, in the Parallel Extensions CTP the class’ original name was Future.

That being said, all of the operations for which the .NET framework now returns a Task used to always be available but were somewhat harder to use. Let’s look at a couple of examples so I can better express what I mean.

A walk through history lane (with examples)

In the following examples, let’s assume that our goal is to download HTML from a couple of URLs and once both downloads are done we need to do something with the HTML. What we are going to do is compare how the different proposals for asynchronous programming in .NET allow you to do this.

The source code for the samples can be found at GitHub. I have tried to make all samples look similar, which leads to a bit of code duplication, but I think that makes the comparisons simpler. Basically, all samples follow this model:

class Program
{
    public static AutoResetEvent ResetEvent = new AutoResetEvent(false);

    static void Main(string[] args)
    {
        // decide which asynchronous proposal to use
        Run(new ProgramWithAPM());
    }

    static void Run(IRunnable runnable)
    {
        runnable.Run();

        ResetEvent.WaitOne();

        Console.ReadLine();
    }
}

Asynchronous Programming Model (APM)

The first model that the Framework proposed for asynchronous programming was the asynchronous programming model.

As you can see in the code below, we need to add an extra variable to keep track of the amount of pending requests. Additionally, we need to add a lock object to avoid a race condition for downloads that complete at the same time (if you want to try it out just remove the lock and add a Thread.Sleep(10000) after decrementing the pending count). Imagine the work that you would need to do to add error handling…

class ProgramWithAPM : IRunnable
{
    private int pending;

    private readonly object lockObject;

    public ProgramWithAPM()
    {
        this.pending = 0;
        this.lockObject = new object();
    }

    public void Run()
    {
        var schenkelmanRequest = (HttpWebRequest)WebRequest.Create(new Uri("http://blogs.southworks.net/dschenkelman"));
        var convertiRequest = (HttpWebRequest)WebRequest.Create(new Uri("http://blogs.southworks.net/mconverti"));

        this.pending = 2;

        schenkelmanRequest.BeginGetResponse(ar =>
            {
                var response = (HttpWebResponse)schenkelmanRequest.EndGetResponse(ar);
                WriteContent(response);
            }, schenkelmanRequest);

        convertiRequest.BeginGetResponse(ar =>
            {
                var response = (HttpWebResponse)convertiRequest.EndGetResponse(ar);
                WriteContent(response);
            }, convertiRequest);
    }

    private void WriteContent(HttpWebResponse response)
    {
        using (var reader = new StreamReader(response.GetResponseStream()))
        {
            var content = reader.ReadToEnd();
            lock (this.lockObject)
            {
                Console.WriteLine(content.Substring(0, 300));
                this.pending--;

                if (this.pending == 0)
                {
                    Console.WriteLine("Downloads finished");
                    Program.ResetEvent.Set();
                }
            }
        }
    }
}

Event-based asynchronous pattern (EAP)

After APM came the event-based asynchronous pattern. It’s similar to the APM example, but instead of using callbacks and IAsyncResult it leverages events. An interesting addition to this model is the possibility of cancelling a particular asynchronous operation (not shown here, it is just part of the spec).

public class ProgramWithEvents : IRunnable
{
    private int pending;

    private readonly object lockObject;

    public ProgramWithEvents()
    {
        this.pending = 0;
        this.lockObject = new object();
    }

    public void Run()
    {
        var convertiClient = new WebClient();
        var schenkelmanClient = new WebClient();

        convertiClient.OpenReadCompleted += (sender, eventArgs) => this.WriteContent(eventArgs.Result);
        schenkelmanClient.OpenReadCompleted += (sender, eventArgs) => this.WriteContent(eventArgs.Result);

        this.pending = 2;

        schenkelmanClient.OpenReadAsync(new Uri("http://blogs.southworks.net/dschenkelman"));
        convertiClient.OpenReadAsync(new Uri("http://blogs.southworks.net/mconverti"));
    }

    private void WriteContent(Stream stream)
    {
        using (var reader = new StreamReader(stream))
        {
            var content = reader.ReadToEnd();

            lock (lockObject)
            {
                Console.WriteLine(content.Substring(0, 300));

                this.pending--;

                if (this.pending == 0)
                {
                    Console.WriteLine("Downloads finished");
                    Program.ResetEvent.Set();
                }
            }
        }
    }
}

Task-based asynchronous pattern (TPM)

Finally, we get to the task-based asynchronous pattern. The relevant parts here are:

  • The usage of the Task.WhenAll, which greatly reduces the amount of code required to get this working, but most importantly makes the intent clear.
  • The usage of ContinueWith, which allows you to provide code that does some work when a task finishes and returns a new task that will be completed when the work is done.

Note: I’m not using async/await as I want to focus on Tasks. In a future post, the relationship between tasks and async/await will be covered.

class ProgramWithTasks : IRunnable
{
    public void Run()
    {
        var client = new HttpClient();

        var convertiTask = client.GetStreamAsync(new Uri("http://blogs.southworks.net/mconverti")).ContinueWith(t =>
        {
            using (var reader = new StreamReader(t.Result))
            {
                var content = reader.ReadToEnd();
                Console.WriteLine(content.Substring(0, 300));
            }
        });

        var schenkelmanTask = client.GetStreamAsync(new Uri("http://blogs.southworks.net/dschenkelman")).ContinueWith(t =>
        {
            using (var reader = new StreamReader(t.Result))
            {
                var content = reader.ReadToEnd();
                Console.WriteLine(content.Substring(0, 300));
            }
        });

        Task.WhenAll(convertiTask, schenkelmanTask).ContinueWith(t =>
            {
                Console.WriteLine("Downloads finished");
                Program.ResetEvent.Set();
            });
    }
}

Abstracting APM and EAP with Tasks

As I stated at the beginning of the blog post, Tasks represent an abstraction for an asynchronous operation. For that reason, all other programming models can be abstracted using Tasks. I have created a couple of extension methods that do this exact thing. These methods are just meant as an example. If you are going to be doing this for real you should first make sure that the methods are not already implemented, and if that is that case use the TaskFactory class.

public static class TaskExtensions
{
    public static Task<Stream> GetResponseAsync(this HttpWebRequest webRequest)
    {
        var tcs = new TaskCompletionSource<Stream>();

        webRequest.BeginGetResponse(ar =>
        {
            var response = (HttpWebResponse)webRequest.EndGetResponse(ar);

            tcs.SetResult(response.GetResponseStream());
        }, webRequest);

        return tcs.Task;
    }

    public static Task<Stream> TaskBasedOpenReadAsync(this WebClient webClient, Uri uri)
    {
        var tcs = new TaskCompletionSource<Stream>();

        OpenReadCompletedEventHandler callback = null;

        callback = (sender, args) =>
            {
                tcs.SetResult(args.Result);
                webClient.OpenReadCompleted -= callback;
            };

        webClient.OpenReadCompleted += callback;

        webClient.OpenReadAsync(uri);

        return tcs.Task;
    }
}

With those extensions the APM example is greatly simplified (I won’t show the updated EAP sample, as it looks similar).

class ProgramWithAPM : IRunnable
{
    public void Run()
    {
        var schenkelmanRequest = (HttpWebRequest)WebRequest.Create(new Uri("http://blogs.southworks.net/dschenkelman"));
        var convertiRequest = (HttpWebRequest)WebRequest.Create(new Uri("http://blogs.southworks.net/mconverti"));

        var schenkelmanTask = schenkelmanRequest.CustomGetResponseStreamAsync().ContinueWith(t =>
        {
            using (var reader = new StreamReader(t.Result))
            {
                var content = reader.ReadToEnd();
                Console.WriteLine(content.Substring(0, 300));
            }
        });

        var convertiTask = convertiRequest.CustomGetResponseStreamAsync().ContinueWith(t =>
        {
            using (var reader = new StreamReader(t.Result))
            {
                var content = reader.ReadToEnd();
                Console.WriteLine(content.Substring(0, 300));
            }
        });

        Task.WhenAll(convertiTask, schenkelmanTask).ContinueWith(t =>
        {
            Console.WriteLine("Downloads finished");
            Program.ResetEvent.Set();
        });
    }
}

A final example: Cancellation

What if we wanted to only carry out work with only the first download that finishes (e.g.: useful when working against multiple CDNs) and also avoid performing unnecessary downloads? Then we have to find a way to execute code once the first Task completes and cancel the other one. The following code does just that (I’m not even going to bother doing this with the other models, it requires a lot more thinking). The key takeaways from the following code are:

  • The usage of the Task.WhenAny to execute the continuation when the task that finishes sooner completes.
  • Providing TaskContinuationOptions for the continuation.
  • Providing a cancellation Token for the download tasks and cancelling when the task that finishes sooner completes.
public class ProgramWithTasksAndCancellation : IRunnable
{
    public void Run()
    {
        var client = new HttpClient();

        var cts = new CancellationTokenSource();

        var convertiTask = client.GetAsync(new Uri("http://blogs.southworks.net/mconverti"), cts.Token);
        convertiTask.ContinueWith(t => Console.WriteLine("Converti completed"), TaskContinuationOptions.NotOnCanceled);

        var schenkelmanTask = client.GetAsync(new Uri("http://blogs.southworks.net/dschenkelman"), cts.Token);
        schenkelmanTask.ContinueWith(t => Console.WriteLine("Schenkelman completed"), TaskContinuationOptions.NotOnCanceled);

        Task.WhenAny(convertiTask, schenkelmanTask).ContinueWith(t =>
        {
            cts.Cancel();

            var firstTaskThatCompleted = (t.Result);

            firstTaskThatCompleted.Result.Content.ReadAsStringAsync().ContinueWith(t2 =>
                {
                    Console.WriteLine(t2.Result.Substring(0, 300));

                    Console.WriteLine("Downloads finished");
                    Program.ResetEvent.Set();
                });
        });
    }
}

Asynchronous I/O in C#: I/O Completion Ports

I finally got around to writing this blog post as I feel it has been a personal debt for some time now. After introducing async I/O in C#, I spent a lot of time thinking about how to write about the topic of this blog post so let’s jump right into it.

What are I/O completion ports?

As this article explains, an I/O Completion Port (IOCP from now on) is a queue-like operating system object that can be used to simultaneously manage multiple I/O operations. This is done by associating multiple file handles (not necessarily to a file, any asynchronous-able I/O endpoint) to a single IOCP and monitoring it for changes. Whenever an operation on any of the file handles completes, and I/O completion packet is queued into the IOCP.

I think the following picture does a better job at explaining the concept:

image

What do they have to do with asynchronous I/O in C#?

Underneath the covers, an asynchronous operation could be implemented in many different ways.

The important part about asynchrony is that it is relative to the caller.

That means that one possible alternative could be to actually spin up a new  orker thread and perform a blocking call in it. Although that might not be what we want in every scenario (we are blocking a worker thread, just not the caller’s thread) it is still asynchronous from a caller’s perspective.

Another alternative that some framework components implement is using IOCP together with completion port threads. I did not know about this before, but ThreadPool threads can be either worker threads or completion port threads (this is explained with detail in this article).  With this approach, the ThreadPool is in charge of monitoring IOCPs and dispatching tasks to completion port threads that are in charge of handling the completion of an operation (also shown in this article). How IOCP and the CLR interact is explained with more detail in Chapter 28 of CLR via C# 4th Edition.

image

Some of the benefits of using IOCP are:

  • All I/O operations can be registered to the same completion port object (simplifying the CLRs job).
  • We avoid blocking any of our own threads and ThreadPool worker threads.
  • We get automatic thread management, which minimizes context switching and gives our main thread more CPU time.

Show me some code…

The link to the working code is in the samples section (bottom of the post), but this is a high level overview of how you would work with a completion port.

The first thing to do is create one and store a handle to it.

// create completion port
var completionPortHandle = Interop.CreateIoCompletionPort(new IntPtr(-1), IntPtr.Zero, 0,  0);

After that, whenever you create a file handle for asynchronous I/O you associate it to the IOCP.

const uint Flags = 128 | (uint)1 << 30;

var fileHandle = Interop.CreateFile("test.txt", (uint)1 << 31, 0, IntPtr.Zero, 3,
    /*FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED */ Flags,
    IntPtr.Zero);

Interop.CreateIoCompletionPort(
    fileHandle,
    completionPortHandle,
    (uint)fileHandle.ToInt64(), 
    0);

Finally, whenever you perform an operation you must specify a callback and get a pointer to a NativeOverlapped* structure:

var readBuffer = new byte[1024];

uint bytesRead;

var overlapped = new Overlapped 
{
    AsyncResult = new FileReadAsyncResult()
    {
        ReadCallback = (bytesCount, buffer) =>
            {
                var contentRead = Encoding.UTF8.GetString(buffer, 0, (int)bytesCount);
            },
        Buffer = readBuffer
    } 
};

NativeOverlapped* nativeOverlapped = overlapped.UnsafePack(null, readBuffer);

Interop.ReadFile(fileHandle, readBuffer, (uint)readBuffer.Length, out bytesRead, nativeOverlapped);

How is the callback invoked?

You might have noticed that the previous code only provides a callback, but it is never actually invoked. This is the role of a separate component, which we are using to simulate a completion port thread:

var completionPortThread = new Thread(() => new IOCompletionWorker().Start(completionPortHandle))
{
    IsBackground = true
};
completionPortThread.Start();

That component is in charge of checking the completion port for queued elements and invoking the related asynchronous callback (and also some cleanup).

public class IOCompletionWorker
{ 
    public unsafe void Start(IntPtr completionPort)
    {
        while (true)
        {
            uint bytesRead;
            uint completionKey;
            NativeOverlapped* nativeOverlapped;

            var result = Interop.GetQueuedCompletionStatus(
                completionPort, 
                out bytesRead,
                out completionKey,
                &nativeOverlapped, 
                uint.MaxValue);

            var overlapped = Overlapped.Unpack(nativeOverlapped);

            if (result)
            {
                var asyncResult = ((FileReadAsyncResult)overlapped.AsyncResult);
                asyncResult.ReadCallback(bytesRead, asyncResult.Buffer);
            }
            else
            {
                ThreadLogger.Log(Interop.GetLastError().ToString());
            }

            Overlapped.Free(nativeOverlapped);
        }
    }
}

Samples

Together with Mariano Converti we held a talk some time ago introducing this subject, and created a GitHub repo for the code. Under the source folder you will find three samples:

  1. IOCompletionPorts: Shows how to create a completion port from C# code by taking advantage of DllImport. It gives an idea a high level idea of how things could be implemented underneath the covers (of course the code is nowhere near reusable), and provides a full working sample for the code provided above.
  2. ThreadPoolsSample: Shows that asynchronous callbacks are invoked in thread pool threads.
  3. CompletionPortThreadsSample:Shows that some asynchronous callbacks are invoked in completion port threads, while others are invoked in worked threads.

[Spanish] Webcast Disponible: Arquitectura MVVM para la construcción de aplicaciones Windows Store

For those who don’t read Spanish, this blog post provides details about a Spanish speaking webcast that Diego Poza and I presented last week for the MSDN Latin American community.


La semana pasada junto con mi amigo Diego “Tony” Poza hicimos un Web Cast en el cual explicamos diferentes formas de crear aplicaciones Windows Store con una arquitectura mantenible y flexible.

Queremos agradecerles a todos los asistentes, ya que fue una sesión muy interactiva y con muchas preguntas muy interesantes.

Algunos de los temas que se trataron durante el Web Cast fueron:

  • Cómo tomar ventaja de las PCL (bibliotecas de clases portables).
  • Cómo decidir si usar un framework o no.
  • Manejo de dependencias de los ViewModels.
  • Pruebas unitarias.

Video Online

Para los interesados, les dejamos a continuación los detalles del evento y los links para descargar la grabación o verla online:

Si tienen alguna otra pregunta pueden contactarnos por twitter (@dschenkelman y @diegopoza).

Links

A continuación incluyo algunos de los links referenciados utilizados durante la charla:

Webcast: Modernización de aplicaciones WPF de línea de negocio (spanish)

For those who don’t read Spanish, this blog post provides details about an upcoming Spanish speaking webcast for the MSDN Latin American community.

Este Jueves (22 de Agosto) junto con mi amigo Mariano Converti daremos un web cast sobre como utilizar algunas de las últimas tecnologías Microsoft para desarrollar aplicaciones WPF 4.5. Los detalles del evento son:

  • Link de inscripción
  • Día: Jueves 22 de Agosto de 2013
  • Horario: 06:00 PM (GMT-3)
  • Duración: 1 hora (aproximadamente)
  • Idioma: Español

Entre otras cosas vamos a mostrar como utilizar las siguientes tecnologías para crear aplicaciones de línea de negocio:

Esperamos que puedan asistir!

fakewin8: Configuring valid parameters for fake methods

Yesterday I blogged about fakewin8, a set of components that leverage code generation to create fake classes, which can be used to simplify unit testing in environments where dynamic proxy generation is not a viable option. If you are developing Windows Store or Windows Phone apps you should take it for a spin to see how it feels like.

Today’s blog post explains how fakewin8 allows you to define valid parameters for fake methods.

A bit of context

Commonly, when creating unit tests you need to setup constraints for mock method invocations. This is usually done by providing predicates or specific values for the parameters with which a method must be invoked. If these are not met, your test should fail.

Implementation

In fakewin8 you can configure fake methods to only accept invocations that match a certain set of predicates based on its parameters. If an invocation does not match a specified predicate an InvalidInvocationException is thrown. To specify constraints for a parameter of type T, a predicate of type Func<T, bool> must be used. For example:

[gist id=04e749d3d85e0f6b2d71 file=Accept.cs]

For the common scenario where any possible value is acceptable for a particular parameter, you can use Any<T>.IsOK() which creates a Func<T, bool> that always returns true:

[gist id=04e749d3d85e0f6b2d71 file=Any.cs bump=1]

fakewin8: Easy fakes for Windows Store apps unit tests

In case you are short in time, here’s the Github link: https://github.com/dschenkelman/fakewin8. Otherwise, read on.

If you are reading this, you probably know that due to the changes in the reflection API, all unit testing libraries that depend on the creation of dynamic proxies do not work in Windows RT (for example Moq). As someone who does a lot of Windows 8 development and makes heavy use of unit tests, this was something that really changed the way I approach unit testing.

I’ve seen many different proposals to workaround this issue, such as having linked files, having the components under test in a portable class library (and then using any mocking framework) and using public properties that expose setters for the methods to fake. While those approaches do work fine (in fact I’ve tried all of them), none of them fully suit my needs. I just did not feel completely comfortable with only one of them.  That’s why I came up with the following.

Premises

  1. For each interface or base class, I want to create only one class that can be used as a stub/mock in any test method. This means that all methods must be easy to setup with different logic for different unit tests.
  2. No additional components should be required (i.e.: no portable class libraries, no linked files).
  3. Method invocations should be automatically tracked so assertions can be performed based on them.
  4. Fake class generation should be automatic. We want to focus on the tests development, not the fakes development.

Proposal

fakewin8 proposes the usage of classes like FakeAction and FakeFunc, which act as normal Action and Func, but keep track of the number invocations and parameters on each of them.

For example, for this interface:

public interface INavigationService
{
    void Navigate(string view);

    void GoBack();
}

The following fake class should be created (and only this class should be required):

public class FakeNavigationService : INavigationService
{
    public FakeAction<string> NavigateAction { get; set; }

    public FakeAction GoBackAction { get; set; }

    public void Navigate(string viewName)
    {
        this.NavigateAction.Invoke(viewName);
    }

    public void GoBack()
    {
        this.GoBackAction.Invoke();
    }
}

The FakeAction and FakeFunc classes (at the moment they support until up to 3 parameters) can be leveraged like this in your unit tests:

// arrange
this.fakeNavigationService.NavigateAction = FakeMethod.CreateFor<string>(view => { });

// act

// assert
Assert.AreEqual(1, this.fakeNavigationService.NavigateAction.NumberOfInvocations);
Assert.AreEqual("ViewName", this.fakeNavigationService.NavigateAction.Invocations.ElementAt(0).FirstParameter);

Additionally, given the path to an assembly and an output directory, you can automatically generate the fake classes.

FakeWin8.Generator.Console.exe <dllPath> <outputDir>

The generated code for the sample interface is the following one (no indentation yet):

public class FakeNavigationService : INavigationService
{
public FakeAction<string> NavigateAction { get; set; }

public FakeAction GoBackAction { get; set; }

public void Navigate(string view)
{
this.NavigateAction.Invoke(view);
}

public void GoBack()
{
this.GoBackAction.Invoke();
}
}