Thursday, November 27, 2008

Program your own ToString method with VB.NET

Every built-in type in VB.NET environment has a ToString method which returns a textual representation of the value. ToString method is declared to System.Object as

Public Overridable Function ToString() As String

and very class that inherits from System.Object inherits ToString method too. Since ToString method is declared as Overridable, inherited classes typically override this base method. Besides inheriting ToString method it is also overloaded with method that accepts a format string as a parameter. More information about format strings for ToString method can be found in MSDN. Here's a link to Int64.ToString method with format string. The same MSDN page contains also examples for formatting numbers, dates and time. Examples are provided to both VB.NET and C#.

When you write your own classes in VB.NET, there's nothing to prevent that you write your own ToString method too. Here's a simple PersonName class that implements ToString method.

Option Explicit On
Option Strict On
Public Class PersonName

  Private _FirstName As String
  Private _LastName As String

  Public Sub New()
    ' Initialize class
    _FirstName = ""
    _LastName = ""

  End Sub

  Public Sub New(ByVal FirstName As String, ByVal LastName As String)
    ' Initialize class
    _FirstName = FirstName
    _LastName = LastName

  End Sub

  Public Property FirstName() As String
    '
    Get
      Return _FirstName
    End Get
    Set(ByVal value As String)
      _FirstName = value
    End Set

  End Property

  Public Property LastName() As String
    Get
      Return _LastName
    End Get
    Set(ByVal value As String)
      _LastName = value
    End Set

  End Property

  Public Overrides Function ToString() As String
    ' Return name as a string
    Dim TempStr As String

    TempStr = ""
    If _FirstName.Length > 0 Then
      TempStr = _FirstName
    End If
    If _LastName.Length > 0 Then
      If TempStr.Length > 0 Then
        ' Add space between names
        TempStr = TempStr & " " & _LastName
      Else
        TempStr = _LastName
      End If
    End If
    Return TempStr

  End Function

  Public Overloads Function ToString(ByVal Format As String) As String
    ' Return name as a string
    ' Format="f", "l", "fl", "lf", "f,l", "l,f"
    Dim TempStr As String

    TempStr = ""
    Select Case Format
      Case "f"
        TempStr = _FirstName
      Case "l"
        TempStr = _LastName
      Case "fl"
        If _FirstName.Length > 0 Then
          TempStr = _FirstName
        End If
        If _LastName.Length > 0 Then
          If TempStr.Length > 0 Then
            ' Add space between names
            TempStr = TempStr & " " & _LastName
          Else
            TempStr = _LastName
          End If
        End If
      Case "lf"
        If _LastName.Length > 0 Then
          TempStr = _LastName
        End If
        If _FirstName.Length > 0 Then
          If TempStr.Length > 0 Then
            ' Add space between names
            TempStr = TempStr & " " & _FirstName
          Else
            TempStr = _FirstName
          End If
        End If
      Case "f,l"
        If _FirstName.Length > 0 Then
          TempStr = _FirstName
        End If
        If _LastName.Length > 0 Then
          If TempStr.Length > 0 Then
            ' Add space between names
            TempStr = TempStr & ", " & _LastName
          Else
            TempStr = _LastName
          End If
        End If
      Case "l,f"
        If _LastName.Length > 0 Then
          TempStr = _LastName
        End If
        If _FirstName.Length > 0 Then
          If TempStr.Length > 0 Then
            ' Add space between names
            TempStr = TempStr & ", " & _FirstName
          Else
            TempStr = _FirstName
          End If
        End If
    End Select
    Return TempStr

  End Function

End Class

The first ToString method has to be declared as Overrides, since the class is inherited from System.Object and the method overrides the method from the base class.

The second ToString method accepts a format string argument and it has to be declared as Overloads, since it overloads our first method. Accepted format strings are "f", "l", "fl", "lf", "f,l" and "l,f" and they affect if either first or the last name is outputted first and how they are separated.

The following example shows, how to test ToString methods and how the output from the our custom ToString method is formatted.

Dim aPersonName As New PersonName("John", "Doe")
MessageBox.Show(aPersonName.ToString, _
  "Name", MessageBoxButtons.OK, MessageBoxIcon.Information)
MessageBox.Show(aPersonName.ToString("f"), _
  "Name", MessageBoxButtons.OK, MessageBoxIcon.Information)
MessageBox.Show(aPersonName.ToString("l"), _
  "Name", MessageBoxButtons.OK, MessageBoxIcon.Information)
MessageBox.Show(aPersonName.ToString("fl"), _
  "Name", MessageBoxButtons.OK, MessageBoxIcon.Information)
MessageBox.Show(aPersonName.ToString("lf"), _
  "Name", MessageBoxButtons.OK, MessageBoxIcon.Information)
MessageBox.Show(aPersonName.ToString("f,l"), _
  "Name", MessageBoxButtons.OK, MessageBoxIcon.Information)
MessageBox.Show(aPersonName.ToString("l,f"), _
  "Name", MessageBoxButtons.OK, MessageBoxIcon.Information)

And the resulting output is

John Doe
John
Doe
John Doe
Doe John
John, Doe
Doe, John

Thursday, November 13, 2008

Convert CSharp source code to VB.NET source code

Occasionally you search for code samples or code snippets for a specific problem with the search engines. Usually you do find a code snippet but it is written in a "wrong" language, most notably with C#. Then you face the problem, how to convert C# code to VB.NET code. Of course, you can do it manually if you're CSharp literate.

Fortunately there are a few options to translate C# source code to VB.NET automatically and for free. Translators can be divided in two categories, web-based translators and applications that are capable to do the conversion. The pros of the web-based translators are obvious, you don't need to install any additional applications to your computer.

There are a few things to remember when using .NET code translators. Although the original source code might be fully tested, you need to re-test the translated code. There's always some code which can't be translated, at least correctly.

Here's a few rules of thumb to get most of the code converters. Do not try to translate a whole application. The result may be hard to test and the resulted source code may be more or less spaghetti style code. Keep it simple, translate only code snippets or one class at a time.

Finally, code translators usually work in both ways i.e. they translate from CSharp to VB.NET as well as from VB.NET to CSharp.

Web-based CSharp to VB.NET converters

http://www.carlosag.net/Tools/CodeTranslator/ is an on-line translator by Carlos Mares. Supported translations are C# -> VB.NET and VB.NET -> C#. As usually, the code is pasted in the text box and then you press Go-button. The translated code is replaced in the text box. Extra option is to upload a whole file to be translated.

http://www.developerfusion.com/tools/convert/csharp-to-vb/ is an on-line translator by Developer Fusion Ltd. Supported translations are C# -> VB.NET and VB.NET -> C#. Also .NET 3.5 syntax is supported. Extra feature is automatically copy result to clipboard. Developer Fusion's translator gives accurate information if the original source has error. It also gives information about the code parts that are not supported in the target language and thus are not possible to translate.

http://converter.telerik.com/ is an on-line translator by Telerik. Supported translations are C# -> VB.NET and VB.NET -> C#. Like Developer Fusion's translator, this translator gives accurate information if the original source has error. Translator also gives information about the code parts that are not supported in the target language and thus are not possible to translate.

A good list of translators, both free and commercial, can be found on Converting code between .NET programming languages
Converters mentioned above are just samples, new converts seem to arise in the net almost daily.

CSharp to VB.NET converter applications

SharpDevelop (http://www.sharpdevelop.net/) is actually an IDE for .NET programming. In the Tools-menu you'll find "Covert code to"-option. Supported translations are C# -> VB.NET, VB.NET -> C# and a conversions to a bit exotic Boo-language. As you can expect, you'll get messages from syntax errors in the original code. Also code parts that are not supported in the target language are marked with comments. Current SharpDevelop version is 2.2, but version 3.0 is in the beta phase and it will propably support .NET 3.5 syntax.

.NET Reflector (http://www.red-gate.com/products/reflector/) is a tool to view, navigate, and search through, the class hierarchies of .NET assemblies. .NET Reflector was originally programmed by Lutz Roeder but Red Gate Software Ltd. acquired it this year. They still offer a free version of it. Since Reflector handles assemblies rather than source code, it supports quite wide range of conversions. Easiest way to convert from the assembly to source code, is to use a suitable plug-in for the Reflector. In the case of VB.NET conversion, Denis Bauer has a great plug-in for this www.denisbauer.com/NETTools/FileDisassembler.aspx. Supported conversions i.e. source languages generated with this plug-in are C#, Visual Basic and Delphi. Latest version is 5.0.42.0 and it was published in 2007 so there's no .NET 3.5 support.

Which CSharp to VB.NET source code converter to choose from?

My personal favorite is Developer Fusion's translator since I convert often and small C# snippets to VB.NET. I've always got the job done with it and it's fast to use. However, take a look at the other converters too. You may find a more suitable for your needs.

Thursday, November 6, 2008

A quick tip: Check with VB.NET if operating system is Windows Vista

One day I fixed some old VB.NET application that works fine in Windows XP and Windows 2000. The problem was, it didn't work as expected with Windows Vista.

I located the spot which handled Windows registry in a way that did not work in Vista and I was quickly able to write a Vista-compatible version. Since it was not possible to have two versions of the application and I did not have time to re-write that part of the code to be compatible with all Windows versions, I decided to include both code snippets in the same version and just check operating system.

Checking operating system version with VB.NET is an easy job and I wrote a little wrapper for my Windows Vista check:

''' <summary>
''' Returns true if the OS version is any Vista version
''' </summary>
''' <returns>True if Vista OS</returns>
''' <remarks></remarks>
Public Function IsVista() As Boolean
  '
  If Environment.OSVersion.Version.Major = 6 Then
    Return True
  Else
    Return False
  End If

End Function

In the application I use it in the following way:

If IsVista() Then
  ' Vista specific code
Else
  ' Code for older Windows versions
End If

That saved me a lot of time and testing.