SignalR – Simple Implementation

Hi Guys,

Back with an interesting post here. I was recently trying to find a simple and to the point example of SignalR with no big code snippets to work with. It was somewhat complex to understand the whole picture. Anyways, here is the “to the point” with no extra details small application.

It consists of

  1. Web Application (Our Host for SignalR)
  2. Windows Client Application (Demonstrating how you can invoke SignalR and Interact with)
  3. Source Code attached at end of this article
Web Application – The Host
Follow these steps
* Create Empty VS 2012 – Web Application Project
* Install SignalR Package from NuGet (Microsoft ASP.Net SignalR)
Signlar_Select
* Add Global.asax
* Put in following Code

       protected void Application_Start(object sender, EventArgs e)        {

            RouteTable.Routes.MapHubs();

        }

*  Add Default.aspx

* Paste following HTML

<%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”Default.aspx.cs” Inherits=”WebCommunicator.Default” %>

<!DOCTYPE html>

<html xmlns=”http://www.w3.org/1999/xhtml”&gt;

<head runat=”server”>

    <title></title>

    <script src=”Scripts/jquery-1.6.4.min.js”></script>

    <script src=”Scripts/jquery.signalR-1.0.1.js”></script>

    <script src=”signalr/hubs”></script>

    <script src=”Scripts/app.js”></script>

</head>

<body>

    <form id=”form1″ runat=”server”>

    <div>

        <input id=”txt” style=”width: 200px;” /><input type=”button” id=”btnSend” value=”Send”/>

        <div id=”messages”>

        </div>

    </div>

    </form>

</body>

</html>

 *  Add Hub code in App_Code folder for the project

    

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using Microsoft.AspNet.SignalR;

using Microsoft.AspNet.SignalR.Hubs;

 

namespace WebCommunicator.App_Code

{

    [HubName(“commHub”)]

    public class CommunicationHub : Hub

    {

        public void send(string message)

        {

            Clients.All.addMessage(message);//this should be in js

            Clients.Caller.sendAcknlowedge(message + ” received …”);

        }

    }

}

*  Add app.js in Scripts folder in web project

$(document).ready(function () {

    $(function () {

        var commHub = $.connection.commHub;

        commHub.client.addMessage = function (message) {

            $(“#messages”).append(“<li>” + message + “</li>”);

        };

        commHub.client.sendAcknlowedge = function (message) {

            $(“#messages”).append(“<li><b><i>Server Responded: ” + message + “</i></b></li>”);

        };

        $(“#btnSend”).click(function () {

            commHub.server.send($(“#txt”).val());

        });

        $.connection.hub.start();

    });

});

AND THAT’s IT FOR Server Side Code …

Easy Right? 🙂

Now, Let’s make Windows Client for it…

Windows Client

* Create a New Windows Form Project (You can make WPF/ Windows Phone Etc …)

* Install Client Package for SignalR from NuGet

Full Code Snippet for the Window Form (Paste this code and add a text box and two buttons in designer)

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

using Microsoft.AspNet.SignalR;

using Microsoft.AspNet.SignalR.Client;

using Microsoft.AspNet.SignalR.Client.Hubs;

 

namespace WebCommunicator.WinClient

{

    public partial class Form1 : Form

    {

        IHubProxy proxy;

        HubConnection connection;

        public Form1()

        {

            InitializeComponent();

            this.FormClosing += Form1_FormClosing;

        }

 

        void Form1_FormClosing(object sender, FormClosingEventArgs e)

        {

            if (connection != null)

                connection.Disconnect();

            connection = null;

        }

 

        private void button1_Click(object sender, EventArgs e)

        {

//Put your url here.. i published to iis before using it from client.

             connection = new HubConnection(@”http://172.16.27.128/WC/“);

            proxy = connection.CreateHubProxy(“commHub”); //name from the hubName attribute

           //to receive the callback from server. You can do anything on this!

             proxy.On(“sendAcknlowedge”, 

                msg => 

                this.Invoke(() => listBox1.Items.Add(msg)));

            connection.Error += connection_Error;

            connection.Start().Wait();

        }

        void connection_Error(Exception obj)

        {

            MessageBox.Show(obj.Message);

        }

//send message to server

        private void button2_Click(object sender, EventArgs e)

        {

            proxy.Invoke<string>(“send”, textBox1.Text); //this “send” is defined on hub

        }

    }

    public static class ControlExtensions

    {

        public static void Invoke(this Control Control, Action Action)

        {

            Control.Invoke(Action);

        }

    }

}

That’s IT for client…

Now, as you have already deployed the web application… You can open multiple browsers from a machine or from multiple machine and see the magic.

I had two machines (Mac and Windows) – Used safari from mac and  windows for forms app and IE test… It worked all great.

Signlar in Action

NOTE:

This is really to the point working solution. I will describe each item in next article soon. Also you can find details for each of them everywhere on the internet. I had to share this as i had problem gathering information. So, hopefully that will some of people.

Gotchas:

  1. Leave aside what you know about applications. Just start with it. If you will think too much, you will never get it working.
  2. Remember HubName
  3. Make sure order of js files inclusion is correct, just like mentioned above
  4. if you get $.connection as undefined means that you don’t have javascript files loaded correctly.

You can download source code from here… WebCommunicator.zip (Source Code)

One thought on “SignalR – Simple Implementation

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.