I have a method to check and make sure my SQL server is online, which I use in some connection sensitive parts of my code.
Although it works fine, I notice it takes upto 20ms to run, and I was wondering if anyone knows of a better way of checking SQL server to ensure its up and kicking.
Here is my existing code.
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public static bool IsSqlServerOnline(string connectionString)
{
#if DEBUG || DEBUG_SINGLE_CORE
Stopwatch sw = new Stopwatch();
sw.Start();
#endif
#if DEBUG || DEBUG_SINGLE_CORE
// This sould only occur of we are in the VSTS designer
if (string.IsNullOrEmpty(connectionString))
{
return false;
}
#endif
if ( !NetworkInterface.GetIsNetworkAvailable() )
{
return false;
}
if (string.IsNullOrEmpty(connectionString)) throw new ArgumentNullException("connectionString");
bool isSqlServerOnline = false;
SqlConnectionStringBuilder conString = new SqlConnectionStringBuilder(connectionString);
try
{
using (Ping p = new Ping())
{
string sqlSvr = conString.DataSource;
if (sqlSvr != null)
isSqlServerOnline = p.Send(sqlSvr).Status == IPStatus.Success;
}
}
catch (PingException)
{
isSqlServerOnline = false;
}
if ( isSqlServerOnline )
{
try
{
conString.ConnectTimeout = 3;
using (SqlConnection conn = new SqlConnection(conString.ToString()))
{
conn.Open();
isSqlServerOnline = true;
}
}
catch ( Exception )
{
isSqlServerOnline = false;
}
}
#if DEBUG || DEBUG_SINGLE_CORE
sw.Stop();
Trace.WriteLine(string.Format("IsSqlServerOnline: {0}", sw.ElapsedMilliseconds));
#endif
return isSqlServerOnline;
}