I have developed a web app in MVC 5 with the Database First approach.
When hosting the app I get an error "Generating user instances in SQL Server is disabled. Use sp_configure 'user instances enabled' to generate user instances."
The thing is that this only happens when I host the application on the server. When ran locally there are no errors. I am not sure what is causing this error as I am using an online database connection,not local mdf file. From what research I've done on this error I can only find examples where people have used a local database.
Below is the web.config connection string:
<connectionStrings>
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=***.***.***.**,1434;Initial Catalog=tsp13amp_tsp136;User Id=******;Password=******;MultipleActiveResultSets=True;" />
<add name="TSPEntities" providerName="System.Data.EntityClient" connectionString="metadata=res://*/Models.TSPEntities.csdl|res://*/Models.TSPEntities.ssdl|res://*/Models.TSPEntities.msl;provider=System.Data.SqlClient;provider connection string="Data Source=***.***.***.**,1434;Initial Catalog=tsp13amp_tsp136;User Id=******;Password=******;MultipleActiveResultSets=True;App=EntityFramework"" />
And the stacktrace as I can't seem to make head or tails of it:
[SqlException (0x80131904): Generating user instances in SQL Server is disabled. Use sp_configure 'user instances enabled' to generate user instances.]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +6568558
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +717
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +4515
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +84
System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) +53
System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) +368
System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) +6597311
System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) +6597891
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData) +942
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +816
System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions) +61
System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) +953
System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +6605639
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.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) +98
[HttpException (0x80004005): Unable to connect to SQL Server database.]
System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) +4572298
System.Web.Management.SqlServices.SetupApplicationServices(String server, String user, String password, Boolean trusted, String connectionString, String database, String dbFileName, SqlFeatures features, Boolean install) +229
System.Web.DataAccess.SqlConnectionHelper.CreateMdfFile(String fullFileName, String dataDir, String connectionString) +908
Thanks for any help with this.
It's is possible this feature is disabled on the server, use following script on the database server to activate it:
EXEC sp_configure 'user instances enabled', 1;
RECONFIGURE;
Related
I'm trying to create a new SQL server database but its not working.
I'm using aspnet_regsql.exe.
I use these 'Server name' and 'Database name':
Server name: .\sqlexpress
Database name: <default>
This is my error:
Setup failed.
Exception:
Unable to connect to SQL Server database.
----------------------------------------
Details of failure
----------------------------------------
System.Web.HttpException (0x80004005): Unable to connect to SQL Server database. ---> System.Data.SqlClient.SqlException (0x80131904): Login failed for user 'Arad\Arad'. Reason: Server is in single user mode. Only one administrator can connect at this time.
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK)
at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.Open()
at System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString)
ClientConnectionId:a468a12c-632a-43d0-be32-a0a30e4fb5c1
at System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString)
at System.Web.Management.SqlServices.SetupApplicationServices(String server, String user, String password, Boolean trusted, String connectionString, String database, String dbFileName, SqlFeatures features, Boolean install)
at System.Web.Management.ConfirmPanel.Execute()
If you could tell me how to resolve this issue, I'll be glad! Thanks!
From viewing your Stack Trace
Reason: Server is in single user mode. Only one administrator can connect at this time.
it looks like your SQL Server instance is in single user mode. Take a look at this article where the author explains how to remove your server from single user mode.
To respond to your comment below, the article I provided suggests running those queries in SQL Server Management Studio. From the stack trace provided, I believe that when you login to your database server with SSMS that you will see (Single User) next to your database, like this:
You should select the "master" database from your databases drop-down list and execute the queries that are referenced within the article. Does this make sense?
I have created a website in which I am authenticating user as per the user and password present in the database. It was working fine until I uploaded on the IIS server.
I am getting the following error.
Server Error in '/' Application.
--------------------------------------------------------------------------------
The database 'C:\INETPUB\WWWROOT\WEBSITE11\APP_DATA\ASPNETDB.MDF' cannot be opened because it is version 655. This server supports version 612 and earlier. A downgrade path is not supported.
Could not open new database 'C:\INETPUB\WWWROOT\WEBSITE11\APP_DATA\ASPNETDB.MDF'. CREATE DATABASE is aborted.
An attempt to attach an auto-named database for file C:\inetpub\wwwroot\WebSite11\App_Data\aspnetdb.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
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.Data.SqlClient.SqlException: The database 'C:\INETPUB\WWWROOT\WEBSITE11\APP_DATA\ASPNETDB.MDF' cannot be opened because it is version 655. This server supports version 612 and earlier. A downgrade path is not supported.
Could not open new database 'C:\INETPUB\WWWROOT\WEBSITE11\APP_DATA\ASPNETDB.MDF'. CREATE DATABASE is aborted.
An attempt to attach an auto-named database for file C:\inetpub\wwwroot\WebSite11\App_Data\aspnetdb.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
Source Error:
Line 16: {
Line 17: // Verify that the username/password pair is valid
Line 18: if (Membership.ValidateUser(Login1.UserName, Login1.Password))
Line 19: {
Line 20: e.Authenticated = true;
Source File: c:\inetpub\wwwroot\WebSite11\LoginPage.aspx.cs Line: 18
Stack Trace:
[SqlException (0x80131904): The database 'C:\INETPUB\WWWROOT\WEBSITE11\APP_DATA\ASPNETDB.MDF' cannot be opened because it is version 655. This server supports version 612 and earlier. A downgrade path is not supported.
Could not open new database 'C:\INETPUB\WWWROOT\WEBSITE11\APP_DATA\ASPNETDB.MDF'. CREATE DATABASE is aborted.
An attempt to attach an auto-named database for file C:\inetpub\wwwroot\WebSite11\App_Data\aspnetdb.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +6675958
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +688
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +4403
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +84
System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) +55
System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) +368
System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) +6704598
System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) +6705099
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions) +610
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +1049
System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) +74
System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnectionOptions userOptions) +6707667
System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnectionOptions userOptions) +78
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) +2192
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +116
System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +1012
System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +6712291
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +152
System.Data.SqlClient.SqlConnection.Open() +229
System.Web.DataAccess.SqlConnectionHolder.Open(HttpContext context, Boolean revertImpersonate) +150
System.Web.DataAccess.SqlConnectionHelper.GetConnection(String connectionString, Boolean revertImpersonation) +4880234
System.Web.Security.SqlMembershipProvider.GetPasswordWithFormat(String username, Boolean updateLastLoginActivityDate, Int32& status, String& password, Int32& passwordFormat, String& passwordSalt, Int32& failedPasswordAttemptCount, Int32& failedPasswordAnswerAttemptCount, Boolean& isApproved, DateTime& lastLoginDate, DateTime& lastActivityDate) +3888545
System.Web.Security.SqlMembershipProvider.CheckPassword(String username, String password, Boolean updateLastLoginActivityDate, Boolean failIfNotApproved, String& salt, Int32& passwordFormat) +186
System.Web.Security.SqlMembershipProvider.ValidateUser(String username, String password) +195
LoginPage.Login1_Authenticate(Object sender, AuthenticateEventArgs e) in c:\inetpub\wwwroot\WebSite11\LoginPage.aspx.cs:18
System.Web.UI.WebControls.Login.AttemptLogin() +160
System.Web.UI.WebControls.Login.OnBubbleEvent(Object source, EventArgs e) +93
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +84
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3804
--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18067
I tried to search that i need to downgrade the version of the database but dont know how exactly. I have sql-server 2008.
I dont have the liberty to create the entire database into the downgrade instance.
You need to create a script for database and then create that database in SQL Server where you want to use this. Here is the reference link for that.
http://www.mssqltips.com/sqlservertip/2810/how-to-migrate-a-sql-server-database-to-a-lower-version/
I am attempting to deploy an asp.net application to a Windows Server 2012 server and have come across an issue where the application will no longer connect to a localdb server on SQL Server 2012. I am able to access the localdb database in Microsoft SQL Server Management Studio, the database explorer will connect, and I copied the connection string from the properties of the connection into the Web.Config file replacing the asterisks with the actual password. Even though the connection is possible I still can't get it to connect.
The connection string in the Web.Config (Replacing the user id and password with actual values) is:
<add name="ApplicationServices"
connectionString="Data Source=(localdb)\v11.0;Initial Catalog=Grouplink;Integrated Security=False;User ID=******;Password=*********;"
providerName="System.Data.SqlClient" />
The exception details are as follows:
System.Data.SqlClient.SqlException was caught
Class=14
ErrorCode=-2146232060
HResult=-2146232060
LineNumber=65536
Message=Login failed for user 'sa'.
Number=18456
Procedure=""
Server=(localdb)\v11.0
Source=.Net SqlClient Data Provider
State=1
StackTrace:
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK)
at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.Open()
at GroupLinkMembership.SQLNet.GetTable(String TableName, String Cmd) in C:\Users\Administrator\Documents\GroupLinkMembership\GroupLinkMembership\SQLNet.vb:line 20
InnerException:
The application worked on the development system so I do not know why the code is not working while the other access methods do work. The exception occurs when attempting to open the connection.
Seems like localdb\v11.0 does not exist on the other computer, replace the "(localdb)\v11.0" with applicable "{servername}{SQLServerInstanceName}" in connection string without curly braces in my text.
In my site, I am trying to loop through a list view and insert information into my database. However, when I run the site, I get
Cannot open user default database. Login failed. Login failed for
user.... (my user name)
The only thing is, on another page that I have an insert command, it works fine, and I am able to access data from the database without any issues.
The code that I am attempting to use is:
Guid InsertID = System.Guid.NewGuid();
String connectionString = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString;
var myConnection = new SqlConnection(connectionString);
SqlCommand insertCMD = new SqlCommand("INSERT INTO Orders (Order_ID, Item_ID, QTY, Price_Per_Unit, Total_Price) VALUES (#Order_ID, #Item_ID, #QTY, #Price_Per_Unit, #Total_Price)", myConnection);
insertCMD.Connection.Open();
foreach (ListViewItem item in ItemLV.Items)
{
TextBox QTY = (TextBox)item.FindControl("QTYTB");
int InsertQTY = int.Parse(QTY.Text);
if (InsertQTY > 0)
{
Label Price = (Label)item.FindControl("PriceLabel");
HiddenField ItemID = (HiddenField)item.FindControl("IDHF");
Decimal InsertPrice = Decimal.Parse(Price.Text.Substring(1));
Guid InsertItemID = Guid.Parse(ItemID.Value);
Decimal InsertTotalPrice = InsertPrice * InsertQTY;
insertCMD.Parameters.Clear();
insertCMD.Parameters.AddWithValue("#Order_ID", InsertID);
insertCMD.Parameters.AddWithValue("#Item_ID", InsertItemID);
insertCMD.Parameters.AddWithValue("#QTY", InsertQTY);
insertCMD.Parameters.AddWithValue("#Price_Per_Unit", InsertPrice);
insertCMD.Parameters.AddWithValue("#Total_Price", InsertTotalPrice);
try
{
insertCMD.ExecuteNonQuery();
}
catch
{
Response.Redirect("~/Order/Error.aspx");
}
finally
{
}
}
}
insertCMD.Connection.Close();
This code throws me the error outlined above, yet, on my registration page (using the same code as this less the 'foreach' loop and with a different command and parameters), it works without an issue. So, I am assuming it isn't really to do with my user not having access to the database, but perhaps a problem with my code.
The stack trace is as follows:
[SqlException (0x80131904): Cannot open user default database. Login
failed. Login failed for user (my user account).]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
exception, Boolean breakConnection, Action1 wrapCloseInAction)
+5295167 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +242
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior,
SqlCommand cmdHandler, SqlDataReader dataStream,
BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject
stateObj, Boolean& dataReady) +1682
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) +889
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) +225
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, TaskCompletionSource1 retry, DbConnectionOptions
userOptions, DbConnectionInternal& connection) +78
System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection
owningConnection, TaskCompletionSource1 retry, DbConnectionOptions
userOptions, DbConnectionInternal& connection) +167
System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection
outerConnection, DbConnectionFactory connectionFactory,
TaskCompletionSource1 retry, DbConnectionOptions userOptions) +143
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1
retry) +83 System.Data.SqlClient.SqlConnection.Open() +96
Order_Order.ContinueBTN_Click(Object sender, EventArgs e) in
m:\OrderingSystem\Order\Order.aspx.cs:36
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9553594
System.Web.UI.WebControls.Button.RaisePostBackEvent(String
eventArgument) +103
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String
eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler
sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
+35 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
+1724
EDIT:
My connection string in my web.config file is:
<connectionStrings>
<clear />
<add name="LocalSqlServer" connectionString="Data Source=.\WebSite2013;AttachDbFilename=|DataDirectory|\Ordering_System_Database.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
and the working code from my registration page is:
String connectionString = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString;
var myConnection = new SqlConnection(connectionString);
SqlCommand insertUser = new SqlCommand("INSERT INTO Customer_Profiles(UID, First_Name, Last_Name, State_ID, Country_ID, Phone_Number, Mobile_Number, Date_of_Birth) VALUES(#UID, #First_Name, #Last_Name, #State_ID, #Country_ID, #Phone_Number, #Mobile_Number, #Date_of_Birth)", myConnection);
insertUser.Parameters.AddWithValue("#UID", newUserGuid);
insertUser.Parameters.AddWithValue("#First_Name", FirstNameTB.Text);
insertUser.Parameters.AddWithValue("#Last_Name", LastNameTB.Text);
insertUser.Parameters.AddWithValue("#State_ID", StateDDL.SelectedValue);
insertUser.Parameters.AddWithValue("#Country_ID", CountryDDL.SelectedValue);
if (PhoneTB.Text.Length > 0)
{
insertUser.Parameters.AddWithValue("#Phone_Number", PhoneTB.Text);
}
else
{
insertUser.Parameters.AddWithValue("#Phone_Number", DBNull.Value);
}
if (MobileTB.Text.Length > 0)
{
insertUser.Parameters.AddWithValue("#Mobile_Number", MobileTB.Text);
}
else
{
insertUser.Parameters.AddWithValue("#Mobile_Number", DBNull.Value);
}
insertUser.Parameters.AddWithValue("#Date_of_Birth", BirthDay);
try
{
insertUser.Connection.Open();
insertUser.ExecuteNonQuery();
insertUser.Connection.Close();
}
catch
{
Response.Redirect("~/Error.aspx");
}
}
I have since experimented a bit and added test select and insert queries and discovered that it seems to be only for this page that the errors are occurring, no matter what query I use, yet on all the other pages in my website it will work fine.
Thanks to those who helped, I managed to determine that the problem was actually the connection strings being used by my ListViews - it was attaching my database as a local database instead of using my server instance as it does in the web.config file.
For anyone in the future with this issue, check that any SqlDataSources implemented on your page use the same connection string as that in your web.config file - I have now done this:
ConnectionString="<%$ ConnectionStrings:LocalSqlServer %>"
And the way you'll be able to tell if it is something to do with the page and not the database, is because it will only happen on one page or certain pages (as it did for me).
I am using Entity Framework in ASP.Net project. It works fine in development server. But it throws exceptions in IIS 7. I am using SQL Server 2008 Enterprise as the backend.
Entity Framework Connection String in the web.config follows
<connectionStrings>
<add name="NorthwindEntities" connectionString="metadata=res://*/App_Code.Model.csdl|res://*/App_Code.Model.ssdl|res://*/App_Code.Model.msl;provider=System.Data.SqlClient;provider connection string="Data Source=GIRI-PC\GIRISQL2008;Initial Catalog=Northwind;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
</connectionStrings>
The error I get in iis 7 is:
System.Data.EntityException: The underlying provider failed on Open. ---> System.Data.SqlClient.SqlException: Login failed for user 'IIS APPPOOL\DefaultAppPool'.
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK)
at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, SqlConnection owningObject)
at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, TimeoutTimer timeout)
at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, TimeoutTimer timeout, 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 System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure)
--- End of inner exception stack trace ---
at System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure)
at System.Data.EntityClient.EntityConnection.Open()
at _Default.btn_submit_Click(Object sender, EventArgs e)
Do you have any idea about this problem?
More clearly: SQL Server client could make contact with the specified instance of SQL Server ("GIRI-PC\GIRISQL2008").
This could be:
Lack of a common protocol
Need to specify a different TCP port for IP
Server instance is not listening on the network port your connection is using
Host name could not be resolved (or is wrong)
Instance name is wrong
The specific problem is Login failed for user 'IIS APPPOOL\DefaultAppPool. Sounds like you need to properly configure either; your app pool to use an account that has access to the database, create a new app pool with an account that has access to the database, or allow the DefaultAppPool identity to access the database.
The Database Server the website is trying to access is GIRI-PC\GIRISQL2008. If that is not correct you'll need to; update your web.config to point to the correct Sql Server (and instance) or create web.config transformations (preferred) to keep your development settings and deployment settings (dev, test, stage, prod) seperated.