WCF hosted on IIS (uses MSMQ) cannot connect to SQL server - sql-server

I'm moving existing test environment (hosted on Azure) into new BizSpark Azure subscription.
In old setup, I had API, WCF and SQL Server hosted on same VM. The new configuration is:
API and WCF on VM1 (subscription 1)SQL Server on VM2 (subscription 2)
API works 100%, everything is good.
WCF cannot connect to the database (hosted on VM2).
The exception is:
System.Data.Entity.Core.EntityException: The underlying provider failed on Open. ---> System.Transactions.TransactionManagerCommunicationException: Communication with the underlying transaction manager has failed. ---> System.Runtime.InteropServices.COMException: The MSDTC transaction manager was unable to push the transaction to the destination transaction manager due to communication problems. Possible causes are: a firewall is present and it doesn't have an exception for the MSDTC process, the two machines cannot find each other by their NetBIOS names, or the support for network transactions is not enabled for one of the two transaction managers. (Exception from HRESULT: 0x8004D02A)
at System.Transactions.Oletx.ITransactionShim.Export(UInt32 whereaboutsSize, Byte[] whereabouts, Int32& cookieIndex, UInt32& cookieSize, CoTaskMemHandle& cookieBuffer)
at System.Transactions.TransactionInterop.GetExportCookie(Transaction transaction, Byte[] whereabouts)
--- End of inner exception stack trace ---
at System.Transactions.TransactionInterop.GetExportCookie(Transaction transaction, Byte[] whereabouts)
at System.Data.SqlClient.SqlInternalConnection.GetTransactionCookie(Transaction transaction, Byte[] whereAbouts)
at System.Data.SqlClient.SqlInternalConnection.EnlistNonNull(Transaction tx)
at System.Data.SqlClient.SqlInternalConnection.Enlist(Transaction tx)
at System.Data.ProviderBase.DbConnectionInternal.ActivateConnection(Transaction transaction)
at System.Data.ProviderBase.DbConnectionPool.PrepareConnection(DbConnection owningObject, DbConnectionInternal obj, Transaction transaction)
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.Open()
at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connection, DbInterceptionContext interceptionContext)
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.Core.EntityClient.EntityConnection.Open()
--- End of inner exception stack trace ---
at System.Data.Entity.Core.EntityClient.EntityConnection.Open()
at System.Data.Entity.Core.Objects.ObjectContext.EnsureConnection(Boolean shouldMonitorTransactions)
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__5()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)
at OCS.Web.DocumentGeneration.Ticketing.TicketGenerators.TangibleTicketGenerator.GenerateDocuments(GenerateDocumentsRequest generateDocumentsRequest) in c:\Projects\OCSSvrBase\OCS.Web.DocumentGeneration.Ticketing\TicketGenerators\TangibleTicketGenerator.cs:line 103
at OCS.Web.DocumentGeneration.Ticketing.TicketGenerator.GenerateDocuments(GenerateDocumentsRequest generateDocumentsRequest) in c:\Projects\OCSSvrBase\OCS.Web.DocumentGeneration.Ticketing\TicketGenerator.cs:line 111
I've spent more than a week to resolve this. I've been trying:
to setup Firewall and MSDTC on a way that I found on a few different posts
to create exactly the same settings as I have on LIVE (LIVE configuration is the same, with one difference, both VMs are under the same Azure subscription)
Any idea where I need to look at? My guess is that I'm missing something around MSMQ settings. This is just a guess, based on a fact that my API works perfectly fine (hosted on same VM1).
Thanks in advance!

Related

Microsoft.Data.SqlClient CheckPoolBlockingPeriod(System.Exception) connecting to Azure Sql Database

I have a client application that connects to Azure SQL Database using AD Interactive login. It was working fine until last Friday - running the app would pop up a browser prompt for login, selecting the account would grant access appropriately. It was working fine for quite a while. Then something changed late last week and the app now throws an error when trying to connect to the database. No system patches or updates were applied to my local machine where the app is running during that time period. I confirmed that the last update applied was 4/15/2022 per Windows system settings. Seems CheckPoolBlockingPeriod is now broken? Here is the stack trace:
at Microsoft.Data.ProviderBase.DbConnectionPool.CheckPoolBlockingPeriod(Exception e)
at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) at Microsoft.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
at Microsoft.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) at Microsoft.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions)
at Microsoft.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry, SqlConnectionOverrides overrides)
at Microsoft.Data.SqlClient.SqlConnection.Open(SqlConnectionOverrides overrides)
at Microsoft.Data.SqlClient.SqlConnection.Open()
at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, String srcTable)
at CsharpSqlServer.Program.Main(String[] args) in C:\Users\james.a.barnes\source\repos\dbTest\dbTest\Program.cs:line 65
Can anyone provide any insight into possible causes and workarounds? Again, the code has been running fine for a couple of months and the database connection code has not changed, so something else did. Thanks
If timeout occurs while connecting to Azure SQL Database where connection pooling is enabled, the above exception will be thrown and the login attempt fails for the next few seconds (i.e., "blocking period").
Usually, the above exception will be recovered within a few seconds.
If not, you can resolve the exception by adding ;Connection Timeout=60 to your connection string.
You can also increase the timeout seconds by replacing 60.
You can go through the below SO thread for more information:
c# - SQL Exception: Login failed for user - Stack Overflow

Error 'Could not open a connection to SQL Server' while upgrading database with codefluent pivot runner

We use the pivot runner to update our databases. Since a year we regularly receive error message below. The database server is available, and is hardly used by other processes. After restarting, the same message usually reappears several times, but not always with the same action. As soon as we have managed to update the first database, updating the other (40+) databases also runs smoothly.
Any idea what could be the cause of this?
System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The ser
ver 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: N
amed Pipes Provider, error: 40 - Could not open a connection to SQL Server) ---> System.ComponentModel.Win32Exception (0x80004005): Access is denied
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential
, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, Session
Data reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling, SqlAuthenticationProviderManager sqlAuthProviderMa
nager)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbC
onnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOpti
ons userOptions)
at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOpti
ons, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskComple
tionSource`1 retry, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource
`1 retry, DbConnectionOptions userOptions)
at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.Open()
at CodeFluent.Runtime.Database.Management.Database.GetSchema(String collectionName, String[] restrictionValues)
at CodeFluent.Runtime.Database.Management.SqlServer.Key.Construct(DataRow row)
at CodeFluent.Runtime.Database.Management.Key..ctor(Table table, DataRow row)
at CodeFluent.Runtime.Database.Management.SqlServer.Table.NewKey(DataRow row)
at CodeFluent.Runtime.Database.Management.SqlServer.Table.GetKeys()
at CodeFluent.Runtime.Database.Management.Table.get_Keys()
at CodeFluent.Runtime.Database.Management.Database.ResolveReferencingKeys(Boolean refresh)
at CodeFluent.Runtime.Database.Management.Table.get_ReferencingForeignKeys()
at CodeFluent.Runtime.Database.Management.SqlServer.PivotRunner.<GetConstraintReferencingKeys>d__6.MoveNext()
at CodeFluent.Runtime.Database.Management.SqlServer.PivotRunner.DropConstraint(String tableSchema, String tableName, String constraintName, DistinctDictio
nary`1 constraints)
at CodeFluent.Runtime.Database.Management.SqlServer.PivotRunner.DropConstraint(String tableSchema, String tableName, String constraintName)
at CodeFluent.Runtime.Database.Management.SqlServer.PivotRunner.UpdateColumn(PivotRunnerColumn column, Column existingColumn)
at CodeFluent.Runtime.Database.Management.SqlServer.PivotRunner.UpdateTable(PivotRunnerTable table, Table existingTable)
at CodeFluent.Runtime.Database.Management.SqlServer.PivotRunner.Run()
Difficult to say without the model and the databases. However if it used to work (so assuming the connection string is correct, SQL protocol still enabled, same machine and no change of permissions on the DB for the user) and if the error is not always on the same update step, it may be related to a previous timeout on some DB action, or a previous action not yet finished : for instance a previous index added not yet fully populated or reindexed. It can happen on growing database.
Another reason may be a job task running, like a backup.
Before launching the PivotRunner tool, ensure with Management Studio there is no other running/blocking transactions in progress or not too many opened connections to this DB from previous run/tests (sp_who)
My 2 cents.

How to fix System.Data.SqlClient.SqlException : "Login failed for user "xx\xxxx$""

I ran a web app on IIS and I got a
System.Data.SqlClient.SqlException: "Login failed for user'domain\account$'".
This is a exception when the function DbMigrator.Update() is called
private readonly DbMigrationsConfiguration<MyContext> _config;
public ContextInitializer(string connectionString)
{
_config = new Configuration()
{
TargetDatabase = new DbConnectionInfo(connectionString, "System.Data.SqlClient")
};
}
...
public void InitializeDatabase(MgmtStudioContext context)
{
var migrator = new DbMigrator(_config);
migrator.Update();
}
And here is the stack trace:
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)\r\n
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)\r\n
at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)\r\n
at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)\r\n
at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)\r\n
at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)\r\n
at System.Data.SqlClient.SqlConnection.Open()\r\n
at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)\r\n
at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connection, DbInterceptionContext interceptionContext)\r\n
at System.Data.Entity.SqlServer.SqlProviderServices.<>c__DisplayClass33.<UsingConnection>b__32()\r\n
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()\r\n
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)\r\n
at System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action`1 act)\r\n
at System.Data.Entity.SqlServer.SqlProviderServices.CreateDatabaseFromScript(Nullable`1 commandTimeout, DbConnection sqlConnection, String createDatabaseScript)\r\n
at System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(DbConnection connection, Nullable`1 commandTimeout, StoreItemCollection storeItemCollection)\r\n
at System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(DbConnection connection)\r\n
at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)\r\n
at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)\r\n at
Here is my connection string:
Data Source=(local);Initial Catalog=myTable; Integrated Security=True;
The code works fine in other machine, but in my computer it doesn't work and I can't find out the root cause.
According to the error message, the account 'domain\account$' does not have access to the myTable database.
I suggest you could firstly use the SQL server management system's security to check he account 'domain\account$' does not have access to the (local) server's myTable database.
More details, you could refer to this answer.
Update:
As far as I know, if you want to access SQL Server Using Windows Integrated Security. You should firstly make sure your IIS server and the sql server is inside the same intranet and use the same domain.
Then I suggest you could make sure you have set the right application pool identity account which has the permission to access the sql database.
1.You should the domain account "domain\account" in sql server to make sure it has the read and write permission
2.On IIS, open Application Pool settings.For Identity option, choose "Custom Account". Enter your username domain\account) and password.
Then it will work well.
Please, check the iispool user has permissions to log in to database. You can do this using the Microsoft Sql Server Management Studio.
I usually forget it! I Hope its helps you! Greetings.

The wait operation timed out

I am relatively new to MVC code first application development and I was trying to host an MVC code first application in a VPS. when tried to browse the website after publishing the application I was getting a wait operation timed out error. I tried to do a bit of research and found out enabling TCP/IP on SQL
Configuration manager helped some but I had no luck. Added below is the stack trace, anyone know whats the issue please ?
[Win32Exception (0x80004005): The wait operation timed out]
[SqlException (0x80131904): 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=4223; handshake=2965; ]
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) +356
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +117
System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) +267
System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +318
System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry) +211
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +393
System.Data.SqlClient.SqlConnection.Open() +122
System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch(TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed) +104
System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connection, DbInterceptionContext interceptionContext) +509
System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection) +335
System.Data.Entity.SqlServer.<>c__DisplayClass1.<Execute>b__0() +15
System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func`1 operation) +238
System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements, DbTransaction existingTransaction) +271
System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, VersionedModel targetModel, IEnumerable`1 operations, IEnumerable`1 systemOperations, Boolean downgrading, Boolean auto) +1232
System.Data.Entity.Migrations.DbMigrator.ApplyMigration(DbMigration migration, DbMigration lastMigration) +524
System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId) +193
System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration) +609
System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase) +613
System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration) +116
System.Data.Entity.MigrateDatabaseToLatestVersion`2.InitializeDatabase(TContext context) +156
System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action) +72
System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization() +483
System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input) +177
System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action) +274
System.Data.Entity.Internal.InternalContext.ForceOSpaceLoadingForKnownEntityTypes() +63
System.Data.Entity.DbContext.System.Data.Entity.Infrastructure.IObjectContextAdapter.get_ObjectContext() +31
OfficeTrack.DAL.Context.MasterContext..ctor() +47
OfficeTrack.Web.MvcApplication.Application_Start() +206
[HttpException (0x80004005): 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=4223; handshake=2965; ]
System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) +544
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +186
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +172
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +402
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +343
[HttpException (0x80004005): 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=4223; handshake=2965; ]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +579
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +112
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +712
I had the same problem. Some SQL upgrade command was very long running and caused the error because the default timeout is set to 30 seconds. I've found the following article on SO to overcome this issue:
EF Code First - Timeout expired. The timeout period elapsed prior to completion
For me, it worked setting the CommandTimeout to 180 seconds in the Configuration.cs file.
Good luck
I think this might be useful for someone came looking for an answer for the same mistake in future.
Thanks for the help from everyone but the issue I faced was because of me forgetting to add user to my application pool ! silly mistake from my side !

SQL Azure - The timeout period elapsed during the post-login phase

I have azure cloud service - 2 web instances, serving about 500,000 requests per day. Using Azure business database. There is one issue with it - sometimes (avg. once per day, but not in the same time) there is 2-3 minutes long interval while i am unable to query DB, the error message is like this:
System.Data.Entity.Core.EntityException: The underlying provider failed on Open. ---> System.Data.SqlClient.SqlException: Connection Timeout Expired. The timeout period elapsed during the post-login phase. The connection could have timed out while waiting for server to complete the login process and respond; Or it could have timed out while attempting to create multiple active connections. The duration spent while attempting to connect to this server was - [Pre-Login] initialization=1; handshake=12; [Login] initialization=0; authentication=0; [Post-Login] complete=14004; ---> System.ComponentModel.Win32Exception: The wait operation timed out
--- End of inner exception stack trace ---
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.Open()
at System.Data.Entity.Infrastructure.DbExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
at System.Data.Entity.Infrastructure.DbExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.Core.EntityClient.EntityConnection.Open()
--- End of inner exception stack trace ---
at System.Data.Entity.Core.EntityClient.EntityConnection.Open()
at System.Data.Entity.Core.Objects.ObjectContext.EnsureConnection()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClassb.<GetResults>b__9()
at System.Data.Entity.Infrastructure.DbExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
at System.Lazy`1.CreateValue()
at System.Lazy`1.LazyInitValue()
at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at MyProject.MyRepository.GetItems(Boolean includePremium, Int32 a, Int32 b, Int32 c)
at MyProject.Controllers.MyController.GetItems(String Id, String device)
Numbers in the message - [Pre-Login] initialization=1; handshake=12; [Login] initialization=0; authentication=0; [Post-Login] complete=14004 - are always the same, not some random wait times or something...
Of course I tried to google this error, but all I could find was related to wrong connection management with plain ADO.NET etc. I am using Entity Framework 6, with code-first model, linq to entities queries, queries are not heavy (few ms, always under 1s).
There is this question on SO : Connection timeout in SQL Azure with answer like "this is transient error, just try again" - but this wont solve it for me, I got hundreds of these errors within this interval, I am pretty sure every request fail, so "wait 5 sec and try again" policy wont help here.
Is there something special about Azure DB which I must do about connection lifetime management in EF? Or you think this can be error message for "throttling" DB?
Well, after some time and some refactoring, it seems this error is indeed indicating throttling. We managed to reduce number of requests per minute, and without any other changes these errors disappeared entirely.
Its a shame that SQL Azure dont give more helpful messages about limits/resources.
I was able to fix this issue by disabling the Auto-Pause option. In my case, Auto pause option was enabled with 1 hour as its value and so the database was paused after 1 hour of idle time. So either you can increase this Auto Pause value or can disable it completely.
CAUTION: This will impact your monthly charges

Resources