Phantom error for DB connection

I have an ASP/C#(4.0) app that was been running on my machine for several days. Suddently, in the middle of testing, I got this error. The app does seem to "wait" a short period before throwing the error. I was able to access the server via SQL-Management/Web/RDC/Ping just fine. I tried iisreset, recycling the app pool, and starting/stopping the app pool. Nothing got rid of the error until I rebooted. I'm assuming it has something to do with the connection pool and I figure I'm doing something wrong. This issue also affected the mini-iis that VS starts for debugging/etc.

I can't currently get it to happen again, but I really hate problems that "fix themselves". Since this can't currently be tested, I'm just looking for direction and some ideas incase it comes up again.

Thanks :-)

Exception information: Exception type: SqlException Exception message: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity) at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, SqlConnection owningObject) at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, TimeoutTimer timeout) at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, TimeoutTim er timeout, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance) at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance) at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options) at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject) at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject) at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) at System.Data.SqlClient.SqlConnection.Open() at MyApp.Default.BeginAsyncGetState(Object sender, EventArgs e, AsyncCallback cb, Object state) in C:...Default.aspx.cs:line 65 at System.Web.UI.Page.PageAsyncInfo.CallHandlersPossiblyUnderLock(Boolean onPageThread) at System.Web.UI.Page.PageAsyncInfo.CallHandlersCancellableCallback(Object state) at System.Web.HttpContext.InvokeCancellableCallback(WaitCallback callback, Object state) at System.Web.UI.Page.PageAsyncInfo.CallHandlers(Boolean onPageThread)

 public partial class Default : System.Web.UI.Page
    {

        SqlCommand _sqlCMD;
        SqlConnection _sqlConn = null;

         protected void Page_Load(object sender, EventArgs e)
        {
            String strStateCode = Request.QueryString["State"] ?? String.Empty;

            if (!Page.IsPostBack || !(Session["vchCurrentStateID"] ?? String.Empty).Equals(strStateCode))
            {
                AddOnPreRenderCompleteAsync(
                            new BeginEventHandler(BeginAsyncGetState),
                            new EndEventHandler(EndAsyncGetState)
                        );
            }
        }

         protected IAsyncResult BeginAsyncGetState(object sender, EventArgs e, AsyncCallback cb, object state)
        {
            String ConString = System.Configuration.ConfigurationManager.ConnectionStrings["ReportServer"].ConnectionString;
            _sqlConn = new SqlConnection(ConString);
            _sqlCMD = new SqlCommand();
            SqlDataReader myReader = null;

            _sqlCMD.Connection = _sqlConn;
            _sqlCMD.CommandType = CommandType.StoredProcedure;

            String strStateCode = Request.QueryString["State"] ?? String.Empty;

            IAsyncResult tmpResult = null;
            try
            {
                _sqlConn.Open();

                _sqlCMD.CommandText = "dbo.StateLevel_gState";
                _sqlCMD.Parameters.AddWithValue("@vchShortCode", strStateCode);

                tmpResult = _sqlCMD.BeginExecuteReader(cb, state);
            }
            catch (Exception ex)
            {
                if (_sqlConn != null)
                    _sqlConn.Close();
                if (_sqlCMD != null)
                    _sqlCMD.Dispose();
                if (myReader != null)
                    myReader.Dispose();

                throw;
            }
            return tmpResult;
        }

        void EndAsyncGetState(IAsyncResult ar)
        {
            try
            {
                using (SqlDataReader myReader = _sqlCMD.EndExecuteReader(ar))
                {
                    if (myReader.Read())
                    {
                        lblStateName.Text = myReader.GetString(1);
                        Session["iCurrentStateID"] = myReader.GetInt32(0);
                        Session["vchCurrentStateID"] = Request.QueryString["State"];
                        Session["vchReportLocation"] = myReader.GetString(3);
                    }
                    else
                    {
                        lblStateName.Text = "Invalid State";
                    }
                }
            }
            finally
            {
                if (_sqlConn != null)
                    _sqlConn.Close();

                if (_sqlCMD != null)
                {
                    _sqlCMD.Dispose();
                }
            }
        }
        }

Looks like its a named pipes issue and it could be a change to the database server that you don't know about. Have a look at this: http://blog.sqlauthority.com/2009/05/21/sql-server-fix-error-provider-named-pipes-provider-error-40-could-not-open-a-connection-to-sql-server-microsoft-sql-server-error/

Hope it helps


Named Pipes is the last protocol the sql provider tries if it is using multiple protocols, so you may just have a general authentication issue. I've seen error you've described happen when connecting to servers using different windows accounts by mapping drives or using "Run as".

One trick that might work is to create an alias for your server in the etc/hosts file, and use that in the connection string. That helps keep credentials from being shared across processes.

链接地址: http://www.djcxy.com/p/56706.html

上一篇: 使用.mdf数据库发布ASP.NET项目

下一篇: 数据库连接的幻像错误