Domanda

I am using SqlDependency to monitor changes on a specific db table. I need to call a javascript event after the change event is triggered! any idea ? This code is in my asp.net page code behind

    public void StartTasksMonitor()
    {
        var con = new SqlConnection { ConnectionString = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString };

            if (con.State== System.Data.ConnectionState.Closed)
            {
                con.Open();
            }
            var cmd = new SqlCommand { CommandText = @"SELECT Id
      ,AssignedBy
      ,DateAssigned
      ,AssignedTo
      ,Title
      ,Description
      ,Completed
      ,DateDue
      ,Deleted
      ,DateDeleted
  FROM dbo.Tasks", Connection = con, Notification = null };

            SqlDependency dependency = new SqlDependency(cmd);
            SqlDataReader reader = cmd.ExecuteReader();
            con.Close();
            dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);


    }

    void dependency_OnChange(object sender, SqlNotificationEventArgs e)
    {
        if (e.Type == SqlNotificationType.Change)
        {
            // Have to remove this as it only work's once
            SqlDependency sqlDep = sender as SqlDependency;
            sqlDep.OnChange -= dependency_OnChange;

            // Resetup Dependecy
            StartTasksMonitor();
            string clientFunc = @"alert('test')";

            ScriptManager.RegisterStartupScript(this, GetType(), "alert", clientFunc , true);


        }

    }

the RegisterStartupScript will work only if a postback happens. No postback here is happening. The main purpose of the whole thing is to avoid postback :)

È stato utile?

Soluzione

Solved it by using SignalR :) SignalR + SQLDependency is a kick ass recipe :) Happy Coding

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top