VBUC Features
In the following section, you will find a list of features available in the VBUC Tool, including Command-Line, Typing, .NET Core Support, among others.

Command-Line Interface

The VBUC provides a command-line interface that allows you to upgrade your code via command line rather than using the GUI.
The command to create an upgrade solution and perform the upgrade process is:
vbuccmd <sourcePath> <solutionName(without extension)> [options*]
If you wish to upgrade an existing solution file, use the following command:
vbuccmd <solutionfile> [options*]
Options detail:
Option
Description
/?
Show the usage of the VbucCmd.
/license
Display the license information.
/out <outputPath>
Specify the output directory. Default: <sourcePath>\UpgradeOutput
/target {vb|cs}
Specify the target language. Default: vb
/upgradeoption <file>
Upgrade Option file to use. Values: Standard | MoreDotNet | MoreInterop Or a new option created by the user.
/vsversion <version>
Choose the Visual Studio Version for output. (2010|2012|2013|2015|2017|2019)
/netframework <NET-version>
<NET-version> values: 4.0 - available for VS2010 onwards 4.5.2 - available for VS2012 onwards 4.7 - available for VS2017 onwards 4.7.2 - available for VS2019 onwards
4.8 - available for VS2019 onwards
netcore3.1 - available for VS2019 net5 - available for VS2019
/folder <folder>
Choose to preprocess/upgrade only one subfolder (it has to be relative to the solution source path).
/includeNeeded
Include all needed* projects in the preprocess phase.
/ignoreWarnings
Don't update warnings when loading a solution.
/phase <phaseId>
Execute only the indicated phase. (Default: Preprocess and upgrade) <phaseId> values: solution - Only create a solution file. Not valid for case #2 above. preprocess - Only preprocess projects and create analysis information. upgrade - Only upgrade phase using existing preprocess information. assessment - Generate the assessment report XML.
Typing options (only one option can be used)
/typer - Use full typing for object and variant members. /noTyper - Don't use typing for object and variant members. /localTyper - Use local typing for object and variant members.
Helpers options (only one option can be used)
/binaryHelpers - Use of binary helpers (default for vb.net language). /sourceCodeHelpers - Use of source code helpers (default for c# language). /nugetsHelpers [-version=9.x.x] - Use helpers as nugets (for VS 2017 onwards), optionally reads the nugets version.
/parallel <degree>
Sets the number of projects to be upgraded in parallel. If not specified uses a value calculated based on the computer's resources.
/log <level>
Sets the verbosity of the output log. <level> values: error - only errors are logged. warning - Only warnings and errors are logged. info - Basic output, including errors and warnings. debug - Detailed output, including errors and warnings. If not specified, the default value is debug.
*The needed projects are those that reference or are referenced by one of the projects included in the upgrade. If the needed project is not in the upgrade solution, it will not be included.

Examples

Upgrade all the VB6 projects that are contained in "C:\Source Code\" to C# and leave the output in "C:\Source Code\OutputPath":
vbuccmd "C:\Source Code" MySolutionFilename /out ./OutputPath /target cs
Perform upgrade on all the projects specified in an upgrade solution file:
vbuccmd SolutionFilename.VBCSln

Assessment Process

Visual Basic Upgrade Companion (VBUC) will switch to assessment mode once the current license is expired. This mode allows the user to perform the following actions:
    Create upgrade solutions to solve pre-migration issues i.e. missing references or files.
    Create the assessment report to quantify the efforts required for the migration task.
VBUC will be installed by default in assessment mode if a valid license file is not provided after the installation process. Once VBUC is activated, the assessment mode features will be present in the full version.

How to run the Assessment

Before starting

Before running the Assessment, it's necessary to follow these steps to have a successful analysis:

Running VBUC in Assessment Mode

First, select the Assessment option from the Tools menu.
VBUC Assessment option
Once the option is selected, the Assessment window will appear.
VBUC Assessment Window
Run the Assessment, and it will analyze your VB6 project. Once the analysis is done, you can review the result in a browser by pressing the "Show Results" button. Also, there is a folder called Assessment located in the Output Path. In the next section, you can see the report files.

Assessment report

    Upgrade Solution (*.VBCSln)
      Used to solve:
        Internal and external References
        Project dependencies
    LOC Report.xml
      Source files per project
      Recommended upgrade order
      Lines of code (code, comments, spaces, design lines)
        Per Project
        Detail per file
    AssessmentReport.xml
      Used by Mobilize personnel for estimations.
      Information provided:
        Third-party controls:
          Used methods and properties
          Events
        Data Access components
        COM+ summary and members
        Intrinsic components
        Windows API calls
        Much more

Dependency Analyzer

How to run the Dependency Analyzer

The Dependency Analyzer enables the user to work with the solution and project dependencies. First check the output file is the correct one.
Dependency Analyzer tool
The user has to select the projects that want to analyze, once the projects are selected press the "Analyze" button. It shows all the dependencies from the corresponding projects, as shown below. In addition, by clicking the "Show Table" button it generates a .csv file with all this information.
Dependency Analyzer Result

Typing

This section describes the Typing mechanism used by the VBUC to determine the type of certain elements.

VBUC Type Inference

In Visual Basic 6.0, it is very common to use variables without an explicit declaration.
The Visual Basic Upgrade Companion generates all the explicit, fully-typed declarations for these variables avoiding the usage of generic data types (i.e. Object). The VBUC's type inference engine determines the most appropriate data types for variables, parameters, fields, and return values.
The Visual Basic Upgrade Companion is able to solve variable, method, and inter-project scope typing issues. The resulting source code boasts full typed variable declarations and explicit castings (if necessary) for all the variables, based on their usage and programmatic behavior.
The typing issues are simple to fix on a small scale, but it is complexity raises when combined with late binding and unusual programming practices. The manual changes required to obtain a functionally equivalent code will proportionally grow with the migration project size.
The Visual Basic Upgrade Companion will shorten the manual changes stage by providing pure, high quality, and fully typed .NET source code, allowing the entire migration project to be executed in less time than expected, reducing the overall costs and assuring the highest ROI.
The following VB6 source code sample contains three non-typed and one fixed-length string variable being used and assigned in a particular way.
Original VB6 Source Code
1
Private Sub typeInference()
2
Dim var1
3
Dim var2
4
Dim var3
5
Dim var4 As String * 50
6
var4 = App.Path
7
var1 = ArgTypeInference(var2, var3, var4, Len(var4))
8
End Sub
9
10
Public Function ArgTypeInference(ByVal arg1 As Integer, ByVal arg2 As String, ByVal arg3 As String, ByVal arg4 As Integer)
11
MsgBox arg1
12
MsgBox arg2
13
MsgBox arg3
14
MsgBox arg4
15
ArgTypeInference = 1
16
End Function
Copied!
Due to its advanced type inference mechanism, the Visual Basic Upgrade Companion's resulting source code contains clearly defined data types. For this example, var1, var2, and var3 were typed based on their usage (int and string). Also, the "ArgTypeInference" function's return value type was inferred to be int.
C# Code Generated by the VBUC
1
private void typeInference()
2
{
3
int var2 = 0;
4
string var3 = "";
5
string var4 = new string('\0', 50);
6
var4 = StringsHelper.GetFixedLengthString(Path.GetDirectoryName(Application.ExecutablePath), 50);
7
int var1 = ArgTypeInference(var2, var3, var4, Strings.Len(var4));
8
}
9
10
public int ArgTypeInference(int arg1, string arg2, string arg3, int arg4)
11
{
12
MessageBox.Show(arg1.ToString(), AssemblyHelper.GetTitle(System.Reflection.Assembly.GetExecutingAssembly()));
13
MessageBox.Show(arg2, AssemblyHelper.GetTitle(System.Reflection.Assembly.GetExecutingAssembly()));
14
MessageBox.Show(arg3, AssemblyHelper.GetTitle(System.Reflection.Assembly.GetExecutingAssembly()));
15
MessageBox.Show(arg4.ToString(), AssemblyHelper.GetTitle(System.Reflection.Assembly.GetExecutingAssembly()));
16
return 1;
17
}
Copied!

Custom Typing

We also provide a mechanism that assigns custom .NET data types; it includes variables, functions, fields, properties, among others; which implies a series of changes in the code both in the declarations and in their uses.
It can be used mainly to provide the possibility to fully qualified names of statements if deemed necessary, for example, classes with the same name but with different namespaces.

Extensibility

Mappings Grammar

Mapping is a crucial concept for our migrators. It means that from a set of values as input, a function is applied to each value, and generates a set with new values.
It's a powerful tool that allows design mappings by using a syntax quite similar to C#, which is used to transform VB6 code to its equivalent in .NET (C# or VB).
Applies to the following statements:
    Types
    Members (Methods, properties, subroutines, events, among others)
Also, this tool offers the possibility to generate code for statements that are not supported in .NET (for more information see Upgrade Stubs), reducing time to carry out the compilation of a migrated project.
In the code below they are some types like enumAlign and ctTips (ctTips1), including some members like Active, Tag, ToolTipText and Alignment.
Original VB6 Code source
1
Dim enumVal As enumAlign
2
...
3
Private Sub setCtTips()
4
ctTips1.Active = True
5
ctTips1.Tag = "Display component"
6
ctTips1.ToolTipText = "CtTips1"
7
ctTips1.Alignment = enumVal
8
End Sub
Copied!
By using Mappings Grammar it is possible to migrate classes and their members to their .NET equivalent.
Mappings design using Mappings Grammar
1
type TipsLib.ctTips => System.Windows.Forms.ToolTip;
2
type TipsLib.enumAlign => nomap;
3
4
member TipsLib.ctTips.Active => Active as boolean;
5
member TipsLib.ctTips.Container => Container;
6
member TipsLib.ctTips.Tag => Tag as string;
7
member TipsLib.ctTips.ToolTipText => ToolTipTitle as string;
8
member TipsLib.ctTips.Alignment => nomap;
Copied!
C# Code Generated by VBUC
1
//UPGRADE_ISSUE: (2068) TipsLib.enumAlign object was not upgraded.
2
UpgradeStubs.TipsLib_enumAlignEnum enumVal = (UpgradeStubs.TipsLib_enumAlignEnum) 0;
3
...
4
private void setCtTips()
5
{
6
ctTips1.Active = true;
7
ctTips1.Tag = "Display component";
8
ctTips1.ToolTipTitle = "CtTips1";
9
//UPGRADE_ISSUE: (2064) TipsLib.ctTips property ctTips1.Alignment was not upgraded.
10
ctTips1.setAlignment(enumVal);
11
}
Copied!
    Notes:
      As shown in the example above, ctTips will be upgraded into System.Windows.Forms.ToolTip.
      Some members of ctTips class like Active, Container, Tag and ToolTipText will be upgrade to its .NET equivalent.
      There are some classes and members that are not supported in .NET, so it generates stubs; like the class enumAlign and the member Alignment.
See also:
Map Grammar Documentation.pdf
282KB
PDF

Transformations Rules

Sometimes the client needs to apply custom transformation rules to specific code patterns in order to fulfill a requirement. Here are some examples:
    Rename all properties of a class of type string to str_propertyName.
    Make some classes implement a new interface and create a default method implementation for them.
    Transform all foo(str1, int1, str2, int2) method calls to otherFoo(str1, str2, int1 + int2).
    Add a new function call at the start of the methods in a class, in which the code has exactly one try-cath block.
    Remove the form_load event binding at the designer files, but keep the method handler.
    The VBUC team can create these custom code transformation rules to better achieve the customer-specific needs. The client only needs to define them at a macro level, by specifying the input code pattern, what conditions trigger the rule and how the output code should look like; after that, the VBUC team will handle the rest.

Windows API to Pinvoke

The Microsoft Windows application programming interface (Windows API) allows developers to call Windows OS functions directly. All programs interact with the Windows API at some point, either directly or through some other API.
Visual Basic 6 provides a mechanism to invoke methods in native code via dynamic-linked libraries (DLLs). This mechanism is possible to be used with the DECLARE statement in VB6. This statement indicates to the VB6 compiler where the procedure is located, how it is identified, its calling sequence and return type, and the string character set it uses. The Declare statement creates a reference to an external procedure and supplies this necessary information. In this way, the external procedure is called like any other method in the user code.
The following is a typical declaration and invocation of a Windows API method:
1
Declare Function getUserName Lib "advapi32.dll" Alias "GetUserNameA" (
2
ByVal lpBuffer As String, ByRef nSize As Integer) As Integer
3
Sub getUser()
4
Dim buffer As String = New String(CChar(" "), 25)
5
Dim retVal As Integer = getUserName(buffer, 25)
6
Dim userName As String = Strings.Left(buffer, InStr(buffer, Chr(0)) - 1)
7
MsgBox(userName)
8
End Sub
Copied!
In this case, the getUser internal method displays the current user name, to do this the GetUserNameA external method is being exposed from advapi32.dll with its respective parameters and return value.
Platform Invocation Service (PInvoke) is a feature of Common Language Infrastructure implementations, like Microsoft Common Language Runtime, that enables managed code to call native code. This is the mechanism provided by .NET to invoke this kind of method.
This is an example of how the Beep external method is declared as PInvoke method, which could be used in anywhere of the user code:
1
[DllImport("kernel32.dll")]
2
extern public static int Beep(int dwFreq, int dwDuration);
Copied!
The PInvoke infrastructure supplied by .NET is a mechanism for programmers in .NET to invoke external methods in an efficient and strong way. It will provide a .NET styled syntax to expose external methods and a natural way to invoke those external methods.
In general, for every external *.dll call, the VBUC generates the required interoperability data-type marshalling to allow a smooth interaction between.NET and unmanaged code. The most common changes in this feature are:
    Adds specific interoperability attributes to the signatures of upgraded API calls
    Adds error handling for the upgraded API calls.
    Generates the correct data types for pointer-type parameters
    Modifies structure generation so the marshalling of structs to Windows API calls and the copying of structures in migrated .NET applications is completely automated.
Sometimes declarations (or exposition) of an external method in .NET are easy, but invocation is sometimes complex because it has to deal with error handling, marshalling data types, and setting back values to its respective variables. This code seems to be larger and not natural, so the VBUC applies some refactoring to centralize all this code in methods that will contain all code related to those issues.
In this way, user code will be presented similar to the original, with no additional code to support marshalling or error handling, and this other code will be centralized in some files where the user can improve it or change it if necessary. Maintainability and removal of duplicated code are the main reasons why this approach is implemented in this way.
In addition, as stated above, a large amount of code for error handling, marshalling data types, especially if struct types are used to send or reassign return values to variables, must be generated in order to get the same behavior as VB6 had. All this code is generated by VBUC in those centralized files in a transparent way for all needed cases, mainly blittable types; and it will log EWIs in cases where some manual revision should be done, for non-blittable types.

External-Marshalling Attributes for Structs

The Visual Basic Upgrade Companion is able to add marshalling information to the structures used in Windows API calls. These extra attributes allow the resulting .NET code to be coherent with most of the legacy behavior found on the unmanaged code of the Windows API DLLs.
Original VB6 code:
1
Private Type ACTYLG_TYPE
2
lFirstField As Long ' <Force proper alignment>'
3
lIDN As Long ' INTEGER NOT NULL'
4
sCNCRCY_USER_IDN As String * 8 ' CHAR (8) NOT NULL'
5
sTABLE_ALIAS_NAME As String * 6 ' CHAR (6) NOT NULL'
6
iTABLE_UNQ_IDN_NI As Integer ' <Null Indicator>'
7
lTABLE_UNQ_IDN As Long ' INTEGER'
8
iTABLE_UNQ_SEQ_NUM_NI As Integer ' <Null Indicator>'
9
iTABLE_UNQ_SEQ_NUM As Integer ' SMALLINT'
10
End Type
Copied!
Resulting .NET Code:
1
[Serializable][StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
2
private struct ACTYLG_TYPE
3
{
4
public int lFirstField; // <Force proper alignment>
5
public int lIDN; // INTEGER NOT NULL
6
[Microsoft.VisualBasic.VBFixedArray(7)][System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray, SizeConst=8)]
7
public char[] _sCNCRCY_USER_IDN; // CHAR (8) NOT NULL
8
[Microsoft.VisualBasic.VBFixedArray(5)][System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray, SizeConst=6)]
9
public char[] _sTABLE_ALIAS_NAME; // CHAR (6) NOT NULL
10
public short iTABLE_UNQ_IDN_NI; // <Null Indicator>
11
public int lTABLE_UNQ_IDN; // INTEGER
12
public short iTABLE_UNQ_SEQ_NUM_NI; // <Null Indicator>
13
public short iTABLE_UNQ_SEQ_NUM; // SMALLINT
14
public string sCNCRCY_USER_IDN
15
{
16
get
17
{
18
return new string(_sCNCRCY_USER_IDN);
19
}
20
set
21
{
22
ArraysHelper.CopyStringToCharArray(_sCNCRCY_USER_IDN, value);
23
}
24
}
25
26
public string sTABLE_ALIAS_NAME
27
{
28
get
29
{
30
return new string(_sTABLE_ALIAS_NAME);
31
}
32
set
33
{
34
ArraysHelper.CopyStringToCharArray(_sTABLE_ALIAS_NAME, value);
35
}
36
}
37
38
public static ACTYLG_TYPE CreateInstance()
39
{
40
ACTYLG_TYPE result = new ACTYLG_TYPE();
41
result._sCNCRCY_USER_IDN = new char[8];
42
result._sTABLE_ALIAS_NAME = new char[6];
43
return result;
44
}
45
}
Copied!

Structure of generated PInvoke files

The declaration of a VB6 external method will generate two files.
The number of files will depend on the number of libraries being used in projects. It means if there are two external methods, one using a user32 library method and the other referencing a GDI library method, the VBUC will generate two files (user32 and GDI) in a folder inside the solution named, by default, PInvokeSafeNative. It will contain any additional code related to castings, marshalling, error handling, freeing memory, and so on, and it will have the managed code that will reference the unmanaged code.
The second two generated files (named user32 and GDItoo) will be generated in the folder named PInvokeUnsafeNative, where the PInvoke declaration code will be.
Two subfolders are created, as shown below.
1
/PInvokeSafeNative/
2
Lib1
3
Lib2
4
...
5
LibN
6
/PInvokeUnsafeNative/
7
Lib1
8
Lib2
9
...
10
LibN
Copied!
Inside those folders, a file will be created grouping PInvoke calls per DLL. If your API calls were, for example, to user32.dll, then a file with that name will be generated and all PInvoke calls to that DLL will be arranged inside that file. The following example shows how the code is upgraded.
Original VB6 code
1
Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hwnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
2
3
Private Declare Function GetWindowTextLength Lib "user32" Alias "GetWindowTextLengthA" (ByVal hwnd As Long) As Long
4
5
Private Sub Command1_Click()
6
Dim titleForm1 As String
7
titleForm1 = String(GetWindowTextLength(Me.hwnd) + 1, Chr$(0))
8
GetWindowText Me.hwnd, titleForm1, Len(titleForm1)
9
End Sub
Copied!
.NET Code
1
//File: user32.cs (safe methods)
2
public static class user32
3
{
4
public static int GetWindowText(int hwnd, ref string lpString, int cch)
5
{
6
return MySolutionSupport.PInvoke.UnsafeNative.user32.GetWindowText(hwnd, ref lpString, cch);
7
}
8
public static int GetWindowTextLength(int hwnd)
9
{
10
return MySolutionSupport.PInvoke.UnsafeNative.user32.GetWindowTextLength(hwnd);
11
}
12
}
13
14
//File: user32.cs (unsafe methods)
15
[System.Security.SuppressUnmanagedCodeSecurity]
16
public static class user32
17
{
18
[DllImport("user32.dll", EntryPoint = "GetWindowTextA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
19
extern public static int GetWindowText(int hwnd, [MarshalAs(UnmanagedType.VBByRefStr)] ref string lpString, int cch);
20
21
[DllImport("user32.dll", EntryPoint = "GetWindowTextLengthA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
22
extern public static int GetWindowTextLength(int hwnd);
23
}
24
25
//File: Form1.cs
26
private void Command1_Click(Object eventSender, EventArgs eventArgs)
27
{
28
string titleForm1 = new string(Strings.Chr(0), MySolutionSupport.PInvoke.SafeNative.user32.GetWindowTextLength(this.Handle.ToInt32()) + 1);
29
MySolutionSupport.PInvoke.SafeNative.user32.GetWindowText(this.Handle.ToInt32(), ref titleForm1, Strings.Len(titleForm1));
30
}
Copied!

Upgrading Win API Any arguments

Any is a VB6 data type only used for external method declarations that indicates that it could receive any type.
This is a type that is not available in Visual Studio .NET, so it must be converted to a pointer (System.IntPtr) that contains the beginning of the memory address for each data type used in that argument.
The following example references an external method named LoadCursor. The second parameter is declared as Any.
1
Declare Function LoadCursor Lib "user32" Alias "LoadCursorA" (ByVal hInstance As Long, ByVal lpCursorName As Any) As Long
2
3
Public Sub LoadSomeCursor()
4
' ...'
5
Dim inst As Long, myCursorName As String
6
' ...'
7
LoadCursor inst, myCursorName
8
End Sub
Copied!
These are the corresponding C# and VB.NET resultant codes. You can note the declaration of the Any argument as IntPtr in C# and Integer in VB for the Unsafe methods. The Safe methods are declared depending on the uses or invocations to the respective method. Because of that, the safe method is declared as a string in this case and requires some castings (marshalling) to be able to send this argument as a pointer and its respective setting back.
C#.NET
1
//[PInvokeSafeMethods]
2
public static int LoadCursor(int hInstance, string lpCursorName)
3
{
4
int result = 0;
5
IntPtr tmpPtr = Marshal.StringToHGlobalAnsi(lpCursorName);
6
try
7
{
8
result = MySolutionSupport.PInvoke.UnsafeNative.user32.LoadCursor(hInstance, tmpPtr);
9
lpCursorName = Marshal.PtrToStringAnsi(tmpPtr);
10
}
11
finally
12
{
13
Marshal.FreeHGlobal(tmpPtr);
14
}
15
return result;
16
}
17
18
//[PInvokeUnsafeMethods]
19
[DllImport("user32.dll", EntryPoint = "LoadCursorA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
20
extern public static int LoadCursor(int hInstance, System.IntPtr lpCursorName);
21
22
//…
23
public static void LoadSomeCursor()
24
{
25
int inst = 0;
26
string myCursorName = "";
27
MySolutionSupport.PInvoke.SafeNative.user32.LoadCursor(inst, myCursorName);
28
}
Copied!
VB.NET
1
'[PInvokeSafeMethods]'
2
Public Function LoadCursor(ByVal hInstance As Integer, ByRef lpCursorName As String) As Integer
3
Dim result As Integer = 0
4
Dim tmpPtr As IntPtr = Marshal.StringToHGlobalAnsi(lpCursorName)
5
Try
6
result = MySolutionSupport.UnsafeNative.user32.LoadCursor(hInstance, tmpPtr)
7
lpCursorName = Marshal.PtrToStringAnsi(tmpPtr)
8
Finally
9
Marshal.FreeHGlobal(tmpPtr)
10
End Try
11
Return result
12
End Function
13
14
'[PInvokeUnsafeMethods]'
15
Declare Function LoadCursor Lib "user32" Alias "LoadCursorA"(ByVal hInstance As Integer, ByVal lpCursorName As Integer) As Integer
16
17
'...'
18
Public Sub LoadSomeCursor()
19
Dim inst As Integer
20
Dim myCursorName As String = ""
21
MySolutionSupport.SafeNative.user32.LoadCursor(inst, myCursorName)
22
End Sub
Copied!

Upgrading Win API String arguments

The string arguments in external methods are handled almost as a general case, but the main difference is that if the argument was declared byref or byval, it always would be converted as byref in the target code. It implies handling of byref parameters being sent to that method and the declaration of that argument as VBByRefStr (in C#).
Original VB6 code
1
Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" _
2
(ByVal lpBuffer As String, nSize As Long) As Long
3
4
Public Sub GetCurUserName()
5
Dim lpBuf As String * 200
6
GetUserName lpBuf, 200
7
End Sub
Copied!
C# Code
1
//[PInvokeSafeMethods]
2
public static int GetUserName(ref string lpBuffer, ref int nSize)
3
{
4
return MySolutionSupport.PInvoke.UnsafeNative.advapi32.GetUserName(ref lpBuffer, ref nSize);
5
}
6
7
//[PInvokeUnsafeMethods]
8
[DllImport("advapi32.dll", EntryPoint = "GetUserNameA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
9
extern public static int GetUserName([MarshalAs(UnmanagedType.VBByRefStr)] ref string lpBuffer, ref int nSize);
10
11
//…
12
internal static void GetCurUserName()
13
{
14
string lpBuf = new string('\0', 200);
15
int tempRefParam = 200;
16
MySolutionSupport.PInvoke.SafeNative.advapi32.GetUserName(ref lpBuf, ref tempRefParam);
17
lpBuf = StringsHelper.GetFixedLengthString(lpBuf, 200);
18
}
Copied!
VB.NET Code
1
'[PInvokeSafeMethods]'
2
Public Function GetUserName(ByRef lpBuffer As String, ByRef nSize As Integer) As Integer
3
Return MySolutionSupport.UnsafeNative.advapi32.GetUserName(lpBuffer, nSize)
4
End Function
5
6
'[PInvokeUnsafeMethods]'
7
Declare Function GetUserName Lib "advapi32" Alias "GetUserNameA"(ByVal lpBuffer As String, ByRef nSize As Integer) As Integer
8
9
' ...'
10
Public Sub GetCurUserName()
11
Dim lpBuf As New String(Microsoft.VisualBasic.Constants.vbNullChar, 200)
12
MySolutionSupport.SafeNative.advapi32.GetUserName(lpBuf, 200)
13
End Sub
Copied!

Upgrading Win API Struct arguments

Handling and passing structures to an external method are also handled differently in the PInvoke solution. In this case, a new file is generated in the PInvokeUnsafeMethods folder, which will have the structure being passed as an argument in that external method.
It implies, additionally, that any reference to that structure has to be changed to reference this new location of the structure.
Moreover, in multiple project solutions, a merge and removal of repeated structures must be done, in order to discard many duplicated structures. Sometimes there are differences between some structures that seem very similar (same name but different fields or data type fields), in this case, a renaming is added for subsequent structures and it is possible that some manual revision must be done.
Original VB6 Code
1
Type POINTAPI
2
x As Long
3
y As Long
4
End Type
5
6
Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
7
Public Sub ObtainCursorPos()
8
Dim pos As POINTAPI
9
GetCursorPos pos
10
End Sub
Copied!
C# Code
1
//[PInvokeSafeMethods]
2
public static int GetCursorPos(ref MySolutionSupport.PInvoke.UnsafeNative.Structures.POINTAPI lpPoint)
3
{
4
return MySolutionSupport.PInvoke.UnsafeNative.user32.GetCursorPos(ref lpPoint);
5
}
6
7
// [PInvokeUnsafeMethods]
8
[DllImport("user32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
9
extern public static int GetCursorPos(ref MySolutionSupport.PInvoke.UnsafeNative.Structures.POINTAPI lpPoint);
10
11
//[PInvokeUnsafeMethods\Structures]
12
public static class Structures
13
{
14
[Serializable][StructLayout(LayoutKind.Sequential)]
15
public struct POINTAPI
16
{
17
public int x;
18
public int y;
19
}
20
}
Copied!
VB.NET Code
1
'[PInvokeSafeMethods]'
2
Public Function GetCursorPos(ByRef lpPoint As MySolutionSupport.UnsafeNative.Structures.POINTAPI) As Integer
3
Return MySolutionSupport.UnsafeNative.user32.GetCursorPos(lpPoint)
4
End Function
5
6
'[PInvokeUnsafeMethods]'
7
Declare Function GetCursorPos Lib "user32" (ByRef lpPoint As MySolutionSupport.UnsafeNative.Structures.POINTAPI) As Integer
8
9
'[PInvokeUnsafeMethods\Structures]'
10
<System.Security.SuppressUnmanagedCodeSecurity> _
11
Public Module Structures
12
<Serializable> _
13
<StructLayout(LayoutKind.Sequential)> _
14
_
15
Public Structure POINTAPI
16
Dim x As Integer
17
Dim y As Integer
18
End Structure
19
End Module
Copied!

.NET Core / .NET 5 Support

VBUC offers the possibility to migrate your VB6 project to new .NET platforms like .NET Core 3.1 and .NET 5; for this, it is necessary to follow the steps to Create a VBUC solution targeting new .NET platforms.
See more info on .NET Core / .NET 5

New project files style (SDK style)

One of the most essential differences when choosing .NET Core and .NET 5 vs .NET Framework in terms of generated code, would be the .csproj file since the formers use the new SDK project file style.
.csproj file in .NET Framework
1
<?xml version="1.0" encoding="utf-8"?>
2
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
3
<PropertyGroup>
4
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
5
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
6
<ProductVersion />
7
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
8
...
9
<ProjectReference Include="..\UpgradeSupport\UpgradeHelpers.DB.Essentials\UpgradeHelpers.DB.Essentials.csproj">
10
<Project>{B5D4A0EE-0D52-4EE8-829D-48DAF1E56B8E}</Project>
11
<Name>UpgradeHelpers.DB.Essentials</Name>
12
</ProjectReference>
13
...
14
</Project>
Copied!
.csproj file in .NET Core or .NET 5
1
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
2
<PropertyGroup>
3
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
4
<ProductVersion />
5
<TargetFrameworks>netcoreapp3.1;net5.0-windows</TargetFrameworks>
6
...
7
<PackageReference Include="Mobilize.VBUC.Helpers.DB.Essentials" Version="9.0.0"