Results 1 to 7 of 7

Thread: VB.NET Expression Evaluator using CodeDom.

  1. #1

    Thread Starter
    Frenzied Member conipto's Avatar
    Join Date
    Jun 2005
    Location
    Chicago
    Posts
    1,175

    VB.NET Expression Evaluator using CodeDom.

    The below code is a port of this C# Codebank example to VB.NET, modified to compile VB.NET code instead of C#. This function returns a Double value after evaluating a valid VB Expression which would evaluate to a double. Possible applications include calculators, or anything which would need to perform complex math operations on the fly.

    As with the C# Example, you will need to import a few namespaces or qualify some of the variable names in the example for this to work correctly.

    VB Code:
    1. Imports System.CodeDom.Compiler
    2. Imports Microsoft.VisualBasic 'More than just VB6 Runtime functions in here!
    3. Imports System.Reflection

    And here is the function, converted to VB.NET
    VB Code:
    1. ''' <summary>
    2.     ''' A simple function using CodeDom to process an expression.
    3.     ''' </summary>
    4.     ''' <param name="command">A string expression to evaluate</param>
    5.     ''' <returns>A double with the result of the evaluated command parameter</returns>
    6.     ''' <remarks>Vulnerable to injection attacks.</remarks>
    7.     Private Function ProcessCommand(ByVal command As String) As Double
    8.         Dim MyProvider As New VBCodeProvider 'Create a new VB Code Compiler
    9.         Dim cp As New CompilerParameters     'Create a new Compiler parameter object.
    10.         cp.GenerateExecutable = False        'Don't create an object on disk
    11.         cp.GenerateInMemory = True           'But do create one in memory.
    12.         'If cp.OutputAssembly is used with a VBCodeProvider, it seems to want to read before it is executed.  
    13.         'See C# CodeBank example for explanation of why it was used.
    14.  
    15.         'the below is an empty VB.NET Project with a function that simply returns the value of our command parameter.
    16.         Dim TempModuleSource As String = "Imports System" & Environment.NewLine & _
    17.                                          "Namespace ns " & Environment.NewLine & _
    18.                                          "Public Class class1" & Environment.NewLine & _
    19.                                          "Public Shared Function Evaluate()" & Environment.NewLine & _
    20.                                          "Return " & command & Environment.NewLine & _
    21.                                          "End Function" & Environment.NewLine & _
    22.                                          "End Class" & Environment.NewLine & _
    23.                                          "End Namespace"
    24.         'Create a compiler output results object and compile the source code.
    25.         Dim cr As CompilerResults = MyProvider.CompileAssemblyFromSource(cp, TempModuleSource)
    26.         If cr.Errors.Count > 0 Then
    27.             'If the expression passed is invalid or "", the compiler will generate errors.
    28.             Throw New ArgumentOutOfRangeException("Invalid Expression - please use something VB could evaluate")
    29.         Else
    30.             'Find our Evaluate method.
    31.             Dim methInfo As MethodInfo = cr.CompiledAssembly.GetType("ns.class1").GetMethod("Evaluate")
    32.             'Invoke it on nothing, so that we can get the return value
    33.             Return Convert.ToDouble(methInfo.Invoke(Nothing, Nothing))
    34.         End If
    35.     End Function

    Sample usage and output:
    VB Code:
    1. MsgBox(ProcessCommand(TextBox1.Text)) 'SHows a message box with the result of an expression in TextBox1
    2.         Console.WriteLine(ProcessCommand("1+1").ToString()) 'Displays 2
    3.         Console.WriteLine(ProcessCommand("Math.PI").ToString()) 'Displays 3.14159265358979
    4.         Console.WriteLine(ProcessCommand("Math.Abs(-22)").ToString()) 'Displays 22
    5.         Console.WriteLine(ProcessCommand("3-4+6+7+22/3+66*(55)").ToString()) 'Displays 3649.333333333333333333

    Bill
    Hate Adobe Acrobat? My Codebank Sumbissions - Easy CodeDom Expression evaluator: (VB / C# ) -- C# Scrolling Text Display

    I Like to code when drunk. Don't say you weren't warned.

  2. #2
    PowerPoster JuggaloBrotha's Avatar
    Join Date
    Sep 2005
    Location
    Lansing, MI; USA
    Posts
    4,286

    Re: VB.NET Expression Evaluator using CodeDom.

    this is good, thanx for the convert to vb
    Currently using VS 2015 Enterprise on Win10 Enterprise x64.

    CodeBank: All ThreadsColors ComboBoxFading & Gradient FormMoveItemListBox/MoveItemListViewMultilineListBoxMenuButtonToolStripCheckBoxStart with Windows

  3. #3
    New Member
    Join Date
    Mar 2009
    Posts
    2

    Re: VB.NET Expression Evaluator using CodeDom.

    I get the following error:

    {"Specified argument was out of the range of valid values.
    Parameter name: Invalid Expression - please use something VB could evaluate"} System.Exception

    When trying to do the following formula.

    (MATH.SQRT(MATH.POW((50)/2),2)+(MATH.POW((30),2)))

    does anyone have any ideas?

  4. #4
    PowerPoster JuggaloBrotha's Avatar
    Join Date
    Sep 2005
    Location
    Lansing, MI; USA
    Posts
    4,286

    Re: VB.NET Expression Evaluator using CodeDom.

    MATH.SQRT and MATH.POW is causing the problem, the expression evaluator uses a different keyword for those.
    Currently using VS 2015 Enterprise on Win10 Enterprise x64.

    CodeBank: All ThreadsColors ComboBoxFading & Gradient FormMoveItemListBox/MoveItemListViewMultilineListBoxMenuButtonToolStripCheckBoxStart with Windows

  5. #5
    New Member
    Join Date
    Mar 2009
    Posts
    2

    Re: VB.NET Expression Evaluator using CodeDom.

    is there a list of what keywords are valide for the expression evaluator anywhere?

  6. #6
    New Member
    Join Date
    Aug 2017
    Posts
    2

    Re: VB.NET Expression Evaluator using CodeDom.

    Quote Originally Posted by dana View Post
    I get the following error:

    {"Specified argument was out of the range of valid values.
    Parameter name: Invalid Expression - please use something VB could evaluate"} System.Exception

    When trying to do the following formula.

    (MATH.SQRT(MATH.POW((50)/2),2)+(MATH.POW((30),2)))

    does anyone have any ideas?

    Exp = "(Math.Sqrt(Math.Pow((50) / 2, 2) + (Math.Pow((30), 2))))"
    Exp = ProcessCommand(Exp)
    Console.WriteLine("Exp=" & Exp)

    Exp = 39.0512483795333

  7. #7
    New Member
    Join Date
    Aug 2017
    Posts
    2

    Re: VB.NET Expression Evaluator using CodeDom.

    Quote Originally Posted by dana View Post
    is there a list of what keywords are valide for the expression evaluator anywhere?
    All Functions from System.Math Class

    Imports System.Math

    Starting from Math.Abs Method and ending with Math.Truncate

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width