ASP.NET SignalR dependency.OnChange не вызывать при изменении данных Sql - PullRequest
0 голосов
/ 26 апреля 2018

Это мой код SignalR с SQL.Проблема - это зависимость. OnChange не вызывается при обновлении данных в SQL.

Я также установил для своей базы данных ALTER DATABASE Your_DB_Name SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE;

Я пробовал с SQL 2012,2014 и версии 2016 года.В Sql 2016 он иногда вызывается, но не вызывается каждый раз.

<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.6.4.min.js"></script>
    <script src="Scripts/jquery.signalR-2.2.3.js"></script>
    <script src="signalR/hubs"></script>
    <script type="text/javascript">
        $(function () {

        // Proxy created on the fly
        var job = $.connection.myHub;

        // Declare a function on the job hub so the server can invoke it
        job.client.addMessage = function () {
            debugger;
            getData();
        };

        // Start the connection
        $.connection.hub.start();
        getData();


    });

        function getData() {
            var $tbl = $('#tbl');
            $.ajax({
                url: 'index.aspx/GetData',
                type: 'Post',
                contentType: "application/json; charset=utf-8",
                datatype: 'json',
                success: function (data) {
                    var result = data.d;
                    if (result.length > 0) {
                        $tbl.empty();
                        $tbl.append(' <tr><th>ID</th><th>Name</th></tr>');
                        var rows = [];
                        for (var i = 0; i < result.length; i++) {
                            rows.push(' <tr><td>' + result[i].ProductId + '</td><td>' + result[i].ProductName + '</td></tr>');
                        }
                        $tbl.append(rows.join(''));
                    }
                }
            });
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <table id="tbl">
        </table>
    </form>
</body>
</html>

Код Asp.Net за файлом

    [WebMethod]
        public static IEnumerable<ProductMaster> GetData()
        {                        System.Data.SqlClient.SqlDependency.Start(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);

                    using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
                    {
                        connection.Open();
                        using (SqlCommand command = new SqlCommand(@"SELECT [ProductId],[ProductName]
                       FROM [dbo].[ProductMaster]", connection))
                        {
                            // Make sure the command object does not already have
                            // a notification object associated with it.
                            command.Notification = null;
                            //SqlDependency.Start(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
                            SqlDependency dependency = new SqlDependency(command);
                            dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);

                            if (connection.State == ConnectionState.Closed)
                                connection.Open();
                            System.Data.SqlClient.SqlDependency.Stop(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
                            using (var reader = command.ExecuteReader())
                                return reader.Cast<IDataRecord>()
                                    .Select(x => new ProductMaster()
                                    {
                                        ProductId = x.GetInt32(0),
                                        ProductName = x.GetString(1)
                                    }).ToList();


                        }

                    }


                }

Это не вызывается при обновлении данных В SQL

                private static void dependency_OnChange(object sender, SqlNotificationEventArgs e)
                {
                    if (e.Info == SqlNotificationInfo.Insert)
                    {
                        MyHub.Show();
                    }

                }

Запуск

using System.Configuration;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(SignalRRealTime.Startup))]

namespace SignalRRealTime
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            GlobalHost.DependencyResolver.UseSqlServer(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
            app.MapSignalR();
        }
    }
}

Файл-концентратор

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;

namespace SignalRRealTime
{
    public class MyHub : Hub
    {
        public static void Show()
        {
            IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
            //context.Clients.All.displayStatus();
            context.Clients.All.addMessage("my message");
        }
    }
}
...