Tuesday, June 25, 2013

Improving the Readability of Windows Store Unit Tests

I’ve grown to appreciate the value that testing adds to software development. In my opinion many developers spend far too much time focusing on the red herring of code coverage or writing tests just to check them off, rather than the real benefits they provide when you take a more Test-Driven Development (TDD) approach. Although I’ll be the first to admit I don’t follow strict TDD in all of my projects, I have found that having the discipline to write your tests first as often as possible can save a lot of time on a project and result in a much cleaner API. It’s the difference between building a class and exposing what you think the API should look like, versus writing a test that uses the API the way you would want to consume it, then writing the class to fulfill the need.

One issue I have with tests, however, is that the Microsoft method for testing isn’t very clear. For example, take a look at this:

Assert.IsTrue(2 > 3);                 

How would you describe this test to someone? “assert it is true 2 is greater than three” is how it reads. How about this instead?

Assert.That(2, Is.GreaterThan(3));

That now reads, “assert that 2 is greater than 3”. Doesn’t that describe exactly what you are checking (and hoping will fail?) This becomes even more confusing when you are comparing equality. Try this:

Assert.AreEqual(2, 3);

Compared to this:

Assert.That(2, Is.IsEqualTo(3));

Again, you may think I’m crazy but I think the second is easier to write and read. It just flows and instead of trying to figure out which assertion method makes sense, then putting the expected or actual values in the right place, etc. why not just write it out in a nice, easy to understand sentence?

It turns out it is fairly easy to build your own library of extensions to the existing framework that make it easy to provide a more fluent interface for testing. There are third-party libraries you can look into but the quick and dirty way is right here. I just decided to ride on the truth assertion and extend that to fit my needs. First, a class that will take some generic object and apply a predicate then optionally display a message:

public static class AssertIt
{
    public static void That<T>(T target, Func<T, bool> condition, string message = ""
    {
            if (string.IsNullOrWhiteSpace(message))
            {
                Assert.IsTrue(condition(target));
            }
            else
            {
                Assert.IsTrue(condition(target), message);
            }
    }       
}

Next, a static class for the comparisons. Note the parent class is expecting a predicate, so the helper class will provide the predicate and manage any optional parameters. Here is the “Is” class with two examples:

public static class Is
{
    public static Func<T, bool> GreaterThan<T>(T comparison) where T : IComparable
    {
        return target => target.CompareTo(comparison) > 0;
    }

    public static Func<string, bool> NotNullOrWhitespace()
    {
        return target => !string.IsNullOrEmpty(target);
    }
}

Each method returns the predicate for the comparison and handles any additional parameters that are needed. This enables you to write something like this:

AssertIt.That(2, Is.GreaterThan(3));                 

Of course we need to test that our tests are going to run appropriately! Here’s a pair of tests that ensure our assertions are working correctly for the “greater than” comparison.

[TestMethod]
public
 void GivenAnIntegerWhenComparedGreatherThanToAGreaterIntegerThenShouldFail()
{
    var exception = false;

    try
    {
        AssertIt.That(2, Is.GreaterThan(3));                
    }
    catch (AssertFailedException)
    {
        exception = true;
    }

    Assert.IsTrue(exception, "Test failed: an exception should have been thrown.");
}

[TestMethod]
public
 void GivenAnIntegerWhenComparedGreaterThanToALesserIntegerThenShouldSucceed()
{
    AssertIt.That(3, Is.GreaterThan(2));            
}

And that’s it – to me it’s worthwhile to invest some time in some extension and helper methods to make the code far more readable and easier to write. You could, of course, just plug in a third-party test framework that already provides a fluent interface like NUnit as well.

Wednesday, June 19, 2013

MVVM and Accessing the UI Thread in Windows Store Apps

Any developer who has worked with MVVM in WPF, Silverlight, or Windows Store apps has likely run into the issue of executing an action on the UI thread. This most often happens when work has to be done on another thread. It is a common mistake to perform the work and then attempt to set a property on the view model. The view model exposes properties for data-binding, and data-binding must happen on the UI thread. Therefore, triggering a property change notification on the wrong thread can lead to a thread access violation and result in a crash. It is also necessary to access the UI thread when performing UI-related actions such as showing a modal dialog and waiting for user input.

I’ve seen a lot of different approaches to doing this, some of them quite complex and interesting to read, but a simple solution is easier than you might think. You can choose to set a property on the view model that references the UI thread:

private readonly CoreDispatcher dispatcher;

The dispatcher class queues messages for publication on the UI thread. The messages are callbacks of type DispatchHandler which is simply a named delegate. The dispatcher allows you to specify a priority for the message and higher priority messages will be queued in front of lower priority messages. I’ve rarely found the need to use anything other than the normal priority when performing work on the UI thread.

In this example I’m using a simple property to capture the dispatcher, but you may want to consider creating an interface that mimics the work the dispatcher does. Then you can implement a reference to the dispatcher at runtime but use a mocked implementation for tests.

Grabbing the right dispatcher is easier than you might think. I’ve seen solutions that use dependency properties and data-binding or wire up the dispatcher using code-behind, etc. but the reality is the view model is almost always instantiated on the UI thread (this is true whether it is created in code behind, referenced as a resource or instantiated directly from XAML). Therefore, you can simply capture the dispatcher in the constructor. Be sure you check for design-mode as the attempt to capture the dispatcher will fail in the designer.

if (Windows.ApplicationModel.DesignMode.DesignModeEnabled)
{
    return;
}
this
.dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;

Now that I have captured the dispatcher, I can create a simple method that encapsulates the call to the UI thread (in this case I’m assuming it’s on the view model, but again this could be in an implementation that is referenced via an interface to make it easier to mock for testing).

private async Task OnUiThread(Action action)
{
    await this.dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => action());
}

This is a simple form – it takes an action and simply waits for the dispatcher to queue the callback on the UI thread. The following example will queue the assignment of a property on the UI thread so that data-binding can process the update (note there is another technique with view models that involves always marshalling the property change event to the UI thread). The following code is executed from a background task that is not running on the UI thread:

await this.OnUiThread(() =>
{
this.ViewModelProperty = this.BackgroundWork();
});

This will work for most cases, but if you are scheduling something asynchronous you’ll have a problem. The method I showed performs a “fire and forget” of the work you pass to it. If you are doing something like waiting for a dialog, your code may not behave as intended because it won’t actually wait for the dialog to close – instead, it will simply wait for the call to open the dialog to be scheduled. To solve this, provide a simple overload:

private async Task OnUiThread(Func<Task> action)
{
    await this.dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => await action());
}

The overload also schedules a task, but it also acknowledges the task is asynchronous and awaits the completion of the task. Now you can schedule the work like this:

var dialog = new MessageDialog(message, title);
await this.OnUiThread(async () => await dialog.ShowAsync());

One important thing to keep in mind is that this should be the exception, not the rule, for most apps. A good design will not attempt to manipulate the view model directly, but instead will return a property and allow you to await the task from the UI thread. For example, setting the view model property might be accomplished like this without having to use the dispatcher at all:

this.ViewModelProperty = await this.BackgroundWorkAsync();                       

The dispatcher is most useful when you have scenarios that force you to spawn background tasks that you aren’t able to await from the UI thread, or when you have methods that may be called from a separate thread and must surface information to the UI.

Monday, June 10, 2013

Simple Validation with MVVM for Windows Store apps

Developers who are writing Windows Store apps using C# and XAML might find some of the support for Model-View-ViewModel (MVVM) lacking. Both WPF and Silverlight provided specific interfaces that enabled you to store validation context about fields on a context and even supported asynchronous validation. Although there are some existing frameworks that provide this support, such as Prism for the Windows Runtime, it is also fairly simple and straightforward to roll your own.

I do appreciate the various MVVM frameworks that exist (I’ve even written one of my own) but I find that most of the support I need for Windows Store apps comes out of the box. If you create your project from any of the built-in templates, the classes you need are already generated. In the case of the Blank app template, you simply need to add a single BasicPage item to get the supporting classes for layout-aware apps with intrinsic MVVM support. My favorite class is the BindableBase that provides basic property change notification and a special way to set properties that only triggers change notification if the new value differs from the old.

I use this to create a ValidationErrors class that is simply a collection of errors with a validation flag.

public class ValidationErrors : BindableBase  
{
    private readonly Dictionary<string, string> validationErrors = new Dictionary<string, string>();

    public bool IsValid
    {
        get
        {
            return this.validationErrors.Count < 1;
        }
    }
}

The indexer handles storing the errors and raising the appropriate property change notification so the dictionary can be bound in the UI.

public string this[string fieldName]
{
    get
    {
        return this.validationErrors.ContainsKey(fieldName) ? 
            this.validationErrors[fieldName] : string.Empty;
    }



    set
    {
        if (this.validationErrors.ContainsKey(fieldName))
        {
            if (string.IsNullOrWhiteSpace(value))
            {
                this.validationErrors.Remove(fieldName);
            }
            else
            {
                this.validationErrors[fieldName] = value;
            }
        }
        else
        {
            if (!string.IsNullOrWhiteSpace(value))
            {
                this.validationErrors.Add(fieldName, value);
            }
        }
        this.OnPropertyChanged();
        this.OnPropertyChanged("InValid");
    }
}

Note this implementation simply removes the item. It also supports a single message per item, it could be enhanced by providing a dictionary of lists if you want to support multiple errors per field.

The next step is to create a base class for validations to use.

public abstract class ValidationBase : BindableBase
{
    protected ValidationBase()
    {
        this.ValidationErrors = new ValidationErrors();            
    }

    public ValidationErrors ValidationErrors { get; set; }

    public bool IsValid { get; private set; }

    public void Validate()
    {
        this.ValidationErrors.Clear();
        this.ValidateSelf();
        this.IsValid = this.ValidationErrors.IsValid;
        this.OnPropertyChanged("IsValid");
        this.OnPropertyChanged("ValidationErrors");
    }

    protected abstract void ValidateSelf();
}

Now you can implement the validation in your class. The current implementation assumes you have a validation method that fires at the end, but you could easily enhance it to validate specific items as they are input as well. The sample class is a simple note with a title and description, and both are required to be filled out for validation to pass.

protected override void ValidateSelf()
{            
    if (string.IsNullOrWhiteSpace(this.title))
    {
        this.ValidationErrors["Title"] = "Title is required.";
    }

    if (string.IsNullOrWhiteSpace(this.description))
    {
        this.ValidationErrors["Description"] = "You must type some text for the note.";
    }            
}

Now that the validation is in place, you can easily bind to it in the UI. In this case I’m not using any converters because I want the space for the validation text to remain even if the fields are valid. This prevents the UI from shifting unnaturally. The save command simply calls the Validate method on the note and only saves it if the result is true. Take a look at the XAML and note how the indexers are used to display the validation message.

<TextBlock Text="Title:" Style="{StaticResource PageSubheaderTextStyle}"/>
<
TextBox Text="{Binding Title, Mode=TwoWay}" Grid.Row="1"/>
<
TextBlock Text="{Binding ValidationErrors[Title]}"
Foreground="Red" Grid.Row="2" Style="{StaticResource ItemTextStyle}" Margin="12 0 0 0"/>
<
TextBlock Text="Notes:" Style="{StaticResource PageSubheaderTextStyle}" Grid.Row="3"/>
<
TextBox Text="{Binding Description, Mode=TwoWay}" Grid.Row="4" TextWrapping="Wrap"/>
<
TextBlock Text="{Binding ValidationErrors[Description]}"
Foreground="Red" Grid.Row="5" Style="{StaticResource ItemTextStyle}" Margin="12 0 0 0"/>    

That’s it … now I have a simple way to validate entities and provide messages to the UI through MVVM. The final result looks like this (obviously some more work can be done to highlight the input box itself and style the page, but you should get the general idea).

safenotes

For the full working example (that includes how to use the WinRT data protection provider to encrypt notes) visit http://winrtexamples.codeplex.com/

Tuesday, June 4, 2013

Single Sign On with OAuth in Windows Store Apps

Various providers often provide documentation and even SDKs that make it easier to connect with and authenticate to their service. The problem is that most scenarios assume a web-based application or specific mobile clients. The process in general looks something like this:

oauth

How can you take protocol modeled for the web and make it work in an app that is running on a Windows 8 device? The answer is the WebAuthenticationBroker component in the Windows Runtime.

The web authentication broker is designed to assist you with single sign-on scenarios by emulating a fully web-based experienced. You provide the broker with a starting URL. This URL typically contains information such as special application codes and passwords used to verify your app’s identity with the provider and a redirect URL the provider should send the user to when they are authenticated. You also provide the broker with an ending URL. This is where the magic happens for the broker.

The broker starts by popping up a dialog that is essentially a web browser window without chrome. The user will be presented with the provider’s login page, such as the Facebook example shown here.

facebooksso

The user can then enter their credentials and authorize the app to information. Once they are finished, the provider will redirect them to a final URL. The web broker is configured to listen for this URL, and instead of serving the page, it will intercept the request and provide the details to your app. You can then parse the content of the redirect to obtain the access token that validates the user’s identity and can be used to make further requests from the provider.

The logic to authenticate with Facebook and receive a token is fairly straightforward. There are two URLs involved. The first is the URL used to authenticate with Facebook that we’ll call FaceBookAuth. The URL must be passed a client id (your app id), a redirect URL to send the user to when they are authenticated, a scope to determine what information you will be requesting, and the type of response (we want a token).

The second URL is the redirect URL. Because the example is a client app and not a web page, Facebook’s own confirmation URL is used as the redirect URL and stored in the FacebookRedirectUri constant. After the user authenticates, they will be redirected to the Facebook page. The web authentication broker will be listening for the redirect and will intercept it. The scope informs Facebook what you intend to access, for example, an email.

private const string FaceBookAuth =
https://www.facebook.com/dialog/oauth?client_id={0}&redirect_uri={1}&scope={2}&response_type=token;
private const string FacebookRedirectUri = "https://www.facebook.com/connect/login_success.html";

The code builds the start and end URLs and then calls the AuthenticateAsync method on WebAuthenticationBroker in the Windows.Security.Authentication.Web namespace. It is passed a set of options, the URL to start with, and the URL to listen to.

WebAuthenticationResult result = await WebAuthenticationBroker.AuthenticateAsync(

                                        WebAuthenticationOptions.None,
                                        startUri,
                                        endUri);

The authentication options are provided by passing flags specified in the WebAuthenticationOptions enumeration. Possible values include:

  • None – no options.
  • SilentMode – used for pure SSO that has no UI involved. If the provider displays a web page the authentication will fail.
  • UseTitle – instructs the web authentication broker to parse the title of the window for the web page and return it in the ResponseData property to allow you to parse it as needed.
  • UseHttpPost – when the provider performs a POST to the final website, this option will provide the contents of the POST in the ResponseData property.
  • UseCorporateNetwork – this will render the web page in a special container that supports enterprise authentication and private networks for intranet authentication and requires that similar capabilities are declared for the app.

The result will return a response status (successful, an HTTP error, or the user canceled) and the contents of the final redirect. The Facebook redirect uses a hash to separate the URL from a set of response parameters send in a query string format (name/value pairs). The first parameter is the token you can use for further access, and the second is when the token will expire. Use this to store the token and reuse it without having to request a new one each time.

if (result.ResponseStatus == WebAuthenticationStatus.Success)

{
    var data = result.ResponseData.Substring(result.ResponseData.IndexOf('#'));
    var values = data.Split('&');
    var token = values[0].Split('=')[1];
    var expirationSeconds = values[1].Split('=')[1];
    var expiration = DateTime.UtcNow.AddSeconds(int.Parse(expirationSeconds));
    this.dataStorage.Save(this.Name, expiration, token);
    return token;
}

Once the token has been received, the main authentication step is complete. Now you can use the token to request information about the user. For example, you can obtain their preferred email address to default it without asking or to identify the user internally to your app.

private const string FacebookIdentityUrl = "https://graph.facebook.com/me?scope=email";
public async Task<string> GetEmail(string accessToken)

{
    var client = new HttpClient();
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue
("OAuth", accessToken);
    var result = await client.GetStringAsync(FacebookIdentityUrl);
    var profileInformation = JsonObject.Parse(result);
    var email = profileInformation["email"].GetString();
    return email;
}

You may have noticed earlier that an API was used to save the token. Tokens have expirations and can be reused so you don’t have to force the user to login in repeatedly. A safe and secure way to store tokens that will even roam to other devices (provided the user uses their Microsoft Account and the devices are trusted) is the credential locker. The locker expects a resource (such as the name of the provider), a username, and a password. For this example, the username is fixed and the password is used to store the token and the expiration:

public void Save(string key, DateTime expiration, string token)

{
    var vault = new PasswordVault();
    var credential = new PasswordCredential(
        key, 
        Username, 
        string.Format("{0}|{1}", expiration, token));
    vault.Add(credential);
}

The vault can be queried for the credential and the expiration is used to determine whether the token can be used again or not. If the user requests to sign out, the credential is simply removed from the locker.

For a working code example visit http://winrtexamples.codeplex.com and download the Chapter 8 AuthenticationExamples app. It demonstrates single sign on and retrieval of email for both Facebook and Google. You will need to have developer accounts for each and will have to update the code with your client ids and client secrets for the project to run.