1
votes

I'm new to SignalR and trying to implement a notification when a particular event fires from an API .

What's tried:

Hub:

public class NotificationHub : Hub
{        
    private static IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();

    public static void Send( string content)
    {
        hubContext.Clients.All.addMessage(content);
    }
}

Controller:

//static event from external API
public static void onTick(Tick TickData)
{
    if(TickData.InstrumentToken == buy.InstrumentToken)
    {                   
        NotificationHub.Send(TickData.Bid);   
    } 
}

What shall I use in the View to display the message which is triggered upon the condition?

View, tried :

$(document).ready(function () {
    var conn = $.connection.NotificationHub;
    conn.client.addMessage = function (message) {
        alert(message);
    };

});

Is there anything else needed to get this working?

Edit:

Ashley's answer got me closer and couple of things also was missing like below ,

  • connection.NotificationHubshould beconnection.notificationHub`

  • the order of the js files references should like

1 jquery-1.10.2.min.js
2 jquery.signalR-2.1.0.min.js
3 signalr/hubs

But now while executing it enters the .fail(function() and the console shows error , http://127.0.0.1:8080/signalr/negotiate?clientProtocol=1.5&connectionData=%5B%7B%22name%22%3A%22notificationhub%22%7D%5D&_=1515664348026 Failed to load resource: net::ERR_CONNECTION_REFUSE

Please advise. Thanks in advance.

1
You just need to start the hub connection, will show in answer, give me two secs.Ashley Medway
@AshleyMedway thanks bro.user2695433

1 Answers

0
votes

Make sure you include the SignalR hubs source:

<script type="text/javascript" src="~/signalr/hubs"></script>

You just haven't started the connection for SignalR, add this:

$.connection.hub.start().done(function() {
    //connection has started :-)
}).fail(function() {
    //connection has failed to start :-(
});

Using your example it would look like this:

$(document).ready(function () {
    var conn = $.connection.NotificationHub;
    conn.client.addMessage = function (message) {
        alert(message);
    };

    $.connection.hub.start().done(function() {
        //connection has started :-)
        alert("connected");
    }).fail(function() {
        //connection has failed to start :-(
        alert("failed");
    });
});