简体   繁体   中英

SignalR doesn't update the website in real time after a database update

I'm struggling with the use of SignalR. I'm trying to make it update a website's div when a change to a database happens. I used a working example (I tried it) to see how this would be done, but for some reason it doesn't work on my project.

What is it that doesn't work? Apparently the event of the database's modification doesn't trigger, yet the code (which is nearly the same) in another solution works.

This is the code involved:

NotificationHub.cs

namespace WebApplication.SignalR
{
    public class NotificationHub : Hub
    {
        public void Hello()
        {
            Clients.All.hello();
        }

        [HubMethodName("show")]
        public static void Show()
        {
            IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
            context.Clients.All.displayStatus();
        }
    }
}

NotificationInfo.cs

namespace WebApplication.SignalR_Data
{
    public class NotificationInfo
    {
        public DateTime Date { get; set; }
        public int RowCount { get; set; }
    }
}

NotificationrRepository.cs -- This is where the event handling happens.

namespace WebApplication.SignalR_Data
{
    public class NotificationRepository
    {
        public NotificationInfo GetData()
        {
            using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ReservationDbContext"].ConnectionString))
            {
                connection.Open();
                using (SqlCommand command = new SqlCommand(@"SELECT COUNT(*) FROM dbo.Reservations", connection))
                {
                    command.Notification = null;

                    SqlDependency dependency = new SqlDependency(command);
                    dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);

                    if (connection.State == System.Data.ConnectionState.Closed)
                        connection.Open();

                    return new NotificationInfo { RowCount = (int)command.ExecuteScalar(), Date = DateTime.Now };

                }
            }
        }

        public void dependency_OnChange(object sender, SqlNotificationEventArgs e)
        {
            if(e.Type == SqlNotificationType.Change)
                NotificationHub.Show();
        }
    }
}

This is the View: ReservationHome.cshtml

@{
    ViewBag.Title = "Índice";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<body>

    @RenderPage("~/Views/Shared/_Navbar.cshtml")
    <script src="~/scripts/jquery-2.1.1.min.js"></script>
    <script src="~/scripts/jquery.signalr-2.2.0.min.js"></script>
    <script src="/signalr/hubs"></script>
    <script type="text/javascript">
    $(function () {
        // Declare a proxy to reference the hub.
        var notifications = $.connection.notificationHub;

        //debugger;
        // Create a function that the hub can call to broadcast messages.
        notifications.client.displayStatus = function () {
            getAllMessages();
        };
        // Start the connection.
        $.connection.hub.start().done(function () {
            getAllMessages();
        }).fail(function (e) {
            alert(e);
        });
    });


    function getAllMessages() {
        var div = $('#dbNotifications');
        $.ajax({
            url: '/Reservation/GetUpdate',
            contentType: 'application/html ; charset:utf-8',
            type: 'GET',
            dataType: 'html'
        }).success(function (result) {
            div.empty().append(result);
        }).error(function () {

        });
    }
    </script>



    <div id="wrap">

        <h1>Aplicación de Reserva de Mesas</h1>

        <div id="content">

            <p>En esta aplicación web usted podrá realizar reservas de mesa.</p>

            <div id="dbNotifications"></div>
        </div>

    </div>

</body> 

This is the pertinent controller action (ReservationController.cs

public ActionResult GetUpdate()
{
    NotificationRepository updateRepo = new NotificationRepository();
    return PartialView("_NotificationsCount", updateRepo.GetData());
}

There is a startup class for Owin and SignalR, I didn't add it because I felt it was irrelevant. Global.asax also has these lines:

The main issues stand at NotificationRepository.cs, where for some reason after a database change(such as the insertion of a new row), the event doesn't seem to trigger. The methods within that Repository are only called once, and that is when the page loads.

Any ideas on why this is happening?

Your event dependency_OnChange doesn't trigger because you dispose of the SqlConnection used to register the SqlDependency . It needs to stay open for the event to be raised.

Do not instantiate the SqlConnection within a using statement, just assign it to a variable and make sure you dispose of it when your application shutdown or sooner if relevant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM