I am very new to SignalR and ASP.NET Core and my underlying problem is that I want a user to be able to see changes that are made to the database in realtime. I have an example of working code with SignalR and the ASP.NET framework, but when I try to convert it to ASP Core it fails because of my hub. I'm pretty sure the problem is very straight forward but some of the other examples on the net are just out of my current depth.
CusHub.cs:
public class CusHub : Hub
{
public static void Show()
{
// The below code is what doesn't work in aspcore.
// This is what i'm struggling with.
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<CusHub>();
context.Clients.All.displayCustomer();
}
}
CustomerController.cs:
public JsonResult Get()
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(@"SELECT [Id],[CustId],[CustName] FROM [dbo].[ad.signalr] WHERE [Status] <> 0", connection))
{
command.Notification = null;
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
SqlDataReader reader = command.ExecuteReader();
var listCus = reader.Cast<IDataRecord>()
.Select(x => new
{
Id = (int)x["Id"],
CusId = (string)x["CustId"],
CusName = (string)x["CustName"],
}).ToList();
return Json(new { listCus = listCus });
}
}
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
CusHub.Show();
}
Customer view:
@Html.Hidden("Get", Url.Action("Get", "Customer"))
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>Customer Id</th>
<th>Customer Name</th>
</tr>
</thead>
<tbody id="tblInfo"></tbody>
</table>
SignalR js file:
$(function () {
var cus = $.connection.cusHub;
cus.client.displayCustomer = function () {
getData();
};
$.connection.hub.start();
getData();
});
function getData() {
var $tbl = $('#tblInfo');
$.ajax({
url: $("#Get").val(),
type: 'GET',
datatype: 'json',
success: function (data) {
$tbl.empty();
$.each(data.listCus, function (i, model) {
$tbl.append(
'<tr>' +
'<td>' + model.Id + '</td>' +
'<td>' + model.CusId + '</td>' +
'<td>' + model.CusName + '</td>' +
'<tr>'
);
});
}
});
}
The code doesn't throw any exceptions apart from in my hub.
With the:
GlobalHost.ConnectionManager.GetHubContext<CusHub>()
context.Clients.All.displayCustomer();
Iclientproxy does not contain a definition for displayCustomer();
I know there have been some changes to SignalRCore, but is there an easy fix to get this up at running?
The above code works in ASP.NET framework
Thanks for your help.