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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With