Click here to Skip to main content
15,860,943 members
Articles / Programming Languages / Visual Basic
Article

Compiling with CodeDom

Rate me:
Please Sign up or sign in to vote.
4.48/5 (22 votes)
19 May 20042 min read 129.6K   2.3K   52   12
This article explains how to compile code written in VB.NET or C# using the CodeDom.

Introduction

With the code of this article, you will compile code without having Visual Studio .NET installed, and you will avoid using the tangled compiler command line. With this code, you can create your own compiling environment.

I try to explain in this article how to dynamically compile code in VB.NET or C# using CodeDom technology. This technology simplifies the automatic code generation and can be used like a new generation of script engine, because you can write any .NET code, compile, and execute it in a dynamic way.

Background

What is CodeDom?

CodeDom is Code Document Object Model. This provides a graphical (in the sense of graph nodes, not of a picture) representation of code in the form of a tree. This represents the hierarchy of nested code elements (namespaces contain classes, classes contain methods, methods contain variable declarations, and so on). You can use CodeDom for generating an in memory code tree, or you can use it to compile ordinary code written in a file (like we will do later). View MSDN to read all about CodeDom elements. With this code tree, you can represent any piece of code independently of a specific language.

Using the code

In this section, we will create a class named VBNetCompiler. This class contains all the needed elements to compile Visual Basic .NET code files. I want to remember you that CodeDom is language-agnostic, and for this reason, you can easily create a CSharpCompiler or any compiler supported by CodeDom technology.

Imports section

VB
Imports System.IO
Imports System.CodeDom
Imports System.CodeDom.Compiler
Imports System.Collections.Specialized

Class and private members section

  • mFilesToCompile: Collection that contains all source code files.
  • mImportedDlls: Collection with all DLLs referenced by the code files.
  • mVBCompilerResults: This is an object in the CodeDom namespace to hold the output yielded by the compiler. This is similar to compiler output written in Output Pane of Visual Studio.
  • mVBCompilerErrors: Error collection produced by the Compiler
  • mVBCompilerParameters: This object is used to set the Compiler options
VB
Public Class VBNetCompiler

   'Files to compile
   Protected mFilesToCompile As New _
     System.Collections.Specialized.StringCollection

   'Referenced assemblies
   Protected mImportedDlls As New StringCollection

   'Compiler output
   Protected mVBCompilerResults As CompilerResults
   'Compiler errors
   Protected mVBCompilerErrors As CompilerErrorCollection
   'Compiler parameters
   Protected mVBCompilerParameters As New CompilerParameters

Constructor and public properties

VB
''' Constructor
Public Sub New(ByVal ParamArray pFilesToCompile() As String)
   mFilesToCompile = New System.Collections.Specialized.StringCollection
   For Each oFile As String In pFilesToCompile
      mFilesToCompile.Add(oFile)
   Next
End Sub

''' Constructor
Public Sub New()
End Sub

''' Files to compile
Public Property FilesToCompile() As _
      System.Collections.Specialized.StringCollection
   Get
      Return mFilesToCompile
   End Get
   Set(ByVal Value As System.Collections.Specialized.StringCollection)
      mFilesToCompile = Value
   End Set
End Property

''' Compiler parameters
Public Property VBCompilerParameters() As CompilerParameters
   Get
      Return mVBCompilerParameters
   End Get
   Set(ByVal Value As CompilerParameters)
      mVBCompilerParameters = Value
   End Set
End Property

''' Compiler errors
Public ReadOnly Property VBCompilerErrors() As CompilerErrorCollection
   Get
      Return mVBCompilerErrors
   End Get
End Property

''' Compiler output
Public ReadOnly Property VBCompilerResults() As CompilerResults
   Get
      Return mVBCompilerResults
   End Get
End Property


''' Referenced assemblies
Public Property ImportedDlls() As StringCollection
   Get
      Return mImportedDlls
   End Get
   Set(ByVal Value As StringCollection)
      mImportedDlls = Value
   End Set
End Property

Compile function

This function is the core of the class. First, create a VBCodeProvider, this object provides the code generator object and the code compiler (we will use this object to compile the code). In the line oVBCodeCompiler = oVBCodeProvider.CreateCompiler, we create the code compiler. After creating the compiler, I assign the referenced assemblies needed for code compilation. Later, I add the files to compile, and call the method CompileAssemblyFromFileBatch that compiles the code file array with the parameters specified by mVBCompilerParameters object. The next lines write the compiler output to the Console.

VB
   ''' Compiles the code
   Public Function Compile() As CompilerResults
      Dim oVBCodeProvider As New VBCodeProvider
      Dim oVBCodeCompiler As ICodeCompiler
      Dim oVBCompilerResults As CompilerResults
      Dim oVBCompilerError As CompilerError

      oVBCodeCompiler = oVBCodeProvider.CreateCompiler

      With mVBCompilerParameters
         With .ReferencedAssemblies
            For Each oDll As String In mImportedDlls
               ' adds assembly reference
               .Add(oDll)
            Next
         End With
      End With

      'Compiling process
      Dim oFiles() As String
      ReDim oFiles(mFilesToCompile.Count - 1)
      mFilesToCompile.CopyTo(oFiles, 0)
      oVBCompilerResults = _
       oVBCodeCompiler.CompileAssemblyFromFileBatch(mVBCompilerParameters, _
       oFiles)


      mVBCompilerResults = oVBCompilerResults
      With oVBCompilerResults
         Console.WriteLine("---------------------------------")
         Console.WriteLine("COMPILER OUTPUT: ")
         Console.WriteLine("---------------------------------")
         For Each oOut As String In .Output
            Console.WriteLine(oOut)
         Next
      End With

      With oVBCompilerResults
         Console.WriteLine("---------------------------------")
         Console.WriteLine("COMPILER ERRORS: " & .Errors.Count)
         Console.WriteLine("---------------------------------")

         mVBCompilerErrors = .Errors
         Dim ErrorLog As String
         For Each oVBCompilerError In .Errors
            ErrorLog += oVBCompilerError.ToString & vbNewLine
            Console.WriteLine(oVBCompilerError.ToString)
         Next
         If .Errors.Count > 0 Then
          Throw New Exception("The compiler has thrown the following errors:" & _
                 vbNewLine & ErrorLog)
         End If
      End With

      Return oVBCompilerResults
   End Function

End Class

Comments

With this code, you will create a VBNet compiler, but you can create a CSharpCodeProvider instead of a VBCodeProvider and compile C# code.

This class is a simple example of CodeDom power, but this namespace is huge and has powerful and very interesting capabilities for code generation.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Argentina Argentina
Gustavo is Information Systems Enginner and
Information Systems Analyst. He born in Colonia Caroya, Cordoba, Argentine.
He worked in the Universidad Tecnologica Nacional in Cordoba, Argentine like Research Group Coordinator in the Business Intelligence area.

After that worked like a professor of Visual Basic, SQL Server 2000, .NET Plataform, Visual Basic.NET and C#

His experience in programming includes: QuickBasic, C, C++, FoxPro, Visual Basic, VB.NET, C# and ASP.NET. He has working with XML, XSD, XSLT and other related technologies.

He is now working in Pectra Technology, in the development and the software engineering area in a product named Pectra BPM Studio Framework (Business Process Management Solution) using Microsoft.NET and XML technologies.

His hobbies are play the piano and reading. He is a science lover

Comments and Discussions

 
GeneralMy vote of 5 Pin
srilekhamenon14-Jan-15 17:32
professionalsrilekhamenon14-Jan-15 17:32 
GeneralMy vote of 1 Pin
Member 458009230-Dec-12 22:18
Member 458009230-Dec-12 22:18 
QuestionGenerate the Assembly at runtime Pin
NPotti4-Mar-10 2:08
NPotti4-Mar-10 2:08 
GeneralCompact Framework Pin
rimblock6-Jan-06 8:52
rimblock6-Jan-06 8:52 
QuestionCan u give me an example? Pin
shanviz6-Dec-05 11:44
shanviz6-Dec-05 11:44 
GeneralNot impressed!!! Pin
Anonymous29-Sep-05 21:37
Anonymous29-Sep-05 21:37 
its just a wrapper class for some other .NET classes. Looks like a baby's work to me. would have been much better if u had written the refence and how to use them.
GeneralIs it possible to generate a Class Library Pin
Anonymous16-Aug-05 22:45
Anonymous16-Aug-05 22:45 
GeneralNot only compiling, but also generating code Pin
Alberto Venditti15-Jun-04 9:37
Alberto Venditti15-Jun-04 9:37 
GeneralGreat Job!!! Pin
Member 37455821-May-04 2:24
Member 37455821-May-04 2:24 
GeneralRe: Great Job!!! Pin
Gustavo Bonansea21-May-04 2:37
Gustavo Bonansea21-May-04 2:37 
GeneralBuenisimo Pin
reflex@codeproject20-May-04 14:12
reflex@codeproject20-May-04 14:12 
GeneralRe: Buenisimo Pin
Gustavo Bonansea21-May-04 2:36
Gustavo Bonansea21-May-04 2:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.