Monday, June 28, 2010

ADS 10 Tip #21 – TAdsEvent Component

Version 10 of the Advantage Components for Delphi include a new component TAdsEvent. This component makes it very simple for Delphi developers to add notifications to their applications. Advantage notifications are asynchronous and generally require the use of threading for implementation. The TAdsEvent component creates a secondary thread that can notify the main application thread whenever a notification is received.

Using the TAdsEvent component is quite simple you first assign an AdsConnecton which will be used to create another connection with the same properties. Next you can assign one or more events you want to be notified of in the Events property.

// Setup event component
evtAdmin.AdsConnection = cnAds;
evtAdmin.EventTimeout = -1;

// Start listening for events
evtAdmin.Active := true;

The TAdsEvent component has two events which are used to interact with the main thread. When a notification is received the OnNotification event is raised. If an error occurs the OnLog event is raised. The OnNotification event passes back the event name, event count and any event data. The OnLog event passes back an error string. The code below demonstrates parsing the notification data to determine if it should be displayed to the user in a statusbar control. 

procedure TfOrders.evtAdminNotification(Sender: TObject; event: string;
  count: Integer; eventdata: string);
  bShow: boolean;
  sMsg: string;
  bShow := True;

  if Event = 'AdminMsg' then
    sMsg := 'Admin Message: ' + eventdata
  else if Event = 'OrderProcessed' then
    sMsg := 'Order list updated';
    bShow := False;

  // Update the StatusBar
  if bShow then
    StatusBar1.Panels[0].Text := sMsg;

You can see a demonstration of the TAdsEvent component in this screencast on the DevZone.

No comments: