Click here to Skip to main content
15,893,722 members
Articles / Programming Languages / Visual Basic

C# VB CodeConverter Using NRefactory

Rate me:
Please Sign up or sign in to vote.
3.49/5 (44 votes)
6 Apr 2012CPOL12 min read 343K   7K   114  
C Sharp to Visual Basic Code Converters Using free NRefactory and SharpDevelop
This is an old version of the currently published article.

This article appears in the Third Party Products and Tools section. Articles in this section are for the members only and must not be used to promote or advertise products in any way, shape or form. Please report any spam or advertising.

Introduction

This article is about SharpDevelop IDE and NRefactory as a code converter.

Background

Lots of C# <> VB code converter are available all most all of them are using NRefactory library form SharpDevelop IDE to make the conversion and them make some useful post conversion fixing.

The power of NRefactory is parsing the code before the conversion; even if a keyword could take more than one meaning it could be converted correctly because of understanding the code line before the conversion 

Introduction 

SharpDevelop 

It's an Open Source Development Environment for .NET. It could be used to make many useful code conversion. Also the SharpDevelop IDE is the mother of NRefactory library but the conversion that done using SharpDevelop IDE is much beater. it also provide a wide range of code conversion C#, VB.NET, Boo, Python, Ruby 

About NRefactory: 

ICSharpCode.NRefactory is freely available as a part of SharpDevelop IDE. It is parser library for C# and VB. It consists of a single Abstract Syntax Tree (AST) that can represent all constructs that are available in C# or VB (unlike System.CodeDom, which only represents constructs common to C# and VB). By using the C# parser and a VB output visitor (or vice versa), you can build a code converter. For more info about NRefactory please see: sharpdevelop.net and NRefactory wiki

About AST:

The following example show a simple parsing proses.

Image 1 

Other code converter and comparing to this application:

ApplicationConversion
Technique
What to
convert
ConversionNotes
SharpDevelop IDE Developer IDE freewareCode & file C#, VB.Net,
boo, Python, Ruby
The Best
Econ NetVert Use NRefactory Code & file C# <> VB.Net  
On Line ConverterWeb page
Online service
Code onlyC# <> VB.Net 
Instant VBShare ware
Internal Converter
Code, file
& folder
Special version for
each conversion
convert between:
C#, VB.Net, C++,
Java
 
VB.Net to C# ConverterUse NRefactoryCode & fileVB.Net > C# 
Convert .NETUse NRefactoryCode onlyC# <> VB.Net 
C# to VB.NET Project ConverterUse NRefactoryProjectsC# > VB.Net 

If you know other converter please list in the comment at the bottom of the article

Why it is Useful?

  1. Automate code converting from C# to VB.
  2. Could be use for downloaded project form code project.

Links for keyword conversions between C# and VB:

  1. Language Equivalents
  2. Comparison of C# and VB

Using SharpDevelop as a code converter:

  1. Run SharpDevelop IDE
  2. From file menu select open - project/solution and open the project to be converted
  3. From View menu select projects
  4. In the project window select the project to be converted
  5. from project menu choose convert and then choose the target language
  6. This will convert the whole project
  7. The conversion could be done by right clicking the project icon in the project window then choose convert

Image 2

Points of Interest

How to covert C# code:

The code is converted using ICSharpCode.NRefactory.ParserFactory class:

In VB the code is:

VB
Imports ICSharpCode.NRefactory
Imports ICSharpCode.NRefactory.PrettyPrinter
Imports System.IO

Public Class CS2VB

    Public Overrides Function ConvertCode(ByVal sourceCode As String) As String        
            'var names and format is as in http://wiki.sharpdevelop.net/NRefactory.ashx

            'ICSharpCode.NRefactory is a parser library for C# and VB.
            'It consists of a single Abstract Syntax Tree (AST) 
            'that can represent all constructs that are available in C# or VB 
            '(unlike System.CodeDom, which only represents constructs common to C# and VB).
            'Please try samples\NRefactoryDemo in the SharpDevelop source code to take a look at the AST
            'To parse source code, use: 
            Dim specials As IList(Of ISpecial)
            Dim result As Ast.CompilationUnit
            Dim Parse_errors = ""
            Using parser As IParser = ParserFactory.CreateParser(SupportedLanguage.CSharp, _
                                                                 New StringReader(sourceCode))
                parser.Parse()
                'this allows retrieving comments, preprocessor directives, etc. 
                '(stuff that isn't part of the syntax)
                specials = parser.Lexer.SpecialTracker.RetrieveSpecials()
                'this retrieves the root node of the result AS
                result = parser.CompilationUnit
                If parser.Errors.Count > 0 Then
                    Parse_errors = parser.Errors.ErrorOutput
                End If
            End Using

            'Now you can analyze and/or transform the AST.
            'Should you want to re-create source code from the (modified) AST, use an output visitor: 
            're-insert the comments we saved from the parser into the output
            Dim outputVisitor As New PrettyPrinter.VBNetOutputVisitor
            Dim astViewUnit = result
            Using SpecialNodesInserter.Install(specials, outputVisitor)
                astViewUnit.AcceptVisitor(outputVisitor, Nothing)
            End Using
            Dim outputCode = outputVisitor.Text
            'By using the C# parser and a VB output visitor (or vice versa), 
            'you can build a code converter. Of course, 
            'the real Code Converter in SharpDevelop also transforms the AST to fix cases 
            'where C# and VB semantics differ.

            Return outputCode   

    End Function
End Class

In C# the code is:

C#
using ICSharpCode.NRefactory;
using ICSharpCode.NRefactory.PrettyPrinter;
using System.IO;

public class CS2VB
{

    public override string ConvertCode(string sourceCode)
    {
        //var names and format is as in http://wiki.sharpdevelop.net/NRefactory.ashx

        //ICSharpCode.NRefactory is a parser library for C# and VB.
        //It consists of a single Abstract Syntax Tree (AST) 
        //that can represent all constructs that are available in C# or VB 
        //(unlike System.CodeDom, which only represents constructs common to C# 
        //and VB).
        //Please try samples\NRefactoryDemo in the SharpDevelop source code 
        //to take a look at the AST
        //To parse source code, use: 
        IList specials;
        Ast.CompilationUnit result;
        object Parse_errors = "";
        using (IParser parser = ParserFactory.CreateParser(SupportedLanguage.CSharp, new 
                StringReader(sourceCode))) {
            parser.Parse();
            // this allows retrieving comments, preprocessor directives, etc. 
            //(stuff that isn't part of the syntax)
            specials = parser.Lexer.SpecialTracker.RetrieveSpecials();
            // this retrieves the root node of the result AST
            result = parser.CompilationUnit;
            if (parser.Errors.Count > 0) {
                MessageBox.Show(parser.Errors.ErrorOutput, "Parse errors");
            }
        }
        //Now you can analyze and/or transform the AST.
        //Should you want to re-create source code from the (modified) AST, 
        //use an output visitor: 
        //re-insert the comments we saved from the parser into the output
        PrettyPrinter.VBNetOutputVisitor outputVisitor = new 
                PrettyPrinter.VBNetOutputVisitor();
        object astViewUnit = result;
        using (SpecialNodesInserter.Install(specials, outputVisitor)) {
            astViewUnit.AcceptVisitor(outputVisitor, null);
        }
        object outputCode = outputVisitor.Text;
        //By using the C# parser and a VB output visitor (or vice versa), 
        //you can build a code converter. Of course, 
        //the real Code Converter in SharpDevelop also transforms the AST 
        //to fix cases 
        //where C# and VB semantics differ.

        return outputCode;

    }
}

Demo conversion:

Partial code convert is not supported code should be in class and in method.

Demo1:

C#
class Class1{void sub1(){
    //your code start
    int x =0;
    //your code end
}}

The result in VB

VB
Class Class1
    Sub sub1()
        'your code start
        Dim x As Integer = 0
        'your code end
    End Sub
End Class

Demo2:

C#
namespace WindowsFormsApplication1
{
    partial class Form1
    {
        private System.ComponentModel.IContainer components = null;
		private System.Windows.Forms.TextBox textbox1;
        private System.Windows.Forms.TextBox textbox2;

        
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void InitializeComponent()
        {
            this.textbox1 = new System.Windows.Forms.TextBox();
            this.textbox2 = new System.Windows.Forms.TextBox();
            this.SuspendLayout();
            // 
            // textbox1
            // 
            this.textbox1.Location = new System.Drawing.Point(30, 30);
            this.textbox1.Name = "TEXTBOX1";
            this.textbox1.Size = new System.Drawing.Size(80, 20);
            this.textbox1.TabIndex = 0;
            // 
            // textbox2
            // 
            this.textbox2.Location = new System.Drawing.Point(30, 60);
            this.textbox2.Name = "textbox";
            this.textbox2.Size = new System.Drawing.Size(80, 20);
            this.textbox2.TabIndex = 1;
            this.textbox2.TextChanged += new System.EventHandler(this.textbox_TextChanged);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 262);
            this.Controls.Add(this.textbox2);
            this.Controls.Add(this.textbox1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);
            this.PerformLayout();

        }
        
        public Form1()
        {
            InitializeComponent();
        }

        private void textbox_TextChanged(object sender, EventArgs e)
        {
            string x = "";
            string X = "";
        }
    }
}

The result in VB

VB
Namespace WindowsFormsApplication1
	Partial Class Form1
		Private components As System.ComponentModel.IContainer = Nothing
		Private textbox1 As System.Windows.Forms.TextBox
		Private textbox2 As System.Windows.Forms.TextBox


		Protected Overrides Sub Dispose(disposing As Boolean)
			If disposing AndAlso (components IsNot Nothing) Then
				components.Dispose()
			End If
			MyBase.Dispose(disposing)
		End Sub

		Private Sub InitializeComponent()
			Me.textbox1 = New System.Windows.Forms.TextBox()
			Me.textbox2 = New System.Windows.Forms.TextBox()
			Me.SuspendLayout()
			' 
			' textbox1
			' 
			Me.textbox1.Location = New System.Drawing.Point(30, 30)
			Me.textbox1.Name = "TEXTBOX1"
			Me.textbox1.Size = New System.Drawing.Size(80, 20)
			Me.textbox1.TabIndex = 0
			' 
			' textbox2
			' 
			Me.textbox2.Location = New System.Drawing.Point(30, 60)
			Me.textbox2.Name = "textbox"
			Me.textbox2.Size = New System.Drawing.Size(80, 20)
			Me.textbox2.TabIndex = 1
			AddHandler Me.textbox2.TextChanged, New System.EventHandler(AddressOf Me.textbox_TextChanged)
			' 
			' Form1
			' 
			Me.AutoScaleDimensions = New System.Drawing.SizeF(6F, 13F)
			Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
			Me.ClientSize = New System.Drawing.Size(284, 262)
			Me.Controls.Add(Me.textbox2)
			Me.Controls.Add(Me.textbox1)
			Me.Name = "Form1"
			Me.Text = "Form1"
			Me.ResumeLayout(False)
			Me.PerformLayout()

		End Sub

		Public Sub New()
			InitializeComponent()
		End Sub

		Private Sub textbox_TextChanged(sender As Object, e As EventArgs)
			Dim x__1 As String = ""
			Dim X__2 As String = ""
		End Sub
	End Class
End Namespace

Case sensitive C# to VB:

The converter will automatically rename object if needed.

Event Handler C# to VB:

The event C# handler will be converted as follows:

C#:

C#
this.textbox2.TextChanged += new System.EventHandler(this.textbox_TextChanged);

VB:

VB
AddHandler Me.textbox2.TextChanged, New System.EventHandler(AddressOf Me.textbox_TextChanged)

Code Converters for other languages:

VB6 to .NET

ASP to .NET

Java to .NET

PHP to .NET

C++ to .NET

ColdFusion to .NET

History

  • Initial version.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Lebanon Lebanon
ASP.Net Hosting on Linux server
---------------------------
There is a developer behind every piece of code!
DNA is too complex what about it!
No junk DNA; There is a functional role for noncoding DNA

Comments and Discussions

Discussions on this specific version of this article. Add your comments on how to improve this article here. These comments will not be visible on the final published version of this article.