Connecting Tech Pros Worldwide Help | Site Map

odd SqlInfoMessageEventHandler problem (source code provided)

  #1  
Old November 5th, 2008, 11:35 AM
codefragment@googlemail.com
Guest
 
Posts: n/a
Hi
I'm trying to get the InfoMessage code below working. What I'm
finding is that the print statements have to be before the select
statement, which kind of defies the point in my scenario.
e.g. here the event will fire for 'hi mum' but not for 'hi again'
What am I doing wrong here?

thanks


<add name="Northwind"
connectionString="Integrated
Security=SSPI;database=Northwind;server=localhost; Connect Timeout=30;
Persist Security Info=False"
/>



private void ShowPrintStatements()
{
DbProviderFactory factory = SqlClientFactory.Instance;

ConnectionStringSettings settings =
ConfigurationManager.ConnectionStrings["Northwind"];
string theConnectionString = settings.ConnectionString;

DbConnection connection = factory.CreateConnection();
if (connection is SqlConnection)
{
((SqlConnection)connection).InfoMessage += new
SqlInfoMessageEventHandler(Chapter4_InfoMessage);
}

connection.ConnectionString = theConnectionString;
connection.Open();

DbCommand command = factory.CreateCommand();
command.Connection = connection; command.CommandType =
CommandType.Text;
command.CommandText = "print 'hi mum';select 1 as somecolumn;print
'hi again'";
DbDataReader reader = command.ExecuteReader();

reader.Close();
}

void Chapter4_InfoMessage(object sender, SqlInfoMessageEventArgs e)
{
string message = e.Message;
}
  #2  
Old November 5th, 2008, 11:05 PM
Erland Sommarskog
Guest
 
Posts: n/a

re: odd SqlInfoMessageEventHandler problem (source code provided)


codefragment@googlemail.com (codefragment@googlemail.com) writes:
Quote:
I'm trying to get the InfoMessage code below working. What I'm
finding is that the print statements have to be before the select
statement, which kind of defies the point in my scenario.
e.g. here the event will fire for 'hi mum' but not for 'hi again'
What am I doing wrong here?
You need to call .NextResult to get the second message. To do thing
properly, you should always iterate over .NextResult until returns NULL,
to be sure that you get all results and messages.

--
Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se

Links for SQL Server Books Online:
SQL 2008: http://msdn.microsoft.com/en-us/sqlserver/cc514207.aspx
SQL 2005: http://msdn.microsoft.com/en-us/sqlserver/bb895970.aspx
SQL 2000: http://www.microsoft.com/sql/prodinf...ons/books.mspx

  #3  
Old November 7th, 2008, 08:25 AM
codefragment@googlemail.com
Guest
 
Posts: n/a

re: odd SqlInfoMessageEventHandler problem (source code provided)


You need to call .NextResult to get the second message. To do thing
Quote:
properly, you should always iterate over .NextResult until returns NULL,
to be sure that you get all results and messages.
Yep, that did it, thanks :-)
Closed Thread