Hi all,
Here is a very simple class to compile a string into an assembly. This code probably won't make it into any app, but it is just to show how easy it actually is.
You can compile any class and then invoke any member.
For functions you can just get the object returned by the invoke call, and cast that to the appropriate type.
I have no idea what practical use this has, but it is kinda cool 
vb.net Code:
Imports System.CodeDom.CompilerImports System.ReflectionClass VbCompiler
Public Property Source As String
Public Property DLLS As String()
Public Sub New(ByVal Source As String, ByVal DLLS() As String)
Me.Source = Source
Me.DLLS = DLLS
End Sub
Private _errors As CompilerErrorCollection
Public ReadOnly Property Errors As CompilerErrorCollection
Get
Return _errors
End Get
End Property
Private _successful As Boolean
Public ReadOnly Property Successful As Boolean
Get
Return _successful
End Get
End Property
Public Function Compile() As Assembly
Dim Provider As New VBCodeProvider
Dim Parameters As New CompilerParameters
For Each DLL In Me.DLLS
Parameters.ReferencedAssemblies.Add(DLL)
Next
Parameters.GenerateInMemory = True
Dim results As CompilerResults = Provider.CompileAssemblyFromSource(Parameters, Me.Source)
If results.Errors.Count = 0 Then
_successful = True
Return results.CompiledAssembly
Else
_successful = False
_errors = results.Errors
Return Nothing
End If
End Function
End Class
And use it like so
vb.net Code:
Dim SourceCode As String =<Source>
Imports System.Windows.Forms
Namespace TestCode
Class Class1
Sub ShowMessage()
Messagebox.Show("Hello, This code was compiled from a string!")
End Sub
End Class
End Namespace</Source>.Value
'Very Short program
Dim Dlls() As String = {"System.dll", "System.Core.dll", "System.Data.dll", "System.Windows.Forms.dll"}'Any referenced dll's
Dim Compiler As New VbCompiler(SourceCode, Dlls)
Dim CodeAssembly As Assembly = Compiler.Compile
If Compiler.Successful Then
Dim instance As Object = CodeAssembly.CreateInstance("TestCode.Class1")
Dim CodeType As Type = instance.GetType
Dim Info As MethodInfo = CodeType.GetMethod("ShowMessage")
Info.Invoke(instance, Nothing)
Else
For Each i As CompilerError In Compiler.Errors
MsgBox(i.ErrorText)
Next
End If
With this class you could easily create a RunCode function that takes a string as parameter and run's it.