Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static class ServiceBrokerUtility
- {
- private static List<string> connectionStrings = new List<string>();
- private const string sqlDependencyCookie = "MS.SqlDependencyCookie";
- private static ObjectContext ctx;
- private static RefreshMode refreshMode;
- private static IEnumerable collection;
- private static INotifyRefresh notifyRefresh;
- static public void AutoRefresh(this ObjectContext ctx,
- RefreshMode refreshMode, IEnumerable collection)
- {
- var csInEF = ctx.Connection.ConnectionString;
- var csName = csInEF.Replace("name=", "").Trim();
- var csForEF =
- System.Configuration.ConfigurationManager.ConnectionStrings[csName].ConnectionString;
- var newConnectionString = new
- System.Data.EntityClient.EntityConnectionStringBuilder(csForEF).ProviderConnectionString;
- if (!connectionStrings.Contains(newConnectionString))
- {
- connectionStrings.Add(newConnectionString);
- SqlDependency.Start(newConnectionString);
- }
- ServiceBrokerUtility.ctx = ctx;
- ServiceBrokerUtility.refreshMode = refreshMode;
- ServiceBrokerUtility.collection = collection;
- notifyRefresh = collection as INotifyRefresh;
- AutoRefresh();
- }
- static public void AutoRefresh()
- {
- var oldCookie = CallContext.GetData(sqlDependencyCookie);
- try
- {
- var dependency = new SqlDependency();
- CallContext.SetData(sqlDependencyCookie, dependency.Id);
- dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
- ctx.Refresh(refreshMode, collection);
- }
- finally
- {
- CallContext.SetData(sqlDependencyCookie, oldCookie);
- }
- }
- static void dependency_OnChange(object sender, SqlNotificationEventArgs e)
- {
- AutoRefresh();
- if (ServiceBrokerUtility.notifyRefresh != null)
- System.Windows.Application.Current.Dispatcher.BeginInvoke(
- (Action)(() =>
- ServiceBrokerUtility.notifyRefresh.OnRefresh()));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment