Thursday, December 18, 2008

Getting SQL output messages and record counts from .Net

This code will allow you to get information messages and record counts by running SQL in .Net, besides the recordsets and output parameters.

The InfoMessage event will give you the output of PRINT and other low priority messages.
The StatementCompleted event will give you the record counts affected by each statement (like DELETE, INSERT, UPDATE and SELECT).

Tracking these outputs may help you debug your application in production more easily. The InfoMessage event gives you the line number the message was raised at.

(Using MS Enterprise Library)

Database db = DatabaseFactory.CreateDatabase();
SqlCommand dbc = (SqlCommand)db.GetSqlStringCommand(Properties.Resources.SqlPrepareRecords);
dbc.CommandTimeout = 0;
dbc.StatementCompleted += new StatementCompletedEventHandler(OnStatementCompleted);

using (dbc.Connection = (SqlConnection)db.CreateConnection())
{
dbc.Connection.FireInfoMessageEventOnUserErrors = true;
dbc.Connection.InfoMessage += new SqlInfoMessageEventHandler(OnInfoMessage);
dbc.Connection.Open();
dbc.ExecuteNonQuery();
dbc.Connection.Close();
}

public void OnStatementCompleted(Object sender, StatementCompletedEventArgs args)
{
Console.WriteLine("{0:G} - {1} records affected", DateTime.Now, args.RecordCount);
}

protected void OnInfoMessage(object sender, SqlInfoMessageEventArgs args)
{
foreach (SqlError err in args.Errors)
{
Console.WriteLine(String.Format("{0:G} - Line: {1} Message: {2}", DateTime.Now, err.LineNumber, err.Message);
}
}

No comments: