12

Please read in the entirety before marking this as duplicate.

In a project that I am debugging I receive a SqlException saying the following:

Additional information: A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: SSL Provider, error: 0 - The wait operation timed out.)

This occurred during a debugging session where the previous session executed only seconds before without problem. Since the initial exception, I am unable to connect to the database server in this project. The exception is thrown on the SqlConnection.Open() method call.

The Background

This is not the first time that I have received this. Previously I struggled with it for two weeks eventually initiating a Microsoft support ticket for it. In that instance it turned out the ApplicationName property on the connection string was too long (we were using the fully qualified assembly name) and shortening it alleviated the problem.

This time around, there is

  • No ApplicationName value supplied
  • WinSocks is in its default state
  • Antivirus (ESET) was disabled and was not the issue.
  • Nothing was installed between a working and non-working debug session

Finally, on a whim, I created a new project whose sole purpose was to connect to this same SQL server. I copied the connection string from the non-working project, into the new project and it connects. Is there some kind of per-project connection caching going on? Something that survives a Clean>Rebuild and a restart of Visual Studio and Windows too?

Relevant Code

    public SqlConnection OpenSqlConnection(string connectionString)
    {
        var conn = new SqlConnection(connectionString);
        conn.Open();
        _connectionString = connectionString;
        var sb = new SqlConnectionStringBuilder(_connectionString);
        _server = sb.DataSource;
        _database = sb.InitialCatalog;
        return conn;
    }

The connection string that is being passed in is output from a SqlConnectionStringBuilder elsewhere in the application. The connection string is similar to: "Data Source=SERVER;Initial Catalog=DATABASE;Integrated Security=True;Connect Timeout=60"

CodeWarrior
  • 7,388
  • 7
  • 51
  • 78
  • are you using sql server Express? – Green Falcon Apr 24 '17 at 20:45
  • It has happend for me alot, whenever I see the contents of tables inside the visual studio, I can not rebuild. I have found myself that if I disable `SQL Server Windows NT - 64 bit` (64 bit is in my case) from task manager, I can rebuild the project. – Green Falcon Apr 24 '17 at 20:48
  • @CodeWarrior When you connect to the SqlServer , have you tried giving commandTime = 0 – loneshark99 Apr 24 '17 at 20:50
  • @Media Negative. I am connecting to SQL Server 2008 – CodeWarrior Apr 24 '17 at 21:00
  • @loneshark99 I never get that far. The connection never gets established. It is later on in the execution that I instance a SqlCommand and apply the connection to it. Exception is thrown on SqlConnection.Open() method call. – CodeWarrior Apr 24 '17 at 21:03
  • seeing the code might help us diagnose. –  Apr 24 '17 at 21:10
  • 1
    @CodeWarrior would it be possible to check how many connections are currently acitve in the Sql Server in question. I believe that info is in sys.connections and then if you see a spid for that machine in Sql Server, kill that spid. Then try connection again. – loneshark99 Apr 24 '17 at 21:40
  • @AgapwIesu I have added the code. It is pretty simple code, no frills or anything. – CodeWarrior Apr 24 '17 at 22:57
  • @loneshark99 I have identified two records for connections from my machine. How does one find a SPID and kill it based on machine connection? – CodeWarrior Apr 24 '17 at 22:57
  • 1
    it should be in sys.processes ( kill spid command should kill that connection) also do you close the connection, when you are done with the connection eg : using(var connection = new SqlConnection()) { } – loneshark99 Apr 24 '17 at 23:00
  • @loneshark99 Connections are closed after SqlCommand is completed elsewhere in the code. Pretty sure the SqlConnection is also disposed via using statement as well. Only two spids associated with my machine are from Management Studio. Nothing left over from my project application. – CodeWarrior Apr 24 '17 at 23:04
  • Does it work with a more recent version of SQL Server? (even the free express one) or is it the same? – Simon Mourier Apr 27 '17 at 22:19
  • Seems to be a SQL server instance thing. I have managed to get it to connect to other SQL server instances that are functionally identical (same version, same policies, etc). Interestingly, sometimes I will try those instances and they will not connect. I have 7 or 8 servers that I connect to, generally a Master server first, then one of the other servers second. Occasionally the connection to the master will go through, and a connection to a secondary server will fail. The oddities with this problem are making me irrationally angry. – CodeWarrior Apr 28 '17 at 08:41
  • In my case this error occurred when the server was on a remote network and the connection timeout was set to a very small value (I think 1 second which was still not enough to make a successful connection). I see you provided a sample connection string which has 60 seconds but it might be worth checking it again to make sure your case hasn't got anything to do with my root cause. – Varga Tamas May 01 '17 at 23:01
  • Nothing that I can see. Interestingly, given the timeout value in the connection string, it fails seemingly instantly. It "says" that it connected, but then fails during pre-login handshake. – CodeWarrior May 03 '17 at 00:09
  • Have you deleted the .NET Temporary files? – Ross Bush May 04 '17 at 18:02
  • Where would I find those? I assume they are separate from the build folders that get deleted on Clean? – CodeWarrior May 04 '17 at 18:07
  • I always blow away the temp files when oddities occur. Once in a while it solves a problem, however, I bet your issue is network related. It sounds like something has changed in regards to remote connections and/or authentication. Have you tried the connection with Integrated Security=false. Temp Files --> C:\Windows\Microsoft.NET\Framework<64>\\Temporary ASP.NET Files – Ross Bush May 04 '17 at 18:12
  • Ahh. This application does not use ASP.NET so I imagine that deleting those will no do anything beneficial. Interestingly, on a whim, I decided to uncomment the initializer line that sets the application name. The application I am running connects first to one database, then to another. It managed to connect to the first db this time, but not the second. I would love to understand what is going on here. This is infuriating. – CodeWarrior May 04 '17 at 18:31
  • OK, so after disabling and reenabling the Application Name property on the connection string a few times, both connections go through. I have no idea what this could possibly have to do with anything. It angers me absolutely to no end that the problem was alleviated in this fashion as it makes no sense. Thanks to all of you who helped me. I am pretty sure that I am going to encounter the problem again soon and this will not fix it next time. I am going to award the bounty to @Y.B. as he mentioned the Application Name property and its presence in the connection string. – CodeWarrior May 04 '17 at 18:39

4 Answers4

3

What did the trick for me is increasing the timeout on the connection string, since when connecting by vpn it took to long to establish the connection. You can do this by adding ;connection timeout = value

I got the same error when connecting an application tried to connect to sql server while I was on a vpn.

By default the timeout is set to 15 seconds.

Seems you already have 60secs, maybe you just need more...

Hope it helps!

StefanE
  • 103
  • 8
  • This just fixed it for me, in a completely unrelated app/context. When I left the field blank, it would error after 15 secs. When I changed it to 60 secs (well, 1 min), it connected instantly! – Zach Mierzejewski Oct 22 '18 at 19:27
2

Try explicitly adding Application Name=MyAppName; to the connection string. Auto-generated value from the assembly name might exceed some limit.

Check network settings for things like explicitly limited frame size. Reboot router if SQL Server is running on another machine.

Try adding Pooling=False; to the connection string and checking whether this solves the problem with repeated connections on application restart.

Y.B.
  • 3,526
  • 14
  • 24
  • Addition of Application Name property had no effect. Network settings have not changed (recall, this happened between one debug session and the next, a timespan of a minute at most during which all I was doing was hitting the stop button in VS and the start/debug button. Adding Pooling=false had no effect. – CodeWarrior May 03 '17 at 00:07
  • OK. Can you try connecting with login and password instead of Integrated Security? Is Data Source=SERVER identified by IP or Name? If it's Name is it in local hosts file? – Y.B. May 03 '17 at 23:54
  • Connecting via SQL Authentication also exhibits the problem. The Data Source is by hostname and the hostname is in HOSTS. Connecting via IP address also exhibits the problem. Keep in mind that the error message states that it connected to the database, and that an error occurred during the pre-login handshake. Network connectivity to the server *should not* be a problem in these cases as it says it has successfully connected to the server. – CodeWarrior May 04 '17 at 01:28
  • 1
    E-e-er... Thanks, but I'd rather not receive reputation points for the answer that did not solve the problem. Have you given up or found the solution? Judging by the question votes, quite a few members (me included) would appreciate if you could share it. – Y.B. May 04 '17 at 22:02
  • One more thing to check came to my mind: does the project that exhibit the problem have "SQL Server Debugging" activated in "Configuration Properties" -> "Debugging"? Does the problem persist if run in other Project Configurations? – Y.B. May 04 '17 at 22:16
1

This problem can be related to a firewall in the middle that is doing SSL inspection.

I Suggest you either try again using another connection not doing SSL inspection, or ask your firewall admin to create an exemption for the source and/or destination you are connecting to,

Cheers!

0

So this issue continued to plague me and it appears that it was a function of lag from my home network (I am a remote developer) and the work network accessed over a VPN. I have a 100ms average ping time to servers on the work network.

The real oddity is that the connection string worked without problem for months, then suddenly stopped. At the time, the Application Name value was something like Application Name = "MyProgram.DAL. Culture=en, PublicKeyToken=1a1a1a1a1a1a1a1a, Version=1.0.0.0". In other words a fully qualified assembly name. Eventually I changed this to the shortened "MyProgram.DAL" type name and it worked again.

Some months later, again I was beset by it. And I happened to find that if I just ate the exception and waited a few ticks, everything was fine. The application would happily use the connection even though it reported that it failed. Thus, I changed the method to the below:

    public SqlConnection OpenSqlConnection(string connectionString)
    {
        var conn = new SqlConnection(connectionString);
        var retries = 10;
        while (conn.State != ConnectionState.Open && retries > 0)
        {
            try
            {
                conn.Open();
            }
            catch (Exception)
            {

            }
            Thread.Sleep(500);
            retries--;
        }

        _connectionString = connectionString;
        var sb = new SqlConnectionStringBuilder(_connectionString);
        _server = sb.DataSource;
        _database = sb.InitialCatalog;
        return conn;
    }
CodeWarrior
  • 7,388
  • 7
  • 51
  • 78