Click here to Skip to main content
15,891,316 members
Articles / Web Development / HTML5
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
4.47/5 (9 votes)
19 Mar 2015CPOL2 min read 48.9K   34   4
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):

C#
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:

C#
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

JavaScript
//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

JavaScript
//$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:

HTML
<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:

HTML
<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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
United States United States
A Solutions Architect with more than fourteen years of experience in application development. I mostly work in .NET, Angular, MEAN stack technologies and love to share what I do and learn during my day to day job. Please check my tutorials and blog:
https://fullstackhub.io
https://fullstackhubblog.com

Comments and Discussions

 
QuestionGood Article BUT.......... Pin
ajalilqarshi31-Dec-15 1:20
ajalilqarshi31-Dec-15 1:20 
AnswerRe: Good Article BUT.......... Pin
Yaseer Mumtaz31-Dec-15 3:48
professionalYaseer Mumtaz31-Dec-15 3:48 
QuestionAngular 2, TypeScript and vNext Pin
Member 1123685522-Mar-15 20:01
Member 1123685522-Mar-15 20:01 
AnswerRe: Angular 2, TypeScript and vNext Pin
Yaseer Mumtaz23-Mar-15 8:06
professionalYaseer Mumtaz23-Mar-15 8:06 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.