TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Abdulmajeed Alshari
NA
266
61.4k
SignalR Notifications not show when add new row to table
Feb 1 2018 12:17 PM
Please developers help me a week ago I could not solve the problem
These is details of project as :
1- Startup.cs file as :
[assembly: OwinStartupAttribute(
typeof
(LinkForEmployment.Startup))]
[assembly: OwinStartup(
typeof
(LinkForEmployment.Startup))]
namespace
LinkForEmployment
{
public
partial
class
Startup
{
public
void
Configuration(IAppBuilder app)
{
app.MapSignalR();
ConfigureAuth(app);
}
}
}
2- NotificationHub.cs file as :
using
Microsoft.AspNet.SignalR;
namespace
LinkForEmployment
{
public
class
NotificationHub : Hub
{
//public void Hello()
//{
// Clients.All.hello();
//}
}
}
3- NotificationComponent.cs file as :
using
Microsoft.AspNet.SignalR;
using
System;
using
System.Collections.Generic;
using
System.Configuration;
using
System.Data.SqlClient;
using
System.Linq;
using
LinkForEmployment.Models;
using
System.Web;
namespace
LinkForEmployment
{
public
class
NotificationComponent
{
//Here we will add a function for register notification (will add sql dependency)
public
void
RegisterNotification(DateTime currentTime)
{
string
conStr = ConfigurationManager.ConnectionStrings[
"DefaultConnection"
].ConnectionString;
string
sqlCommand = @
"SELECT [UserId],[NotificationTitle],[NotificationIcon],[NotificationMessage],[link],[NotificationTime] from [dbo].[Notifications] where [NotificationTime] > @AddedOn"
;
//you can notice here I have added table name like this [dbo].[Contacts] with [dbo], its mendatory when you use Sql Dependency
using
(SqlConnection con =
new
SqlConnection(conStr))
{
SqlCommand cmd =
new
SqlCommand(sqlCommand, con);
cmd.Parameters.AddWithValue(
"@AddedOn"
, currentTime);
if
(con.State != System.Data.ConnectionState.Open)
{
con.Open();
}
cmd.Notification =
null
;
SqlDependency sqlDep =
new
SqlDependency(cmd);
sqlDep.OnChange += sqlDep_OnChange;
//we must have to execute the command here
using
(SqlDataReader reader = cmd.ExecuteReader())
{
// nothing need to add here now
}
}
}
void
sqlDep_OnChange(
object
sender, SqlNotificationEventArgs e)
{
//or you can also check => if (e.Info == SqlNotificationInfo.Insert) , if you want notification only for inserted record
if
(e.Type == SqlNotificationType.Change)
{
SqlDependency sqlDep = sender
as
SqlDependency;
sqlDep.OnChange -= sqlDep_OnChange;
//from here we will send notification message to client
var notificationHub = GlobalHost.ConnectionManager.GetHubContext
();
notificationHub.Clients.All.notify(
"added"
);
//re-register notification
RegisterNotification(DateTime.Now);
}
}
public
List
GetData(DateTime afterDate)
{
using
(ApplicationDbContext db =
new
ApplicationDbContext())
{
return
db.Notifications.Where(a => a.NotificationTime > afterDate).OrderByDescending(a => a.NotificationTime).ToList();
}
}
}
}
4-Global.asax.cs file as :
namespace
LinkForEmployment
{
public
class
MvcApplication : System.Web.HttpApplication
{
string
con = ConfigurationManager.ConnectionStrings[
"DefaultConnection"
].ConnectionString;
protected
void
Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
BundleConfig.RegisterBundles(BundleTable.Bundles);
SqlDependency.Start(con);
}
protected
void
Session_Start(
object
sender, EventArgs e)
{
NotificationComponent NC =
new
NotificationComponent();
var currentTime = DateTime.Now;
HttpContext.Current.Session[
"LastUpdated"
] = currentTime;
NC.RegisterNotification(currentTime);
}
protected
void
Application_End()
{
//here we will stop Sql Dependency
SqlDependency.Stop(con);
}
}
}
5- model class file is as :
public
class
Notification
{
public
int
Id {
get
;
set
; }
public
string
UserId {
get
;
set
; }
public
string
NotificationTitle {
get
;
set
; }
public
string
NotificationIcon{
get
;
set
; }
public
string
NotificationMessage {
get
;
set
; }
public
string
link {
get
;
set
; }
public
DateTime NotificationTime {
get
;
set
; }
}
6- NotificationController file is as :
public
class
NotificationController : Controller
{
public
JsonResult GetNotifications()
{
var notificationRegisterTime = Session[
"LastUpdated"
] !=
null
? Convert.ToDateTime(Session[
"LastUpdated"
]) : DateTime.Now;
NotificationComponent NC =
new
NotificationComponent();
var list = NC.GetData(notificationRegisterTime);
//update session here for get only new added contacts (notification)
Session[
"LastUpdate"
] = DateTime.Now;
return
new
JsonResult { Data = list, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
7- _Layout.cshtml Shared page as :
@using LinkForEmployment.Models;
@using Microsoft.AspNet.Identity;
<!DOCTYPE html>
<html lang=
"en-US"
>
<head>
<meta charset=
"utf-8"
/>
<meta name=
"viewport"
content=
"width=device-width, initial-scale=1.0"
>
<title></title>
@*@Styles.Render(
"~/Content/css"
)*@
<link href=
"~/Content/bootstrap.css"
rel=
"stylesheet"
/>
<link href=
"~/Content/bootstrap-rtl.min.css"
rel=
"stylesheet"
/>
<link rel=
"stylesheet"
href=
"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"
/>
<link href=
"~/Content/style.css"
rel=
"stylesheet"
/>
<script src=
"~/Scripts/modernizr-2.6.2.js"
></script>
</head>
<body>
<!--This partial view to show notification -->
@Html.Partial(
"_EmployerNavbar"
)
<!--Body Content-->
<div
class
=
"container-fluid pageContent myContainer"
id=
"cont"
>
<div
class
=
"row"
>
@RenderBody()
<hr />
</div>
</div>
<!--Footer Content-->
<footer
class
=
"page-footer"
>
<!--Write here Footer tags-->
</footer>
@*@Scripts.Render(
"~/bundles/jquery"
)*@
<script src=
"~/Scripts/jquery-1.10.2.min.js"
></script>
<script src=
"~/Scripts/jquery.signalR-2.2.0.min.js"
></script>
<script src=
"/signalr/hubs"
></script>
<script src=
"~/Scripts/bootstrap.min.js"
></script>
@*@Scripts.Render(
"~/bundles/bootstrap"
)*@
@* @RenderSection(
"scripts"
, required:
false
)*@
<style type=
"text/css"
>
/*Added css for design notification area, you can design by your self*/
/* COPY css content from youtube video description*/
.noti-content {
position: fixed;
right: 100px;
background: yellow;
color: blue;
font-size: medium;
font-style: oblique;
font-family: Arial;
border-radius: 4px;
top: 47px;
width: 440px;
display: none;
border: 1px solid #9E988B;
}
ul#notiContent {
max-height: 200px;
overflow: auto;
padding: 0px;
margin: 0px;
padding-left: 20px;
}
ul#notiContent li {
margin: 3px;
padding: 6px;
background: #FF6600;
}
.noti-top-arrow {
border-color: transparent;
border-bottom-color: #F5DEB3;
border-style: dashed dashed solid;
border-width: 0 8.5px 8.5px;
position: absolute;
right: 32px;
top: -8px;
}
span.noti {
color: lightgreen;
margin: 15px;
position: fixed;
right: 100px;
font-size: 30px;
cursor: pointer;
}
span.count {
position: fixed;
top: -1px;
/*color:white;*/
}
/*.noti:hover {
color:white;
}*/
</style>
@* Add jquery code
for
Get Notification & setup signalr *@
<script type=
"text/javascript"
>
$(
function
() {
// Click on notification icon for show notification
$(
'span.noti'
).click(
function
(e) {
debugger
;
e.stopPropagation();
$(
'span.noti'
).css(
"color"
,
"lightgreen"
);
$(
'span.count'
).hide();
$(
'.noti-content'
).show();
var
count = 0;
count = parseInt($(
'span.count'
).html()) || 0;
count++;
// only load notification if not already loaded
if
(count > 0) {
updateNotification();
}
$(
'span.count'
,
this
).html(
' '
);
})
// hide notifications
$(
'html'
).click(
function
() {
$(
'.noti-content'
).hide();
})
// update notification
function
updateNotification() {
$(
'#notiContent'
).empty();
$(
'#notiContent'
).append($(
'<li>Loading...</li>'
));
$.ajax({
type:
'GET'
,
url:
'/Notification/GetNotifications'
,
success:
function
(response) {
debugger
;
$(
'#notiContent'
).empty();
if
(response.length == 0) {
$(
'#notiContent'
).append($(
'<li>Currently You Have No New Notifications.</li>'
));
}
$.each(response,
function
(index, value) {
$(
'#notiContent'
).append($(
'<li>The User , '
+ value.NotificationTitle +
' '
+
'Of ID'
+
' ('
+ value.NotificationMessage +
') Is Written Something.</li>'
));
});
},
error:
function
(error) {
console.log(error);
}
})
}
// update notification count
function
updateNotificationCount() {
$(
'span.count'
).show();
var
count = 0;
count = parseInt($(
'span.count'
).html()) || 0;
count++;
$(
'span.noti'
).css(
"color"
,
"white"
);
$(
'span.count'
).css({
"background-color"
:
"red"
,
"color"
:
"white"
});
$(
'span.count'
).html(count);
}
// signalr js code for start hub and send receive notification
var
notificationHub = $.connection.notificationHub;
$.connection.hub.start().done(
function
() {
console.log(
'Notification hub started'
);
});
//signalr method for push server message to client
notificationHub.client.notify =
function
(message) {
if
(message && message.toLowerCase() ==
"added"
) {
updateNotificationCount();
}
}
})
</script>
<!--End Codes of Notification-->
<script src=
"~/Scripts/Style.js"
></script>
<script src=
"~/Scripts/OurJQuery.js"
></script>
</body>
</html>
8- _EmployerNavbar partial view that will show notifications as :
<
link
href
=
"~/Content/StyleSeekerNavbar.css"
rel
=
"stylesheet"
/>
<
style
>
.list-Items a:hover {
font-size: 14px;
}
.NotifyContenet {
font-size: 10px;
color: black;
}
.navbar-inverse .navbar-nav
>
.open
>
a, .navbar-inverse .navbar-nav
>
.open
>
a:hover, .navbar-inverse .navbar-nav
>
.open
>
a:focus {
color: #ffffff;
background-color: none;
}
.navbar {
/*background:#faebd700;*/
background: #002637;
}
</
style
>
<
div
class
=
"navbar navbar-inverse navbar-fixed-top"
>
<
div
class
=
"container"
>
<
div
class
=
"navbar-header"
>
<
button
type
=
"button"
class
=
"navbar-toggle"
data-toggle
=
"collapse"
data-target
=
".navbar-collapse"
>
<
span
class
=
"icon-bar"
>
</
span
>
<
span
class
=
"icon-bar"
>
</
span
>
<
span
class
=
"icon-bar"
>
</
span
>
</
button
>
<
a
href
=
"#"
class
=
"navbar-brand"
>
<
img
class
=
"logo-img"
src
=
"~/images/Job-Searh-icon-Converted1.png"
/>
</
a
>
</
div
>
<
div
class
=
"navbar-collapse collapse nav-font"
>
<
ul
class
=
"nav navbar-nav navbar-text"
>
<
li
class
=
"navbar-Items"
>
<
a
href
=
"~/Home/index"
class
=
"navbar-Item"
>
Main
</
a
>
</
li
>
<
li
class
=
"navbar-Items"
>
<
a
href
=
"#"
class
=
"navbar-Item"
>
Jobs
</
a
>
</
li
>
<
li
class
=
"navbar-Items"
>
<
a
href
=
"#"
class
=
"navbar-Item"
>
Job apply
</
a
>
</
li
>
<
li
class
=
"navbar-Items"
>
<
a
href
=
"#"
class
=
"navbar-Item"
>
How to use this Site
</
a
>
</
li
>
<!--This is Notification li tag -->
<
li
id
=
"navbar"
class
=
"navbar-Items"
>
<
span
class
=
"noti glyphicon glyphicon-globe"
>
<
span
class
=
"count"
>
</
span
>
</
span
>
<
div
class
=
"noti-content"
>
<
div
class
=
"noti-top-arrow"
>
</
div
>
<
ul
id
=
"notiContent"
>
</
ul
>
</
div
>
</
li
>
</
ul
>
</
div
>
</
div
>
</
div
>
Reply
Answers (
6
)
required field validator
ASP.NET MVC Modal Lookup