Search code examples
c#firebirdfirebird2.1

How to catch an event coming from database to C# (chat application)


I'm trying to develop chat application software using visual C# and Firebird as the database.

When a client a sends a message, I want client B to be notified.

How could I notify client B from the database that a message is waiting?

Assuming that I created an event table in my database that when an insert is made to the message table, how would I catch the message generated by the database in C#?

Can somebody guide me what code I should use in C# just to catch the notification of the database and display it to client B?


Solution

  • Below is a very simple program that handles events, it was copied/modified from Firebird .NET - Examples of use.

    The class that handles the events is FbRemoteEvent. You register the event(s) you are interested in on an instance and you add event handler(s) to be notified when an event occurs. Events are notified asynchronously (although the example doesn't clearly demonstrate that). The event count is the number of events since the last (processed) event notification.

    To simplify the example I have used an execute block to directly post the event (instead of - for example - posting the event from a trigger). Note that in this example the connection notifies itself of the event, but it would have worked exactly the same if the notification was coming from a different connection:

    class Program
    {
        static void Main(string[] args)
        {
            FbConnectionStringBuilder cs = new FbConnectionStringBuilder();
            cs.DataSource = "localhost";
            cs.Database = @"TESTDATABASE.FDB";
            cs.UserID = "SYSDBA";
            cs.Password = "masterkey";
            cs.Charset = "NONE";
            cs.Pooling = false;
    
            FbConnection connection = new FbConnection(cs.ToString());
            connection.Open();
    
            FbRemoteEvent revent = new FbRemoteEvent(connection);
            revent.AddEvents(new string[] { "new_order" });
    
            // Add callback to the Firebird events
            revent.RemoteEventCounts += new FbRemoteEventEventHandler(EventCounts);
    
            // Queue events
            revent.QueueEvents();
    
            string sql = "EXECUTE BLOCK AS BEGIN POST_EVENT 'new_order'; END";
    
            FbCommand command = new FbCommand(sql, connection);
    
            for (int i = 0; i < 5; i++)
            {
                command.ExecuteNonQuery();
            }
    
            System.Threading.Thread.Sleep(2000);
            connection.Close();
            Console.ReadLine();
        }
    
        static void EventCounts(object sender, FbRemoteEventEventArgs args)
        {
            Console.WriteLine("Event {0} has {1} counts.", args.Name, args.Counts);
        }
    }