Search code examples
asp.netsqlsql-serverconnection-timeout

SQL Connection Forcibly Closed


I'm having difficulty with an SQL query against Server 2008 from IIS7. I have a VB.NET class library which runs an update statement. The underlying code used to create the connection hasn't changed, but suddenly the query is failing in our testing and development environments. It does, however, still work against the same server/database using the slightly older code in our production environment.

I've tried setting the connection timeout in the web.config and I'm at a loss to explain the cause.

The basic structure of the query is:

Dim conn = New SqlConnection()
conn.ConnectionString = "Data Source=someserver\sqlexpress2008;Initial Catalog=DatabaseName;User ID=sa;Password=pass"
conn.Open()
Using cmd As SqlCommand = conn.CreateCommand()
    cmd.CommandText = "UPDATE ..."
    cmd.Parameters.AddWithValue("@UName", user.name)
    cmd.ExecuteNonQuery() 'fails with error
End Using

The error is:

A transport-level error has occurred when sending the request to the server. (provider: TCP Provider, error: 0 - An existing connection was forcibly closed by the remote host.)

I've tried restarting IIS and the SQL server and I'm totally out of ideas. I just need a fix


Solution

  • This was a nightmare to track down. It turned out to be cause by a horrible quirk in VB.NET. Nullable datetimes seem to be coerced to DateTime.MinValue, which resulted in a DateTime.MinValue being inserted into an sql datetime. The fix was to check for either !property.HasValue && property.Value != DateTime.MinValue when setting the parameters for the command.