"The underlying provider failed on Open" [closed] - c#

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I keep getting this error when trying to open a connection using entity framework.
I can update the model from the database with no problems at all, but when I run the code in debug it gives this error.
(Running on a Windows 2008 VM)
The code fragment where the error appears looks like this:
public partial class SpatialDatabase : global::System.Data.Objects.ObjectContext
{
try
{
using (EntityConnection conn = new EntityConnection(this.Connection.ConnectionString))
{
conn.Open(); // <== fails here
EntityCommand cmd = conn.CreateCommand();
...
This is connection to an Oracle database.
This code is apparently running ok elsewhere so I have a feeling it is to do with the connection.
We are using an Oracle for .NET (ODAC) driver. I have no idea whether it's 64 or 32 bit, but it works when updating the model but not when run in debug.
(I would show additional code if I knew what to show!)
Connection string from app.config:
<connectionStrings>
<add name="SpatialDatabaseContext" connectionString="metadata=res://*/SpatialDatabase.csdl|res://*/SpatialDatabase.ssdl|res://*/SpatialDatabase.msl;provider=Oracle.DataAccess.Client;provider connection string="DATA SOURCE=ds_name_here;PASSWORD=password_here;PERSIST SECURITY INFO=True;USER ID=user_id_here"" providerName="System.Data.EntityClient" />
</connectionStrings>
[Edit]
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: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
[/Edit]
[Edit2]
The above might be a red herring. I ran it again and didn;t see that error, but I did see this InnerException:
[Oracle.DataAccess.Client.OracleException] = {"ORA-12154: TNS:could not resolve the connect identifier specified"}
[/Edit2]
[Edit 3]
I tried to use the EFOracleProvider instead.
It builds ok, but when I go to generate the entity model I get this:
Microsoft (R) EdmGen version 3.5.0.0
Copyright (C) 2008 Microsoft Corporation. All rights reserved.
error 7001: The provider did not return a ProviderManifestToken string.
Attempt to load Oracle client libraries threw BadImageFormatException. This problem will occur when running in 64 bit mode with the 32 bit Oracle client components installed.
An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)
Generation Complete -- 1 errors, 0 warnings
I have both 32 bit and 64 bit versions of the Oracle client components installed.
How do I choose whether to run 32 bit or 64 bit??
[/Edit3]

Sorry if any of the above were not helpful to you. I just added them because you added SQL Server related things in [Edit]
Anyways, please check the following in SQL Server : http://www.sswug.org/articlesection/default.aspx?TargetID=44331
And in case of Oracle, please refer to the following links if they help..
http://ora-12154.ora-code.com/
http://blogs.msdn.com/b/dataaccesstechnologies/archive/2010/06/30/ora-12154-tns-could-not-resolve-the-connect-identifier-specified-error-while-creating-a-linked-server-to-oracle.aspx
Regards,
Varun Shringarpure

I found a couple of links, thought they would be helpful to you! Hence sharing here.
On referring to this blog post, http://th2tran.blogspot.in/2009/06/underlying-provider-failed-on-open.html
This section I thought of sharing with you from this blog article.
"So IIS is trying to access the database under the credential 'NT AUTHORITY\NETWORK SERVICE' . I looked that the db settings via SQL Server Management Studio and, sure enough, that account is not listed as one of the users allowed to connect. So I added him. And the web app was able to connect successfully."
Try this out!
If you already have taken care of it, then please refer to the following link: MSSQL Error 'The underlying provider failed on Open'
Hope this helps!

In the connection string, for the datasource, make sure to use the full descriptor rather than the entry from TNSNames.ora. For example,
`"data source=(DESCRIPTION= (ADDRESS= (PROTOCOL=TCP) (HOST=**host_name**) (PORT=**1521**)) (CONNECT_DATA= (SERVER=dedicated) (SID=**db_instance**)))"`
instead of
"data source=**my_tns_ds**"

The server was not found or was not accessible.
Means that your connection string points to a server that cannot be found. Most commonly (at least for me) that is due to a wrong Sql Server name, in your case it is likely something similar. Check the
Data Source=(local)
part of the connection string points to a connection you can access with another tool / app
(eg. the app.config of the .edmx file should point to the same place)

For info, there was no fix.
I ended up abandoning the VM I was having the problem on and building another (well someone else built it!)
The problem is now gone.

Related

ASP.NET MVC: moving from SQL Server Express to Azure

I'm sure this has been asked before, but I'm not seeing anything in the similar questions. :(
I've got an ASP.NET MVC application I have developed locally that has been using a SQL Server Express database. In Azure, I recreated the database and taken the connection string it provided and updated the connection string in web.config of my app to use the new database.
When I publish the app to Azure, there doesn't appear to be any issues. However, when I hit a page in the app that accesses the db, it throws an error complaining it can't find the SQL Server Express database. Below is the main snippet from the error:
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: 52 - Unable to locate a Local Database Runtime installation. Verify that SQL Server Express is properly installed and that the Local Database Runtime feature is enabled.)
So it seems like it's ignoring my connection string and still looking for a locally stored SQL Server Express database instead of using the Azure database I specify in the connection string. Any ideas why this might be? My guess is that I have missed something pretty basic (my usual guess when something that seems like it should be simple doesn't work. :) )
Connection strings per below request:
Local:
<add name="FCDbContext" connectionString="data source=(localdb)\MSSQLLocalDB;initial catalog=FormCenterResponder;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
Azure Contection String:
<add name="FCDbContext" connectionString="Server=tcp:***azuredbserver here***,1433;Initial Catalog=***azuredb here***;Persist Security Info=False;User ID=***username here***;Password=***password here***;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" providerName="System.Data.SqlClient" />
And configureservices per another request (it's pretty much defaults):
public void ConfigureServices(IServiceCollection service)
{
services.AddControllersWithViews();
}
Ok, mark this one up to being a asp.net/c# noob. I'll go ahead and post (the embarrassing) answer, though, in case others find themselves in my position.
A co-worker had a look at the code and found an excellent tutorial here. He was able to figure out what I had done wrong.
Basically, I had never registered the database context in Startup.ConfigureServices. I think this is why someone (who has since deleted their question) asked me to post that section of my code. Then that context can be read in by the controller files granting them the info they need to get access to the db.
App is now working as it should.

Can't initialize local SQL Server database with EFCore commandline tools

I've been trying to follow several different tutorials with EFCore and .net core and I've been totally blocked at the point where I try and create a local database.
I've used both the powershell tools and the commandline tools to try and create an initial migration (or do anything, really).
I consistently get the error:
System.InvalidOperationException: An exception has been raised that is likely due to a transient failure. Consider enabling transient error resiliency by adding 'EnableRetryOnFailure()' to the 'UseSqlServer' call.
---> Microsoft.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the login process. (provider: Named Pipes Provider, error: 0 - No process is on the other end of the pipe.)
The database does not currently exist on the system, though local SQL Server appears to be up and running.
Here is the c# code for adding the context:
services.AddDbContextPool<TestDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("TestDb")
)
);
This is the connection string code:
"TestDb": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=TestDb"
I get similar errors whether I run add-migration, dotnet ef migration add, or dotnet ef dbcontext info. (note: with the dotnet calls I am using the -s ..\{webproject}\{webproject}.csproj property
I've also messed with the connection string by adding various combinations of Trusted_Connection=True; MultipleActiveResultSets=True;, and Integrated Security=true.
I've gone into SSMS and ensured the Server authentication is SQL Server and Windows Authentication Mode and that Maximum Connections is set to 0 (unlimited). I've also gone to logins and tried adding the user to pretty much all the server roles.
So, yeah, I'm pretty confused. I've worked with EF for years, though this is my first experience with EFCore and I'm definitely more of a developer than a SQL Admin. This is also my first time trying to use the local db on this particular computer.
Edit: Looking at error.log in AppData\Local\Microsoft\Microsoft SQL Server Local DB\Instances\mssqllocaldb I see this error:
2020-01-28 10:15:03.50 Logon Error: 18456, Severity: 14, State: 38.
2020-01-28 10:15:03.50 Logon Login failed for user 'LAPTOP-NC6HQ4TB\ripli'. Reason: Failed to open the explicitly specified database 'TestDb'. [CLIENT: <named pipe>]
Which is confusing. Of course I can't open the specified database. The entire point is I want to create a DB that doesn't yet exist.
Found the answer. Sorry to everyone who tried to help, as you wouldn't have had enough information to solve it.
In the DbContext I had tried to add some code to the constructor to try and populate some data to the database as part of a test. This caused several problems. If the Database hadn't yet been created it tried to connect to the DB before it had been created, which caused the problems I described.
Furthermore, if I had created the db manually it would try to access the DbSets (which had not yet been created), and then complain that the set name was invalid (which, at this point it was.
This all might have been fine if the DB had been created in advance, but since I was using the DbContext to construct the database, it understandably caused problems.
And all of this headache would have been avoided had I not violated SRP and not tried to (even temporarily) hijack a context constructor to hack in some test data.
The takeaway here? Don't pollute your constructors with unrelated hacks. Bleh.

Connection to Oracle database not working

I am currently working on a project with someone. We are connecting to a oracle Database using the NuGet Package Oracle.ManagedDataAccess.Core.
We are connecting using a connection string that looks like this:
"User Id={this._dbUser};Password={this._dbPassword};Data Source={this._dbServer};"
The Parameters we pass on are correct we checked multiple times.
At first I got a Connection Timed out error which we fixed by adding persist security info=false;Connection Timeout=120; to the connection string.
At first it seemed to be working but then we encountered a new error.
This time it was saying:
Oracle communication: Connection to server could not be established or connection string not parsed
(Might not be 100% accurate because I had to translate it from German to English)
We could not find a solution for this error but we discovered that the error only gets thrown when we run the code on my machine. His is doing totally fine and can connect without any problems.
Could it be that I have some settings set on my machine that would prevent me from accessing the Database?

IIS 8.5 Web.config for named SQL Server instance on alternate port

I recently upgraded to Windows Server 2012 from 2003. It was a big IIS jump from 6 to 8.5. I cannot seem to get a named SQL Server instance on an alternate port to work in my ASP.net 4.0 website.
The connection string I am using is:
<add name="MyConn"
connectionString="Server=192.168.12.5\stage,7839;Database=mydb;uid=myun;pwd=mypw;" />
When the website tries to load in the browser, I get the following error:
[HttpException (0x80004005): 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.)]
We've checked firewall settings to no avail. Is the syntax correct in the above example? I've done numerous searches and found examples of people using
192.168.12.5:7839\stage
or
192.168.12.5\stage;port=7839;
but both of those give syntax errors.
I need some confirmation on the correct syntax for the web.config file. Any help is greatly appreciated, thanks!
Can you go to SQL Server > Configuration Tools > Configuration Manager and see if that instance is really named what you think it is?
You should see something like this:
The entries SQL Server (instacename) on the right hand side show you what instances you have - they should be in state running, and the instance name is in the brackets. If it's MSSQLSERVER, then it's an unnamed default instance - otherwise it's the instance name. Is your instance name correct, as expected - and running?

Azure Cloud Service unable to connect to SQL Database on write operations only

I have developed a web application in lightswitch. There is an HTML lightswitch client that connects to a server (C#) and this server gets the data from an SQL Database.
The application is working correctly in my local machine, the problem comes when I publish the solution to a Cloud Service in Azure. Then, the server connects to the database correctly and can read all the information from it, but when I try to update the database from within my application (insert or update rows) the application freezes and it promts the following error:
Unable to connect to SQL Server database.
Inner exception message:
Unable to connect to SQL Server database.
Inner exception message:
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)
I have checked the connection parameters and all of them are correct, this is the connection string in my web.config:
<add name="My_Data" connectionString="data source=tcp:{MyServer}.database.windows.net,1433;initial catalog={myDatabase};user id={Myuser}#{MyServer};password={MyPassword};Trusted_Connection=False;Encrypt=True;Connection Timeout=30;" providerName="System.Data.SqlClient" />
I have seen other questions with the same issue, but all of them were because the database or the server was not available. I have no problem connecting to the server because I can query my database with no problems.
The error comes when I try to write in my database, either because I click on the save button of a lightswitch screen or because I do it by code in the server:
serverContext.DataWorkspace.My_Data.SaveChanges();
If I comment the previous line, the error is not prompted.
I have also checked the user permissions in the database and this usser is a db_owner, so there should be no problem with that.
Anyone has ever faced a problem like this?
I found the solution!
After a deep research, I discovered that Azure server is adding a connection string to my application (I don't know how nor why). This connection string is inherited from somewhere and it is pointing to a local instance of SQL Express. Obviously, this instance does not exist, so after a timeout the application throws the error shown above.
I don't really know why this is happening nor why only happens when I try to write in my database. The solution I found is to add the following in the connection strings part of my web.config:
<clear />
With this, we delete the inherited connection string. And now, we have to set the connection string of the LocalSqlServer (which will be our connection string, the one that points to our remote SQL Server in Azure):
<add name="LocalSqlServer" connectionString="Data Source={SERVER}.database.windows.net;Initial Catalog={DATABASE};Integrated Security=False;User ID={USER}#{SERVER};Password={PASSWORD};Encrypt=True" />
Now, everything works fine. I hope this can help anyone who faces the same problem than me and I would really like to know why this happened, so if anyone knows it, please tell me :)

Categories

Resources