C# .NET - Error:A network-related or instance-specific error occurred

Asked By Elvin
27-Sep-11 11:14 PM
The full error during Run Time: 

Server Error in '/' Application.

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)

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: 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)

Source Error:

Line 50: 
Line 51:                 // opens the connection
Line 52:                 con.Open();
Line 53: 
Line 54: 

Source File: C:\Users\UsERpcONE\Documents\Visual Studio 2008\Projects\zephyrAir2\zephyrAir2\logIn.aspx.cs Line: 52







My intention is to have the user enter their username, and password and have them redirected to the ZephyrIndex.aspx page.

I was wondering if I have done something wrong with the connection string? Or is it something I missed in Web.config page?  Please assist.Here is the code below for code behind page of LogIn.aspx  using a .mdf database I made using SQL Server in ASP.NET 3.5 framework C# version. I have also the code for the Web.config below.


LOGIN.ASPX.CS CODE BELOW:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Data.SqlTypes;
//using System.Data.Odbc;
using System.Data.OleDb;

namespace zephyrAir2
{
    public partial class logIn : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {



        }
 /*   1)        string strConn;
                //strConn = WebConfigurationManager.ConnectionStrings["ConnectionASPX"].ConnectionString;
                strConn = "Initial Catalog = tblsZephyrAir.mdf;Data Source=localhost;Integrated Security=SSPI;";
                //SqlConnection Conn = new SqlConnection(strConn);
                Conn.Open(); */
        protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
        {
            {
                string username = Login1.UserName;
                string pwd = Login1.Password;

                // 1)
                // set up a connection object
                System.Data.SqlClient.SqlConnection con;

                //When the form loads, a new SQL Connection object will be created with the name of con
                con = new System.Data.SqlClient.SqlConnection();

                //tells C# where the database is
                con.ConnectionString = "Database=.\\SQLEXPRESS; AttachDbFilename=C:\\Visual Studio 2008\\Projects\\zephyrAir2\\zephyrAir2\\App_Data\\tblsZephyrAir.mdf; Integrated Security=True; Connect Timeout=30; User Instance=True";

                // opens the connection
                con.Open();


                string sqlUserName;
                sqlUserName = "SELECT Username,Password FROM UserAccounts ";
                sqlUserName += " WHERE (Username ='" + username + "')";
                sqlUserName += " AND (Password ='" + pwd + "')";
                SqlCommand com = new SqlCommand(sqlUserName, con);

                string CurrentName;
                CurrentName = (string)com.ExecuteScalar();

                if (CurrentName != null)
                {
                    Session["UserAuthentication"] = username;
                    Session.Timeout = 1;
                    Response.Redirect("ZephyrIndex.aspx");
                }
                else
                {
                    Session["UserAuthentication"] = "";
                }
                //close connection
                con.Close();
            }
        }
    }
}
       



WEB.CONFIG  CODE BELOW:   Remember the <!--   and the -->  are just comments.

<?xml version="1.0"?>
<configuration>
  
  <!--  -->
  <!--<connectionStrings>
    <add name="ConnectionASPX" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\tblsZephyAir.mdf;Integrated Security=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  -->
  
<configSections>
<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
<sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/>
<section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
<section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
<section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
</sectionGroup>
</sectionGroup>
</sectionGroup>
</configSections>
<appSettings/>
<connectionStrings>
    <!-- <add name="Zephyr_Air_DB2ConnectionString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Zephyr_Air_DB2.accdb;Persist Security Info=True"
   providerName="System.Data.OleDb" />  -->
<!-- <add name="ConnectionString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\CyBeRfOrCe\Desktop\Zephyr_Air_DB2.accdb"
   providerName="System.Data.OleDb" /> -->
  <add name="ConnectionString2" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\tblsZephyrAir.mdf;Integrated Security=True;User Instance=True"
   providerName="System.Data.SqlClient" />
  <add name="useThisConnStringYOOOOO!" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\tblsZephyrAir.mdf;Integrated Security=True;User Instance=True"
   providerName="System.Data.SqlClient" />
 </connectionStrings>
<system.web>
<!-- 
            Set compilation debug="true" to insert debugging 
            symbols into the compiled page. Because this 
            affects performance, set this value to true only 
            during development.
        -->
<compilation debug="true">
<assemblies>
<add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
</assemblies>
</compilation>
<!--
            The <authentication> section enables configuration 
            of the security authentication mode used by 
            ASP.NET to identify an incoming user. 
        -->
<authentication mode="Forms"/>
<!--
            The <customErrors> section enables configuration 
            of what to do if/when an unhandled error occurs 
            during the execution of a request. Specifically, 
            it enables developers to configure html error pages 
            to be displayed in place of a error stack trace.

        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
            <error statusCode="403" redirect="NoAccess.htm" />
            <error statusCode="404" redirect="FileNotFound.htm" />
        </customErrors>
        -->
<pages>
<controls>
<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</controls>
</pages>
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
</httpHandlers>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</httpModules>
</system.web>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<providerOption name="CompilerVersion" value="v3.5"/>
<providerOption name="WarnAsError" value="false"/>
</compiler>
</compilers>
</system.codedom>
<!-- 
        The system.webServer section is required for running ASP.NET AJAX under Internet
        Information Services 7.0.  It is not necessary for previous version of IIS.
    -->
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<remove name="ScriptModule"/>
<add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</modules>
<handlers>
<remove name="WebServiceHandlerFactory-Integrated"/>
<remove name="ScriptHandlerFactory"/>
<remove name="ScriptHandlerFactoryAppServices"/>
<remove name="ScriptResource"/>
<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>





  Web Star replied to Elvin
27-Sep-11 11:37 PM
Something stopped SQL Server from accepting your connection request.  This could be a network issue or it could be that SQL Server was overwhelmed with connections that were not closed (by your application) or that it has too many resource intensive queries going on to accept new connections.

Could be a lot of things

In Your connection string would look like:

<connectionStrings>
    <add name="myConnectionString";Integrated Security=true
       connectionString="Data Source=DB1\SQLExpress; database=Northwind;" />
</connectionStrings>

The connection string can be found in your web configuration file. (web.config)

Check if the connection string is alright. 
a) You could have misspelt one of the attributes in the connection string. The servername in the above example is DB1 and the instance name is SQLExpress. Check if you have provided them alright.

b)  first, check if you have connectivity to the db server from the web server. You can try the age-old ping command from the command prompt or commands like Tracert. Again, consult your network administrator for faster help.

c)Do you have any firewall in between the web server and the database. If yes, check if you can let this call go thru. You will have to talk to your network administrator to get this done.

d)Make sure the SQL Server Browser service is running on the system.
 
e) Check if the remote connections are configured in SQL Server.  The entire steps are outlined in the Microsoft KB article that is located http://support.microsoft.com/kb/914277. It explains how to create an exception in firewall in order to allow remote connections. 

And also see this article describe details about this error
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/
  aneesa replied to Elvin
27-Sep-11 11:43 PM

Problem

    <appSettings>
  
      <add key="ConnectionString" value="Data Source=(local)/sqlexpress; Database=TestEngine; User ID=ITP136; Password=election2008;"/>
     

    </appSettings>

 

Consider the below points if you're using above connection string.

  1. You need to change the Data Source to "(local)\sqlexpress".  You can even write the machine name or dot ( . ) in place of (local).  I would prefer the dot which is short and simple and avoids the machine name or any other confutions.
  2. This connection string implies that you must have a database named "TestEngine" already attached ( registered ) with your local machine.  So, make sure that this is true.  As you said the user/password are correct so there is no need to verify them.
Problem
    <connectionStrings>

  
              <add name="TestEngineConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=&quot;C:\Databases\TestEngine.mdf&quot;;Integrated Security=True;   

             Connect Timeout=30;User Instance=True" providerName="System.Data.SqlClient" />
  
    </connectionStrings>


Consider below points if you are using above connection string.
  1. The "Integrated Security=True" property implies that your current machine/domain user account will be used to connect to the database.  So make sure the user has proper permissions on the express and the database.
  aneesa replied to Elvin
27-Sep-11 11:48 PM

Change  this  ----->  Database=.\SQLEXPRESS   to ---->  Data Source=.\SQLEXPRESS
  Anoop S replied to aneesa
28-Sep-11 12:53 AM
it's related to some protocols configuration on your server... 

try below step...It may solve your problem...

1) Connect to your server.
2) Click on Start -> Programs -> Microsoft Sql Server 2005/2008 -> Configuration Tools -> SQL Server Surface Area Configuration. It will open up dialog box.
3) Now click on Surface Area Configuration for Service and Connections. It will open up another dialog box.
4) Click on Remote Connection under DataBase Engine node.
5) Make sure Local and remote connections radio button is checked. If not then checked.
6) checked last radio button " Using both TCP/IP and named pipes ".
7) Click on Applay -> OK..
  Reena Jain replied to Elvin
28-Sep-11 03:04 AM
hi,

Please follow the steps.

You are not allowed to remote connection please allow TCP/IP in your sql for that just follow the steps.
Go to All Programs >> Microsoft SQL Server 2008 >> Configuration Tools >> SQL Server Configuration Manager >> Select TCP/IP

Right Click on TCP/IP >> Click on Enable

You must restart SQL Server Services for all the changes to take effect. Right click and go to menu properties to select location where default port of SQL Server can be changed.

3) Open Port in Windows Firewall

Go to Control Panel >> Windows Firewall >> Change Settings >> Exceptions  >> Add Port

Then

Make the following entries in popup “Add a Port” and click OK.
Name : SQL
Port Number: 1433
Protocol: Select TCP

After above steps


4) Enable Remote Connection
Just check the checkbox Allow Remote Connection
  dipa ahuja replied to Elvin
28-Sep-11 07:27 AM
Follow Steps :

Step 1) Make sure SQL SERVER is up and the instance you try to connect is running.

Step 2) Your system Firewall should not block SQL Server port.

Step 3) Go to Computer Management >> Service and Application >> SQL Server 2005 Configuration >> Network Configuration. Enable TCP/IP protocol. Make sure that SQL SERVER port is by Default 1433.

Step 4) Now follow this KB Article of MSDN depending on your server :http://support.microsoft.com/default.aspx?scid=kb;EN-US;914277
Create New Account
help
SQL Server 2005 Express Replication SQL Server Does SQL Server 2005 Express edition support Web based replication from one Client Subscriber using SQL Server 2005 Express
xpsmtp for sql server 2005 SQL Server how can i use a xpsmtp in sql server 2005? SQL Server Discussions SQL Server (1) Money (1) Procedure (1) Database (1) From what I
Can I restore SQL Server 2005 backup to SQL Server Express 2005 SQL Server I have a backup of a SQL Server 2005 DB. Can I restore this to
Replication using SQL Server 2005 I am developing Windows Mobile 6 application. I am trying to synchronize SQL Server 2005 Compact Edition with SQL Server 2005. My problem is: While configuring publication, o n the Subscriber Types page, I am
SQL Server 2005 Lost Profiler Events SQL Server In SQL Server 2005, is it possible for the SQL Server profiler to miss events? This was the case