This project is read-only.
On-demand Variables

Flee expressions support variables whose type and value come from events. If an expression references a variable that doesn't exist in the expression's VariableCollection, Flee will raise the ResolveVariableType event. If the event is handled and a type is specified, Flee will then raise the ResolveVariableValue event every time the expression is evaluated. In that event, you have access to the variable's name and type and it is up to you to provide a compatible value.

Here's an example that ask the user to input an expression and then uses on-demand variables to ask the user for the value of each variable in their expression:

static void Main()
{
   ExpressionContext context = new ExpressionContext();
   VariableCollection variables = context.Variables;

   // Hook up the required events
   variables.ResolveVariableType += new EventHandler<ResolveVariableTypeEventArgs>(variables_ResolveVariableType);
   variables.ResolveVariableValue += new EventHandler<ResolveVariableValueEventArgs>(variables_ResolveVariableValue);

   // Get an expression from the user
   Console.Write("Enter an expression: ");
   string s = Console.ReadLine();
   
   // Compile the expression; Flee will query for the types of any variables
   IDynamicExpression e = context.CompileDynamic(s);

   // Evaluate the expression; Flee will query for the values of each variable
   object result = e.Evaluate();
   Console.WriteLine("The result is: {0}", result);
}

// Called when Flee needs to know the type of a variable
static void variables_ResolveVariableType(object sender, ResolveVariableTypeEventArgs e)
{
   // Make all variables Doubles
   e.VariableType = typeof(double);
}

// Called when Flee needs the value of a variable
static void variables_ResolveVariableValue(object sender, ResolveVariableValueEventArgs e)
{
   Console.Write("Enter value for variable '{0}' ({1}): ", e.VariableName, e.VariableType.Name);
   string value = Console.ReadLine();
   e.VariableValue = Convert.ChangeType(value, e.VariableType);
}


Note that Flee raises the resolve events once for every occurence of a variable in an expression. This means an expression like a + (a * 0.15), will raise both events twice.

Another example
This sample project shows how to use Flee and on-demand variables to compute an expression for each row of a data table where the expression can reference the columns in the current row.

Last edited Nov 9, 2008 at 11:02 PM by ECiloci, version 16

Comments

No comments yet.