Using Dynamic Evaluation and Execution

As a programmer, you have performed static evaluation and static execution countless times. For example, the following code snippet performs both static evaluation and static execution:

<% @LANGUAGE="VBSCRIPT" %>
<%
  Dim iAnswer
  iAnswer = 22 / 7   'A rough approximation of pi
%>

The first line, Dim iAnswer, is an example of static execution. When a browser visits the ASP page that the above code snippet resides in, the first line of code is executed, causing a memory location to be set aside to store the value of iAnswer. The second line, iAnswer = 22 / 7, is an example of both static evaluation and static execution. Initially, the expression 22 / 7 is evaluated, returning the result 3.14285714285714. The execution occurs when this value is stored into the variable iAnswer.

This type of code evaluation and execution is referred to as static because the statement being evaluated and the commands being executed are hardcoded into the script. The only way the expression 22 / 7 will change is if a developer edits the actual ASP file by entering a new expression.

The VBScript 5.0 scripting engine offers two functions that facilitate dynamic evaluation and execution. Let us examine each of these issues separately.

Dynamic evaluation

Imagine you wanted to present your users with a form with a single text box, into which they could enter a mathematical expression. Once the form was submitted, the result would be displayed. For example, the user might enter something like (8 * (5 / 3.5)) - 34. Example 4.7 contains the code to create this form, and Figure 4.4 displays the form when viewed through a browser.

Example 4-7. A Form to Solve a Mathematical Expression

<HTML>
<BODY>
  <FORM METHOD=POST ACTION="SolveMathProblem.asp">
     Enter a mathematical expression (like
     <CODE>5 + 4 * (9 / 4 - 10.5) + 45/2</CODE>):<BR>
     <INPUT TYPE=TEXT NAME=Expression SIZE=40>
     <P>
     <INPUT TYPE=SUBMIT VALUE="Solve this Expression!">
  </FORM>
</BODY>
</HTML>
The form in Example 4.7 when viewed through a browser

Figure 4-4. The form in Example 4.7 when viewed through a browser

When this form is submitted, SolveMathProblem.asp is called and is passed the user’s mathematical expression in the form element Expression. SolveMathProblem.asp dynamically evaluates the user’s input using the Eval function. The Eval function has the following definition:

[EvaluationResult = ] Eval(expression)

where expression is a string variable that contains a valid VBScript expression. Eval returns the result of the evaluated expression as though it had been hardcoded in the script. The code for SolveMathProblem.asp, without any error checking or validation code, is shown in Example 4.8.

Example 4-8. SolveMathProblem.asp Dynamically Evaluates the User’s Input

<% @LANGUAGE="VBSCRIPT" %>
<% Option Explicit %>
<%
    'Read in the user's expression
    Dim strExpression
    strExpression = Request("Expression")

    'Output the result
    Response.Write "The mathematical result of:<BR><CODE>"
    Response.Write strExpression & "</CODE><P>is:<BR><CODE>"
    Response.Write Eval(strExpression) & "</CODE>"
%>

Eval will generate an error if the expression parameter is not a valid VBScript expression. If the user entered a non-valid VBScript expression into the text box (such as Scott Mitchell) in the form in Example 4.7, SolveMathProblem.asp would output a syntax error message, as Figure 4.5 illustrates.

The Eval function expects a valid VBScript expression; an invalid expression results in a syntax error

Figure 4-5. The Eval function expects a valid VBScript expression; an invalid expression results in a syntax error

Warning

Allowing your users to directly enter the commands that will be used in dynamic evaluation or dynamic execution is a security risk, to say the least. If you permit your users to enter input that is dynamically executed, they can easily enter malicious code, such as a series of commands that will delete all of the web pages on your site using the FileSystemObject object model. Even allowing your users to directly enter commands that are dynamically evaluated poses a risk. For example, a user could output the contents of your application and session variables, which might contain connection strings or other sensitive information.

Dynamic execution

The Eval function only allows for expression evaluation. If you need to execute a statement—such as an assignment statement, a variable declaration, or a loop—you will need to use the Execute statement. The Execute statement expects a string parameter that contains one or more statements for execution. If there are multiple statements, they must be delimited by a legal VBScript statement delimiter, namely the carriage return or the colon.

The following code snippet dynamically executes an assignment operation, assigning the value of “Hello, World!” to strWelcomeMessage :

Dim strStatement
strStatement = "strWelcomeMessage = ""Hello, World!"""
Execute strStatement

This next code snippet demonstrates how to execute multiple statements with one call to Execute. Note that each statement is delimited by a colon in the first call to Execute, while each statement is delimited by a carriage return in the second call to Execute:

Dim strStatement

'Delimit the statements using a colon
strStatement = "Dim iAge : iAge = 4 : Response.Write iAge"
Execute strStatement

'Delimit the statements using carriage returns
strStatement = "Dim dtBirthdate" & vbCrLf & _
               "dtBirthDate = DateSerial(1978, 8, 1)" & vbCrLf & _
               "Response.Write ""I was born on "" & FormatDateTime(dtBirthDate)"
Execute strStatement

This final code snippet demonstrates how to create a variable-sized array without using Redim :

'Create an array named aPerfectSizedArray

'How many elements should the array contain?
Dim strElementsInArray
strElements = "10"

'Create the array
Dim strStatement
strStatement = "Dim aPerfectSizedArray(" & strElements & ")"

Execute strStatement

Tip

In VBScript, the equals operator has two functions—logical equivalence and assignment. When using the equals sign with the Eval statement, the equals sign serves as the logical equivalence operator. When using an equals sign within an Execute statement, the equals sign serves as the assignment operator.

Get Designing Active Server Pages now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.