I have few web sites running in IIS 7.5 and each one is mapped to its own related database, using the connectionStrings section in each one of the config files. The string is using "Integrated Security=SSPI" and everything is working fine so far, users can read and write to their respective dbs. The IIS and the SQL Server are on the same machine and the SQL is set for mixed authentication.
I want to set Integrated Security=false and add user=mySpecifDb;pwd=test123 to the string, but it doesn't work. The web site throws a db connection error. I've created the user "mySpecifDb" using the SSMS and followed all the instructions so far. I can log into the SSMS using the credentials "mySpecifDb" and "test123" and I can read and write to the selected database and only to it exclusively. I can't access any other db using these credentials and this is what I want. In the IIS 7.5 all websites are using the DefaultAppPool. I dont know where to go from this point.
EDIT: This is the real connection string with the real credentials. As mentioned before I can log in SSMS using them, and read/write to AutoParkDemo db only.If I just change "true" to "SSPI" then all works.
<connectionStrings>
<clear />
<add name="AutoPark" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=AutoParkDemo;Integrated Security=false;user=apmDemo;pwd=*****" providerName="System.Data.SqlClient" />
</connectionStrings>
EDIT:
Server Error in '/Manager' Application.
Login failed for user 'apmDemo'.
Exception Details: System.Data.SqlClient.SqlException: Login failed for user 'apmDemo'.
Stack Trace:
[SqlException (0x80131904): Login failed for user 'apmDemo'.]
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) +642
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 oldConnection, DbConnectionInternal& connection) +1089
System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +6785863
System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry) +233
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +278
System.Data.SqlClient.SqlConnection.Open() +239
System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch(TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed) +207
System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connection, DbInterceptionContext interceptionContext) +438
System.Data.Entity.SqlServer.<>c__DisplayClass1.<Execute>b__0() +15
System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func`1 operation) +263
System.Data.Entity.SqlServer.SqlProviderServices.UsingConnection(DbConnection sqlConnection, Action`1 act) +375
System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action`1 act) +749
System.Data.Entity.SqlServer.SqlProviderServices.GetDbProviderManifestToken(DbConnection connection) +504
System.Data.Entity.Core.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection) +118
[ProviderIncompatibleException: The provider did not return a ProviderManifestToken string.]
System.Data.Entity.Core.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection) +459
System.Data.Entity.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices providerServices, DbConnection connection) +51
[ProviderIncompatibleException: An error occurred accessing the database. This usually means that the connection to the database failed. Check that the connection string is correct and that the appropriate DbContext constructor is being used to specify it or find it in the application's config file. See http://go.microsoft.com/fwlink/?LinkId=386386 for information on DbContext and connections. See the inner exception for details of the failure.]
System.Data.Entity.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices providerServices, DbConnection connection) +300
System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory) +83
System.Data.Entity.Infrastructure.DefaultManifestTokenResolver.ResolveManifestToken(DbConnection connection) +327
System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection) +118
System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext) +94
System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input) +248
System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +618
System.Data.Entity.Internal.InternalContext.CreateObjectContextForDdlOps() +23
System.Data.Entity.Database.Exists() +40
Microsoft.AspNet.Identity.EntityFramework.IdentityDbContext`1.IsIdentityV1Schema(DbContext db) +168
Microsoft.AspNet.Identity.EntityFramework.IdentityDbContext`1..ctor(String nameOrConnectionString, Boolean throwIfV1Schema) +80
AutoParkManager.Models.ApplicationDbContext..ctor() in c:\AppVS2013\AutoPark\AutoParkManager\Models\IdentityModels.cs:12
AutoParkManager.Controllers.AccountController..ctor() in c:\AppVS2013\AutoPark\AutoParkManager\Controllers\AccountController.cs:22
[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.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +92
[InvalidOperationException: An error occurred when trying to create a controller of type 'AutoParkManager.Controllers.AccountController'. Make sure that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +256
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +169
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +270
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +147
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +12639055
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288
Change you connectionstring like below and try again. Take off the Integrated Security=false; and specify Persist Security Info=True;
<add name="AutoPark" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=AutoParkDemo;Persist Security Info=True;user=apmDemo;pwd=*****" providerName="System.Data.SqlClient" />
A better solution would be to create a new local windows user on the server, add that user to the SQL database (with correct permissions). Then create a new app pool using this new identity and assoicate the one web site with this new app pool. You would leave the Integrate Security as True.
If you really want to specify the user in the config, then as Martin and Dennis commented we would need full error message and connection string (minus the password)
Related
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
I have an ASP.NET MVC app featuring nHibernate as ORM (using SQL Server as database).
Every 5-6 requests, an exception is thrown containing random error described with the title above.
This is only happening on GET requests and starts with:
ERROR While preparing SELECT ..
These issues started ever since I've upgraded NHibernate 4.x to NHibernate 5.0.3 (5.1.1 now). During this process I've also updated the target framework, used to be .NET 4.5.2 now is .NET 4.7.2.
I've checked literally everything, made sure there aren't any connection leaks or timeouts against the DB but the error still persists. Tried switching the "TransparentNetworkIPResolution" and "Enlist" features off from the connection string - the problem is still here.
Any idea regarding the solution of the problem would be more than welcome.
This is the line that is the culprit for the exception below (DepartmentService:838):
var department = _departmentRepository.Get(departmentId);
The scenario is the following, I have multiple grids thus multiple requests are fired towards the same action. Every 5th-6th refresh of the same page, one of the many requests would fail (the one request that fails is random, i.e. sometimes it's the 1st, sometimes the 2nd, and so on).
Here is full exception snippet from my logs:
2020-06-26 13:25:16,297 [50] ERROR NHibernate.Util.ADOExceptionReporter [(null)] - While preparing SELECT department0_.DepartmentId as departmentid1_22_0_, department0_.CreatedAt as createdat4_22_0_, department0_.ModifiedAt as modifiedat5_22_0_, department0_.Name as name2_22_0_, department0_.Status as status6_22_0_, department0_.CreatedBy as createdby7_22_0_, department0_.ModifiedBy as modifiedby8_22_0_, department0_.SiteId as siteid3_22_0_ FROM dbo.Departments department0_ WHERE department0_.DepartmentId=#p0 an error occurred
2020-06-26 13:25:16,298 [50] ERROR NHibernate.Util.ADOExceptionReporter [(null)] - The requested operation cannot be completed because the connection has been broken.
2020-06-26 13:25:16,300 [50] ERROR [(null)] - NHibernate.ADOException: While preparing SELECT department0_.DepartmentId as departmentid1_22_0_, department0_.CreatedAt as createdat4_22_0_, department0_.ModifiedAt as modifiedat5_22_0_, department0_.Name as name2_22_0_, department0_.Status as status6_22_0_, department0_.CreatedBy as createdby7_22_0_, department0_.ModifiedBy as modifiedby8_22_0_, department0_.SiteId as siteid3_22_0_ FROM dbo.Departments department0_ WHERE department0_.DepartmentId=#p0 an error occurred ---> System.InvalidOperationException: The requested operation cannot be completed because the connection has been broken.
at System.Data.SqlClient.SqlInternalConnectionTds.ExecuteTransaction(TransactionRequest transactionRequest, String name, IsolationLevel iso, SqlInternalTransaction internalTransaction, Boolean isDelegateControlRequest)
at System.Data.SqlClient.SqlDelegatedTransaction.Initialize()
at System.Transactions.TransactionStatePSPEOperation.PSPEInitialize(InternalTransaction tx, IPromotableSinglePhaseNotification promotableSinglePhaseNotification, Guid promoterType)
at System.Transactions.TransactionStateActive.EnlistPromotableSinglePhase(InternalTransaction tx, IPromotableSinglePhaseNotification promotableSinglePhaseNotification, Transaction atomicTransaction, Guid promoterType)
at System.Transactions.Transaction.EnlistPromotableSinglePhase(IPromotableSinglePhaseNotification promotableSinglePhaseNotification, Guid promoterType)
at System.Transactions.Transaction.EnlistPromotableSinglePhase(IPromotableSinglePhaseNotification promotableSinglePhaseNotification)
at System.Data.SqlClient.SqlInternalConnection.EnlistNonNull(Transaction tx)
at System.Data.SqlClient.SqlInternalConnection.Enlist(Transaction tx)
at System.Data.ProviderBase.DbConnectionInternal.ActivateConnection(Transaction transaction)
at System.Data.ProviderBase.DbConnectionPool.PrepareConnection(DbConnection owningObject, DbConnectionInternal obj, Transaction transaction)
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource1 retry)
at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.Open()
at NHibernate.Connection.DriverConnectionProvider.GetConnection()
at NHibernate.AdoNet.ConnectionManager.GetConnection()
at NHibernate.AdoNet.AbstractBatcher.Prepare(DbCommand cmd)
--- End of inner exception stack trace ---
at NHibernate.AdoNet.AbstractBatcher.Prepare(DbCommand cmd)
at NHibernate.AdoNet.AbstractBatcher.ExecuteReader(DbCommand cmd)
at NHibernate.Loader.Loader.GetResultSet(DbCommand st, QueryParameters queryParameters, ISessionImplementor session, IResultTransformer forcedResultTransformer)
at NHibernate.Loader.Loader.DoQuery(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies, IResultTransformer forcedResultTransformer)
at NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies, IResultTransformer forcedResultTransformer)
at NHibernate.Loader.Loader.LoadEntity(ISessionImplementor session, Object id, IType identifierType, Object optionalObject, String optionalEntityName, Object optionalIdentifier, IEntityPersister persister)
at NHibernate.Loader.Entity.AbstractEntityLoader.Load(ISessionImplementor session, Object id, Object optionalObject, Object optionalId)
at NHibernate.Loader.Entity.AbstractEntityLoader.Load(Object id, Object optionalObject, ISessionImplementor session)
at NHibernate.Persister.Entity.AbstractEntityPersister.Load(Object id, Object optionalObject, LockMode lockMode, ISessionImplementor session)
at NHibernate.Event.Default.DefaultLoadEventListener.LoadFromDatasource(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options)
at NHibernate.Event.Default.DefaultLoadEventListener.DoLoad(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options)
at NHibernate.Event.Default.DefaultLoadEventListener.Load(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options)
at NHibernate.Event.Default.DefaultLoadEventListener.ProxyOrLoad(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options)
at NHibernate.Event.Default.DefaultLoadEventListener.OnLoad(LoadEvent event, LoadType loadType)
at NHibernate.Impl.SessionImpl.FireLoad(LoadEvent event, LoadType loadType)
at NHibernate.Impl.SessionImpl.Get(String entityName, Object id)
at NHibernate.Impl.SessionImpl.Get[T](Object id)
at Codera.Data.NHibernate.NHRepository1.Get(Object id) at Castle.Proxies.Invocations.NHRepository1_Get_10.InvokeMethodOnTarget()
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at ISOQuest.Data.NHibernate.Interceptors.MethodInterceptor.Intercept(IInvocation invocation) in C:\Projects\ISOQuestGen6\ISOQuest.Data.NHibernate\Interceptors\MethodInterceptor.cs:line 49
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Castle.Proxies.DepartmentRepositoryProxy.Get(Object id)
at ISOQuest.Business.Services.DepartmentService.GetDepartmentAdministrators(Guid departmentId, Int32 type) in C:\Projects\ISOQuestGen6\Modules\ISOQuest\ISOQuest.Business\Services\Department\DepartmentService.cs:line 838
at ISOQuest.Web.Controllers.Api.DepartmentsController.LoadDepartmentAdministrators(Guid departmentId, Int32 type) in C:\Projects\ISOQuestGen6\Modules\ISOQuest\ISOQuest.Web\Controllers\Api\DepartmentsController.cs:line 454
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) at System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) at System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) at System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
After trying everything, I circled back to nHibernate 5.X change logs, ended up here: https://nhibernate.info/doc/nhibernate-reference/transactions.html, and found this little note at the very end of the changelog:
As of NHibernate v5.0, FlushMode.Commit requires the configuration setting transaction.use_connection_on_system_prepare to be true for flushing from transaction scope commit. Otherwise, it will be your responsibility to flush the session before completing the scope.
Using transaction.use_connection_on_system_prepare can cause undesired transaction promotions to distributed: it requires using a dedicated connection for flushing, and it delays session disposal (if done inside the scope) to the scope disposal. If you want to avoid this, set this setting to false and manually flush your sessions.
For new applications, it is recommended to set transaction.use_connection_on_system_prepare to false, and to flush explicitly your sessions before scope completion. For old applications, consider checking how sessions are flushed, and if possible switch it to false too.
Basically, the one setting we had changed while migrating to nHibernate 5 was the FlushMode from "Auto" to "Commit", but somehow missed this flag (transaction.use_connection_on_system_prepare = false).
Hope this will help other people with legacy systems trying to upgrade!
I am trying to deploy a database dacpac with powershell and receiving error below. Anyone know how to fix this? I am thinking its due to me having SQL Server 2016. Trying to understand what the error message means.
Here is the code: Main error seems unable to connect to localhost?? This basic user access. I tried right clicking and Running As Administrator on Powershell, still does not work.
add-type -path "C:\Program Files (x86)\Microsoft SQL Server\140\DAC\bin\Microsoft.SqlServer.Dac.dll"
$dacService = new-object Microsoft.SqlServer.Dac.DacServices "server=localhost"
$dp = [Microsoft.SqlServer.Dac.DacPackage]::Load("C:\Test\ScaffoldTest.dacpac")
try
{
$dacService.deploy($dp, "ScaffoldTest", "True")
}
catch
{
Write-Host "LoadException";
$Error | format-list -force
Write-Host $Error[0].Exception.ParentContainsErrorRecordException;
}
Error:
Exception calling "Deploy" with "3" argument(s): "Could not deploy package."
At line:32 char:1
+ $dacService.deploy($dp, "ScaffoldTest", "True")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DacServicesException
Exception : System.Management.Automation.MethodInvocationException: Exception calling "Deploy" with "3" argument(s): "Could not deploy package." --->
Microsoft.SqlServer.Dac.DacServicesException: Could not deploy package. ---> Microsoft.Data.Tools.Schema.Sql.Deployment.DeploymentFailedException: Unable to connect
to target server 'localhost'. Please verify the connection information such as the server name, login credentials, and firewall rules for the target server. --->
System.Data.SqlClient.SqlException: Login failed for user ''.
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.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.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.Open()
at Microsoft.Data.Tools.Schema.Common.SqlClient.ReliableSqlConnection.<OpenConnection>b__0()
at Microsoft.Data.Tools.Schema.Common.SqlClient.RetryPolicy.<>c__DisplayClass4.<ExecuteAction>b__3(RetryState retryState)
at Microsoft.Data.Tools.Schema.Common.SqlClient.RetryPolicy.ExecuteAction[R](Func`2 func, Nullable`1 token)
at Microsoft.Data.Tools.Schema.Common.SqlClient.RetryPolicy.ExecuteAction(Action`1 action, Nullable`1 token)
at Microsoft.Data.Tools.Schema.Common.SqlClient.RetryPolicy.ExecuteAction(Action action, Nullable`1 token)
at Microsoft.Data.Tools.Schema.Common.SqlClient.ReliableSqlConnection.OpenConnection()
at Microsoft.Data.Tools.Schema.Common.SqlClient.ReliableConnectionHelper.OpenConnection(SqlConnectionFactory connectionFactory, Boolean useRetry)
at Microsoft.Data.Tools.Schema.Common.SqlClient.ReliableConnectionHelper.OpenConnection(SqlConnectionFactory connectionFactory, Action`1 usingConnection,
Predicate`1 catchException, Boolean useRetry)
at Microsoft.Data.Tools.Schema.Common.SqlClient.ReliableConnectionHelper.GetServerAndDatabaseVersion(SqlConnectionFactory connectionFactory,
ServerAndDatabaseInfo& info)
at Microsoft.Data.Tools.Schema.Sql.SqlDatabaseSchemaProviderFamily.DetermineSqlPlatform(SqlConnectionFactory connectionFactory, CompatibilityLevelVerification
verificationMode, String& errorMessage)
at Microsoft.Data.Tools.Schema.Sql.SqlDatabaseSchemaProviderFamily.DetermineDatabaseSchemaProvider(SqlConnectionFactory connectionFactory, String& errorMessage)
at Microsoft.Data.Tools.Schema.Sql.SqlDatabaseSchemaProviderFamily.DetermineDatabaseSchemaProvider(SqlConnectionFactory connectionFactory)
at Microsoft.Data.Tools.Schema.Sql.Deployment.SqlDeploymentEndpointServer.GetProviderType(DatabaseSchemaProviderFamily connectionSniffer, SqlConnectionFactory
connectionFactory, Type& providerType, Boolean& validDataSource, SqlException& exception)
--- End of inner exception stack trace ---
at Microsoft.Data.Tools.Schema.Sql.Deployment.SqlDeploymentEndpointServer.OnInit(ErrorManager errors, String targetDBName)
at Microsoft.Data.Tools.Schema.Sql.Deployment.SqlDeployment..ctor(SqlDeploymentConstructor constructor)
at Microsoft.Data.Tools.Schema.Sql.Deployment.SqlDeploymentConstructor.ConstructServiceImplementation()
at Microsoft.SqlServer.Dac.DacServices.CreatePackageToDatabaseDeployment(SqlConnectionFactory connectionFactory, IPackageSource packageSource, String
targetDatabaseName, DacDeployOptions options, ErrorManager errorManager)
at Microsoft.SqlServer.Dac.DeployOperation.<>c__DisplayClass3.<>c__DisplayClass5.<CreatePlanInitializationOperation>b__1()
at Microsoft.Data.Tools.Schema.Sql.Dac.OperationLogger.Capture(Action action)
at Microsoft.SqlServer.Dac.DeployOperation.<>c__DisplayClass3.<CreatePlanInitializationOperation>b__0(Object operation, CancellationToken token)
at Microsoft.SqlServer.Dac.Operation.Microsoft.SqlServer.Dac.IOperation.Run(OperationContext context)
at Microsoft.SqlServer.Dac.ReportMessageOperation.Microsoft.SqlServer.Dac.IOperation.Run(OperationContext context)
at Microsoft.SqlServer.Dac.OperationExtension.CompositeOperation.Microsoft.SqlServer.Dac.IOperation.Run(OperationContext context)
at Microsoft.SqlServer.Dac.OperationExtension.CompositeOperation.Microsoft.SqlServer.Dac.IOperation.Run(OperationContext context)
at Microsoft.SqlServer.Dac.DeployOperation.Microsoft.SqlServer.Dac.IOperation.Run(OperationContext context)
--- End of inner exception stack trace ---
at Microsoft.SqlServer.Dac.DeployOperation.Microsoft.SqlServer.Dac.IOperation.Run(OperationContext context)
at Microsoft.SqlServer.Dac.OperationExtension.Execute(IOperation operation, DacLoggingContext loggingContext, CancellationToken cancellationToken)
at Microsoft.SqlServer.Dac.DacServices.InternalDeploy(IPackageSource packageSource, Boolean isDacpac, String targetDatabaseName, DacDeployOptions options,
CancellationToken cancellationToken, DacLoggingContext loggingContext, Action`3 reportPlanOperation, Boolean executePlan)
at Microsoft.SqlServer.Dac.DacServices.Deploy(DacPackage package, String targetDatabaseName, Boolean upgradeExisting, DacDeployOptions options, Nullable`1
cancellationToken)
at CallSite.Target(Closure , CallSite , Object , Object , String , String )
--- End of inner exception stack trace ---
at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)
at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)
at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
If your SQL Server is using Windows Authentication you need to indicate that in your connection string:
$dacService = new-object Microsoft.SqlServer.Dac.DacServices "server=localhost;Integrated Security=True;"
We are in a situation where some of our connections are timing out (possibly), we need to handle the code in certain way if the connection to SQL timesout, I know that command timeouts can easily be simulated by using WAITFORDELAY but how would you simulate a connection timeout ?
I just managed to simulate a connection time out
1st execute the following query on your sql server (I did it in ssms)
ALTER DATABASE my_Test_DB SET SINGLE_USER;
Fired up the following code from Visual Studio
namespace TimeOut_Test_Project_ASP
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string cs = "Data Source=ServerName;Initial Catalog=my_Test_DB; Integrated Security=SSPI;Connect Timeout=3";
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("SELECT * FROM dbo.TableName", con);
con.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
}
}
}
}
Error Stack
Server Error in '/' Application.
The wait operation timed out
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ComponentModel.Win32Exception: The wait operation timed out
Stack Trace:
[Win32Exception (0x80004005): The wait operation timed out]
[SqlException (0x80131904): Connection Timeout Expired. The timeout period elapsed during the post-login phase. The connection could have timed out while waiting for server to complete the login process and respond; Or it could have timed out while attempting to create multiple active connections. The duration spent while attempting to connect to this server was - [Pre-Login] initialization=309; handshake=1; [Login] initialization=0; authentication=1; [Post-Login] complete=2002; ]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +5340655
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +244
System.Data.SqlClient.TdsParserStateObject.ReadSniError(TdsParserStateObject stateObj, UInt32 error) +601
System.Data.SqlClient.TdsParserStateObject.ReadSniSyncOverAsync() +256
System.Data.SqlClient.TdsParserStateObject.TryReadNetworkPacket() +39
System.Data.SqlClient.TdsParserStateObject.TryPrepareBuffer() +64
System.Data.SqlClient.TdsParserStateObject.TryReadByte(Byte& value) +86
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +222
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +69
System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) +30
System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) +317
System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) +891
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, SessionData reconnectSessionData) +518
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +278
System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) +38
System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) +732
System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) +85
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) +1057
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 oldConnection, DbConnectionInternal& connection) +196
System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +146
System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +16
System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry) +94
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +110
System.Data.SqlClient.SqlConnection.Open() +96
First_Project_ASP._Default.Page_Load(Object sender, EventArgs e) in D:\c# Projects\First Project ASP\First Project ASP\Default.aspx.cs:22
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
System.Web.UI.Control.OnLoad(EventArgs e) +92
System.Web.UI.Control.LoadRecursive() +54
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +772
Set back your database to multi-use mode
ALTER DATABASE [my_Test_DB] SET MULTI_USER;
After seeing this comment, I had the idea to try connecting to the wrong host, and it works.
Keep the username, DB, etc. as normal, but change the "host" parameter to be a valid URL/IP that you have control of, but such that the username and password won't work.
The connection will time out.
This way, you don't have to ALTER your database in any way, so it's really nice.
It might also work to use other incorrect connection parameters, like the database name.
You can also try setting the timeout to one second and see if it then throws the timeout exception. Note that 1 is as low a value as you can set. Add to your connection string "Connection Timeout=1;". Note that this is a CONNECTION timeout, not a query timeout which is a different thing altogether and not set in the connection string. Note that this may or may not work to actually simulate it if the connection is made in under 1 second.
I have also tried just disconnecting the network cable from my dev machine just before trying to make the connection.
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).