I'm still learning ASP.NET MVC architecture and if any of my questions parts seem awful, sorry for the inconvenience that happened.
I want to add push notifications to my ASP.NET MVC web application which I have never used before.
I followed this article: http://demo.dotnetawesome.com/push-notification-system-with-signalr
I'm using Entity Framework, and added the database connection string to my web.config file.
I used to create database connection via a class:
public class zSqlDb: DbContext
{
public zSqlDb(): base("Data Source=YEA-LAPTOP;Initial Catalog=db_ptweb;Integrated Security=True")
{
}
}
So in this article, he creates a class and there writes code to save data changes in the database.
This is the code:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using Microsoft.AspNet.SignalR;
namespace PushNotification
{
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["sqlConString"].ConnectionString;
string sqlCommand = @"SELECT [ContactID],[ContactName],[ContactNo] from [dbo].[Contacts] where [AddedOn] > @AddedOn";
//you can notice here I have added table name like this [dbo].[Contacts] with [dbo], it's mandatory 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>();
notificationHub.Clients.All.notify("added");
//re-register notification
RegisterNotification(DateTime.Now);
}
}
public List<Contact> GetContacts(DateTime afterDate)
{
using (MyPushNotificationEntities dc = new MyPushNotificationEntities())
{
return dc.Contacts.Where(a => a.AddedOn > afterDate).OrderByDescending(a => a.AddedOn).ToList();
}
}
}
}
But I did to add records to the database by using the controller. So will this change the definition of the push notification process? If yes then I want to know how to match this code with mine.