locked
sql dependency RRS feed

  • Question

  • User-1169218742 posted

    hello everyone,

    so ive got an application the displays a sql table and i want changes to the table to show up whenever they are made without having to refresh the webpage

    i thought i could use sql dependency for this and rebind the gridview whenever there is a onchangeevent. buuut the event is never firing. here is my code, can anyone tell me what im doing wrong

    thank you

     protected void Page_Load(object sender, EventArgs e)
        {
            //Response.Write("<script>alert('" + msg + "')</script>");
            
            SqlClientPermission permission =
           new SqlClientPermission(
           PermissionState.Unrestricted);
            try
            {
                permission.Demand();
                
            }
            catch (System.Exception)
            {
                Response.Write("<script>alert('" + "no permission" + "')</script>");
            }
           // string connectionString = "Data Source =.\\SQLEXPRESS; Initial Catalog = DIRECTORYDB;  Integrated Security = True";
            string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
    
          //  SqlDependency.Stop(constr);
            SqlDependency.Start(constr);
    
            using (SqlConnection con = new SqlConnection(constr))
            {
                con.Open();
                using (SqlCommand command = new SqlCommand("SELECT First_Name FROM [dbo].[Table]", con))
                {
                    command.Notification = null;
                    // Create a dependency and associate it with the SqlCommand.
                    SqlDependency dependency = new SqlDependency(command);
                    // Maintain the refence in a class member.
    
                    // Subscribe to the SqlDependency event.
                    dependency.OnChange += new OnChangeEventHandler(OnDependencyChange);
    
                    // Execute the command.
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        // Process the DataReader.
                        
                       
                      
                    }
                }
            }
        
            
        }
        void OnDependencyChange(object sender, SqlNotificationEventArgs e)
        {
            // Handle the event (for example, invalidate this cache entry).
            Response.Write("<script>alert('" + "test" + "')</script>");
    
           
    
        }

    Monday, April 18, 2016 11:25 PM

All replies