Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SignalR don't call jQuery function

I've this piece of code in my page, but it don't run when i make changes in the database, what could be the problem. This starts well, when i load the page this executes the function twice, but if i send a message to the database this doens't execute.

$(function () {

var chat = $.connection.chatHub;
chat.client.allTalks = function () {
    refresh();
};
$.connection.hub.start();
    refresh();

});

SERVER SIDE (HUB):

    [HubName("chatHub")]
    public class ChatHub : Hub
    {
        public static void AllTalks()
        {
            IHubContext context = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
            context.Clients.All.allTalks();
        }
    }

HANDLER

...

using (SqlCommand command = new 
SqlCommand(@"SELECT * FROM [dbo].[chat_talks]", connection)) {

//CONTENT

SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);

... }

        public void dependency_OnChange(object sender, SqlNotificationEventArgs e)
        {
            ChatHub.AllTalks();
        }

GLOBAL.ASAX

        protected void Application_Start(object sender, EventArgs e)
        {
            SqlDependency.Start(ConfigurationManager.ConnectionStrings["ProjectSellerConnection"].ConnectionString);
        }

enter image description here

like image 464
Severiano Avatar asked Mar 14 '14 14:03

Severiano


1 Answers

First off, it is redundant to have your first line in your server-side code. There is no need to call for a hubContext inside the Hub. You can just do:

public static void AllTalks()
{
    Clients.All.allTalks();
}

I would suggest, perhaps foolishly, to not use SQL Dependency. I would instead suggest using the following technique of calling SignalR (specifically, it will call the client functions):

var hubContext = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
hubContext.Clients.All.allTalks();

You can call this in, for example, actions in MVC and WebAPI Controllers, thus meaning if you've done any database updates in those actions, you can subsequently call clients using this methodology. I know it's not as fancy as SQL Dependency, and perhaps not the answer your looking for, but it will solve your problem - since it appears the problem seems to be with SignalR detecting the database changes.

In other words, this methodology will work, but it's probably not the precise one you are hoping for.

like image 192
James Haug Avatar answered Oct 06 '22 16:10

James Haug