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.
Related
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!
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.
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
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.
I'm attempting to deploy my first MVC application and I keep running into issues revolving around connecting to my sql server database. My current problem is that when I try to publish the site, I'm greeted with: SqlException (0x80131904): Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'. What I'm not sure of however, is if this is my main issue or just a symptom of a different problem all together. I think the issue has to do with my connection strings (although I certainly could be wrong about that), which I've tweaked about 20 different ways. My most recent attampt to get it to work looks like this:
<add name="DefaultConnection"
connectionString="Data Source=*ip address*;AttachDbFilename=C:\*full path*\aspnet-SourceMvc-20130301025953.mdf;Initial Catalog=aspnet-SourceMvc-20130301025953;Integrated Security=True"
providerName="System.Data.SqlClient" />
<add name="StqmContext"
connectionString="Data Source=*ip address*;AttachDbFilename=C:\*full path*\Quotes.mdf;Initial Catalog=Quotes;Integrated Security=True"
providerName="System.Data.SqlClient" />
I've spent all day researching the issue, which seems pretty common, but they all seem to offer different solutions...non of which have worked so far.
Some additional information about the application: It's an ASP.NET MVC 4 application. The database was constructed using the Entity Framework Code-First method and I'm running SQl Server 2012, Enterprise ed. on Windows Server 2008 R2. The application was originally developed on my Windows 8 machine using Visual Studio 2012 Ultimate, and once I finished it, I moved it to my work machine with Windows Server 2008 R2 and am trying to publish it in Visual Studio Express 2012 Web Developer ed.
On a side note, how do you open a database that was created using code first in the sql server management studio?
Thanks in advance to anyone who can help.
Stack Trace:
[SqlException (0x80131904): Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'.]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +6676046
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +810
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +4403
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +84
System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) +55
System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) +368
System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) +6704814
System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) +6705315
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions) +610
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +1049
System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) +74
System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnectionOptions userOptions) +6707883
System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnectionOptions userOptions) +78
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) +2192
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +116
System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +1012
System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +6712511
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +152
System.Data.SqlClient.SqlConnection.Open() +229
System.Data.SqlClient.SqlProviderServices.UsingConnection(SqlConnection sqlConnection, Action`1 act) +134
System.Data.SqlClient.SqlProviderServices.UsingMasterConnection(SqlConnection sqlConnection, Action`1 act) +3805003
System.Data.SqlClient.SqlProviderServices.GetDbProviderManifestToken(DbConnection connection) +10955690
System.Data.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection) +91
[ProviderIncompatibleException: The provider did not return a ProviderManifestToken string.]
System.Data.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection) +10955761
System.Data.Entity.ModelConfiguration.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices providerServices, DbConnection connection) +48
[ProviderIncompatibleException: An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct.]
System.Data.Entity.ModelConfiguration.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices providerServices, DbConnection connection) +242
System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection) +82
System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext) +88
System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input) +248
System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +524
System.Data.Entity.Internal.InternalContext.CreateObjectContextForDdlOps() +23
System.Data.Entity.Database.Exists() +40
SourceMvc.Filters.SimpleMembershipInitializer..ctor() +128
[InvalidOperationException: The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588]
SourceMvc.Filters.SimpleMembershipInitializer..ctor() +461
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +159
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +256
System.Activator.CreateInstance(Type type, Boolean nonPublic) +127
System.Activator.CreateInstance(Type type) +11
System.Threading.LazyHelpers`1.ActivatorFactorySelector() +72
System.Threading.LazyInitializer.EnsureInitializedCore(T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory) +241
System.Threading.LazyInitializer.EnsureInitialized(T& target, Boolean& initialized, Object& syncLock) +139
System.Web.Mvc.Async.AsyncControllerActionInvoker.InvokeActionMethodFilterAsynchronously(IActionFilter filter, ActionExecutingContext preContext, Func`1 nextInChain) +145
System.Web.Mvc.Async.AsyncControllerActionInvoker.InvokeActionMethodFilterAsynchronously(IActionFilter filter, ActionExecutingContext preContext, Func`1 nextInChain) +840201
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__31(AsyncCallback asyncCallback, Object asyncState) +266
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +146
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +202
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag) +112
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState) +839055
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +146
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +166
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag) +27
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState) +50
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +146
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +166
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +826145
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +146
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +166
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, Object tag) +27
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +401
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState) +786250
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +146
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +166
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, Object tag) +27
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +343
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +12550291
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288
If you intend to use integrated security you need to turn impersonation on:
<identity impersonate="true" />
Otherwise add username and password to the connection string:
Data Source=myServerAddress;Initial Catalog=myDataBase;User ID=xxx;Password=yyy;
Integration tests are passing but in debug mode your getting login failed for user 'NT AUTHORITY\ANONYMOUS LOGON', then I'd be adding authenticate to the Web.config:
<system.web>
<authentication mode="Windows"></authentication>
If you get this error message when setting up a Scheduled Task, be sure to uncheck: Do not store password. The task will only have access to local computer resources.
If you setup an account that requires a password, but you also have that box checked, it will apparently default back to the anonymous login.