【问题标题】:Create real time notification module like Facebook for database changes为数据库更改创建像 Facebook 这样的实时通知模块
【发布时间】:2015-01-19 04:32:38
【问题描述】:

我正在尝试使用 ASP.NET MVC 4 创建像 Facebook 这样的通知模块。

我的数据库中的表很少。

只要有人更改(插入/更新/删除)数据库中这些表的行,我就可以在我的应用程序前端将其显示为通知

只是想知道解决这个问题的最佳方法,非常感谢可以提供任何建议或资源

谢谢!

【问题讨论】:

  • 你可能想看看SignalR
  • 是的!我已经将该库添加到我的项目中,因为也遵循了本教程 venkatbaggu.com/… 但在本教程中,当我们更改表格行时它不会显示任何通知
  • 那你需要贴出你试过的代码并说明问题。
  • 这里是 SignalR asp.net/signalr/overview/getting-started/… 示例代码的逐步实现,如果您已经实现并且它不起作用,请在此处发布您的代码。
  • @MokshShah 这个链接失效了

标签: jquery ajax asp.net-mvc asp.net-mvc-4 signalr


【解决方案1】:

您可以使用SignalR,这是一个用于开发需要实时通信的应用程序的库。在此类应用程序中,一旦在服务器上生成数据或在服务器上发生一些有趣的事件,客户端就需要使用最新数据。实现此功能的传统方法是定期对服务器进行 Ajax 调用。但是,这种方法有其自身的缺陷。另一种方法是使用 HTML5 Web 套接字或服务器发送事件 (SSE) 来执行实时通信。但是,这两种技术都只适用于支持 HTML5 的浏览器。如果目标浏览器支持 SignalR,则 SignalR 使用 HTML5 Web Sockets,否则将回退到其他技术。

创建通知系统。如果您使用的是 ASP.NET WebForms,请向项目中添加一个新的 SignalR Hub 类,如下所示:

namespace SignalRDemo
{
    public class MyHub1 : Hub
    {
            //call method like SendNotifications when your database is changed
            public void SendNotifications(string message)
            {
                Clients.All.receiveNotification(message);
            }
    }
}

接下来,将 Global.asax 文件添加到您的 Web 应用程序并在 Application_Start 事件处理程序中编写以下代码。

protected void Application_Start(object sender, EventArgs e)
{
    RouteTable.Routes.MapHubs();
}

此外,您会在 Scripts 文件夹下找到某些脚本文件。

SignalR Scripts

现在,向项目中添加一个 Web 表单并将其命名为 AdminForm.aspx。在 Web 表单中添加以下标记:

<!DOCTYPE html>
<html>
<head>
    <title>Admin Form Sending Notifications</title>

    <script src="/Scripts/jquery-1.8.2.min.js" ></script>
    <script src="/Scripts/jquery.signalR-1.0.0.js"></script>
    <script src="/signalr/hubs"></script>

    <script type="text/javascript">
        $(function () {
            var proxy = $.connection.notificationHub;
            $("#button1").click(function () {
                proxy.server.sendNotifications($("#text1").val());
            });
            $.connection.hub.start();
        });
    </script>

</head>
<body>
    <input id="text1" type="text" />
    <input id="button1" type="button" value="Send" />
</body>
</html>

AdminForm.aspx 在 head 部分引用 SignalR 脚本文件。请注意以粗体字母标记的代码。首先声明一个名为 proxy 的变量来保存对远程集线器类 (NotificationHub) 的代理的引用。确保客户端代码在命名约定中使用驼峰式大小写。例如,NotificationHub 在客户端代码中称为 notificationHub。

接下来,按钮的点击事件处理程序被连接到一个函数。客户端事件处理程序调用代理对象的 sendNotifications() 方法并传递在文本框中输入的通知消息(参见前面的图了解管理表单的外观)。

最后调用 hub 的 start() 方法开始连接。

向项目添加另一个 Web 表单并将其命名为 ClientForm.aspx。在 Web 表单中键入以下标记:

<!DOCTYPE html>
<html>
<head>
    <title>Client Form Receiving Notifications</title>
    <script src="/Scripts/jquery-1.8.2.min.js" ></script>
    <script src="/Scripts/jquery.signalR-1.0.0.js"></script>
    <script src="/signalr/hubs"></script>
    <script type="text/javascript">
        $(function () {
            var proxy = $.connection.notificationHub;
            proxy.client.receiveNotification = function (message) {
                $("#container").html(message);
                $("#container").slideDown(2000);
                setTimeout('$("#container").slideUp(2000);', 5000);
            };
            $.connection.hub.start();
        });
    </script>
</head>
<body>
    <div class="notificationBalloon" id="container">
    </div>
</body>
</html>

现在管理员发送的通知将像这样显示给所有客户端。

要使用 SignalR 和 SQL 依赖项显示来自 SQL Server 的实时更新,请执行以下步骤:

第 1 步:在数据库上启用 Service Broker

以下是需要启用服务代理的查询

ALTER DATABASE BlogDemos SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE ;

第 2 步:启用 SQL 依赖项

    //Start SqlDependency with application initialization
     SqlDependency.Start(connString);

第 3 步:创建中心类

public class MessagesHub : Hub
    {
        private static string conString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
        public void Hello()
        {
            Clients.All.hello();
        }

        [HubMethodName("sendMessages")]
        public static void SendMessages()
        {
            IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MessagesHub>();
            context.Clients.All.updateMessages();
        }


    }

第 4 步:从存储库中获取数据

创建 MessagesRepository 以在数据更新时从数据库中获取消息。

public class MessagesRepository
    {
        readonly string _connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

        public IEnumerable<Messages> GetAllMessages()
        {
            var messages = new List<Messages>();
            using (var connection = new SqlConnection(_connString))
            {
                connection.Open();
                using (var command = new SqlCommand(@"SELECT [MessageID], [Message], [EmptyMessage], [Date] FROM [dbo].[Messages]", connection))
                {
                    command.Notification = null;

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

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

                    var reader = command.ExecuteReader();

                    while (reader.Read())
                    {
                        messages.Add(item: new Messages { MessageID = (int)reader["MessageID"], Message = (string)reader["Message"], EmptyMessage =  reader["EmptyMessage"] != DBNull.Value ? (string) reader["EmptyMessage"] : "", MessageDate = Convert.ToDateTime(reader["Date"]) });
                    }
                }

            }
            return messages;


        }

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

第五步:在启动类注册 SignalR

app.MapSignalR();

第6步:然后使用该方法在您的视图中实时显示

<script src="/Scripts/jquery.signalR-2.1.1.js"></script>
 <!--Reference the autogenerated SignalR hub script. -->
    <script src="/signalr/hubs"></script>

<script type="text/javascript">
    $(function () {
        // Declare a proxy to reference the hub.
        var notifications = $.connection.messagesHub;

        //debugger;
        // Create a function that the hub can call to broadcast messages.
        notifications.client.updateMessages = function () {
            getAllMessages()

        };
        // Start the connection.
        $.connection.hub.start().done(function () {
            alert("connection started")
            getAllMessages();
        }).fail(function (e) {
            alert(e);
        });
    });


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

        });
    }
</script>

希望这会有所帮助:)

【讨论】:

  • 非常感谢您的指导,但在此示例中您似乎没有使用任何数据库,如果我错了请纠正
  • 惊人的解释..谢谢
【解决方案2】:

您可以使用 SqlDependency + SignalR 来做到这一点。

点击此链接:
SqlDependency:http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldependency(v=vs.110).aspx

信号R:http://signalr.net/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 2012-03-11
    • 1970-01-01
    • 2017-10-24
    • 2012-09-17
    • 2010-10-19
    相关资源
    最近更新 更多