Using await to build cool UI tutorials

In the last post we discussed how we can build custom awaiters and showed simple example how to await for click on the Button instance.

Maybe it was not obvious how we can expand that idea and create some useful application, so i decided to expand the whole concept in this post.

We are going to build some more complex awaiters (for example TextBox awaiter that awaits for certain text to by typed into it) and use it together with the old Button click-awaiter to build the tutorial on how to use some imaginary app inside of the app itself.

For those not patient enough here is what it will look like at the end:

Tutorial App Gui With Await

So lets get started. First we need to build that awaiter for text box to be typed into the TextBox. This is little more complicated then our Button awaiter because in this case we need to pass the text parameter to our awaiter, and await keyword does not support that out of the box.

This is the usage we want to achieve in the end – if we are awaiting for text “123” to be entered into TextBox named tb1 then we want to be able to write something like this in our code:

    await new TextBoxTextAwaiter(tb1, "123");

To do the trick, first we are going to create one intermediary class TextBoxTextAwaiter that will accept two parameters, our TextBox instance and the text that we are expecting to be typed into it:


    public class TextBoxTextAwaiter
    {
        public TextBox TextBox { get; set; }
        public string TextToAwait { get; set; }

        public TextBoxTextAwaiter(TextBox textBox, string textToAwait)
        {
            TextBox = textBox;
            TextToAwait = textToAwait;
        }
    }

So now that we have something to hold on to our parameters we will create an extension method GetAwaiter for that class TextBoxTextAwaiter so that it can be awaited:

    public static class TextBoxAwaiterExtensions
    {
        public static TextBoxAwaiter GetAwaiter(this TextBoxTextAwaiter textBoxTextAwaiter)
        {
            return new TextBoxAwaiter(textBoxTextAwaiter.TextBox, textBoxTextAwaiter.TextToAwait);
        }
    }

As you see in the GetAwaiter we are creating instance of another class called TextBoxAwaiter (details of it below) and pass all the parameters into its constructor and this class can now do the actual await for use:

    public class TextBoxAwaiter : INotifyCompletion
    {
        private readonly string _textToAwait;

        public TextBoxAwaiter(TextBox textBoxToAwait, string textToAwait)
        {
            _textToAwait = textToAwait;
            TextBoxToAwait = textBoxToAwait;
        }

        public void GetResult() {}

        public bool IsCompleted
        {
            get { return TextBoxToAwait.Text.Equals(_textToAwait); }
        }

        public TextBox TextBoxToAwait { get; set; }
        public void OnCompleted(Action continuation)
        {
            TextChangedEventHandler h = null;
            h = (sender, args) =>
            {
                TextBoxToAwait.Focus();
                if (IsCompleted)
                {
                    TextBoxToAwait.TextChanged -= h;
                    continuation();
                }
            };
            TextBoxToAwait.TextChanged += h;
        }
    }

As you see this final awaiter is simple and works similarly like our ButtonAwaiter with difference that its subscribing to TextChanged event of the TextBox and checks if our desired text is entered. Once the text is entered, we are notifying awaiter that we are done by calling the continuation Action (and unsubscribing from TextChanged event for the cleanup).

And that’s all, now we can build any in-application tutorial that involves typing certain text in TextBoxes and clicking on the Buttons.  We could off course go further and build all kinds of awaiters for example MouseMovedAwaiter, MouseMovedToRegionAwaiter, UserInactivityAwaiter etc.

Also on mobile platforms we could easily create SwipeAwaiter, ShakeDeviceAwaiter, DoubleTapAwaiter etc.

This would be out of the scope of this article, i just wanted to share this idea :)

So here is how we would implement that imaginary “GUI Tutorial” from the image on the top of the post:

            public MainWindow()
        {
            InitializeComponent();
            Loaded += (a,e) => { Setup(); };
        }

        private async void Setup()
        {
            await BtnTutorial;
            ShowDemo();
        }

        private async void ShowDemo()
        {
            tb1.Text = "";
            AddVisualCue(Btn1);
            ShowMsg("Press First button");
            await Btn1;
            ClearVisualCues(Btn1);

            AddVisualCue(Btn2);
            ShowMsg("Press Second button");
            await Btn2;
            ClearVisualCues(Btn2);

            AddVisualCue(Btn3);
            ShowMsg("Press Third button");
            await Btn3;
            ClearVisualCues(Btn3);

            AddVisualCue(Btn4);
            ShowMsg("Press Fourth button");
            await Btn4;
            ClearVisualCues(Btn4);

            AddVisualCue(tb1);
            ShowMsg("Type the code '123' into the TextBox");
            await new TextBoxTextAwaiter(tb1, "123");
            ClearVisualCues(tb1);

            ShowMsg("Tutorial finished");

            Setup();
        }

I’m not posting the whole source code here because you can download the full zipped solution to see all the details. We simply use our awaiters to avoid boilerplate code for anticipated user interactions and we can concentrate on the actual logic of the tutorial.

Off course this is very simplified example but its very easy to extend it and make it really useful and interesting.

I can imagine this approach being used to create in-app tutorials for mobile applications where user would be expected to touch certain parts of the screen, do swipe actions, then maybe shake the device to clear screen etc.

Or for mobile games for kids where they should “interact” with the device in order to proceed in the game, take a picture of their pet, say some voice commands etc.

i would hear about see some nice usages of this pattern, feel free to post some in the comments.

Download full source code in Visual Studio 2013

Awaiting for that Button click

Why wait when we can await?

I believe that most of C# developers know about the new language features for asynchronous programming with async and await keywords but how many of us are really exploiting them to full extent?

Recently i was watching the excellent C# Language Internals course on PluralSight.com by Bart De Smet and came across very cool idea of using Await to wait for Button to be clicked – which pushed me to write this post and share it with everyone.

By implementing a custom awaiter for Button (via extension methods) and hooking up to the Click handler we are able to await for that button to be clicked in very elegant way.

So innstead of manually adding Clicked event handler to each Button we hide that functionality in our awaiter and then we are able to write code this:

 private async void AwaitForButtonClicks()
 {
     await btn1;
 }

How do we implement custom awaiter?

Implementing custom awaiter surprisingly does not require you to inherit some class or implement an interface. Compiler is smart enough to recognize if you are implementing proper methods (either directly on the instance or via extension method) and if you do, then you can use await keyword on that type.

Cool thing about that is that you don’t need to own the class which you want to extend with awaiter,  same as in our case where we want to await for System.Windows.Control.Button which we don’t own (we could off course inherit it but if it would be sealed, we could still do it via extension methods).

Lets write the awaiter:

    public static class ButtonAwaiterExtensions
    {
        public static ButtonAwaiter GetAwaiter(this Button button)
        {
            return new ButtonAwaiter()
            {
                Button = button
            };
        }
    }

As you see we are adding the GetAwaiter method on the Button via extension method and returning the ButtonAwait which is just a class in which we will implement the actual await functionality (it could also be a struct instead of class). Also we pass the instance of the Button instance so that our ButtonAwaiter has something to attach to.

Compiler will recognize that we added this method (and also it will check if the ButtonAwaiter class that we return from it is implementing proper methods and interfaces) and because it will “see” all is implemented properly await keyword will start working for us.

In order for all this to work lets implement the ButtonAwaiter class:

    public class ButtonAwaiter : INotifyCompletion
    {
        public bool IsCompleted
        {
            get { return false; }
        }

        public void GetResult()
        {

        }

        public Button Button { get; set; }

        public void OnCompleted(Action continuation)
        {
            RoutedEventHandler h = null;
            h = (o, e) =>
            {
                Button.Click -= h;
                continuation();
            };
            Button.Click += h;
        }
    }

Our awaiter first of all returns false in the IsCompleted notifying the runtime that when we await for button, that it cannot return immediately, but only later after button is clicked.
And we take care of that in the OnCompleted method where runtime is subscribing with Action continuation to be called after awaiting is done – in other words after someone has clicked on the Button instance.
So in that method we create Click button handler and subscribe to the Click event and then inside that handler we unsubscribe (so we don’t get restart the await state machine every next time Button is clicked) and then we invoke the continuation action to notify everyone that our await is finished.

Note that GetResults does not return nothing since it would not make sense to return anything in our case – we are just waiting for the button click.

And that’s really all there is to it.

How to use this thing?

Now in our app we can await for multiple Buttons in which ever order we want and then do some action after Buttons are pressed in that specific order:

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            Loaded += (s, e) =>
            {
                AwaitForButtonClicks();
            };
        }

        private async void AwaitForButtonClicks()
        {
            await btn1;

            await btn2;

            await btn3;

            MessageBox.Show("Well done!");

            AwaitForButtonClicks();
        }
    }

So as you see in the Loaded even of the Window we call our async method that is awaiting for Button clicks and then show some message. And then we recursively start waiting again :)

Don’t forget that first await is waiting for click on the btn1 instance so even if you click some other button, code will still be waiting there for that specific click. Once first btn1 is clicked, execution moves to second line and awaits for btn2 to be clicked etc.

Button Awaiter in action

Ok we can use it but is it really useful?

I can think of scenarios where this could be really useful.

Besides freeing us from always writing the boilerplate code for subscribing to Click event of the button, there are more advantages.

Imagine a application that has many UI elements and interactions and you want to create a tutorial for your app that will run inside of the app.

Imagine app itself guiding the user through its own tutorial by highlighting certain Buttons or TextBoxes, and waiting for the user to click them or write some text in TextBox, or move some sliders of the app to understand how to setup parameters etc.

We could also use this in some game where user has to press some buttons in certain order etc.

Possibilities are endless and this Button awaiter is just a start – in one of the next posts I will write some more examples on how to await for different actions, how to pass parameters to await, so stay tuned.

I hope you find this useful and that it will push you to start exploring those (not so new) language features.

Download Visual Studio 2013 solution with source code for this post

Introducing the Unit Testing Context Pattern

Another pattern?

Well yes. I write unit and integration tests almost every day and along the way i learned all kinds of different tricks and gotchas on how to be more productive and how to write less fragile tests.

But one of the patterns that emerged i never saw in the code of other people so i decided to share it here since i find it very useful.

I call it Testing Context Pattern and – unlike it’s name – its very simple.

Idea is to create in your Test Fixture a private class called (you guessed it) TestContext and put all the mocks/instances needed for testing the current class and then create instance of that class we test by using those mocks and then also expose all of that as public fields of the TestContext.

That way we have all we need for testing in one place and we can start having fun!

So if we are testing class WebPageDownloader that needs two more entities to function (IUrlPermissioner and IUrlRetriever) then we create class TestContext like this:

        private class TestContext
        {
            public Mock<IUrlPermissioner> PermissionerMock;
            public Mock<IUrlRetriever> UrlRetrieverMock;
            public WebPageDownloader Downloader;
        }

Notice here that we expose the mocks of the dependencies on the context (I’m using Moq testing framework but you can choose any other you like) this is very important because later in our tests we can then give further setups/expectations to those mocks that are used inside test class.

Next we create a private method on test fixture that creates instance of context for us, initializes it with all the mocks needed for testing and the tested class instance itself and returns it (this is to avoid creating this in each test):

        private TestContext CreateContext()
        {
            var ctxt = new TestContext()
            {
                PermissionerMock = new Mock<IUrlPermissioner>(),
                UrlRetrieverMock = new Mock<IUrlRetriever>(),
            };

            ctxt.Downloader = new WebPageDownloader(ctxt.PermissionerMock.Object, ctxt.UrlRetrieverMock.Object);

            return ctxt;
        }

As you see i create all the mocks that our tested class needs, then i instantiate it by passing mocked instances into its constructor and then i save mocks and target class in the context for usage in further tests.

Testing Context in action

So now in each test i call CreateContext method to get fresh instance of TestContext and start testing my target class.
Good thing about this is that in the TestContext we have all the mocks of dependencies used to create the tested class, so we can still manipulate them, mock out some specific methods for each test, and also we can check later in the test if the mocks were used in proper way, check what methods the target class invoked on them etc.

Here is an example of test that checks if our class throws exception for URl that is not permitted by IUrlPermissioner:

        [Test]
        [ExpectedException(typeof(SecurityException))]
        public void Download_WhenNotPermitted_Throws()
        {
            var ctxt = CreateContext();

            var badUrl = "http://www.SomeBadUrl";

            // arrange
            ctxt.PermissionerMock.Setup(a => a.IsUrlAllowed(badUrl)).Returns(false);

            // act
            ctxt.Downloader.Download(badUrl);

            // assert we don't need to do since we have ExpectedException attribute
        }

As you can see in the test we just call the CreateContext method to get fresh context, then we use the mocks from the context to setup our expected calls and return values, and then we invoke actual method on the class we are testing and then we expect the exception (via ExpectedException attribute that we placed on the test method)

Here is little more complex scenario where we setup multiple mock interactions with our class and then expect return result to be correct:

        [Test]
        public void Download_WhenAllowed_ShouldReturnWebpageGotViaRetriever()
        {
            var ctxt = CreateContext();

            var OkUrl = "http://www.SomeOkUrl";
            var OkUrlContent = "Some Web Page";

            // arrange
            ctxt.PermissionerMock.Setup(a => a.IsUrlAllowed(OkUrl)).Returns(true);
            ctxt.UrlRetrieverMock.Setup(a => a.Retrieve(OkUrl)).Returns(OkUrlContent);

            // act
            var result = ctxt.Downloader.Download(OkUrl);

            // assert
            Assert.AreEqual(OkUrlContent, result);
        }

Another good thing here is that if you later refactor your target class and add/remove dependencies you can easily change TestContext and CreateContext method accordingly and none of your existing tests should fail to compile because of that, unlike the situation when you would do all this in each test.

As usually, you can download Visual Studio 2012 solution showing this in action if you are interested.

I hope this simple pattern can help someone in writing better tests.
If you have comments or if you are doing something similar in your tests leave a comment i would love to hear it.

Marbles

Video of my game Marbles for Windows 8

Hi all,

here is 1 minute video of my game Marbles for Windows 8. Its recorded on my desktop machine and played using a mouse,

but it works also with touch based devices, and you can even play with multiple hands at the same time, which opens some interesting

multiplayer possibilities…

Let me know if you have some ideas how to improve the gameplay, what power-ups i could add etc…