'How to get notifications using signal r based on selected value on client browser

Here is the code of server side i.e of NotificationHub where i intend to add some logic by which i get realtime update from database based on client send value from front end

public class NotificationHub : Hub
{

    /// <summary>
    /// This function will be called from client to get all the messages.
    /// </summary>
    /// <returns></returns>
    public IEnumerable<MessageLog> GetAllMessagesLogs(string hello="")
    {
        string conStr = "Data Source=xyz;Initial Catalog=SignalRDatabase;Trusted_Connection=true;";
        SqlConnection connection = new SqlConnection(conStr);

        string query = $"SELECT Message,EventID,LL.Name as LogLevelID,OC.Name as OperationCodeID,ML.ServerName,ML.ComponentName,ML.SubComponentName FROM [dbo].[MessageLog] ML" +
            " inner join [dbo].[LogLevel] LL on ML.LogLevelID = LL.ID" +
            " inner join [dbo].[OperationCode] OC on ML.OperationCodeID = OC.ID" +
            $" where ML.SubComponentName='{hello}'";
        SqlDependency.Start(conStr);
        SqlCommand command = new SqlCommand(query, connection);
        SqlDependency dependency = new SqlDependency(command);

        //If Something will change in database and it will call dependency_OnChange method.
        dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
        connection.Open();
        SqlDataAdapter da = new SqlDataAdapter(command);
        DataTable dt = new DataTable();
        da.Fill(dt);

        List<MessageLog> messageList = new List<MessageLog>();
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            MessageLog ml = new MessageLog();
            ml.Name = dt.Rows[i]["Message"].ToString();
            ml.EventID = Convert.ToInt32(dt.Rows[i]["EventID"].ToString());
            ml.LogLevelName = dt.Rows[i]["LogLevelID"].ToString();
            ml.OperationCodeName = dt.Rows[i]["OperationCodeID"].ToString();
            ml.ServerName = dt.Rows[i]["ServerName"].ToString();
            ml.ComponentName = dt.Rows[i]["ComponentName"].ToString();
            ml.SubComponentName = dt.Rows[i]["SubComponentName"].ToString();
            messageList.Add(ml);
        }
        return messageList;

    }

    private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
    {
        if (e.Type == SqlNotificationType.Change)
        {

            SendNotifications();
        }
    }
    private void SendNotifications()
    {
        IEnumerable<MessageLog> messageList = GetAllMessagesLogs();

        IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
        if(messageList.Count()>0)
        context.Clients.All.broadcastMessage(messageList);//Will update all the clients with message log.

    }
}

and here is the client side code javascript for now i have passed hard coded string in method getAllMessagesLogs() which will obviously change and will be bound with some select change event on front end

 <script type="text/javascript">
    $(function () {
        $('#btnPause').click(function () {
            $('#hdnValue').val(0);
        });
        $('#btnResume').click(function () {
            $('#hdnValue').val(1);
        });
        var $messageTable = $('#messageTable');
        var $messageTableBody = $messageTable.find('tbody');
        // Declare a proxy to reference the hub.
        var ew = $.connection.notificationHub;
        //This method will fill all the Messages in case of any database change.
        ew.client.broadcastMessage = function (messageLogs) {
            // Html encode display name and message.
            var i = 0;
            if ($('#hdnValue').val() == 1) {
                $messageTableBody.empty();

                $.each(messageLogs, function () {
                    var encodedName = messageLogs[i].Name;
                    var encodedEvent = messageLogs[i].EventID;
                    var encodedLogLevel = messageLogs[i].LogLevelName;
                    var encodedOCode = messageLogs[i].OperationCodeName;
                    var encodedServerName = messageLogs[i].ServerName;
                    var encodedCompName = messageLogs[i].ComponentName;
                    var encodedSubCompName = messageLogs[i].SubComponentName;
                    if (encodedLogLevel == "Fatal") {
                        $messageTableBody.append('<tr style="background-color:Red"><td>' + encodedName + '</td><td>' + encodedEvent + '</td><td>' + encodedLogLevel + '</td><td>' + encodedOCode + '</td><td>' + encodedServerName + '</td><td>' + encodedCompName + '</td><td>' + encodedSubCompName + '</td></tr>');
                    }
                    if (encodedLogLevel == "Warning") {
                        $messageTableBody.append('<tr style="background-color:Yellow"><td>' + encodedName + '</td><td>' + encodedEvent + '</td><td>' + encodedLogLevel + '</td><td>' + encodedOCode + '</td><td>' + encodedServerName + '</td><td>' + encodedCompName + '</td><td>' + encodedSubCompName + '</td></tr>');
                    }
                    else {
                        $messageTableBody.append('<tr><td>' + encodedName + '</td><td>' + encodedEvent + '</td><td>' + encodedLogLevel + '</td><td>' + encodedOCode + '</td><td>' + encodedServerName + '</td><td>' + encodedCompName + '</td><td>' + encodedSubCompName + '</td></tr>');
                    }
                    i = i + 1;
                });
            }
        };

        //This is where i want to send parameters and on selected parameters i want to receive notification in future
        $.connection.hub.start().done(function () {

            ew.server.getAllMessagesLogs("well hello").done(function (messageLogs) {
                debugger;
                console.log(messageLogs)
                var i = 0;
                if ($('#hdnValue').val() == 1) {
                    $messageTableBody.empty();
                    $.each(messageLogs, function () {
                        var encodedName = messageLogs[i].Name;
                        var encodedEvent = messageLogs[i].EventID;
                        var encodedLogLevel = messageLogs[i].LogLevelName;
                        var encodedOCode = messageLogs[i].OperationCodeName;
                        var encodedServerName = messageLogs[i].ServerName;
                        var encodedCompName = messageLogs[i].ComponentName;
                        var encodedSubCompName = messageLogs[i].SubComponentName;
                        if (encodedLogLevel == "Fatal") {
                            $messageTableBody.append('<tr style="background-color:Red"><td>' + encodedName + '</td><td>' + encodedEvent + '</td><td>' + encodedLogLevel + '</td><td>' + encodedOCode + '</td><td>' + encodedServerName + '</td><td>' + encodedCompName + '</td><td>' + encodedSubCompName + '</td></tr>');
                        }
                        if (encodedLogLevel == "Warning") {
                            $messageTableBody.append('<tr style="background-color:Yellow"><td>' + encodedName + '</td><td>' + encodedEvent + '</td><td>' + encodedLogLevel + '</td><td>' + encodedOCode + '</td><td>' + encodedServerName + '</td><td>' + encodedCompName + '</td><td>' + encodedSubCompName + '</td></tr>');
                        }
                        else {
                            $messageTableBody.append('<tr><td>' + encodedName + '</td><td>' + encodedEvent + '</td><td>' + encodedLogLevel + '</td><td>' + encodedOCode + '</td><td>' + encodedServerName + '</td><td>' + encodedCompName + '</td><td>' + encodedSubCompName + '</td></tr>');
                        }
                        i = i + 1;
                    });
                }
            });
        });
    });

</script>

so what i want is that to subscribe to some database change event based on selected value from client browser



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source