CS.DB.CLOSE.FINALLY

Close data base connections in 'finally' block.

This rule triggers whenever a call to the closing method from given connection type is not present in a 'finally' block. If the resource is used via a 'using' statement the rule will not trigger.

You can specify a list of type names and the closing method names for each of these types. Full type name (as a regular expression): Full name of a type for which the rule ensures that a call to its closing method is placed within finally block.

Method (as a regular expression): Name of the method that is to be used for closing the resource. If a connection type overrides a closing method from an ancestor class, then in the 'Full type name' parameter, you should specify the name of the first ancestor class that implements this method.

Vulnerability and risk

Failure to close and release database connections can cause other users to experience long waits for connections. If connections are left unclosed, other users may have to wait for the connections to be returned by the database.

Mitigation and prevention

Ensure that your code is structured to close and release DB resources in all cases, even in exception and error conditions. By including the close statement in a finally block, the method will get called under all circumstances.

Vulnerable code example

Copy
  using System.Data.SqlClient;
  namespace myApplication
  {
      class MyClientApplication
      {
          public void myMethod(SqlConnection connection)
          {
              try
              {
                 connection.Open() ;
                 // do some thing
             }
             catch(Exception exc)
             {
                 //Handle error
             }
             connection.Close(); // VIOLATION
         }
     }
 }

Fixed code example

Copy
  using System.Data.SqlClient;
  namespace myApplication
  {
      class MyClientApplication
      {
          public void myMethod(SqlConnection connection)
          {
              try
              {
                 connection.Open();
                 // do some thing
             }
             catch(Exception exc)
             {
                 //Handle error
             }
             finally
             {
                 connection.Close(); // FIX
             }
         }
     }
 }