'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
Search our solution for missing scope.Complete() statements, or
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.
Solution 1:[1]
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 */);
Solution 2:[2]
I'm not aware of any existing R# plugin that checks for this, but you could certainly create one of your own. All you'd have to do is to detect a using statement with a variable declaration of the TransactionScope type, then iterate the contained statements looking for the Complete() call.
If you are interested in doing this, I recommend you download the ReSharper SDK and check out the Plugin Development Guide.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | flq |
| Solution 2 | Rais Alam |
