Using .NET to make your Application Scriptable

Finishing Off

The only part left to do is to finish off the main form by making the Edit Script button work as it should. This means showing the dialog and, if the compile was successful, storing the compiled script and initialising it.

Private Sub btnEditScript_Click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles btnEditScript.Click
    Dim f As New frmScript()
    'Show script editing dialog with current script source
    f.ScriptSource = ScriptSource
    If f.ShowDialog(Me) = DialogResult.Cancel Then Return
    'Update local script source
    ScriptSource = f.ScriptSource
    'Use the compiled plugin that was produced
    Script = f.CompiledScript
End Sub

private void btnEditScript_Click(object sender, System.EventArgs e)
    frmScript f = new frmScript();
    // Show script editing dialog with current script source
    f.ScriptSource = ScriptSource;
    if (f.ShowDialog(this) == DialogResult.Cancel)
    // Update local script source
    ScriptSource = f.ScriptSource;
    // Use the compiled plugin that was produced
    Script = f.CompiledScript;

That's it! When you open the sample solutions you'll notice that I wrote a blank, template script that simply provides a blank implementation of IScript and embedded it as a text file in the host application. Code in the constructor of the main form sets the initial script source to this. You'll also notice that I used VB scripting for this example, but changing one line of code and writing a new default script is all you need to do to make it use C# code to script instead.

To try it out, run the solution. Click the Edit Script button on the main form and put whatever you like in the four methods. You can use Host.ShowMessage to cause the host application to show a messagebox and Host.TextBox to use that textbox on the main form. Press Ok, and assuming the compile succeeds you can press the four buttons to run the four corresponding procedures in the script you just compiled.

In the real world the scripting interfaces would obviously be much more complicated than this, but this should give you a pretty good idea of how to compile on the fly and hook up a compiled script to your application. I have provided both a VB and C# solution to go with this article, which are functionally identical. Open the Scripting.sln file in the Scripting directory.

You might also like...



Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Java is to JavaScript what Car is to Carpet.” - Chris Heilmann