views:

448

answers:

2

Is it possible to detect an error in a connection before we get an application "Transport-level error" using Linq?

Lets say that I have a SQL server called SQLServer1, and I am running an application that connects to that server using LinQ to get some information.

I decide to change the server Name to SQLServer2. The next time my application run I will get an error like this:

"A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 0 - The specified network name is no longer available.)"

Because LinQ doens't know that there was a change!

How can I catch this during runtime? Is it possible to extend the DataContext class to check somehow the connection before getting the data?

Thanks!

A: 
try
{
   // run linq query here
}
catch (Exception e)
{
   // take appropriate action to handle the error like updating the connection string, etc.
}
John JJ Curtis
Thanks for your answer.But to be more precise, I am looking for a way to do this validation by extending the DataContext class.How can this be done?Is there any way for me to manipulate the connection Pool and find out that my connection is not OK?Thanks again.
You maybe be able to use the DbConnection property. If you just wanted to do a quick check, you could close and re-open the DbConnection inside of a try-catch block, then if there was an error you could set the connection string on the DbConnection to a new value and try opening it again.
John JJ Curtis
+2  A: 

Here's how I've extended the class. I use a singleton pattern for calling the data context, which results in one data context object being instantiated per page request regardless of the number of times the singleton is called. On the first call to the singleton per request, I run DataContext.DatabaseExists(), and if it is false, I gracefully handle the error. Now whenever any of my code attempts to do anything with the datacontext, it prompts my users with a "sorry, the database is down" message.

ASP.NET C# code:

namespace dal
{
    public partial class DataModelDataContext
    {
        public static DataModelDataContext DataContext
        {
              get
              {
                  if (System.Web.HttpContext.Current.Items["ModelDataContext"] == null)
                  {
                      DataModelDataContext datacontext = new DataModelDataContext();
                      //Once per page request, of the datacontext is requested, check to see if the database connection is valid.
                      if (!datacontext.DatabaseExists())
                      {
                           System.Web.HttpContext.Current.Response.Redirect("DatabaseIsDown.html");
                      }
                      System.Web.HttpContext.Current.Items["ModelDataContext"] = datacontext;

                  }
                  return (DataModelDataContext)System.Web.HttpContext.Current.Items["ModelDataContext"];
              }
        }
    }
}
Adam