COM+ to .NET: Fast Forward Your VB Components

Originally published at O’Reilly

The joke goes: “How do you pronounce ‘C#’?”, and the punch line is: “The language formerly known as Java.”

Extending this, you can say that .NET is “…the infrastructure formerly known as COM/DCOM.”

The .NET infrastructure is significantly different from COM/COM+. However, information about .NET has been out long enough so that most of you have passed the “But, why?” stage. You’re probably now interested in discovering how you can continue to create and support your existing component development to be ready when your organization adopts the production release of .NET. In particular, if you work with ASP and make use of COM+ components created with Visual Basic, you’ll be interested in how you can ensure that your components migrate well to the new .NET environment.

We’ll take a look at some of the changes .NET will have on your current VB ASP component development efforts. In particular, we’ll look at what you can do now to ensure your components are forward compatible with .NET.

What Variant?

One significant change between COM/COM+ and .NET is that the Variant data type is no longer supported; its functionality has been incorporated into the Objectdata type. For Visual Basic programmers this is a major change, particularly if you’ve worked with component development and have used variants to pass data to and from component methods.

For future compatibility, you can begin to use specific data types rather than the Variant in your new components. However, if you have used Variant in existing code, be aware that Microsoft has provided two means of porting your components that contain variants to .NET.

The first is the Visual Studio Upgrade Wizard, which is automatically engaged when you open your older VB code into Visual Studio .NET for the first time. This wizard replaces all instances of Variant with Object, and any time you try and type in a Variant, it replaces it immediately with Object. No additional effort is necessary on your part.

For instance, if you had a subroutine such as the following:

Sub test (ByVal varValue As Variant)

The upgrade wizard changes the subroutine to:

Sub test (ByVal varValue as Object)

If you didn’t provide a data type for a variable in VB 6.0, defaulting to a data type of Variant, the upgrade wizard automatically redefines the variable as Object in VB.NET.

(The upgrade wizard performs other upgrade modifications that will be highlighted throughout this article.)

You don’t have to open and convert a compiled component to .NET to ensure compatibility with the environment. A second means of porting your components to .NET is the utility, TlbImp. How to use this tool was discussed and demonstrated in a previous article; basically what happens is the tool creates a .NET assembly for the component that allows it to run within the .NET managed code environment, without having to recompile the component.

Dropping Variant isn’t the only change from VB 6.0 to .NET. VB Data Types and type checking is another significant area of change, which is discussed next.

Data Types and Data Typing

A chief concern about Visual Basic in the past, particularly from C++ or Java programmers, has been that Visual Basic is a weakly typed programming language. For instance, you can concatenate a number with a string in Visual Basic 6.0, and VB will automatically convert the numeric into a string value, using implicit conversion, as shown in the following example:

iValue = 123
StrSum = iValue & "123"

This type of operation is still allowed with .NET when using the overloaded concatenation operation (‘&’), as shown above, but any other use of numerical values where a string is expected will generate an error. As an example, you won’t be able to pass a number through a string parameter and have VB automatically perform the conversion:

Sub tstValue (String strValue As String)
...
Dim iValue As Integer
iValue = 13
tstValue iValue

The above works with VB 6.0, but it won’t work with VB.NET.

To support this new shift to stronger data typing, Visual Basic .NET also introduces the Option Strict statement:

Option Strict

Like its earlier predecessor, Option ExplicitOption Strict enforces explicit variable declaration:

Dim iValue As Integer

However, Option Strict enhances this data protection capability by prohibiting implicit conversions between strings and numbers, as well as limiting numeric conversions to those termed as widening conversions. A widening conversion is any that converts a smaller number, or less precise one, to a larger, more precise one, such as converting an integer to a double.

Option Strict also prohibits late-binding. Using this option, the following, while legal in Visual Basic 6.0 will generate a compiler error in .NET:

Dim obj As Object
...
obj.SomeMethodCall ...

As late-binding is detrimental to any wire based communication between application components, such as in a distributed or Web-based environment, you’ll want to avoid its use even within your existing Visual Basic 6.0 component development. Late-binding always requires two method calls for every call within the actual code: one to find information about the method (through automation and a process referred to as reflection), and one to invoke the method itself, necessitating two round-trips across the wire. Placing Option Strict at the top of your code module just helps to ensure that you don’t accidentally leave late-bound variables in your code.


Accessing COM/COM+ Objects Within the ASP.NET Environment–Don’t miss Shelley Powers’ first article on the differences between ASP.NET and the original ASP server environment. Shelley has also updated her book on ASP components within the Windows 2000/COM+ environment, Developing ASP Components, 2nd Edition.


All of these new techniques enforce a stricter adherence to a more strongly typed language, while still providing the option of more loosely typed conversions that do exist in many existing Visual Basic applications. This is a necessary compromise between the Visual Basic of today and the one included as part of .NET.

To ensure that your code moves cleanly into this more strongly typed environment, you can use the Option Explicitstatement now to enforce variable declarations in your current applications. Also, eliminate any narrowing conversions (converting numbers of larger precision and size to smaller data types, with the potential loss of data) in your code, and make use of explicit conversion functions when working with numbers and strings together:

StrSum = "Account is " & CStr(iValue) & " overdue"

In addition, use type libraries (included in your code module by attaching the libraries to your project) to perform early binding, not only for future compatibility, but also to improve the performance of your Visual Basic applications today.

When you open an existing VB 6.0 project in VB.NET, the upgrade wizard automatically adds the Option Strictstatement with a value of “Off” to provide for backwards compatibility in behavior. The Option Explicit statement is left as is (“off” by default).

Another .NET change to Visual Basic — and one that particularly impacts component developers — is the size of the integer data type, covered in the next section.

Integer Size

A significant data type change between the two releases of VB is the size of integer values. Starting with Visual Basic .NET, the Integer data type is equivalent to the new .NET System.Int32 data type, and is now 32-bits, and signed.

An advantage to 32-bit integers is that this size is more efficient within numeric operations than the older 16-bit integer, particularly on 32-bit operating systems, such as the current default Windows 2000 basic operating system.

Another benefit of the changed integer size is that VB is brought in line with other mainstream programming languages, such as C++, Java, and Perl. If you’ve worked with component development, particularly with components based in different languages, one of the most frustrating aspects of working with Visual Basic has been its 16-bit integer, especially when so many other languages have 32-bit integers. This is particularly apparent when accessing VB components from within PerlScript.

If you still want access to 16-bit numbers, you’ll need to use the new Short value, and use the Long data types for 64-bit values.

The upgrade wizard maintains the integrity of the VB application by converting VB integers to shorts (16-bit). If you want to ensure that your component is converted to the new .NET integer type, start using the VB 6.0 long data type for your variables and particularly your method parameters in your existing development effort.

A less significant data type change is that currency is no longer a supported data type. Instead, a new Decimal type has been provided to allow for more precision and more digits:

Dim decValue As Decimal

In Visual Basic 6.0, the Decimal data type was only available as a Variant sub-type.

Dates are also handled differently in Visual Basic .NET, and are implemented with the .NET DateTime format instead of the current Double format. To convert between the older and the new date format, Microsoft is providing routines such as ToDouble to convert the new data type to the original double value.

You can best prepare your existing code for these new data types by isolating your use of Date and Currency within your components as much as possible in order to manually migrate your code in the future if necessary.

Speaking of function parameters, another significant change within Visual Basic .NET is subroutine semantics, including a different parameter passing implementation.

Subroutine Modifications

Parameters, and how they are passed from the calling program are handled differently between VB 6.0 and VB.NET. By default in Visual Basic 6.0, all parameters are passed by reference if the ByVal keyword isn’t used. This allows the procedure to modify the variable used to pass the parameter in the calling program, which can lead to unexpected results, an example of which is:

Sub testValue(iNewValue As Integer)
   iNewValue = iNewValue + 20
End Sub

...

Dim iValue As Integer
iValue = 2

Call testValue(iValue)

' value is now 22 rather than 2

Parameters are passed by value as a default in Visual Basic .NET, protecting against accidental and unexpected data changes. You must explicitly use the ByRef keyword in order to pass a parameter by reference.

You can easily ensure the future compatibility of your existing code with Visual Basic .NET by using the explicit ByVal and ByRef keywords with all of your parameters in your 6.0 Visual Basic code.

The Optional parameter keyword also has different semantics in Visual Basic .NET. In 6.0 you can specify that a parameter is optional without having to provide a default value:

Sub someRoutine (Optional ByVal iValue As Integer)

In 6.0 you’d use IsMissing to check to see if the value changed. In Visual Basic .NET, you must supply a default value for all optional parameters:

Sub someRoutine (Optional ByVal iValue as Integer = 0)

To ensure smooth migration to .NET, when using Optional in your existing code, provide default values. This approach not only allows your code to move forward into .NET, it’s also a good programming practice to apply today – the use of IsMissing adds unnecessary complexity to your procedures.

Other changes with Visual Basic .NET have to do with structured data, such as arrays.

Structural Changes with Arrays

If you use arrays, you’ll find that you can no longer re-define the lower bound of an array with the Option Base statement in VB .NET:

Option Base 1

All arrays now start at zero, as arrays start in most programming languages. Again, this change is necessary for programming language interoperability, something that .NET tends to encourage (or at least, not discourage). In addition, you can’t specify a fixed array size in .NET as you could in 6.0:

Dim strValue(10) as String

Instead, you’ll use syntax similar to the following:

Dim iValue as Integer = new Integer(10) { }

This new approach allocates storage for 10 elements of the specified data type, but doesn’t fix the size of the array itself. The array can be changed through the use of the ReDim statement:

ReDim iValue(20)

To allow for maximum forward compatibility in your code, avoid the use of Option Base to reset the base value of an array. Not using this statement forces your arrays to begin with the zero boundary. The upgrade wizard will also convert arrays to being zero-based, if so instructed when the project is first opened.

Microsoft hasn’t restricted its Visual Basic changes to structural and data type changes. The use of built-in functions will also be impacted in .NET.

Built-in Functions and Namespaces

One brand new feature of Visual Basic .NET that I do want to mention in this article is the concept of namespaces. Namespaces are ways of exposing externally created components to an application, similar to importing a type library into C++ or attaching a reference to a type library in Visual Basic 6.0.

You can import a namespace into Visual Basic .NET code using the imports statement:

imports Microsoft.VisualBasic.ControlChars

With imports, you can reference members of the namespace without having to type the qualifying namespace name. Instead of:

dValue = Math.sqrt(number)

You can use:

dValue = sqrt(number)

The reason I’ve introduced the namespace concept into an article focusing on forward compatibility of VB ASP components is because many Visual Basic 6.0 built-in functions have now been defined within specific namespaces, such as the System.Math namespace, just shown.

One significant alteration to your code based on namespace use is with the String data type. Now, you can access Stringdirectly from within your code:

Dim strValue as String 

In Visual Basic.NET, String is actually defined as part of the System.String namespace. In fact, all supported data types are now a part of the System namespace, as is much of VB’s built-in functionality.

To ensure backwards compatibility, Microsoft has provided a specific namespace, Microsoft.VisualBasic.Compatibility.VB6 that you can import into your existing Visual Basic 6.0 components. This will allow applications to work within the Visual Basic .NET environment until you have time to make the actual modifications.

One final change in Visual Basic .NET I’ll look at is the impact on Properties within the new environment, and the use of Set and Let.

Property Changes

In Visual Basic 6.0, you use direct assignment when assigning scalar values but must use the Set keyword when assigning an object to a variable:

Set obj = SomeObject

In Visual Basic.NET, the infrastructure supporting properties has changed, and the Set and Get keywords are now disallowed in the programming language.

As a demonstration of this change, in the past when you’ve worked with ADO, you’ve assigned a Connection object to a variable using syntax similar to the following:

Set rs.ActiveConnection = conn

Chances are, you’ve forgotten to use the Set keyword, resulting in an assignment of the Connection object’s default property, the connection string, instead of the object itself:

rs.ActiveConnection = conn

With the above, the code will still work, a database connection is assigned to the ResultSet object, but what happens is that a second connection is created using the connection string rather than using the existing connection object.

Visual Basic .NET no longer supports the concept of default properties unless they take parameters. This is one of the design changes folks have been asking for, and one that was long overdue.

With this type of change, the accidental assignment of a default property, as described with the ADO Connection object, will no longer occur – a definite improvement within the language and the tool.

The .NET infrastructure also specifies a new approach for defining properties that provides the means to set and retrieve the property value. An example of a property within the PDC-based release of Visual Basic .NET is the following:

' Internal storage, always in degrees. 
Dim Degrees As Double = 0  
  Property Angle(ByVal Radians As Boolean) As Double 
  Get 
    Angle = Degrees 
    If Radians Then Angle = Angle * 3.1415926536 / 180 
  End Get 
  Set 
    ' The keyword Value stands for the value passed in. 
    Degrees = Value    
    If Radians Then Degrees = Degrees * 180 / 3.1415926536 
  End Set 
  End Property

By providing a means to define how a property is set and retrieved, the Property LetProperty Set, and Property Getstatements are no longer necessary and been removed from language support. Again, as with many of the other changes detailed in this article, the upgrade wizard will automatically correct the use of Set and Get and property management when your VB 6.0 component project is opened. Compiled components that have been wrapped via the use of TlbImp aren’t impacted by these code internal changes.

Summary

You’ve not yet had a chance to get a detailed look at all of the Visual Basic .NET changes – many are still being determined. However, you should have a better understanding of the types of changes headed your way, and how they will impact your existing VB components and component development.

Hopefully I’ve also shown that though the changes are significant, they aren’t overwhelming. In fact, there are many steps you can take now that will allow for a smooth migration of your VB component code to the new .NET architecture.

As I finished writing this article, Microsoft announced that it was restoring some of the Visual Basic 6.0 functionality it had originally pulled with the first beta release of VB.NET. This move was to ensure that VB.NET could support applications developed before the release of VB.NET.

However, if you’re creating new applications–or components–adjust your code to be in synch with VB.NET rather than depending on support for the older VB code base.