Web clients with MatriX and SignalR

Persistent realtime connections for ASP.NET in code behind to the web browser were hard to implement in the past. There hasn’t been a ASP.NET component for this for a while.

With SignalR there is an asynchronous realtime signaling library for ASP.NET now that a team at Microsoft is working on. Using SignalR its pretty easy to build real-time web applications.

Using SignalR and MatriX its very easy to write scalable XMPP web applications with a very small amount of JavaScript code.

Let’s get started:

Create a new ASP.NET MVC web application project first. Then install SignalR using the NuGet Package Console with the following command:

install-package SignalR

This will add SignalR with all required references to the new project we just created.

Now we create a Hub for MatriX. Hubs are a higher level framework API to exchange different messages between server (code behind) and client (web browser) bidirectional in realtime.

We First implement the IConnected and IDisconnect interfaces to the Hub. Our Hub has a static Dictionary for all XmppClients instances. Whenever a new client connects to the bidirectional realtime channel of SignalR we create a new XmppClient instance for it, setup the event handlers and add the client to the dictionary. When a browser disconnects from SignalR we disconnect all event handlers and remove the XmppClient from the dictionary.

public class MatrixHub : Hub, IConnected, IDisconnect
    private static readonly Dictionary<string, XmppClient> XmppClients = new Dictionary<string, XmppClient>();

    public Task Disconnect()
        if (XmppClients.ContainsKey(Context.ConnectionId))
            var xmppClient = XmppClients[Context.ConnectionId];

            xmppClient.OnReceiveXml -= xmppClient_OnReceiveXml;
            xmppClient.OnSendXml -= xmppClient_OnSendXml;
            xmppClient.OnMessage -= xmppClient_OnMessage;


        return Clients.leave(Context.ConnectionId, DateTime.Now.ToString());

    public Task Connect()
        if (!XmppClients.ContainsKey(Context.ConnectionId))
            var xmppClient = new XmppClient();

            xmppClient.OnReceiveXml += xmppClient_OnReceiveXml;
            xmppClient.OnSendXml += xmppClient_OnSendXml;       
            xmppClient.OnMessage += xmppClient_OnMessage;
            XmppClients.Add(Context.ConnectionId, xmppClient);

        return Clients.joined(Context.ConnectionId, DateTime.Now.ToString());

    public Task Reconnect(IEnumerable<string> groups)
        return Clients.rejoined(Context.ConnectionId, DateTime.Now.ToString());

Now we add a Open and Close function to our Hub which can be executed from the webpage via JavaScript. The JavaScript passes the username, password and XMPP domain as a string to the Open function.

Context.ConnectionId is the Id of the JavaScript client calling this Hub. We use this ids for our XmppClient dictionary and need it to lookup the correct XmppClient instance from the dictionary. After retrieving the XmppClient instance we set Username, Password and XmppDomain. Then we call Open() and MatriX starts to login to the XMPP server with the given credentials.

The same applies to the Close function. We first lookup the correct XmppClient and then call Close on it to close the XMPP stream.

public void Open(String username, String password, String xmppDomain)
    XmppClient xmppClient = XmppClients[Context.ConnectionId];
    xmppClient.Username = username;
    xmppClient.Password = password;
    xmppClient.XmppDomain = xmppDomain;


public void Close()
    XmppClient xmppClient = XmppClients[Context.ConnectionId];

Now we implement the OnSendXml and OnReceiveXml handlers we subscribed to in the Connect Task. This is server side C# code telling the client to call sendXml() and receiveXml() JavaScript functions.

Clients is a dynamic object of SignalR. Clients[Context.ConnectionId] gets the correct client and executes the function on this single client only.

void xmppClient_OnSendXml(object sender, Matrix.TextEventArgs e)
    var text = HttpUtility.HtmlEncode(String.Format("Send: {0}", e.Text));

void xmppClient_OnReceiveXml(object sender, Matrix.TextEventArgs e)
    var text = HttpUtility.HtmlEncode(String.Format("Recv: {0}", e.Text));

The last step before we goto our JavaScript is the OnMessage function. SignalR can also send complex objects. So lets create a simple Message class to send the message properties as an object to our JavaScript. The Message class has 2 simple String properties. Body for the Text of the message and From for the full Jid of the sender.

public class Message
    public string Body;
    public string From;

Whenever MatriX receives a message in the OnMessage handler we raise the callback onMessage in our JavaScript and pass a new instance of the Message object we just created.

void xmppClient_OnMessage(object sender, MessageEventArgs e)
           new Message
           		From = e.Message.From,
           		Body = e.Message.Body

The backend and code behind stuff is done now. Now we have to add JavaScript to our web page to setup the SignalR connection.

First we have to include some JavaScript files. We need jquery, the signalR script and the hubs which get created dynamically by SignalR on the server.

<script src="@Url.Content("~/Scripts/jquery-1.6.4.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.signalR-0.5.2.js")" type="text/javascript"></script> 
<script src="@Url.Content("~/signalr/hubs")" type="text/javascript"></script>

The following code shows how to create our MatriX Hub in JavaScript and connect it to the SignalR server. matrixHub is defined in the dynamically created JavaScript file we added before.

<script type="text/javascript">
    $(function () {
        var matrixHub = $.connection.matrixHub;
		// TODO, callbacks and hub invoker

Now we add the JavaScript code which gets executed when we press the Login and Logout buttons on our wegpage.

The Login button executes the Open function in our C# Hub and passes username, password and XmppDomain. The Logout button executes the Close function without any parameters.

This is all that has to be done to execute a Hub function from JavaScript in realtime.

$("#loginButton").click(function () {

$("#logoutButton").click(function () {

The last pieces which are missing are the JavaScript functions we execute form the Hub to send data to the webpage from the server.

The sendXml and readXml callbacks append the Xml debug to a div. The onMessage callbacks appends a incoming message to a div.

// signalR callback for outgoing xml debug
matrixHub.sendXml = function (message) {
    $("#log").append("<span class='log send'>" + message + "</span><br/>");

// signalR callback for incoming xml debug
matrixHub.receiveXml = function (message) {
    $("#log").append("<span class='log recv'>" + message + "</span><br/>");

matrixHub.onMessage = function (msg) {
            "<span class='from'>" + msg.From + ":</span>" +
            "<span class='message'>" + msg.Body + "</span>" +

SignalR can also send data to all connected clients or a group of clients, but we don’t need these features.

SignalR handles all the connection stuff for the client and the server automatically for us, and keeps the connection always alive. It chooses the right connection technique for your browser and scales on the server with modern async and await techniques.

Under the hood SignalR is using the same techology as BOSH. On the web server MatriX connects to the XMPP server directly over the default TCP transport. This means you can connect to any XMPP server including Google Talk, Facebook or Windows Live Messenger without using a BOSH proxy from your web page.

The complete example is included in the latest MatriX download.

This post refers to a SinalR version 0.5.x. There were many incompatible API changes in SignalR, so many stuff in this post in not compatible with the current SingalR versions.
The example included in the MatriX download should be always up to date.

MatriX for WinRT

Windows 8 with the new Metro UI is coming soon. We were working hard in the last weeks to port MatriX also to WinRT. Because WinRT is only a subset of the full .NET Framework and introduces many new techniques, namespaces and classes we had to rewrite lots of our code. We are happy to announce that a Beta version of MatriX for WinRT is available now.

Please contact us when you are interested at the beta version.

Customer support is amazing

I have analyzed lots of .net xmpp sdk and Matrix is the best and the easiest to use.
Customer support is amazing.

Seckin Durgay, Matriks

BOSH prebind in MatriX and attach to Strophe

Why prebind and attach?

When your web application is already logged in and needs to establish a XMPP connection you have a seamless and secure solution with prebind and attach. You don’t have to ask the user to provide the credentials again, and you don’t have to render the credentials insecure in your HTML output.

Prebind with MatriX

This code shows how to prebind a session with MatriX. On success MatriX raises the OnPrebind event and provides the Jid, Rid and Sid in the PrebindEventArgs. The Rid is the last one used by MatriX and must be incremented before getting passed to Strophe.
You can render this params in a new page and attach the session with Strophe.

var xmppClient = new XmppClient
	Username = "testuser",
	XmppDomain = "ag-software.de",
	Password = "secret",
	Transport = Matrix.Net.Transport.BOSH,
	Uri = new System.Uri("http://ag-software.de/http-bind/")

// subscribe to the prebind event
xmppClient.OnPrebind += client_OnPrebind;

void client_OnPrebind(object sender, PrebindEventArgs e)
	prebindArgs = e;
// start prebinding with MatriX now

You can download a complete ASP .NET example project here:
Bosh Prebind Example

MatriX XMPP library for iOS and Android available

MatriX XMPP library for iOS and Android is in Beta status now. Both versions are based on MonoTouch and Mono for Android from Xamarin.

Using this technology you can easily port your existing MatriX based c# XMPP apps to iOS and Android and resuse most of your existing code and business logic.

When you are interested in Beta testing then please contact us.

Microsoft adds XMPP support to Windows Live Messenger

This are great news for the XMPP community. Microsoft has added XMPP client support to their Windows Live servers. You can read the announcement here.

Microsoft does not support any of the mandatory SASL mechanisms SCRAM, DIGEST-MD5 and PLAIN. Instead they have implemented their own X-MESSENGER-OAUTH2 SASL mechanism. This means that all existing XMPP Software is not able to connect to their server without code changes or updates.

I have updated the MatriX library to support the X-MESSENGER-OAUTH2 SASL mechanism. You can download the latest binary here.

Here is an example how you can connect to Windows Live Messenger with MatriX.
The XMPP domain is messenger.live.com. Microsoft has the proper SRV records, so MatriX discovers the hostname automatically. All you have to do is subscribe to the OnBeforeSasl event and disable the the automatic SASL mechanism selection and choose the X_MESSENGER_OAUTH2 mechanism for authentication. Additional you have to pass SaslProperties which include your access token.

var xmppClient = new XmppClient {XmppDomain = "messenger.live.com"};
xmppClient.OnBeforeSasl += xmppClient_OnBeforeSasl;

private void xmppClient_OnBeforeSasl(object sender, SaslEventArgs e)
	e.Auto = false;

	const string ACCESS_TOKEN = "your_access_token";
	e.SaslMechanism = SaslMechanism.X_MESSENGER_OAUTH2;
	e.SaslProperties = new LiveMessengerProperties
							   AccessToken = ACCESS_TOKEN

Of course you must retrieve your access token before you can connect with MatriX.

Some additional useful resources from Microsoft:


Alex from AG-Software is a bright individual who we have worked with on several occasions regarding the implementation of XMPP servers and development understanding in order to introduce the technology into our vehicle tracking solution at that time. He is very professional, hardworking and technically able, I would recommend Alex to anyone thinking of introducing XMPP into their organisation.

Simon Atherton, Tracking By Design

Matrix as made XMPP fun

Matrix has made XMPP fun and easier to develop for windows and ce platform. The sdk as been well thought out and offers a whole host of functions to allow you to become up and running in a very quick time.

Support is not too bad at all, but the forum does provide plenty of answers to common problems so it should be rare to really need any in depth support.

In all I would say that Matrix does offer a great sdk and it will save you many man hours in xmpp development. I do reccomend it and as yet not discovered any major issues.

However still waiting for Alex to finish socks5 encoding. Which i think will add a new dimension to this wonderful product.

Max Parsons, Taximax

We are very impressed

We’ve been running agsxmpp for about 2 years, at the heart of a high volume mission critical application, and I don’t believe we’ve ever had a single error that could be traced back to it. We were very impressed. I’m looking forward immensely to using Matrix instead, as the inability to use standard LINQ was pretty much the only complaint any of us had with the software.

Chris Hagan, Monash University

MatriX status update

I have not posted any updates for a while, which does not mean that there aren’t any.
So what I am working on?

There is huge progress in MatriX. Many of our customers are demanding support for special XEPs and other library extensions. So I have been working very close with them implementing many new XEPs and other useful features. I will create separate blog posts for some of these features.

Windows Phone Mango is coming now with sockets. So I have added sockets to the Windows Phone Mango version which is RTM now.

The port of MatriX to Android using mono for Android is nearly finished. You can expect a beta version very soon. Drop me an email when you are interested to join the beta test.

Whats next? Once the Android version is done I will start to work on a iOS version with MonoTouch.

You will be able to target all major mobile platform and reuse lots of your existing code and business logic.

There was no official release for a while, but the latest stable builds are always located here: http://www.ag-software.net/download-directory/