Script Generation in C# with In Script Objects
The generation and compilation of script element in C# language that allows for the insertion of in script objects.
Introduction
In my developments in Visual Studio over the years, I have frequently asked myself why Microsoft did not add a script generator to their toolbox. For many programmers, this would have been very useful in the creation of applications that need scripting in the user interface or that have the need to generate code.
Recently, silly me, I discovered that in .NET 2005, a code generation tool was introduced, but since has been forgotten (at least I could not find any good implementation for script creation).
Following the above statements, I have created for my work a script/code generation tool that converts a script in C# form (string) into a single simple assembly and then loads that assembly to create a script block object.
Using the Code
The code is quite simplistic in that the generation tool is a static
function, to which you send your arguments, which are:
string source
- If astring source
is "" the run function of the object will returnnull
Optional:
Dictionary<string, object> InnerObjects
- A collection of inner objects to be taken into account in the source (see example below)Type BaseType
- A base class type for the source, must be derived fromCSharpGeneratedCodeBlock
type which is defined in the code generation assembly.CompilerParameters Parameters
- A collection of compiler parameters as defined inSystem.CodeDom.Compiler
Example of use:
// Inner object collection;
Dictionary<string,object> InObjs=new Dictionary<string,object>();
// Adding an inner object called lama.
InObjs["Lama"] = 2.0;
// Generating the code block with the function.
CodeGen.CSharpGeneratedCodeBlock block =
CodeGen.CSharpCodeGenerator.Compile("return 2.0*Lama;",InObjs);
// running the code block;
double value = Convert.ToDouble(block.Run());
// Write the value.
Console.Write(value);
// The generated value, is 4.0;
Should be Noted...
If the code generated is needed for network/Web applications, it is imperative that all assemblies are created on disk rather than in memory. This is the default for the code generation class and could be changed in the code parameters. Furthermore, any object that is added to the object list should be sourced in an on disk assembly.
Bugs
The code presented is quite new and not without bugs. Any bug report would be greatly appreciated.
To Conclude
In this article, I introduced a simple way to generate code/application script.
Any comments, questions, bugs can be sent to me by e-mail at Zav.Shotan@GMail.com.
History
- 23rd December, 2007: Initial post