Use regular expressions in Visual Studio to clean up code
This is a reminder to myself.
Knut, remember that Regular Expressions are very handy to clean up a lot of messy code.
Here is an example:
The following function call results in a code analysis warning:
DBHelper.SetPropertyFromDB(m_City, dr("CITY"))
It's a helper function that returns the typed value from a DBValue. Not really useful these days with NHibernate or Typed Datasets, but it's code from an old application. Here is the signature of the code:
Shared Sub SetPropertyFromDB(ByRef pProperty As Object, ByVal value As Object)
The warning reported is:
"Warning: Implicit conversion from 'Object' to 'String' in copying the value of 'ByRef' parameter 'pProperty' back to the matching argument."
To fix this, I created a new method that returns the correct typed value instead of returning the referenced parameter and marked the old method "Obsolete":
Public Shared Function GetDBValue(ByVal pProperty As Object, ByVal dbValue As Object) As Object
Now, I had to rewrite all the calls to the function (several hundred calls). This included returning the typed value into the same variable as the first parameter in the function call, like this:
m_City = DBHelper.GetDBValue(m_City, dr("CITY"))
This is easily achieved by using Regular Expressions in the "Find and Replace" dialog in Visual Studio:
Find What:
DBHelper.SetPropertyFromDB\({.*},
(note: the \ escapes the ( and the expression group is marked by a {})
Replace with:
\1 = DBHelper.GetDBValue(\1,
(note: the \1 will represent the expression group)
Pretty simple, and very powerful
No comments yet.
Leave a comment
Search
Knut Hamang
Recent Posts
Recent Comments
- Jack on Html to Pdf in .NET
- Øyvind on Creating dynamic menus in EPiServer
- Jim Liddell on [Updated] Continuous Integration using an LCD-TV
- Arshika on Html to Pdf in .NET
- Arshika on Html to Pdf in .NET