Legacy applications are not always extremely old. Sometimes they have just been ignored for a while and in order to reduce support costs they need a polish.
First Things First: Project Options
If you’ve ever worked with a VB.NET project that has been around since the early days of .NET 1.1, you probably had a lot of cleanup to do before applying any of the latest technologies. If this effort is taken haphazardly, it can result in a mess that is difficult to clean up. Taken in the proper order, though, legacy VB.Net can be updated quickly and easily.
Option Explicit = On
The first thing to do is ensure Option Explicit is turned on. This is a property in the VB.NET Compile project page that requires all variables to have an explicit declaration – a DIM statement. When this option is set to Off, variables can be created and used on-the-fly without a formal declaration. This is bad because with Option Explicit = Off, a simple typo in a variable name will cause the compiler to create a new variable by that name, resulting in bugs that are very hard to find.
Note that Option Explicit can also be turned on and off in code! Before setting the project property, scan through your code for “Option Explicit” to see if there are any landmines waiting for you.
To minimize the confusion, set Option Explicit for one project, then build and fix any errors. Normally it only takes a few “DIM” statements to get things working again. Then move on to the next project, making sure to check in your code after each build so you have a “check point”.
Option Strict = On
After setting the Option Explicit = On for all projects, set Option Strict = On. This option enforces valid type conversions (called Widening Conversions) and can catch a lot of bugs that are difficult to find later on. After setting this option, you’ll most likely see a lot of error appear in the Error List of Visual Studio.
The most common error I’ve come across (and one that’s a bit difficult for some to find) is with SQL DataReaders. After querying data from a database, it used to be common to retrieve that data out of a DataReader with this syntax (where dr is the datareader): Dim myString = dr(“StringFieldName”)
Once you turn on Option Strict, all of these assignments will start to fail. To fix this, you use the DataReader method GetString (or GetDateTime, etc.). However, you’ll notice when you do this that there is still an error – GetString requires an integer for the field number, not a string indicating the field name. To get around this, you can use the GetOrdinal method resulting in the following line: Dim myString = dr.GetString(dr.GetOrdinal(“StringFieldName”))
While you’re updating, don’t forget to restructure to allow unit testing. Click here to see how.