Friday, July 17, 2009

Tip #50 – Working with Connection Events

The AdsConnection object has two events which can be monitored for activity. These include the InfoMessage and StateChanged events. The InfoMessage event is triggered whenever a warning message is sent from the server. The StateChanged event is fired each time the connection state changes.

In order to capture these events an event handler must be assigned for the events. You must first create a function which can handle the output of the event you wish to respond to. Then you must register this function as the event handler with the AdsConnection object. The example below shows code for both the InfoMessage and StateChanged events in C#.

   1: // State change event handler
   2: private void OnConnectionStateChange(object sender, StateChangeEventArgs args)
   3: {
   4:     lblOrigState.Text = args.OriginalState.ToString();
   5:     lblNewState.Text = args.CurrentState.ToString();
   6: }
   7:  
   8: // Warning message event handler
   9: private void OnWarningMessage(object sender, AdsInfoMessageEventArgs args)
  10: {
  11:     lblWarning.Text = args.Message;
  12: }
  13:  
  14: private void Form1_Load(object sender, EventArgs e)
  15: {
  16:     // setup the connection object
  17:     cnADS = new AdsConnection();
  18:  
  19:     // Add the event handler
  20:     cnADS.StateChange += new StateChangeEventHandler(OnConnectionStateChange);
  21:     cnADS.InfoMessage += new AdsInfoMessageEventHandler(OnWarningMessage);
  22: }

When the StateChanged event is fired the OnConnectionStateChange function is called. This function updates the contents of two label controls with the state descriptions. Similarly, the InfoMessage event will execute the OnWarningMessage function which will put the warning message into another label control. For the example I created an UPDATE statement that inserts a string value that is too long for the field I am updating.

Connection Events

When the Connect button is pressed the AdsConnection.Open() method is called. If successful the StateChanged event is fired and the labels ( Original State and Current State ) are updated. Since the connection is open the Current State is Open and the Original State was Closed.

Clicking the Warning button executed an UPDATE query which provided a string value that was too long for the field being updated resulting in a data truncation warning. This fires the InfoMessage warning which runs the OnWarningMessage function which places the warning message in the label on the bottom of the form.

No comments: