FRANCESCO BALENA ON VB MIGRATION

 

VB Migration Partner will support Visual Studio 2012

clock July 23, 2012 15:48

A few customers asked about our support for the forthcoming Visual Studio 2012, so here is the official announcement:

VB Migration Partner will add support for Microsoft Visual Studio 2012 within a few weeks after VS official release. This includes code generation for both VB.NET and C# and support for .NET 4.5.



A library for all .NET developers, free!

clock January 20, 2011 17:12

David McCarter, from www.dotNetTips.com, has released a new version of his open source .NET library, containing a lot of useful classes and methods. This new releases includes new features and bug fixes.

You can download it from here.



Vote for a VB6 migration session at TechEd Europe 2010

clock October 14, 2010 16:45

I submitted a BoF session at TechEd Europe 2010, entitled "VB6-to-.NET Migration: Myths, Truths, and Real-World Experiences".

There is a poll on these Birds-of-Feathers sessions, and only the ones that get most votes will be accepted.

Regardless of whether you attend TechEd, you can help by voting for my session. In addition to having me speak at TechEd, a lot of votes on this session will hopefully convince Microsoft that VB6-to-.NET migration is a hot topic and that they should invest more in that direction.



Basta! 2010 slides available

clock September 27, 2010 15:45

We just uploaded the two slide packs of my session at Basta! 2010 in Frankfurt, Germany.

VB6 to .NET Migration: Myth, Truth, and Real-World Experiences

VB6 to .NET Migration: Tips, Traps, and Techniques

Happy reading!



Two migration e-books all serious developers should read

clock September 17, 2010 10:51

In our quest to provide useful info to our users and readers, we periodically surf the Internet looking for articles, books, whitepapers, tools, etc. related to VB6 to .NET migration.

This week the search has been quite fruitful, and we have added two great items to our Articles page:

Navigating your way through Visual Basic 6.0 to Visual Basic.NET Application Upgrades
This 62-page e-book is one of the best collection of problems & solutions you can find on the Internet, with tons of detailed examples and code samples. It is obviously based on first-hand experience of the author with Microsoft Upgrade Wizard, and the solutions he proposes are valid and functional.

Visual Basic .NET Enhancements Compared to Visual Basic 6.
This e-book focuses on many differences between VB6 and VB.NET and in many cases it goes much deeper than the other articles mentioned in this page. It’s not the best place to start from when learning VB.NET, but it’s surely a must-read for the serious developer facing a complex migration project. (148 pages).

Both e-books are by David Ross Goben and are written in a clear and bright style. A must-read for all serious VB6 and VB.NET developers.

NOTE: Interestingly, virtually all the issues that David found when migrating his VB6 apps are handled automatically by our VB Migration Partner. (More on this in a subsequente post.)



A .NET library to access Windows Vista and Windows 7 features

clock September 16, 2009 21:58

One of the reasons to migrate your code to .NET is create modern user interface that take advantage of the power of newer versions of Windows. On the other hand, the .NET Framework has been designed to work in the same way over a wide range of Windows versions, including versions that are about ten years old, and therefore it doesn't provide access to the most intriguing features of Vista and Windows 7.

The solution comes in a new library from Microsoft, named Windows API Code Pack for .NET Framework. Version 1.0 of this great tool has been just released, and already implements an impressive range of Windows features:

  • Windows 7 Taskbar Jump Lists, Icon Overlay, Progress Bar, Tabbed Thumbnails, and Thumbnail Toolbars.
  • Windows 7 Libraries, Known Folders, non-file system containers.
  • Windows Shell Search API support, a hierarchy of Shell Namespace entities, and Drag and Drop functionality for Shell Objects.
  • Explorer Browser Control.
  • Shell property system.
  • Windows Vista and Windows 7 Common File Dialogs, including custom controls.
  • Windows Vista and Windows 7 Task Dialogs.
  • Direct3D 11.0, Direct3D 10.1/10.0, DXGI 1.0/1.1, Direct2D 1.0, DirectWrite, Windows Imaging Component (WIC) APIs. (DirectWrite and WIC have partial support)
  • Sensor Platform APIs
  • Extended Linguistic Services APIs
  • Power Management APIs
  • Application Restart and Recovery APIs
  • Network List Manager APIs
  • Command Link control and System defined Shell icons.
  • Shell Search API support.
  • Drag and Drop functionality for Shell objects.
  • Support for Direct3D and Direct2D interoperability.
  • Support for Typography and Font enumeration DirectWrite APIs. 

The library comes with an extensive help file and all code samples are available in both VB.NET and C#. Last but not the least, the entire source code is provided.



Pay attention to orphaned ADODB objects

clock September 2, 2009 01:26

Don't take me wrong: COM Interop is a great piece of technology, and Microsoft developers made wonders with it. If you consider how different the COM and .NET worlds are, it's a miracle that they can communicate with each other in such a smooth way.

Actually, COM Interop is such a magic that it's easy to forget that all the COM objects that we manipulate from .NET aren't the "real" COM objects. Instead, they are .NET wrappers that redirect all calls to the actual COM object by means of COM Interop. This fact has many implications. Consider for example this VB6 code:

Function GetRecordCount(ByVal cn As ADODB.Connection, ByVal sql As String) As Integer
   Dim rs As New ADODB.Recordset
   rs.Open sql, cn
   GetRecordCount = rs.RecordCount
End Function

As you see, the Recordset object isn't closed explicitly, but it isn't a problem in VB6 because all COM objects are automatically closed when they are set to Nothing or go out of scope. However, if you translate this code to VB.NET you are in trouble, because nothing happens when the method exits. In other words, you'll have an open recordset hanging somewhere in memory and cause unexplainable errors later in the application. For example, you'll get an error when you'll later try to open another recordset on the same connection.

We know that some customers had to work around this issue by enabling the MARS option with SQL Server, which enables multiple active recordsets on any given connection. This might be a viable solution if you are working with SQL Server 2005 or 2008, but VB Migration Partner offers a better way to handle this case: use the AutoDispose pragmas.

In fact, when this pragma is used, all disposable objects are correctly disposed of when they go out of scope. In this case, VB Migration Partner emits the following code:

Function GetRecordCount(ByVal cn As ADODB.Connection, ByVal sql As String) As Integer
   Dim rs As New ADODB.Recordset
   Try
      rs.Open(sql, cn)
      GetRecordCount = rs.RecordCount
   Finally
      SetNothing6(rs)
   End Try
End Function

where the SetNothing6 helper method takes care of orderly invoking the Close or Dispose method, if necessary.



Can your VB6 conversion tool handle null propagation?

clock May 21, 2009 09:13

If you have massively used Variants in your VB6 apps, the migration to .NET might be a nightmare. The best that the Upgrade Wizard and other tools can do is translating each “As Variant” into “As Object”, on the assumption that the Object type can do everything that a Variant does.

You shouldn’t be surprised to learn that this is one of the false migration myths, or is a gross oversimplification of the truth, to say the least. In fact, the .NET Object type lacks what arguably is the most useful feature of Variants: support for Null values and Null propagation in expressions.

Under VB6 a Variant variable can hold the special Null value and – even more important – all the string and math expression that involve a Null operand also deliver a Null Variant value. Virtually all database-intensive applications deal with Null values and have used null propagation to an extent. Now, let’s consider this VB6 code:

' rs is an ADODB.Recordset
Dim realPrice As Variant
realPrice = rs("Price")
realPrice = realPrice * (100 – rs("Discount")) / 100
If Not IsNull(realPrice) Then DisplayPrice(realPrice)

Under VB6, if either the Price or the Discount field is Null, the realPrice variable is assigned Null and the DisplayPrice method isn’t invoked. Now, consider the “canonical” VB.NET version of the above code:

Dim realPrice As Object
realPrice = rs.Fields("Price").Value
realPrice = realPrice * (100 – rs.Fields("Discount").Value) / 100
If Not IsNull(realPrice) Then DisplayPrice(realPrice)

Under .NET a Null database field returns a DBNull object – more precisely, the DBNull.Value element. The problem is, no math or string operation is defined for the DBNull type, something I consider one of the most serious mistakes Microsoft made in this area. As a result, the third statement throws an exception if either field is Null. So long, functional equivalence! Welcome, migration head-aches!

Null propagation is a serious problem not to be underestimated. One of our customers has found that, on the average, one out of 40 statements uses Variant expression and relies on null propagation. To put things in the right perspective, in a middle-sized real-world application you can expect to manually fix several thousand statements that use null propagation. What’s worse, there is no simple way to work around Null values in VB.NET, short of splitting all statements in portion and testing each and every subexpression for the DBNull.Value value.

If you use VB Migration Partner, you can solve the above problem in the most elegant and painless way. Just use the following project-level pragmas:

 '## project:NullSupport
 '## project:ChangeType Variant, VB6Variant

The NullSupport pragma tells VB Migration Partner to map some VB library functions – such as Left, Mid, Right, and a few others – to special methods that are defined in VB Migration Partner’s support library and that, not surprisingly, correctly return a Null value if their argument is Null (as they do under VB6).

The ChangeType pragma converts all Variant members – variable, fields, properties, methods, etc. – as the special VB6Variant type (also defined in VB Migration Partner’s support library) which redefines all the math, comparison, string, and logical operators to support null values.

Yes, this is all you need to add null propagation support to your VB.NET code! This feature alone can save you literally weeks in a real-world migration project. And don’t forget that VB Migration Partner is the only VB6 conversion software that supports Null values and Null propagation easily and automatically.

When you hear other vendors claiming that “our tool uses advanced artificial-intelligence-based techniques to ensure functional equivalence with the original VB6 code”, just ask them how it deals with Null values. Smile



Accomplishing the impossible: VARPTR in VB.NET!

clock March 16, 2009 02:39

VB6 supports three functions – VarPtr, StrPtr, and ObjPtr – that were never officially supported by Microsoft, yet they have been extensively used by many expert VB6 developers. In fact, you badly need these functions when calling some especially complex Windows API functions. Of these functions, the most useful one is VarPtr, which returns the address of the memory location where the value of a variable is stored.

Neither the Upgrade Wizard nor any other VB6 migration tool supports the VarPtr keyword, thus I decided that our VB Migration Partner *had* to correctly convert it. Thanks to Google, I found out that the problem had been discussed at length in many forums, but no definitive solution has ever been found yet. You can write an implementation in unsafe C#, or an unmanaged DLL written in C or Delphi, but these solution would force us to distribute a separate DLL with VB.NET apps converted by VB Migration Partner, which I’d rather not to.

It took a while and a lot of thinking, but in the end I figure out a way to solve the problem. Yes, it is possible to write a VarPtr function in plain VB.NET, with only the help of a method exposed by the Windows API. Actually, you need just a few lines of code:

' -----------------------------------------------------------
' VARPTR implementation in VB.NET
' Part of VB Migration Partner’s support library
'
' Copyright © 2009, Francesco Balena & Code Architects
' -----------------------------------------------------------

Module VarPtrSupport
   ' a delegate that can point to the VarPtrCallback method
   Private Delegate Function VarPtrCallbackDelegate( _
     
ByVal address As Integer, ByVal unused1 As Integer, _
      ByVal
unused2 As Integer, ByVal unused3 As IntegerAs Integer


   ' two aliases for the CallWindowProcA Windows API method
   ' notice that 2nd argument is passed by-reference
   Private Declare Function CallWindowProc Lib "user32" _
      Alias
"CallWindowProcA" _
      (ByVal wndProc As VarPtrCallbackDelegate, ByRef var As Short, _
      ByVal unused1 As Integer, ByVal unused2 As Integer,  _
     
ByVal unused3 As Integer) As Integer

   Private Declare Function CallWindowProc Lib "user32" _
      Alias "CallWindowProcA" _
      (ByVal wndProc As VarPtrCallbackDelegate, ByRef var As Integer, _
      ByVal unused1 As Integer, ByVal unused2 As Integer, _
     
ByVal unused3 As Integer) As Integer
   ' ...add more overload to support other data types...

   ' the method that is indirectly executed when calling CallVarPtrSupport
   ' notice that 1st argument is declared by-value (this is the
   ' argument that receives the 2nd value passed to CallVarPtrSupport)

   Private Function VarPtrCallback(ByVal address As Integer, _
        
ByVal unused1 As Integer, ByVal unused2 As Integer, _
         ByVal unused3 As Integer) As Integer
      Return address
   End Function


  
' two overloads of VarPtr
   Public Function VarPtr(ByRef var As Short) As Integer
      Return CallWindowProc(AddressOf VarPtrCallback, var, 0, 0, 0)
   End Function

   Public Function VarPtr(ByRef var As Integer) As Integer
      Return CallWindowProc(AddressOf VarPtrCallback, var, 0, 0, 0)
   End Function

   ' ...add more overload to support other data types...
End Module

To understand how the trick works, let’s see what happens when you call the VarPtr method. The only line of code in this method invokes one of the overloads of CallWindowProc method. The CallWindowProc method takes five arguments, the first one of which is a delegate that must point to a method that takes four 32-bit values. CallWindowProc invokes the method pointed to by the delegate and passed the other four values to such a method.

The key point in this mechanism is that each CallWindowProc overload takes a value by-reference in its second argument – a Short and an Integer, respectively. This means that the CallWindowProc method (buried inside the User32.dll) receives the address of the Short or Integer variable. This address is a 32-bit integer and is passed verbatim to the VarPtrCallback method. This method in turn receives a 32-bit integer value with by-value semantics, which means that the address parameter now contains whatever value was pushed on the stack by the CallWindowProc method.

Let’s quickly recap: the VarPtr method pushes the address of the Short or Integer variable – that is, the value we are interested in – on the stack. This 32-bit integer is received by the CallWindowProc method (in User32.dll) and is sent to the VarPtrCallback method, which receives it in its first argument and returns it verbatim to the CallWindowProc method, which in turn returns it to the VarPtr method that can finally return it to the caller.

Notice that you might need to add more overloads for the VarPtr method (and the CallWindowProc method), to support data types other than Short or Integer. Just remember that you can’t use this technique with String, Objects, or other reference types. It doesn’t work with Boolean values, either.

Interestingly, you can use the VarPtr method with structures, provided that the structure doesn’t contain any String, Object, or Boolean elements. To get the address of a structure just use VarPtr on its first element, as in this example:

Structure POINTAPI
   Public x As Integer
   Public y As Integer

End Structure

Dim
pnt As POINTAPI
Dim addr As Integer = VarPtr(pnt.x) 

To prove that the VarPtr function works correctly, let’s use it together with the CopyMemory Windows API method to delete an element in an array by quickly shifting all the elements towards lower indices:

Declare Sub CopyMemory Lib "Kernel32.dll" Alias "RtlMoveMemory" _
   (ByVal dest As Integer, ByVal source As Integer, _
    ByVal numBytes As Integer)


Sub
Main()
   Dim arr(1000) As Integer
   ' initialize the array
  
For n As Integer = 0 To UBound(arr) : arr(n) = n : Next
   ' ...
   ' delete first element by shifting all elements towards the beginning
   '
of the array, then clear last element
   CopyMemory(VarPtr(arr(0)), VarPtr(arr(1)), UBound(arr) * 4)
   arr(UBound(arr)) = 0
   ' check that it worked fine
   For n As Integer = 0 To UBound(arr) - 1
      If arr(n) <> n + 1 Then Debug.Print("Wrong value at index {0}", n)
   Next

End Sub

In case you are wondering why you should use CopyMemory and VarPtr to shift all the elements of an array – instead of a plain For … Next loop – the answer is: execution speed. Under VB6 this technique was often used to significantly speed up array operations; the VB.NET compiler produces more efficient code and this technique is seldom necessary, nevertheless the ability to convert this code from VB6 without any major edits means that you don’t have to spend too much time trying to understand what the VB6 developer meant to do.

Please notice that this implementation of VarPtr works well in 32-bit applications only, and fails when running on 64-bit operating systems. To ensure that things work as expected and that 32-bit code is generated even when running on 64-bit versions of Windows, you must select the Target CPU = x86 option in the Advanced Compile Options dialog box, in the Compile tab of the My Project page. (Odds are that you have to select this option anyway when doing complex operations with pointers.)

Important warnings: working with memory addresses under .NET can be very dangerous, much more dangerous than under VB6. The reason is, the garbage collector can fire virtually anytime while the program is executing, therefore the address of an object can suddenly change and the unmanaged method (CopyMemory in above example) would receive the address of a memory area that doesn't contain the data any longer. The neat result would be either a wrong value or an application crash. When using this implementation of VarPtr under VB.NET keep the following points into account:

  1. VarPtr is absolutely safe only when used to return the address of simple local variables, such as Short, Integer, Single, Double, or Date variables. Using local variables is safe because local variables are allocated on the stack and don't move even if an unexpected garbage collection occurs immediately after the VarPtr method returns but before the unmanaged method complete its execution.
  2. Passing the element of a Structure is safe, but only if the Structure is held in a local variable (as opposed to a class field)
  3. In all other cases, VarPtr isn't  100% safe and might occasionally deliver wrong results or crash the application. For example, it isn't 100% safe to pass VarPtr a class field or an element of an array, because array elements are stored in the managed heap and can be moved by the garbage collector (regardless of whether the array is stored in a local variable). 
  4. In a single-thread application the probability that a garbage collection occurs unexpectedly are very low and might even be considered as negligible, but they can't be considered as equal to zero.
  5. You can further minimize the probability of an unexpected GC by avoiding calling methods and language functions (e.g. Left, Int, Abs) inside the call to the unamanged method but, again, you can't reduce this probability to zero.

To recap, except when you are in cases #1 and #2 above, the converted code will work most of the time, but it can't be guaranteed to work always.The only documented way to ensure that an object doesn't move in memory because of unexpected gargabe collection is by pinning the object, by means of methods exposed by the System.Runtime.InteropServices.Marshal class.

Even with this limitation, the VB.NET implementation VarPtr method is quite helpful when doing a quick-and-dirty migration - using VB Migration Partner or the Upgrade Wizard. You can use VarPtr to check that the converted code works as intended, but it is strongly recommended that you get rid of VarPtr before going to production. In the CopyMemory case see above, for example, you can do without the VarPtr by using a different overload of the CopyMemory method that takes by-reference arguments:

 

Declare Sub CopyMemoryByref Lib "Kernel32.dll" Alias "RtlMoveMemory" _
   (ByRef dest As Integer, ByRef source As Integer, _
    ByVal numBytes As Integer)

(This code works because the .NET Framework automatically pins every object passed by reference to an external method.)

Even better, you should do your best to avoid unamanged calls altogether and replace them with calls to methods of pure .NET objects.



Subtle threading issues and how to fix them (automatically) with VB Migration Partner

clock February 10, 2009 09:09

One customers brought an issue to our attention. He was using a migrated VB.NET component in a heavy multi-threaded environment (the component is called by ASP.NET pages) and found that occasionally the program crashed with an unexplainable error message. A quick look at the stack trace confirmed the initial suspect: the error was caused by two threads that initiates a call to the same method at the same time. We have fixed the problem in our library in a few minutes (the fix will appear in version 1.10.03, due in a few days), but we realized that the problem isn't confined to our library. To explain why, a short digression is in order.

VB6 components use Single-Threaded Apartment (STA) model: each thread lives in an “apartment” of its own. In plain English, this means that each thread works with a different set of global variables. For example, assume that the ActiveX DLL project contains a BAS module with the following variable declaration:

    ' ...(in the UserInfo.bas file)
    Public UserName As String


Thanks to STA threading model, each client – running in a different thread – can write this variable and read it back, without worrying about another client (in another thread) overwriting the variable with a different value. As you see, STA makes multi-threading programming virtually as easy as single-thread (i.e. traditional) programming. Of course,when writing multi-threaded apps you have to take care of many other potential concurrency issues – for example, two threads working on the same temporary file or registry key – but at least you don’t need to worry about global variables.

By contrast, components written in VB.NET – and all .NET languages, for that matter – use free-threading, which means that all threads can access all variables at the same time. Therefore, the VB.NET component exposes the same UserName field to all threads, which means that any thread can overwrite the value stored there by another thread.

To simplify programming in free-threaded contests, the .NET Framework supports the ThreadStatic attribute. You can apply this attribute only to static class fields – either fields defined in modules or fields defined in classes and marked with the Shared kewword:

    <ThreadStatic()> _
    Public UserName As String


All fields marked with the ThreadStatic attribute are stored in the Thread Local Storage (TLS) area. The separation among threads is automatic, because each thread owns a different TLS.

In theory, when migrating a VB6 DLL meant to be used by free-threaded clients, you should scrutinize each and every variable in BAS modules and decide whether to tag them with the ThreadStatic attribute. To make this task as easy as possible, as well as to avoid any manual edit of the resulting VB.NET code, starting with version 1.10.03 VB Migration Partner supports the ThreadSafe pragma, which can be applied at the project-, file-, method- and variable-level scope. In most cases, therefore, all you need to do is using a single pragma that affects all the variables in the current project:

    '## project:ThreadSafe True
    Public UserName As String





Follow Francesco Balena on VB6 migration’s group on

LinkedIn


VB Migration Partner - Subscribe to our feed RSS  blog RSS
 
AddThis Feed Button
 
 

Home blog
 
AddThis Social Bookmark Button


 

Sign in

Search

Calendar

<<  May 2013  >>
SuMoTuWeThFrSa
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

Archive

Categories

 

Microsoft Regional Director
Microsoft is a registered trademark of Microsoft Corporation in the United States and other countries and is used under license from Microsoft
 

My Blogs


My programming tools



VB Migration Partner


VBMaximizer for VB6


Form Maximizer for .NET

 

My books


Programming Microsoft Visual Basic 6


Programming Microsoft Visual Basic 2005: The Language


Practical Guidelines and Best Practices for Microsoft Visual Basic .NET and Visual C# Developers