Abdulmajeed Alshari

Abdulmajeed Alshari

  • NA
  • 266
  • 60.5k

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 :
  1. [assembly: OwinStartupAttribute(typeof(LinkForEmployment.Startup))]  
  2. [assembly: OwinStartup(typeof(LinkForEmployment.Startup))]  
  3. namespace LinkForEmployment  
  4. {  
  5.     public partial class Startup  
  6.     {  
  7.         public void Configuration(IAppBuilder app)  
  8.         {  
  9.             app.MapSignalR();  
  10.             ConfigureAuth(app);       
  11.        }  
  12.     }  

2- NotificationHub.cs file as :
  1. using Microsoft.AspNet.SignalR;  
  2.   
  3. namespace LinkForEmployment  
  4. {  
  5.     public class NotificationHub : Hub  
  6.     {  
  7.         //public void Hello()  
  8.         //{  
  9.         //    Clients.All.hello();  
  10.         //}  
  11.     }  

3- NotificationComponent.cs file as :
  1. using Microsoft.AspNet.SignalR;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Configuration;  
  5. using System.Data.SqlClient;  
  6. using System.Linq;  
  7. using LinkForEmployment.Models;  
  8. using System.Web;  
  9.   
  10. namespace LinkForEmployment  
  11. {  
  12.     public class NotificationComponent  
  13.     {  
  14.         //Here we will add a function for register notification (will add sql dependency)    
  15.         public void RegisterNotification(DateTime currentTime)  
  16.         {  
  17.             string conStr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;  
  18.             string sqlCommand = @"SELECT [UserId],[NotificationTitle],[NotificationIcon],[NotificationMessage],[link],[NotificationTime] from [dbo].[Notifications] where [NotificationTime] > @AddedOn";  
  19.             //you can notice here I have added table name like this [dbo].[Contacts] with [dbo], its mendatory when you use Sql Dependency    
  20.             using (SqlConnection con = new SqlConnection(conStr))  
  21.             {  
  22.                 SqlCommand cmd = new SqlCommand(sqlCommand, con);  
  23.                 cmd.Parameters.AddWithValue("@AddedOn", currentTime);  
  24.                 if (con.State != System.Data.ConnectionState.Open)  
  25.                 {  
  26.                     con.Open();  
  27.                 }  
  28.                 cmd.Notification = null;  
  29.              
  30.                 SqlDependency sqlDep = new SqlDependency(cmd);  
  31.                 sqlDep.OnChange += sqlDep_OnChange;  
  32.                 //we must have to execute the command here    
  33.                 using (SqlDataReader reader = cmd.ExecuteReader())  
  34.                 {  
  35.                     // nothing need to add here now    
  36.                 }  
  37.             }  
  38.         }  
  39.   
  40.         void sqlDep_OnChange(object sender, SqlNotificationEventArgs e)  
  41.         {  
  42.             //or you can also check => if (e.Info == SqlNotificationInfo.Insert) , if you want notification only for inserted record    
  43.             if (e.Type == SqlNotificationType.Change)  
  44.             {  
  45.                 SqlDependency sqlDep = sender as SqlDependency;  
  46.                 sqlDep.OnChange -= sqlDep_OnChange;  
  47.   
  48.                 //from here we will send notification message to client    
  49.                 var notificationHub = GlobalHost.ConnectionManager.GetHubContext();  
  50.                 notificationHub.Clients.All.notify("added");  
  51.                 //re-register notification    
  52.                 RegisterNotification(DateTime.Now);  
  53.             }  
  54.         }  
  55.   
  56.         public List GetData(DateTime afterDate)  
  57.         {  
  58.             using (ApplicationDbContext db = new ApplicationDbContext())  
  59.             {  
  60.                 return db.Notifications.Where(a => a.NotificationTime > afterDate).OrderByDescending(a => a.NotificationTime).ToList();  
  61.             }  
  62.         }  
  63.     }  

4-Global.asax.cs file as :
  1. namespace LinkForEmployment  
  2. {  
  3.     public class MvcApplication : System.Web.HttpApplication  
  4.     {  
  5.         string con = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;  
  6.   
  7.         protected void Application_Start()  
  8.         {  
  9.             AreaRegistration.RegisterAllAreas();  
  10.             RouteConfig.RegisterRoutes(RouteTable.Routes);  
  11.             GlobalConfiguration.Configure(WebApiConfig.Register);  
  12.             FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);  
  13.             BundleConfig.RegisterBundles(BundleTable.Bundles);  
  14.             SqlDependency.Start(con);  
  15.         }  
  16.         protected void Session_Start(object sender, EventArgs e)  
  17.         {  
  18.             NotificationComponent NC = new NotificationComponent();  
  19.             var currentTime = DateTime.Now;  
  20.             HttpContext.Current.Session["LastUpdated"] = currentTime;  
  21.             NC.RegisterNotification(currentTime);  
  22.         }  
  23.         protected void Application_End()  
  24.         {  
  25.             //here we will stop Sql Dependency    
  26.             SqlDependency.Stop(con);  
  27.         }  
  28.     }  

5- model class file is as :
  1. public class Notification  
  2.    {  
  3.        public int Id { getset; }  
  4.        public string  UserId { getset; }  
  5.        public string NotificationTitle { getset; }  
  6.        public string NotificationIcon{ getset; }  
  7.        public string NotificationMessage { getset; }  
  8.        public string link { getset; }  
  9.        public DateTime NotificationTime { getset; }  
  10.    } 
6- NotificationController file is as :
  1. public class NotificationController : Controller  
  2.    {  
  3.        public JsonResult GetNotifications()  
  4.        {  
  5.            var notificationRegisterTime = Session["LastUpdated"] != null ? Convert.ToDateTime(Session["LastUpdated"]) : DateTime.Now;  
  6.            NotificationComponent NC = new NotificationComponent();  
  7.            var list = NC.GetData(notificationRegisterTime);  
  8.   
  9.            //update session here for get only new added contacts (notification)    
  10.            Session["LastUpdate"] = DateTime.Now;  
  11.            return new JsonResult { Data = list, JsonRequestBehavior = JsonRequestBehavior.AllowGet };  
  12.        }  
  13.    }   
7- _Layout.cshtml Shared page as :
  1. @using LinkForEmployment.Models;    
  2. @using Microsoft.AspNet.Identity;    
  3. <!DOCTYPE html>    
  4. <html lang="en-US">    
  5. <head>    
  6.     <meta charset="utf-8" />    
  7.     <meta name="viewport" content="width=device-width, initial-scale=1.0">    
  8.     <title></title>    
  9.     @*@Styles.Render("~/Content/css")*@    
  10.     <link href="~/Content/bootstrap.css" rel="stylesheet" />    
  11.     <link href="~/Content/bootstrap-rtl.min.css" rel="stylesheet" />    
  12.     <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />    
  13.     <link href="~/Content/style.css" rel="stylesheet" />    
  14.     <script src="~/Scripts/modernizr-2.6.2.js"></script>    
  15. </head>    
  16. <body>    
  17.     <!--This partial view to show notification -->    
  18.     @Html.Partial("_EmployerNavbar")    
  19.         
  20.     <!--Body Content-->    
  21.     
  22.     <div class="container-fluid pageContent myContainer" id="cont">    
  23.     
  24.         <div class="row">    
  25.             @RenderBody()    
  26.             <hr />    
  27.         </div>    
  28.     </div>    
  29.     
  30.     <!--Footer Content-->    
  31.     <footer class="page-footer">    
  32. <!--Write here Footer tags-->    
  33.     </footer>    
  34.     @*@Scripts.Render("~/bundles/jquery")*@    
  35.     <script src="~/Scripts/jquery-1.10.2.min.js"></script>    
  36.     <script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>    
  37.     <script src="/signalr/hubs"></script>    
  38.     <script src="~/Scripts/bootstrap.min.js"></script>    
  39.     @*@Scripts.Render("~/bundles/bootstrap")*@    
  40.     @* @RenderSection("scripts", required: false)*@    
  41.     
  42.     <style type="text/css">    
  43.         /*Added css for design notification area, you can design by your self*/    
  44.         /* COPY css content from youtube video description*/    
  45.         .noti-content {    
  46.             position: fixed;    
  47.             right: 100px;    
  48.             background: yellow;    
  49.             color: blue;    
  50.             font-size: medium;    
  51.             font-style: oblique;    
  52.             font-family: Arial;    
  53.             border-radius: 4px;    
  54.             top: 47px;    
  55.             width: 440px;    
  56.             display: none;    
  57.             border: 1px solid #9E988B;    
  58.         }    
  59.     
  60.         ul#notiContent {    
  61.             max-height: 200px;    
  62.             overflow: auto;    
  63.             padding: 0px;    
  64.             margin: 0px;    
  65.             padding-left: 20px;    
  66.         }    
  67.     
  68.             ul#notiContent li {    
  69.                 margin: 3px;    
  70.                 padding: 6px;    
  71.                 background: #FF6600;    
  72.             }    
  73.     
  74.         .noti-top-arrow {    
  75.             border-color: transparent;    
  76.             border-bottom-color: #F5DEB3;    
  77.             border-style: dashed dashed solid;    
  78.             border-width: 0 8.5px 8.5px;    
  79.             position: absolute;    
  80.             right: 32px;    
  81.             top: -8px;    
  82.         }    
  83.     
  84.         span.noti {    
  85.             color: lightgreen;    
  86.             margin: 15px;    
  87.             position: fixed;    
  88.             right: 100px;    
  89.             font-size: 30px;    
  90.             cursor: pointer;    
  91.         }    
  92.     
  93.         span.count {    
  94.             position: fixed;    
  95.             top: -1px;    
  96.             /*color:white;*/    
  97.         }    
  98.         /*.noti:hover {   
  99.             color:white;   
  100.         }*/    
  101.     </style>    
  102.     @* Add jquery code for Get Notification & setup signalr *@    
  103.     <script type="text/javascript">    
  104.     
  105.     $(function () {    
  106.         // Click on notification icon for show notification    
  107.         $('span.noti').click(function (e) {    
  108.             debugger;    
  109.             e.stopPropagation();    
  110.             $('span.noti').css("color""lightgreen");    
  111.             $('span.count').hide();    
  112.             $('.noti-content').show();    
  113.             var count = 0;    
  114.             count = parseInt($('span.count').html()) || 0;    
  115.             count++;    
  116.             // only load notification if not already loaded    
  117.             if (count > 0) {    
  118.                 updateNotification();    
  119.             }    
  120.             $('span.count'this).html(' ');    
  121.         })    
  122.         // hide notifications    
  123.         $('html').click(function () {    
  124.             $('.noti-content').hide();    
  125.         })    
  126.         // update notification    
  127.         function updateNotification() {    
  128.             $('#notiContent').empty();    
  129.             $('#notiContent').append($('<li>Loading...</li>'));    
  130.             $.ajax({    
  131.                 type: 'GET',    
  132.                 url: '/Notification/GetNotifications',    
  133.                 success: function (response) {    
  134.                     debugger;    
  135.                     $('#notiContent').empty();    
  136.                     if (response.length == 0) {    
  137.                         $('#notiContent').append($('<li>Currently You Have No New Notifications.</li>'));    
  138.                     }    
  139.                     $.each(response, function (index, value) {    
  140.                         $('#notiContent').append($('<li>The User , ' + value.NotificationTitle + ' ' + 'Of ID' + ' (' + value.NotificationMessage + ') Is Written Something.</li>'));    
  141.                     });    
  142.                 },    
  143.                 error: function (error) {    
  144.                     console.log(error);    
  145.                 }    
  146.             })    
  147.         }    
  148.         // update notification count    
  149.         function updateNotificationCount() {    
  150.             $('span.count').show();    
  151.             var count = 0;    
  152.             count = parseInt($('span.count').html()) || 0;    
  153.             count++;    
  154.             $('span.noti').css("color""white");    
  155.             $('span.count').css({ "background-color""red""color""white" });    
  156.             $('span.count').html(count);    
  157.     
  158.         }    
  159.         // signalr js code for start hub and send receive notification    
  160.         var notificationHub = $.connection.notificationHub;    
  161.         $.connection.hub.start().done(function () {    
  162.             console.log('Notification hub started');    
  163.         });    
  164.         //signalr method for push server message to client    
  165.         notificationHub.client.notify = function (message) {    
  166.             if (message && message.toLowerCase() == "added") {    
  167.                 updateNotificationCount();    
  168.             }    
  169.         }    
  170.     })    
  171.     </script>    
  172.     
  173.     <!--End Codes of Notification-->    
  174.     <script src="~/Scripts/Style.js"></script>    
  175.     <script src="~/Scripts/OurJQuery.js"></script>    
  176.     
  177. </body>    
  178. </html>    
8- _EmployerNavbar partial view that will show notifications as :
  1. <link href="~/Content/StyleSeekerNavbar.css" rel="stylesheet" />    
  2.     
  3. <style>    
  4.     .list-Items a:hover {    
  5.         font-size: 14px;    
  6.     }    
  7.     
  8.     .NotifyContenet {    
  9.         font-size: 10px;    
  10.         color: black;    
  11.     }    
  12.     
  13.     .navbar-inverse .navbar-nav > .open > a, .navbar-inverse .navbar-nav > .open > a:hover, .navbar-inverse .navbar-nav > .open > a:focus {    
  14.         color: #ffffff;    
  15.         background-color: none;    
  16.     }    
  17.     
  18.     .navbar {    
  19.         /*background:#faebd700;*/    
  20.         background: #002637;    
  21.     }    
  22. </style>    
  23. <div class="navbar navbar-inverse navbar-fixed-top">    
  24.     <div class="container">    
  25.         <div class="navbar-header">    
  26.             <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">    
  27.                 <span class="icon-bar"></span>    
  28.                 <span class="icon-bar"></span>    
  29.                 <span class="icon-bar"></span>    
  30.             </button>    
  31.             <a href="#" class="navbar-brand">    
  32.                 <img class="logo-img" src="~/images/Job-Searh-icon-Converted1.png" />    
  33.             </a>    
  34.         </div>    
  35.         <div class="navbar-collapse collapse nav-font">    
  36.             <ul class="nav navbar-nav navbar-text">    
  37.                 <li class="navbar-Items">    
  38.                     <a href="~/Home/index" class="navbar-Item">    
  39.                         Main    
  40.                     </a>    
  41.                 </li>    
  42.                 <li class="navbar-Items">    
  43.                     <a href="#" class="navbar-Item">    
  44.                        Jobs    
  45.                     </a>    
  46.                 </li>    
  47.     
  48.                 <li class="navbar-Items">    
  49.                     <a href="#" class="navbar-Item">    
  50.                       Job apply    
  51.                     </a>    
  52.                 </li>    
  53.                 <li class="navbar-Items">    
  54.                     <a href="#" class="navbar-Item">    
  55.                       How to use this Site    
  56.                     </a>    
  57.                 </li>    
  58.          <!--This is Notification li tag -->  
  59.                 <li id="navbar" class="navbar-Items">    
  60.                     <span class="noti glyphicon glyphicon-globe"><span class="count"> </span></span>    
  61.                     <div class="noti-content">    
  62.                         <div class="noti-top-arrow"></div>    
  63.                         <ul id="notiContent"></ul>    
  64.                     </div>    
  65.                 </li>    
  66.             </ul>    
  67.         </div>    
  68.     </div>    
  69. </div>  

Answers (6)