Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - How do I check for missing scope.Complete() statements?

Programmers on my team sometimes open a transaction and forget to include the scope.Complete() statement (see code block below). Any ideas on ways to either

  1. Search our solution for missing scope.Complete() statements, or

  2. Have Visual Studio automatically highlight or raise a warning for missing scope.Complete() statements?

Here's the line we miss:

 using(TransactionScope scope = new TransactionScope())
 {
      /* Perform transactional work here */
      scope.Complete(); <-- we forget this line
      /* Optionally, include a return statement */
 }

What I have tried
 
I have tried using a ReSharper Custom Pattern for this purpose, with no luck. Ideally I would search for something like:

using(TransactionScope scope = new TransactionScope())
{
    $statements1$
    [^(scope.Complete();)]
    $statements2$
}

However, ReSharper only accepts regular expressions for identifiers, not for statements, so this does not appear to work (http://www.jetbrains.com/resharper/webhelp/Reference__Search_with_Pattern.html).

Any ideas? I'm open to using other plugins or tools as well.

like image 857
Ben Paul Avatar asked Jun 18 '12 14:06

Ben Paul


1 Answers

Could you force programmers to use a custom API instead of the low-level scope.Complete stuff?

A closure will force usage of .Complete():

public static void Do(this TransactionScope scope, Action action) {
  using (scope) {
    action();
    scope.Complete();
  }
}

Then you could do:

new TransactionScope().Do(() => /* Transactional stuff */);
like image 117
flq Avatar answered Oct 03 '22 11:10

flq