Я отправил уведомление в свое приложение, когда что-то изменилось в таблице в моей базе данных SQL Server. Это мой класс слушателей:SqlDependency не срабатывает/запускает событие
class dbListener
{
public dbListener()
{
Debug.WriteLine(MainWindow.dbContext.Database.Connection.ConnectionString + "Password=xxx;");
SqlDependency.Stop(MainWindow.dbContext.Database.Connection.ConnectionString + "Password=xxx;");
SqlDependency.Start(MainWindow.dbContext.Database.Connection.ConnectionString + "Password=xxx;");
connection = new SqlConnection(MainWindow.dbContext.Database.Connection.ConnectionString + "Password=xxx;");
connection.Open();
SomeMethod();
}
SqlConnection connection;
void SomeMethod()
{
// Assume connection is an open SqlConnection.
// Create a new SqlCommand object.
SqlCommand command = new SqlCommand("SELECT CODVEI FROM dbo.ArchivioErogazioni", connection);
// Create a dependency and associate it with the SqlCommand.
command.Notification = null; // ---> DO I NEED IT??
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.
command.ExecuteReader();
}
// Handler method
void OnDependencyChange(object sender, SqlNotificationEventArgs e)
{
// Handle the event (for example, invalidate this cache entry).
MessageBox.Show("ikjkjkj");
Debug.WriteLine("fkldjkfjklgjf");
SomeMethod();
}
void Termination()
{
// Release the dependency.
SqlDependency.Stop(MainWindow.GetConnectionString("Model"));
}
}
Неправильное включение данного события. В начале приложения он показывает мне окно сообщения (это в случае управления, чтобы проверить его) один или два раза, я не знаю, почему. Затем, когда я редактирую значения в базе данных из SQL Server Management Studio, я получаю окно сообщения или 0 или 1 или 2 раза, а затем он снова не срабатывает.
В моей базе данных, я выполнить этот скрипт:
USE master ;
GO
ALTER DATABASE IN4MATICSystem_Pie SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE
GO
ALTER AUTHORIZATION ON DATABASE::IN4MATICSystem_Pie to sa;
Я, конечно, сделал большую ошибку ..... который один ??
UPDATE:
После намеков T McKeown, это мой код (по-прежнему не работает, он показывает мне 2 или 3 окна сообщений при запуске, а затем ничего):
class dbListener
{
public dbListener()
{
Debug.WriteLine(MainWindow.dbContext.Database.Connection.ConnectionString + "Password=xxx;");
SqlDependency.Stop(MainWindow.dbContext.Database.Connection.ConnectionString + "Password=xxx;");
SqlDependency.Start(MainWindow.dbContext.Database.Connection.ConnectionString + "Password=xxx;");
connection = new SqlConnection(MainWindow.dbContext.Database.Connection.ConnectionString + "Password=xxx;");
connection.Open();
SomeMethod();
}
SqlConnection connection;
SqlCommand command;
void SomeMethod()
{
// Assume connection is an open SqlConnection.
// Create a new SqlCommand object.
if (command == null)
{
command = new SqlCommand("SELECT * FROM dbo.ArchivioErogazioni", connection);
// Create a dependency and associate it with the SqlCommand.
}
else
{
command.Notification = null; // this cancels any previous notifcation object
}
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.
command.ExecuteReader();
}
// Handler method
void OnDependencyChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
// Handle the event (for example, invalidate this cache entry).
MessageBox.Show("ikjkjkj");
Debug.WriteLine("fkldjkfjklgjf");
SqlDependency dependency = (SqlDependency)sender;
dependency.OnChange -= OnDependencyChange;
//dependency.OnChange -= OnDependencyChange;
SomeMethod();
}
}
void Termination()
{
// Release the dependency.
SqlDependency.Stop(MainWindow.GetConnectionString("Model"));
connection.Close();
}
}
Я где-то читал, что мне нужно это сделать, иначе событие будет запущено только один раз ... это неправильно? –
Да, но вы никогда не регистрировали слушателя ... посмотрите на мое редактирование –
Я скопировал его, но .... он показывает мне 3 раза окно сообщения при запуске ... тогда я редактирую вовлеченную таблицу из sql server management, но ничего не происходит. Я также попытался переместить объявление зависимости SqlDependency снаружи, как атрибут класса te, и использовать его в методе init и в OnDependencyChange, но он все тот же. –