TFS 2010 restored database, TfsJobAgent cannot connect to database - tfs

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

Related

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

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.

Azure WebJobs cannot connect to mdf database

I am developing an Azure website and a WebJob. The development database is an Mdf file. The Mvc app can connect to Azure storage and the database. The WebJob can connect to the Azure storage, but the database throws this:
System.Data.SqlClient.SqlException occurred
HResult=0x80131904
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: 50 - Local Database Runtime error occurred. Specified LocalDB instance name is invalid.
)
Source=Core .Net SqlClient Data Provider
StackTrace:
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling)
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)
Both the Mvc and WebJob share the same connection strings:
Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=D:\\Projects\\Test1\\Code\\Database\\Test1.mdf;Integrated Security=True;Connect Timeout=30;Encrypt=False
It doesn't make any difference if the Mvc app is running when the WebJob is started.
In the MVC app user secrets, I had to use double slashes, like this:
Data Source=(LocalDB)\\MSSQLLocalDB
In the app.config file for the webjob console app, I had to use single slashes like this:
Data Source=(LocalDB)\MSSQLLocalDB

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?

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);

Entity Data Model System.ArgumentOutOfRangeException

I am using the entity data model to connect to a database. It works fine locally. When I upload my website to the server it throws the following error:
Server Error in '/' Application.
Non-negative number required.
Parameter name: count
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.ArgumentOutOfRangeException: Non-negative number required.
Parameter name: count
Source Error:
Line 14: //Fill the Route collection here.
Line 15: routes.Clear();
Line 16: foreach (var page in context.PageInfos)
Line 17: {
Line 18: //get the friendly URL
Source File: e:\HostingSpaces\homelink\dev.homelinkfamilysupport.org\wwwroot\Global.asax Line: 16
Stack Trace:
[ArgumentOutOfRangeException: Non-negative number required.
Parameter name: count]
System.Buffer.BlockCopy(Array src, Int32 srcOffset, Array dst, Int32 dstOffset, Int32 count) +0
System.Data.SqlClient.TdsParserStateObject.ReadByteArray(Byte[] buff, Int32 offset, Int32 len) +153
System.Data.SqlClient.TdsParser.ConsumePreLoginHandshake(Boolean encrypt, Boolean trustServerCert, Boolean& marsCapable) +173
System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity) +473
System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, SqlConnection owningObject) +129
System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, TimeoutTimer timeout) +164
System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, TimeoutTimer timeout, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance) +195
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance) +232
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) +185
System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options) +33
System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject) +524
System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject) +66
System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) +479
System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) +108
System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +126
System.Data.SqlClient.SqlConnection.Open() +125
System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure) +52
[EntityException: The underlying provider failed on Open.]
System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure) +161
System.Data.EntityClient.EntityConnection.Open() +98
System.Data.Objects.ObjectContext.EnsureConnection() +81
System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) +46
System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator() +44
ASP.global_asax.RegisterRoutes(RouteCollection routes) in e:\HostingSpaces\homelink\dev.homelinkfamilysupport.org\wwwroot\Global.asax:16
ASP.global_asax.Application_Start(Object sender, EventArgs e) in e:\HostingSpaces\homelink\dev.homelinkfamilysupport.org\wwwroot\Global.asax:7
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1
The database on the server definately has the exact same structure and data as it was restored from a .bak file of the original (from which the EDM was generated).
Any help on this will be much appreciated.
For reference sake: this was caused due to my hosting provider changing the port I had to use to connect to SQL server. Not related to the code.

Resources