Using .NET Languages to make your Application Scriptable


Ultimate Contributor
Nov 17, 2002
User Rank
Because of size limitations I have had to strip the embedded code samples from this article. However, you can still View the full article on my website.


Read my Plugins Tutorial.


You can go a long way to make a large application customisable. You can include a comprehensive options and preferences system or even use configuration files to allow access to advanced settings, but theres nothing like being able to write code within an application to fully control it or simply hook in to it.

I recently wrote an IRC client in .NET. People have grown accustomed to having scripting support in such things so as part of the exercise I decided to include exactly that.

How Scripting is Implemented

Scripts are implemented in a similar way to plugins. Essentially, they ARE plugins, but theyre compiled on the fly from inside the application rather than precompiled. This makes it much easier for the user since they dont have to worry about unloading existing plugins, possibly closing your application then recompiling their dll.

Plugins work by conforming to an interface defined in a shared assembly that the host application knows about. Often when the plugin is initialised a reference is also passed to it of another interface that the host application has implemented, to allow the plugin to control the behaviour and other aspects of that application.

Luckily for us, in .NET the compilers for the main languages are built right in to the framework. These are worth an article on their own really, but for the purposes of this article we will but scratch the surface. The key to us using them for this purpose is that they can accept language source as a string and spit out an assembly in memory. This assembly object acts just the same as an assembly object loaded from a compiled dll.

By the end of this article I hope to have taken you through the process of doing this, and have developed a helper class in both VB and C# that illustrates the processes involved.

The Object Model

This part is just the same as writing for plugin-based applications. The first step is to create a shared dll which is referenced by the host application and contains the interfaces needed to be known by both that and the script. My imagination being what it is, for this article well make a simple host application that has four buttons on it and calls methods in a script when each button is clicked. It will make available to the script a UI control and a method to show a message box.

The Host Application

Before we get in to how were going to edit and compile the script, lets design the simple host application. All we want is a form with a textbox and four buttons on it. We will also want two variables scoped to the whole form, one to store the current script source and one of type IScript that well use to call the compiled scripts methods. The form itself will implement IHost for simplicity. We also want another button that well use to show the script editing dialog.

Providing a Script Editor

This is probably the most tedious part to get working really well. The three most important things to implement here in a commercial application are a good code editor (I suggest using a commercial syntax highlighting control), some form of intellisense or helpers for code creation and background compilation of the script to highlight errors as they are typed, like in Visual Studio. For this article well just use a textbox for code editing with no background compilation.

The script editor form needs to be able to accept script source, which will go in to its main editing textbox. It needs to have Ok and Cancel buttons, and a listview to display compile errors should there be any. But most importantly, it needs to be able to compile the script and produce an instance of the class that implements IScript to be handed back to the main form.

Dynamic Compilation

Finally on to the meat of the article. As I said already, compiler services are built in to the .NET framework. These live in the System.CodeDom namespace. I say compiler services and not compilers because CodeDom encompasses a lot more than that. However, the bits were interested in live in the System.CodeDom.Compiler namespace.

To start off with we need an instance of a class that inherits from CodeDomProvider. This class provides methods to create instances of other helper classes specific to that language. Derivatives of CodeDomProvider are shipped with the framework for all four .NET languages, however the only two were interested in are VB and C#, the most popular. They are Microsoft.VisualBasic.VBCodeProvider and Microsoft.CSharp.CSharpCodeProvider. The design of this system is so good that after choosing which of these to use, the steps are exactly the same.

The first thing we use is the CodeDomProviders CreateCompiler method to get an instance of a class implementing ICodeCompiler. Once we have this thats the last we need from our CodeDomProvider. Our helper class will have a CompileScript function, which will accept script source, the path to an assembly to reference and a language to use. Well overload it so the user can use their own codeprovider if they want to support scripting in a language other than VB or C#.

The next step once we have our ICodeCompiler is to configure the compiler. This is done using the CompilerParameters class. We create an instance of it using the parameterless constructor and configure the following things:

We dont want an executable, so set GenerateExecutable to false.
We dont want a file on disk, so set GenerateInMemory to true.
We dont want debugging symbols in it, so set IncludeDebugInformation to false.
We add a reference to the assembly passed as a parameter.
We add a reference to System.dll and System.Windows.Forms.dll to make the TextBox usable.

As a side note, to provide information for compilers specific to the language you are using (such as specifying Option Strict for VB) you use the CompilerOptions property to add extra command-line switches.

Once we have our CompilerParameters set up we use our compilers CompileAssemblyFromSource method passing only our parameters and a string containing the script source. This method returns an instance of the CompilerResults class. This includes everything we need to know about whether the compile succeeded - if it did, the location of the assembly produced and if it didnt, what errors occured.

That is all this helper function will do. It will return the CompilerResults instance to the application for further processing.

We also need one more helper function, which we will pretty much completely take straight from the plugin services we developed in my previous tutorial. This is the function that examines a loaded assembly for a type implementing a given interface and returns an instance of that class.

Analysing the Compile Results

Back to our script editing dialog. In the handler procedure for the Ok button, we need to use the procedure weve just written to compile the source code. Well start by getting the path to the assembly the compiler needs to reference - our interfaces assembly. This is easy since its in the same directory as the running host application. Then we clear our "errors" listview and run the CompileScript function.

Next we look at the Errors collection of our results. If it is empty, the compile succeeded. In this case, we use our FindInterface method to instantiate the class from the assembly and store it, then return DialogResult.Ok to the procedure that showed the script editor. If the Errors collection is not empty, we iterate through it populating the listview with all the errors that occured during the compile.

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.

Thats it! When you open the sample solutions youll 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. Youll 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.

[Broken External Image]:

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.

Download Solutions from the full article on my website.