HillBilly <so******@somew here.comwrote:
I refactored as this implementation. ..
#region Method: IsDatabaseOffli ne()...
public void IsDatabaseOffli ne()
{
SqlConnection connection = new
SqlConnection(G etConnectionStr ing("MyConnecti onString"));
if (!String.IsNull OrEmpty(connect ion.ToString()) )
{
try
{
connection.Open ();
connection.Clos e();
connection.Disp ose();
}
catch (SqlException ex)
{
Response.Redire ct(ResolveUrl(" ~/ErrorPages/DatabaseError.a spx?Caught-SqlException")) ;
}
}
}
#endregion
No, that is still a bad thing in my view, for a few reasons:
1) You're mixing your database logic with your page logic. What if you
ever want to create a page with diagnostics of various things? Or use
this code for something other than a web page?
2) A method called "IsDatabaseOffl ine" really should return something.
Based on the method name I *certainly* wouldn't expect it to be
redirecting a response.
3) You should still use a "using" statement for the connection, IMO.
That way you don't need to explicitly close it or call Dispose (doing
both is reasonably pointless, btw) but you'll still close it if
something odd (like an asynchronous exception) happens after Open.
4) It may well be worth actually *doing* something with the connection
- something which forces it to try to talk to the database for real.
Otherwise you may find you've got stale connections which can be opened
and closed with no problems, but can't do any real work. I know that's
a problem with some connections on some platforms, but I don't know if
it's relevant in your particular situation.
You know I didn't even need the redirect in the try block but it sure taught
me a lesson in two ways. First, I've learned about ThreadAbortExce ption and
secondly I realized when the IsDatabaseOffli ne method is marked static it
causes an error because the SqlConnection object is not static which implies
all members of a static method must themselves be static.
The SqlConnection object is declared inside the method - it's
irrelevent. However, the Response property isn't static, and
GetConnectionSt ring may not be depending on what you're doing.
--
Jon Skeet - <sk***@pobox.co m>
Web site:
http://www.pobox.com/~skeet
Blog:
http://www.msmvps.com/jon.skeet
C# in Depth:
http://csharpindepth.com