Generate and Execute Dynamic Script With .NET : Page 4
Use the System.Reflection classes in the .NET Framework to write, execute, and interact with code you write dynamically at run-time from your applications.
by Randy Holloway
Oct 21, 2002
Page 4 of 4
Now that you've seen a bit of Jscript.NET, here's an example application that performs a basic math calculation known as a factorial. The factorial of a number n is defined as n!, where n is an integer greater than 1, or more completely, n * (n-1)!. So for the number 3, 3! is equal to 3 * 2!, which is equal to 3 * 2 * 1, or 6. The point of this example is to demonstrate that you can develop applications that build unique scripts based on user input or other variable factors, and then compile and execute the code dynamically. For factorials, this capability is important because a standard recursive algorithm to perform the calculation degrades substantially as the number n becomes large; this example demonstrates a practical way to improve the performance of the factorial calculation for large number.
To begin the example, create a new Windows Forms application in C#. Add two text box controls (txtNumber and txtResult) and a command button named btnCompute to the form. The txtNumber TextBox will hold the factorial calculation and the txtResult TextBox will display the result. The btnCompute button will initiate the process to create the JScript.NET class code, compile it, and perform the factorial computation. Your form should look similar to Figure 1.
Randy Holloway is the founder of Winformation Systems, a technology consulting and training initiative specializing in the development of enterprise systems in the Windows environment and Web services technologies. He has also worked as an information technology director specializing in digital imaging and photo production processes. Randy speaks on technology-related topics and writes for publications including XML & Web Services Magazine and Visual Studio Magazine. Contact Randy at