Click here to Skip to main content
15,896,154 members
Articles / Programming Languages / Visual Basic

Compile and Run VB.NET Code using the CodeDom

Rate me:
Please Sign up or sign in to vote.
4.81/5 (42 votes)
27 Jan 2006CPOL8 min read 206.9K   7.8K   52  
Demonstrates "run-time" compilation and execution of VB.NET code, using the CodeDom
Imports System.Text



Public Class frmMain


    Private Sub btnGo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGo.Click

        Dim oRetVal As Object = CompileAndRunCode(Me.RichTextBox1.Text)

        MsgBox(oRetVal)

    End Sub


    Private Function GenerateCannedRoutine() As StringBuilder
        Dim oRetSB As New StringBuilder

        ' Grab a variable from somewhere....
        Dim sText As String = "July 30, 2006"

        oRetSB.Append("If Date.Parse(""" & sText & """) < System.DateTime.Now() Then " & vbCrLf)
        oRetSB.Append(" Return ""OLD"" " & vbCrLf)
        oRetSB.Append("Else " & vbCrLf)
        oRetSB.Append(" Return ""NEW"" " & vbCrLf)
        oRetSB.Append("End If " & vbCrLf)

        Return oRetSB
    End Function

    Public Function CompileAndRunCode(ByVal VBCodeToExecute As String) As Object

        Dim sReturn_DataType As String
        Dim sReturn_Value As String = ""
        Try

            ' Instance our CodeDom wrapper
            Dim ep As New cVBEvalProvider

            ' Compile and run
            Dim objResult As Object = ep.Eval(VBCodeToExecute)
            If ep.CompilerErrors.Count <> 0 Then
                Diagnostics.Debug.WriteLine("CompileAndRunCode: Compile Error Count = " & ep.CompilerErrors.Count)
                Diagnostics.Debug.WriteLine(ep.CompilerErrors.Item(0))
                Return "ERROR" ' Forget it
            End If
            Dim t As Type = objResult.GetType()
            If t.ToString() = "System.String" Then
                sReturn_DataType = t.ToString
                sReturn_Value = Convert.ToString(objResult)
            Else
                ' Some other type of data - not really handled at 
                ' this point. rwd
                'ToDo: Add handlers for other data return types, if needed

                ' Here is an example to handle a dataset...
                'Dim ds As DataSet = DirectCast(objResult, DataSet)
                'DataGrid1.Visible = True
                'TextBox2.Visible = False
                'DataGrid1.DataSource = ds.Tables(0)
            End If

        Catch ex As Exception
            Dim sErrMsg As String
            sErrMsg = String.Format("{0}", ex.Message)
            ' Do Nothing - This is just a negative case
            ' This outcome is expected in late interpreting
            ' I suppose what I am saying is: Don't stop my program because the script writer can't write
            ' script very well.  To be fair, we could log this somewhere and notify somebody.
        End Try

        Return sReturn_Value

    End Function

    Public Sub New()

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        ' Build our code fragment 
        Dim sCode As System.Text.StringBuilder
        sCode = GenerateCannedRoutine()
        Me.RichTextBox1.Text = sCode.ToString

    End Sub
End Class

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

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


Written By
Software Developer (Senior) Texas Woman's University
United States United States
I wrote my first program when I was a child - Basic on the TRS-80 used line numbers back then. I enjoy the problem solving and creative process that writing software invokes.

Comments and Discussions