sql managed instance authentication fails when using AAD integrated method - azure-active-directory

I have setup hybrid identity with Azure Active Directory with Federation (AD FS) method. I have created sql managed instance and added a user as Active directory Admin. Now, I tried connecting to this sql managed instance from a domain joined VM logged in as the user using AAD integrated method. The connection failed with the following error:
===================================
Cannot connect to {},3342.
===================================
One or more errors occurred. (mscorlib)
Program Location:
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at System.Data.SqlClient.SqlInternalConnectionTds.GetFedAuthToken(SqlFedAuthInfo fedAuthInfo)
at System.Data.SqlClient.SqlInternalConnectionTds.OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK)
at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover, Boolean isFirstTransparentAttempt, Boolean disableTnir)
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, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling, SqlAuthenticationProviderManager sqlAuthProviderManager)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource1 retry)
at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.Open()
at Microsoft.SqlServer.Management.SqlStudio.Explorer.ObjectExplorerService.ValidateConnection(UIConnectionInfo ci, IServerType server)
at Microsoft.SqlServer.Management.UI.ConnectionDlg.Connector.ConnectionThreadUser()
===================================
One or more errors occurred. (mscorlib)
Program Location:
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task1.GetResultCore(Boolean waitCompletionNotification) at System.Threading.Tasks.Task1.get_Result()
at System.Data.SqlClient.SqlInternalConnectionTds.<>c__DisplayClass134_1.b__0()
at System.Threading.Tasks.Task`1.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
===================================
Failed to parse XML blob.
Reason: XML document must have a top level element.
Line: 0, Position: 0
Text: (null) (System.Data)
Program Location:
at ADALNativeWrapper.ADALGetAccessToken(String username, IntPtr password, String stsURL, String servicePrincipalName, ValueType correlationId, String clientId, Boolean* fWindowsIntegrated, Int64& fileTime)
at System.Data.SqlClient.ActiveDirectoryNativeAuthenticationProvider.<>c__DisplayClass2_0.b__0()
at System.Threading.Tasks.Task`1.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
SSMS version(latest):15.0.18384.0
Please help me resolve this issue.

According to the error that you have received, please check whether the federated-on premises domain is configured for SSO for pass through authentication and password hash authentication. Also, check whether latest version of SQL Server Management Studio or SQL Server Data Tools is installed or not on the VM through which you are trying to connect to the database.
Next, confirm whether the application for which you are connecting to the database has service principal API permissions set or not. ‘Directory.Read.All’ application API permissions need to be added for the application with the assigned Azure AD Admin set as the consent. The Service principal for ‘SQL Managed Instance Contributor’ role should be set for the Azure AD Admin credentials.
For Azure Active Directory – Integrated authentication method, before connecting to the database, make sure you are entering the database name in the ‘Options’ section (bottom right corner) in the SSMS database connection dialog box. Also, check the connection string for parameters like ‘Active Directory Integrated’ and ‘Integrated Security=True’ for successful connection.
Please refer the below links for your reference: -
https://learn.microsoft.com/en-us/azure/azure-sql/database/authentication-aad-configure?tabs=azure-powershell
https://azure.microsoft.com/en-gb/blog/windows-azure-now-supports-federation-with-windows-server-active-directory/
https://learn.microsoft.com/en-us/azure/azure-sql/database/authentication-aad-overview
Thanking you,

Related

Can not connect to local database via SSMS

My local database connection was working fine few hours ago. but now I can not connect to local database via SSMS. I did not change any settings nor anything. I was working with my database from SSMS and then shutdown my laptop. Now I can connect to it.
Component name Version
------------------------------------------------------
Microsoft SQL Server Management Studio 12.0.2254.0
Microsoft SQL Server 2014
I can connect to other databases of different servers but can not access my local database. The error is showing ::
===================================
Cannot connect to ---.
===================================
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)
(.Net SqlClient Data Provider)
------------------------------ For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft%20SQL%20Server&EvtSrc=MSSQLServer&EvtID=2&LinkId=20476
------------------------------ Error Number: 2 Severity: 20 State: 0
------------------------------ Program Location:
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
exception, Boolean breakConnection, Action1 wrapCloseInAction) at
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at
System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo,
SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout,
Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean
integratedSecurity, Boolean withFailover) at
System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo
serverInfo, String newPassword, SecureString newSecurePassword,
Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean
withFailover) at
System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo
serverInfo, String newPassword, SecureString newSecurePassword,
Boolean redirectedUserInstance, SqlConnectionString connectionOptions,
SqlCredential credential, TimeoutTimer timeout) at
System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer
timeout, SqlConnectionString connectionOptions, SqlCredential
credential, String newPassword, SecureString newSecurePassword,
Boolean redirectedUserInstance) at
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity
identity, SqlConnectionString connectionOptions, SqlCredential
credential, Object providerInfo, String newPassword, SecureString
newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString
userConnectionOptions, SessionData reconnectSessionData) at
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions
options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo,
DbConnectionPool pool, DbConnection owningConnection,
DbConnectionOptions userOptions) at
System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection
owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions
userOptions) at
System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection
owningConnection, TaskCompletionSource1 retry, DbConnectionOptions
userOptions, DbConnectionInternal oldConnection, DbConnectionInternal&
connection) at
System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection
outerConnection, DbConnectionFactory connectionFactory,
TaskCompletionSource1 retry, DbConnectionOptions userOptions) at
System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection
outerConnection, DbConnectionFactory connectionFactory,
TaskCompletionSource1 retry, DbConnectionOptions userOptions) at
System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource1
retry) at
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource1
retry) at System.Data.SqlClient.SqlConnection.Open() at
Microsoft.SqlServer.Management.SqlStudio.Explorer.ObjectExplorerService.ValidateConnection(UIConnectionInfo
ci, IServerType server) at
Microsoft.SqlServer.Management.UI.ConnectionDlg.Connector.ConnectionThreadUser()
===================================
The system cannot find the file specified
Go to StartMenu Run - type services.msc - look for service named SQL Server (MSSQLSERVER). Right click on it and start.

WebMatrix's Web Deploy (for Wordpress Brandoo) cannot access remote MSSQL database

I am having trouble configuring the databases MSSQL for WebDeploy (for a Wordpress Brandoo site). I will show the steps that have seemed to be correct so far. I am very new at this and it has taken me days just to get this far:
Installed WebMatrix on local and remote computers.
Installed Wordpress Brandoo on local using Web Platform Installer.
Created an empty site in ISS on Remote, added permissions and enabled remote management.
On remote computer, using Web Matrix, I opened the site folder (the empty site I created in ISS), right-clicked and chose "New SQL Server Connection". For "Database" I put the same database name as my local Wordpress. I chose "Database Authentication" and put in the same Wordpress username and password as my local machine but but I got an error message:
Login failed for user 'wordpressuser652'.
System.Data.SqlClient.SqlException (0x80131904): Login failed for user 'wordpressuser652'.
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK)
at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.Open()
at Microsoft.WebMatrix.DatabaseManager.SqlDatabase.SqlDatabaseProvider.TestConnection(String connectionString)
at Microsoft.WebMatrix.DatabaseManager.IisDbManagerModuleService.TestConnection(DatabaseConnection databaseConnection, String configPathState)
at Microsoft.WebMatrix.DatabaseManager.Client.ClientConnection.Test(ManagementConfigurationPath configPath)
at Microsoft.WebMatrix.DatabaseManager.Client.DatabaseHierarchyInfo.EnsureLoaded()
ClientConnectionId:2cd9db2c-94bc-4838-b6b7-758b5d6cbca0
So instead I chose "Windows Authenticaiton". The database appeared in the WebMatrix database section (althought it didn't have tables like on the local machine.
I right clikced the new databse connection on the remote WebMatrix and chose "copy connection string". Then I went to IIS on the remote computer, right clicked my site and chose Web Deploy>Configure Web Deploy Publishing. I pasted in the connection string and sent PublishSettings the file to the local computer.
On the local computer, in Web Matrix, I clicked to publish my site and opened the PublishSettings file. I had to put in my IP address instead of the default url provided. The settings were vailidated successfully.
But during the publish compatibility test it said the database was not available:
When I tried to continue I got the following error:
Clicking "Copy Details" gave the following error:
Could not publish the site. Could not publish to the remote database. Please ensure the publish profile contains a database and verify that the remote database is accessible.
Error detail:
(20/03/2015 5:23:56 PM) An error occurred when the request was processed on the remote computer.
at Microsoft.Web.Deployment.StatusThreadHandler.CheckForException()
at Microsoft.Web.Deployment.AgentClientProvider.RemoteDestSync(DeploymentObject sourceObject, DeploymentSyncContext syncContext, Nullable`1 syncPass, String syncSessionId)
at Microsoft.Web.Deployment.DeploymentObject.SyncToInternal(DeploymentObject destObject, DeploymentSyncOptions syncOptions, PayloadTable payloadTable, ContentRootTable contentRootTable, Nullable`1 syncPassId, String syncSessionId)
at Microsoft.Web.Deployment.DeploymentObject.SyncTo(DeploymentProviderOptions providerOptions, DeploymentBaseOptions baseOptions, DeploymentSyncOptions syncOptions)
at Microsoft.Web.Deployment.DeploymentObject.SyncTo(String provider, String path, DeploymentBaseOptions baseOptions, DeploymentSyncOptions syncOptions)
at Microsoft.Web.Deployment.DeploymentObject.SyncTo(DeploymentWellKnownProvider provider, String path, DeploymentBaseOptions baseOptions, DeploymentSyncOptions syncOptions)
at Microsoft.WebMatrix.Deployment.WebDeployWorker.Execute(CommandManager commandManager, CertificateValidationService certificateValidationService, Boolean skipHiddenFiles)
Missing source parameter 'Database User Password' (Password for the database user name.). This must be set for successful synchronization.
at Microsoft.Web.Deployment.ParameterizationRuleHandler.PreSync(DeploymentSyncContext syncContext)
at Microsoft.Web.Deployment.DeploymentSyncContext.ProcessSync(DeploymentObject destinationObject, DeploymentObject sourceObject)
at Microsoft.Web.Deployment.DeploymentObject.SyncToInternal(DeploymentObject destObject, DeploymentSyncOptions syncOptions, PayloadTable payloadTable, ContentRootTable contentRootTable, Nullable`1 syncPassId, String syncSessionId)
at Microsoft.Web.Deployment.DeploymentAgent.HandleSync(DeploymentAgentAsyncData asyncData, Nullable`1 passId)
It says the database user password is missing. But I have used Windows Authentication on the server and specified that in the connection string. Is it necessary to use Database Authentication on the server? If so is anybody able to tell me why Database Authentication could not connect on the server (according to the first error message)? Am I doing this all wrong? is there an easier way? If you know how to do it I would really appreciate some simple steps because I am very new to this. Much appreciated.
Additional info:
Local system: Windows 7.
Remote system: Windows Server 2012, IIS 8.
Web Matrix 3

SqlDependency.Start method fails after deployment

After implementing caching for my ASP MVC 5 app, and using SqlDependency and service broker, everything works fine on the local database. I get notifications when a specific change occurs in the database.
However, after deploying the application to production machine, call to SqlDependency.Start(string connectionString) fails by throwing an exception:
System.Data.SqlClient.SqlException: Login failed for user 'sa'.
with the following stack trace (system calls included, calls within my app code - excluded):
[SqlException (0x80131904): Login failed for user 'sa'.]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +6749670
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +815
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +4515
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +84
System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) +53
System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) +368
System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) +6777754
System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) +6778255
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData) +878
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) +6781425
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) +2105
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) +1089
System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +6785863
System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry) +233
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +278
System.Data.SqlClient.SqlConnection.Open() +239
Since the local and production database are kept in sync (and one was initially restored from the other one) DB settings are the same - I checked this to be sure, though.
I'm quite certain that service broker is enabled for the production DB.
What kind of IIS configuration should I consider important, which may cause this difference? I'm using Sql Server Express at the moment. Also, I don't use SqlCacheDependency but only SqlDependency.
This isn't a Service broker issue.
The error is: Login failed for user 'sa'
Check your connection credentials. Does your app allow the credentials to be modified at run-time? I'd recommend you do allow flexible configuration at deployment.
Even if you checked, can you guarantee that the deployment SQL server instance has the same SQL credentials, this may be the case even if you restored your development database.

Azure and SQL Server: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server

Using Azure with SQL Server. In 30% of the cases where the SimpleRoleProvider is implicitly called we get an error: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server. The error occurs frequently but is not reproducible. It looks like a timeout..
[Authorize(Roles = "Administrator")]
public class AdminController : Controller
{
...
}
The stack trace looks like:
[Win32Exception (0x80004005): Access is denied]
[SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)]
System.Data.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) +889
System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) +307
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions) +434
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +225
System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) +37
System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnectionOptions userOptions) +558
System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnectionOptions userOptions) +67
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) +1052
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +78
System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +167
System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) +143
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +83
System.Data.SqlClient.SqlConnection.Open() +96
System.Web.DataAccess.SqlConnectionHolder.Open(HttpContext context, Boolean revertImpersonate) +88
System.Web.DataAccess.SqlConnectionHelper.GetConnection(String connectionString, Boolean revertImpersonation) +239
System.Web.Security.SqlRoleProvider.GetRolesForUser(String username) +762
WebMatrix.WebData.SimpleRoleProvider.GetRolesForUser(String username) +54
System.Web.Security.RolePrincipal.IsInRole(String role) +9461104
We don't have this problem on our own server. Is this a configuration issue? We are using the free trail version of Azure yet.
--- ADDITION ---
The bad thing is that the MVC-framework "handles" the request, in the example given (Role
Management). The use of the framework is to add an abstraction layer to handle "domain request" conveniently. So what to do in this case?
Thanks in advance for any help!
I assume by Azure and SQL Server you mean the SAAS Azure SQL Database (the names change faster than I can keep track), not the IAAS SQL Server on Windows Azure. First thing ou need to determine wether your application is being throttled, see Connection Constraints and give this article a good, thorrough read: Causes of Connection Termination. If your application is being throttled then you need to revisit your design and address the specific reason why you're being throttled.
It's expected on SQL Azure. It should happen on about 0.5% of the time, not 30%.
Here's a previous question that addressed this topic
Connection failures in SQL Azure are common. This is because your
application will create a connection pool but while your side thinks
these connections are over, Azure could terminate them at their end
and you will never know about it.
You should implement a retry logic on your code in case one of these timeouts occur. Microsoft already has a library for this: the Transient Fault Handling Application Block

Cannot open database <database> requested by the login. The login failed. Login failed for user <user>

When I access the database with management studio, everything works, I access the tables... but when I run the Windows Service that is accessing the database with the same user, so, throws this error.
System.Data.EntityException: The underlying provider failed on Open. ---> System.Data.SqlClient.SqlException: Cannot open database "sttcoletorsbvt" requested by the login. The login failed.
Login failed for user 'usr_stt_coletor'.
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK)
at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, SqlConnection owningObject)
at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, TimeoutTimer timeout)
at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, TimeoutTimer timeout, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options)
at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.SqlClient.SqlConnection.Open()
at System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure)
--- End of inner exception stack trace ---
at DynamicModule.ns.Wrapped_IServicoConfiguracaoColetor_3f81c81b8be24d3998bbc85dfa25d87f.SelecionarConfiguracao()
at Infraero.TINE3.STTColetor.Negocio.Coletor.ColetarBilhetes(String arquivoParaProcessar)
at Infraero.TINE3.STTColetor.WindowsService.ManipuladorBilhetes.RealizarProcedimentoColeta(String caminhoArquivo)
at Infraero.TINE3.STTColetor.WindowsService.ServicoColetor.RealizarColeta()
How can I solve that?
Try ensuring that the user has access to the initial catalog in your connection string. If your connection string doesn't have an initial catalog, add one that the user has access to. This could explain why it works in one case and not the other.

Resources