In the past few days I was moved to analyze some legacy code from a huge web application written by a company I work with. I have to write some new modules to integrate in this application; but while I was reviewing the code to ‘learn’ the style and code format used (to try to build code similar to the one already written for uniformity and ease of maintenance for the other guys I work with), I faced code like this:
using (DbCommand c = CurrentDatabase.GetSqlStringCommand(sql))
CurrentDatabase.AddInParameter(c, "UserId", DbType.String, UserName);
List<Filiale> list = new List<Filiale>();
dr = CurrentDatabase.ExecuteReader(c);
Can you see the bug here ?
The DataReader is created, used ... and never closed...that is: a big resource leak! I looked around and found some more code similar to this one.
The solution is indeed huge (60+ projects) and with many classes for the data access written in an ‘old-style’ fashion. So we need a way to easily identify the ‘critical’ sections and check the code for similar resource leaks, because we do not want to check file by file if we can avoid it. I thought of it a bit and a solution came into my mind.
The best practice is to wrap each DataReader inside a using statement to clean up resources properly, and it is already used in many code fragments of the solution, so:
Why can’t I try to use the Visual Studio ‘Find and Replace’ feature with some regular expression, looking for all the pieces of code that contains an ExecuteReader() call not wrapped inside a using statement?
So I opened my favorite Regex editor an wrote down something like this:
It basically looks for any line that contains the ‘ExecuteReader’ string and do not contains the ‘using’ string-
I tested it with some code snippets and seemed to work, the bad news is: you can’t use this in Visual Studio..because the regex syntax is a bit different from the standard, check the VS or the MSDN help for the syntax.
You have to modify the expression like this:
Using this method you can easily identify all the code to check to fix the bug mentioned above. A similar technique can be used to identify anything you like in your code.
- NUnitit: Visual Studio Addin to support NUnit and some customizations to it (26/08/2015)
- Resharper and the OutOfMemoryException problem (26/08/2015)
- Spot Hidden Exceptions using IntelliTrace (26/08/2015)
- Visual Studio 2010 designer error: Value cannot be null. Parameter name: objectType (26/08/2015)
- VS2008 SP1 + PowerCommands = Toolbox AddItems...Crash! (26/08/2015)
- More related document (12)