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 a string source
is "" the run function of the object will return null
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 from CSharpGeneratedCodeBlock
type which is defined in the code generation assembly.CompilerParameters Parameters
- A collection of compiler parameters as defined in System.CodeDom.Compiler
Example of use:
Dictionary<string,object> InObjs=new Dictionary<string,object>();
InObjs["Lama"] = 2.0;
CodeGen.CSharpGeneratedCodeBlock block =
CodeGen.CSharpCodeGenerator.Compile("return 2.0*Lama;",InObjs);
double value = Convert.ToDouble(block.Run());
Console.Write(value);
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
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.