Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: TCP Provider, error: 35 - An internal exception was caught) #1412

Closed
disl opened this issue Nov 27, 2021 · 15 comments
Assignees

Comments

@disl
Copy link

disl commented Nov 27, 2021

Describe the bug

On "System.Data.SQLClient" (WinForms- und Xamarin-App) connection open works fine.

A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: TCP Provider, error: 35 - An internal exception was caught)

Exception message:
Stack trace:

at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) in D:\a\_work\1\s\src\Microsoft.Data.SqlClient\netcore\src\Microsoft\Data\SqlClient\SqlInternalConnection.cs:line 616 at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) in D:\a\_work\1\s\src\Microsoft.Data.SqlClient\netcore\src\Microsoft\Data\SqlClient\TdsParser.cs:line 1315 at Microsoft.Data.SqlClient.TdsParser.ConsumePreLoginHandshake(Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean& marsCapable, Boolean& fedAuthRequired) in D:\a\_work\1\s\src\Microsoft.Data.SqlClient\netcore\src\Microsoft\Data\SqlClient\TdsParser.cs:line 955 at Microsoft.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover, SqlAuthenticationMethod authType) in D:\a\_work\1\s\src\Microsoft.Data.SqlClient\netcore\src\Microsoft\Data\SqlClient\TdsParser.cs:line 501 at Microsoft.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) in D:\a\_work\1\s\src\Microsoft.Data.SqlClient\netcore\src\Microsoft\Data\SqlClient\SqlInternalConnectionTds.cs:line 1881 at Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) in D:\a\_work\1\s\src\Microsoft.Data.SqlClient\netcore\src\Microsoft\Data\SqlClient\SqlInternalConnectionTds.cs:line 1585 at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) in D:\a\_work\1\s\src\Microsoft.Data.SqlClient\netcore\src\Microsoft\Data\SqlClient\SqlInternalConnectionTds.cs:line 1433 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) in D:\a\_work\1\s\src\Microsoft.Data.SqlClient\netcore\src\Microsoft\Data\SqlClient\SqlInternalConnectionTds.cs:line 525 at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) in D:\a\_work\1\s\src\Microsoft.Data.SqlClient\netcore\src\Microsoft\Data\SqlClient\SqlConnectionFactory.cs:line 136 at Microsoft.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) in D:\a\_work\1\s\src\Microsoft.Data.SqlClient\netcore\src\Common\src\Microsoft\Data\ProviderBase\DbConnectionFactory.cs:line 123 at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) in D:\a\_work\1\s\src\Microsoft.Data.SqlClient\netcore\src\Microsoft\Data\ProviderBase\DbConnectionPool.cs:line 822 at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) in D:\a\_work\1\s\src\Microsoft.Data.SqlClient\netcore\src\Microsoft\Data\ProviderBase\DbConnectionPool.cs:line 1759 at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) in D:\a\_work\1\s\src\Microsoft.Data.SqlClient\netcore\src\Microsoft\Data\ProviderBase\DbConnectionPool.cs:line 1222 at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) in D:\a_work\1\s\src\Microsoft.Data.SqlClient\netcore\src\Microsoft\Data\ProviderBase\DbConnectionPool.cs:line 1130
at Microsoft.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) in D:\a\_work\1\s\src\Microsoft.Data.SqlClient\netcore\src\Microsoft\Data\ProviderBase\DbConnectionFactory.cs:line 122 at Microsoft.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) in D:\a_work\1\s\src\Microsoft.Data.SqlClient\netcore\src\Common\src\Microsoft\Data\ProviderBase\DbConnectionInternal.cs:line 350
at Microsoft.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) in D:\a\_work\1\s\src\Microsoft.Data.SqlClient\netcore\src\Common\src\Microsoft\Data\ProviderBase\DbConnectionClosed.cs:line 39 at Microsoft.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource1 retry, SqlConnectionOverrides overrides) in D:\a_work\1\s\src\Microsoft.Data.SqlClient\netcore\src\Microsoft\Data\SqlClient\SqlConnection.cs:line 1838
at Microsoft.Data.SqlClient.SqlConnection.Open(SqlConnectionOverrides overrides) in D:\a_work\1\s\src\Microsoft.Data.SqlClient\netcore\src\Microsoft\Data\SqlClient\SqlConnection.cs:line 1335
at Microsoft.Data.SqlClient.SqlConnection.Open() in D:\a_work\1\s\src\Microsoft.Data.SqlClient\netcore\src\Microsoft\Data\SqlClient\SqlConnection.cs:line 1304
at GetShift_Maui_2.Services.StaffService.GetItemAsync(String Email) in C:\Users\dnepr\source\repos\GetShift_Maui_2\GetShift_Maui_2\Services\StaffService.cs:line 59

To reproduce

Include a complete code listing (or project/solution) that we can run to reproduce the issue.

Partial code listings, or multiple fragments of code, will slow down our response or cause us to push the issue back to you to provide code to reproduce the issue.

...
using Microsoft.Data.SqlClient;
...

...
 public static string g_conn_str = "Data Source=.....amazonaws.com,1433;Initial Catalog=MyDB;Encrypt=False; TrustServerCertificate=false;User ID=admin;Password=mypass";
...

 public async Task<StaffsType> GetItemAsync(string Email)
        {
            StaffsType item = new StaffsType ();

            try
            {
                using (SqlConnection connection = new SqlConnection(App.g_conn_str))
                {
                    connection.Open();   //   **<--- Error happens here**

                    string selectQuery = "SELECT TOP 1 * FROM [dbo].fu_staffs_by_email ('" + Email + "')";

                    SqlCommand command = new SqlCommand(selectQuery, connection);
                    command.Connection = connection;
                    command.CommandText = selectQuery;
                    var reader = await command.ExecuteReaderAsync();
                    if (!reader.HasRows)
                        return null;

                    while (reader.Read())
                    {
                        item.Id = Convert.ToInt32(reader["Id"]);
                        item.Email = Convert.ToString(reader["Email"]);
                        item.ClientsId = Convert.ToInt32(reader["ClientsId"]);
                        item.Password = Convert.ToString(reader["Password"]);
                        item.FullName = Convert.ToString(reader["FullName"]);
                        item.Staffs_Types_Shortmark = Convert.ToString(reader["Staffs_Types_Shortmark"]);
                        item.ClientName = Convert.ToString(reader["ClientName"]);
                    }
                    return await Task.FromResult(item);
                }
            }
            catch (SqlException ex)
            {
                var msg = ex.Message;
                var stack_trace = ex.StackTrace;
                Debug.WriteLine(ex);
                return null;
            }
            catch (Exception ex)
            {
                var msg = ex.Message;
                Debug.WriteLine(ex);
                return null;
            }
        }

Expected behavior

A clear and concise description of what you expected to happen.

Further technical details

Microsoft.Data.SqlClient version: 4..0.0
.NET target: net6.0-android;net6.0-ios;net6.0-maccatalyst;net6.0-windows10.0.19041
SQL Server version: 2014
Operating system: Windows 11 Pro (Version 10.0.22000 Build 22000)

Additional context
Add any other context about the problem here.

@JRahnama
Copy link
Contributor

@disl thanks for bringing this up to our attention. We will look into this shortly and will update you accordingly.

@Kaur-Parminder
Copy link
Contributor

@disl What is the project type you are using in the Repro above? Just WinForms or Xamrin App(Xamrin.Forms)? It will help if you attach sample code with just "Hello world" level.

@disl
Copy link
Author

disl commented Dec 22, 2021

@disl What is the project type you are using in the Repro above? Just WinForms or Xamrin App(Xamrin.Forms)? It will help if you attach sample code with just "Hello world" level.

@Kaur-Parminder An error message happens in a MAUI (a successor of Xamarin, currently only works in the preview version of Visual Studio). A "Hello World" sample code could look exactly like above, unfortunately I cannot publish my access to the Amazon database here.

@Kaur-Parminder
Copy link
Contributor

@disl I did a setup for MAUI. I tested with Windows Machine and Android Emulator. I was able to make connection successfully with localhost and Remote connection with Android emulator (I see some permission error but related to internal access). For localhost I have used the connection string "Data Source=tcp:localhost;Database=xxx;Integrated Security=true;Encrypt=false" and for Remote connection "Data Source = xxxx;Database=xxxx; UID=xxxx; PWD=xxxxx; Connection Timeout = 30;TrustServerCertificate=true;" Please Note Encrypt=false and TrustServerCertificate=true . You can read more about it here . You may also test with version 3.0 without Encrypt=false and TrustServerCertificate=true .

@disl
Copy link
Author

disl commented Dec 28, 2021

@Kaur-Parminder

  1. In WinForms that works
  2. Unfortunately error happens in MAUI-project anyway. I have tried your variant with version 4 and abbreviated variant with versions 2 and 3.

@rangitoto72
Copy link

Additional Info:
I too get the same error

OSX
Dot Net core 3.1.10 ( Web API )
Microsoft.Data.SQLClient V 3.0.1
Doesnt matter if i run in Visual Studio MAC or VSCode, same result.

Connection String:
"Connection": "Data Source=[SERVER],1433;Initial Catalog=[DATABASE];User ID=[USERID];Password=[PASSWORD];Connection Timeout=30;"

This works fine, as soon as i change Microsoft.Data.SQLClient to 4.0 Error
A connection was successfully established with the server, but then an error occurred......

Tried using recommendations as per above examples, still errors.
Rollback to V3.0.1 - No issues , working fine in Prod / Dev

@JRahnama
Copy link
Contributor

@rangitoto72 have you tried adding Encrypt=false to your connection string?

@disl
Copy link
Author

disl commented Dec 31, 2021

@Kaur-Parminder , @JRahnama

EXPERIMENT (MAUI-Android, Emulator, Microsoft.Data.SqlClient-Versionen: 2,3,4):
1.
Data Source=...amazonaws.com,1433;Initial Catalog=...;User ID=...;Password=...;Connection Timeout=30;Integrated Security=true;Encrypt=false;TrustServerCertificate=true;
2.
Data Source=...amazonaws.com,1433;Initial Catalog=...;User ID=...;Password=...;Connection Timeout=30;Encrypt=false;TrustServerCertificate=true;

RESULT:
A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: TCP Provider, error: 35 - An internal exception was caught)

@chandra-arifin
Copy link

any solution to this problem?

@leehonys
Copy link

leehonys commented Aug 3, 2022

同样的问题。MAUI 运行调试windows10应用的时候是没问题的,但是运行安卓的时候,就提示:
A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: TCP Provider, error: 35 - An internal exception was caught).
English Message : Connection open error . A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: TCP Provider, error: 35 - An internal exception was caught)
Source=SqlSugar
StackTrace:
at SqlSugar.AdoProvider.GetDataReader(String sql, SugarParameter[] parameters)
at SqlSugar.QueryableProvider1[[System.Int32, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].GetData[Int32](KeyValuePair2 sqlObj)
at SqlSugar.QueryableProvider1[[System.Int32, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]._ToList[Int32]() at SqlSugar.QueryableProvider1[[System.Int32, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ToList()
at SqlSugar.QueryableProvider`1[[MauiApp1.Data.RiXiaoshou, MauiApp1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].Count()
at MauiApp1.MainPage.GetDataTotalCount(DateTime startDate, DateTime endDate, String pinpai) in F:\Projects\Study\MauiApp1\MainPage.xaml.cs:line 86
at MauiApp1.MainPage.FindRixiaoshus_Clicked(Object sender, EventArgs e) in F:\Projects\Study\MauiApp1\MainPage.xaml.cs:line 127
at System.Threading.Tasks.Task.<>c.b__128_0(Object state)
at Android.App.SyncContext.<>c__DisplayClass2_0.b__0() in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/Android.App/SyncContext.cs:line 36
at Java.Lang.Thread.RunnableImplementor.Run() in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/Java.Lang/Thread.cs:line 36
at Java.Lang.IRunnableInvoker.n_Run(IntPtr jnienv, IntPtr native__this) in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/obj/Release/net6.0/android-33/mcw/Java.Lang.IRunnable.cs:line 84
at Android.Runtime.JNINativeWrapper.Wrap_JniMarshal_PP_V(_JniMarshal_PP_V callback, IntPtr jnienv, IntPtr klazz) in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/Android.Runtime/JNINativeWrapper.g.cs:line 22

@chandra-arifin
Copy link

i try MAUI with localhost sql server, but failed too. handshake error . winforms works fine.
BUT MAUI connect to sql azure (No TLS / Security) works fine, with TLS => Error handshake

@anwarulmustafa
Copy link

My connection string is working with windows but with android have the same error
A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: TCP Provider, error: 35 - An internal exception was caught)
Nothing is working with me. Please help

@lcheunglci
Copy link
Contributor

I am able to reproduce the error 35 on my simple maui app on the android emulator as well. I'll further investigate to see if I can figure out how to set up the self-signed certificate on android emulator and keep you all posted.

@lcheunglci
Copy link
Contributor

If anyone is curious, I managed to get it working on an android emulator running android 21 and Sql Server 2019 with MDS 5.0. I posted my reply here

@cheenamalhotra
Copy link
Member

Closing as solution posted above.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

9 participants