Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

SignalR, Angular JS and ASP.NET MVC Real Time Communication

0.00/5 (No votes)
19 Mar 2015 1  
Using SignalR with AngularJS to develop real time communication application in ASP.NET MVC and C#.

Introduction

In this post, I will explain how we can use SignalR with AngularJS to develop real time communication application in ASP.NET MVC and C#. I had a problem where different CSRs are allowed to update same client information and one CSR update may overwrite other CSR's changing if both are trying to update at same time. The solution suggested by CSRs were "when anyone update record, instantly broadcast and show message to all CSRs who are on Edit page".

I achieved this functionality through SignalR with AngularJS and toaser.js as client side to show warning message. To read more about SingalR please follow link: http://signalr.net. I will list down steps with necessary code how you can develop this application:

Get Started

1 - First you need to get SingalR installed on your machine using NuGet Package or by following command:

Install-Package Microsoft.AspNet.SignalR.Sample

2 - Make sure you have following JS files in your solution, you can easily get them from their official websites:

  • angular.js
  • jquery.singalR-x.x.x.js
  • toaster.js

3: Create new SignalR hub class BroadcastMessageHub.cs and paste following code (to read more about SignalR and ASP.NET MVC please follow link: http://www.asp.net/signalr/overview/getting-started/tutorial-getting-started-with-signalr-and-mvc):

using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;

namespace JobTracker
{

  [HubName("chat")]
  public class MultiUserHub : Hub
   {

     public void SendMessage(string message)
      {
        Clients.All.newMessage(message);
      }
  }
}

 

4: Create another Startup.cs class and paste following code in it:

using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(JobTracker.Startup))]
namespace JobTracker
 {
   public class Startup
    {
      public void Configuration(IAppBuilder app)
       {
        app.MapSignalR();
       }
    } 
 }

 

5: Server side code and configuration is done, now move to client side, create two JS files app.js and mainCtrl.js. You can name them whatever you want, app.js will have angular module definition and function to communicate with server side hub.

app.js

//toaster is added as dependency that will show message in attractive warning message box, to read

//more about toaster.js please follow link: <a href="http://codeseven.github.io/toastr/demo.html">http://codeseven.github.io/toastr/demo.html</a>

(function () {
    angular.module('app', ['toaster']);

$(function () {
  $.connection.hub.logging = true;
  $.connection.hub.start();
 });

$.connection.hub.error(function (err) {
  console.log('An error occurred: ' + err);
 });

 angular.module('app').value('chat', $.connection.chat);
})();

 

mainCtrl.js

//$http service is used to get logged on user information from controller action, you can use $resource //service to get info through ASP.NET Web API.
//chat and toaster are dependencies defined in angular module to send message to all user and show
//it in toaster "warning" dialog box

"use strict";

angular.module('app').controller('mainCtrl', function ($scope, $http, chat, toaster) {
 $scope.messages = [];
 $http.get("GetLoginUserID").then(function (response) {
 $scope.LogonUserID = response.data;
});

$scope.sendMessage = function () {
 chat.server.sendMessage($scope.LogonUserID.data +' Just modified records, please refresh page to get latest!');
 $scope.newMessage = "";
};

chat.client.newMessage = function onNewMessage(message) {
 toaster.pop('warning', "Please read message!", message);

 $scope.messages.push({ message: message });

 $scope.$apply();

 console.log(message);
 };

});

 

6: Once you created these two JS files, make sure that your reference following JS files in your ASP.NET page or MVC view where you want to trigger message broadcast event:

  •  jquery.singalR-x.x.x.js
  • <script src='/signalr/hubs'></script> for dynamically generating scripts, you can check generated script through developer tool.
  • angular.js
  • toaster.js
  • app.js
  • mainCtrl,.js

7: You have to add following line for toaster container along timeout in millisecond for message dialog box:

<toaster-container toaster-options="{'time-out': 5000}"></toaster-container>

8: The final step is to bind event with button or any control, I am binding it with submit button, sendMessage is defined in mainCtrl.js which broadcast message:

<input id="btnSave" ng-click="sendMessage()" type="submit" value="Save" />

9: The application should be working as following:

"If there are two users UserA and UserB are on same edit screen, as soon UserA will submit btnSave button, toaster warning dialog box "UserA just modified record, please refresh page to get latest!" would be displayed on top right corner of screen on both UserA and UserB screens. The same functionality should be working for n number of logged on users.

 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here