Question

I'm using LINQ to SQL (dbml) and i'd like to check if the connection to the connection string is valid before going further.. for example, if the IP in the connection string is incorrect (or the database goes down), the program crashes and would like to make a check for this. I tried this:

if (DataContext.DatabaseExists())
  MessageBox.Show("Connection Exists");

That works if the connection is valid, but if the connection is invalid, it freezes at the if statement. What else can I try or do?

<add name="NflDataEntities" connectionString="metadata=res://*/NflData.csdl|res://*/NflData.ssdl|res://*/NflData.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=10.10.***.***;initial catalog=NflData;persist security info=True;user id=*****;password=****;MultipleActiveResultSets=True;App=EntityFramework&quot;"
      providerName="System.Data.EntityClient" />
Was it helpful?

Solution

This is by design. It "freezes" because it's scanning the network looking for the database server. If it's not found then it returns false, but that can take some time.

There are other options for verifying the server, like this one here. You'll need to use the SqlConnectionStringBuilder to parse the connection string and get the DataSource. Armed with that information you can run that command and grab its response. You'll need to redirect the standard output though and then parse the output. In short, not really a very good option.

OTHER TIPS

The problem may be that the request to the DB has a timeout that must tick down before it returns. Try setting the timeout in your connection string temporarily to a very short time (a second or two) and that may speed it up.

You can run an async method while showing a message that the system is working so the UI won't freeze while waiting for the Sql Response:

ShowMessage("Loading"); // Running on UI thread
        Task.Factory.StartNew(() =>
        {
            try
            {
                return DataContext.DatabaseExists();
            }
            catch (SqlException)
            {
                return false;
            }
        }).ContinueWith(isValid =>
        {
            if (isValid.Result)
                ShowMessage("Success");
            else
                ShowMessage("Failure");
        });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top