[Windows (Phone) 8] Using SignalR in Windows (Phone) 8 apps!

January 2nd, 2013 | Posted by Tom in .NET | Article | Windows 8 | Windows Phone | WinJS | WinRT | Read: 12,468

ASP.NET SignalR is a project developed by Microsoft to allow developers to add real-time web functionality to your applications. Here is the official description of the project:

ASP.NET SignalR is a new library for ASP.NET developers that makes it incredibly simple to add real-time web functionality to your applications. What is “real-time web” functionality? It’s the ability to have your server-side code push content to the connected clients as it happens, in real-time.

You may have heard of WebSockets, a new HTML5 API that enables bi-directional communication between the browser and server. SignalR will use WebSockets under the covers when it’s available, and gracefully fallback to other techniques and technologies when it isn’t, while your application code stays the same.

SignalR also provides a very simple, high-level API for doing server to client RPC (call JavaScript functions in your clients’ browsers from server-side .NET code) in your ASP.NET application, as well as adding useful hooks for connection management, e.g. connect/disconnect events, grouping connections, authorization.

So as soon as you plan to push content from your server to one (of more) of clients, you might take a look at SignalR. I’ve started to play with it this week (a good way to start the new year) and so, here is a brief introduction to this (and powerful) framework!

First, on the server side, you have to add a reference to the correct Nuget package (be careful, the project is not in the stable branch yet):

image

Then, you have to create a Hub, in other words a kind of endpoint that will expose the methods to all the clients. Defining a hub just mean create a class that derive from the Hub class:

public class DemoHub : Hub
{
    public void Send(string message)
    {
        Clients.All.getMessage(message);
    }

    public string SayHello(string name)
    {
        return "Hello" + name;
    }
}

Deriving from the Hub class allows you to access to the Clients property which can be used to access:

  1. To all the clients connected (through the All property),
  2. To the caller of the method (through the Caller property),
  3. Etc

image

Once that you get access to the list of clients you want, you can call the methods that you want on that clients (here, on our code, we call the getMessage of each clients, passing in parameter needed):

public void Send(string message)
{
    Clients.All.getMessage(message);
}

Of course, you can also defined some methods that will be called by the clients:

public string SayHello(string name)
{
    return "Hello" + name;
}

Now that the server part is done, we can start the client part. SignalR have Nuget packages for most of the client API: .NET, Windows Phone, WinRT, Silverlight and even Javascript: this is very powerful !

First, we need to create a connection to the Web Server:

var connection = new HubConnection("http://localhost:49449/");

Once this is done, we can create a proxy that will allow us to invoke methods on the server (and being notified when the server call a method on the clients): it’s the same job as the WCF proxy created when you add a service reference (except that this new one is not strongly typed):

var proxy = connection.CreateHubProxy("DemoHub");

You can see that the CreateHubProxy method takes in parameter the class name of the Hub you’ve created on the Web Server. If you want, you can use the HubName attribute (on the Hub class) to get a kind of alias for your hub:

[HubName("MyHubTest")]
public class DemoHub : Hub

In that case, the method CreateHubProxy will look like:

// Create a proxy to the service
var proxy = connection.CreateHubProxy("MyHubTest");

Next, you have to perform 2 things:

  1. Add a kid of event handler to all the methods that will be called by the server of the clients
  2. Start the connection

If the second one is really simple (just call the Start method of the HubConnection type), the first one is simple too. Indeed, on the proxy you’ve created, you can use the extension method On, that takes in parameters:

  1. The name of the “event” you want to be notified
  2. An Action (and its parameters) corresponding to the parameters sent from the server

image

So, in our case, if we want to be notified when the method getMessage is called from the server, we just need to use the following code:

proxy.On("getMessage", message =>
{
    this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => lb.Items.Add(message));
});

// Start the connection
await connection.Start();

Pretty simple!

Lastly, we need to be able to invoke the methods defined on the Hub so we’ll use the method Invoke of the proxy:

// Call the method on the server
await proxy.Invoke("Send", "My name is WinRT");

// Call the method on the server and get the result
var s = await proxy.Invoke<string>("SayHello", "Tom");

Now, let’s use the same code from an application console:

// Connect to the service
var connection = new HubConnection("http://localhost:49449/");

// Create a proxy to the service
var proxy = connection.CreateHubProxy("DemoHub");

// Start the connection
await connection.Start();

// Call the method on the server
await proxy.Invoke("Send", "My name is Console");

(As you can see, the code is strictly the same !)

If we launch the application from the Windows 8 side (the one where the handler to getMessage has been set), we can see that all the messages has been sent to the server and broadcast to the clients:

image

So, as you can see, getting push system in any kind of applications is pretty easy using SignalR. If you want to get more info, you can take a look at the Wiki. Also, don’t hesitate to go to David Fowler’s blog, the main developer of the project.

 

Happy coding!

You can follow any responses to this entry through the RSS 2.0 You can leave a response, or trackback.

Add Comment Register



Leave a Reply