SQL Connection Errors in Microsoft Azure - c#

We have entity framework implemented in our Web API 2.0 code. To call database entities, we are using store procedure calls. Our entire application is hosted in Microsoft Azure cloud. Here are the two exception which we are facing.
Message : An error occurred while executing the command definition. See the inner exception for details.
InnerException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. This failure occured while attempting to connect to the Principle server.
One more exception we are facing is like:
Message : The underlying provider failed on Open.
InnerException: The connection was not closed. The connection's current state is connecting.
Note: Code is in C# Web API 2.0. We are using Entity Framework to call Store Procedure. Database is in SQL Server 2012. In web.config, the connection string looks like below:
<add name="*****Entities" connectionString="metadata=res://*/Models.Database.*****.csdl|res://*/Models.Database.*****.ssdl|res://*/Models.Database.*****.msl;provider=System.Data.SqlClient;provider connection string="data source=*****;Failover Partner=*****;initial catalog=*****;user id=*****;password=********;MultipleActiveResultSets=True;Pooling=false;Connection Lifetime=2;App=EntityFramework"" providerName="System.Data.EntityClient" />
Also, this errors are not continuous, we guess this might be happening either network issues or while heavy traffic. But we are still not having any firm cause about this.
Please guide us with a solution for the same.

This looks like Transient Fault error to me.
You should use EF6 (or later) and setup the Execution Strategies.

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.

EntityException: The underlying provider failed on Open + inner exceptions

I apologize in beforehand because I see that a lot of people have already answered this question but still I cannot find the answer I am looking for.
In my solution I got 5 projects where 2 are C# libraries (the Core layer and the Data layer). The other 3 are using the Core layer to connect to the data layer and these three are a web-API project, a test winform project and a MVC project. I am currently trying out the winform project and that is where the error occurs. The API project works fine when connecting to database.
As the title suggest I have gotten this common exception in the winform project
System.Data.DataException: 'An exception occurred while initializing
the database. See the InnerException for details.'
EntityException: The underlying provider failed on Open.
with the following inner exceptions
SqlException: Connection Timeout Expired. The timeout period elapsed
while attempting to consume the pre-login handshake acknowledgement.
This could be because the pre-login handshake failed or the server was
unable to respond back in time. The duration spent while attempting
to connect to this server was - [Pre-Login] initialization=38878;
handshake=35;
Win32Exception: The wait operation times out
The errors occurs in my Datacontext on Database.Initialize(true);:
public class DataContext : DbContext
{
public DataContext() : base("HololensRegistreringsskyltar")
{
Database.SetInitializer(new DataContextInitializer<DataContext>());
Database.Initialize(true);
}
}
I am also using generic repository pattern with Unit Of Work if that matters (and I am new to it).
Btw there is only a connection string in the API projects web.config, maybe there should be in the other two "outer" layers too?
Can anyone tell me how to solve this issue and making it work for all 3 "outer" layers?
Following cases can cause this exception:
An instance of the SQL Server Database Engine is not running.
The SQL Server Browser service is not running.
The TCP/IP is disabled.
The server name was typed incorrectly.
There are network problems.
The TCP/IP port for the Database Engine instance is blocked by a firewall.
The client and server are not configured to use the same network protocol.

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 :)

"The underlying provider failed on Open" [closed]

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.

Categories

Resources