Angularjs+asp.net MVC+SIGNALR Implementation Message Push sample

Source: Internet
Author: User


Background

OA management system, the employee submits the application form, the message real-time informs the related personnel to carry on the approval in time, after the approval the result pushes to the user.

Technology options

The first thing to find is firebase, so excited to start to sell up. Firebase is simple to use: a reference to a JS can be, according to the official online tutorials quickly applied to the project. The next day to open the project found that the push function is not, this is why? Finally found Firebase official website can't open ... Is firebase by Google will also be celestial to the wall off? Perhaps Firebase himself hung up, in short, can not be used. Because to completely put the push data in the Firebase server to implement the push function, there will be the following several issues to worry about:

1. Data insecurity

2. Too strong dependence on firebase

3.firebase fee (Free edition too weak)

So decisively give up firebase, friend recommend have a call signalr Dongdong can try, this is specially for asp.net developers prepared a message push class library, and do not rely on other servers, free.

How to use

1. Search and add signalr latest version in NuGet


2. Refer to Jquery.signalr-2.2.0.min.js file in the page (depending on jquery) and add <script src= "/signalr/hubs" ></script> Scripts for automatic generation of SIGNALR

3. Add MsgHub.cs class for processing corresponding user information and message push implementation

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using Microsoft.AspNet.SignalR;
Using Microsoft.AspNet.SignalR.Hubs;
Namespace Zmeioa.services
{[Authorize]
[Hubname ("Zmhub")]
public class Msghub:hub
{///<summary>
Connection
</summary>
<returns></returns>
public override System.Threading.Tasks.Task onconnected ()
{
Groups.add (Context.connectionid, Context.User.Identity.Name);
Return base. Onconnected ();
}
<summary>
Re-connect
</summary>
<returns></returns>
public override System.Threading.Tasks.Task onreconnected ()
{
Groups.add (Context.connectionid, Context.User.Identity.Name);
Return base. Onreconnected ();
}
<summary>
Disconnect
</summary>
<param name= "stopcalled" ></param>
<returns></returns>
public override System.Threading.Tasks.Task ondisconnected (bool stopcalled)
{
Groups.remove (Context.connectionid, Context.User.Identity.Name);
Return base. Ondisconnected (stopcalled);
}
}
}
Note: SIGNALR push messages are based on user connections (ConnectionID), and SIGNALR automatically generates a ConnectionID for each session. But our push is based on the user (privilege system), that is, only after the login to register to this hub. Here I use is the groups of the SIGNALR, the login user's ConnectionID and corresponding UserID add to the groups, the push time as long as designated groups NAME,SIGNALR will automatically find its corresponding ConnectionID and send a message (this may not be the best way, because each user's userid will be added as groups key, when the user is very large groups will be huge, but I have not found a better alternative).

4. There are two forms of message push: A. Service-side direct push; b. Client Push.

The difference is that the service-side push is the persistent data can be pushed directly to the relevant people, and the client push is persisted after the data, the client based on the return value of the case, using the Signalr JS method to invoke the service side of the push function. I'm using the server-side push data directly, because after the data is persisted, it's entirely possible to notify the person concerned, and if you return to the foreground and then invoke the service-side push method, it's just superfluous.

such as: Notify the approver immediately after the successful preservation of the application form.

Get the hub's context in service

Message Push context
</summary>
protected static Ihubcontext Zmhubcontext = Globalhost.connectionmanager.gethubcontext<msghub> ();
Push messages to related people after saving requisition (Note: Dynamic method Broadcasttodo is the way to receive messages on the client)

public static Applyform Save (FormView view)
{//Omit business Operation ...///notify to be done
ZmHubContext.Clients.Groups (app. Auditorids.split (', ')). Broadcasttodo (App. Auditorids, new {type = "new", data = app});
return app;
}
5. Connect the hub when registering the angular module and pass it into the module as value so that each controller can use this connection:

var Zmhub = $.connection. Zmhub;
  var ZMapp = Angular.module (' ZMapp ', [' Ngroute ', ' ngresource ', ' ngsanitize ', ' ngmessages ', ' ngsvgattributes '] ). Value (' Zmhub ', zmhub);
6. Receive the push message in the controller of the homepage, and provide two kinds of push experience: A. Desktop Alert; b. On-page messages. Desktop Alerts are cool, even when the browser is minimized, in the bottom right corner of the desktop can also receive hints (Chrome and Firefox support, IE does not support)

function (UserIDs, obj) {
Notify subordinate controller of pending matters
$scope. $broadcast (' todoschanged ', obj);
Show Desktop Alerts
if (Obj.type = = ' new ') {//Desktop Alert title
var title = ' From [' + Obj.data.ApplicantName + '] application form ';
Requisition single type name
var formtypename = Defaultservice.getenumtext (Obj.data.Type);
var msg = ' [' + Formtypename + '] ' + obj.data.Name; Desktop Notification method
Notifyservice.notify (' Todos ', title, MSG);
}
}
The Receive method of subordinate controller (regarding Angularjs's broadcast not much explanation, do not understand can go to the official website to consult):

function (d, obj) {
$scope. $apply (function () {//If new data is added, add a bar to the current list
if (Obj.type = = ' new ') {
$scope. Todoapps.unshift (Obj.data);
}
else if (obj.type = ' delete ') {//If it is an undo request, delete the data in the current list
for (var j = 0 J < $scope. Todoapps.length; j + +) {
if ($scope. todoapps[j]. Id = = obj.data.Id) {
$scope. Todoapps.splice (J, 1);
Break
}
}
}
});
});
Desktop Notification Service:

function () {
return {
Notify:function (icon, title, msg) {
At a, let's check if we have permission for notification
If not, let ' s ask for it
if (window. Notification && notification.permission!== "granted") {
Notification.requestpermission (function (status) {
if (notification.permission!== status) {
Notification.permission = status;
}
});
}
var iconpath = '/content/images/icons/' + (icon | | ' info ') + '. png ';
var options = {
Lang: ' Zh-cn ',
Body:msg,
Icon:iconpath
};
var notify;
If the user agreed to get notified
if (window. Notification && Notification.permission = = "Granted") {
notify = new Notification (title, options);
}
else if (window. Notification && notification.permission!== "denied") {
Notification.requestpermission (function (status) {
if (notification.permission!== status) {
Notification.permission = status;
}
if (status = = "Granted") {
notify = new Notification (title, options);
}
else {
Console.log (' You have banned desktop alerts and can't push them to your desktop! ');
}
});
}
else {
Console.log (' You have banned desktop alerts and can't push them to your desktop! ');
}
if (notify) {
Notify.onclose = function (evt) {
};
Click to switch to browser
Notify.onclick = function () {
Window.focus ();
};
}
}
};
});

Desktop Alert effect:


Summarize:

Using SIGNALR to push messages is generally simpler, just a few simple steps to implement, and is Selfhost, do not have to worry about the dependencies of other servers and data security issues, interested friends can try.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.