Frage

I am trying to make use of the Notification event given by Npgsql in vb.net. I partially got an idea about this mechanism, what i learned was, when ever a particular table's data has got changed, its trigger will be fired, so inside that trigger we can notify to the front end about the data change.

I managed to run this following code in my front end

Public Sub test()

    Dim conn = New NpgsqlConnection("Server=servername;port=portNo; _
               User Id=UID;pwd=PWD;DataBase=DB;")
    conn.Open()

    Dim command = New NpgsqlCommand("listen notifytest;", conn)
    command.ExecuteNonQuery()


    AddHandler conn.Notification, AddressOf NotificationSupportHelper

    command = New NpgsqlCommand("notify notifytest;", conn)
    command.ExecuteNonQuery()



End Sub

Private Sub NotificationSupportHelper(ByVal sender As Object, _
                                      ByVal e As NpgsqlNotificationEventArgs)

'Notified here.

End Sub

The above code is working with out any issues. But what i am trying to know is how to create a trigger which will notifies about the data change to the front end as a result the Notification event in my front end gets fired ? and where do i need to call listen.? Do i need to call listen for each query's execution .? Can any body will clarify my doubts with some sample codes.?

War es hilfreich?

Lösung

FRONT END:

Public Sub test()

Dim conn = New NpgsqlConnection(" Server=server; port=portno;User Id=uid; pwd=pwd; DataBase=Db; ")
conn.Open()

Dim command = New NpgsqlCommand("listen notifytest;", conn)
command.ExecuteNonQuery()

AddHandler conn.Notification, AddressOf NotificationSupportHelper


command = New NpgsqlCommand("update testtable set field='test' where id=1", conn)
Dim x As NpgsqlDataReader = command.ExecuteReader
End Sub

Private Sub NotificationSupportHelper(ByVal sender As Object, ByVal e As NpgsqlNotificationEventArgs)
    MsgBox(e.Condition)
End Sub

TRIGGER:

CREATE OR REPLACE FUNCTION testingNotify()
  RETURNS trigger AS
$BODY$ 
    begin
       notify notifytest;
       return null;
    end;     
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION testingNotify() OWNER TO testserver;

The trigger given above will get fired if Insert or delete or update happens in the table testtable. so in the above code, inside the procedure named test, i had written a query for updating the table tabletest, so while executing the query the NotificationSupportHelper gets called.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top