Mohammad Zare
Mohammad Zare

Reputation: 1509

How to check sql connection status in application start-up?

My application is a WPF C# database app that work with sql Server 2008 and Entity Framework.

if sql server Stopped or ..., my application hangs but i want to Show a message to the user if this problem occurred. Please help me how can i do it.

Upvotes: 1

Views: 4251

Answers (2)

Oleg Dok
Oleg Dok

Reputation: 21766

Since - in general - you may have no permissions or ability to check sql server's service status, try to connect to your database with the short timeout (5 sec or less) catch the Exception and show to user what you want.

var csb = new SqlConnectionStringBuilder(yourConnectionString);
csb.ConnectTimeout = 5;
try
{
  using(var c = new SqlConnection(csb.ToString())
  {
    c.Open();
  }
}
catch(Exception ex)
{
  Show the exception to user
}

go on your own

Upvotes: 1

Jan Remunda
Jan Remunda

Reputation: 7930

You can check if sql server service is running

http://support.microsoft.com/kb/912426/en-us

and then perform simple select in try-catch block to detect, that you have user rights to database.

try
{
var b = db.Table.FirstOrDefault();
}
catch(Exception e)
{
ShowMessageBox(e.Message);
}

Upvotes: 2

Related Questions