Azure SQL Database sometimes unreachable from Azure Websites - asp.net

I have a asp.net application deployed to Azure websites connecting to Azure SQL Database. This has been working fine for the last year, but last weekend I have started getting errors connecting to the database giving the following stacktrace.
[Win32Exception (0x80004005): Access is denied]
[SqlException (0x80131904): 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)]
This error comes and goes staying a few hours and then goes away for a few hours. The database is always accessible from my machine.
A few things that I have tried are:
Adding a "allow all" firewall rule (0.0.0.0-255.255.255.255) has no effect
Changing the connection string to use the database owner as credential has no effect.
what does have effect is to change the azure hosting level to something else. This resolves the issue temporarily and the website can access the database for a few hours more.
What could have have happened for this error to start showing up? The application hasn't been changed since August.
EDIT:
Azure support found that there was socket and port exhaustion on the instance. What the root cause for that is, is still unkown.

Craig is correct in that you need to implement SQLAzure Transient Fault Handling. You can find instructions here: https://msdn.microsoft.com/en-us/library/hh680899(v=pandp.50).aspx
From the article
You can instantiate a PolicyRetry object and wrap the calls that you
make to SQL Azure using the ExecuteAction method using the methods
show in the previous topics. However, the block also includes direct
support for working with SQL Azure through the ReliableSqlConnection
class.
The following code snippet shows an example of how to open a reliable
connection to SQL Azure.
using Microsoft.Practices.EnterpriseLibrary.WindowsAzure.TransientFaultHandling;
using Microsoft.Practices.EnterpriseLibrary.WindowsAzure.TransientFaultHandling.AzureStorage;
using Microsoft.Practices.EnterpriseLibrary.WindowsAzure.TransientFaultHandling.SqlAzure;
...
// Get an instance of the RetryManager class.
var retryManager = EnterpriseLibraryContainer.Current.GetInstance<RetryManager>();
// Create a retry policy that uses a default retry strategy from the
// configuration.
var retryPolicy = retryManager.GetDefaultSqlConnectionRetryPolicy();
using (ReliableSqlConnection conn =
new ReliableSqlConnection(connString, retryPolicy))
{
// Attempt to open a connection using the retry policy specified
// when the constructor is invoked.
conn.Open();
// ... execute SQL queries against this connection ...
}
The following code snippet shows an example of how to execute a SQL command with retries.
using Microsoft.Practices.EnterpriseLibrary.WindowsAzure.TransientFaultHandling;
using Microsoft.Practices.EnterpriseLibrary.WindowsAzure.TransientFaultHandling.AzureStorage;
using Microsoft.Practices.EnterpriseLibrary.WindowsAzure.TransientFaultHandling.SqlAzure;
using System.Data;
...
using (ReliableSqlConnection conn = new ReliableSqlConnection(connString, retryPolicy))
{
conn.Open();
IDbCommand selectCommand = conn.CreateCommand();
selectCommand.CommandText =
"UPDATE Application SET [DateUpdated] = getdate()";
// Execute the above query using a retry-aware ExecuteCommand method which
// will automatically retry if the query has failed (or connection was
// dropped).
int recordsAffected = conn.ExecuteCommand(selectCommand, retryPolicy);
}

The answer from Azure support indicated that the connection issues I was experiencing was due to port/socket exhaustion. This was probably caused by another website on the same hosting plan.
Some answers to why the symptoms were removed by changing hosting service level:
Changing the hosting plan helped for a while since this moved the virtual machine and closed all sockets.
Changing the hosting plan from level B to level S helped since azure limits the number of sockets on level B.

Related

Azure login to user db with pyodbc from a Azure webjob

I am trying to login to Azure sql server with pyodbc which logs me in a master db rather than the userdb like 'xyzdb' that i provide in the connection string. The solution to this seems changing to a DSN less based logins that needs configuring the dsn on windows machine.
But i require to run the python script with pyodbc connection from a Azure webjob so configuring dsn is not possible. Hence not able to use the user database as intended. Any solution?
After login to master db i thought to change to user db with "USE xyzdb;" Sql command to which the azure sql server responded 'USE cannot be used to switch between databases' hence xyzdb login cannot be made. I am stuck :).
I made the azure sql server with xyzdb database. Then i tried connection string for newly created server:
pyodbc.connect('Driver={ ODBC Driver 13 for SQL Server};Server=tcp:abc.database.windows.net,1433;Database=xyzdb;
Uid=ur_username;Pwd=ur_password;Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;')
This connection string logged me in masterdb not in xyzdb as intended. And As Sql server are physically maintained in stack in data center interconnection is not everytime feasible unless using something as pool elastic. So 'USE xyzdb;' Sql statement from master DB was providing 'USE cannot be used for switching between databases'.
for 3 days i tried with other methods but it didn't worked,so i posted the question.Then i tried the connection string as:
pyodbc.connect('Driver={ODBC Driver 13 for SQL Server};Server=tcp:abc.database.windows.net,1433;
Uid=ur_username;Pwd=ur_password;Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;Database=xyzdb')
moving the Database field at the end of the string thinking it will first make a connection with server then it will log me in database xyzdb and It logged me in the xyzdb database.It worked the first time itself.
Now if i try with any of the 2 strings above its working as expected. Don't know what was the issue?.Looks like i wasted time of others as well :). we can remove the question i presume, as i can login the userdb. Thanks.

Database is not accessible on server but working well on localhost

I have developed my first website in ASP.NET with C#. It's a small website which uses Microsoft SQL server 2008 for database and I've deployed it on a free hosting site www.somee.com. It's database is working well on my computer but when I try to access the database on server it gives following 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: SQL Network Interfaces,
error: 26 - Error Locating Server/Instance Specified)].
I have updated connection string of the database in web.config and I've used getConString() method for accessing connection string like this:
public string getConString()
{
return System.Configuration.ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
}
What can I do to solve this problem.
Wbsite url is: www.easyways.somee.com
Thanks all of you for your support. I got the solution for my problem. Actually I did something wrong either in creating a database or in using connection string.
Now I recreated a blank database and then I executed the SQL script that I created for my database by navigating to "User -> Managed products -> MS SQL -> Databases -> (Database name) -> New SQL query from file". And also updated the new connection string in web.config file.
This is the connection string I used now:
"workstation id=dataeasyways.mssql.somee.com;packet size=4096;user id=easyways_db;pwd=********;data source=dataeasyways.mssql.somee.com;persist security info=False;initial catalog=dataeasyways"
Your hosting provider provides the connection information for you (in the case of your hosting provider you can see their Help Page here, which shows you how to connect to their DB.
Basically it boils down to logging into their control panel.
In "User menu" navigate to "User -> Managed products -> MS SQL -> Databases -> (Database name)".
Also remember that since this is a remote database there is a small chance that its firwalled from the outside world and only local webservers can access the database.

The transaction manager has disabled its support for remote/network transactions

I'm using SQL Server and ASP.NET. I have the following function:
Using js = daoFactory.CreateJoinScope()
Using tran = New Transactions.TransactionScope()
'...
tran.Complete()
End Using
End Using
However, the following exception is thrown:
The transaction manager has disabled its support for remote/network transactions.
Description of JoinScope:
Public Class JoinScope
Implements IJoinScope
Implements IDisposable
'...
End Class
I have worked this way in another application with the same environment without a problem, but here I have this problem. What could I do to fix the issue?
Make sure that the "Distributed Transaction Coordinator" Service is
running on both database and client.
Also make sure you check "Network DTC Access", "Allow Remote Client",
"Allow Inbound/Outbound" and "Enable TIP".
To enable Network DTC Access for MS DTC transactions
Open the Component Services snap-in.
To open Component Services, click Start. In the search box, type dcomcnfg, and then press ENTER.
Expand the console tree to locate the DTC (for example, Local DTC) for which you want to enable Network MS DTC Access.
On the Action menu, click Properties.
Click the Security tab and make the following changes:
In Security Settings, select the Network DTC Access check box.
In Transaction Manager Communication, select the Allow Inbound and Allow Outbound check boxes.
I had a store procedure that call another store Procedure in "linked server".when I execute it in ssms it was ok,but when I call it in application(By Entity Framework),I got this error.
This article helped me and I used this script:
EXEC sp_serveroption #server = 'LinkedServer IP or Name',#optname = 'remote proc transaction promotion', #optvalue = 'false' ;
for more detail look at this:
Linked server : The partner transaction manager has disabled its support for remote/network transactions
In my scenario, the exception was being thrown because I was trying to create a new connection instance within a TransactionScope on an already existing connection:
Example:
void someFunction()
{
using (var db = new DBContext(GetConnectionString()))
{
using (var transaction = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted }))
{
someOtherFunction(); // This function opens a new connection within this transaction, causing the exception.
}
}
}
void someOtherFunction()
{
using (var db = new DBContext(GetConnectionString()))
{
db.Whatever // <- Exception.
}
}
I was getting this issue intermittently, I had followed the instructions here and very similar ones elsewhere. All was configured correctly.
This page: http://sysadminwebsite.wordpress.com/2012/05/29/9/ helped me find the problem.
Basically I had duplicate CID's for the MSDTC across both servers. HKEY_CLASSES_ROOT\CID
See: http://msdn.microsoft.com/en-us/library/aa561924.aspx section Ensure that MSDTC is assigned a unique CID value
I am working with virtual servers and our server team likes to use the same image for every server. It's a simple fix and we didn't need a restart. But the DTC service did need setting to Automatic startup and did need to be started after the re-install.
Comment from answer: "make sure you use the same open connection for all the database calls inside the transaction. – Magnus"
Our users are stored in a separate db from the data I was working with in the transactions. Opening the db connection to get the user was causing this error for me. Moving the other db connection and user lookup outside of the transaction scope fixed the error.
I post the below solution here because after some searching this is where I landed, so other may too. I was trying to use EF 6 to call a stored procedure, but had a similar error because the stored procedure had a linked server being utilized.
The operation could not be performed because OLE DB provider _ for linked server _ was unable to begin a distributed transaction
The partner transaction manager has disabled its support for remote/network transactions*
Jumping over to SQL Client did fix my issue, which also confirmed for me that it was an EF thing.
EF model generated method based attempt:
db.SomeStoredProcedure();
ExecuteSqlCommand based attempt:
db.Database.ExecuteSqlCommand("exec [SomeDB].[dbo].[SomeStoredProcedure]");
With:
var connectionString = db.Database.Connection.ConnectionString;
var connection = new System.Data.SqlClient.SqlConnection(connectionString);
var cmd = connection.CreateCommand();
cmd.CommandText = "exec [SomeDB].[dbo].[SomeStoredProcedure]";
connection.Open();
var result = cmd.ExecuteNonQuery();
That code can be shortened, but I think that version is slightly more convenient for debugging and stepping through.
I don't believe that Sql Client is necessarily a preferred choice, but I felt this was at least worth sharing if anyone else having similar problems gets landed here by google.
The above Code is C#, but the concept of trying to switch over to Sql Client still applies. At the very least it will be diagnostic to attempt to do so.
I was having this issue with a linked server in SSMS while trying to create a stored procedure.
On the linked server, I changed the server option "Enable Promotion on Distributed Transaction" to False.
Screenshot of Server Options
If you could not find Local DTC in the component services try to run this PowerShell script first:
$DTCSettings = #(
"NetworkDtcAccess", # Network DTC Access
"NetworkDtcAccessClients", # Allow Remote Clients ( Client and Administration)
"NetworkDtcAccessAdmin", # Allow Remote Administration ( Client and Administration)
"NetworkDtcAccessTransactions", # (Transaction Manager Communication )
"NetworkDtcAccessInbound", # Allow Inbound (Transaction Manager Communication )
"NetworkDtcAccessOutbound" , # Allow Outbound (Transaction Manager Communication )
"XaTransactions", # Enable XA Transactions
"LuTransactions" # Enable SNA LU 6.2 Transactions
)
foreach($setting in $DTCSettings)
{
Set-ItemProperty -Path HKLM:\Software\Microsoft\MSDTC\Security -Name $setting -Value 1
}
Restart-Service msdtc
And it appears!
Source: The partner transaction manager has disabled its support for remote/network transactions
In case others have the same issue:
I had a similar error happening. turned out I was wrapping several SQL statements in a transactions, where one of them executed on a linked server (Merge statement in an EXEC(...) AT Server statement). I resolved the issue by opening a separate connection to the linked server, encapsulating that statement in a try...catch then abort the transaction on the original connection in case the catch is tripped.
I had the same error message. For me changing pooling=False to ;pooling=true;Max Pool Size=200 in the connection string fixed the problem.

SQL Server Connection Issue

We recently launched a new web site... there are roughly ~150 users active during peak hours. During peak hours, we are experiencing an issue every few minutes, the exception text is listed below.
System.Web.HttpUnhandledException:
Exception of type 'System.Web.HttpUnhandledException' was thrown.
---> System.Data.SqlClient.SqlException: The client was unable to establish a connection because of an error during connection initialization process before login.
Possible causes include the following:
the client tried to connect to an unsupported version of SQL Server;
the server was too busy to accept new connections;
or there was a resource limitation (insufficient memory or maximum allowed connections) on the server. (provider: Named Pipes Provider, error: 0 - No process is on the other end of the pipe.)
Our data access layer calls various DataTableAdapters using the following syntax.
EDIT
Yes, da is the name assigned to the DataTableAdapter. There is no connection.Open() because the DataTableAdapter takes care of all that, right?
using(TheDataLayer.some.strongly.typedNameTableAdapters.suchAndSuchTableAdapter da = new TheDataLayer.some.strongly.typedNameTableAdapters.suchAndSuchTableAdapter())
{
StronglyTyped.DataTable dt = new StronglyTyped.DataTable();
da.FillByVariousArguments(dt, ..., ...);
//da.Dispose();
return something;
}
The connection string looks something like:
<add name="MyConnectionString"
connectionString="Data Source=myDBServerName;Initial Catalog=MyDB;User ID=MyUserName;Password=MyPassword"
providerName="System.Data.SqlClient" />
I'm trying to rule the problem being in Code. Is there anything "simple" that can be done to minimize this issue?
Thanks.
Have you tried "Connection Pooling" directly in connection string settings?
Example:
connectionString="....;Pooling=true;Min Pool Size=1;Max Pool Size=10;..."
You can read more info here: http://msdn.microsoft.com/en-us/library/8xx3tyca%28v=vs.71%29.aspx
Without seeing the code that actually opens and uses the connection, it's hard to say where the problem is.
Please update your question with what happens when you create that DataAdapter (I'm guessing that's what da means).
Also, if you're using the using statement, you shouldn't be disposing of the thing you created the using statement for.
We had similar issue which only happenes in our production environment and it was particularly associated with load. During busy time of day we would recieve several of the above mentioned exception.
We gone through a massive investigation around why this exception occurs and did a lot of changes to fix the issue. The defacto change we did which aleviated the problem was connection pool setting by setting min pool size to 1 and max pool size to 10. (It can vary based on your situation)
This issue will be more prevalent when you have several i.e. 1000's of Customer DB and use default connection string (i.e. database=DBName;server=ServerName). We were not explicitly setting min/max pool size hence it took default settings which set Min pool size to 0 and max pool size to 100.
Again, I dont have concrete proof but the theory is that during busy time of the day based on load it made several connection to DB server and DB server was bombarded with a lot of connection request at single point to several databases. Either Application server or DB server did have bandwidth to handle that many connection in a short period of time. Also, it was happening with server with most databases. Though we did not see a lot of connection at a time but Application server was not able to make connection to databases for a short duration when it had surge of requests going in.
After we set min pool size we aliveated this problem as there is atleast one connection to each database which is available all the time and if there is blast of request which required to make connection to several databases we already had atleast one connection to the database available before we request a new one.
Maybe unrelated to the actual problem you were facing, but this error is also thrown if you are trying to connect without specifying the correct port along with the database server name.

What does error ORA-12571 (TNS:packet writer failure) mean in a Web Service?

Background: I'm calling a Web Service written in ASP.NET that queries an Oracle database. I know the Web Service itself works, because I've used it before other applications. So I have a web application in Visual Studio that I've been switching back and forth to point from a 'DEV' web service to a production configured version of the same web service for testing. Pointing to the 'DEV' configured web service is no problem, but calling the production version I always get an exception calling the service:
SoapException was unhandled by user code
Server was unable to process request. ---> could not execute query
[ SELECT this_.FIELD1 as FIELD1_18_0_, this_.FIELD2 as FIELD12_18_0_ FROM ABC.TABLE_A this_ WHERE this_.FIELD1 like :p0 ORDER BY this_.FIELD1 asc ]
Positional parameters: #0>00073%
[SQL: SELECT this_.FIELD1 as FIELD1_18_0_, this_.FIELD2 as FIELD12_18_0_ FROM ABC.TABLE_A this_ WHERE this_.FIELD1 like :p0 ORDER BY this_.FIELD1] ---> ORA-12571: TNS:packet writer failure
I ran the SQL queries against the appropriate database (cut and pasted straight out of the exception message) and the query came back with the expected data. I've tried updating and re-adding the Web Service reference both as a "Service Reference" (.NET 3.0+ way) and as a "Web Reference" (Older .NET way), and both give the same error.
Question: So, what does a "ORA-12571: TNS:packet writer failure" error mean in the context of a Web Service? Looking up the Oracle Error number gives some very vague possible causes such as "loose cable connection" or "IP address conflict". I'm fairly certain it's neither of these, since a different application is currently successfully using that Web Service. Possibly some kind of configuration error, or maybe something more subtle? Anyone else seen this vexing Oracle error number being attributed to something web-service related?
Your call is going from the ws client to the ws server to the oracle database.
Your error is an ORA error, which is generated by the database. So your problem is probably between the ws server and the database.
When you ran "the SQL queries against the appropriate database", did you do it from the web server? If not could you try that. Make sure that you are using the same connection configuration.
EDIT
As per the comment below, the real problem was a driver mismatch.
I would suggest re-examining your assumptions more carefully, as this is clearly an error in the web-service dialogue with the db and should be completely independent of the w/s caller.
If the w/s call is generating this specific exception, it should be doing so for all other invocations, so your 'other application' that's using the web service successfully is simply not executing the same code or there are outside factors at play.
Either way, it's unrelated to how the service is registered or invoked.

Resources