none
How do I evaluate a string to execute code? RRS feed

  • Question

  • Suppose I want to execute the following code

    myform  = new formDialog

    The catch is, that the code is in a string, and I want to evaluate it and execute it at runtime.

    Can this be done in VB.net?

    (The general problem that I'm trying to solve is that I have a variable declared as type FORM, I set it at one point to perhaps "FormDialog", then I close it, and at some point I want to reopen it.   I can't reopen it, because it has been disposed.   If I set it to type NEW FormDialog, then it would work, but often I don't know if the type is FormDialog, or some other form, but I do have a string that is the name of the original form ("FormDialog", for instance).   I can't do this: myForm = new "FormDialog"

    Thanks.

    Monday, July 16, 2018 8:31 AM

Answers

  • Hi 

    I hope the following two methods can help you.

    1.(Reflection):

    Dim str As String
    str = "myTest.FormDialog"  
    Dim tempAssembly As System.Reflection.Assembly = System.Reflection.Assembly.GetExecutingAssembly()
    Dim frm2 As Form = CType(tempAssembly.CreateInstance(str), Form)
    frm2.Show()

    2.(Type.GetType() ):

    Dim frmName, fullName As String
    frmName = "FormDialog"
    fullName = Application.ProductName & "." & frmName
    Dim frm2 As Form
    frm2 = Activator.CreateInstance(Type.GetType(fullName, True, True))
    frm2 .Visible = True

    Best Regards,

    Alex


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    • Edited by Alex Li-MSFT Monday, July 16, 2018 9:15 AM
    • Marked as answer by Gidmaestro Monday, July 16, 2018 6:09 PM
    Monday, July 16, 2018 9:04 AM
  • The catch is, that the code is in a string, and I want to evaluate it and execute it at runtime.

    Can this be done in VB.net?


    The only way is with a feature called CodeDom, but this namespace is kind of really if you want to create your own IDE(similar to Visual Studio for example).

    Here is a link to a guide:

    Dynamic Source Code Generation and Compilation


    Hire Me For This Job!
    Don't forget to vote for Helpful Posts and Mark Answers!
    *This post does not reflect the opinion of Microsoft, or its employees.




    Monday, July 16, 2018 9:27 AM
    Moderator
  • Here's a simple little class I created a long time ago for quick compilation of snippets.  Just keep in mind that there are some performance considerations (compile time, excessive assembly loading) associated with using this kind of code.

    Public NotInheritable Class VBSnippetCompiler
        Public Shared Function Compile(code As String) As System.Reflection.Assembly
            Return Compile(code, Nothing)
        End Function
    
        Public Shared Function Compile(code As String, ParamArray references() As String) As System.Reflection.Assembly
            Dim unit As New System.CodeDom.CodeSnippetCompileUnit
            If references IsNot Nothing AndAlso references.Length > 0 Then
                unit.ReferencedAssemblies.AddRange(references)
            End If
            unit.Value = code
    
            Dim provider As New Microsoft.VisualBasic.VBCodeProvider
            Dim params As New System.CodeDom.Compiler.CompilerParameters
            params.GenerateInMemory = True
    
            Dim result As System.CodeDom.Compiler.CompilerResults = provider.CompileAssemblyFromDom(params, unit)
            If result.Errors.Count > 0 Then
                Dim innerExs As New List(Of Exception)
                For Each ce As System.CodeDom.Compiler.CompilerError In result.Errors
                    innerExs.Add(New Exception(String.Format("Line: {0}, Error: {1}", ce.Line, ce.ErrorText)))
                Next
                Throw New AggregateException("One or more compile errors occured.  See inner exception for details.", innerExs)
            End If
            Return result.CompiledAssembly
        End Function
    
        Public Shared Function ExecuteMethod(Of T)(methodCode As String, ParamArray references() As String) As T
            Dim builder As New System.Text.StringBuilder
            builder.AppendLine("Public Class GeneratedObject")
            builder.AppendLine("Public Function GeneratedMethod() As " & GetType(T).FullName)
            builder.AppendLine(methodCode)
            builder.AppendLine("End Function")
            builder.AppendLine("End Class")
            Dim asm As System.Reflection.Assembly = Compile(builder.ToString, references)
            Dim o As Object = asm.CreateInstance("GeneratedObject")
            Return CType(o.GetType.GetMethod("GeneratedMethod").Invoke(o, Nothing), T)
        End Function
    
    End Class
    


    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"

    • Marked as answer by Gidmaestro Monday, July 16, 2018 6:10 PM
    Monday, July 16, 2018 2:02 PM
    Moderator

All replies

  • Hi 

    I hope the following two methods can help you.

    1.(Reflection):

    Dim str As String
    str = "myTest.FormDialog"  
    Dim tempAssembly As System.Reflection.Assembly = System.Reflection.Assembly.GetExecutingAssembly()
    Dim frm2 As Form = CType(tempAssembly.CreateInstance(str), Form)
    frm2.Show()

    2.(Type.GetType() ):

    Dim frmName, fullName As String
    frmName = "FormDialog"
    fullName = Application.ProductName & "." & frmName
    Dim frm2 As Form
    frm2 = Activator.CreateInstance(Type.GetType(fullName, True, True))
    frm2 .Visible = True

    Best Regards,

    Alex


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    • Edited by Alex Li-MSFT Monday, July 16, 2018 9:15 AM
    • Marked as answer by Gidmaestro Monday, July 16, 2018 6:09 PM
    Monday, July 16, 2018 9:04 AM
  • The catch is, that the code is in a string, and I want to evaluate it and execute it at runtime.

    Can this be done in VB.net?


    The only way is with a feature called CodeDom, but this namespace is kind of really if you want to create your own IDE(similar to Visual Studio for example).

    Here is a link to a guide:

    Dynamic Source Code Generation and Compilation


    Hire Me For This Job!
    Don't forget to vote for Helpful Posts and Mark Answers!
    *This post does not reflect the opinion of Microsoft, or its employees.




    Monday, July 16, 2018 9:27 AM
    Moderator
  • Here's a simple little class I created a long time ago for quick compilation of snippets.  Just keep in mind that there are some performance considerations (compile time, excessive assembly loading) associated with using this kind of code.

    Public NotInheritable Class VBSnippetCompiler
        Public Shared Function Compile(code As String) As System.Reflection.Assembly
            Return Compile(code, Nothing)
        End Function
    
        Public Shared Function Compile(code As String, ParamArray references() As String) As System.Reflection.Assembly
            Dim unit As New System.CodeDom.CodeSnippetCompileUnit
            If references IsNot Nothing AndAlso references.Length > 0 Then
                unit.ReferencedAssemblies.AddRange(references)
            End If
            unit.Value = code
    
            Dim provider As New Microsoft.VisualBasic.VBCodeProvider
            Dim params As New System.CodeDom.Compiler.CompilerParameters
            params.GenerateInMemory = True
    
            Dim result As System.CodeDom.Compiler.CompilerResults = provider.CompileAssemblyFromDom(params, unit)
            If result.Errors.Count > 0 Then
                Dim innerExs As New List(Of Exception)
                For Each ce As System.CodeDom.Compiler.CompilerError In result.Errors
                    innerExs.Add(New Exception(String.Format("Line: {0}, Error: {1}", ce.Line, ce.ErrorText)))
                Next
                Throw New AggregateException("One or more compile errors occured.  See inner exception for details.", innerExs)
            End If
            Return result.CompiledAssembly
        End Function
    
        Public Shared Function ExecuteMethod(Of T)(methodCode As String, ParamArray references() As String) As T
            Dim builder As New System.Text.StringBuilder
            builder.AppendLine("Public Class GeneratedObject")
            builder.AppendLine("Public Function GeneratedMethod() As " & GetType(T).FullName)
            builder.AppendLine(methodCode)
            builder.AppendLine("End Function")
            builder.AppendLine("End Class")
            Dim asm As System.Reflection.Assembly = Compile(builder.ToString, references)
            Dim o As Object = asm.CreateInstance("GeneratedObject")
            Return CType(o.GetType.GetMethod("GeneratedMethod").Invoke(o, Nothing), T)
        End Function
    
    End Class
    


    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"

    • Marked as answer by Gidmaestro Monday, July 16, 2018 6:10 PM
    Monday, July 16, 2018 2:02 PM
    Moderator