ManagedIdentityCredential authentication unavailable. No Managed Identity endpoint found - sql-server

we have a nightly process (all running on Azure VMs) which is largely a collection of powershell scripts to update DBs in our TEST environment. Quite frequently we hit issues like below. We have around 25 DBs to update and at some random point in the process we'll have sporadic errors trying to use Azure Managed Identity Authentication. Below shows how it all works perfectly for one DB, but then fails on the next DB even though run from the same process on the same Azure VM and connecting to the same SQL Managed Instance where the source VM's Managed Identity is configured to have full sysAdmin rights.
I've previously been advised in effect, "these services just aren't that reliable so you just need to wrap all such logic in retry logic and hope you eventually get lucky". The frequency with which we see these issues is making me wonder if there is more going on than that and if anyone has seen this or has other ideas? If the nature of these services are such that it just isn't that reliable to work every time, you'd think they would add the retry logic in the core libraries such as Microsft.Data.SqlClient or the underlying Azure.Identity libraries vs expecting developers to detect these issues higher in the logic chain and respond?
Anyway, I'm not sure if anyone else has seen this or I'm just unlucky :)
[06:51:56][Step 5/6] ========================================================================
[06:51:56][Step 5/6] Updating DB zzzzz_Regression (zzzzzRegression) on server xxxxx-tcc-sql.2222.database.windows.net (xxxxx-TCC-SQL)
[06:51:56][Step 5/6] ========================================================================
[06:51:57][Step 5/6] 6:51:56 AM:Using env file from command line: .\Package\BuildScripts\Configs\mmmmmTestAzure.fmenv.xml
[06:51:57][Step 5/6] 6:51:57 AM:Loaded environment: mmmmmTestAzure
[06:51:57][Step 5/6] 6:51:57 AM:Applying change scripts.
[06:52:09][Step 5/6] 6:52:09 AM:Creating functions.
[06:52:27][Step 5/6] 6:52:27 AM:Creating triggers.
[06:52:34][Step 5/6] 6:52:34 AM:Creating stored procedures.
[06:54:08][Step 5/6] 6:54:07 AM:Database FM3OMS_Regression upgraded successfully.
[06:54:08][Step 5/6] Inializing Report Urls on Database Id zzzzzRegression
[06:54:14][Step 5/6] ========================================================================
[06:54:14][Step 5/6] Updating DB yyyyy (yyyyy) on server xxxxx-tcc-sql.2222.database.windows.net (xxxxx-TCC-SQL)
[06:54:14][Step 5/6] ========================================================================
[06:54:14][Step 5/6] 6:54:14 AM:Using env file from command line: .\Package\BuildScripts\Configs\mmmmmTestAzure.fmenv.xml
[06:54:15][Step 5/6] 6:54:14 AM:Loaded environment: mmmmm
[06:54:15][Step 5/6] 6:54:14 AM:Applying change scripts.
[06:54:28][Step 5/6] 6:54:28 AM:Creating functions.
[06:54:52][Step 5/6] 6:54:52 AM:Creating triggers.
[06:55:10][Step 5/6] 6:55:03 AM:Creating stored procedures.
[06:57:39][Step 5/6] 6:57:39 AM:Database yyyyy upgraded successfully.
[06:57:42][Step 5/6] Inializing Report Urls on Database Id yyyyy
[06:58:18][Step 5/6] Initialize-FMReportUrls : 6:58:07 AM:Using env file from command line:
[06:58:18][Step 5/6] .\Package\BuildScripts\Configs\mmmmmTestAzure.fmenv.xml 6:58:13 AM:Loaded environment: mmmmmTestAzure
[06:58:18][Step 5/6] System.AggregateException: One or more errors occurred. ---> Azure.Identity.CredentialUnavailableException:
[06:58:18][Step 5/6] ManagedIdentityCredential authentication unavailable. No Managed Identity endpoint found. at
[06:58:18][Step 5/6] Azure.Identity.ManagedIdentityClient.<AuthenticateAsync>d__12.MoveNext() --- End of stack trace from previous location
[06:58:18][Step 5/6] where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at
[06:58:18][Step 5/6] System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at
[06:58:18][Step 5/6] Azure.Identity.ManagedIdentityCredential.<GetTokenImplAsync>d__9.MoveNext() --- End of stack trace from previous
[06:58:18][Step 5/6] location where exception was thrown --- at Azure.Identity.CredentialDiagnosticScope.FailWrapAndThrow(Exception ex)
[06:58:18][Step 5/6] at Azure.Identity.ManagedIdentityCredential.<GetTokenImplAsync>d__9.MoveNext() --- End of stack trace from previous
[06:58:18][Step 5/6] location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
[06:58:18][Step 5/6] task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at
[06:58:18][Step 5/6] Azure.Identity.ManagedIdentityCredential.<GetTokenAsync>d__7.MoveNext() --- End of stack trace from previous location
[06:58:18][Step 5/6] where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at
[06:58:18][Step 5/6] System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at
[06:58:18][Step 5/6] System.Threading.Tasks.ValueTask`1.get_Result() at
[06:58:18][Step 5/6] Microsoft.Data.SqlClient.ActiveDirectoryAuthenticationProvider.<AcquireTokenAsync>d__19.MoveNext() --- End of inner
[06:58:18][Step 5/6] exception stack trace --- at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
[06:58:18][Step 5/6] at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification) at
[06:58:18][Step 5/6] System.Threading.Tasks.Task`1.get_Result() at
[06:58:18][Step 5/6] Microsoft.Data.SqlClient.SqlInternalConnectionTds.GetFedAuthToken(SqlFedAuthInfo fedAuthInfo) at
[06:58:18][Step 5/6] Microsoft.Data.SqlClient.SqlInternalConnectionTds.OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) at
[06:58:18][Step 5/6] Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream,
[06:58:18][Step 5/6] BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) at
[06:58:18][Step 5/6] Microsoft.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream,
[06:58:18][Step 5/6] BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at
[06:58:18][Step 5/6] Microsoft.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) at
[06:58:18][Step 5/6] Microsoft.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword,
[06:58:18][Step 5/6] SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover, Boolean
[06:58:18][Step 5/6] isFirstTransparentAttempt, Boolean disableTnir) at
[06:58:18][Step 5/6] Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword,
[06:58:18][Step 5/6] SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential
[06:58:18][Step 5/6] credential, TimeoutTimer timeout) at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer
[06:58:18][Step 5/6] timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString
[06:58:18][Step 5/6] newSecurePassword, Boolean redirectedUserInstance) at

This is a problem with the Azure VM, or an issue with Microsoft.Data.SqlClient.
ManagedIdentityCredential authentication unavailable. No Managed
Identity endpoint found.
This message claims that the local http endpoint that Azure provides when you enable Managed Identity on a VM is not available to hand out access tokens.
You should
make sure you're current on Microsoft.Data.SqlClient,
open an Azure Support incident and/or create an issue in the SqlClient repo, or perhaps the Azure.Identity repo and
switch to SQL Auth, or non-MSI AAD auth (eg ActiveDirectoryServicePrincipal where you use the ClientId as the user name and a Client Secret as the password or ActiveDirectoryDefault which supports supplying the ClientID and ClientSecret in environment variables) as a workaround.

Related

Unable to connect from data studio to SQL Server 2022 running on Docker

I am trying to connect to SQL Server running on docker. I am on windows 11 with WSL ubuntu 22.04.1.
This is how I start my instance by running this command in powershell.
docker run -e "ACCEPT_EULA=Y" -e "MSSQL_SA_PASSWORD=password123" -p 1433:1433 -d mcr.microsoft.com/mssql/server:2022-latest
In Azure Data Studio (also tried SSMS), I connect using these settings (leaving the rest at defaults):
Connection type: Microsoft SQL server
server: localhost // also tried localhost,1433 and 0.0.0.0,1433
user name: sa
password: password123
which gives me the following error
(provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
Microsoft.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
---> System.ComponentModel.Win32Exception (2): The system cannot find the file specified.
at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at Microsoft.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnectionString connectionOptions, Boolean withFailover)
at Microsoft.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
at Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
at Microsoft.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, DbConnectionPool pool)
at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
at Microsoft.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions)
at Microsoft.Data.ProviderBase.DbConnectionFactory.<>c__DisplayClass48_0.<CreateReplaceConnectionContinuation>b__0(Task`1 _)
at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
--- End of stack trace from previous location ---
at Microsoft.SqlTools.ServiceLayer.Connection.ReliableConnection.ReliableSqlConnection.<>c__DisplayClass30_0.<<OpenAsync>b__0>d.MoveNext() in D:\a\_work\1\s\src\Microsoft.SqlTools.ManagedBatchParser\ReliableConnection\ReliableSqlConnection.cs:line 312
--- End of stack trace from previous location ---
at Microsoft.SqlTools.ServiceLayer.Connection.ConnectionService.TryOpenConnection(ConnectionInfo connectionInfo, ConnectParams connectionParams) in D:\a\_work\1\s\src\Microsoft.SqlTools.ServiceLayer\Connection\ConnectionService.cs:line 666
ClientConnectionId:00000000-0000-0000-0000-000000000000
Error Number:2,State:0,Class:20
and when I try server: localhost,1433 the error changes into:
provider: TCP Provider, error: 0 - An attempt was made to access a socket in a way forbidden by its access permissions.)
Microsoft.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 0 - An attempt was made to access a socket in a way forbidden by its access permissions.)
---> System.ComponentModel.Win32Exception (10013): An attempt was made to access a socket in a way forbidden by its access permissions.
at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at Microsoft.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnectionString connectionOptions, Boolean withFailover)
at Microsoft.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
at Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
at Microsoft.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, DbConnectionPool pool)
at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
at Microsoft.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions)
at Microsoft.Data.ProviderBase.DbConnectionFactory.<>c__DisplayClass48_0.<CreateReplaceConnectionContinuation>b__0(Task`1 _)
at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
--- End of stack trace from previous location ---
at Microsoft.SqlTools.ServiceLayer.Connection.ReliableConnection.ReliableSqlConnection.<>c__DisplayClass30_0.<<OpenAsync>b__0>d.MoveNext() in D:\a\_work\1\s\src\Microsoft.SqlTools.ManagedBatchParser\ReliableConnection\ReliableSqlConnection.cs:line 312
--- End of stack trace from previous location ---
at Microsoft.SqlTools.ServiceLayer.Connection.ConnectionService.TryOpenConnection(ConnectionInfo connectionInfo, ConnectParams connectionParams) in D:\a\_work\1\s\src\Microsoft.SqlTools.ServiceLayer\Connection\ConnectionService.cs:line 666
ClientConnectionId:00000000-0000-0000-0000-000000000000
Error Number:10013,State:0,Class:20
edit: I tried the following to no avail
net stop hns
net start hns
running azure data studio as administrator.
updating azure data studio to latest version.
edit2: solved, ping localhost resolves to ::1 which is default ipv6 protocol as default instead of ipv4, thanks #AlwaysLearning

Can't connect to SQL SERVER running on docker

I've installed a sqlserver docker container and it seems that the instalation its fine, as shown bellow:
I've setup the server using this command:
docker run -e "ACCEPT_EULA=Y" -e "MSSQL_SA_PASSWORD=<#MystrongPassword1" -p 1433:1433 --name sql1 --hostname sql1 -d mcr.microsoft.com/mssql/server:2022-latest
The problem is: I'm trying to create a connection on Azure Data Studio, this is the configuration I'm using
When I click the "Connect" button, it doesnt connect and the below errors are shown:
When the first error apears, I click the "enable trust certificate" button, and then the second error pop up appears and the connection fails:
The error details:
Microsoft.Data.SqlClient.SqlException (0x80131904): Login failed for user 'sa'.
at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at Microsoft.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at Microsoft.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK)
at Microsoft.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
at Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
at Microsoft.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, DbConnectionPool pool)
at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
at Microsoft.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions)
at Microsoft.Data.ProviderBase.DbConnectionFactory.<>c__DisplayClass48_0.<CreateReplaceConnectionContinuation>b__0(Task`1 _)
at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
--- End of stack trace from previous location ---
at Microsoft.SqlTools.ServiceLayer.Connection.ReliableConnection.ReliableSqlConnection.<>c__DisplayClass30_0.<<OpenAsync>b__0>d.MoveNext() in D:\a\_work\1\s\src\Microsoft.SqlTools.ManagedBatchParser\ReliableConnection\ReliableSqlConnection.cs:line 312
--- End of stack trace from previous location ---
at Microsoft.SqlTools.ServiceLayer.Connection.ConnectionService.TryOpenConnection(ConnectionInfo connectionInfo, ConnectParams connectionParams) in D:\a\_work\1\s\src\Microsoft.SqlTools.ServiceLayer\Connection\ConnectionService.cs:line 666
ClientConnectionId:cbab63a5-c831-442e-b117-eb024e6f16bf
Error Number:18456,State:1,Class:14
I just deleted it all and created all the same but this time it worked

How to connect external MS SQL server database from container

I'm new in Docker and we are migrating our working ASP.NET CORE app to Docker in company
Problem is I did't find any releated topics about how to connect to external already existing MS SQL server [not in docker image] database from container.
All topics are about connecting to official Image of MS SQL-Server[which I don't need].
I wrote Dockerfile and application running but there no connection to SQL Server
Please give me correct direction with topics or hints thank you!
Dockerfile
FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS base
WORKDIR /app
EXPOSE 5000 //port to app
EXPOSE 1433 //SQL-Server port
FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build
WORKDIR /src
COPY UploadCore/UploadCore.csproj UploadCore/
RUN dotnet restore UploadCore/UploadCore.csproj
COPY . .
WORKDIR /src/UploadCore
RUN dotnet build UploadCore.csproj -c Release -o /app
FROM build AS publish
RUN dotnet publish UploadCore.csproj -c Release -o /app
FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "UploadCore.dll"]
I'm running my app as below
docker run -it --rm -p 5000:5000 -p 1433:1433 --name UploadCore my-app_test:4.5
Error:
Microsoft.EntityFrameworkCore.Database.Connection[20004]
An error occurred using the connection to database 'MIS_REPORTS' on server 'server02'.
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
Microsoft.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 25 - Connection string is not valid: Connection string is not valid)
at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at Microsoft.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover, SqlAuthenticationMethod authType)
at Microsoft.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
at Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
at Microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, DbConnectionPool pool)
Docker provides its own internal DNS service that can do things like resolve other container names as host names. It looks like you've configured your database location as a bare host name server02. This hits the Docker DNS resolver first, and it tries to resolve it as a container name; when that fails, that's why you're getting the error you do.
In different environments you can tell this apart from different kinds of errors by error messages like "name resolution failed" or "no such host"; this is different from an error message like "connection refused" or "connection reset by peer".
You can resolve this by using a fully-qualified domain name (FQDN) as your database location; for example, server02.example.com instead of just server02. Since that doesn't look like a container name, it will cause Docker to forward the DNS request to your normal name server.

A network related or instance specific error-26 while deploying MVC5 app to Windows server 2012 and Migration

Please don't mark it as duplicate tried out few of these similar errors already .
Scenario :
Just tried to deploy the MVC5 Entity Framework Code First Migration to a Windows 2012 Server which initially worked as without Styles/JS running so redeployed it changing the Bundling names ( this have no chance to be related with the current issue but stating it here). The CodeFirst DB gets created properly and the publish is successful but not able launch the app, it throws this error.
WebConfig Connectionstring:
<connectionStrings>
<add name="ERPContext_DatabasePublish" connectionString="Data Source=TSSERVER;Initial Catalog=TS_ERP;User ID=tssql;Password=*******" providerName="System.Data.SqlClient" />
</connectionStrings>
TroubleShoot:
Checked SQL Services are running ( also Sql Server Browse )
Checked Connection String /Credentials( if its wrong the DB itself wont have created at first place by Migration
Manually able to log into the SQlServerStudio using same credentials
Was working fine in the initial deployment without any problem
DB user instance has admin rights
IIS configurations are defaults
Would that mean its related to any Firewall or Port ( 1433/1434) issues? But since the initial deployment was successful the Server/Network admin team has rejected that request to investigate.
Is there any chance that there are multiple references of connectionstrings for Entity Framework etc. I had check the IIS virtual directory connections too.
The application deployed ( web server) and SQlServer runs on the same server machine so the SQL remote also doesn't seems to be the issue here.
Appreciate any thoughts regarding the same.
Apologies for posting the full error stack just in case if it has more hints
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)[SqlException (0x80131904): >System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection
owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean
allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions
userOptions, DbConnectionInternal& connection) +350
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection
owningObject, TaskCompletionSource1 retry, DbConnectionOptions
userOptions, DbConnectionInternal& connection) +156
System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection
owningConnection, TaskCompletionSource1 retry, DbConnectionOptions
userOptions, DbConnectionInternal oldConnection, DbConnectionInternal&
connection) +268
System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection
outerConnection, DbConnectionFactory connectionFactory,
TaskCompletionSource1 retry, DbConnectionOptions userOptions) +314
System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource1
retry) +204
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource1
retry) +428
System.Data.SqlClient.SqlConnection.OpenAsync(CancellationToken
cancellationToken) +572
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) +62
System.Data.Entity.SqlServer.<<ExecuteAsync>b__3>d__6.MoveNext() +292
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) +62
System.Data.Entity.SqlServer.<ExecuteAsyncImplementation>d__91.MoveNext()
+503 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) +62
System.Data.Entity.Core.EntityClient.d__8.MoveNext() +924
[EntityException: The underlying provider failed on Open.]
System.Data.Entity.Core.EntityClient.d__8.MoveNext() +1255
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) +62
System.Data.Entity.Core.Objects.d__9.MoveNext()
+514 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) +62
System.Data.Entity.Core.Objects.d__3d1.MoveNext()
+312 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) +62
System.Data.Entity.SqlServer.<ExecuteAsyncImplementation>d__91.MoveNext()
+579 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) +62 System.Data.Entity.Utilities.CultureAwaiter1.GetResult()
+48 System.Data.Entity.Core.Objects.<GetResultsAsync>d__e.MoveNext() +734
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) +62 System.Data.Entity.Utilities.CultureAwaiter1.GetResult()
+48 System.Data.Entity.Internal.d__0.MoveNext() +332 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) +62
System.Data.Entity.Infrastructure.d__251.MoveNext()
+371 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) +62 Microsoft.AspNet.Identity.CultureAwaiter1.GetResult()
+48 Microsoft.AspNet.Identity.d__13.MoveNext() +438 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) +62 Microsoft.AspNet.Identity.CultureAwaiter1.GetResult()
+48 Microsoft.AspNet.Identity.<RoleExistsAsync>d__d.MoveNext() +403 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) +62 Microsoft.AspNet.Identity.AsyncHelper.RunSync(Func1
func) +232 ERPLite.Startup.CreateRolesandUsers() in
C:\Users\trss\source\repos\ERP\ERP\Startup.cs:36
ERPLite.Startup.Configuration(IAppBuilder app) in
C:\Users\trss\source\repos\ERP\ERP\Startup.cs:22
[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) +128
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags
invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
+146 Owin.Loader.<>c__DisplayClass12.b__b(IAppBuilder builder) +93
Owin.Loader.<>c__DisplayClass1.b__0(IAppBuilder
builder) +209
Microsoft.Owin.Host.SystemWeb.OwinAppContext.Initialize(Action1
startup) +842
Microsoft.Owin.Host.SystemWeb.OwinBuilder.Build(Action1 startup) +51
Microsoft.Owin.Host.SystemWeb.OwinHttpModule.InitializeBlueprint()
+101 System.Threading.LazyInitializer.EnsureInitializedCore(T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory)
+136 Microsoft.Owin.Host.SystemWeb.OwinHttpModule.Init(HttpApplication
context) +162
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr
appContext, HttpContext context, MethodInfo[] handlers) +583
System.Web.HttpApplication.InitSpecial(HttpApplicationState state,
MethodInfo[] handlers, IntPtr appContext, HttpContext context) +169
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr
appContext, HttpContext context) +396
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr
appContext) +333
[HttpException (0x80004005): Exception has been thrown by the target
of an invocation.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +525
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context)
+124 System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest
wr, HttpContext context) +700
Posting this for those who encounter this error and already checked the list of troubleshooting points mentioned in the question.
Once creating a publish/deployment using WebDeploy it will add 1 more connection string in the target webconfig as _DatabasePublish (refer question) apart from the existing local connectionString.
I assumed that the _DatabasePublish would be used by the published app but it requires both the connectionStrings pointed to the same DB.
While creating the EF Migration it used _DatabasePublish and subsequent ( Seeding etc) used the other connectionString. But I'm sure there should be ways to change this though.

Error after MVC app authenticates with Azure AD

I am debugging an application on our testing server that throws an error after you successfully authenticate with Azure AD. I believe OWIN Katana middle-ware is trying to cache the access token it received from Azure AD into its token cache but it cant startup the database to cache it. It works fine when i run it locally on my development machine.
I feel like I'm missing something obvious, I'm new to the Katana middle-ware and OpenID Connect in general.
On the test server it gives this error: A network-related or instance-specific error occurred while establishing a connection to SQL Server.
In the windows Event Viewer on the server i get this error a ton of times:
Event 528, SQLLocalDB 13.0
Windows API call WaitForMultipleObjects returned error code: 575. Windows system error message is: {Application Error}
The application was unable to start correctly (0x%lx). Click OK to close the application.
Reported at line: 3730.
Stack Trace:
at
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling)
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.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.Open()
at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connection, DbInterceptionContext interceptionContext)
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.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.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.Database.Create(DatabaseExistenceState existenceState)
at System.Data.Entity.CreateDatabaseIfNotExists`1.InitializeDatabase(TContext context)
at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
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.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, Expression`1 predicate)
at MealPlanSignup.Web.Models.ADALTokenCache..ctor(String signedInUserId) in C:\Agent\_work\9\s\MealPlanSignup.Web\Models\AdalTokenCache.cs:line 14
at MealPlanSignup.Web.Startup.<ConfigureAuth>b__7_0(AuthorizationCodeReceivedNotification context) in C:\Agent\_work\9\s\MealPlanSignup.Web\App_Start\Startup.Auth.cs:line 54
at Microsoft.Owin.Security.OpenIdConnect.OpenIdConnectAuthenticationHandler.<AuthenticateCoreAsync>d__1a.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.Owin.Security.OpenIdConnect.OpenIdConnectAuthenticationHandler.<AuthenticateCoreAsync>d__1a.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Owin.Security.Infrastructure.AuthenticationHandler.<BaseInitializeAsync>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware`1.<Invoke>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContextStage.<RunApp>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware`1.<Invoke>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContextStage.<RunApp>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNon
Web config connection string and EF config:
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-MealPlanSignup.Web-20170303111008.mdf;Initial Catalog=aspnet-MealPlanSignup.Web-20170303111008;Integrated Security=True" providerName="System.Data.SqlClient" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
Based on the code, you were using the entity framework to create the custom cache for the ADAL authentication library.
And this issue is caused by the connection of SQL DB, the error has nothing to do with Katana or OWIN component. It is config issue or the SQL server issue, please check the connection for the entity framework could works well.
Below are two helpful articles for your reference:
Entity Framework Config File Settings
Connection Strings
https://blogs.msdn.microsoft.com/sqlexpress/2011/12/08/using-localdb-with-full-iis-part-1-user-profile/
The ADALTokenChache that visual studio builds out for you by default uses a dbcontext built out for the localdb, when i moved it to a test server which didnt have sqlserver express or localdb installed it bombed out. I just ended up adding the tokenCache table to a database we already had running and changed my connection string to use it instead. Fei Xue was correct, i appreciate his help and patients with someone trying to learn!

Resources