Can't connect with Azure SQL using SQLConnection on Linux - c#

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.

Related

C# Console Application Unable to Connect to Remote SQL Server 2008 Using TCP/IP Protocol

I am currently unable to connect to a remote SQL Server using the TCP/IP protocol in C#.
Using named pipes does work, but the TCP/IP connection doesn't. The frustrating thing is that I can connect to the database using the TCP/IP protocol in the server explorer window within Visual Studio 2015, but my code cannot, even though I am copying and pasting the exact connection strings.
As soon I a remove "Network Library = dbmssocn" from the connection strings, the code works, but this makes it use named pipes, which I cannot rely on being an an option outside of the development environment.
Just in case, I have verified that the TCP/IP protocol is enabled on the SQL Server. This makes sense, since I can specify the TCP/IP protocol in visual studio's server explorer window and those connections work.
The server is also configured for both SQL authentication and Windows authentication. The windows firewall is probably also not the issue as it is currently turned off.
Here is the code that I'm using:
DbConnection testConnectionIntegrated = new SqlConnection("Data Source = MyServer; Initial Catalog = MyDatabase; Integrated Security = True; Encrypt = True; TrustServerCertificate = True; Network Library = dbmssocn");
try
{
Console.Write("Attempting to connect using Windows Authentication...");
testConnectionIntegrated.Open();
Console.WriteLine(testConnectionIntegrated.State);
}
catch (Exception caughtException)
{
Console.WriteLine("Integrated Security Connection Failed");
Console.WriteLine(caughtException.Message);
}
finally
{
Console.Write("Closing connection...");
testConnectionIntegrated.Close();
Console.WriteLine(testConnectionIntegrated.State);
}
DbConnection testConnectionSQLAuth = new SqlConnection("Data Source = MyServer; Initial Catalog = MyDatabase; Persist Security Info = True; User ID = my_user_name; Password = my_password; Encrypt = True; TrustServerCertificate = True; Network Library = dbmssocn");
try
{
Console.Write("Attempting to connect using SQL Authentication...");
testConnectionSQLAuth.Open();
Console.WriteLine(testConnectionSQLAuth.State);
}
catch (Exception caughtException)
{
Console.WriteLine("SQL Authentication Connection Failed");
Console.WriteLine(caughtException.Message);
}
finally
{
Console.Write("Closing connection...");
testConnectionSQLAuth.Close();
Console.WriteLine(testConnectionIntegrated.State);
}
And this is the error message I'm seeing for both connection attempts:
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 - A non-recoverable error occurred during a database lookup.)
Is there anything that I'm missing?
Edit:
I have verified the following on the server:
Remote connections are allowed.
The TCP/IP protocol is enabled and configured.
The named pipes protocol is enabled and configured.
Firewall is not the problem.
The SQL Server and SQL Server Browser services are running.
I have restarted the services to make sure.
Also, I have restarted my development machine, and the problem still exists.

How to access database in SQL Server 2008 from another computer

I need to access database in another computer using c#...I am using connection string with IP address for accessing database and also changed firewall setting but it shows error as follows
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 - A connection attempt failed because the connected
party did not properly respond after a period of time, or established
connection failed because connected host has failed to respond.)
I m using this connection string
SqlConnection con = new SqlConnection("data source=192.168.1.12,1063;initial catalog=trinity;integrated security=false;network library=DBMSSOCN");
This is actually quite a large topic involving: Networking, Authentication, Authorization and Permissions. Quick checklist:
Open port 1433 on local firewall where SQL Server is running.
Open SQL Server Configuration Manager on the local machine where SQL Server is running and enable TCP connections.
Add a Windows Login or SQL Account user and grant permissions to the database. DON'T USE THE SA ACCOUNT TO CONNECT REMOTELY EVER!.
In your connection string you have Integrated security=false;, so you need to provide User ID=mysqlserveruserid;Password=mysqlserverpassword; parameters in your connection string instead. If you change Integrated security=true; your Windows credentials will be used.
Also why the IP Address? Do you not have network name resolution on your network? e.g. DNS or WINS.
Is SQL Server running as the default instance or does it have a named instance? If it's a named instance (would have been a choice taken when installing SQL Server) You will need Data source=computername\sqlserverinstancename;
More detailed information on all these aspects can be found on MSDN
https://msdn.microsoft.com/en-us/library/ms345332.aspx
Try given solutions, it may help you
http://blogs.msdn.com/b/walzenbach/archive/2010/04/14/how-to-enable-remote-connections-in-sql-server-2008.aspx

Cannot connect to any remote database using SqlConnection

I cannot connect to a particular SQL Server 2008 database server from C#.
I am able to connect using SSMS, and run queries using SQLCMD, but when I try to connect from C# using the SqlConnection it fails to open the connection with a 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: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
Here is my code:
using (SqlConnection conn = new SqlConnection(#"Server=LDNPSM050000137\PLN000000014T;Initial Catalog=MiscData;Integrated Security=True;"))
{
//exception occurs on this line
conn.Open();
//use connection
conn.Close();
}
I get a similar response using ODBC:
string connectionString = #"Driver={SQL Server Native Client 10.0};Server=LDNPSM050000137\PLN000000014T;Database=MiscData;Trusted_Connection=yes;";
using (OdbcConnection connection = new OdbcConnection(connectionString))
{
connection.Open();
}
This fails with an OdbcExcpetion:
ERROR [08001] [Microsoft][SQL Server Native Client 10.0]SQL Server Network Interfaces: Error Locating Server/Instance Specified [xFFFFFFFF].
ERROR [HYT00] [Microsoft][SQL Server Native Client 10.0]Login timeout expired
ERROR [08001] [Microsoft][SQL Server Native Client 10.0]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online.
I have checked the server and instance name are correct, and the server is configured to allow remote connections because I can connect through SSMS. Does anybody have a suggestion of what the problem could be or how to resolve this?
Update:
In case this helps somebody diagnose the problem - This is specific to my machine/user account. My colleague can run the code fine from his machine. I am also able to connect to my local instance using a connectionstring with the appropriate changes to the Server and Initial Catalog.
The error occurs for all remote database servers.
I'm not sure if this is specific to my company's specific IT infrastructure - but the reason this was not working for me was because the project was saved in My Documents which stored on a network share. Apparently .NET will not let you connect to a remote database server when the executing code is located on a network share - it work fine when I copied the project to my local drive. I am using Windows 7 and Visual Studio 2012.
Network shares by default have partial trust, so things that work when a project is on your local drive, e.g. connecting to remote server, won't from network location.
You can give the network location full trust (https://msdn.microsoft.com/en-us/library/zdc263t0(VS.80).aspx) or move your project onto your local drive.
I think the problem is the Server value in your Connect string:
From MSDN
I think you need to do this:
Server=tcp:LDNPSM050000137\PLN000000014T
Server=np:LDNPSM050000137\PLN000000014T
Depending upon whether you want to use TCP or Named Pipes...

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