In the previous article, we have seen How to create editable cell in jquery datatable. Here In this article, we will learn, How to implement a SignalR Push Notification in Asp.Net. for notifying connected users when one user done any action on the server.
Now a day’s most of the applications are multi-user application, where multiple users done their task on the same time. The Actual problem is any user(s) done any action (ex. Send Broadcast Message) other user doesn’t know it unless refresh the application.
We have a right way to notify all the connected users if there any changes happen on the server without reload the web page or update the web page. This is the in which asp.net SignalR comes into play.
What is SignalR?
Asp.Net SignalR is a library for Asp.Net developers that make developing real time web functionality easy. SignalR allows bi-directional communication between server and client. Server can now push content to connected client instantly as it becomes available.
Just follow the following steps to implement “SignalR Push Notification”.
In this article, we have used Visual Studio 2015, Apsp.Net Technology, and SQL Server Management Studio.
Step 1: Create new empty project.
Open visual studio and Go to File > New > Project > ASP.NET Web Application in left side Web option > Enter Application Name > Click on Ok > Select empty template > Click Ok.
Step 2: Create Database and Table.
Open SQL server management studio > Connect to SQL Server Database Engine > Right click on Database > select New Database > Enter Database name (Chathub) > click on Ok. A Database is created, Expand the Database there you can see Table option so, Right click on Tables > Select Table > Add fields in Table with proper data type > Save Table (Ctrl + S) enter table name Tbl_Chat.
CREATE TABLE [dbo].[Tbl_Chat](
[Id] [int] IDENTITY(1,1) NOT NULL,
[FromUser] [nvarchar](50) NULL,
[Message] [nvarchar](max) NULL,
CONSTRAINT [PK_Tbl_Chat] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
Step 3: Add Entity Data Model.
Go to Solution Explorer > Right click on project name from solution explorer > Add New folder > Enter Folder Name (model). Right click on model folder > Select Add New Item > From Left Panel Select Data > Select ADO.NET Entity Data Model > Enter model name > click on Add button.
A Popup window will open that is Entity Data Model Wizard > Select Generate from database > Next choose your data connection > Select your database > Next > Select Tables > enter Model Namespace > finally click on Finish.
Step 4: Install Entity Framework and SignalR NuGet Package.
Go to Solution Explorer > Right click on Project name > Select Manage NuGet Packages > Click on Browse Option > Search Entity Framework > Click on Install. Search SignalR > Select SignalR > Click on Install.
We can install packages from package manager console.
Go to Tools (Menu) > Select Library Package Manager > Open the “Package Manager Console” > Write the below command.
- PM> Install-Package Microsoft.AspNet.SignalR
After installed SignalR package, a scripts folder is created automatically, and you can see in scripts folder Jquery, Jquery.SignalR file is available. We will use this two file in our web application.
Step 5: Add an Owin startup file.
Add an Owin startup class in application for enabling the SignalR in our application. Go to Solution explorer > Right click on your project > Add New Item > select OWIN Startup Class > Enter the class name (Startup.cs) > Add.
Replace the below code in recently created Startup.cs file.
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(SignalRChat.Startup))]
namespace SignalRChat
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
//Any coonection or hub wire up and configuration should go here
app.MapSignalR();
}
}
}
Step 6: Add SignalR Hub Class
Here in this application, we will use this for showing notification. SignalR uses ‘Hub’ objects to communicate between the client and server. Go to the Solution Explorer > Right click on the project > Add New Item > Select SignalR Hub Class > Enter the name of class ChatHub > Click on Add.
Replace the following code into the ChatHub class file.
using Microsoft.AspNet.SignalR;
using SignalRChat.model;
namespace SignalRChat
{
public class ChatHub : Hub
{
public void Send(string name, string message)
{
//save chat in DB.
ChathubEntities1 objEntity = new ChathubEntities1();
Tbl_Chat chat = new Tbl_Chat();
chat.FromUser = name;
chat.Message = message;
objEntity.Tbl_Chat.Add(chat);
objEntity.SaveChanges();
// Call the broadcastMessage method to update clients.
Clients.All.broadcastMessage(name, message);
}
}
}
In the above code we inherit the Hub class and create one “Send” method with two parameter (name, message). In this method we store the message details in DB and then broadcast this message to all connected clients.
Step 7: Create HTML page for send and showing notification.
Create index.html page and load the Bootstrap CDN, JQuery, Bootstrap Js, Jquery.SignalR Js in the head section. In between script tag we will write the code for message send and notification. In between body tag we will write the HTML code for design the page.
<!DOCTYPE html>
<html>
<head>
<title>SignalR Simple Chat</title>
<meta charset="utf-8" />
<style type="text/css">
.chatContainer {
background-color: floralwhite;
border: thick solid #808080;
padding: 20px;
margin: 20px;
}
</style>
<!-- Style References -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!--Script References-->
<script src="scripts/jquery-1.10.2.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="scripts/jquery.signalR-2.1.2.min.js"></script>
<script src="signalr/hubs"></script>
<script type="text/javascript">
$(function () {
// Declare a proxy to refernce the hub.
var chat = $.connection.chatHub;
//Create a function that the hub can call to broadcast messages.
chat.client.broadcastMessage = function (name, message) {
var Name = $('<div />').text(name).html();
var Msg = $('<div />').text(message).html();
//Add the message to the page
$('#msgs').append('<li><strong>' + Name + '</strong>: ' + Msg + '</li>');
};
//Get the user name and store it to prepend messages.
$('#displayname').val(prompt('Enter your name:', ''));
//Set initial focus to message input box.
$('#message').focus();
//Start the connection
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
//Call the Send Method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
//Clear textbox and reset focus for next comment.
$('#message').val('').focus();
});
});
});
</script>
</head>
<body>
<div class="row">
</div>
<div class="row">
<div class="col-md-3">
</div>
<div class="col-md-6">
<div class="chatContainer">
<input type="text" id="message" />
<input type="button" id="sendmessage" value="Send" />
<input type="hidden" id="displayname" />
<ul id="msgs"></ul>
</div>
</div>
<div class="col-md-3">
</div>
</div>
</body>
</html>
In the above code we have load the “signalr/hubs” script reference but it actually not available in project folder. This is automatically creating the “signalr/hubs” while save and run the application. In runtime this folder will create automatically.
Run the application, copy you’re running application URL and open another browser or other tab and paste the copied URL and Enter. Enter your name in the prompt and then write the message and click on Send button. Open your second browser or tab and you can see your message without reload the page.
I hope this tutorial is helpful to you for create push notification, if you have any query then comment me in below comment box.
No comments:
Post a Comment