Search code examples
c#vb.netembeddedinterpreter

End-user embedded programable VB inside C#


How would it be possible to build a complete C# application with the feature of creating new functionalities thru new VB files. Those files shouldn't have to be compiled but interpreted in runtime.

I think of it as an embedded VB interpreter, but don't know how it can be accomplished. You could build a robust base application and then let your technicians adapt it to the particularities of each client (databases, tables, filters, network services,...)

A client of mine has a software with that open functionality but I ignore the details.

It also be great if python could be integrated!


Solution

  • Using VBCodeProvider you can compile VB.NET code at run-time.

    The following example, compiles a piece of VB.NET code at run-time and run it:

    private void button1_Click(object sender, EventArgs e)
    {
        using (var vbc = new VBCodeProvider())
        {
            var parameters = new CompilerParameters(new[] {
            "mscorlib.dll",
            "System.Windows.Forms.dll",
            "System.dll",
            "System.Drawing.dll",
            "System.Core.dll",
            "Microsoft.VisualBasic.dll"});
            var results = vbc.CompileAssemblyFromSource(parameters,
            @"
            Imports System.Windows.Forms
            Imports System.Drawing
            Public Class Form1
                Inherits Form
                public Sub New () 
                    Dim b as Button = new Button()
                    b.Text = ""Button1""
                    AddHandler b.Click, 
                        Sub (s,e)
                            MessageBox.Show(""Hello from runtime!"")
                        End Sub       
                    Me.Controls.Add(b)
                End Sub
            End Class");
    
            //Check if compilation is successful, run the code
            if (!results.Errors.HasErrors)
            {
                var t = results.CompiledAssembly.GetType("Form1");
                Form f = (Form)Activator.CreateInstance(t);
                f.ShowDialog();
            }
            else
            {
                var errors = string.Join(Environment.NewLine,
                    results.Errors.Cast<CompilerError>()
                    .Select(x => x.ErrorText));
                MessageBox.Show(errors);
            }
        }
    }