The following C# code shows how to use WMI to query printers information, set and get default printer.
public bool SetDefaultPrinter()
{
System.Management.ManagementObjectSearcher search =
default(System.Management.ManagementObjectSearcher);
System.Management.ManagementObjectCollection results =
default(System.Management.ManagementObjectCollection);
System.Management.ManagementObject printer =
default(System.Management.ManagementObject);
search =
new System.Management.ManagementObjectSearcher("select * from win32_printer");
results = search.Get();
//Get Default Printer
System.Management.ManagementObject defaultPrinter = null;
foreach (System.Management.ManagementObject foundPrinter in results)
{
System.Management.PropertyDataCollection
propertyDataCollection = foundPrinter.Properties;
if ((bool)foundPrinter["Default"]) // DEFAULT PRINTER
{
System.Diagnostics.Debug.WriteLine(foundPrinter["Name"]);
System.Diagnostics.Debug.WriteLine(foundPrinter["Location"]);
}
}
//Sets new default Printer
foreach (System.Management.ManagementObject foundPrinter in results)
{
System.Diagnostics.Debug.Print(foundPrinter["Name"].ToString());
if (foundPrinter["Name"].Equals("PDFCreator"))
{
System.Management.ManagementBaseObject outParams =
foundPrinter.InvokeMethod("SetDefaultPrinter", null, null);
if (outParams == null)
System.Diagnostics.Debug.WriteLine("Unable to set default printer");
Int32 retVal = (int)(uint)outParams.Properties["ReturnValue"].Value;
if (retVal == 0)
return true;
else
return false;
}
}
return false;
}
For VB6 applications it is common to rely on OS or Kernel API Calls. Some of those APIs might
need you to send data back and for the native API.
Marshalling in .NET can be complicated and bothersome. I have published several posts about
interop. But it usually depends on adding several marshalling attributes and even tricks specially for
fixed strings.
So I decided to provide a more a simpler approach for conversion. In this approach you just need to things:
1. Your VB6 types or structs will be mapped to .NET classes
2. All VB6 type or struct fields will be mapped to public fields
3. An attribute must be used on those fields to indicate the field length, for arrays or strings.
4. Extension methods .AsString() .SetFromString and .GetClassLength will handle all the complexities of setting the struct fields.
Let’s see an example:
Type EmployeeRecord
FirstName As String * 5
LastName As String * 5
End Type
That vb6 type will be mapped in .NET following this approach to:
public class EmployeeRecord
{
[FixedLength(5)]
public string FirstName = "Mau";
[FixedLength(5)]
public string LastName = "Rojas";
}
You can then simple use that class in .NET
var emp = new EmployeeRecord {FirstName="Mauricio",LastName="Rojas"} ;
var str = emp.AsString();
//This str value will be "MauriRojas" the helper extension methods
// .AsString and .SetFromString will handle setting the internal class fields
All that is very good but how is this used in Marshalling?? Well very simple. Let’s say you have a Dll called foo.dll
with a function foo that receives an EmployeeRecord:
[DllImport("foo.dll")]
public static extern int foo(IntPtr Struct);
Then if you want to call that function you will do something like:
var emp = new EmployeeRecord { FirstName="Ann",LastName="Smith"};
string str = emp.AsString();
var ptr = IntPtr.Zero;
ptr = Marshal.StringToBSTR(str);
//or
ptr = Marshal.StringToHGlobalAnsi(str);
//or
ptr = Marshal.StringToHGlobalAuto(str);
//or
ptr = Marshal.StringToHGlobalUni(str);
//And call the native function
foo(ptr);
If the function modifies the structure and you want to reflect those changes then you will do something like:
str = Marshal.PtrToStringAnsi(ptr,typeof(EmployeeRecord).GetClassLength())
emp.SetFromString(str);
This solution can also be applied for more complex structures. For example:
public class EmployeeRecord
{
[FixedLength(5)]
public string FirstName = "Mau";
[FixedLength(5)]
public string LastName = "Rojas";
}
public class Record1
{
public int field1;
[FixedLength(10)]
public string field2 = "";
public EmployeeRecord rec = new EmployeeRecord();
}
public class GeneralInfo
{
public int field1;
[ArrayLength(5)]
[FixedLength(2)]
public String[] countrycodes = { "cr","es","mx","pa","ni"};
[FixedLength(2)]
public EmployeeRecord[] employees;
}
If you want to try it out this is the link to the CODE
If you were in VB6 HelpContextID will be familiar for you (http://msdn.microsoft.com/en-us/library/aa267690(v=vs.60).aspx). In those sweet VB6 days all you had to do was:
Private Sub Form_Load ()
App.HelpFile = "VB.HLP"
Frame1.HelpContextID = 21004
Text1.HelpContextID = 21001
Form1.HelpContextID = 21005
End Sub
And each time you pressed the F1 button your application will have opened the .hlp file and show you the Help Topic corresponding to that ID. After migration from VB6 to WinForms Help you now have the HelpProvider.SetHelpKeyword http://msdn.microsoft.com/en-us/library/system.windows.forms.helpprovider.sethelpkeyword.aspx And you had to do something like:
internal System.Windows.Forms.HelpProvider HelpProvider1;
...
HelpProvider1.HelpNamespace = "sample.chm";
HelpProvider1.SetHelpKeyword(TextBox1, "1007.html");
HelpProvider1.SetHelpNavigator(TextBox1, HelpNavigator.Topic);
HelpProvider1.SetHelpKeyword(ListBox1, "1006.html");
HelpProvider1.SetHelpNavigator(ListBox1, HelpNavigator.Topic);
And all that seems nice. But, what can you do when you cross over to SilverlightjQuery15205164761650376022_1357918518660? Well, in general there are several systems that allow you to author your help files in html or convert your .hlp or .chm files to html, but how do you link your components to that help system in order to provide context-sensitive help???? Ok. So one of the possible solutions is very very simple. In general, the solution that I will show in this post is this: 1) First implement an attached property for adding a HelpKeyword to Silverlight components 2) Set the helpkeyword in the desired components 3) Provide logic that will open the appropiate help file. Ok. So let's implement a Silverlight Attached property. An attached propery is like adding a new property to your controls. This new attached property will be called Helpkeyword
using System;
using System.Windows.Shapes;
namespace System.Windows.Controls
{
public class HelpProvider
{
public static readonly DependencyProperty HelpKeyword =
DependencyProperty.RegisterAttached("HelpKeyword", typeof(string), typeof(HelpProvider), new PropertyMetadata(null));
public static void SetHelpKeyword(UIElement element, string keyword)
{
element.SetValue(HelpKeyword, keyword);
}
public static string GetHelpKeyword(UIElement element)
{
return (string)element.GetValue(HelpKeyword);
}
}
}
Ok. So once we have the attached property we have to use it, and set it on the code: To set it on the code we must add a namespace:
<UserControl x:Class="SilverlightApplication.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
...
xmlns:help="clr-namespace:System.Windows.Controls"
mc:Ignorable="d"
....>
And apply the attribute to components
<Button help:HelpProvider.HelpKeyword="helpforbutton1" Content="Button" ... />
<TextBox help:HelpProvider.HelpKeyword="helpfortext1" Height="47" ... />
So that almost everything, now we just need to trigger the appropiate logic, to do that we will add a KeyUp handler to the top most element, in this example a grid. NOTE: if Silverlight is running on the browser F1 is not an option. I just used F2 here as an example.
<Grid x:Name="LayoutRoot" Background="White" Height="205" KeyUp="LayoutRoot_KeyUp">
<Button help:HelpProvider.HelpKeyword="helpforbutton1" ... />
<TextBox help:HelpProvider.HelpKeyword="helpfortext1" ... />
</Grid>
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Browser;
namespace SilverlightApplication
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}
private void LayoutRoot_KeyUp(object sender, KeyEventArgs e)
{
//check for the specific key. For now use F2 as the Help Shortcut
if (e.Key==Key.F2) {
var uielement = FocusManager.GetFocusedElement() as UIElement;
if (uielement!=null)
{
var keyword = HelpProvider.GetHelpKeyword(uielement);
var host = HtmlPage.Document.DocumentUri.Host;
var port = HtmlPage.Document.DocumentUri.Port;
var url = string.Format("http://{0}:{1}/help/{2}.html", host,port,keyword);
HtmlPage.Window.Navigate(new Uri(url),"_blank");
}
} // else ignore the keystroke
}
}
}
This property can be used on the IDE:
On code
var uielement = FocusManager.GetFocusedElement() as UIElement;
if (uielement!=null) {
var keyword = HelpProvider.GetHelpKeyword(uielement);
}
This is an image of the application running.
And you can download the code from: CODE
If you have any questions or would like more info on Silverlight migration check www.silverlightmigration.com
In VB6 when you have an ActiveX Library it was very important to use
the BinaryCompatibility setting to make sure that your applications did not break after a change.
So let’s first introduce what is binary compatibility and how to accomplish that in .NET.
Binary Compatibility allows to make changes to your components or COM classes without recompiling
every application you've made that uses the component.
And why do you need it. Why compatibility breaks.
On lets see.
An ActiveX Control or DLL expose Public interfaces.
Those interfaces have all of the properties, methods, events, etc. that you've marked as Public.
In other words, everything you've added that shows in Intellisense while working outside of your component.
Now let's say you have create a class, with two Methods Method1 and Method2
When you compile, VB generates all the COM infraestructure you need for your component.
It defines a CoClass and an interface and an entry for each method.
For a vb class with two methods:
Sub Method1()
End Sub
Sub Method2()
End Sub
It will produce a typelib like:
// Generated .IDL file (by the OLE/COM Object Viewer)
//
// typelib filename: <could not determine filename>
[
uuid(8ABA2C0C-7CCA-40CD-A944-56707566634A),
version(1.0)
]
library Project1
{
// TLib : // TLib : OLE Automation : {00020430-0000-0000-C000-000000000046}
importlib("stdole2.tlb");
// Forward declare all types defined in this typelib
interface _Class1;
[
odl,
uuid(6B86684C-B3DD-4680-BF95-8DEE2C17AF5B),
version(1.0),
hidden,
dual,
nonextensible,
oleautomation
]
interface _Class1 : IDispatch {
[id(0x60030000)]
HRESULT Method1();
[id(0x60030001)]
HRESULT Method2();
};
[
uuid(C71C7AB0-552A-4D5D-A9FB-AF33830A697E),
version(1.0)
]
coclass Class1 {
[default] interface _Class1;
};
};
As you can see in the typelib there are IDs associated to each coclass, interface and
methods. Those IDs are the ones use when you generate the .exe file for your application.
Now if you modify your Class to:
Sub Method3()
End Sub
Sub Method4()
End Sub
Sub Method1()
End Sub
Sub Method2()
End Sub
and you use No Compatibility the typelib after your changes will be:
// Generated .IDL file (by the OLE/COM Object Viewer)
//
// typelib filename: <could not determine filename>
[
uuid(FE5C56C2-E03A-4DC0-994D-B68543C72A46),
version(1.0)
]
library Project1
{
// TLib : // TLib : OLE Automation : {00020430-0000-0000-C000-000000000046}
importlib("stdole2.tlb");
// Forward declare all types defined in this typelib
interface _Class1;
[
odl,
uuid(A3032E1E-52FE-42E0-98FF-84A9DD4FD8C3),
version(1.0),
hidden,
dual,
nonextensible,
oleautomation
]
interface _Class1 : IDispatch {
[id(0x60030000)]
HRESULT Method3();
[id(0x60030001)]
HRESULT Method4();
[id(0x60030002)]
HRESULT Method1();
[id(0x60030003)]
HRESULT Method2();
};
[
uuid(72721504-CC56-4BB9-9447-C7193FE8C02D),
version(1.0)
]
coclass Class1 {
[default] interface _Class1;
};
};
As you can see, now the ids for the methods, CoClass are different, so your applications will return errors like: Error 430 (Automation error, the component dies horribly) or Error 429 (can't create the object at all)
But if you instead used BinaryCompatibility then the typelib for your class will be:
// Generated .IDL file (by the OLE/COM Object Viewer)
//
// typelib filename: <could not determine filename>
[
uuid(8ABA2C0C-7CCA-40CD-A944-56707566634A),
version(1.1)
]
library Project1
{
// TLib : // TLib : OLE Automation : {00020430-0000-0000-C000-000000000046}
importlib("stdole2.tlb");
// Forward declare all types defined in this typelib
interface _Class1;
[
odl,
uuid(6E9C59C3-82D7-444C-92FB-01B49D91A2FF),
version(1.1),
hidden,
dual,
nonextensible,
oleautomation
]
interface _Class1 : IDispatch {
[id(0x60030002)]
HRESULT Method3();
[id(0x60030003)]
HRESULT Method4();
[id(0x60030000)]
HRESULT Method1();
[id(0x60030001)]
HRESULT Method2();
};
[
uuid(C71C7AB0-552A-4D5D-A9FB-AF33830A697E),
version(1.1)
]
coclass Class1 {
[default] interface _Class1;
};
typedef [uuid(6B86684C-B3DD-4680-BF95-8DEE2C17AF5B), version(1.0), public]
_Class1 Class1___v0;
};
If you compare now the two typelibs you can see the Method1 and Method2 keep the same ids.
For each version a typedef is generated that will point to the last version. For example adding a Method5 will add new entry like:
typedef [uuid(6B86684C-B3DD-4680-BF95-8DEE2C17AF5B), version(1.0), public]
_Class1 Class1___v0;
typedef [uuid(6E9C59C3-82D7-444C-92FB-01B49D91A2FF), version(1.1), public]
_Class1 Class1___v1;
Well that is what binary compatibility does. Now how to achieve binary compatibility in .NET
Binary Compatibility in .NET
Achieving binary compatibility in .NET is really easy. You just need to give more information to
make explicit how your typelib information will be. I will follow an approach as the one I already explained in this post:
http://blogs.artinsoft.net/mrojas/archive/2010/06/23/exposing-c-classes-thru-interop.aspx
Lets take our previous example:
using System;
using System.Runtime.InteropServices;
namespace InteropExamples
{
public class Class1
{
public void Method3()
{
}
public void Method4()
{
}
public void Method1()
{
}
public void Method2()
{
}
public void Method5()
{
}
}
}
In previous posts I had recommended using partial classes and using interfaces to explicitly specify what you what to be seen in COM. This means you start up with something like:
public partial class Class1
{
public void Method3()
{
}
public void Method4()
{
}
public void Method1()
{
}
public void Method2()
{
}
}
[ComVisible(true)]
public interface _Class1
{
void Method3();
void Method4();
void Method1();
void Method2();
}
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_Class1))]
partial class Class1 : _Class1
{
#region _Class1 Members
void _Class1.Method3()
{
Method3();
}
void _Class1.Method4()
{
Method4();
}
void _Class1.Method1()
{
Method1();
}
void _Class1.Method2()
{
Method2();
}
#endregion
}
Now to make this code binary compatible then you have to make sure that the tlb file generated for your class is almost identical to that generated before. To acomplish that we must make sure that we your methods, interfaces and classes have the same guids and ids. Lets see how:
using System;
using System.Runtime.InteropServices;
namespace InteropExamples
{
public partial class Class1
{
public void Method3()
{
System.Windows.Forms.MessageBox.Show("3 N");
}
public void Method4()
{
System.Windows.Forms.MessageBox.Show("4 N");
}
public void Method5()
{
System.Windows.Forms.MessageBox.Show("5 N");
}
public void Method1()
{
System.Windows.Forms.MessageBox.Show("1 N");
}
public void Method2()
{
System.Windows.Forms.MessageBox.Show("2 N");
}
}
[ComVisible(true)] //This to make the interface Visible for COM
[TypeLibType((TypeLibTypeFlags)((short)TypeLibTypeFlags.FHidden |
(short)TypeLibTypeFlags.FDual |
(short)TypeLibTypeFlags.FNonExtensible |
(short)TypeLibTypeFlags.FOleAutomation))] //This to use the same flags as in previous tlb
[Guid("9BAFD76D-8E6B-439C-8B6D-37260BFA3317")] //This is to make the class have the guid
public interface _Class1
{
[DispId(0x60030000)]
void Method1();
[DispId(0x60030001)]
void Method2();
[DispId(0x60030002)]
void Method3();
[DispId(0x60030003)]
void Method4();
[DispId(0x60030004)]
void Method5();
}
[ComVisible(true)] //This to make the class Visible for COM
[ClassInterface(ClassInterfaceType.None)] //This is to make sure that we have control on interface generation
[ComDefaultInterface(typeof(_Class1))] //To set default interface
[ProgId("Project1.Class1")] //To set ProgId
[Guid("C71C7AB0-552A-4D5D-A9FB-AF33830A697E")] //Maintain same Guid.
partial class Class1 : _Class1, Class1___v0, Class1___v1
{
#region _Class1 Members
void _Class1.Method3()
{
Method3();
}
void _Class1.Method4()
{
Method4();
}
void _Class1.Method1()
{
Method1();
}
void _Class1.Method2()
{
Method2();
}
#endregion
#region Class1___v0 Members
void Class1___v0.Method1()
{
Method1();
}
void Class1___v0.Method2()
{
Method2();
}
void Class1___v0.Method3()
{
Method3();
}
void Class1___v0.Method4()
{
Method4();
}
void Class1___v0.Method5()
{
Method5();
}
#endregion
#region Class1___v1 Members
void Class1___v1.Method1()
{
Method1();
}
void Class1___v1.Method2()
{
Method2();
}
void Class1___v1.Method3()
{
Method3();
}
void Class1___v1.Method4()
{
Method4();
}
void Class1___v1.Method5()
{
Method5();
}
#endregion
}
//This is to keep compatibility with old versions
//we cannot generate a typedef so we will need to add all of the versions
//for BinaryCompatibility
[ComVisible(true)]
[Guid("6B86684C-B3DD-4680-BF95-8DEE2C17AF5B")]
[TypeLibType(TypeLibTypeFlags.FHidden)]
public interface Class1___v0
{
[DispId(0x60030000)]
void Method1();
[DispId(0x60030001)]
void Method2();
[DispId(0x60030002)]
void Method3();
[DispId(0x60030003)]
void Method4();
[DispId(0x60030004)]
void Method5();
}
//This is to keep compatibility with old versions
//we cannot generate a typedef so we will need to add all of the versions
//for BinaryCompatibility
[ComVisible(true)]
[Guid("4A7A3317-BF13-443E-9DB0-2C5EA21F00CA")]
[TypeLibType(TypeLibTypeFlags.FHidden)]
public interface Class1___v1
{
[DispId(0x60030000)]
void Method1();
[DispId(0x60030001)]
void Method2();
[DispId(0x60030002)]
void Method3();
[DispId(0x60030003)]
void Method4();
[DispId(0x60030004)]
void Method5();
}
}
Sadly in .NET you cannot use Interface Inheritance in COM. If there is interface inheritance YOU HAVE TO IMPLEMENT each interface. In the case of code that comes from VB6. VB6 just uses typedefs, so you really don’t know which methods belong to each version. So in the end all versions have all methods.
The other alternative to this method, is just to implement last version. And after generating the tlb, decompile it to an .IDL file add the typedefs and recompiled it. I explained something similar in this post:http://blogs.artinsoft.net/mrojas/archive/2010/05/17/interop-remove-prefix-from-c-enums-for-com.aspx
Ok. I hope this helps you to have an more clear idea of what Binary Compatibility is and how to do it in .NET. I am attaching some sample code. It show an ActiveX library that uses BinaryCompatibility and three version on an aplications that uses the different versions. And also a .NET class library that is equivalent to the VB6 one. HERE
Enjoy.
AutoCAD 2010 will not be supporting VBA.
Quoting
“If you utilize VBA macros in your work environment, they will no longer work unless the VBA module is installed on your system. “
“When you run a command that requires VBA, a message dialog box will be displayed stating that VBA is no longer installed with AutoCAD and directing you to a website where you can download the VBA module. “
And also you can see that Autodesk states: “Autodesk is evaluating how long VBA will be supported in Autodesk products in the future. Though supported in the AutoCAD 2010-based products, it may or may not be supported in future releases. Therefore, it is strongly recommended that VB developers develop all new code using VB .NET.”
VBA does not support 64bit systems in a native way.
But If you want some advice from the VB migration experts or help on your migration project from VBA to VB.NET or C# you can us contact Artinsoft Migration Services.
We build the VB Upgrade Wizard that shipped with Visual Studio and have been doing VB migrations for years.
In it March issue, Visual Studio Magazine published an in-depth article about legacy migrations called “Unlocking Legacy Code”. This article talks about the challenges faced by companies migrating from Visual Basic 6.0 to .NET, the drivers behind these migrations and the pros and cons of using an automated migration solution.
The article uses BEMAS Software as a case study for successful migration products. I am incredibly happy they are doing as well as they are with the conversion – they are using our tools, and I visited BEMAS about a year and a half ago to train them on the VBUC and help them plan the migration project. I remember they had a lot of conditional statements (by “a lot”, we are talking thousands of different combinations), as mentioned in the article:
"We also ran into some issues with the conversion tool because early on in the VB code we did a lot of #ifs, which means that the code acts differently depending on how you compile it," Pownall adds. BEMAS worked with ArtinSoft so that VBUC would recognize those instances and convert the code correctly.
It was quite a challenge to get it to convert, since the default behavior of the VBUC is to convert the code inside the conditional statement that evaluates to “TRUE”. Commenting out the conditionals wasn’t going to work either, since that would cause multiple variable declarations and other semantic errors that caused issues during the migration of this particular code. In the end we worked together with BEMAS, and with heavy involvement of the VBUC development team, we managed to modify the tool enough to get the code converted correctly.
Another very interesting item mentioned by Steve Pownall in the article, that I want to talk about some more, is the fact that even though the code came through very cleanly, it didn’t have the .NET architecture they were aiming for so they had to “The dev team had to massage or opted to rewrite the rest of the codebase manually in C# and .NET 3.5 using VS2008.”. This is a very important point, since the overall architecture of the code will remain as it was in VB6.0. The migration, however, gets you quickly to a stable .NET codebase that you can then rework to make it take advantage of the latest features of the .NET Framework. In our experience, this path (migrate, then enhance) is the one with the lowest risk, and it allows you to reduce the time to market for your applications by a wide margin. This is important to keep in mind, since we, as developers, always want to improve the code base – it is part of our professional formation, and I would say, part of our nature – but we sometimes fail to grasp the additional risk this implies. The migration is very controlled process, that gets you predictable results in a short time. Enhancing the application after the migration may seem like duplicating work (and indeed, there are enhancements that can be done during the migration process) but it guarantees that you will get a .NET in the allocated timeframe and budget, not to mention the cost advantage.
Read the complete article, Unlocking Legacy Code at Visual Studio Magazine.
One very common requirement for migration projects is to adapt certain error handling patterns used in a customer’s Visual Basic 6.0 code to the structured error handling provided by .NET, cleaning up the code, improving its maintainability, and, whenever possible, complying with .NET best practices.
The VBUC already converts several commonly used error handling patterns, such as the ones described in this old post. There are, however, situations where the VBUC is not able to recognize a pattern. these usually involve Goto statements, On Error Resume Next, Resume Next or some other construct usually associated with “spaghetti code”. When one of these patterns is encountered, the VBUC does a very basic transformation and generates an EWI so it can be cleaned up through manual intervention later on, such as in the following example:
Visual Basic 6.0 Code |
.NET Code |
Private Function <NAME>(<PARAMS>) As <TYPE>
Const MethodName As String = "<NAME>"
On Error GoTo ErrorLabel
<STATEMENTS 1>
On Error GoTo <LABEL>
<STATEMENTS 2>
CleanUp:
<STATEMENTS 3>
Exit Function
<LABEL>:
<STATEMENTS 4>
LogError(MethodName)
Err.Raise 16, , MethodName
ErrorLabel:
<STATEMENTS 5>
LogError(MethodName)
Err.Raise Err.Number, , MethodName
End Function
|
private <TYPE> <NAME>()
{
const string MethodName = "<NAME>";
//UPGRADE_TODO: (1065) Error handling statement
(On Error Goto) could not be converted.
More Information: http://www.vbtonet.com/ewis/ewi1065.aspx
NotUpgradedHelper.NotifyNotUpgradedElement(
"On Error Goto Label (ErrorLabel)");
<STATEMENTS 1>
try
{
<STATEMENTS 2>
<STATEMENTS 3>
return result;
}
catch (Exception ex)
{
<STATEMENTS 4>
LogError(MethodName);
throw new System.Exception(
((int) 16).ToString() +
", " + String.Empty +
", " + MethodName);
ErrorLabel:
<STATEMENTS 5>
//UPGRADE_WARNING: (2081) Err.Number has a new behavior.
More Information: http://www.vbtonet.com/ewis/ewi2081.aspx
LogError(MethodName);
throw new System.Exception(
Information.Err().Number.ToString() +
", " + String.Empty +
", " + MethodName);
return result;
}
} |
Most of the time it is possible to generate a solution that will correctly convert the error handling pattern, maintaining functional equivalence and meeting any additional coding guidelines from our customers. For the previous example, The VBUC can be customized so the generated code looks as follows:
try
{
try
{
<STATEMENTS 1>
}
catch (Exception ex){
<STATEMENTS 5>
throw;
}
try
{
<STATEMENTS 2>
}
catch (Exception <LABEL>Ex)
{
<STATEMENTS 4>
<LABEL>Ex.Data.Add("ERROR",16);
throw;
}
}
finally
{
<STATEMENTS 3>
}
This example makes some assumptions on the nature of the code and on the intention of the original VB6.0 developer, in particular:
- Errors raised by <STATEMENTS 1> should be handled by <STATEMENTS 5>
- Errors raised by <STATEMENTS 2> should be handled by <STATEMENTS 4>
- <STATEMENTS 3> is cleanup code that should always be executed
- The Exception needs to be thrown again without loosing any information
This is just an example, but the intention is to show what type of customizations can be done. The VBUC transformation engine is very powerful, and, as long as a pattern can be identified, can help you automate the solution to most VB6.0 problems.
A while ago I wrote about the decision that many people face when
starting to consider a migration from Visual Basic 6.0 to the .NET
platform: choosing the target language, mainly between VB.NET and C#. Today I found a great post by John Fuex
on that subject, not inciting the war between both trenches but instead
describing the process he and his company went through to solve the C# versus .NET dilemma.
He basically used the following criteria to qualify each language:
Functionality, Learning Curve, Existing Code, Developer Preferences,
“Street Cred” (for both the developers and products), and Recruiting.
But in the end it reinforces the notion that there’s not a standard
solution, so the selection should always be made case by case.
You can read the whole post here.
When you develop applications with remoting, or in some COM + Remoting
scenarios, you could start founding very interesting exceptions.
We had a very unconfortable one. We had an ActiveX that is used in an
intranet Web Page, that uses remoting to instanciate some classes in
the local network.
When we runned outside of the IE, everything seem to work, but running in IE it produced an exception like:
Error : Return argument has an invalid type.
Type : System.InvalidCastException
Source: mscorlib
Source: at System.Runtime.Remoting.Proxies.RealProxy.ValidateReturnArg(Object arg, Type paramType)
at System.Runtime.Remoting.Proxies.RealProxy.PropagateOutParameters(IMessage msg, Object[] outArgs, Object returnValue)
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
Why??? Well what happens is simple, it is having an assembly resolution problem, it is not being able to resolve the type.
We solve the problem adding something like:
1. Find a place in your code to add an event like this (it could be in the Main of your program for example):
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
2. Add a handler like this:
static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
System.Reflection.Assembly assembly = null;
try
{
assembly = System.Reflection.Assembly.Load(new System.Reflection.AssemblyName(args.Name));
}
catch (Exception ex)
{
System.Diagnostics.Trace.WriteLine(
string.Format(“Problem with resolution of {0} : {1} {2}”, args.Name, ex.Message, ex.StackTrace));
}
return assembly;
}
Well, this worked for us, and I hope that helps you out.
Here is a quick way to know if a binary file (*.exe, *.dll, *.ocx, …) has a dependency on the Visual Basic 6.0 Runtime. The trick is to use the Dependency Walker tool to see its dependencies. The dependency you are looking for is the Visual Basic 6.0 runtime library (msvbvm60.dll), and it appears on the tree if you are dealing with a VB6.0 binary:
If you are concerned about the VB6.0 runtime not being supported after Windows Server 2008 and Windows 7, this is a trick that can help you decide whether to keep a particular third party ActiveX component in your application through COM Interop after migrating to the .NET Framework or to start looking for a replacement in case the runtime is no longer available (and thus the component will no longer work).
Dependency Walker is a freeware tool that was included with Visual Studio 6.0, is included in the Windows Support Tools and can be downloaded from the Dependency Walker homepage.
The business-oriented newspaper, El Financiero, just published an article talking about the advantages of performing a migration instead of a manual rewrite. The article talks about how Banamex (part of Citigroup) saved an estimated 80% of the cost when compared to rewriting their 125 applications, totaling over 5 million lines of code. It also talks about the advantages of being in .NET, including how it allows customers to rapidly respond to changes in market conditions.
You can read the original article in Spanish at the following link: Cambiar el software en estos tiempos de crisis or read the Google Translation in English. You can also check out the Banamex/Citigroup case study at the following link: Banamex - Citigroup turns to ArtinSoft to ensure compliance and business continuity through massive migration to C#.NET
Yesterday TechNewsWorld published an article called Planning a Migration Route From Visual Basic 6 to .Net, which discusses some aspects of a report by the Aberdeen Group. The article contains lots of valuable information for those of you considering moving your VB6.0 applications to .NET, by giving a very good idea on the best practices performed by the “Best-in-Class” organizations. I wanted to touch briefly on some of the points from the article, and how it matches our experience helping Fortune/Global 1000 companies upgrade their applications to the latest technology.
Something that is consistent with what we’ve seen is that 33% of the respondents from Best-in-Class and 15% of the “All Others” organizations engage a third party to assist with the migration. We at ArtinSoft, with our Consulting Services group, and along with our world-wide partners, have seen this as a growing trend, and have accumulated a vast a mount of experience that can be leveraged by these organizations to move away from legacy environments.
Also, as part of our migration methodology, we promote a controlled process that first brings your VB6.0 application up to Functional Equivalence in .NET, and then you can use this as a base to enhance an improve your investment. For many clients we also use the extensibility capabilities of the Visual Basic Upgrade Companion to prepare the source code for these enhancements by automating specific architectural modifications required by our customers. These modifications represent an enhancement in itself, and also leave the code ready for further changes by making sure it meets all the practices and coding standards of the organization. The Vertex Omiga and Supervisor Case Studies are a good example in this regard – and we’ve done other migrations with even more important customizations that, unfortunately, I can’t mention directly.
Finally, I want to quote the following text from near the end of the article:
“The research shows that Best-in-Class companies are six times more likely than all other companies to use code conversion or automated porting tools in order to help accelerate part of the migration process.”
You can read our case studies that show this is in fact the case, and we have helped many organizations save time and resources when performing migrations aided by using the Visual Basic Upgrade Companion.
As you are probably well aware, along with the release of Windows 7 RC came some big news that affect Visual Basic 6.0 applications: Professional and Ultimate Editions of Windows 7 will feature a Windows XP Mode for backwards compatibility with legacy applications. This means that even if you are using components that have issues with Windows 7, you will be able to run your VB6.0 application on the new operating system, albeit within a Windows XP virtual machine.
It is important to mention that the VB team over at Microsoft was already making sure the IDE and VB6 runtime would work on Windows 7, as I commented before (second comment on that post) based on the Support Statement for Visual Basic 6.0 on Windows Vista, Windows Server 2008 and Windows 7:
The Visual Basic team is committed to “It Just Works” compatibility for Visual Basic 6.0 applications on Windows Vista, Windows Server 2008 and Windows 7.
The Visual Basic team’s goal is that Visual Basic 6.0 applications that run on Windows XP will also run on Windows Vista, Windows Server 2008 and Windows 7. The Visual Basic team is also committed to the Visual Basic 6.0 development environment running on Windows Vista, Windows Server 2008 and Windows 7.
The objective of XP Mode is clearly to move forward the Windows architecture to the latest technologies, free of all the legacy bits required to maintain compatibility of old applications (read the History posts at the The Old New Thing blog for examples), while at the same time it allows developers to smoothly upgrade their applications without the threat of the application not working in the new OS. It is basically a compromise of old vs. new. And it is very easy to draw parallels between XP Mode and the approach taken by Apple, first with Classic and then with Rosetta, to smooth the transition to new platforms. But as was the case in those scenarios, Classic was eventually phased out, and Rosetta will eventually be as well.
I personally think that this technology may end up being around for a while, and may even end up included in the next versions of Windows if there is enough customer demand for it. This has to be the same technology used in their Microsoft Enterprise Desktop Virtualization (MED-V) solution, targeted towards enterprise customers:
“Microsoft Enterprise Desktop Virtualization (MED-V) provides deployment and management of virtual Windows desktops to enable key enterprise scenarios. MED-V 1.0 helps enterprises upgrade to the latest version of Windows even when some applications are not yet compatible.”
Even in the scenario that XP Mode is supported for a long time, you still have to consider it as something that can be used for a smooth transition while you upgrade your applications to the .NET Framework, and not as an excuse for not upgrading. It can help you plan a gradual migration, were you first start migrating certain modules while leaving others in VB6, with tools like the Interop Forms Toolkit. And keep in mind that even though the application will run, the IDE is simply not supported anymore and neither are most controls that cause compatibility issues. And at the same time you will be missing the benefits of using the latest technologies and the increased productivity of the .NET Framework.
This week Microsoft updated its support statement for Visual Basic 6.0 to include the upcoming Windows 7. Even though the original idea was to not support VB6 in Windows 7, given the outstanding demand, the runtime WILL BE included in the OS.
To summarize, the support status of the different Visual Basic 6.0 components is:
- Visual Basic 6.0 IDE: Unsupported as of April 8, 2008.
- Visual Basic 6.0 Runtime: Supported for the lifetime of Windows Vista, Server 2008 and 7. *This is the big change in the Support Statement*.
- Visual Basic 6.0 Runtime Extended Files: The supported versions are here.
Even though the runtime components will be supported in Windows 7, it is important to consider the implications of the IDE not being supported (as I described in this post). There are also additional advantages of moving to .NET such as 64-bit support (VB6 apps are 32-bit only) and all the productivity, maintainability and deployment gains provided by the platform.
One of the key features of the Visual Basic Upgrade Companion (one that is not present in the Developer Edition, BTW) is that it’s functionality can be customized and extended. By doing this, developers working on a migration can have the VBUC do as much of the work as possible for them, minimizing the manual work and producing a higher quality product that satisfy both the developer’s and end user’s expectations. Performing repetitive changes to, for example, replace the data access components from VB6 (ADO/RDO/DAO) with native .NET data access (ADO.NET), is better done by the VBUC at migration time. This also applies to particular programming patterns used by organizations that need to be replaced by .NET-native patterns, and to coding conventions that vary between VB6 and .NET languages.
The Visual Basic Upgrade Companion includes three mechanisms to customize the generated code: Migration Profiles, Custom Maps and Additional Customizations.
Migration Profiles
A new feature that was introduced in version 2.0 of the Visual Basic Upgrade Companion, it gives end users control over which features and transformations to use for a particular migration, by using the concept of Migration Profiles. These profiles provide two types of rules that can be switched on/off. The first type, Code Conversion Rules, that deal with patterns applied to the code, such as generating structure error handling (try…catch) from On Error…Goto statements or applying commonly used naming conventions to the code. The second type is called Component Maps, and deal with translations from from one ActiveX component, such as a status bar or a grid, to a native version of the component.
Profiles are managed through the Profile Maintenance screen:
Custom Maps
The Visual Basic Upgrade Companion includes a “mapping” mechanism that allow end-users of the tool to define the transformation of one element of a library used in the VB6 code to a member of an assembly in .NET. This allows a migration team to identify and implement time-saving transformations, and, when combined with the implementation of an adapter for the .NET component, can speed up the migration process dramatically.
The Mappings are defined through a GUI editor launched from within the VBUC itself:
Once the mappings are defined, they can be switched on and off in the migration through the Migration Profile Maintenance Window:
Additional Customizations
ArtinSoft’s VBUC development team can also include additional complex rules in the VBUC, including customizations for items such as error handling patterns, architectural modifications, and others. These customizations also include mapping COM controls to in-house libraries, or force in-house naming conventions. This was a decision point for one of clients in the United Kingdom, Vertex Financial Services, as documented in the Vertex Omiga case study:
“Vertex decided to migrate the Omiga application to C# using a customized version of the Visual Basic Upgrade Companion, a tool developed by ArtinSoft based on artificial intelligence technology. ArtinSoft was highly recommended by Microsoft UK, and the customization of this migration tool enabled Vertex to automatically convert coding patterns and meet its preferred standards.”
These type of customizations require some modifications to the VBUC that can only be performed by ArtinSoft’s in-house team. It is a very valuable option that allows companies to get a an end product which furthers increases the return on investment from the migration.
Earlier this week we launched an joint initiative with Microsoft and Avanade in the UK for helping Visual Basic 6.0 developers move their applications to .NET. The initiative consists of several parts:
The initiative is UK-only at the time, but if you want to take advantage of these time-limited deals feel free to contact us. The press release for the campaign can be found here and at our website. Eric Nelson from Microsoft has been heavily involved - you can read his blog post on the initiative here.
The campaign has been well received so far. In the two days since launch, we already have several leads interested in both offerings!!
Jointly with the Visual Basic 6.0 migration campaign we are launching in the UK, today we released the Visual Basic Upgrade Companion Developer Edition. This is a scaled down version of the Visual Basic Upgrade Companion, targeted at individual developers that want to migrate their Visual Basic 6.0 applications as fast and painlessly as possible. It has a license that is valid for three months and allows you to migrate an application of up to 50,000 lines of code.
The VBUC Developer Edition does have some fewer features than the fully-fledged Visual Basic Upgrade Companion. All the features that we decided to include in the Developer Edition, however, are targeted towards automating as much of the migration process as possible. So, we left out features that have been introduced by the request of our enterprise customers over the 7+ years the tool has been on the market (yep, we were already doing VB6 migrations before the official release of .NET - and it wasn't all fun with the Betas). We made it so that getting an application up and running in C# or VB.NET is as simple as possible.
Here you can see the VBUC Developer Edition in action (video recorded by yours truly :) ):
And, as an introductory offer, The VBUC Developer Edition will only cost £199 for a limited time. So why wait?
The Visual Basic Upgrade Companion is able to generate both C# and Visual Basic .NET code from the original Visual Basic 6.0 code base. Thus, when doing a migration project with our tools, you can choose either language. This decision is a challenge itself, especially if you aren't doing any .NET development before the migration. You have to measure the skill set of your staff, and how comfortable they will feel with the transition from VB6 to either language.
Here are some points that are normally thrown around when comparing C# and VB.NET:
- Support: Both languages are well supported by Microsoft, and are first-class citizens on the .NET Framework. Neither one will go the way of the Dodo (or the way of J#, for that matter).
- Adoption: C# seems to have higher adoption than VB.NET. A completely unscientific and in no way statistically valid quick search on the books section of Amazon, however, returned 15,429 results for C#, and 2,267 results for Visual Basic .NET. Most of our customers migrate to C# instead of VB.NET as well. So there may be some truth in this.
- Perception: C# was developed from the ground up for the .NET Framework. This has affected VB.NET's mind share, as C# is viewed as the new, cool language in town. C# is also seen as an evolution of C and C++, which are considered more powerful languages. And we've all heard at least one Visual Basic 6.0 joke - which means that even though VB.NET is a completely different beast, the "VB" name may work against it.
- Familiarity: Visual Basic .NET's syntax is very similar to VB6's, so it is assumed that VB6 developers will feel right at home. This may or may not be true, since they will need to learn all the differences of the new environment, not only the syntax.
- Cost: It also looks like people with skills in C#, on average, earn more than those with skills in VB.NET. This is also something to keep in mind when deciding which language to choose.
.NET allows you to mix programming languages, even on the same Solution. So you could have some developers work in C#, while other work in VB.NET - basically let them use the language they feel more comfortable with. DON'T. This may become a maintenance nightmare in the future. You should definitely standardize on just one language, either C# or VB.NET, and stick with it. That way you'll save time and resources, and overall have a more flexible team.
Also, keep in mind that the biggest learning curve when coming from the VB6 world won't be the object orientation of VB.NET or the curly bracket syntax of C#. It will be learning the .NET Framework. That is what you should plan training for, not for a particular language. Learning the syntax for a new programming language is pretty trivial compared to the effort required to correctly use all the APIs in .NET.
All in all, you can do anything on either language. I personally like C# better, mainly because I started with C, C++ and Java before moving on to .NET development. Coding is C# is "natural" for me. But you can develop any type of application in C# or VB.NET, as there's no meaningful difference under the covers.
When planning the migration of large applications you may want to use a phased approach. This means that as you migrate the first portions of your application to .NET, you will need to keep the interaction with the Visual Basic 6.0 code. Depending on your application's architecture, you can use one of the following approaches:
- Interop Forms toolkit: Now at version 2.0, it simplifies the process of embedding .NET forms and controls inside VB6 applications. It is recommended for GUI-intensive applications
- Binary Compatible .NET DLLs: This technique allows you to expose .NET components through COM. It is recommended for multi-tier apps, especially if you want to migrate the back end before you migrate the front end. It allows VB6 and ASP applications to continue using the same components even after they are migrated to the .NET Framework.
The current version of the Visual Basic Upgrade Companion is able to add binary compatibility information to these components. The VBUC does this automatically to ActiveX DLLs, and it is as easy as activating the "COM Visible" feature in the Upgrade Profile:
Once you have the .NET code, you need to check Register for COM Interop in the Project Properties page in Visual Studio.NET, and then you are all set. Your VB6 and ASP applications will continue working with the newly migrated .NET components, transparently, while they await their turn for a migration.
You can read more about this feature on the COM class exposure page.
We recently did some quick tests on the results of some projects that we just finished migrating to compare the binary size and memory footprint of the resulting migrated .NET application and the original Visual Basic 6.0 application. Here is a brief summary of the results.
Binary Size
We have seen that binary sizes remain very similar or decrease by a small margin when compared to the original Visual Basic 6.0 binaries. There is a small amount of application re-factoring that contributes to this reduction, though, such as consolidating all shared files to a common library (instead of including the same files in several VB6 projects, which increases the code base and binary size).
You do have to take into account the space required by the .NET Framework itself, that varies from 280MB to 610MB.
Memory Footprint
Our observations on the memory footprint of migrated .NET applications, when compared to the original VB6 applications, is consistent to what we've seen with the binaries' size. .NET applications have higher initial memory consumption, since the .NET Framework sets up the stack and heap space at startup, and you have to add the memory required by the JIT compiler. Even with these constraints, a quick revision of applications that we've migrated for customers shows that the memory consumption is, on average, around 10% less than in VB6 (these are no scientific measurements, just based on monitoring memory consumption during the execution of test cases).
We have also seen that .NET normally maintains a more consistent memory usage pattern, while VB6 applications has more peaks where the memory consumption goes up, then back down. This is caused by the .NET Framework holding on to resources until the Garbage Collector runs, and the overall improvements in memory management included in the .NET Framework.
.NET applications have a memory overhead associated with the .NET Framework itself. This is more noticeable in small applications, but overall, is a tradeoff required for running on a managed environment. According to the .NET System Requirements, the Framework requires at least 96MB (256MB recommended) of RAM to run. In our experience, however, you should have at least 512MB (1GB recommended) of RAM to run migrated applications comfortably (on Windows XP).