0
votes

I have a program which would use the Application Role to write data to a SQL Server 2005.

using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
    SqlCommand sqlCommand = new SqlCommand();
    sqlCommand.Connection = sqlCon;
    sqlCommand.CommandType = CommandType.Text;
    sqlCommand.CommandText = 
               "EXEC sp_setapprole 'application Role name','password';";
    sqlCommand.CommandText += sqlComm;
    sqlCommand.CommandTimeout = 300;

    sqlCon.Open();
    int res = sqlCommand.ExecuteNonQuery();
}

This code is in a loop. for the first time, it's OK. In second iterator, it throws exception.

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. Event ID 18059 Source MSSQLSERVER

Is there anyone meet this problem before?

Best Regards,

2
Can you post the code of the loop, and is there any reason the SqlCommand object isn't wrapped in a using statement? - Kane

2 Answers

1
votes

turn off connection pooling, explicitly. by default is on and connection pooling does not work with unreversible impersonation like approles.

1
votes

The using{} statement calls IDispose at the end of the block thus killing your connection. https://msdn.microsoft.com/en-us/library/yh598w02.aspx using Statement (C# Reference)