Click here to Skip to main content
15,893,401 members
Articles / Programming Languages / Visual Basic

Eval3 wrapper

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
8 Feb 2010CPOL1 min read 13.3K   5  
Evaluator for multiple VB expressions based on Eval3 library

Introduction

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 interpret a string that contains multiple expressions enclosed in square brackets.
For example, this string:

GIS_[Format(Now, 'yy-MM-dd')]-[Field('ID')]-[Field('Source')]

will be evaluated to something like this:

GIS_10-01-13-5324523-DFS235F

Background

Let's assume we have an expression 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 significantly reduces execution time while keeping it really simple.

Using the Code

Download code: Eval3 Wrapper; Evaluation 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:

VB.NET
' 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)
 ev.AddEnvironment(c)
 ev.AddEnvironment(e)
 ev.Initiate()
 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:

VB.NET
' Find all expression in square brackets
Public Sub New(ByVal expression As String)
     ...
    _matches = Regex.Matches(_expression, "[\[][^\[\]]{1,}[\]]")
End Sub

This article was originally posted at http://feeds.feedburner.com/flafi

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Database Developer
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --