The SqlConnection object exposes a few events that can be useful to trap "back-channel" communications from SQL Server. There are no new events implemented by ADO.NET 2.0, so I'll have to make do with those pulled forward from ADO.NET 1.1. Handling the Connection events is simple for Visual Basic .NET developerssimply declare the Connection object using the WithEvents operand. In C#, you'll have to set up a delegate to the SqlInfoMessageEventHandler. The Connection events are the:
The example shown in Figure 9.34 shows how to set up the Connection event handlers in Visual Basic .NET and implement code to deal with the returned values. Because the FireInfoMessageEventOnUserErrors property has not been set to true, the RAISERROR messages generated by the T-SQL are not passed to the InfoMessage event handler. Figure 9.34. Using WithEvents to set up Connection Exception handlers.
Sometimes, your application design requires that you leave the SqlConnection open for the life of the applicationor at least for extended periods of time. In other designs (especially ASP.NET and Web Services), you'll be prevented from holding SqlConnection objects open. In this case, you need to avoid the most fundamental of mistakesleaving the SqlConnection in an open state when it falls from scope. I've talked about this a number of times, so I won't pound on this further. However, I do need to briefly touch on an old saw about using Connection.Dispose instead of or in addition to Connection.Close. OO purists will say, "If the class implements a Dispose method, you should call it when you're done with the object." I say to them in response: "Who's going to pay for all that extra (and unneeded code)? Are you aware that the TextBox, Label, and every other control has a Dispose method? How many programs do you see that call Dispose on every single one of these controls. Let's not go there." |