TransactionScope on Azure App Services with Sql Azure - c#

So I have the following trivial code in a WebAPI controller that is published to an Azure App Service website.
using (var tx = new TransactionScope())
{
var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["OrganizationManagement"].ConnectionString);
connection.Open();
return Enumerable.Empty<TimeSessionDTO>();
}
100% of the time this is giving me a transport error exception on the Open call:
A transport-level error has occurred when receiving results from the
server. (provider: TCP Provider, error: 0 - An existing connection was
forcibly closed by the remote host.)
I have tried using ReliablSqlConnection from the Transient Fault Handling EL block using an exponential retry policy, and I just end up with a transaction timeout with that.
If I remove the surrounding TransactionScope, it works and does not throw an exception.
If I run the same code on my local machine with the connection string still pointing to the SQL Azure database, it works fine with the TransactionScope.
What could be going on that I cannot open a database connection inside of a transaction, in an Azure website?
Update: I should also note that using an Entity Framework DbContext inside of a TransactionScope was working fine. It's just choking on plain ADO.NET for some reason.
FYI I also tried it on a new MVC application on Azure, with the same result. I just don't get it :)

Wow, so the problem seems to have been with the connection string. When I first deployed the database I let the database project build the connection string from the server/database/user info, which I later added to the Web.config file in the WebAPI project. Then when I deployed the WebAPI project I guess it saved that connection string in the publish profile.
It turns out that connection string used a little different format and different options than what is supplied when you view the connection strings in the Azure portal. I had already changed it in the Web.config file, but it seems that what is in the publish profile overwrites what is in Web.config, so the change never took effect on the server.
I guess that explains why it worked when I ran it locally, but I have no idea why it only failed when it was in a transaction.

Related

Fatal NServiceBus exception when starting endpoint, cannot open database

We just made some changes to our project and deployed it. We have 7 endpoint databases in our SQL Server database for NServiceBus. We recently added 2 more. One of the two services using one of the two new endpoints fails to start. When looking at our log file we see the following error:
FATAL NServiceBus.GenericHost [(null)] - Exception when starting endpoint.
System.Data.SqlClient.SqlException (0x80131904): Cannot open database "A_NSBEP_WebEventProcessor" requested by the login. The login failed. Login failed for user 'xxxx'
The connection string is
'connection.connection_string'='Data Source=localhost\DevSQLServer;Initial Catalog=A_NSBEP_WebEventProcessor;Integrated Security=true;Enlist=true'
All of the connection strings are configured in OctopusDeploy. They are all identical except obviously for the database name. All of the other services start and login to their respective endpoint with no problem. I even went through the process of creating a .udl file, connecting to the database and using that slightly different connection string. Still without success.
Any thoughts?

Azure Hybrid Connection string

I have successfully created an Hybrid Connection between Azure and an on-premise resource. I see "Connected" in both the Azure Portal and Hybrid Connection Manager.
When I run my .NET code local in Visual Studio with the connection string "AppServer://MyPC:5162/AzureOeApi" everything runs fine but when I run it in Azure, I get a connection error (it can't see the on-prem end-point).
Do I need to change my connection string when running in Azure to force it to go through the Hybrid Connection or will it be handled automatically?
No need to change connection string.
We had similar issue - connection was "Connected", but no requests whould go through. You need to use fully qualified domain name in configuration of hybrid connection.
Please also read this question - similar question
I've been struggling with this problem for a whole day and finally I had a breakthrough: in my original connection string I was referring to [DB_SERVER]\[INSTANCE], having correctly configured the DB instance to listen to a given TCP port [PORT].
With this setup the Hybrid Connection was 'Connected' but I was getting the exception:
ExceptionMessage: The underlying provider failed on Open. -InnerExceptionMessage: 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)
It turns out that the connection string needs do explicitly refer to the port number (instead of the DB instance) using the syntax [DB_SERVER],[PORT] (mind the comma!).
Unfortunately Microsoft does not document this subtle detail....

Restore NHibernate after lost Oracle database connection

I have a long running application that uses NHibernate.ISessionFactory to connect to an Oracle database.
Occasionally the database goes offline (e.g. for weekend maintenance), but even once the database is back online, subsequent queries fail with the following exception (inner exceptions also shown):
NHibernate.Exceptions.GenericADOException: could not execute query
[ select .....]
>> Oracle.ManagedDataAccess.Client.OracleException: ORA-03135: Connection lost contact
>> OracleInternal.Network.NetworkException: ORA-03135: Connection lost contact
>> System.Net.Sockets.SocketException: An established connection
was aborted by the software in your host machine
Restarting the application restores the functionality, but I would like the application to be able to automatically cope without a restart, by "resetting" the connection.
I have tried the following with my ISessionFactory when I hit this exception:
sf.EvictQueries();
sf.Close();
sf = null;
sf = <create new session factory>
but see the same exception after recreating the ISessionFactory. I assume this is because NHibernate is caching the underlying broken connection in some kind of connection pool?
How can I persuade NHibernate to create a genuinely new connection (or even just reset all state completely), and hence allow my application to fix the connection issue itself without an application restart?
EDIT:
Following A_J's answer, note that I am already calling using (var session = _sessionFactory.OpenSession()) for each database request.
I suspect you are opening ISession (call to ISessionFactory.OpenSession()) at startup and closing it at application end. This is wrong approach for any long running application.
You should manage connection at lower level of time. In web application, this is generally handled per request. In your case, you should find what that should be. If yours is windows service that does some activity after specified time then Timer_Tick event is good place.
I cannot suggest what that location could be in your application; you need to find out on your own.
Edit 1
Looking at your edit and comment, I do not think this has anything to do with NHibernate. May be that the connection pool is returning a disconnected/stale connection to NHibernate.
Refer this and this accepted answer.

Promote Method returned an invalid Value for the Distributed transaction error

I have just deployed my ASP.NET web API application to Azure app services. I get this error when saving to db:
Promote Method returned an invalid Value for the Distributed
transaction
This is the way I create and open the connection:
var connection = new SqlConnection(connstr);
connection.Open();
but if I comment out the connection.Open();, I no longer get that error. Can anyone explain why?
That error means that your transactions are being promoted to a distributed transaction. As far as i know, DCOM is not supported in the Azure WebApp (may be wrong, but it looks like the issue is still here).
Do you open the multiple sqlconnections in the scope?

The underlying provider failed on Open - EF 6.1, MSSQL 2008 r2

when Our WinApp is idle for while around 8-10 minutes ,and try to do something like get list of customers, we got this error "The underlying provider failed on Open"
i use EF6.1 & MSSQL 2008 r2 Here Is my connection string :
<add
name="MISSystemEntities"
connectionString="metadata=res://*/DB_Model.csdl|res://*/DB_Model.ssdl|res://*/DB_Model.msl;
provider=System.Data.SqlClient;
provider connection string="Data Source=10.10.0.3\r2;Initial Catalog=MISSystem;User ID=user;Password=pass;MultipleActiveResultSets=True""
providerName="System.Data.EntityClient"
/>
Sql Option Auto Close Is Off
Distributed Transaction Coordinator Is Active for Clients "actually We don't use it"
have ping to server without any time aout at the same time that error occurs
test with domain administrator rights and still have problem
also We Test Connection time out and query execute time out with random values:(
Its seems related the connection issue.
Seems like a connection issue. You can use the Data link properties to find if the connection is fine. Do the following,
Create a blank notepad and rename it to "X.UDL" Double click open it, under connections tab choose the server name/enter the name use the correct credentials and DB OK to save it.
Now open the file in Notepad and check, compare the connection string properties with this..
Refer link:- Entity Framework The underlying provider failed on Open
The underlying provider failed on open entity framework
Please read the link
Here is same issue explain to resolve by Microsoft team member.
http://blogs.msdn.com/b/dataaccesstechnologies/archive/2012/08/09/error-quot-the-underlying-provider-failed-on-open-quot-in-entity-framework-application.aspx
my problem (issue) was SQL server Connection pooling :D
the pooling store the last request time and when u idle for while around 5-10 min and then when it receive request it'll answer the request ( !??! ) but after that the pooling terminate your connection and your next request throw the exception :(
for now i set timer to each 30s send a request to DB !
i was using entity framework 6 with wcf web service with "integrated security=true" in the wcf web.config. the error message was similar. what was happening, iis was using the application pool credentials to connect to the database. once i specified a user account in the connection string, it worked like a charm...
hope this helps.

Categories