2015-04-23 33 views
1

我正在嘗試顯示用戶的在線朋友。爲此,我在UserInfo表中創建了一個OnlineStatus列。我創建了一個集線器,它在開始時調用一個函數,該函數向服務器發送一個Ajax請求以獲取在線朋友列表。如果該用戶的一位朋友登錄,OnlineStatus將被設置爲1,否則爲0.爲了讓用戶實時看到他的在線朋友,我使用了SqlDependency,如果OnlineStatus列被更新並且SiganlR調用集線器的功能,轉而調用Client的函數,該函數依次向服務器發送Ajax請求,請求更新的在線用戶列表。 Hub在開始時工作正常,但是如果用戶註銷並且SqlDependency沒有被調用。請幫我解決它。 這裏是行動:如果表已更新,SqlDependency不起作用

Public JsonResult FindOnlineFriends(long UserId) 
     { 
      List<UserDetails> onlinefriends = new List<UserDetails>(); 
      using(SqlConnection con=new SqlConnection(connectionString)) 
      { 
       using(SqlCommand cmd=new SqlCommand()) 
       { 
        StringBuilder builder = new StringBuilder(); 
        builder.Append("select [UserId],[DisplayPhoto],[Name] from [dbo].[UserInfo] as userself,("); 
        builder.Append("(select [PersonId2] from [dbo].[FriendsRelation] where [PersonId1] like @UserId) union"); 
        builder.Append("(select [PersonId1] from [FriendsRelation] where [PersonId2] like @UserId)) as friends "); 
        builder.Append("where [userself].[UserId]=[PersonId2] and [OnlineStatus]=1"); 
        cmd.CommandText = builder.ToString(); 
        cmd.Connection = con; 
        cmd.Parameters.AddWithValue("@UserId",UserId); 
        cmd.Notification = null; 
        SqlDependency.Stop(connectionString); 
        SqlDependency.Start(connectionString); 
        SqlDependency dependency = new SqlDependency(cmd); 
        dependency.OnChange += new OnChangeEventHandler(onlineFriends_OnChange); 
        con.Open(); 
        using(SqlDataReader rdr=cmd.ExecuteReader()) 
        { 
         if(rdr.HasRows) 
         { 
          while(rdr.Read()) 
          { 
           onlinefriends.Add(new UserDetails { UserId = Convert.ToInt64(rdr["UserId"]), Name = rdr["Name"].ToString(), DisplayPhoto = rdr["DisplayPhoto"].ToString() }); 
          } 
         } 
        } 
       } 
      } 
      return Json(onlinefriends,JsonRequestBehavior.AllowGet); 
     } 
     private void onlineFriends_OnChange(object sender, SqlNotificationEventArgs e) 
     { 
      if (e.Type == SqlNotificationType.Change) 
      { 
       SocialNetworkHub.SocialNetworkHub.ShowOnlineFriends(); 
      } 
     } 

回答

0

您的解決方案將只適用於一個用戶。當您撥打SqlDependency.Start()SqlDependency.Stop()時,它會刪除所有訂閱。但是,對於您的任務,最好使用SqlDependency-SqlDependencyEx的開源實現,因爲使用此組件,您可以獨立監控UserInfo表的UPDATE更改。代碼示例:

int changesReceived = 0; 
using (SqlDependencyEx sqlDependency = new SqlDependencyEx(
      TEST_CONNECTION_STRING, TEST_DATABASE_NAME, TEST_TABLE_NAME)) 
{ 
    sqlDependency.TableChanged += (o, e) => changesReceived++; 
    sqlDependency.Start(); 

    // Make table changes. 
    MakeTableInsertDeleteChanges(changesCount); 

    // Wait a little bit to receive all changes. 
    Thread.Sleep(1000); 
} 

Assert.AreEqual(changesCount, changesReceived); 

希望這會有所幫助。