Sony Arouje

a programmer's log

Posts Tagged ‘SignalR

Meteor as a persistence layer

leave a comment »

The idea of considering Meteor as a persistence layer might be crazy. But there is a good reason for doing that, the real time pushing of data to connected clients using Distribute Data Protocol. Then why cant we write the entire application in Meteor including the User interface, yes we can Meteor supports it. But some people have preference or every one might not be comfortable in creating stunning UI in Meteor but good in ASP.NET. So how do we bridge the best of both the worlds. Let’s take a look at it.

Let’s think about an online Cricket score board, what are all the components we might have

  1. A score feeder, a deamon that gets the score from a REST Api or a web service and updates to database.
  2. A web app that fetches the data and present it to the user.

The issue here is to get the updated score the user needs to refresh the page. What if user gets the data in real time without doing any page refresh. Let’s see how to add these kind of features.

Here the UI will be in ASP.NET and the DDP client library is DDPClient.NET and for real time signalling of data to connected client, we can use SignalR. DDPClient.NET is integrated with SignalR.

 

MeteorPersistenceLayer

 

Let’s have a look at how DDPClient.NET can be used in this scenario to push data to connected clients. In one of my previous post I explained a bit detail about DDPClient.NET. Recently I added SignalR framework to it to extend DDPClient accessible from any type of application, be it an ASP.NET or Javascript app or Windows Phone or Desktop app that can act as SignalR Client.

Rest of the post we will see how to receive real time updates from Meteor server using DDPClient.NET.

Right now in DDPClient.NET, SignalR uses self hosting approach. Let’s see how to start the DDPClient.NET, for test I hosted it in a console application.

 

class Program
{
    static void Main(string[] args)
    {
        DDPClientHost host = new DDPClientHost("http://localhost:8081/", "localhost:3000");
        host.Start();
        Console.ReadLine();
    }
}

 

DDPClientHost take two parameters the first one is, in which URL DDPClient.NET should listen for incoming request, the second one is to specify where Meteor server is running. Then just call the Start function in the DDPClientHost instance. That’s it, now DDPClient.NET is ready to receive incoming request.

ASP.NET Javascript client

Let’s see how to subscribe to a Meteor’s published item from a javascript client.

$(function () {
    var connection = $.hubConnection('http://localhost:8081/');
    proxy = connection.createProxy('DDPStream')
    connection.start()
             .done(function () {
                 proxy.invoke('subscribe', 'allproducts','product');
                 $('#messages').append('<li>invoked subscribe</li>');
             })
             .fail(function () { alert("Could not Connect!"); });


             proxy.on('flush', function (msg) {
                 $('#messages').append('<li>' + msg.prodName + '</li>');
             });

});

Let’s do a quick walkthrough of the code. As you can see

  • The hubÇonnection should point to the url where DDPClient.NET is listening.
  • The proxy should be created for DDPStream, it’s a SignalR Hub and is mandatory to use the same name.
  • Once the connection started successfully, we should invoke the Subscribe function declared in DDPStream hub with the published item name declared in Meteor. we should also pass the name of the Collection it returns, in this case it returns a collection of Product. If in case the Meteor’s published item name and the collection name is same then we can simply write proxy.invoke(‘subscribe’, ‘product’); You don’t have to pass the collection name’.

See the code below to see how to publish item from Meteor Server.

Meteor.publish("allproducts", function () {
    return Products.find();
});

Products is a Meteor’s collection that returns Product

Products = new Meteor.Collection("product");
  • Also we should have a function called Flush as shown below. This function will called by the DDPStream to send the data to the connected clients.
proxy.on('flush', function (msg) {
    $('#messages').append('<li>' + msg.prodName + '</li>');
});

Desktop/Console Application client

It’s similar to the code shown above but it will in C#. See the code below.

class Program
{
    static void Main(string[] args)
    {
        var hubConnection = new HubConnection("http://localhost:8081/");
        var ddpStream = hubConnection.CreateProxy("DDPStream");
        ddpStream.On("flush", message => System.Console.WriteLine(message.prodName));
        hubConnection.Start().Wait();
        ddpStream.Invoke("Subscribe", "allproducts","product");
        System.Console.Read();
    }
}

That’s it we are done. Now any insert or update of data to the product collection will get notified instantly to all the connected clients. If you run the application you can see the ASP.NET page will show any newly added product without refreshing the page. The DDPClient.NET is still in development.

You can download DDPClient.NET and the example from Github.

Happy coding…

Written by Sony Arouje

October 4, 2012 at 1:10 am

Posted in .NET

Tagged with , ,

SignalR – Real time pushing of data to connected clients

with 25 comments

Updated post about how to create a chat application using SignalR 2.1

How many times you might have refreshed your browser to see the updated score of a cricket match or refresh to get the updated stock details. Isn’t that cool if the browser can display the updated data without refreshing or doing a page load. Yes it is, then the next question come to mind is how to implement it using .NET technology. There is no straight forward approach, most of them have loads of code.

So how do we achieve it? The answer is SignalR. Scott Hanselman have a nice post about SignalR. In his post he explains a small chat application using 12 lines of code.

I wanted a real time pushing of data to ASP.NET, Javascript client or desktop clients for a project I am working on. The details of that project I will post it later. I am aware of SignalR but never really tried or doesn’t know how to make it work. Yesterday I decided to write a tracer to better understand how SignalR works. This post is all about that tracer I created.

Tracer Functionality

The functionality is very simple. I need two clients a console and a web app. Data entered in any of these clients should reflect in other one. A simple functionality to test SignalR.

Let’s go through the implementation.

I have three projects in my solution 1. SignalR self hosted server 2. A console Client 3. A Web application.

SignalR server

Here I used a self hosting option. That means I can host the server in Console or Windows service. Have a look at the code.

using System;
using System.Threading.Tasks;
using SignalR.Hosting.Self;
using SignalR.Hubs;
namespace Net.SignalR.SelfHost
{
    class Program
    {
        static void Main(string[] args)
        {
            string url = "http://localhost:8081/";

            var server = new Server(url);
            server.MapHubs();
            
            server.Start();
            Console.WriteLine("SignalR server started at " + url);

            while (true)
            {
                ConsoleKeyInfo ki = Console.ReadKey(true);
                if (ki.Key == ConsoleKey.X)
                {
                    break;
                }
            }
        }

        public class CollectionHub : Hub
        {
            public void Subscribe(string groupName)
            {
                Groups.Add(Context.ConnectionId, groupName);
                Console.WriteLine("Subscribed to: " + collectionName);
            }

            public Task Unsubscribe(string groupName)
            {
                return Clients[groupName].leave(Context.ConnectionId);
            }

            public void Publish(string message, string groupName)
            {
                Clients[groupName].flush("SignalR Processed: " + message);
            }
        }

    }
}

As you can see from the main I hosted the SignalR server in a specific URL. You can see another Class called CollectionHub inherited from Hub. So what is a hub? Hubs provide a higher level RPC framework, client can call the public functions declared in the hub. In the above Hub I declared Subscriber, Unsubscribe and Publish function. The clients can subscribe to messages by providing a Collection Name, it’s like joining to a chat room. Only the members in that group receives all the messages.

You will notice another function called Publish with a message and a groupName. The clients can call the publish method by passing a message and a group name. SignalR will notify all the clients subscribed to that group with the Message passed. So what’s this ‘flush’ function called in publish, it’s nothing but the function defined in the client. We will see that later.

We are done, run the console application and our SignalR server is ready to receive requests.

SignalR clients

First we will look into a Console client. Let’s see the code first.

using SignalR.Client.Hubs;
namespace Net.SignalR.Console.Client
{
    class Program
    {
        static void Main(string[] args)
        {
            var hubConnection = new HubConnection("http://localhost:8081/");
            var serverHub = hubConnection.CreateProxy("CollectionHub");
            serverHub.On("flush", message => System.Console.WriteLine(message));
            hubConnection.Start().Wait();
            serverHub.Invoke("Subscribe", "Product");
            string line = null;
            while ((line = System.Console.ReadLine()) != null)
            {
                // Send a message to the server
                serverHub.Invoke("Publish", line, "Product").Wait();
            }

            System.Console.Read();
        }
    }
}

Let’s go line by line.

  1. Create a hub connection with the url where SignalR server is listening.
  2. Create a proxy class to call functions in CollectionHub we created in the server.
  3. Register an event and callback, so that Server can call client and notify updates. As you can the Event name is ’Flush’, if you remember the server calls this function in Publish function to update the message to clients.
  4. Start the Hub and wait to finish the connection.
  5. We can call any public method in declared in Hub using the Invoke method by passing the function name and arguments.

Run the console application and type anything and hit enter. You can see some thing like below.

image

The name prefixed ‘SignalR Processed’ is the message back from the SignalR server. So we are done with a console application.

Now how about we have to display the updates in a web application. Let’s see how to do it in web application. In web application I used javascript to connect to the SignalR server.

<html xmlns="http://www.w3.org/1999/xhtml">
    <script src ="Scripts/json2.js" type="text/jscript"></script>
    <script src="Scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.signalR-0.5.3.min.js" type="text/javascript"></script>
    <script type="text/javascript">
           $(function () {
               var connection = $.hubConnection('http://localhost:8081/');
               proxy = connection.createProxy('collectionhub')
               connection.start()
                    .done(function () {
                        proxy.invoke('subscribe', 'Product');
                        $('#messages').append('<li>invoked subscribe</li>');
                    })
                    .fail(function () { alert("Could not Connect!"); });


               proxy.on('flush', function (msg) {
                   $('#messages').append('<li>' + msg + '</li>');
               });

               $("#broadcast").click(function () {
                   proxy.invoke('Publish', $("#dataToSend").val(), 'Product');
               });

           });
    </script>
    <body>
        <div>
            <ul id="messages"></ul>
            <input type="text" id="dataToSend" />
            <input id="broadcast" type="button" value="Send"/>
        </div>
    </body>
</html>

 

You can install SignalR Javascript client from Nuget and it will install all the required js files. The code looks very similar to the one in Console application. So not explaining in detail.

 

Now if you run all three application together and any update in one client will reflect in other. As you can see in web client we use Javascript for DOM manipulation, so the page will never refresh but you will see the updated info.

image

I hope this post might help you to get started with SignalR.

Dowload the source code.

Happy coding….

Written by Sony Arouje

October 2, 2012 at 4:48 pm

Posted in .NET

Tagged with , ,

%d bloggers like this: