I have an error deserializing a JSON string containing a SqlException instance.
Environment information:
- .NET Core: version 2.2
- Newtonsoft.Json: version 11.0.1
Result Error:
System.InvalidCastException: 'Unable to cast object of type 'Newtonsoft.Json.Linq.JValue' to type 'System.Guid'.'
Stack:
at System.Data.SqlClient.SqlException..ctor(SerializationInfo si, StreamingContext sc)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateISerializable(JsonReader reader, JsonISerializableContract contract, JsonProperty member, String id)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
Here a test that reproduce my issue:
[Fact(DisplayName = nameof(TestShitSingleSqlEx2))]
public async Task TestErrorSingleSqlEx2()
{
string json = #"{
""$type"": ""System.Data.SqlClient.SqlException, System.Data.SqlClient"",
""ClassName"": ""System.Data.SqlClient.SqlException"",
""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: TCP Provider, error: 40 - Could not open a connection to SQL Server)"",
""Data"": {
""$type"": ""System.Collections.ListDictionaryInternal, System.Private.CoreLib"",
""HelpLink.ProdName"": ""Microsoft SQL Server"",
""HelpLink.EvtSrc"": ""MSSQLServer"",
""HelpLink.EvtID"": ""0"",
""HelpLink.BaseHelpUrl"": ""http://go.microsoft.com/fwlink"",
""HelpLink.LinkId"": ""20476"",
""SqlError 1"": ""System.Data.SqlClient.SqlError: 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: TCP Provider, error: 40 - Could not open a connection to SQL Server)""
},
""InnerException"": null,
""HelpURL"": null,
""StackTraceString"": "" at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)\\n at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)\\n at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)\\n at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)\\n at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)\\n at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)\\n at System.Data.SqlClient.SqlConnection.OpenAsync(CancellationToken cancellationToken)\\n--- End of stack trace from previous location where exception was thrown ---\\n at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnectionAsync(Boolean errorsExpected, CancellationToken cancellationToken)\\n at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync(CancellationToken cancellationToken, Boolean errorsExpected)\\n at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable`1.AsyncEnumerator.BufferlessMoveNext(DbContext _, Boolean buffer, CancellationToken cancellationToken)\\n at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)\\n at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable`1.AsyncEnumerator.MoveNext(CancellationToken cancellationToken)\\n at System.Linq.AsyncEnumerable.SelectEnumerableAsyncIterator`2.MoveNextCore(CancellationToken cancellationToken) in D:\\\\a\\\\1\\\\s\\\\Ix.NET\\\\Source\\\\System.Interactive.Async\\\\Select.cs:line 106\\n at System.Linq.AsyncEnumerable.AsyncIterator`1.MoveNext(CancellationToken cancellationToken) in D:\\\\a\\\\1\\\\s\\\\Ix.NET\\\\Source\\\\System.Interactive.Async\\\\AsyncIterator.cs:line 98\\n at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext(CancellationToken cancellationToken)\\n at System.Collections.Generic.AsyncEnumerableHelpers.ToArrayWithLength[T](IAsyncEnumerable`1 source, CancellationToken cancellationToken) in D:\\\\a\\\\1\\\\s\\\\Ix.NET\\\\Source\\\\System.Interactive.Async\\\\AsyncEnumerableHelpers.cs:line 48\\n at System.Collections.Generic.AsyncEnumerableHelpers.ToArray[T](IAsyncEnumerable`1 source, CancellationToken cancellationToken) in D:\\\\a\\\\1\\\\s\\\\Ix.NET\\\\Source\\\\System.Interactive.Async\\\\AsyncEnumerableHelpers.cs:line 16\\n at XXXXXX.Manufacturing.Sublot.EntityFramework.Repositories.SublotRepository.LoadDataModelAsync(IEnumerable`1 ids) in /src/Sublot/Sublot.EntityFramework/Repositories/SublotRepository.cs:line 28\\n at XXXXXX.Manufacturing.EntityFramework.Repository.DbMultiMapRepository`3.OnGetAsync(IEnumerable`1 ids)\\n at XXXXXX.Manufacturing.Repository.MultiRepository`1.GetAsync(String id)\\n at XXXXXX.Manufacturing.Sublot.Cqrs.Handlers.SublotHandler.Handle(MoveSublotCommand command) in /src/Sublot/Sublot.Cqrs.Handlers/SublotHandler.cs:line 193\\n at Rebus.Pipeline.Receive.HandlerInvoker`1.Invoke()\\n at Rebus.Pipeline.Receive.DispatchIncomingMessageStep.Process(IncomingStepContext context, Func`1 next)\\n at Rebus.Sagas.LoadSagaDataStep.Process(IncomingStepContext context, Func`1 next)\\n at Rebus.Sagas.Exclusive.NewEnforceExclusiveSagaAccessIncomingStep.Process(IncomingStepContext context, Func`1 next)\\n at Rebus.Pipeline.Receive.ActivateHandlersStep.Process(IncomingStepContext context, Func`1 next)\\n at Rebus.Pipeline.Receive.HandleRoutingSlipsStep.Process(IncomingStepContext context, Func`1 next)\\n at Rebus.Retry.Simple.FailedMessageWrapperStep.Process(IncomingStepContext context, Func`1 next)\\n at Rebus.Pipeline.Receive.DeserializeIncomingMessageStep.Process(IncomingStepContext context, Func`1 next)\\n at Rebus.Pipeline.Receive.HandleDeferredMessagesStep.Process(IncomingStepContext context, Func`1 next)\\n at Rebus.Retry.FailFast.FailFastStep.Process(IncomingStepContext context, Func`1 next)\\n at Rebus.Retry.Simple.SimpleRetryStrategyStep.DispatchWithTrackerIdentifier(Func`1 next, String identifierToTrackMessageBy, ITransactionContext transactionContext, String messageId, String secondLevelMessageId)"",
""RemoteStackTraceString"": null,
""RemoteStackIndex"": 0,
""ExceptionMethod"": null,
""HResult"": -2146232060,
""Source"": ""Core .Net SqlClient Data Provider"",
""WatsonBuckets"": null,
""Errors"": null,
""ClientConnectionId"": ""00000000-0000-0000-0000-000000000000""
}";
var settings = new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.All,
}; ;
var cmd = JsonConvert.DeserializeObject<System.Data.SqlClient.SqlException>(json, settings);
}
I already tested that with TypeNameHandling.None (default value) it works. But i had this error in a production environment (using rebus v5.4.0) and i'm not confidet to modify TypeNameHandling for all messages.
The problem appears to be in the cast of the property ""ClientConnectionId"": ""00000000-0000-0000-0000-000000000000""
In fact if you remove it from the json string it works.
The problem is that the code that converts the type is inside the class
System.Data.SqlClient.SqlException
Here is the source code that performs class deserialization:
private SqlException(SerializationInfo si, StreamingContext sc) : base(si, sc)
{
HResult = SqlExceptionHResult;
foreach (SerializationEntry siEntry in si)
{
if ("ClientConnectionId" == siEntry.Name)
{
_clientConnectionId = (Guid)siEntry.Value;
break;
}
}
}
source: https://github.com/dotnet/corefx/blob/master/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlException.cs
the problem lies in that cast:
(Guid)siEntry.Value;
I've posted the issue on GitHub SqlClient. The fix implemented by the project team is on the way of being merged so it should be available in versions newer than Microsoft.Data.SqlClient v1.1.2.
DummyRick, consider that (by looking at the stacktrace of the SqlException) it looks like you are using the legacy System.Data.SqlClient package instead of the Microsoft.Data.SqlClient.
Related
I was running code from this repo and generating an error from the Book.API, I get an error page like this:
The request ID is |574e8e13-4e9d31fed64d4793.
When I look at the log entry in the file, I see:
{
"Timestamp": "2021-01-25T18:07:24.6565993-06:00",
"Level": "Fatal",
"MessageTemplate": "BADNESS!!! Cannot open database \"Demo_EffectiveLogging\" requested by the login. The login failed.\r\nLogin failed for user 'TCA-PRECISION\\terry.aney'. -- {ErrorId}.",
"Exception": "System.Data.SqlClient.SqlException (0x80131904): Cannot open database \"Demo_EffectiveLogging\" requested by the login. The login failed.\r\nLogin failed for user 'TCA-PRECISION\\terry.aney'.\r\n 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)\r\n at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)\r\n at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)\r\n at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)\r\n at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)\r\n at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)\r\n at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)\r\n at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)\r\n at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)\r\n at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)\r\n at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)\r\n at System.Data.SqlClient.SqlConnection.Open()\r\n at Dapper.SqlMapper.QueryImpl[T](IDbConnection cnn, CommandDefinition command, Type effectiveType)+MoveNext() in /_/Dapper/SqlMapper.cs:line 1079\r\n at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)\r\n at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)\r\n at Dapper.SqlMapper.Query[T](IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Boolean buffered, Nullable`1 commandTimeout, Nullable`1 commandType) in /_/Dapper/SqlMapper.cs:line 721\r\n at BookClub.Data.BookRepository.GetAllBooks() in C:\\Users\\terry.aney\\OneDrive\\.NET Core Tutorials\\EffectiveLogging\\BookClub.Data\\BookRepository.cs:line 33\r\n at BookClub.Logic.BookLogic.GetAllBooks(Boolean callBadMethod) in C:\\Users\\terry.aney\\OneDrive\\.NET Core Tutorials\\EffectiveLogging\\BookClub.Logic\\BookLogic.cs:line 26\r\n at BookClub.API.Controllers.BookController.GetBooks(Boolean throwException) in C:\\Users\\terry.aney\\OneDrive\\.NET Core Tutorials\\EffectiveLogging\\BookClub.API\\Controllers\\BookController.cs:line 45\r\n at lambda_method(Closure , Object )\r\n at Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable.Awaiter.GetResult()\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)\r\n at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)\r\n at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)\r\n at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)\r\n at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)\r\n at BookClub.Infrastructure.Middleware.ApiExceptionMiddleware.Invoke(HttpContext context) in C:\\Users\\terry.aney\\OneDrive\\.NET Core Tutorials\\EffectiveLogging\\BookClub.Infrastructure\\Middleware\\ApiExceptionMiddleware.cs:line 28\r\nClientConnectionId:2daf3389-b366-4b50-b1c2-651419fd247e\r\nError Number:4060,State:1,Class:11",
"Properties": {
"ErrorId": "0cc05d84-e36f-4e2b-b8e0-57bf5e465046",
"SourceContext": "BookClub.Infrastructure.Middleware.ApiExceptionMiddleware",
"RequestId": "8000017c-000c-fc00-b63f-84710c7967bb",
"RequestPath": "/api/Book",
"SpanId": "|303de91c-4b6f6e187de2f4f3.",
"TraceId": "303de91c-4b6f6e187de2f4f3",
"ParentId": ""
}
}
{
"Timestamp": "2021-01-25T18:07:24.8378974-06:00",
"Level": "Error",
"MessageTemplate": "An unhandled exception has occurred while executing the request.",
"Exception": "System.Exception: API Failure\r\n at BookClub.UI.StandardHttpMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) in C:\\Users\\terry.aney\\OneDrive\\.NET Core Tutorials\\EffectiveLogging\\BookClub.UI\\StandardHttpMessageHandler.cs:line 57\r\n at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)\r\n at BookClub.UI.Pages.BookListModel.OnGetAsync() in C:\\Users\\terry.aney\\OneDrive\\.NET Core Tutorials\\EffectiveLogging\\BookClub.UI\\Pages\\BookList.cshtml.cs:line 27\r\n at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.ExecutorFactory.NonGenericTaskHandlerMethod.Execute(Object receiver, Object[] arguments)\r\n at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeHandlerMethodAsync()\r\n at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeNextPageFilterAsync()\r\n at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.Rethrow(PageHandlerExecutedContext context)\r\n at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)\r\n at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeInnerFilterAsync()\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)\r\n at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)\r\n at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)\r\n at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)",
"Properties": {
"EventId": {
"Id": 1,
"Name": "UnhandledException"
},
"SourceContext": "Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware",
"RequestId": "80000069-0004-fb00-b63f-84710c7967bb",
"RequestPath": "/BookList",
"SpanId": "|574e8e13-4e9d31fed64d4793.",
"TraceId": "574e8e13-4e9d31fed64d4793",
"ParentId": ""
}
}
So it appears to be matching the SpanId instead of the RequestId.
So my questions:
I was watching the Pluralsight course, the screen shots seemed to be showing RequestId properly. How is that possible that his shows correct RequestId and mine shows SpanId?
I created a new project and to my knowledge, implemented everything the same way the repo did, yet I do not get SpanId, TraceId, or ParentId in my log properties. Any guess to what I might have missed?
Should the SpanId's match across WebApi and Website calls (i.e. the two logs above, the top one is Web API and second one is Web Site and both have unique Span/Request IDs)? Or am I supposed to use CorrelationId?
General question, what is difference between SpanId vs TraceId vs HttpContext.TraceIdentifier? Should my error.cshtml just use TraceIdentifier instead of looking at Activity.Current.Id?
Update: I implemented my project in .NET 5. That might be the culprit for missing properties in log, but the rest of the questions remain valid.
Update: I have figured out workaround for missing properties in .NET 5. And I also have TraceId spanning across calls from site to api, but I am wondering what SpanId represents, I'm not finding it easily on the web.
Context
Currently I am creating an Extract, Transform and Load (ETL) application written in C# with .NET Core. The target of the ETL application is a database that is accessed through Entity Framework Core 2.1.0 and later 2.1.1. A database first approach is used, since the schema's are fixed. Microsoft offers the following guide to approach this situation. The guide states that the CLI command Scaffold-DbContext in the Package Manager Console can be used to generate the DbContext and the corresponding entity models.
Earlier in this project I have successfully used this CLI command. However the naming of the models did not correspond directly to the table and column names. The newer versions of this CLI Tooling offers a option -UseDatabaseNames, so I therefore opted to rerun this command in order to generate some updated models. Additionally, regenerating the DbContext is something I am planning to do more often in the future.
The Problem
Unfortunately running the Scaffold-DbContext command now returns the following error: Instance failure.. The verbose option gives some more insight into what is going wrong, but I am unclear as to what exactly is going wrong and how to resolve it.
Command
Scaffold-DbContext "[ConnectionString]" Microsoft.EntityFrameworkCore.SqlServer -UseDatabaseNames -OutputDir Models -v -force
Verbose Output
Using project '[ProjectName]'.
Using startup project '[ProjectName]'.
Build started...
Build succeeded.
C:\Program Files\dotnet\dotnet.exe exec --depsfile C:\Repos\[Client]\[ProjectName]\[ProjectName]\[ProjectName].Service\bin\Debug\netcoreapp2.1\[ProjectName].Service.deps.json --additionalprobingpath C:\Users\[MyComputerUsername]\.nuget\packages --additionalprobingpath "C:\Program Files\dotnet\sdk\NuGetFallbackFolder" --runtimeconfig C:\Repos\[Client]\[ProjectName]\[ProjectName]\[ProjectName].Service\bin\Debug\netcoreapp2.1\[ProjectName].Service.runtimeconfig.json C:\Users\[MyComputerUsername]\.nuget\packages\microsoft.entityframeworkcore.tools\2.1.1\tools\netcoreapp2.0\any\ef.dll dbcontext scaffold Server=[ConnectionString] Microsoft.EntityFrameworkCore.SqlServer --json --output-dir Models --use-database-names --force --verbose --no-color --prefix-output --assembly C:\Repos\[Client]\[ProjectName]\[ProjectName]\[ProjectName].Service\bin\Debug\netcoreapp2.1\[ProjectName].Service.dll --startup-assembly C:\Repos\[Client]\[ProjectName]\[ProjectName]\[ProjectName].Service\bin\Debug\netcoreapp2.1\[ProjectName].Service.dll --project-dir C:\Repos\[Client]\[ProjectName]\[ProjectName]\[ProjectName].Service\ --language C# --working-dir C:\Repos\[Client]\[ProjectName]\[ProjectName] --root-namespace [ProjectName].Service
Using assembly '[ProjectName]'.
Using startup assembly '[ProjectName]'.
Using application base 'C:\Repos\[Client]\[ProjectName]\[ProjectName]\[ProjectName].Service\bin\Debug\netcoreapp2.1'.
Using working directory 'C:\Repos\[Client]\[ProjectName]\[ProjectName]\[ProjectName].Service'.
Using root namespace '[ProjectName]'.
Using project directory 'C:\Repos\[Client]\[ProjectName]\[ProjectName]\[ProjectName].Service\'.
The EF Core tools version '2.1.1-rtm-30846' is older than that of the runtime '2.1.2-rtm-30932'. Update the tools for the latest features and bug fixes.
Finding design-time services for provider 'Microsoft.EntityFrameworkCore.SqlServer'...
Using design-time services from provider 'Microsoft.EntityFrameworkCore.SqlServer'.
Finding design-time services referenced by assembly '[ProjectName]'.
No referenced design-time services were found.
Finding IDesignTimeServices implementations in assembly '[ProjectName]'...
No design-time services were found.
Exception
System.InvalidOperationException: Instance failure.
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)
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.SqlServer.Scaffolding.Internal.SqlServerDatabaseModelFactory.Create(DbConnection connection, IEnumerable`1 tables, IEnumerable`1 schemas)
at Microsoft.EntityFrameworkCore.SqlServer.Scaffolding.Internal.SqlServerDatabaseModelFactory.Create(String connectionString, IEnumerable`1 tables, IEnumerable`1 schemas)
at Microsoft.EntityFrameworkCore.Scaffolding.Internal.ReverseEngineerScaffolder.ScaffoldModel(String connectionString, IEnumerable`1 tables, IEnumerable`1 schemas, String namespace, String language, String contextDir, String contextName, ModelReverseEngineerOptions modelOptions, ModelCodeGenerationOptions codeOptions)
at Microsoft.EntityFrameworkCore.Design.Internal.DatabaseOperations.ScaffoldContext(String provider, String connectionString, String outputDir, String outputContextDir, String dbContextClassName, IEnumerable`1 schemas, IEnumerable`1 tables, Boolean useDataAnnotations, Boolean overwriteFiles, Boolean useDatabaseNames)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScaffoldContextImpl(String provider, String connectionString, String outputDir, String outputDbContextDir, String dbContextClassName, IEnumerable`1 schemaFilters, IEnumerable`1 tableFilters, Boolean useDataAnnotations, Boolean overwriteFiles, Boolean useDatabaseNames)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScaffoldContext.<>c__DisplayClass0_1.<.ctor>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Instance failure.
As stated before I am unclear what exactly is going wrong. My google searches have not resulted in any relevant information. Additionally I have tried updating the SDK, tools and other references. And I tried deleting the DbContext and models. Any help would be greatly appreciated!
I think you need to change your instance name.
For example :
Scaffold-DbContext "Server=PC\SQLEXPRESS;Database=***;User
ID=sa;Password=****" Microsoft.EntityFrameworkCore.SqlServer
-OutputDir model
So your instance in this case is : PC\\SQLEXPRESS.
This instance should be like this : .\SQLEXPRESS
This is indeed an instance error. I copied the connection string from one of my classes. My SQL server instance is PC\Expresss, but my connection string was PC\\Express, just removed a back slash.
Yea this is usually a matter of mis-spelling the instance name in your scaffold-dbcontext command on the PM Console..
You can use this little TSQL to find out the exact spelling of your SQL Server instance: SELECT ##SERVERNAME
I have done the following -
I set up a new EC2 instance running Windows Server 2008 with IIS7.
I set up a new RDS Instance running SQL Server 2008 R2.
I have configured the Security Group for the RDS server to allow SQL Server connections on port 1433 from the EC2 instance.
On the EC2 instance I can connect to the RDS SQL Database by creating a User or System ODBC Connection from Windows. I can also connect from my own computer with SQL Management Studio.
When I try to start up my .NET Web Application I get this error
A network-related or instance-specific error occurred while establishing
a connection to SQL Server. The server was not found or was not accessible.
Verify that the instance name is correct and that SQL Server is configured
to allow remote connections. (provider: SQL Network Interfaces, error: 26 -
Error Locating Server/Instance Specified)
This is my connection string, I am using Entity Framework and an edmx, Database first.
<add name="EntitiesName" connectionString="metadata=res://*/Models.Model1.csdl|res://*/Models.Model1.ssdl|res://*/Models.Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=myrdsserver.rds.amazonaws.com;initial catalog=VPN;User Id=userid;Password=password;Persist Security Info=True;MultipleActiveResultSets=True;"" providerName="System.Data.EntityClient" />
I've tried everything in the following links but nothing works to allow me to connect.
aws ec2 could not open a connection to sql server
entity framework 5 and amazon rds underlying prodiver failed to open
can't connect to rds instance from ec2 instance
UPDATE:
I created a Windows .NET Forms application that uses the same connection string and Entity Framework and it works. I ran it from the same EC2 instance. It seems that the main difference here is that IIS is not involved with the Windows Form application. I'm not sure how that is keeping the Web application from working.
Here is the stack trace from the web page:
[SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +6573870
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +717
System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover) +6600312
System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) +219
System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) +6602662
System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) +6603203
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData) +942
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +1162
System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) +72
System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) +6606457
System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) +103
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) +2102
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +116
System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) +1079
System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +6610951
System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry) +233
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +278
System.Data.SqlClient.SqlConnection.Open() +239
Hangfire.SqlServer.SqlServerStorage.CreateAndOpenConnection() +49
Hangfire.SqlServer.SqlServerStorage..ctor(String nameOrConnectionString, SqlServerStorageOptions options) +279
Hangfire.SqlServerStorageExtensions.UseSqlServerStorage(IGlobalConfiguration configuration, String nameOrConnectionString) +80
MyWebApplication1.Startup.Configuration(IAppBuilder app) +39
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +76
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +211
System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) +35
Owin.Loader.<>c__DisplayClass1.<LoadImplementation>b__0(IAppBuilder builder) +341
Microsoft.Owin.Host.SystemWeb.OwinAppContext.Initialize(Action`1 startup) +996
Microsoft.Owin.Host.SystemWeb.OwinHttpModule.InitializeBlueprint() +119
System.Threading.LazyInitializer.EnsureInitializedCore(T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory) +241
Microsoft.Owin.Host.SystemWeb.OwinHttpModule.Init(HttpApplication context) +108
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +530
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +304
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +404
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +475
[HttpException (0x80004005): Exception has been thrown by the target of an invocation.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +12618692
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +159
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +12458309
I found out what this was. Everything I did in my question was correct and working. I had another connection string in the application Startup that was being called for another service. That connection string wasn't updated so it wasn't opening the connection.
I have a .NET 4.5 Forms application that works great locally. Does not require any authentication and I can use all pages. However, I am able to register user, log in and log out without any problems.
On godaddy, I can get to an HTML page I put on godaddy so everything is setup fine. But when I try to go to Default.aspx, I get a log in error even though nothing is requiring authentication locally. When I try to register a user, I get this error below.
One thing I noticed is that my application is 4.5 and this error shows 4.0 at the bottom. Now on godaddy, they just say you are using 4.0/4.5. There is no separation between them. I have talked to godaddy few times but they say they have very little technical help for custom sites like this and I have to resolve these. But if the .NET version is the problem, I will convert my projects or recreate them in 4.0.
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.SqlInternalConnection.OnError(SqlException
exception, Boolean breakConnection, Action1 wrapCloseInAction)
+5296071 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +558
System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo,
SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout,
Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean
integratedSecurity, Boolean withFailover) +5308555
System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo
serverInfo, String newPassword, SecureString newSecurePassword,
Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean
withFailover) +145
System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo
serverInfo, String newPassword, SecureString newSecurePassword,
Boolean redirectedUserInstance, SqlConnectionString connectionOptions,
SqlCredential credential, TimeoutTimer timeout) +920
System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer
timeout, SqlConnectionString connectionOptions, SqlCredential
credential, String newPassword, SecureString newSecurePassword,
Boolean redirectedUserInstance) +307
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity
identity, SqlConnectionString connectionOptions, SqlCredential
credential, Object providerInfo, String newPassword, SecureString
newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString
userConnectionOptions) +434
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions
options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo,
DbConnectionPool pool, DbConnection owningConnection,
DbConnectionOptions userOptions) +225
System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool
pool, DbConnectionOptions options, DbConnectionPoolKey poolKey,
DbConnectionOptions userOptions) +37
System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnectionOptions
userOptions) +558
System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnectionOptions
userOptions) +67
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection
owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean
allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions
userOptions, DbConnectionInternal& connection) +1052
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection
owningObject, TaskCompletionSource1 retry, DbConnectionOptions
userOptions, DbConnectionInternal& connection) +78
System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection
owningConnection, TaskCompletionSource1 retry, DbConnectionOptions
userOptions, DbConnectionInternal& connection) +167
System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection
outerConnection, DbConnectionFactory connectionFactory,
TaskCompletionSource1 retry, DbConnectionOptions userOptions) +143
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource1
retry) +83 System.Data.SqlClient.SqlConnection.Open() +96
System.Data.SqlClient.SqlProviderServices.UsingConnection(SqlConnection
sqlConnection, Action1 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.Web.Providers.ModelHelper.GetStorageMetadata(String
providerName, DbConnection connection, String ssdl) +35
System.Web.Providers.ModelHelper.CreateMetadataWorkspace(String
providerName, DbConnection connection, String csdl, String ssdl,
String msl) +154
System.Web.Providers.ModelHelper.CreateEntityConnection(ConnectionStringSettings
setting, String csdl, String ssdl, String msl) +109
System.Web.Providers.ModelHelper.CreateMembershipEntities(ConnectionStringSettings
setting) +28
System.Web.Providers.DefaultMembershipProvider.Membership_CreateUser(String
applicationName, String userName, String password, String salt, String
email, String passwordQuestion, String passwordAnswer, Boolean
isApproved, DateTime& createDate, Boolean uniqueEmail, Int32
passwordFormat, Object& providerUserKey) +51
System.Web.Providers.DefaultMembershipProvider.CreateUser(String
username, String password, String email, String passwordQuestion,
String passwordAnswer, Boolean isApproved, Object providerUserKey,
MembershipCreateStatus& status) +823
System.Web.UI.WebControls.CreateUserWizard.AttemptCreateUser() +304
System.Web.UI.WebControls.CreateUserWizard.OnNextButtonClick(WizardNavigationEventArgs
e) +110 System.Web.UI.WebControls.Wizard.OnBubbleEvent(Object
source, EventArgs e) +401
System.Web.UI.WebControls.CreateUserWizard.OnBubbleEvent(Object
source, EventArgs e) +119
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)
+37 System.Web.UI.WebControls.Button.OnCommand(CommandEventArgs e) +114 System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +159
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String
eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler
sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
+35 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
+1724
Version Information: Microsoft .NET Framework Version:4.0.30319;
ASP.NET Version:4.0.30319.18055
I have a .NET 4.5 Forms application that works great locally. Does not
require any authentication and I can use all pages
If you run the application locally, Visual Studio uses SQL Express for development. As the result, it is working without even you notice it. Normally, the database is created inside App_Data folder.
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.
However, when you deploy the application (to GoDaddy), you need to explicitly provide the connection in web.config to connect to actual SQL Server.
According to the above error message, you did not provide the correct connection string in web.config.
ASP.NET MVC 4 website, SQL Server 2012.
When I upload all files to Windows Server 2008 R2, source, web config etc, the app works fine.
When I use 'Web Deploy' - which only uploads 'required files', ie strips out source files, web.config etc - it comes up with this error:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
Stack Trace:
[SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +6676046
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +810
System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover) +6702720
System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) +219
System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) +6704856
System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) +6705315
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions) +610
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +1049
System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) +74
System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnectionOptions userOptions) +6707883
System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnectionOptions userOptions) +78
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) +2192
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +116
System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +1012
System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +6712511
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +152
System.Data.SqlClient.SqlConnection.Open() +229
System.Data.SqlClient.SqlProviderServices.UsingConnection(SqlConnection sqlConnection, Action`1 act) +134
System.Data.SqlClient.SqlProviderServices.UsingMasterConnection(SqlConnection sqlConnection, Action`1 act) +3805119
System.Data.SqlClient.SqlProviderServices.GetDbProviderManifestToken(DbConnection connection) +10957386
System.Data.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection) +91
[ProviderIncompatibleException: The provider did not return a ProviderManifestToken string.]
System.Data.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection) +10957457
System.Data.Entity.ModelConfiguration.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices providerServices, DbConnection connection) +48
[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) +242
System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection) +82
System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext) +88
System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input) +248
System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +524
System.Data.Entity.Internal.InternalContext.CreateObjectContextForDdlOps() +23
System.Data.Entity.Database.CreateIfNotExists() +38
cityKingMVC4.MvcApplication.Application_Start() in c:\a\src\cityKingMVC4\Global.asax.cs:27
[HttpException (0x80004005): 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.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) +12864365
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +175
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +304
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +404
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +475
[HttpException (0x80004005): 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.Web.HttpRuntime.FirstRequestInit(HttpContext context) +12881108
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +159
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +12722297
As there is no web.config on the server now (I assume it has been compiled into a .dll) - and the error message doesn't tell me what it is trying to connect as - how on earth can I debug this? How can I find out what connection string it is trying to use?
There is no transform in web.release.config to change the connection string.
Any ideas how to debug - and what might be causing this?
Thanks.
Web.config is not compiled into the dll of your website. If your connection string is stored in the web.config, make sure the file is on the server when running the website. Do either of the following:
Include web.config in deployment by following the steps in this previous answer.
Manually copy web.config to your server and change the settings there. This will prevent overriding the settings when deploying.
For a production website, the second option is probably the best.
try saving connection string in web.config file. Then run it.