Как отправить уведомление об изменении базы данных для входа в систему - PullRequest
0 голосов
/ 10 января 2019

Я хочу отправлять уведомление для определенного пользователя входа в систему всякий раз, когда какая-либо операция выполняется для этого пользователя в базе данных. Операция, как кто-то, пользователь прокомментировал пост входа пользователя в систему, а затем я хочу уведомить этого пользователя.

public class NotificationHub:Hub
{
    //Nothing required here   
    //public void Hello()  
    //{  
    //    Clients.All.hello();  
    //} 
}

public class NotificationComponent
{

    private SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlConString"].ConnectionString);
    //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 [Id],[Title],[Notification] from [dbo].[tbl_Notification] where IsActive=1";
        //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("@uid", UD.uid);
            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)
    {
        if (e.Type == SqlNotificationType.Change && e.Info == SqlNotificationInfo.Insert)
        {
            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);
        }
        RegisterNotification(DateTime.Now);
    }

    public List<tbl_Notification> GetData(DateTime afterDate)
    {
        using (adminEntities dc = new adminEntities())
        {
            return dc.tbl_Notification.Where(a => a.IsActive==1).OrderByDescending(a => a.CreateDate).ToList();
        }
    }
 }

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.MapSignalR();
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
    }
}

// Изменения в Global.asax.cs

    string con =  
   ConfigurationManager.ConnectionStrings["sqlConString"].ConnectionString;
    protected void Application_Start()
    {
        MvcHandler.DisableMvcResponseHeader = true;
        AreaRegistration.RegisterAllAreas();
        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        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);
    }

Просмотр страницы Javascript is

     $(function () {
        // 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) {
            debugger
            if (message && message.toLowerCase() == "added") {
                updateNotificationCount();
            }
        }

        // update notification count
        function updateNotificationCount() {
            debugger
            //$('span.count').show();
            var count = 0;
            count = parseInt($('.notification-number').html()) || 0;
            count++;
            $('.notification-number').html(count);
            $('.notification-number').css('display', 'block');
        }
      });

Я не могу понять, где я могу сравнить логин пользователя и уведомить пользователя, чтобы отправить уведомление

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...