Connecting to SQL Azure with ADO.NET - c#

Hi I try to connect to a SQL AZURE DB with ADO.NET.
Here is my code:
private static string userName = "<**#********>";
private static string password = "<********>";
private static string dataSource = "<******.database.windows.net>";
private static string databaseName = "<******>";
public void Save()
{
SqlDataReader queryResultCloud;
string queryString = "select * from tblScan";
SqlConnectionStringBuilder connString2Builder;
connString2Builder = new SqlConnectionStringBuilder();
connString2Builder.DataSource = dataSource;
connString2Builder.InitialCatalog = databaseName;
connString2Builder.Encrypt = true;
connString2Builder.TrustServerCertificate = false;
connString2Builder.UserID = userName;
connString2Builder.Password = password;
using (SqlConnection connection = new SqlConnection(connString2Builder.ConnectionString))
{
SqlCommand command = new SqlCommand(queryString);
command.Connection = connection;
connection.Open();
queryResultCloud = command.ExecuteReader();
connection.Close();
}
and I get next error:
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)

Your code seems to be correct. One thing to try is to set TrustServerCertificate to true, and see if it works. Note it is recommended to set this property to false when Encrypt is set to true. But there’re reports that combination cause connection issues. I would like to suggest you to check http://www.wadewegner.com/2010/08/using-the-trustservercertificate-property-with-sql-azure-and-entity-framework/ for more information. In addition, check again if you have configured SQL Azure firewall to allow connection to your local machine. If you’re behind a proxy, it is needed to add your proxy’s IP address to the firewall exception.
Best Regards,
Ming Xu.

You're likely behind a proxy that doesn't allow outbound connections to port 1433, which is the only port you can use with SQL Azure:
The Windows Azure SQL Database service is only available with TCP port
1433. To access a SQL Database database from your computer, ensure that your firewall allows outgoing TCP communication on TCP port 1433.
I'm in this situation as well, and the most promising / challenging solution appears to be this port bridging application technique, but the solution itself is dated and needs an older version of VS than I have installed, so I'm looking at some other alternatives.

Related

How to convert ASP.NET Core code to access SQL Server to work with local SQLite DB?

I've been developing my web application to work with a SQL Server database hosted on Azure. To interface with it, I've been using code similar to the following:
SqlConnection scn = new SqlConnection(GetConnectionString());
SqlCommand cmd = new SqlCommand("Select page_name from Pages where page_name = #page_name", scn);
cmd.Parameters.AddWithValue("#page_name", pageName);
try
{
scn.Open();
string ret = Convert.ToString(cmd.ExecuteScalar());
scn.Close();
return ret;
}
catch (Exception er)
{
throw er;
}
finally
{
if (scn != null)
{
if (scn.State != System.Data.ConnectionState.Closed)
{
scn.Close();
}
scn.Dispose();
}
}
Now that I've realized that I can use a local SQLite database, I'm trying to switch over to that, since there is no reason for this application to need a DB server. I've put in this new connection string:
Data Source=test2.db;
But I get an error:
An unhandled exception occurred while processing the request.
ExtendedSocketException: No such device or address
System.Net.Dns.InternalGetHostByName(string hostName)
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: TCP Provider, error: 35 - An internal exception was caught)
It looks like it's still trying to connect to a SQL Server. How can I make it use the local SQLite database that I put in the connection string?
I figured it out, it was way simpler than I thought it would be.
Install the NuGet package System.Data.SQLite.
Replace all of the instances of SqlConnection, SqlCommand, SqlDataAdapter, etc. with their SQLite equivalents (eg. SQLiteConnection, SQLiteCommand, SQLiteDataAdapter).
In Startup.cs, change options.UseSqlServer to options.UseSqlite.

error connection to database c#

I'm trying to connect to a database from VS2017
var str = str1.ConnectionString =
"Data Source=141.*****.199;" +
"Initial Catalog=****;" +
"User id=***;" +
"Password=****;";
using (SqlConnection conn = new SqlConnection(str))
{
try
{
conn.Open();
var text = "SELECT * FROM Users u WHERE u.Id=76769";
...
}
catch (Exception e)
{
return req.CreateResponse(HttpStatusCode.OK, e.ToString());
}
and get error
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.
It's azure function. If I set this connection from LogicApp, then there are no errors.
Why the connection does not work from the azure-function?
can someone help. Functions refer to the database not with only ip , which are listed on the portal. They have several variants. And on the portal these addresses do not look, only through https: //resources.azure.com. And yes, you just need to specify in the firewall all valid values
I am connecting to an SQL DB from Azure Function, and I noticed a little difference in connection string that I am using.
Pls try and see if it works for you:
"Server=tcp:141.*****.199,1433;Initial Catalog=****;User ID=*****;Password=*****;"
1433 - is the default MS SQL port number.

Querying a website database from a C# console application

I'm trying to write a simple app in C# that will query a database available to the public located at https://newswire.theunderminejournal.com/
They give an example located at https://newswire.theunderminejournal.com/sample2.php
As far as I know, the server I'm trying to connect to is "newswire.theunderminejournal.com" and the database is "newsstand".
This gives me a string of:
string connection_str ="Server=newsstand.theunderminejournal.com;Database=newsstand";
My code looks like this:
xData = "Unable to connect to database.";
string server = "'newswire.theunderminejournal.com'";
//string server = "45.75.164.122";
string database = "'newsstand'";
string connection_str = string.Format("Server={0};Database={1};", server, database);
Console.WriteLine(connection_str);
SqlConnection connection = new SqlConnection(connection_str);
try
{
connection.Open();
xData = "Connection established!";
}
catch(Exception e)
{
xData = e.Message;
}
connection.Close();
connection.Dispose();
This results only in an error message:
"A network-related or instance-specific error occured while not
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)"
I've pinged the server, getting an IP address at 45.79.164.122 and no issues at all pinging it.
Is there something obvious I'm missing here? I'm brand new to C# so if there is another/better way of doing this, I'd appreciate it!
Thanks.
You cannot create a SqlConnection to a mySQL database, which is why the error message refers to "… establishing a connection to SQL Server.".
You need to use a MySqlConnection instead, which you get when you install Connector/Net - which you can download from Oracle here

Entity framework connection string enable to connect to DB server

I'm using the entity framework in a winforms application.
When i set scsb.DataSource ="localhost" every thing works fine but when i try to connect to onother DB server i got an exception:
"The underlying provider failed on Open."
public DistributionSSEntities1 Connection()
{
var scsb = new SqlConnectionStringBuilder();
scsb.DataSource = "192.168.1.100";
scsb.InitialCatalog = "DistributionSS";
scsb.IntegratedSecurity = true;
//------------------------
EntityConnectionStringBuilder builder = new EntityConnectionStringBuilder();
builder.Metadata ="res://*/Model.Model.csdl|res://*/Model.Model.ssdl|res://*/Model.Model.msl";
builder.Provider = "System.Data.SqlClient";
builder.ProviderConnectionString = scsb.ConnectionString;
DistributionSSEntities1 db = new DistributionSSEntities1(builder.ToString());
return db;
}
Has the remote Sql been setup to allow remote connections? Has the remote Sql been allowed access through the windows firewall... there's so many reasons why it wouldn't connect.
You're using Integrated Security - which may work great for a local Sql; but the network user that your WinForm app is running under must have the correct rights to access the remote box.
I'd suggest to start eliminating possibilities do the following:
Check the Sql logs on the target server. That always has the exact reason why an attemp failed - not the watered down version you get through the exception. (eg. C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\Log)
Connect to it using a sql username password - not integrated security to make sure it's not that
Firewall
EDIT
It's important to remember that the error messages return to the client regarding login attempt failures are purposefully obscure or without information - to limit an attacker gaining enough information to improve the attack (see the technet article for proof). So checking the Sql Server logs is a necessity - if your login/connection attempt actually made it to the server.
From Article:
To increase security, the error message that is returned to the client
deliberately hides the nature of the authentication error. However, in
the SQL Server error log, a corresponding error contains an error
state that maps to an authentication failure condition. Compare the
error state to the following list to determine the reason for the
login failure.
public DistributionSSEntities Connection()
{
string ConString = "SERVER=192.168.1.100;DATABASE=DistributionSS;UID=sa;PASSWORD=125;";
SqlConnectionStringBuilder SCB= new SqlConnectionStringBuilder(ConString);
//------------------------
EntityConnectionStringBuilder builder = new EntityConnectionStringBuilder();
builder.Metadata = "res://*/Model.Model.csdl|res://*/Model.Model.ssdl|res://*/Model.Model.msl";
builder.Provider = "System.Data.SqlClient";
builder.ProviderConnectionString = SCB.ConnectionString;
DistributionSSEntities db = new DistributionSSEntities(builder.ToString());
return db;
}

Connection String in c#

I am trying to connect to a database with my connection string and recieve the following error when trying to connect to the database. For intergrated Security I user SSID so I don't have to enter a username and password. Also, the database resides on the same machine and was created inside VS2010. I can connect to the db without a problem using the SqlDataSource, but I am looking to start writing my own connection strings.
protected void btnUpdate_Click(object sender, EventArgs e)
{
string source = "server=(local)" + "integrated security=SSPI;" + "Connect Timeout=30; " + "database=Name";
SqlConnection conn = new SqlConnection(source);
conn.Open();
conn.Close();
}
The Error I get is this:
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)
Try the following syntax as connection string:
string source = "Data Source=Server Address;Initial Catalog=Database Name;Integrated Security=SSPI;";
Where Server Address should be localhost or .\SQLExpress
Hope thats correct. I have'nt installed a vs for testing
You are missing a ; after the server name.
Why are you concatenating all the parts of the connection string if they do not change? It makes it more difficult to read.
Try this:
string source = "server=(local);integrated security=SSPI;ConnectTimeout=30;database=Name";
You need a semicolon after (local)
string source = "server=(local);" + "integrated security=SSPI
I notice you tagged the question with asp.net
by default asp.net runs under a system account, when you are using integrated security then that account is trying to access your database, it probably doesn't have permission.
Take a look here for some information.
I would recommend you to use the SqlConnectionStringBuilder: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder(v=VS.100).aspx
That will probably make it easier.
To connect to SQL Server from C#.NET, you need to create a connection string such as below:
private SqlConnection connection;
private string connectionString =
#"Server=(local);Database=Embedding_SQL_Test;User ID=sa;Password=123";
connection = new SqlConnection( connectionString );
Next, you use the SqlConnection object created above to create a 'SqlCommand', as shown below:
SqlCommand cmd = new SqlCommand( "select * from Customer where CustomerID = #Cid",
connection);
The SQL query shown here can be replaced by a SELECT, INSERT, UPDATE queries etc.
Next to execute the SQL queries in the database, you use the following methods:
ExecuteReader - to execute SELECT queries
ExecuteNonQuery - to execute INSERT, DELETE, UPDATE, and SET statements.
This is a very short description of how to connect to SQL Server database from C# and execute SQL queries in the database.
For details about the connection string, the methods and their parameters check the following link: ( http://www.shahriarnk.com/Shahriar-N-K-Research-Embedding-SQL-in-C-Sharp-Java.html )
Here you will also find details about how to pass parameters to the SQL queries as well as calling stored procedures and much more.

Categories