Compile and execute code at RunTime
Last week i needed to compile and run scripts at runtime. The idea was to add code snippets into a DB and load and execute them at runtime. My first idea was to write a scripting language but it was an hard work and i had no time for this.
Searching around i found a very interesting thing about the Framework. It’s possible to load, compile and run .Net code from script file or simple string. Everything happens in memory so you don’t need to generate an output file
Here is the solution:
Needed:
Imports System
Imports System.Reflection
Imports System.Reflection.Emit
Assume we have a TextBox named TextBox1 where we’ll write the source code we want to compile and run on the fly.
Try If TextBox1.Text.Trim <> "" Then Dim VBP As New VBCodeProvider Dim CVB As System.CodeDom.Compiler.ICodeCompiler CVB = VBP.CreateCompiler Dim PM As New System.CodeDom.Compiler.CompilerParameters PM.GenerateInMemory = True ' PM.GenerateExecutable = True PM.OutputAssembly = "Generated.dll" PM.MainClass = "ClassMain" PM.IncludeDebugInformation = True Dim ASM As System.Reflection.Assembly For Each ASM In AppDomain.CurrentDomain.GetAssemblies() PM.ReferencedAssemblies.Add(ASM.Location) Next 'Get compilation results Dim Results As System.CodeDom.Compiler.CompilerResults Results = CVB.CompileAssemblyFromSource(PM, TextBox1.Text) 'Show possible compilation errors Dim Err As System.CodeDom.Compiler.CompilerError For Each err In Results.Errors ListBox1.Items.Add("Error N. " & err.ErrorNumber &_ " Message: " & err.ErrorText & " Line " & err.Line) Next 'Use the compiled assembly Dim RunObj As New Object Dim vArgs() As Object RunObj = Results.CompiledAssembly.CreateInstance( "Generated.ClassMain", False, Reflection.BindingFlags.CreateInstance, Nothing, vArgs, Nothing, Nothing) If Not RunObj Is Nothing Then RunObj.Esegui() Else MsgBox.Show("Compile Error") End If Else MsgBox.Show("Write VB.Net code to compile") End If Catch err As Exception MsgBox.Show(err.Message & " " & err.StackTrace) End Try
Download this code: RuntimeCode.vb.txt
Here is a sample vb file that you can load and compile at runtime
Imports System.Windows.Forms Imports Microsoft.VisualBasic namespace Generated public class ClassMain public sub Esegui() messagebox.show("Ciao come va?") end sub end class end namespace
Download this code: RuntimeCodeTest.vb.txt
I hope it could be useful for your tasks ![]()
TAGS: Asp.net, dotnet, code snippet, seo, search engine optimization, visual studio.net, sample code, c#, vb.net
























M.Sathiskumar said
am September 17 2007 @ 6:59 am
Hi..
This Code is very helpfull fo me…
Thanks for your shareing programms