2

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.

1
  • You say it throws exceptions, but you haven't told us what the exceptions are. Please be specific when you get an exception - edit that into your question. Commented Jul 23, 2019 at 13:48

1 Answer 1

1

I assume you're using a Strongly typed hub if you have a displayCustomer() method. Check out the example in that documentation, which should put you on the right path. But here are a couple issues I see right away:

First, you'll need to change the declaration of CusHub to derive from Hub<T> where T is the interface you made to define the methods that your SignalR client will accept. So if that's called ICusHub, then you would have something like this:

public class CusHub : Hub<ICusHub>

Second, you don't need to get a context. It's already available in your Hub class. So all you need is this:

await Clients.All.displayCustomer();
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for pointing me in the right direction. Really appreciate it. I'm now connected to the hub. However, i keep getting exceptions on my client side in reference to: con.client.DisplayCustomer = function () {. It comes back with the error Uncaught (in promise) TypeError: Cannot set property 'DisplayCustomer' of undefined. am i doing this incorrectly?
That's telling you that con.client is undefined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.