Converting event based async calls to Task

Working on a new WinPhone app the other day I encountered an interesting problem which made me scratch my head quite a bit. I needed to read the list of appointments from the phone’s calendar. No big deal, right? Using the MVVM pattern I created a separate view model for my page and a service where I wanted to put all my phone specific stuff. The initial signature of my method was

public IEnumerable<Appointment> GetAppointments();

When trying to implement the method I found out that the calendar API uses the old style event based async pattern (EAP). I tried couple of different methods to wrap the async call and the result from the event in a single method call and failed miserably. After that I tried changing the method to the new async/await style. I knew I had to return a Task<T> so the signature of my method became

public Task<IEnumerable<Appointment>> GetAppointments();

But I still did not know how to make it work. And then I finally came across the TaskCompletionSource class that already solves my problem:

public Task<IEnumerable<Appointment>> GetAppointments()
{
    return Task.Run(() =>
    {
        var tcs = new TaskCompletionSource<IEnumerable<Appointment>>();

        var appts = new Appointments();
        appts.SearchCompleted += (o, e) =>
        {
            tcs.TrySetResult(e.Results);
        };
        appts.SearchAsync(DateTime.Today, DateTime.Today.AddDays(1), "appointments");

        return tcs.Task;
    });
}

Beautiful, isn’t it?

Multi-platform development with c#

The life of the mobile developer today is not easy at all. The market is segmented with at least 3 major players (counting Microsoft, not counting Blackberry). Clients/users want native look and feel and native performance on each platform. Tools like PhoneGap promising write-once-run-everywhere with html5/css/javascript unfortunately just don’t deliver on that promise.

In the recent years Microsoft, knowing that it is not quite winning the post-PC battle is trying to lure the developers to write apps for winphone/win8 by providing the best dev tools and a relatively easy path (with the partnership with xamarin) to porting apps from android or ios to winphone/win8.

Besides code reuse, there is another also important aspect of mobile (or not) development: using a modern and powerful language. In the recent years Java is trailing behind c# (catching up but still not there) and objective-c is so not in the same league as the other two that apple had to introduce a whole new language to replace it few month ago. And c# is almost everywhere – on the client, on the server, on a device, in the cloud – devs can use the same skills and the same tools for any type or size project. (in all honesty that mostly applies to javascript too – with the exception of the nice tools part).

So in the following days I’ll create a small demo of a LOB application on all mobile platforms using visual studio, c#, xamarin, an mvvm library, etc. My goal is to have a form and call a service with the data from the form writing as little code as reasonable and reusing it as much as possible.

Pipes for Windows 8

The Windows 8 version of Pipes is in the store and got a 1000 downloads in the first week. Working on the first update already with a “big orange button”™ for rate and review as well as few smaller improvements.

Download from Windows Store

AgileThought hackathon

AT-hackathon-logo

This week I took part in the inaugural AgileThought hackathon. My team consisted of Esteban Garcia (ALM MVP) , Eric Landes (also ALM MVP) and me (what am I doing with those two?). We wanted to do “something mobile” and/or “something with TFS”. Our initial proposal was for a Windows 8 TFS dashboard app but it was rejected since another team submitted a similar idea before us. We ended up writing a Windows 8 client for the TFS team rooms using the newly released REST API. It turned out pretty good (both visually and functionally) and we won the Cool Use of Technology award at the end.

WebSockets – metro style app

Building the metro app. To our existing solution I’ll add an empty Windows Store Application. As I mentioned earlier the WebSockets support is built in the WinRT so there are no nuget packages to install, we just need to include the Windows.Networking.Sockets namespace.

On my main page I’ll have a stack panel called Container, which sits inside a scroll viewer, and in that container I’ll be adding different custom controls. There is also a text block where we can watch the messages that we send and receive similar to what we did on the HTML5 page.

The programming model for the client is very similar to what we saw on the server and in HTML5. There are 2 important events that we need to handle (MessageReceived and Closed); to open a connection we call ConnectAnync() method and to send and receive messages we use a DataReader and a DataWriter to read and write to and from the input and output streams. I’ll create a simple class that will wrap all this complexity and expose a couple of more convenient methods and events.

using Windows.Networking.Sockets;
using Windows.Storage.Streams;

public class Socket
{
    private MessageWebSocket socket;

    private DataWriter writer;

    public event MessageDelegate OnConnected;

    public event MessageDelegate OnDisconnected;

    public event MessageDelegate OnMessage;

    public event MessageDelegate OnStatus;

    public Socket()
    {
        this.socket = new MessageWebSocket();
        this.socket.Control.MessageType = SocketMessageType.Utf8;

        this.socket.MessageReceived += (sender, args) =>
        {
            var reader = args.GetDataReader();
            var message = reader.ReadString(reader.UnconsumedBufferLength);

            // remove ""
            message = message.Remove(message.Length - 1).Remove(0, 1); 

            Status("<<< " + message);             

            if (OnMessage != null) OnMessage(message);         
        };

        this.socket.Closed += (sender, args) =>
        {
            Status("Disconnected");

            this.socket.Dispose();
            this.socket = null;

            if (OnDisconnected != null) OnDisconnected(null);
        };
    }

    public async void Connect(string url)
    {
        Status("Connecting to " + url + " ...");
        await socket.ConnectAsync(new Uri(url));
        writer = new DataWriter(socket.OutputStream);
        Status("Connected");

        if (OnConnected != null) OnConnected(null);
    }

    public async Task Send(string message)
    {
        Status(">>> " + message);

        writer.WriteString(message);
        await writer.StoreAsync();
    }

    public void Disconnect()
    {
        Status("Disconnecting...");
        socket.Close(1000, "user request");
    }

    void Status(string status)
    {
        if (OnStatus != null) OnStatus(status);
    }
}

The next thing I’ll need is a helper class that will dispatch the messages between the different controls on the main page. All controls will implement a simple IChatControl interface. It contains one method to receive a message and two events to send a message and to send a local message. Also there is a reference property so we know who we are talking to.

public interface IChatControl
{
    string Reference { set; } 

    event MessageDelegate SendMessage;

    event MessageDelegate SendLocalMessage;

    void ReceiveMessage(string message);
}

In my helper class ControlManager I’ll have a collection (dictionary) of controls. There is a single public method that sends a message to the correct control. Each message has a sender, a command and a body. What the method does, it finds the right control to receive the message and sends it to that control. If a control like that does not exist it creates a new one and adds it to the container.

public class ControlsManager
{
    Dictionary<string, UIElement> controls;
    Panel container;

    public event MessageDelegate SendMessage;

    public event MessageDelegate SendLocalMessage;

    public ControlsManager(Panel container)
    {
        this.controls = new Dictionary<string, UIElement>();
        this.container = container;
    }

    public void SendMessageToControl(string sender, string command, string message)
    {
        var control = FindControl(command, sender);
        if (control != null)
            ((IChatControl)control).ReceiveMessage(message);
    }

    private UIElement FindControl(string command, string reference)
    {
        UIElement control = null;
        string key = command + "_" + reference;

        if (controls.ContainsKey(key))
        {
            control = controls[key];
        }
        else
        {
            Type t = GetType(command);
            if (t != null)
            {
                control = (UIElement)Activator.CreateInstance(t);
                ((IChatControl)control).Reference = reference;
                ((IChatControl)control).SendMessage += (message) => 
                    { if (SendMessage != null) SendMessage(message); };
                ((IChatControl)control).SendLocalMessage += (message) => 
                    { if (SendLocalMessage != null) SendLocalMessage(message); };

                controls.Add(key, control);
                container.Children.Add(control);
            }
        }

        return control;
    }

    private Type GetType(string command)
    {
        switch (command)
        {
            case "#CHAT":
                return typeof(ChatControl);
            case "#FRIEND":
                return typeof(FriendsControl);
            case "#TICTACTOE":
                return typeof(TicTacToeControl);
            default:
                return null;
        }
    }
}

The last thing before we get to business is a class that will parse the messages that we receive. Every message has a sender, a command and a body, the sender is marked with @ and the command with # (just like twitter) so a typical message would be “@John #tictactoe 1 1” which means that I’m playing tic tac toe with John and I put an X in the middle square, more about that later on…

Now let’s look at our controls. All of them will implement the IChatControl interface.

First the FriendsControl. In the middle of the control there is a listbox that is databound to a collection of Friends. At the bottom, there is a text box and a button to add a new friend. When the button is pressed we send a message “FOLLOW name”. Also, at the top, there is a text box and a button to set the user’s status, when the button is pressed we send a “STATUS status” message. The type of message the control expects is with a name of a friend and that friend’s status so when a message like that is received we update the friend’s status or add a new friend. That control is initialized a bit different than the other controls. Let’s see how it works…

Now the ChatControl… it is a lot simpler than the FriendsControl. There is a scroll viewer where we put chat “bubbles”. When a message is received all we do is to add a bubble with the text of the message. There is a text box and a Send button where we can compose our own message and when the button is pressed the message is send and another bubble is added. One important thing to notice is that we can have multiple conversations with different people and all the messages get send to the right person and delivered to the right control. Demo…

In the next post we’ll look at the tic tac toe game…

WebSockets – the server

This is part two of my notes for my session about websockets that I’ll be presenting in two weeks at the Orlando Code Camp.

So… the server… having server that replies back whatever you send to it is fascinating but not very useful. I’ll extend the server from part one to allow the clients that are connected to it to talk to each other.

The first thing the server must do when receives a message is to parse it into a command and a payload:

public class Server : WebSocketHandler
{
    public override void OnOpen()
    {
       Say("hello from server");
    }

    public override void OnMessage(string message)
    {
        try
        {
            if (message == string.Empty)
                throw new Exception("empty command");

            string command;
            ParseCommand(ref message, out command);

            // handle known commands...

            throw new Exception("unrecognized command");
        }
        catch (Exception x)
        {
            Say("ERROR " + x.Message);
        }
    }

    public void Say(string message)
    {
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        base.Send(serializer.Serialize(message));
    }

    void ParseCommand(ref string message, out string command)
    {
        int pos = message.IndexOf(' ');
        command = message.Substring(0, pos);
        message = message.Remove(0, pos);
    }
}

The first thing a client must do after establishing connection is to introduce itself (“Hi, I’m John”) before he is able to send any commands. To do that the client will send a message “LOGIN John”. The first word of the message is the command (LOGIN) and the payload is the user name. When the server receives the message it will see the command LOGIN and will reply with “hello John”. No other commands will be allowed until the client has logged in.

if (command == "LOGIN")
{
    UserName = message;
    Say("hello " + UserName);
    return;
}

if (UserName == string.Empty)
    throw new Exception("unauthorized");

// other commands...

Now on the server we have a bunch of connections and we have the ability to assign a UserName to each connection. If we want want one connection to be able to send a message to another we need to build a little bit of plumbing in the form of a static class that keep a collection of all open connections:

public static class Connections
{
    static List<Server> connections = new List<Server>();

    public static void Add(Server server)
    {
        lock (connections)
        {
            connections.Add(server);
        }
    }

    public static void Remove(Server server)
    {
        lock (connections)
        {
            connections.Remove(server);
        }
    }

    public static Server Find(string userName)
    {
        lock (connections)
        {
            return connections
              .Where(s => s.UserName == userName)
              .FirstOrDefault();
        }
    }
}

We’ll have to change the HTTP handler to add the connection to that collection when a new connection is established:

public class WS : IHttpHandler
{
    public bool IsReusable
    {
        get { return false; }
    }

    public void ProcessRequest(HttpContext context)
    {
        if (context.IsWebSocketRequest)
        {
            var server = new Server();
            Connections.Add(server);
            context.AcceptWebSocketRequest(server);
        }
    }
}

And also when a connection is closed it needs to be removed from the collection:

public class Server : WebSocketHandler
{
    public string UserName { get; private set; }

    // ...

    public override void OnClose()
    {
        Connections.Remove(this);
        base.OnClose();
    }
}

Now we are in business…

if (command.StartsWith("@"))
{
    string recipient = command.Remove(0, 1);

    var conn = Connections.Find(recipient);
    if (conn == null)
        throw new Exception("user " + recipient + " is not online");

    conn.Say(UserName + ": " + message);
    return;
}

To test that we can open 2 browser windows, in the first one will login as John and in the second one we’ll login as Mary. Then John can send Mary a message “@Mary How are you doing?”

WebSockets – introduction

This is the first of a series of posts about building real-time applications for Windows 8 (metro style) using websockets. These are my notes for a session that I will be presenting at the Orlando Code Camp on March 16th.

So what are websockets? Websockets are relatively new technology that allows two-way communication between a client and a server. In the past if we wanted to simulate a two way communication between the client and the server we had to do some form of polling where the client asks the server “do you have something for me?” and then the server have the opportunity to send back it’s message. The problem with that model is that most of the times there is no message to be send and so 90% of the whole communication is complete waste. With websockets the only communication that occurs is when either the client or the server have the message for the other. This is a lot more effective, scales better and is a lot easier to program.

Websockets are often viewed as a part of the HTML5 standard but in fact both server and client development is fully supported with the version 4.5 of the .net framework on a Windows 8 machine or Windows Server 2012 using IIS 8. Also all current version of the major web browsers support websockets including IE10, Firefox 6, Chrome 14 and Opera 12.

How does it work? The client send an HTTP GET request to the server asking to open a websocket connection. The server replies with a special “connection upgrade” response and after that both the client and the server can send messages to each other in any order. (This is obviously the simplified version, look in the F12 dev tools in Chrome to see the exact format of the request and the response).

Rome was not build in a day. Let’s create a simple client and a server to demonstrate the mechanics of the websockets handshake and communication.

– Using Visual Studio 2012 on a Windows 8 machine with IIS8 installed create a new Web Application. Configure the app to use IIS instead of the development web server.

– Install nuget package Microsoft.WebSockets

– Add a new HttpHandler called WS.ahx – this will perform the handshake

using Microsoft.Web.WebSockets;

public class WS : IHttpHandler
{
    public bool IsReusable
    {
        get { return false; }
    }

    public void ProcessRequest(HttpContext context)
    {
        if (context.IsWebSocketRequest)
            context.AcceptWebSocketRequest(new Server());
    }
}

– Add a new class Server.cs that inherits from WebSocketHandler and overrides OnOpen(), OnMessage() and OnClose() methods

using Microsoft.Web.WebSockets;

public class Server : WebSocketHandler
{
    public override void OnOpen()
    {
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        base.Send(serializer.Serialize("hello from server"));
    }

    public override void OnMessage(string message)
    {
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        base.Send(serializer.Serialize(message + " back"));
    }

    public override void OnClose()
    {
        base.OnClose();
    }
}

– And finally add a web page called default.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>WebSockets demo</title>
    <script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.0.min.js"></script>
    <script src="//ajax.aspnetcdn.com/ajax/modernizr/modernizr-2.0.6-development-only.js"></script>
</head>
<body>
    <h1>WebSockets demo</h1>

    <input type="text" id="message" />
    <input type="button" id="send" value="Send" />

    <pre id="messages"></pre>

    <script type="text/javascript">

        $(function () {

            if (Modernizr.websockets) {
                log("### websockets supported");
            }

            if (!window.WebSocket && window.MozWebSocket)
                window.WebSocket = window.MozWebSocket;

            var host = "ws://localhost:8080/WS.ashx";
            var connection = new WebSocket(host);

            connection.onopen = function () {
                log("### connection open");
            };

            connection.onclose = function () {
                log("### connection closed");
            }

            connection.onmessage = function (message) {
                var data = window.JSON.parse(message.data);
                log("<<< " + data);
            };

            $("#send").click(function () {
                var message = $("#message").val();
                log(">>> " + message);
                connection.send(message);
                $("#message").val("");
            });
        });

        function log(s) {
            $("<div/>").html(s).appendTo($("#messages"));
        }

    </script>
</body>
</html>

– Set the default.html to be a start page and run the application. A simple webpage should appear with a textbox and a button. Whatever we say to the server the server should say it back. Now we are in business…

Veni, vidi, vici

This weekend I attended a two-day Windows 8 event – a dev camp and hackaton in Seaworld Orlando. The event was organized by Microsoft and reminded me of the dev events from old days – very well-organized and executed. The best part was that I won one of the 3 grand prizes for the hackaton – a Samsung slate and $500 gift card.

I presented a simple To Do List application. There are 3 columns for to do items (list, today and tomorrow) and the user can rearrange his list with drag and drop. I also implemented a share contract and a live tile showing the top 3 items. I even incorporated a palm tree which was one of the requirements for extra credit.

The app actually turned out pretty well for a one day effort and seems quite usable. I plan to submit it to the marketplace with almost no changes so I can test how the process works (and see how many people would pay 99c to be more organized)…

Application Excellence Review

Yesterday was my Application Excellence Review with and engineer from Microsoft. The meeting lasted solid 2 hours, not like someone suggested around 15 minutes.

The requirement for the review is to have your app at least 70% ready and it should clearly show the UI and the features of the final app. The developer must complete and submit a long survey about every possible aspect of a metro style app as well as the results of the windows application certification kit (WACK) that comes with the SDK. So besides having your app ready you need to spend at least two hours preparing for the meeting.

The meeting started well, we had a nice chat about win 8 and the marketplace while the engineer was downloading my app from the microsoft support site where I had previously uploaded it. It was really hard for me to upload my 5 files and I guess it was as hard for him to download them. (The site is at least 10 years old and did not work for me most of the time)

After that I demonstrated how the app works, which features are implemented already and which are coming in the release. We also discussed my monetization strategy.

I was up for a good start… and then he run the WACK… and it failed!!! The WACK has never failed for me before and I run it again while I was talking to him and it worked on my machine (WACK WOMM) again… It will be fun times when I finally submit the app for marketplace certification… Now I was nervous. He looked at the report from when I run the WACK in the morning and said that it is not a requirement for the WACK to succeed at this stage but once I submit for certification it should work.

That was the first 20 minutes. For the next hour and a half we went thru every single question of the survey and we discussed every single possible feature that a metro app could implement.

Overall the meeting was very positive and the guy gave me several very good suggestions. Few hours later I received my token and today I registered my (free for 2 years) developer account.