Saturday, May 9, 2015

SignalR - Damien Edwards' MoveShape sample . Getting it to work with latest SignalR + Sample Project


I had a good learning experience with SignalR. I started by watching Damien Edwards Video on YouTube. Now I am officially the SignalR newbie and I am hoping to keep climbing this ladder in upward direction :)

In this post I would like to share my experience with the Move Shape example that Damien showed in his video. I initially followed all the instructions as he demonstrated, but I failed to get it to work. I then read through the SignalR documentation and found that the latest version has a few changes since that video was filmed. I corrected the example and this post contains all the things that are different and of course the sample project source code for you to download. So lets get started.


As you may have noticed in the video, this was how the example worked. You drag and move the box in one browser, the box in other browser will follow the movements.


First thing you would need to change is in the Hub definition file. Or the MoveShapeHub class. There are a couple of changes in the class code.

  1. Hub methods have to be attributed using HubMethodNameAttribute
  2. Instead of calling the client method on Clients object, you have to call it on Clients.All property.

So the new code looks like this (notice the highlights)

    public class MoveShapeHub : Hub

        public void MoveShape(int x, int y)
            Clients.All.shapeMoved(Context.ConnectionId, x, y);

The next thing that is changed is the way hub was extended. If you remember the video, he used the $.connection.extend method. But now you just have to define it like a regular prototype

    hub.client.shapeMoved = function (cid, x, y) {
        if ($ != cid) {
            $shape.css({ left: x, top: y });

Also notice that instead of hub.shapeMoved, it is now called hub.client.shapeMoved. Next change goes inside the drag handler. Instead of calling hub.moveShape, you have to call hub.server.moveShape.

so the Hub's start-done handler looks like this

    $.connection.hub.start().done(function() {
            drag: function () {
                hub.server.moveShape(this.offsetLeft, this.offsetTop || 0);

And you're done. Happy coding!

Downloading the sample project

You can download the full-blown VS2013 Solution Here.