Sunday, February 7, 2010

Eval3 wrapper

Title:       Eval3  wrapper
Author:      Bulat Yapparov, Chris Ellison
Member ID:   5425273
Language:    Vb.Net
Platform:    Windows
Technology:  dotNet
Level:       Intermediate
Description: Evaluator for multiple VB expressions based on Eval3 library
Section      Type the Code Project Section you Wish the Article to Appear
SubSection   Type the Code Project SubSection you Wish the Article to Appear
License:     CPOL (default - select your desired license from our list)


Eval3 library writen by Pascal Ganaye allows to parse and evaluate VB code, which is great but often it is not enough.
What I needed was a class that would interprit a string that contains multiple expressions inclosed in square brakets.
For example this string:
GIS_[Format(Now, 'yy-MM-dd')]-[Field('ID')]-[Field('Source')]
Will be evaluated to something like this:


Lets assume we have an exprsion similar to the shown example above which we need to evaluate multiple times.
I have writen a class that will parse the whole expression once and store "formulas" for future evaluations.
This sighnificantly reduces execution time while keeping it really simple

Using the code

Download Code: Eval3 Wrapper; Evalutation functions

It is very easy to use EvalFormulaCollection class once you have Eval3 added to your project.
You just need to:
  • Create new instance of EvalFormulaCollection class with expression that you need to evaluate
  • Add "environment" object that provides functions that can be used in expression
  • Call Initiate() method that will make reusable array of parsed "formulas".
  • Call Value() property to get the interpreted value of the expression which is evaluated without parsing!
Code example:
' Test evaluation of the expression with multiple VB Expressions
Sub Test()
 Dim c As New MyClass
 dim e as New evaluationFunctions
 Dim expression As String = _ 
     "GIS_[Format(Now, 'yy-MM-dd')]-[Field('ID')]-[Field('Source')]"
 Dim ev as New EvalFormulaCollection(expression)
 MsgBox ev.Value()
End Sub

Points of Interest

The best thing about this code is its size. It is quite impressive what you can do with Regex class from RegularExpressions library with one line of code:
' Find all expression in square brackets
Public Sub New(ByVal expression As String)
    _matches = Regex.Matches(_expression, "[\[][^\[\]]{1,}[\]]")
End Sub