andrew4582

ServiceBrokerUtility

Aug 1st, 2011
352
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.93 KB | None | 0 0
  1. public static class ServiceBrokerUtility
  2. {
  3.   private static List<string> connectionStrings = new List<string>();
  4.   private const string sqlDependencyCookie = "MS.SqlDependencyCookie";
  5.   private static ObjectContext ctx;
  6.   private static RefreshMode refreshMode;
  7.   private static IEnumerable collection;
  8.   private static INotifyRefresh notifyRefresh;
  9.  
  10.  
  11.   static public void AutoRefresh(this ObjectContext ctx,
  12.                 RefreshMode refreshMode, IEnumerable collection)
  13.   {
  14.     var csInEF = ctx.Connection.ConnectionString;
  15.     var csName = csInEF.Replace("name=", "").Trim();
  16.     var csForEF =
  17.       System.Configuration.ConfigurationManager.ConnectionStrings[csName].ConnectionString;
  18.     var newConnectionString = new
  19.       System.Data.EntityClient.EntityConnectionStringBuilder(csForEF).ProviderConnectionString;
  20.     if (!connectionStrings.Contains(newConnectionString))
  21.     {
  22.       connectionStrings.Add(newConnectionString);
  23.       SqlDependency.Start(newConnectionString);
  24.     }
  25.     ServiceBrokerUtility.ctx = ctx;
  26.     ServiceBrokerUtility.refreshMode = refreshMode;
  27.     ServiceBrokerUtility.collection = collection;
  28.     notifyRefresh = collection as INotifyRefresh;
  29.     AutoRefresh();
  30.   }
  31.  
  32.   static public void AutoRefresh()
  33.   {
  34.    var oldCookie = CallContext.GetData(sqlDependencyCookie);
  35.    try
  36.    {
  37.     var dependency = new SqlDependency();
  38.     CallContext.SetData(sqlDependencyCookie, dependency.Id);
  39.     dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
  40.     ctx.Refresh(refreshMode, collection);
  41.    }
  42.    finally
  43.    {
  44.     CallContext.SetData(sqlDependencyCookie, oldCookie);
  45.    }
  46.   }
  47.  
  48.   static void dependency_OnChange(object sender, SqlNotificationEventArgs e)
  49.   {
  50.    AutoRefresh();
  51.    if (ServiceBrokerUtility.notifyRefresh != null)
  52.     System.Windows.Application.Current.Dispatcher.BeginInvoke(
  53.      (Action)(() =>
  54.       ServiceBrokerUtility.notifyRefresh.OnRefresh()));
  55.   }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment