Why can't I see a localdb database created by a UWP (Desktop Bridge App) in the SQL Server Object Explorer? - entity-framework-6

Does UWP support LocalDB?
My investigations indicate there are some issues using localdb that I don't experience with SQL Server 2017 Development edition.
I managed to convert a winforms EF-Code First, xaf application to run as a UWP app with the help of this blog
I have Enterprise Authentication set.
When I run the desktop bridge app it creates the database and log file inside
c:\users\kirst
which is my user folder.
However I cannot see the new database in the SQL Server Object Explorer
Clicking Refresh does not help.
A similar app that does not use the desktop bridge will also create the database inside my user directory. In this case I can also see the database in the SQL Server Object Explorer , (localdb)\MSSQLLocalDB
In both cases the connection string is of the form
"Integrated Security=SSPI;MultipleActiveResultSets=True;Data Source=(localdb)\mssqllocaldb;Initial Catalog=mydatabase"
and
providerName="System.Data.SqlClient"/>
I am using Entity Framework 6.2
.Net Framework 4.7.2
UWP Target Version and Min Version 1809 Build 17763
I am running in the VS2017 15.9.4 IDE
At a dos prompt in c:\Program files\Microsoft SQL Server
dir sqlservr.exe /s shows 2 files
one at
c:\Program files\Microsoft SQL Server\130\LocalDB\Binn
and one at
c:\Program files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\MSSQL\Binn
When I query ##Version from within the program, in both cases I see
Microsoft SQL Server 2016 (SP1) (KB3182545) - 13.0.4001.0 (X64)
Oct 28 2016 18:17:30 Copyright (c) Microsoft Corporation
Express Edition (64-bit) on Windows 10 Pro 6.3 <X64>
(Build 17763: ) (Hypervisor)
I experience problems if I try to connect to the database created by my UWP App from my non UWP Program
For example this message about a log file in a folder that does not exist.
This issue is linked
[Update1]
I set up a simple demo of the problem on Github
Set the Startup project to WAPProjThings (The Desktop Bridge) to run it.
In the demo ,if I create the database via the Bridge App as startup then switch to the console app to run, I get
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in EntityFramework.dll
Additional information: Cannot create file 'C:\Users\kirst\Things02.mdf' because it already exists. Change the file path or the file name, and retry the operation.
CREATE DATABASE failed. Some file names listed could not be created. Check related errors. occurred
If I create the database using the Console App and then try and open it with the Bridge app the error is
`System.Data.SqlClient.SqlException
HResult=0x80131904
Message=Cannot create file 'C:\Users\kirst\Things03.mdf' because it already exists. Change the file path or the file name, and retry the operation.
CREATE DATABASE failed. Some file names listed could not be created. Check related errors.
Source=.Net SqlClient Data Provider
StackTrace:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
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.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand t, DbCommandInterceptionContext`1 c)
at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
at System.Data.Entity.SqlServer.SqlProviderServices.<>c__DisplayClass1a.<CreateDatabaseFromScript>b__19(DbConnection conn)
at System.Data.Entity.SqlServer.SqlProviderServices.<>c__DisplayClass33.<UsingConnection>b__32()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation)
at System.Data.Entity.SqlServer.SqlProviderServices.UsingConnection(DbConnection sqlConnection, Action`1 act)
at System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action`1 act)
at System.Data.Entity.SqlServer.SqlProviderServices.CreateDatabaseFromScript(Nullable`1 commandTimeout, DbConnection sqlConnection, String createDatabaseScript)
at System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(DbConnection connection, Nullable`1 commandTimeout, StoreItemCollection storeItemCollection)
at System.Data.Entity.Core.Common.DbProviderServices.CreateDatabase(DbConnection connection, Nullable`1 commandTimeout, StoreItemCollection storeItemCollection)
at System.Data.Entity.Core.Objects.ObjectContext.CreateDatabase()
at System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(DbConnection connection)
at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
at System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext internalContext, Func`3 createMigrator, ObjectContext objectContext)
at System.Data.Entity.Internal.InternalContext.CreateDatabase(ObjectContext objectContext, DatabaseExistenceState existenceState)
at System.Data.Entity.Database.Create(DatabaseExistenceState existenceState)
at System.Data.Entity.CreateDatabaseIfNotExists`1.InitializeDatabase(TContext context)
at System.Data.Entity.Internal.InternalContext.<>c__DisplayClassf`1.<CreateInitializationAction>b__e()
at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
at System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c)
at System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action)
at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
at System.Data.Entity.Internal.InternalContext.Initialize()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
at System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable`1 source)
at ClassLibrary2.ThingFuncs.ThingDo() in C:\dev\Things\ClassLibrary2\ThingFuncs.cs:line 11
at Things.Form1.Form1_Load(Object sender, EventArgs e) in C:\dev\Things\Things\Form1.cs:line 23
at System.Windows.Forms.Form.OnLoad(EventArgs e)
at System.Windows.Forms.Form.OnCreateControl()
at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
at System.Windows.Forms.Control.CreateControl()
at System.Windows.Forms.Control.WmShowWindow(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.Form.WmShowWindow(Message& m)
at System.Windows.Forms.Form.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
`I
[Update2]
I tried to investigate whether a new UWP app - non desktop bridge had the same issue.
To do this I created a solution containing UWP app and a Framework 4.7.2 library.
Nuget let me add Entity Framework 6.2 to both projects. However when I tried to add a reference the library from the UWP I got a message
Unable to add a reference to project
followed by
The method or operation is not implemented
Then I got the Warning
Warning NU1701 Package 'EntityFramework 6.2.0' was restored using '.NETFramework,Version=v4.6.1'
instead of the project target framework 'UAP,Version=v10.0.17134'.
This package may not be fully compatible with your project. App1 C:\dev\XThings2\App1\App1.csproj
[Update3]
I created a new UWP App with a UWP Class library to hold an Entity Framework Core Data Access layer.
However when I tried to run that I got an error indicating that
LocalDB is not supported on this platform.
System.PlatformNotSupportedException: LocalDB is not supported on this platform.
at System.Data.SqlClient.SNI.LocalDB.GetLocalDBConnectionString(String localDbInstance)
at System.Data.SqlClient.SNI.SNIProxy.GetLocalDBDataSource(String fullServerName, Boolean& error)
at System.Data.SqlClient.SNI.SNIProxy.CreateConnectionHandle(Object callbackObject, String fullServerName, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Byte[]& instanceName, Byte[]& spnBuffer, Boolean flushCache, Boolean async, Boolean parallel, Boolean isIntegratedSecurity)
at System.Data.SqlClient.SNI.TdsParserStateObjectManaged.CreatePhysicalSNIHandle(String serverName, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Byte[]& instanceName, Byte[]& spnBuffer, Boolean flushCache, Boolean async, Boolean parallel, Boolean isIntegratedSecurity)
at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover)
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, Boolean applyTransientFaultHandling, String accessToken)
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.TryOpen(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.Open()
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnection(Boolean errorsExpected)
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.BeginTransaction(IsolationLevel isolationLevel)
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.BeginTransaction()
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(DbContext _, ValueTuple`2 parameters)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable`1 commandBatches, IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Storage.RelationalDatabase.SaveChanges(IReadOnlyList`1 entries)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList`1 entriesToSave)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.DbContext.SaveChanges()
at Data.ThingFuncs.ThingDo()
[Update4]
Back in my original program I have discovered that create database behaviour of the UWP app is different when running in release mode to running in debug mode.
When running in Release Mode via the Bridge Project CheckDatabaseCompatibility does not trigger the xaf DatabaseVersionMismatch event. When running in Release mode in the console project it does. ( This particular behavior occurs for SQL Server Developer edition as well ) Possibly I should write it up as a separate question, but I mention it here in case it is linked.

I have come to the conclusion that localdb is not a supported version of SQL Server for production.
As explained here
LocalDB is a special, low impact version of the SQL Server engine, that is not installed as a Windows Service, but launched (made to run) on demand by the ADO.NET client opening a connection to it. It is intended for single user scenarios, and not for any prodcution use - for production you should use SQL Server Express (or higher)

There is a method to connect UWP to a localdb, you have to use the winforms sql data factory method the issues is although you have access to System.Data.SQLClient, you do not have SqlDataAdapter so you cannot create a user login system. However you can read data from the database and create ObservableCollections. To save you time Adapter Client doesn't work either. I think we have to wait for another update where the all the SQL libraries have been added.

Related

Asp.net MVC site deployed to Microsoft Azure Web Sites throws error

I'm using Visual Studio 2015 Update 3.
I have ASP.NET MVC 4 website. Target framework: .NET Framework 4.5. The site have its own database. The site works locally and interacts with database ((LocalDb)\v11.0).
Then I deployed the site to Azure Web Sites through VS using Publish button. Web App was published successfully. But I'm unable to open it in browser. I receive the following error in browser:
Server Error in '/' Application.
The system cannot find the file specified
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 system
cannot find the file specified
Source Error:
An unhandled exception was generated during the execution of the
current web request. Information regarding the origin and location of
the exception can be identified using the exception stack trace below.
Stack trace:
[Win32Exception (0x80004005): The system cannot find the file specified]
[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: 52 - Unable to locate a Local Database Runtime installation. Verify that SQL Server Express is properly installed and that the Local Database Runtime feature is enabled.)]
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) +1000
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +800
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) +741
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) +451
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +108
System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) +943
System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +143
System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +22
System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry) +139
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +367
System.Data.SqlClient.SqlConnection.Open() +129
WebMatrix.Data.Database.EnsureConnectionOpen() +47
WebMatrix.Data.<QueryInternal>d__0.MoveNext() +67
System.Linq.Enumerable.FirstOrDefault(IEnumerable`1 source) +183
WebMatrix.Data.Database.QuerySingle(String commandText, Object[] args) +98
WebMatrix.WebData.DatabaseWrapper.QuerySingle(String commandText, Object[] parameters) +19
WebMatrix.WebData.SimpleMembershipProvider.CheckTableExists(IDatabase db, String tableName) +54
WebMatrix.WebData.SimpleMembershipProvider.CreateTablesIfNeeded() +50
WebMatrix.WebData.WebSecurity.InitializeMembershipProvider(SimpleMembershipProvider simpleMembership, DatabaseConnectionInfo connect, String userTableName, String userIdColumn, String userNameColumn, Boolean createTables) +71
WebMatrix.WebData.WebSecurity.InitializeProviders(DatabaseConnectionInfo connect, String userTableName, String userIdColumn, String userNameColumn, Boolean autoCreateTables) +51
WebMatrix.WebData.WebSecurity.InitializeDatabaseConnection(String connectionStringName, String userTableName, String userIdColumn, String userNameColumn, Boolean autoCreateTables) +55
OnlineAuction.MvcApplication.SetSecurityOptions() +60
OnlineAuction.MvcApplication.Application_Start() +51
[HttpException (0x80004005): 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: 52 - Unable to locate a Local Database Runtime installation. Verify that SQL Server Express is properly installed and that the Local Database Runtime feature is enabled.)]
System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) +477
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +118
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +176
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +350
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +303
[HttpException (0x80004005): 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: 52 - Unable to locate a Local Database Runtime installation. Verify that SQL Server Express is properly installed and that the Local Database Runtime feature is enabled.)]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +657
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +96
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +189
Here is my DB connection string in Web.config:
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=OnlineAuctionDb;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\OnlineAuctionDb.mdf" providerName="System.Data.SqlClient"/>
I uploaded entire Web.config file to DropBox
Is it a problem with database or not? I have published the whole site by using Publish button in VS. But may be database is not attached to the cloud web app? I'm not sure. If the problem is in missing database how can I publish database associated with the website so they work together?
The problem is definitely that the website can't find or communicate with the database. There are several ways to do this, but you will need to figure out how you want your database to be hosted - it looks like you're using SQL, so your options are:
SQL Express/LocalDB on the instance that your website is running on
Azure SQL DB (which will be hosted in azure and accessible by your website)
SQL Server hosted in VMs in Azure
Another SQL database hosted elsewhere (on premises maybe) and can be accessed by a hybrid connection
I'd recommend option 2, since it gives you a managed solution out of the box that can scale with your app, but is network addressable, so multiple instances of your web app can share it, it's backed up automatically, etc. etc.
Perhaps share some more information on what you've got already or what you have in mind you're trying to achieve?

SessionState server not working in WebForm inside MVC app

I have a MVC4 app that is using a ReportViewer control on a aspx page inside a iframe in my razor view. I followed this answer here: https://stackoverflow.com/a/11055132/876511.
Well this worked ok on localhost but it doesn't when i deploy to server.
First error i got was solved by setting the "Copy Local" property to true of the Microsoft.ReportViewer.WebForms Reference.
Than I got this error on server: "Could not load file or assembly 'Microsoft.ReportViewer.Common". For that i manually copied the dll from "C:\windows\assembly\GAC_MSIL\Microsoft.ReportViewer.Common\11.0.0.0__89845dcd8080cc91" to the bin directory on server.
But now i'm getting this error that i can't figure it out:
[Win32Exception (0x80004005): The network path was not found]
[SqlException (0x80131904): A network-related or instance-specific
error occurred while establishing a connection to SQL Server. The
server was not found or was not accessible. Verify that the instance
name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)] System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection
owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean
allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions
userOptions, DbConnectionInternal& connection) +414
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(TaskCompletionSource1
retry) +83 System.Data.SqlClient.SqlConnection.Open() +96
System.Web.SessionState.SqlStateConnection..ctor(SqlPartitionInfo
sqlPartitionInfo, TimeSpan retryInterval) +110
[HttpException (0x80004005): Unable to connect to SQL Server session
database.]
System.Web.SessionState.SqlSessionStateStore.ThrowSqlConnectionException(SqlConnection
conn, Exception e) +235
System.Web.SessionState.SqlStateConnection..ctor(SqlPartitionInfo
sqlPartitionInfo, TimeSpan retryInterval) +944
System.Web.SessionState.SqlSessionStateStore.GetConnection(String id,
Boolean& usePooling) +231
System.Web.SessionState.SqlSessionStateStore.SetAndReleaseItemExclusive(HttpContext
context, String id, SessionStateStoreData item, Object lockId, Boolean
newItem) +199
System.Web.SessionState.SessionStateModule.OnReleaseState(Object
source, EventArgs eventArgs) +798
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+136 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +69
What network path? The SQL Server? The rest of the app gets there fine.
Please help me, i have been stuck here for a few days and have no more ideias.
EDIT:
Found out where the error is. In my web.config.release i have this:
<sessionState mode="SQLServer" sqlConnectionString="Data Source=SQLSERVER;User ID=ASPState;Password=XXXXXXX" timeout="120" xdt:Transform="Replace"/>
When i comment out the reportViewer works, otherwise it gives network error. Somethings wrong, probably with the conn string, not sure what.
EDIT2:
Conn string is fine otherwise would not work on the intire app.
My new guess is because its a mix of MVC and Webforms...
The mvc connects ok to the sessionstate server but my webform doesnt. Why?
try
ReportViewerRSFReports.ProcessingMode = ProcessingMode.Remote;
ReportViewerRSFReports.ServerReport.ReportServerCredentials = new CustomReportCredentials("user", "pass", "domain");
ReportViewerRSFReports.ServerReport.ReportServerUrl = new Uri("http://<Server Name>/ReportServer");
ReportViewerRSFReports.ServerReport.ReportPath = "/MYAPP/test";
ReportViewerRSFReports.ServerReport.Refresh();
Replace reportserver.mydomain with your ReportServer.
To a vaoid errors, i normally get the report server url and report path from BID out put windows during report deployment.

TFS 2010 restored database, TfsJobAgent cannot connect to database

I have a Team Foundation Server 2010 setup, in which I have TFS on one server and the databases on another. Recently the server with the databases completely crashed and I had to replace it. I restored the databases from backups, and changed the web.config file for tfs to point to the new server and most everything seems to be working. I can connect to tfs, do checkouts/checkins, create work items, etc. However, I cannot queue builds, and the event log is filling up with errors saying that TfsJobAgent cannot connect to the database. I was wondering if anyone knew if there was a way to configure TfsJobAgent to point to my new database. The event log details are below (TCOSRV1 is the machine running tfs, not the database server). Any help would be greatly appreciated.
TF53010: The following error has occurred in a Team Foundation
component or extension: Date (UTC): 7/11/2013 4:55:27 PM Machine:
TCOSRV1 Application Domain: TfsJobAgent.exe Assembly:
Microsoft.TeamFoundation.Framework.Server, Version=10.0.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a; v2.0.50727 Service
Host: Process Details: Process Name: TFSJobAgent Process Id: 3520
Thread Id: 5304 Account name: NT AUTHORITY\NETWORK SERVICE
Detailed Message: There was an error during job agent execution. The
operation will be retried. Similar errors in the next five minutes may
not be logged. Exception Message: TF246017: Team Foundation Server
could not connect to the database. Verify that the server that is
hosting the database is operational, and that network problems are not
blocking communication with the server. (type
DatabaseConnectionException)
Exception Stack Trace: at
Microsoft.TeamFoundation.Framework.Server.TeamFoundationSqlResourceComponent.TranslateException(Int32
errorNumber, SqlException sqlException, SqlError sqlError) at
Microsoft.TeamFoundation.Framework.Server.TeamFoundationSqlResourceComponent.TranslateException(SqlException
sqlException) at
Microsoft.TeamFoundation.Framework.Server.TeamFoundationSqlResourceComponent.MapException(SqlException
ex, QueryExecutionState queryState) at
Microsoft.TeamFoundation.Framework.Server.TeamFoundationSqlResourceComponent.HandleException(SqlException
ex) at
Microsoft.TeamFoundation.Framework.Server.TeamFoundationSqlResourceComponent.Execute(ExecuteType
executeType, CommandBehavior behavior) at
Microsoft.TeamFoundation.Framework.Server.ExtendedAttributeComponent.ReadDatabaseAttribute(String
attributeName) at
Microsoft.TeamFoundation.Framework.Server.DatabaseConnectionValidator.ValidateDatabaseInstanceStamp(String
configConnectionString, Guid configInstanceId) at
Microsoft.TeamFoundation.Framework.Server.DatabaseConnectionValidator.ValidateApplicationConfiguration(String
configConnectionString, Guid configInstanceId, List`1 sqlInstances,
String analysisInstance, String analysisDatabaseName, Boolean
ignoreAnalysisDatasourceUpdateErrors, Boolean autoFixConfiguration,
Boolean fullValidation, DatabaseVerificationDatabaseTypes
continueOnMissingDatabaseTypes) at
Microsoft.TeamFoundation.Framework.Server.ApplicationServiceHost..ctor(Guid
instanceId, String connectionString, String physicalDirectory, String
plugInDirectory, String virtualDirectory, Boolean
failOnInvalidConfiguration) at
Microsoft.TeamFoundation.Framework.Server.JobApplication.SetupInternal()
at
Microsoft.TeamFoundation.Framework.Server.JobServiceUtil.RetryOperationsUntilSuccessful(RetryOperations
operations)
Inner Exception Details:
Exception Message: 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) (type SqlException) SQL Exception Class: 20
SQL Exception Number: -1 SQL Exception Procedure: SQL Exception Line
Number: 0 SQL Exception Server: SQL Exception State: 0 SQL Error(s):
Exception Data Dictionary: HelpLink.ProdName = Microsoft SQL Server
HelpLink.EvtSrc = MSSQLServer HelpLink.EvtID = -1 HelpLink.BaseHelpUrl
= http://go.microsoft.com/fwlink HelpLink.LinkId = 20476
Exception Stack Trace: at
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
exception, Boolean breakConnection, Action1 wrapCloseInAction) at
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at
System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo,
SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout,
Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean
integratedSecurity, Boolean withFailover) 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, TaskCompletionSource1 retry, DbConnectionOptions
userOptions, DbConnectionInternal& connection) at
System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection
owningConnection, TaskCompletionSource1 retry, DbConnectionOptions
userOptions, DbConnectionInternal& connection) at
System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection
outerConnection, DbConnectionFactory connectionFactory,
TaskCompletionSource1 retry, DbConnectionOptions userOptions) at
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1
retry) at System.Data.SqlClient.SqlConnection.Open() at
Microsoft.TeamFoundation.Framework.Server.TeamFoundationSqlResourceComponent.Execute(ExecuteType
executeType, CommandBehavior behavior)
Restoring to a new Data Tier (as it's called when you move between servers) needs to follow a quite extensive process to ensure that all settings are properly updated. The procedure would be the same for the process you'd use to migrate from one SQL Server to another.
The full process is explained here:
http://msdn.microsoft.com/en-US/library/ms404869(v=vs.100).aspx

asp.net mvc: InitializeSimpleMembershipAttribute throwing exception when app is run from IIS, but works fine when app is run from Visual Studio

I created a asp.net mvc4 web application in Visual Studio. By default it creates a file Filters\InitializeSimpleMembershipAttribute.cs. I am getting an exception on line 34 when this attribute is invoked:
using (var context = new UsersContext())
{
**if (!context.Database.Exists())**
{
// Create the SimpleMembership database without Entity Framework migration schema
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
}
The exception happens when I try to run the webapp through IIS, but does not happen when running the app through visual studio F5 or Ctrl+F5 (VS uses iisexpress I think). The ConnectionString is same in both cases and copied below. Also I have configured the apppool in IIS to run under my identity (to match what happens when app is run through VS).
context.Database.Connection
{System.Data.SqlClient.SqlConnection}
[System.Data.SqlClient.SqlConnection]: {System.Data.SqlClient.SqlConnection}
base {System.ComponentModel.Component}: {System.Data.SqlClient.SqlConnection}
ConnectionString: "Data Source=(LocalDb)\\v11.0;AttachDbFilename=|DataDirectory|\\aspnet-MvcApplication1-20130328112431.mdf;Initial Catalog=aspnet-MvcApplication1-20130328112431;Integrated Security=True;Application Name=EntityFrameworkMUE"
ConnectionTimeout: 15
Database: "aspnet-MvcApplication1-20130328112431"
DataSource: "(LocalDb)\\v11.0"
ServerVersion: 'context.Database.Connection.ServerVersion' threw an exception of type 'System.InvalidOperationException'
State: Closed
I have checked my machine has SQLEXPRESS installed
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (X64)
Mar 29 2009 10:11:52
Copyright (c) 1988-2008 Microsoft Corporation
Express Edition (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1)
(1 row(s) affected)
How can I fix this exception? Exception details in case anyone wants:
Server Error in '/EntityBrowser' Application.
--------------------------------------------------------------------------------
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: 50 - Local Database Runtime error occurred. Error occurred during LocalDB instance startup: SQL Server process failed to start.
)
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: 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: 50 - Local Database Runtime error occurred. Error occurred during LocalDB instance startup: SQL Server process failed to start.
)
Source Error:
Line 32: using (var context = new UsersContext())
Line 33: {
Line 34: if (!context.Database.Exists())
Line 35: {
Line 36: // Create the SimpleMembership database without Entity Framework migration schema
Source File: c:\Users\siddjain\Documents\Visual Studio 2012\Projects\MvcApplication1\Filters\InitializeSimpleMembershipAttribute.cs Line: 34
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: 50 - Local Database Runtime error occurred. Error occurred during LocalDB instance startup: SQL Server process failed to start.
)]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +5295167
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +242
System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover) +5307115
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) +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, 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.Data.SqlClient.SqlProviderServices.UsingConnection(SqlConnection sqlConnection, Action`1 act) +79
System.Data.SqlClient.SqlProviderServices.UsingMasterConnection(SqlConnection sqlConnection, Action`1 act) +384
System.Data.SqlClient.SqlProviderServices.GetDbProviderManifestToken(DbConnection connection) +241
System.Data.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection) +26
[ProviderIncompatibleException: The provider did not return a ProviderManifestToken string.]
System.Data.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection) +170
System.Data.Entity.ModelConfiguration.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices providerServices, DbConnection connection) +32
[ProviderIncompatibleException: An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct.]
System.Data.Entity.ModelConfiguration.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices providerServices, DbConnection connection) +192
System.Data.Entity.ModelConfiguration.Utilities.DbConnectionExtensions.GetProviderInfo(DbConnection connection, DbProviderManifest& providerManifest) +39
System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection) +46
System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext) +62
System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input) +123
System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +468
System.Data.Entity.Internal.InternalContext.CreateObjectContextForDdlOps() +17
System.Data.Entity.Database.Exists() +36
MvcApplication1.Filters.SimpleMembershipInitializer..ctor() in c:\Users\siddjain\Documents\Visual Studio 2012\Projects\MvcApplication1\Filters\InitializeSimpleMembershipAttribute.cs:34
[InvalidOperationException: The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588]
MvcApplication1.Filters.SimpleMembershipInitializer..ctor() in c:\Users\siddjain\Documents\Visual Studio 2012\Projects\MvcApplication1\Filters\InitializeSimpleMembershipAttribute.cs:45
[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) +113
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +232
System.Activator.CreateInstance(Type type, Boolean nonPublic) +83
System.Activator.CreateInstance(Type type) +6
System.Threading.LazyHelpers`1.ActivatorFactorySelector() +68
System.Threading.LazyInitializer.EnsureInitializedCore(T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory) +115
System.Threading.LazyInitializer.EnsureInitialized(T& target, Boolean& initialized, Object& syncLock) +106
MvcApplication1.Filters.InitializeSimpleMembershipAttribute.OnActionExecuting(ActionExecutingContext filterContext) in c:\Users\siddjain\Documents\Visual Studio 2012\Projects\MvcApplication1\Filters\InitializeSimpleMembershipAttribute.cs:21
System.Web.Mvc.Async.AsyncControllerActionInvoker.InvokeActionMethodFilterAsynchronously(IActionFilter filter, ActionExecutingContext preContext, Func`1 nextInChain) +69
System.Web.Mvc.Async.<>c__DisplayClass3b.<BeginInvokeActionMethodWithFilters>b__35() +21
System.Web.Mvc.Async.AsyncControllerActionInvoker.InvokeActionMethodFilterAsynchronously(IActionFilter filter, ActionExecutingContext preContext, Func`1 nextInChain) +489
System.Web.Mvc.Async.<>c__DisplayClass3b.<BeginInvokeActionMethodWithFilters>b__35() +21
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__31(AsyncCallback asyncCallback, Object asyncState) +191
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters, AsyncCallback callback, Object state) +197
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState) +446
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +302
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState) +30
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +382
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +317
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +15
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState) +71
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +249
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.17929
It is possible that the machine config is configured to use a local database connection that needs to be overridden. Try adding
<clear/>
<add name="LocalSqlServer" connectionString="... same as your UsersContext connection string"/>
at the start of your connection strings within your web config

Why are my MVC 4 Authorize checks throwing an exception?

I am using Visual Studio 2012 with SQL Server Express 2012. I created an MVC 4 Web Application using the "Internet Application" template.
I wanted to use an existing database on my instance of SQL Server 2012 Express (as opposed to the template's MDF). I have modified my web.config to point to my local SQL express instance instead and have deleted the template-generated MDF. My Web.Config has:
<add name="DefaultConnection"
connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=Administration;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/>
The stock membership code has a call to initialize the DB:
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
Once the application fires up, the tables get created in the Administration database as I would expect. I can create users and they are populated in Administration. I can populate the roles table and add roles to a user's profile through code and verify that it took. e.g.:
Roles.GetRolesForUser("kristian"); // = string[] { "Administrator" }
But if I try and use role-based authorization like:
[Authorize(Roles = "Administrator")]
I get the following exception:
Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed.
It gives a long nasty stack trace that makes me think it's still trying to create an MDF file:
[SqlException (0x80131904): Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed.]
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) +5309659
System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions) +38
System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +5311874
System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) +143
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource1 retry) +83
System.Data.SqlClient.SqlConnection.Open() +96
System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) +76
[HttpException (0x80004005): Unable to connect to SQL Server database.]
System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) +131
System.Web.Management.SqlServices.SetupApplicationServices(String server, String user, String password, Boolean trusted, String connectionString, String database, String dbFileName, SqlFeatures features, Boolean install) +89
System.Web.Management.SqlServices.Install(String database, String dbFileName, String connectionString) +27
System.Web.DataAccess.SqlConnectionHelper.CreateMdfFile(String fullFileName, String dataDir, String connectionString) +386
The line at the bottom of this bundle of joy makes me think it's related to the now-deleted MDF ('System.Web.DataAccess.SqlConnectionHelper.CreateMdfFile'). Am I correct in this? Or is the authorization implemented by the template just incomplete?
If someone else has dealt with this or knows why my attribute usage is failing I would greatly appreciate the help.
I had this same problem. It appears to be related to not initializing SimpleMembership properly. Try making sure that [InitializeSimpleMembership] is used or directly call Database.SetInitializer<UsersContext>(null);

Resources