Use CodeDoM to load code from file and compile it at Runtime in VB.net

Public Sub LoadCodeFromFileAndExecute() 
 Try
        Dim objCodeCompiler As System.CodeDom.Compiler.CodeDomProvider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("VisualBasic")

        Dim objCompilerParameters As New System.CodeDom.Compiler.CompilerParameters
        objCompilerParameters.ReferencedAssemblies.Add("System.dll")
  
  ''The below one is a custom dll that I require for processing the logic (and have provided as an example, just so you can refer such custom ones as required)
        objCompilerParameters.ReferencedAssemblies.Add("D:\\DynamicCode\\bin\\CustomCommon.dll")            
  
  ''Again, the Nlog is used for logging and the configuration for Nlog is loaded from the web.config, when the application initializes itself.
        objCompilerParameters.ReferencedAssemblies.Add("D:\\DynamicCode\\bin\\Nlog.dll")
  
        objCompilerParameters.GenerateInMemory = True

        ' Get the source code and compile it from the file system (assuming that your code itself is residing in the bin folder from where the application is being executed)
        Dim strCode As String = String.Empty
        Using sw As StreamReader = New StreamReader("D:\\DynamicCode\\bin\\GetLogDetailsFromDictionary.vb")
            strCode = sw.ReadToEnd()
        End Using

  ''Try to compile the code 
        Dim objCompileResults As System.CodeDom.Compiler.CompilerResults = objCodeCompiler.CompileAssemblyFromSource(objCompilerParameters, strCode)

        ' Check for compiler errors.  In my case I am just exiting the Sub
        If objCompileResults.Errors.HasErrors Then
            Exit Sub
        End If

        ' Get a reference to the NEW assembly emitted by CodeDom as part of the compilation performed in the earlier statement
        Dim objAssembly As System.Reflection.Assembly = objCompileResults.CompiledAssembly

        ' Create an instance of the DynamicCode class referenced in the source code.
        Dim objTheClass As Object = objAssembly.CreateInstance("HelloWorld")

  ''Verify if the CreateInstance was able to generate a new instance successfully
        If objTheClass Is Nothing Then
            Exit Sub
        End If

  ''Invoke the Method 
        Dim objResult As Object = objTheClass.GetType.InvokeMember("SayHello", _
                    BindingFlags.InvokeMethod, Nothing, objTheClass, Nothing)

    Catch ex As Exception

        Throw
    End Try
End Sub

762 total views, no views today