Intermittent SQL Connection Issue using AAD token (MSI approach) - azure

Facing an issue with Azure SQL authentication using Managed Service Identity of App Service. Its set up as mentioned in this article - Azure-sql-auth-with-msi
Everything was working fine for past few months but recently we started getting some intermittent errors when trying to open SQL connection:
Unhandled Exception: System.Data.SqlClient.SqlException: Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'.
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling, SqlAuthenticationProviderManager sqlAuthProviderManager)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
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.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()
Earlier I suspected it could be something to do with some code changes. However, was able to reproduce it with simple web job whose sole responsibility is to get the token and open a SQL connection.
Wierd part is, its not failing continuously but randomly after certain intervals (2 out of 10 times). I tried to compare tokens for successful and failed attempts but do not see any difference in it.
Sample Web job code:
using (SqlConnection conn = new SqlConnection
{
ConnectionString = "data source=<server>.database.secure.windows.net;
Initial Catalog=<db>;
Persist Security Info=True;MultipleActiveResultSets=True",
AccessToken = new AzureServiceTokenProvider()
.GetAccessTokenAsync("https://database.windows.net/").Result
})
{
conn.Open();
string cmdText = "SELECT SUSER_SNAME()";
using (SqlCommand sqlCommand = new SqlCommand(cmdText, conn))
{
object obj = sqlCommand.ExecuteScalar();
}
}
Thanks for any help in advance!

Related

ef.core error on azure

I am experiencing the following error only on azure:
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: TCP Provider, error: 0 - An attempt was made to access a socket in a way forbidden by its access permissions.)
The system is running .core 2 with ef.core and mssql.
If I use DB context provided by a DI then everything works fine, but if I initialise my own DbContext, then the error will appear.
The strangest thing, if I run a local copy of the code connected to azure's db then everything works fine, with no errors. The error only occurs while the code is running in azure.
I don't know where to start debuging this...or why this error occurs on azure
Trace:
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, object providerInfo, bool redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, bool applyTransientFaultHandling)
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, uint waitForMultipleObjectsTimeout, bool allowCreate, bool onlyOneCheckConnection, DbConnectionOptions userOptions, out DbConnectionInternal connection)
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions, out DbConnectionInternal connection)
System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, out DbConnectionInternal connection)
System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions)
System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions)
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource<DbConnectionInternal> retry)
System.Data.SqlClient.SqlConnection.Open()
Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(bool errorsExpected)
Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable+Enumerator.BufferlessMoveNext(bool buffer)
Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions+<>c__DisplayClass12_0.<Execute>b__0(DbContext c, TState s)
Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.Execute<TState, TResult>(TState state, Func<DbContext, TState, TResult> operation, Func<DbContext, TState, ExecutionResult<TResult>> verifySucceeded)
Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute<TState, TResult>(IExecutionStrategy strategy, Func<TState, TResult> operation, Func<TState, ExecutionResult<TResult>> verifySucceeded, TState state)
Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute<TState, TResult>(IExecutionStrategy strategy, TState state, Func<TState, TResult> operation)
Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable+Enumerator.MoveNext()
System.Linq.Enumerable+SelectEnumerableIterator.MoveNext()
System.Linq.Enumerable.TryGetFirst<TSource>(IEnumerable<TSource> source, out bool found)
lambda_method(Closure , QueryContext )
Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler+<>c__DisplayClass17_1.<CompileQueryCore>b__0(QueryContext qc)
Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute<TResult>(Expression query)
Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute<TResult>(Expression expression)
System.Linq.Queryable.FirstOrDefault<TSource>(IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate)
In azure, go to application settings > Connection Strings , and set your connection string there.
For example, if you have your connection string set in your application.json, like this:
{
"ConnectionStrings": {
"DefaultConnection": "yourconnectionstring"
},
Then your values under Application Settings > Connection Strings , would be as follows:
Name: DefaultConnection
Value: YourConnectionString
and select SQL Database from the drop down menu.
Hit save, let the application restart and you should be good to go.

SqlException (0x80131904) with sitecore and sql server express 2016

I'm getting the following sql exception when I try to connect to a newly installed sitecore instance (build worked), I am using SQL Server Express 2016.
[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)]
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling) +1418
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +470
System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) +70
System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) +945
System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) +114
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) +1637
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) +132
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +246
System.Data.SqlClient.SqlConnection.Open() +122
Sitecore.Data.DataProviders.Sql.DataProviderCommand..ctor(IDbCommand command, DataProviderTransaction transaction, Boolean openConnection) +106
Sitecore.Data.DataProviders.Sql.<>c__DisplayClass4.<CreateCommand>b__3() +48
Sitecore.Data.DataProviders.NullRetryer.Execute(Func`1 action, Action recover) +289
Sitecore.Data.DataProviders.Sql.<>c__DisplayClass12.<CreateReader>b__10() +30
Sitecore.Data.DataProviders.NullRetryer.Execute(Func`1 action, Action recover) +289
Sitecore.Data.DataProviders.Sql.SqlDataApi.CreateReader(String sql, Object[] parameters) +251
Sitecore.Data.DataProviders.Sql.SqlDataProvider.GetContentLanguages() +190
Sitecore.Data.DataProviders.Sql.SqlDataProvider.LoadLanguages() +146
Sitecore.Data.DataProviders.Sql.SqlDataProvider.GetLanguages() +49
Sitecore.Data.SqlServer.SqlServerDataProvider.LoadItemDefinitions(String condition, Object[] parameters, SafeDictionary`2 prefetchData) +1335
Sitecore.Data.DataProviders.Sql.SqlDataProvider.PrefetchItems(String itemCondition, String fieldCondition, String childCondition, Object[] parameters) +147
Sitecore.Data.DataProviders.Sql.SqlDataProvider.EnsureInitialPrefetch() +255
Sitecore.Data.DataProviders.Sql.SqlDataProvider.GetPrefetchData(ID itemId) +67
Sitecore.Data.DataProviders.Sql.SqlDataProvider.GetItemDefinition(ID itemId, CallContext context) +9
Sitecore.Data.DataProviders.DataProvider.GetItemDefinition(ID itemID, CallContext context, DataProviderCollection providers) +148
Sitecore.Data.DataSource.GetItemInformation(ID itemID) +88
Sitecore.Data.DataSource.GetItemData(ID itemID, Language language, Version version) +31
Sitecore.Nexus.Data.DataCommands.GetItemCommand.GetItem(ID , Language , Version , Database ) +92
Sitecore.Nexus.Data.DataCommands.GetItemCommand.Execute(ID , Language , Version , Database ) +496
Sitecore.Data.Engines.DataCommands.GetItemCommand.DoExecute() +139
Sitecore.Data.Engines.EngineCommand`2.Execute() +96
Sitecore.Data.Managers.ItemProvider.GetItem(ID itemId, Language language, Version version, Database database) +292
Sitecore.Data.Managers.ItemProvider.GetItem(ID itemId, Language language, Version version, Database database, SecurityCheck securityCheck) +141
Sitecore.Data.Managers.<>c__DisplayClass2f.<GetItem>b__2e() +58
Sitecore.Data.Managers.PipelineBasedItemProvider.ExecuteAndReturnResult(String pipelineName, String pipelineDomain, Func`1 pipelineArgsCreator, Func`1 fallbackResult) +96
Sitecore.Data.Managers.ItemManager.GetItem(String itemPath, Language language, Version version, Database database) +142
Sitecore.FXM.Matchers.DomainMatcherRepository.GetAllDomainMatchers(IDatabase database) +81
Sitecore.FXM.Sites.FxmSiteProvider.GetFxmSites() +182
Sitecore.FXM.Sites.FxmSiteProvider.get_FxmSites() +103
Sitecore.FXM.Sites.FxmSiteProvider.GetSites() +88
System.Linq.<SelectManyIterator>d__16`2.MoveNext() +321
Sitecore.Sites.SiteCollection.AddRange(IEnumerable`1 sites) +138
Sitecore.Sites.SitecoreSiteProvider.GetSites() +225
Sitecore.Sites.SiteContextFactory.GetSites() +256
Sitecore.Sites.SiteContextFactory.GetSiteContext(String hostName, String fullPath, Int32 portNumber) +121
Sitecore.Pipelines.HttpRequest.SiteResolver.ResolveSiteContext(HttpRequestArgs args) +430
Sitecore.Pipelines.HttpRequest.SiteResolver.Process(HttpRequestArgs args) +50
(Object , Object[] ) +74
Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args) +484
Sitecore.Nexus.Web.HttpModule.(Object , EventArgs ) +528
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +142
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +92
From what I understand looking around at different other people who have similar problems the solution might be to go into my Sql Server Management Studio ->SQL Server network config and configure some protocols, however the UI for the SSMS for Express does not have the Network config as far as I can see, at least not under the connected database menu which has the submenus
Database
Security
Server Objects
Replication
Management
I would prefer to not have to get the non express installation, because I just need to check that frontend code I have developed when deployed into our Sitecore environment works.
Check Sitecore compatibility tables here: https://kb.sitecore.net/articles/087164
Sitecore does not support SQL Server 2016 and it does not support SQL Server Express 2016.

Microsoft.Jet.OLEDB.4.0 Connection string with SSL doesn't work

I have a application in which I am fetching an Excel Sheet from a server and edit/add data into it and save it. It was working fine when I didn't add a SSL but since I have added a SSL it stopped working and giving an error on
con.open();
My connection still look like this.
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;\"";
Error looks like this
at
System.Data.OleDb.OleDbServicesWrapper.GetDataSource(OleDbConnectionString
constr, DataSourceWrapper& datasrcWrapper)
at
System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString
constr, OleDbConnection connection)
at
System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionOptions
options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo,
DbConnectionPool pool, DbConnection owningObject)
at
System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection
owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions
userOptions)
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.ProviderBase.DbConnectionInternal.OpenConnection(DbConnection
outerConnection, DbConnectionFactory connectionFactory)
at System.Data.OleDb.OleDbConnection.Open()
at
CSNY_timelog.Controllers.ReportController.GenerateReport1(ReportViewModel
objviewmodel) in c:\Users\Arpan\Documents\Visual Studio
2012\Projects\CSNY_timelog\CSNY_timelog\Controllers\ReportController.cs:line
939
Does any one know how to fix this issue?
Do I have to add more option in connection string to make it work?

Weird exception when acceding database from web api project

I am suddenly getting the following exception when trying to query the database
Application: 2014-03-27T20:56:01 PID[15096] Error Error Getting user with id : 885151 Exception : System.Data.Entity.Core.EntityException: The underlying provider failed on Open. ---> 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: TCP Provider, error: 0 - An attempt was made to access a socket in a way forbidden by its access permissions.) ---> System.ComponentModel.Win32Exception: An attempt was made to access a socket in a way forbidden by its access permissions
Application: --- End of inner exception stack trace ---
Application: at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
Application: at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
Application: at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover)
Application: at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
Application: at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
Application: at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
Application: at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData)
Application: at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
Application: at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
Application: at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
Application: at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
Application: at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
Application: at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
Application: at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
Application: at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
Application: at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
Application: at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
Application: at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
Application: at System.Data.SqlClient.SqlConnection.Open()
Application: at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.<Open>b__38(DbConnection t, DbConnectionInterceptionContext c)
Application: at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
Application: at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connection, DbInterceptionContext interceptionContext)
Application: at System.Data.Entity.Core.EntityClient.EntityConnection.<Open>b__2()
Application: at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
Application: at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
Application: at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation)
Application: at System.Data.Entity.Core.EntityClient.EntityConnection.Open()
Application: --- End of inner exception stack trace ---
Application: at System.Data.Entity.Core.EntityClient.EntityConnection.Open()
Application: at System.Data.Entity.Core.Objects.ObjectContext.EnsureConnection(Boolean shouldMonitorTransactions)
Application: at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
Application: at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__5()
Application: at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
Application: at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
Application: at System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
Application: at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
Application: at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
Application: at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__2[TResult](IEnumerable`1 sequence)
Application: at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable`1 query, Expression queryRoot)
Application: at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
Application: at System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression)
Application: at System.Linq.Queryable.SingleOrDefault[TSource](IQueryable`1 source)
Application: at ServerMapping.Dal.GetUser(String externalID)
Application: at TasteItWebSite.Controllers.LoginApiController.Get(String id)
The thing is that its not all the time... sometimes it works but sometimes it does not. Its a webapi project which connects to an sql azure db using EF6.1
Why is this happening?
This is definitely a basic error showing that you are unable to connect to SQL Server. Usually, with Entity Framework, this means the config file is not set up properly.
I can think of two reasons.
If the machine accessing the database is in Azure and has its IP address changing, then you have to whitelist the IP in the Azure SQL database.
We've seen this where I work - same error. Azure SQL says there can and will be transient errors when executing queries. Here is a link with some more information: SQL Azure Database retry logic

Intermittent IIS/Azure Errors

I have a web app running on an Azure VM. It is single-code base, multiple db's. Based on appsettings in the web.config (basically localhost or production), it knows which database to use.
Just recently I made a simple update and pushed the code to the server. I use git to pull files from the repo to the server, then copy my dll's from my local dev machine to the server. It's not the best, but it's worked for now.
Since this last update, I've been getting intermittent database connection errors (nothing related to the udpates I pushed). Based on the errors I'm receiving, the app is looking for the wrong database (what's set for localhost) instead of using the production databases. It fails on login since the db doesn't exist. I can log in, sometimes customers can't, even at the same time. Then I switch to a new computer and it doesn't work. I've restarted IIS and that's solved it once, but I am totally at a loss about what is going on.
Thoughts:
Could the dll or build be corrupted?
Is something wrong with IIS?
Other Ideas?
Any help, much appreciated!
Scott J.
Edit: It seems only to happen on the login. I changed the login page back to the original. It worked, now it stopped working sometimes again. Very frustrating!
Error Message:
Cannot open database "companyA" requested by the login. The login failed. Login failed for user 'IIS APPPOOL\Production'.
System.Data.SqlClient.SqlException (0x80131904): Cannot open database "companyA" requested by the login. The login failed. Login failed for user 'IIS APPPOOL\Production'. at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions) at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnectionOptions userOptions) 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 PLM.Providers.SqlConnectionHolder.Open(HttpContext context, Boolean revertImpersonate) in C:\Users\Israel\Desktop\ODESK\Scott\PLMMemberhipProvider\SqlConnectionHelper.cs:line 127 at PLM.Providers.SqlConnectionHelper.GetConnection(String connectionString, Boolean revertImpersonation) in C:\Users\Israel\Desktop\ODESK\Scott\PLMMemberhipProvider\SqlConnectionHelper.cs:line 57 at PLM.Providers.SqlMembershipProvider.GetConnectionHolder() in C:\Users\Israel\Desktop\ODESK\Scott\PLMMemberhipProvider\SQLMembershipProvider.cs:line 101 at PLM.Providers.SqlMembershipProvider.GetPasswordWithFormat(String username, Boolean updateLastLoginActivityDate, Int32& status, String& password, Int32& passwordFormat, String& passwordSalt, Int32& failedPasswordAttemptCount, Int32& failedPasswordAnswerAttemptCount, Boolean& isApproved, DateTime& lastLoginDate, DateTime& lastActivityDate) in C:\Users\Israel\Desktop\ODESK\Scott\PLMMemberhipProvider\SQLMembershipProvider.cs:line 1704 at PLM.Providers.SqlMembershipProvider.CheckPassword(String username, String password, Boolean updateLastLoginActivityDate, Boolean failIfNotApproved, String& salt, Int32& passwordFormat) in C:\Users\Israel\Desktop\ODESK\Scott\PLMMemberhipProvider\SQLMembershipProvider.cs:line 1562 at PLM.Providers.SqlMembershipProvider.CheckPassword(String username, String password, Boolean updateLastLoginActivityDate, Boolean failIfNotApproved) in C:\Users\Israel\Desktop\ODESK\Scott\PLMMemberhipProvider\SQLMembershipProvider.cs:line 1549 at PLM.Providers.SqlMembershipProvider.ValidateUser(String username, String password) in C:\Users\Israel\Desktop\ODESK\Scott\PLMMemberhipProvider\SQLMembershipProvider.cs:line 856 at System.Web.UI.WebControls.Login.AuthenticateUsingMembershipProvider(AuthenticateEventArgs e) at System.Web.UI.WebControls.Login.OnAuthenticate(AuthenticateEventArgs e) at System.Web.UI.WebControls.Login.AttemptLogin() at System.Web.UI.WebControls.Login.OnBubbleEvent(Object source, EventArgs e) at System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) at System.Web.UI.WebControls.Button.OnCommand(CommandEventArgs e) at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) ClientConnectionId:5257f0df-46c9-4faa-bfea-1db4daf509b3
What kind of database are you logging into? I'm hoping that your data is stored in SQL Azure or Azure Storage.
If your production database is created within the worker role, note that your worker role will be periodically re-started by Microsoft whenever your worker's OS needs to be updated, etc. and any locally created files (inc. DB files) will be deleted when the VM reboots.

Resources