Intermittent SQL Server Connection Failure - c#

So we keep getting these errors, intermittently.
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)
Notice the part there about Named Pipes Provider?
Here is my connection string:
var conStr = "Data Source=tcp:MyServer;Initial Catalog=MyDatabase;User ID=myusername;Password=myuserpassword;Max Pool Size=100;MultipleActiveResultSets=True;Connect Timeout=120;";
In my connection string you'll notice I specify TCP. So this error message is crazy to me. I cant replicate this with any sort of reliability, but, it happens every, single, day. Nothing in the event logs, sql server log, surrounding application logs, nothing. Also when it happens there are at least 2k other connections from various other applications/servers throughout the enterprise that dont have this issue, until they do.
I should add that these are all VMs living inside of a VSphere cluster with 40Gbps connectivity between all the various hosts.
I've read every single hit 3 pages deep on google search results (yep, I went 3 whole pages deep). I'm lost.
What does the exception really mean?
Why does it say its using Named Pipers Provider?
Per request:
static void Main(string[] args)
{
var conStr = "Data Source=tcp:MyServer;Initial Catalog=MyDatabase;User ID=myusername;Password=myuserpassword;Max Pool Size=100;MultipleActiveResultSets=True;Connect Timeout=120;";
using (var con = new SqlConnection(conStr))
{
con.Open();
}
}

Related

Can't connect with Azure SQL using SQLConnection on Linux

I'm currently developing an ASP.NET Core WebApi that uses an Azure SQL Db for data persistence.
I use Linux Mint 19 as a development environment.
Unfortunately when dbConnection.Open() is called I keep getting SQLException:
Exception has occurred: CLR/System.Data.SqlClient.SqlException
An exception of type 'System.Data.SqlClient.SqlException' occurred in
System.Data.SqlClient.dll but was not handled in user code: '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: TCP
Provider, error: 40 - Could not open a connection to SQL Server)'
Here's my code:
private const string connectionString = "Server=tcp:{myserver}.database.windows.net,1433;Initial Catalog={mydb};Persist Security Info=False;User ID={user};Password={pass};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = "my_server.database.windows.net";
builder.UserID = "my_user";
builder.Password = "my_pass";
builder.InitialCatalog = "my_db";
using(IDbConnection dbConnection = new SqlConnection(builder.ConnectionString)){
dbConnection.Open();
var result = dbConnection.Query<Task>("SELECT * FROM Tasks");
if (dbConnection.State == ConnectionState.Open)
{
dbConnection.Close();
}
}
I've tried both using SQLConnectionStringBuilder and passing connectionString with my credentials. None of it worked.
I've opened port 1433 using the command:
sudo ufw allow 1433
but it didn't help, still getting the same exception.
Any help would be much appreciated.
Thanks.
UPDATE
I managed to connect with Azure SQL. It looks like my ISP blocks connection. I was able to connect using my smartphone WiFi hotspot.
First, make sure you have created appropriate firewall rule to allow traffic from your network to reach Azure SQL Database. Learn here how to do it.
Please try to ping your SQL Azure server. The ping should fail but it should return the current IP Address of the Azure SQL Database logical server. If you cannot see that IP returned then the issue is a DNS issue.
With the IP address returned on the previous step, try to telnet that IP address on port 1433.
telnet 181.37.11.112 1433
If you cannot connect using telnet, use traceroute command to diagnose when locate where data loss occurs.

provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server, pgsql

I am using Dapper to connect to pgsql database. The below code was working few days back. But don't know why its not working now. The same credentials are working with pgadmin3 but not with the c# code.
here is the controller method, for simplicity I wrote all db code in Get method.
the below code was
public IEnumerable<Item> Get()
{
string connString = "Server=192.168.1.11;Database=db_alpha1;Uid=postgres;Pwd=xxxxxx";
using (IDbConnection db = new SqlConnection(connString))
{
db.Open();
return db.Query<Item>("Select * From items").ToList();
}
}
Here is the error on line db.Open();:
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)
Also, I already configured pg_hba.conf file, added my system ip address.
Thanks to #Steve. The issue has resolved, it was a silly mistake, I replaced
SqlConnection with NpgsqlConnection, and added npgsql package.

web service - SQL connection string

I've built an .asmx web service which retrieves informations from a local sql server 2014 database.
Everything is working fine on localhost, but after publishing the web service to Azure i get the error:
An unhandled exception of type 'System.Web.Services.Protocols.SoapException'
occurred in System.Web.Services.dll
Additional information: Server was unable to process request. ---> 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: SQL
Network Interfaces, error: 26 - Error Locating Server/Instance
Specified)
SQL Server is configured to allow remote connections.
My connection string is like:
string con2 = #"Data Source=OfficePc\MSSQLSERVER2014;Initial Catalog=Database;Persist Security Info=True;User ID=Admin;Password=123456";
Is the error the result of something missing from the connection string, or am i missing some configurations changes?
As Paul mentioned in a comment under the question, your connection string is pointing to a local database resource (presumably on your dev machine). Even though you configured your local database server to support remote connections, the address OfficePc\MSSQLSERVER2014 isn't addressable, as that does not equate to a machine address (IP address).
Your app would need to connect to your database via an accessible IP address (which might require you to do some port-forwarding on your local network, or open ports on your firewall).
Alternatively, you can migrate your database to Azure (either with SQL Server in a VM or with the SQL Database service).
Keep in mind: If you are accessing a local (on-premises) database server from Azure, there will be latency added, as well as some outbound bandwidth costs.
It looks like SQL Server instance is not running or not accessible. Try connecting to the same database using SSMS and if you get the same error then the instance is not running.
Mostly the error occurs when the Database server was not found. Recheck if the server name (Data Source) is mentioned correctly. If you manually generated the connection string use .uld file to generate connection string.
To auto generate connection string using .udl file:
Create a sampe.txt file.
Rename it as sample.udl file.
Then double click on it, It will show you window entitled 'Data Link Properties'.
Configure the connection there.
Then Test the connection using test connection button.
Then open the file with notepad. It will show you the exact connection string.
For further reference check : MSDN

Impersonation succeeds but database connection fails

I have C# (.NET 4.5) code like this (simplified for demonstration) used to connect to a SQL Server 2012 database:
public static void Test(WindowsIdentity ident)
{
using (WindowsImpersonationContext ctx = ident.Impersonate())
{
using (SqlConnection con = new SqlConnection("Data Source=MyServer;Initial Catalog=MyDatabase;Persist Security Info=False;Integrated Security=SSPI;Network Library=dbmssocn"))
{
con.Open();
}
ctx.Undo();
}
}
The Open() method throws the following exception every time:
System.Data.SqlClient.SqlException (0x80131904): 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: TCP Provider, error: 0 - No
connection could be made because the target machine actively refused
it.)
The impersonation is succeeding because if I add tracing like this:
public static void Test(WindowsIdentity ident)
{
using (TextWriterTraceListener listener = new TextWriterTraceListener(#"C:\temp\trace.log"))
{
using (WindowsImpersonationContext ctx = ident.Impersonate())
{
listener.WriteLine("Impersonated");
using (SqlConnection con = new SqlConnection("Data Source=MyServer,MyPort;Initial Catalog=MyDatabase;Persist Security Info=False;Integrated Security=SSPI;Network Library=dbmssocn"))
{
listener.WriteLine("About to open connection; WindowsIdentity.GetCurrent().Name = " + WindowsIdentity.GetCurrent().Name);
con.Open();
}
ctx.Undo();
listener.WriteLine("Impersonation undone");
}
}
}
I get this:
Impersonated
About to open connection; WindowsIdentity.GetCurrent().Name = MyDomain\MyUser
If I put the exact same connection string in a .udl file, run it under the same "MyDomain\MyUser" account on the same machine, and click Test Connection, it succeeds. Since that's the case, I just don't see how the problem could be a firewall or anything of that nature. Does anyone know what could be going wrong? I do not have access to log onto the database server itself, so I cannot check its event log (etc.) at this point.
Your problem come from the connection string. The "Network Library = dbmssocn" in connection string will make client attempting to connect to SQL server on the UDP port 1434 rather than the TCP port 1433. You remove the "Network Library = dbmssocn" from the your application's connection string the application will connect to SQL server successfully.
The anonymous login failed error means that kerberos authentication failed for some reason.
Kerberos delegation (delegation is when your impersonated credentials are passed to a different machine) is relatively simple in theory. In practice it is fraught with gotcha's and can be one of the most frustrating things to troubleshoot.
In your case, it is entirely possible that from the standpoint of your program, the impersonation is succeeding, but the token it is passing to sql server isn't usable.
If you are lucky and have access to a really good network/system admin, then they can help you troubleshoot it.
Otherwise googling "sql server kerberos delegation" will point you in the right direction.
This is the kind of problem that requires substantial back and forth to resolve and is more suited to a forum than a Q&A site.

Sql Connection Problem

I have a sqlconnection problem. i have perfectly connection to sql server when i m using sqldatasource.
but when i m try use SqlConnection object throw an exception.
string qstring = "Data Source=****;Initial Catalog=**;User ID=**;Password=**";
SqlConnection con = new SqlConnection(qstring);
con.Open(); (exception thrown here)
exception is : 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)
Sql server is in different machine and i can connect using SqlDataSource object for example i can bind a grid by that way. But i must connect with SqlConnection object
Connection string is true because i have it from SqlDataSource...
Thx for your helps..
You might also want to make sure that the SQL Server is set up to accept remote connections.
(for sql2005 Configuration tools -> Surface AreaConfiguration-> Services and Connections -> database, Local and remote connections )
Is your SQL server is in the same machine ? if yes , Check the SQL server service is running , If its in a different machine,check your development machine has connectivity to it .You can ping to that machine to verify this. You can also check the surface area connection wizard to check whether the SQL server support remote connections , as snomag said
If the code that you have shown is what you have then I'm not surprised that you couldn't connect.
You'll need to have the correct Data Source, UserID and Password in qstring. As it stands asterisk characters won't mean anything.
A new point
A further point, which is often forgotten, SQLConnection will only work with Microsoft SQL Server. If your SQL is provided by a different manufacturer the use OleDBConnection instead.

Categories