Connection Open Event (in DAB)

Topics: Data Access Application Block
Jul 22, 2010 at 4:43 PM

Hi,

I need an event (with the connection object) when a connection has been opened to the DB. How do I go about getting this achieved?

Jul 23, 2010 at 6:33 AM

Hi,

As far as I know, DAAB does not support this directly. Though, one way I know how you can achieved this is to have something like the sample below.

static void Main(string[] args)
{
           Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>();
           DbCommand command = db.GetSqlStringCommand("Select * From Products");
           command.Connection = db.CreateConnection();
           command.Connection.StateChange += new StateChangeEventHandler(dbConn_StateChange);           

           using (command.Connection)
           {
               command.Connection.Open();
               using (IDataReader reader = db.ExecuteReader(command))
               {
                   if (reader.Read())
                  {
                       Console.WriteLine(reader[0].ToString());
                   }
               }
               command.Connection.Close();
           }
}

static void dbConn_StateChange(object sender, StateChangeEventArgs e)
{
Console.WriteLine(String.Format("Connection has been changed to: {0}", e.CurrentState));
}

Gino Terrado
Global Technology and Solutions
Avanade, Inc.
entlib.support@avanade.com