Using SignalR on Windows Phone 7

Windows phone topic If you need real time communication between two or more clients and you are using Microsoft stack, SignalR is the way to go. If you take a look at their github samples, you’ll notice that they already have sample for Windows Phone 8. What about Windows Phone 7 support? Well, due to the beauty of open source, you simply fork it and write the missing client library.

However, this might not be as easy as one thinks. Open the Microsoft.AspNet.SignalR.sln solution and locate Microsoft.AspNet.SignalR.Client.WP8. If you take a closer look, you’ll notice that this project consists only of linked files shared with other client libraries. So let’s add a new project and name it Microsoft.AspNet.SignalR.Client.WP7 (although it would be better to name it 7.1 or 7.5). Now drag all files and folders from the WP8 project to the WP7 project while holding down the Alt key. This adds files as links instead adding their copies. Once you are done, hit Compile.

It won’t compile you say. Of course it won’t, so let’s fix it.

What is missing from this project are three things: support for async/await pattern for Windows Phone 7 projects (I presumed you are using Visual Studio 2012) and Newtonsoft.Json. Once you add those via NuGet, you will be left with a few compiler errors complaining the lack of HashSet<T>. You can either create your own wrapper, decompile it from some other .NET version or us my naive implementation. Either way, supply your implementation and once you are done, you can finally compile WP7 project and we can move on to building some apps.

Create a new Windows Phone 7 application (single page template is good enough) and insert the following XAML in the last Grid element:

<ListBox x:Name="listInfo"></ListBox>

And now for the actual code that does something, add this to MainPage.xaml.cs:

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
    var connection = new Connection("http://host:40476/raw-connection");

    connection.Received += data => Report(data);

    connection.Reconnected += () => Report("[{0}]: Connection restablished", DateTime.Now);

    connection.StateChanged += change => Report(change.OldState + " => " + change.NewState);

    connection.Error += ex =>
    {
        Report("========ERROR==========" + ex.Message + "=======================");
    };

    connection.Start();
}

void Report(string message)
{
    Dispatcher.BeginInvoke(() =>
                            listInfo.Items.Add(message));
}

void Report(string format, params object[] args)
{
    Dispatcher.BeginInvoke(() =>
                            listInfo.Items.Insert(0, string.Format(format, args)));
}

This is basically the same code from the console client twisted a little bit for this application. Don’t forget to add reference to the previously created class library and install async targeting pack to this project also.

Now, to actually try out this example, run the projects in the following order:

  • Microsoft.AspNet.SignalR.Hosting.AspNet.Samples
  • Microsoft.AspNet.SignalR.Client.Samples
  • Microsoft.AspNet.SignalR.Client.Samples (no, this is not a mistake, run it twice for more clients :) )
  • Microsoft.AspNet.SignalR.Client.WP7.Sample – finally, our WP7 app

What will happen now is the following: you will host the web application that actually holds the SignalR service on IIS Express and both console clients and Windows Phone 7 application will connect to it. Once they are connected, simply type something in the console client and hit Enter. You should get the same message in other clients immediatel (including itself). You can also navigate to http://localhost:40476/Raw/ to see the same message. The following screenshot shows results on my machine.
SignalR running in several clients

Now go build your own cool apps using SignalR. If you were lazy to write all this code down, you can get the code from github over at tpetrina/SignalR. Once I figure out how this open source thing works, it will probably end in the main branch. Also, beware of HashSet :) .

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Last updated by at .