Weird Entity Framework error: login failed for user - sql-server

I have an application with multiple DbContext subclasses that share a connection string (this is to avoid EF's horrible startup time with a single large DbContext type). At certain points (repeatable for me and somewhat for others), I get the following error when trying to make a database query:
System.Data.EntityException: "The underlying provider failed on Open."
with inner exception:
System.Data.SqlClient.SqlException "Login failed
for user 'username'"
The problem appears to go away if I switch back to using a single giant DbContext.
Does anyone know what this means/how to fix it? Would it help if I reused the same DbConnection object across DbContexts (as opposed to just using the same connection string)? This connection string has already succeeded in making several queries in the same request, so it can't be that the credentials are bad.
I am using ASP.NET MVC 3, EF 4.3.1, .NET 4.0, VS 2010.
The relevant stack trace is below:
[SqlException (0x80131904): Login failed for user 'testing_net'.]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +6351920
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() +412
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +1363
System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) +53
System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, TimeoutTimer timeout) +6366878
System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, TimeoutTimer timeout, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance) +6366793
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance) +352
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) +831
System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options) +49
System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject) +6368598
System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject) +78
System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) +2194
System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) +89
System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +6372110
System.Data.SqlClient.SqlConnection.Open() +300
System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure) +67
[EntityException: The underlying provider failed on Open.]
System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure) +11108990
System.Data.EntityClient.EntityConnection.Open() +142
System.Data.Objects.ObjectContext.EnsureConnection() +97
System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) +57
System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator() +47
System.Linq.Enumerable.Single(IEnumerable`1 source) +156
A rough outline of the code is as follows:
// db context:
public class MyDbContext<T> : DbContext {
public MyDbContext(string connectionString) : base(connectionString) { }
protected override OnModelCreating(DbModelBuilder builder)
{
// constructs the model base on the type of T
// code first POCO entities are annotated with an attribute that links
// them to one or more types T
}
}
I use AutoFac's DI to inject my DbContext's into the services my data access layer. The lifespan of the context is length of the HttpRequest.
The actual exception occurs on a call to Queryable.Single().
EDIT: I think this question might be relevant, but I'm not sure what to make of the race condition described.
EDIT: Now that I understand the issue, I can post the offending piece of code:
MyDbContext<T1> db1 = ...
var connectionString = db1.Database.Connection.ConnectionString;
var dbContext2 = new MyDbContext<T2>(connectionString);

It turns out that the problem was related to the PersistSecurityInfo connection string property. From MSDN:
PersistSecurityInfo: Gets or sets a Boolean value that indicates if
security-sensitive information, such as the password, is not returned
as part of the connection if the connection is open or has ever been
in an open state.
My connection string originally had a username and password in it. I would initialize a DbContext with this string, then later initialize a different context using the same string in the initial context's Database.Connection property. However, because PersistSecurityInfo was set to false, in some scenarios the password silently vanished from the connection's reference to the connection string, leading to login failure on the new DbContext instance.
The possible solutions I've thought of are to:
1. Set PersistSecurityInfo to true
2. Keep a separate reference to the connection string and use that
3. Use a different form of authentication that doesn't put the username and password in the connection string

As far as I know, the user should have some roles that are db_datareader, db_datawriter, db_ddladmin, db_owner or db_securityadmin. About more roles information, please refer to:
http://msdn.microsoft.com/en-us/library/ms189121(v=SQL.105).aspx

I had similar issue, I had forgotten to change the integrated security to false and add the local user id and password to the connection string in the web config file.

Related

SqlException while initializing database, but only on Azure and only with CF Migrations

I'm getting a SqlException when running initialization against an Azure SQL Server database: The server was not found or was not accessible.
Here's my Context code, in relevant part:
Private Sub New(Connection As DbConnection)
MyBase.New(Connection, True)
Database.SetInitializer(New CreateDatabaseIfNotExists(Of Context))
Database.SetInitializer(New MigrateDatabaseToLatestVersion(Of Context, Migrations.Configuration))
Try
Me.Database.Initialize(False)
Catch ex As Exception
HttpContext.Current.Response.Write(ex.ToString)
HttpContext.Current.Response.End()
End Try
End Sub
Public Shared Function Create() As Context
Return New Context(DbConnection)
End Function
Here's the full exception stack trace:
1. System.Data.SqlClient.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.ComponentModel.Win32Exception (0x80004005): Access is denied
2. 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)
3. at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
4. at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
5. at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
6. at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
7. at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
8. at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
9. at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
10. at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
11. at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
12. at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
13. at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
14. at System.Data.SqlClient.SqlConnection.Open()
15. at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.<>c.<Open>b__13_0(DbConnection t, DbConnectionInterceptionContext c)
16. at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
17. at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connection, DbInterceptionContext interceptionContext)
18. at System.Data.Entity.SqlServer.SqlProviderServices.<>c__DisplayClass60_0.<UsingConnection>b__0()
19. at System.Data.Entity.Infrastructure.DbExecutionStrategy.<>c__DisplayClass17_0.<Execute>b__0()
20. at System.Data.Entity.Infrastructure.DbExecutionStrategy.Execute[TResult](Func`1 operation)
21. at System.Data.Entity.Infrastructure.DbExecutionStrategy.Execute(Action operation)
22. at System.Data.Entity.SqlServer.SqlProviderServices.UsingConnection(DbConnection sqlConnection, Action`1 act)
23. at System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action`1 act)
24. at System.Data.Entity.SqlServer.SqlProviderServices.CreateDatabaseFromScript(Nullable`1 commandTimeout, DbConnection sqlConnection, String createDatabaseScript)
25. at System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(DbConnection connection, Nullable`1 commandTimeout, StoreItemCollection storeItemCollection)
26. at System.Data.Entity.Core.Common.DbProviderServices.CreateDatabase(DbConnection connection, Nullable`1 commandTimeout, StoreItemCollection storeItemCollection)
27. at System.Data.Entity.Core.Objects.ObjectContext.CreateDatabase()
28. at System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(DbConnection connection)
29. at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
30. at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
31. at System.Data.Entity.MigrateDatabaseToLatestVersion`2.InitializeDatabase(TContext context)
32. at System.Data.Entity.Internal.InternalContext.<>c__DisplayClass66_0`1.<CreateInitializationAction>b__0()
33. at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
34. at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
35. at System.Data.Entity.Internal.LazyInternalContext.<>c.<InitializeDatabase>b__58_0(InternalContext c)
36. at System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input)
37. at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action)
38. at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
39. at System.Data.Entity.Internal.InternalContext.Initialize()
40. at Website.Db.Context..ctor(DbConnection Connection) in D:\Dev\Application\__Legacy\Website\Db\Context.vb:line 24
41. ClientConnectionId:00000000-0000-0000-0000-000000000000
42. Error Number:5,State:0,Class:20
Now, when I insert some test code prior to the initialization attempt, e.g.:
Public Shared Function Create() As Context
Return New Context(DbConnection)
End Function
Private Sub New(Connection As DbConnection)
MyBase.New(Connection, True)
Database.SetInitializer(New CreateDatabaseIfNotExists(Of Context))
Database.SetInitializer(New MigrateDatabaseToLatestVersion(Of Context, Migrations.Configuration))
Dim sConnectionString As String = Connection.ConnectionString
HttpContext.Current.Response.Write($"Connection string: {sConnectionString}")
HttpContext.Current.Response.Write("<br />")
HttpContext.Current.Response.Write($"Can connect: {Db.Connection.CanConnect(sConnectionString)}")
HttpContext.Current.Response.End()
Try
Me.Database.Initialize(False)
Catch ex As Exception
HttpContext.Current.Response.Write(ex.ToString)
HttpContext.Current.Response.End()
End Try
End Sub
... my string is correct and the connection sails through just fine. It's only when I try to connect via my context that it fails (i.e. Me.Database.Initialize(False)).
Here's my CanConnect code:
Public Shared Function CanConnect(ConnectionString As String) As Boolean
CanConnect = True
Try
Utils.ExecuteNonQuery("SELECT * FROM INFORMATION_SCHEMA.TABLES", ConnectionString)
Catch ex As Exception
CanConnect = False
End Try
End Function
Public Shared Function ExecuteNonQuery(CommandText As String, ConnectionString As String) As Integer
Using oSqlCnn As New SqlConnection(ConnectionString)
Using oSqlCmd As SqlCommand = oSqlCnn.CreateCommand
oSqlCmd.CommandType = CommandType.Text
oSqlCmd.CommandText = CommandText
oSqlCnn.Open()
Return oSqlCmd.ExecuteNonQuery
End Using
End Using
End Function
So a plain-vanilla ADO.NET connection gets through while an EF Code First connection doesn't—both using the same connection string. Very odd.
Further compounding the mystery is the fact that all of this works great on my dev machine connecting to a locally-installed SQLEXPRESS instance. My context has no problem connecting and applying the migrations here. It only fails on Azure.
Searches reveal nothing, mostly only advice on how to properly configure a migration scenario. I've already done that, as evidenced on my dev machine.
I looked briefly at SqlException's members, with the thought that I might get the connection string and review it for accuracy, but that's not an option.
Why is this connection attempt failing only under the context, and only on Azure? How can I track it down so I can fix it?
--EDIT--
Here's my connection string (sanitized for security):
Server=tcp:some.database.windows.net,1433;Initial Catalog=somedb;Persist Security Info=False;User ID=username;Password=password;
--EDIT--
There's been some halting progress, but the new information clouds the picture even further.
According to this answer, for which I'm waiting for a confirmation from an Azure SQL engineer, System.Data.SqlClient first attempts a TCP connection (assuming it's instructed to do so via a tcp: prefix in the connection string). If that first attempt fails, the client falls back to Named Pipes.
This would seem to be what's happening in this case, as the stack trace indicates a Named Pipes failure (as helpfully noticed by #AlwaysLearning, in the comments). Of course Named Pipes isn't supported by Azure SQL, so a connection failure would be expected at that point.
So I first thought we were one step closer to a solution, until I encountered this: a query of the server's sys.event_log reveals a nearly unanimous record of successful connections.
This is getting really strange.
--EDIT--
The test on my local dev machine of disabling Named Pipes didn't reveal anything. The connection sailed through just fine on TCP alone.
So that narrows it down a bit. Failure is occurring only via EF6, and only on Azure. (But the connection log shows success.)
This is a real head-scratcher.
--EDIT--
I've been able to confirm that the successful connections in the log are from the ADO.NET connections from my testing (above).
The failed connections don't hit the log, as the server can't be found in order to log them (at least the Named Pipes attempts). This remains the big mystery.
--EDIT--
I opened an issue at the EntityFramework repo and published a repro project:
https://github.com/dotnet/ef6/issues/1987
https://github.com/InteXX/DbConnectionTest
--EDIT--
The clues keep coming in, but they continue to point in all different directions.
I have another database on the same server whose website uses the exact same Migrations code that I'm using here. That application works just fine, and the connection string is nearly identical.
Confusing. But this problem is at the server level, not at the database level.
Is it possible to intercept the connection string before it hits the database, to verify that it's not been corrupted on its way up the stack?
The problem is solved.
The savvy developer (not me) will note in the Context class from commit 3c20e41 of the repro project that I was building two separate connection strings in two different places. At the time, I was under the mistaken impression that CF Migrations only uses the default constructor for design-time operations, e.g. Add-Migration, Update-Database, etc.
It turns out that this is emphatically not the case. DbMigrator runtime code execution does indeed loop back to call the default constructor (there's a hidden clue: see line 31 in the stack trace above). And the default constructor is where I was getting the design-time connection string. That's why the Azure-based connection attempt was failing—because it couldn't find the server name provided by the design-time string. Naturally.
Now check the repaired code from commit d45888b. There's only one connection string source, and that source only builds the design-time string if Configuration.ConnectionStrings is Nothing. (I've had that happen before, which is why I built the two-string concept—I just didn't go far enough with it.)
And that's why it was working fine on my local dev machine—because I was using the design-time string.
I only discovered all this by sheer accident. I was working out another testing scenario and I got the username and password values mixed up in my design-time string builder. The connection failure report indicated a login failure this time, displaying the username that was attempted. Wait a minute! That's my password! Duh.
The only way (under that version of the code) that the design-time string could have been produced was during a call to the default constructor. Which, according to my previous understanding, didn't occur at runtime.
Live and learn.
Here's the code directly, in case at some point in the distant future I decide to take the repo down. Possible, but unlikely. I'd rather leave it up as a memento of questionable programming practices.
Old Context (broken)
Imports System.Data.Common
Imports System.Data.Entity
Imports System.Data.SqlClient
Imports System.Reflection
Imports DbConnectionTest.Db.Models
Namespace Db
Public Class Context
Inherits DbContext
Public Sub New()
MyBase.New(Utils.DesignTimeConnectionString) ' <--
End Sub
Private Sub New(Connection As DbConnection)
MyBase.New(Connection, True)
Database.SetInitializer(New CreateDatabaseIfNotExists(Of Context))
Database.SetInitializer(New MigrateDatabaseToLatestVersion(Of Context, Migrations.Configuration))
Me.Database.Initialize(False)
End Sub
Public Shared Function Create() As Context
Return New Context(New SqlConnection(Utils.RunTimeConnectionString)) ' <--
End Function
Protected Overrides Sub OnModelCreating(Builder As DbModelBuilder)
Builder.Configurations.AddFromAssembly(Assembly.GetExecutingAssembly)
MyBase.OnModelCreating(Builder)
End Sub
Protected Overrides Sub Dispose(Disposing As Boolean)
MyBase.Dispose(Disposing)
End Sub
Public Overridable Property Customers As DbSet(Of Customer)
Public Overridable Property Invoices As DbSet(Of Invoice)
End Class
End Namespace
New Utils (now working)
Imports System
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Namespace Db
Friend Class Utils
Friend Shared ReadOnly Property DbConnectionString() As String
Get
If ConfigurationManager.ConnectionStrings Is Nothing Then
With New SqlConnectionStringBuilder
.MultipleActiveResultSets = True
.PersistSecurityInfo = False
.IntegratedSecurity = False
.InitialCatalog = DB_NAME
.DataSource = Environment.MachineName
.Password = ""
.UserID = ""
DbConnectionString = .ConnectionString
End With
Else
DbConnectionString = ConfigurationManager.ConnectionStrings(DB_NAME).ConnectionString
End If
End Get
End Property
Friend Const DB_NAME As String = "DbConnectionTest"
End Class
End Namespace

Server error: if (User.IsInRole("Administrators"))

In my MVC 4 internet application I can't use this:
#if (User.IsInRole("Administrators"))
It result in this error:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The >server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is >configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating >Server/Instance Specified)
This has been bothering me for quite a long time any help is REALLY appreciated.
Here is the stack trace:
[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: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +5296071
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +558
System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover) +5308555
System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) +145
System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) +920
System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) +307
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions) +434
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +5311099
System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) +37
System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnectionOptions userOptions) +558
System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnectionOptions userOptions) +67
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) +1052
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +78
System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +167
System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +143
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +83
System.Data.SqlClient.SqlConnection.Open() +96
System.Web.DataAccess.SqlConnectionHolder.Open(HttpContext context, Boolean revertImpersonate) +88
System.Web.DataAccess.SqlConnectionHelper.GetConnection(String connectionString, Boolean revertImpersonation) +239
System.Web.Security.SqlRoleProvider.GetRolesForUser(String username) +762
WebMatrix.WebData.SimpleRoleProvider.GetRolesForUser(String username) +53
System.Web.Security.RolePrincipal.IsInRole(String role) +9461104
ASP._Page_Views_Home_Index_cshtml.Execute() in e:\HR\Vorönn 2013\VERK\Bordspil\Bordspil\Views\Home\Index.cshtml:23
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +97
System.Web.WebPages.StartPage.RunPage() +17
System.Web.WebPages.StartPage.ExecutePageHierarchy() +62
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +76
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +260
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +115
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +295
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
System.Web.Mvc.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17() +23
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +242
System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +21
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +177
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +89
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +102
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +43
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +57
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +47
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +47
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9629296
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
EDIT: It only results in this error when I auto login.
In MVC User.IsInRole or similar Authorization Methods are trying to use SimpleMembership provider by default.
If you are using a custom authorization you need to add the below code to your web.config:
<system.webServer>
<modules>
<remove name="RoleManager" />
</modules>
</system.webServer>
If you are using SimpleMembership make sure its databases are initialized.
This problem means that you can't connect to your database.
You should check your connectionstring and see whether you really have access to the database.
Note: It's possible that the connectionstring is correct and your database is available but that you have a network-related problem (port is not opened for example)
There's a possibility that you're using two different conncetion string (one for your normal data objects and one for the membership). You should check the following things:
(Supposing you're using SimpleMembership): Under the folder filters there's a class called InitializeSimpleMembershipAttribute. Locate the call to WebSecurity.InitializeDatabaseConnection. The first parameter to that method is the name of the connectionstring it will look up in the web.config. Make sure this is the correct name
Look in your web.config and make sure that the connection string is correct (for the simplemembership provider)
We had the same kind of problems and solved them. Check the following link
Error running MVC4 on Azure
The idea is to ensure the connection is created for every session started (so even after a timeout, where we had troubles as MVC uses a non existing connection).

Login failed for user 'someone'

I work on Microsoft SQL Server 2008 R1 and visual studio 2010.
My target is to clone a server to a new machine. However, after setting the application up and entering "local/storytelling" in the browser's URL, the error msg appears. After google the possible mistake, I have set the authentication mode form "Windows Authentication mode" to "SQL Server and Windows Authentication mode".
But the error remains... And I have no more idea now.
Here is the error msg:
[SqlException (0x80131904): Login failed for user 'storytelling'.]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +4846887
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +194
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2392
System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) +35
System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject) +144
System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart) +342
System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance) +221
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance) +189
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) +185
System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options) +31
System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject) +433
System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject) +66
System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) +499
System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) +65
System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +117
System.Data.SqlClient.SqlConnection.Open() +122
_Default.Page_Load(Object sender, EventArgs e) in D:\storytelling\Default.aspx.vb:21
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +50
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627
I don't know what's the problem to the code:(Source file: "Default.aspx.vb")
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("StoryTelling2ConnectionString").ConnectionString)
Dim cmmd As New SqlCommand
Dim strSQL As String
conn.Open()
The error log highlight conn.Open() in red color. I guess it's probably I lost some steps as I cloned the server. But I have no idea what steps I ignored.
Please provide some suggestion.
Thanks.
I finally know what happened. Sorry for the poor representation of my problem. I take reference to this and this, finding out that the windows server 2008 has installed an SQL Express edition for me. Nevertheless, I don't know at all, so I install another SQL Server. In this condition. I have two SQL server edition, and according to the thread MSDN FORUM, the log in to the different server is quite different in the "Server Name" input.
In short, my connection string is always incompatible with the "Server Name" input, and thus the log in process always failed.

Why timeout may occur in SqlConnection.Open()?

What are the cases when timeout occurs in SqlConnection.Open()?
On one of our IIS boxes 10 seconds after AppProcess was recycled the following exception appeared:
Type : System.Data.SqlClient.SqlException, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Message : Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
Source : .Net SqlClient Data Provider
Help link :
Errors : System.Data.SqlClient.SqlErrorCollection
Class : 11
LineNumber : 0
Number : -2
Procedure :
Server : XXX
State : 0
ErrorCode : -2146232060
Data : System.Collections.ListDictionaryInternal
TargetSite : Void OnError(System.Data.SqlClient.SqlException, Boolean)
Stack Trace : at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
at System.Data.SqlClient.TdsParserStateObject.ReadSniError(TdsParserStateObject stateObj, UInt32 error)
at System.Data.SqlClient.TdsParserStateObject.ReadSni(DbAsyncResult asyncResult, TdsParserStateObject stateObj)
at System.Data.SqlClient.TdsParserStateObject.ReadNetworkPacket()
at System.Data.SqlClient.TdsParser.ConsumePreLoginHandshake(Boolean encrypt, Boolean trustServerCert, Boolean& marsCapable)
at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, SqlConnection owningObject)
at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject)
at System.Data.SqlClient.SqlInternalConnectionTds.LoginWithFailover(Boolean useFailoverHost, String primaryHost, String failoverHost, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart)
at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options)
at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.SqlClient.SqlConnection.Open()
at NHibernate.Connection.DriverConnectionProvider.GetConnection()
at NHibernate.Impl.SessionFactoryImpl.OpenConnection()
According to MSDN Number property contains SQL Engine Error. But I was not able to find error -2 in master.dbo.sysmessages.
The interval between operation that tried to open the connection was about 3.5 seconds. The connection timeout has not been explicitly changed.
After 2 seconds similar exception appeared for the same thread, but in the different place. The call stack was much shorter:
Type : System.Data.SqlClient.SqlException, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Message : Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
Source : .Net SqlClient Data Provider
Help link :
Errors : System.Data.SqlClient.SqlErrorCollection
Class : 11
LineNumber : 0
Number : -2
Procedure :
Server : XXX
State : 0
ErrorCode : -2146232060
Data : System.Collections.ListDictionaryInternal
TargetSite : Void OnError(System.Data.SqlClient.SqlException, Boolean)
Stack Trace : at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.SqlClient.SqlConnection.Open()
at NHibernate.Connection.DriverConnectionProvider.GetConnection()
at NHibernate.Impl.SessionFactoryImpl.OpenConnection()
The interval between operation that tries to communicate to DB and the error is less than second.
Questions:
1. How to reproduce such errors?
2. Why call stack is shorter in the second case?
Seems like issue was caused by mirroring. The same situation is described here
Some cases of timeout in SqlConnection.Open() refers to a connection leak. It can occur when the connection pool is out of connections. First you should check number of reclaimed connections counter of IIS machine. It should be 0. If not you should check your code to ensure that sql connections are closed properly.
There can be some reasons such as your SQL server is not able to process your job..
Generally server which is hosting SQL Server, Ram - CPU Process goes up, and your sql cant give a response to your call. increase your timeout duration, and wait more (If you sure, your connection settings are all correct).

Login Failed for User 'NT AUTHORITY/NETWORK SERVICE' when using EntityDataSource with ASP:ListView

I have receive the infamous Login Failed for User 'NT AUTHORITY/NETWORK SERVICE' when I try to run a page that contains and EntityDataSource and Listview. Here's Stack Trace:
[SqlException (0x80131904): Login failed for user 'NT AUTHORITY\NETWORK SERVICE'.]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +4846887
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +194
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2392
System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) +35
System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject) +144
System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart) +342
System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance) +221
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance) +189
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) +185
System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options) +31
System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject) +433
System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject) +66
System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) +499
System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) +65
System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +117
System.Data.SqlClient.SqlConnection.Open() +122
System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure) +47
[EntityException: The underlying provider failed on Open.]
System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure) +168
System.Data.EntityClient.EntityConnection.Open() +96
System.Data.Objects.ObjectContext.EnsureConnection() +81
System.Data.Objects.ObjectQuery1.GetResults(Nullable1 forMergeOption) +46
System.Data.Objects.ObjectQuery1.System.Collections.Generic.IEnumerable<T>.GetEnumerator() +39
System.Linq.Enumerable.Single(IEnumerable1 source) +107
System.Data.Objects.ELinq.ObjectQueryProvider.b__2(IEnumerable1 sequence) +5
System.Data.Objects.ELinq.ObjectQueryProvider.ExecuteSingle(IEnumerable1 query, Expression queryRoot) +25
System.Data.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute(Expression expression) +43
System.Linq.Queryable.Count(IQueryable1 source) +240
System.Web.UI.WebControls.EntityDataSourceQueryBuilder1.Build(ObjectContext context, Boolean computeCount) +154
System.Web.UI.WebControls.EntityDataSourceView.ExecuteSelect(DataSourceSelectArguments arguments, Creator qbConstructor) +889
System.Web.UI.WebControls.EntityDataSourceView.ExecuteSelect(DataSourceSelectArguments arguments) +102
System.Web.UI.DataSourceView.Select(DataSourceSelectArguments arguments, DataSourceViewSelectCallback callback) +19
System.Web.UI.WebControls.DataBoundControl.PerformSelect() +142
System.Web.UI.WebControls.ListView.PerformSelect() +57
System.Web.UI.WebControls.BaseDataBoundControl.DataBind() +73
System.Web.UI.WebControls.BaseDataBoundControl.EnsureDataBound() +82
System.Web.UI.WebControls.ListView.CreateChildControls() +55
System.Web.UI.Control.EnsureChildControls() +87
System.Web.UI.Control.PreRenderRecursiveInternal() +44
System.Web.UI.Control.PreRenderRecursiveInternal() +171
System.Web.UI.Control.PreRenderRecursiveInternal() +171
System.Web.UI.Control.PreRenderRecursiveInternal() +171
System.Web.UI.Control.PreRenderRecursiveInternal() +171
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +842
Here's the contents of my EntityDataSource:
<asp:EntityDataSource ID="PartsDataSource" runat="server"
ConnectionString="name=Diel_inventoryEntities"
DefaultContainerName="Diel_inventoryEntities" EntitySetName="PartList"
EntityTypeFilter="PartList"
Select="it.[PARTNUMBER], it.[NSN], it.[PARTNAME], it.[REV], it.[CUSTOMER]">
</asp:EntityDataSource>
Besides creating the .edmx file, listview and entitydatasource, are there any other steps I need to take to resolve this error message?
Thanks,
Sid
This means that the user NT AUTHORITY/NETWORK SERVICE is used to log on to the database, and is denied. You should either make the website run under a different user account (using impersonation), or change the connection string to specify a sql account/pass. Both solutions require that you create the login in SQL Server, and grant that user the necessary rights.
Try this.I encountered the same error with a fresh IIS setup. I used :
"integrated security=false;User Id=sa;Password=yourpassword"

Resources