Game Development Reference
The Microsoft object model takes automation even further and allows you to
record scripts based on actions you perform in the application, which can later be
played back to repeat. This level of extensibility is very powerful, but it's tricky to
get right. You must build your architecture from the ground up with this level of
extensibility in mind, or you will fail. If you manage to pull it off though, your
power users will kiss the ground you walk on for making their productive lives that
much more enjoyable.
Implementing a C# Command Window
Before moving on to the implementation details behind the object model and the
Model-View-Controller pattern, let's focus on code generation with CodeDom.
We will use this powerful .NET feature to compile C# code at runtime with which
we can automate our application (through the object model).
We can start by referencing the namespaces that we will be using.
using System.Text; // For StringBuilder
using System.Reflection; // For the Assembly type
using System.CodeDom.Compiler; // For CSharpCodeProvider support
using System.Collections.Specialized; // For StringCollection
using Microsoft.CSharp; // For CSharpCodeProvider support
Basically, what we are building is a class that can take a string of C# source code
and compile it to an in-memory assembly. This assembly will contain a method
that can be invoked to run whatever script we have written.
public class ScriptEngine
Regardless of the script logic, there will always be identical stub code that must be
compiled in order to generate correct source code that will support runtime
automation. Rather than having the user write the same stub code every time, we
will provide a simple method that takes in a string containing C# code and wraps
it within a default layer of stub code. The following code shows the method to gen-
erate the stub wrapper code. Take note of the namespace, class, and method names.