2015-02-08 190 views
0

我正在努力使用SignalR。我試圖在更改數據庫時更新網站的div。我使用了一個工作示例(我嘗試過)來了解這將如何完成,但出於某種原因,它不適用於我的項目。SignalR在數據庫更新後不會實時更新網站

這是什麼不起作用?顯然數據庫的修改事件不會觸發,但另一個解決方案中的代碼(幾乎相同)可以工作。

這是所涉及的代碼:

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 - 這就是事件處理髮生。

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(); 
     } 
    } 
} 

這是視圖: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> 

這是相關的控制器動作(ReservationController.cs

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

有一個啓動類Owin和SignalR,我沒有添加它,因爲我覺得它是無關緊要的bal.asax也有這些行:

主要問題站在NotificationRepository.cs,由於某種原因在數據庫更改後(例如插入一個新行),事件似乎沒有觸發。該存儲庫中的方法僅調用一次,即加載頁面時。

爲什麼會發生這種情況的任何想法?

+0

我不確定是否看到與通知中心「show」方法有關的相應javascript函數? – 2015-02-09 03:44:39

回答

0

您的事件dependency_OnChange不會觸發,因爲您處置用於註冊SqlDependencySqlConnection。它需要保持開放,以便舉辦活動。

不要在using語句中實例化SqlConnection,只需將它分配給一個變量,並確保在應用程序關閉時處理它,或者在相關時儘快處置它。

+0

我會試試,但它讓我覺得很奇怪。這是我遵循的例子:http://venkatbaggu.com/signalr-database-update-notifications-asp-net-mvc-usiing-sql-dependency/ - 我可以證實這是可行的,它有一個使用SqlConnection聲明。 編輯:剛試過,它沒有工作,發生了同樣的事情 – krieg 2015-02-08 21:57:05