Query Notifications : SqlDependency « Database ADO.net « Visual C++ .NET






Query Notifications

 
#include "stdafx.h"
using namespace System;
using namespace System::Data;
using namespace System::Threading;
using namespace System::Data::SqlClient;

ref class MyNotification
{
public:
    MyNotification(String^ connectionString, String^ sql)
    {
        ConnectionString = connectionString;
        Sql = sql;

        SqlDependency::Start(ConnectionString);

        SyncHandle = gcnew AutoResetEvent(true);
        ChargeNotification();
    }
    void OnChangedHandler(Object^ caller, SqlNotificationEventArgs^ e)
    {
        if ( e->Source == SqlNotificationSource::Data &&
            e->Type == SqlNotificationType::Change &&
            (e->Info == SqlNotificationInfo::Delete ||
            e->Info == SqlNotificationInfo::Insert ||
            e->Info == SqlNotificationInfo::Update) ){
            Console::WriteLine(e->Info.ToString());

            ChargeNotification();
        }
    }

    void ChargeNotification()
    {
        SqlConnection^ connection = gcnew SqlConnection(ConnectionString);
        connection->Open();

        SqlCommand^ WatchCommand = gcnew SqlCommand(Sql, connection);

        SqlDependency^ myDependency = gcnew SqlDependency(WatchCommand);

        myDependency->OnChange += gcnew OnChangeEventHandler(this, &MyNotification::OnChangedHandler);

        SqlDataReader^ myReader = WatchCommand->ExecuteReader();
        myReader->Close();

        SyncHandle->Set();
    }
    void Wait()
    {
        SyncHandle->Reset();
        SyncHandle->WaitOne();
    }

    String^ ConnectionString;
    String^ Sql;
    AutoResetEvent^ SyncHandle;
};

void main()
{
        SqlConnection^ myConnection = nullptr;

        SqlConnectionStringBuilder^ connectionBuilder = gcnew SqlConnectionStringBuilder();        
        connectionBuilder->DataSource = "localhost\\sqlexpress";
        connectionBuilder->InitialCatalog = "myCatalog";
        connectionBuilder->IntegratedSecurity = true;

        myConnection = gcnew SqlConnection(connectionBuilder->ToString());
        myConnection->Open();
        
        MyNotification^ commandNotification = gcnew MyNotification(myConnection->ConnectionString,"SELECT ID, Song FROM dbo.Music");

        SqlCommand^ testCommand = gcnew SqlCommand("INSERT INTO Music(Song) VALUES('T')",myConnection);
        testCommand->ExecuteNonQuery();
        commandNotification->Wait();

        testCommand->CommandText ="UPDATE Music SET Song='T' WHERE Song='T'";
        testCommand->ExecuteNonQuery();
        commandNotification->Wait();

        testCommand->CommandText = "DELETE FROM Music WHERE Song='T'";
        testCommand->ExecuteNonQuery();
        commandNotification->Wait();
        myConnection->Close();
}

   
  








Related examples in the same category