Как жить уведомления в MVC с SignalR? - PullRequest
0 голосов
/ 04 октября 2018

Я пытаюсь сделать живое уведомление, используя signalR.Мой проект работает на localhost.Но я не вижу своего уведомления, когда я устанавливаю webconfig на стороне сервера.(хотя я сделал это с signalR)

Когда я запускаю часть проверки "Интернет" элемента проверки Chrome, я вижу, что запрос не падает.как мне решить эту проблему?

код ajax;

 function updateNotification() {
            $('#notiContent').empty();
            $('#notiContent').append($('<li>Yükleniyor...</li>'));
            $.ajax({
                type: 'GET',
                datatype : JSON,
                contentType: 'application/json; charset=utf-8',
                url: '/notification/GetNotificationFlows',
                success: function (response) {
                    $('#notiContent').empty();
                    if (response.length  == 0) {
                        $('#notiContent').append($('<li>Data yok..</li>'));
                    }
                    $.each(response, function (index, value) {

                        $('#notiContent').append($('<li>Yeni kişi : ' + value.flowName + ' (' + value.flowPhone + ') eklendi.</li>'));
                    });
                },
                error: function (error) {
                    console.log(error);
                }
            })
        }

Global.asax;

 string con = ConfigurationManager.ConnectionStrings["sqlConString"].ConnectionString;
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        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);
    }
}

Компонент уведомления

public void RegisterNotification(DateTime currentTime)
    {
        string conStr = ConfigurationManager.ConnectionStrings["sqlConString"].ConnectionString;
        string sqlCommand = @"SELECT [flowId],[flowName],[flowEMail],[flowPhone],[kaynakId] from [dbo].[flow] where [createDate] > @createDate";
        //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("@createDate", 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)
    {
        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("eklendi.");

            //re-register notification
            RegisterNotification(DateTime.Now);
        }
    }

    public List<flow> GetFlows(DateTime afterDate)
    {
        using (smartCMSEntities dc = new smartCMSEntities())
        {
            return dc.flow.Where(a => a.createDate > afterDate).OrderByDescending(a => a.createDate).ToList();
        }
    }

Контроллер уведомлений

public JsonResult GetNotificationFlows()
    {
        var notificationRegisterTime = Session["LastUpdated"] != null ? Convert.ToDateTime(Session["LastUpdated"]) : DateTime.Now;
        NotificationComponent NC = new NotificationComponent();
        var list = NC.GetFlows(notificationRegisterTime);
        Session["LastUpdate"] = DateTime.Now;
        return new JsonResult { Data = list, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    }

Центр уведомлений

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

SQL (для SQL-зависимости)

ALTER DATABASE [db_name] SET ENABLE_BROKER with rollback immediate;
...