I had no luck with this question so I've produced this simple-as-possible-test-case to demonstrate the problem.
In the code below, is it possible to detect that the connection is unusable before trying to use it?
SqlConnection c = new SqlConnection(myConnString);
c.Open(); // creates pool
setAppRole(c); // OK
c.Close(); // returns connection to pool
c = new SqlConnection(myConnString); // gets connection from pool
c.Open(); // ok... but wait for it...
// ??? How to detect KABOOM before it happens?
setAppRole(c); // KABOOM
The KABOOM manifests as a error in the Windows event log;
The connection has been dropped because the principal that opened it subsequently assumed a new security context, and then tried to reset the connection under its impersonated security context. This scenario is not supported. See "Impersonation Overview" in Books Online.
...plus an exception in code.
setAppRole is a simple method to set an application role on the connection. It is similar to this...
static void setAppRole(SqlConnection conn) {
using (IDbCommand cmd = conn.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "exec sp_setapprole ";
cmd.CommandText += string.Format("@rolename='{0}'",myUser);
cmd.CommandText += string.Format(",@password='{0}'",myPassword);
cmd.ExecuteNonQuery();
}
}
In the real code an attempt is made to use sp_unsetapprole prior to closing the connection but it cannot always be guaranteed (inherited buggy multithreaded app). In any case it still seems reasonable to expect to be able to detect the kaboom before causing it.