Entity framework connection string enable to connect to DB server - c#

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;
}

Related

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.

Why is my azure process not connecting to azure database?

I have a web app and a batch pool.
In the batch pool, created tasks are using the same database as the web app.
Today I started receiving the following exception in the batch:
A transport-level error has occurred when receiving results from the server. (provider: Session Provider, error: 19 - Physical connection is not usable)
The code base has not changed, older versions do not work, there were no updates, it just popped out of the blue. I repeated a couple tasks in a controlled debug environment in VS and they went through without any exceptions thrown. I went in and added the batch node’s IP to the sql server firewall rules, also no result. Meanwhile, the web application uses the database just fine.
Both the web app and batch pool are located in East US.
Here’s a snippet from Program.cs in my batch task:
MyEntities db; //MyEntities extends DbContext
System.Data.Entity.Core.EntityClient.EntityConnectionStringBuilder connstr = new System.Data.Entity.Core.EntityClient.EntityConnectionStringBuilder();
connstr.ProviderConnectionString = connectionString;
connstr.Provider = "System.Data.SqlClient";
connstr.Metadata = "res://*/MyEntities.csdl|res://*/MyEntities.ssdl|res://*/MyEntities.msl";
try {
db = new PepeEntities(connstr.ConnectionString);
}
The connection string looks like this:
Persist Security Info=True; Data Source=<host>; Initial Catalog=<database name>; Integrated Security=False; User ID=<login>; Password=<password>; MultipleActiveResultSets=True; Connect Timeout=30; Encrypt=True;
Edit:
This problem has subsided the same way it appeared: out of the blue. I’ll carry out tests whenever it surfaces again.
You can try one of these 2 possibilities:
1. Enabling an Execution Strategy:
public class MyEntitiesConfiguration : DbConfiguration
{
public MyEntitiesConfiguration()
{
SetExecutionStrategy("System.Data.SqlClient", () => new SqlAzureExecutionStrategy());
}
}
# please view more details here:https://msdn.microsoft.com/en-US/data/dn456835
2. if you have explicitly opened the connection, ensure that you close it. You can use an using statement:
using(var db = new PepeEntities(connstr.ConnectionString){
..do your work
}
https://blogs.msdn.microsoft.com/appfabriccat/2010/12/10/sql-azure-and-entity-framework-connection-fault-handling/

Windows Authentication to Oracle database

I am trying to connect to a Oracle database by using the Windows Identity Token,
it worked yesterday but today it doesn't and I dont know why.
This is my code:
string ssoConnectionString;
var user = CreateSSOConnectionString(connectionStringBuilder, out ssoConnectionString);
oracleConnectionStringBuilder = new OracleConnectionStringBuilder
{
UserID = user.Identity.Name,
ConnectionString = ssoConnectionString
};
private WindowsPrincipal CreateSSOConnectionString(IConnectionStringBuilder connectionStringBuilder, out string ssoConnectionString)
{
var user = new WindowsPrincipal(WindowsIdentity.GetCurrent());
ssoConnectionString = ConfigurationManager.AppSettings["SSOConnectionString"];
ssoConnectionString = string.Format(ssoConnectionString, connectionStringBuilder.Host);
return user;
}
Connection = new Oracle.DataAccess.Client.OracleConnection();
Connection.ConnectionString = oracleConnectionString.ConnectionString;
Connection.Open(); //Fails on this line
The Code doesn't exactly look like this, but it's the essentials.
The SSO ConnectionString is located in app.config and looks like this:
<add key="SSOConnectionString" value="DATA SOURCE={0};User Id=/;" />
Here is a link showing how Oracle them selves explain how to do it: http://docs.oracle.com/cd/E11882_01/win.112/e18754/featConnecting.htm#i1006432
This is the error message I get:
ORA-1017: invalid username/password; logon denied
I have checked with breakpoints and everything looks fine. I've also searched alot around for this error and most people say it's because of password becoming case sensitive in Oracle version 11g, but I'm not providing any password.
What caused this error was actually a mismatch between the Oracle.DataAccess.dll version and the Oracle Client installed on my machine.
So the error is actually not at all related to the code or connection string in the configuration file.
Check your Oracle Client version by writing "sqlplus" in a command window, check that the Oracle.DataAccess.dll version and target .NET framework version matches.

Connecting to SQL Azure with ADO.NET

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.

How to have unique entity framework connection strings in each user configuration file

I have a situation when some clients see the server by its local IP and some by global. So that for some of them IP is 10.0.0.4 and for some 94.44.224.132. I use ClickOnce for deployment and Entity Framework to generate the DB mapping. Now ive connection string setting in my user settings section and for each user i store his own one. After that for entity context's construction i do the following:
SomeEntities context = new SomeEntities(new EntityConnection("metadata=res://*/DBModel.csdl|res://*/DBModel.ssdl|res://*/DBModel.msl;provider=System.Data.SqlClient;provider connection string=\"" + Properties.Settings.Default.ServerLocalConnectionString + "\""));
But there are some problems with Open/Close and Command execution after such approach. Is there some right way to store individual connection strings for every client and not overwrite them with deployment(ClickOnce is preferable)?
Found answer here.
EntityConnectionStringBuilder ecb = new EntityConnectionStringBuilder();
if (serverName=="Local")
{
ecb.ProviderConnectionString = Properties.Settings.Default.ServerLocalConnectionString;
}
else
{
ecb.ProviderConnectionString = Properties.Settings.Default.ServerConnectionString;
}
ecb.Metadata = "res://*/";
ecb.Provider = "System.Data.SqlClient";
SomeEntities context = new SomeEntities(new EntityConnection(ecb.ToString());
It seems this works. And now i can deploy the application and leave to the user the decision to which server does he want to connect and leave that configuration after updates, because its written in user's app.config.

Categories