patterncsharpMinor
C# Method to determine database status
Viewed 0 times
databasestatusdeterminemethod
Problem
I have a task that I am trying to complete and would appreciate direction, to know which is the most efficient path to take for future requirements.
Use Case: A background process that determines if a specific database is broken. This task will be run every two minutes as we must know ASAP if there is a problem with the database.
My Solution: Opening a connection with said database, if the conenction is refused - an email is then sent notifying the appropriate individuals.
Here is the method I built to determine the DB state:
I am aware that the Using statement leverages the IDisposable class and will auto-dispose the connection, but I wanted to be extra cautious and included the finally statement out of paranoia.
If anyone could please give me criticism, suggestions, recommendations or really anything that can help me improve this code I would greatly appreciate it. I am also open to different ideas on how I can determine if a DB is broken.
Use Case: A background process that determines if a specific database is broken. This task will be run every two minutes as we must know ASAP if there is a problem with the database.
My Solution: Opening a connection with said database, if the conenction is refused - an email is then sent notifying the appropriate individuals.
Here is the method I built to determine the DB state:
public bool DatabaseConnection()
{
bool statusUp = true;
using (var databaseConnection = new SqlConnection(ConfigData.ConnectionStrings.DatabaseConnectionString))
{
try
{
databaseConnection.Open()
}
catch (SqlException ex)
{
const string message = "Could not establish a connection with Database.";
Log.DatabaseStatusDown(message, ex);
statusUp = false;
}
finally { databaseConnection.Close(); }
}
return statusUp
}I am aware that the Using statement leverages the IDisposable class and will auto-dispose the connection, but I wanted to be extra cautious and included the finally statement out of paranoia.
If anyone could please give me criticism, suggestions, recommendations or really anything that can help me improve this code I would greatly appreciate it. I am also open to different ideas on how I can determine if a DB is broken.
Solution
Closing the database connection in the
To overcome this problem in a clean way you should let the
Method's should be named using a verb or verb phrase. So better name it e.g
Otherwise it looks ok for me.
finally will cause an exception if the Open () call throws an exception, so you better close the connection immediately after you opened it in the try block. To overcome this problem in a clean way you should let the
using block handle it to close the database connection.Method's should be named using a verb or verb phrase. So better name it e.g
IsDatabaseServerAlive ().Otherwise it looks ok for me.
Context
StackExchange Code Review Q#90061, answer score: 3
Revisions (0)
No revisions yet.