tags:

views:

27

answers:

1

Hi guys,

I have difficulty in using the vb code dom. Basically, I want to compile this piece of code dynamically:

Imports System    
Imports System.Collections.Generic
Imports Microsoft.VisualBasic
Namespace Formula

Public Class TsCalculator

Public Sub New()

End Sub

Public Shared Function Evaluate(ByVal Ts As Dictionary(Of String, Decimal)) As decimal

Dim result = If((Ts("sss")+Ts("zzz")) <> 0, (Ts("KWHD") - Ts("zzzz"))*Ts("sdsd")/(Ts("sds")+Ts("1ANGAT_M-DISPATCH")), (Ts("sdsd") - Ts("sdsd"))*(.5D + .5D))

Return result

End Function

End Class

End Namespace

And for compiling this code, i use this function:

 Public Shared Function CompileCode(ByVal classname As String _

, ByVal inputname As String, _

ByVal compiler As CodeDomProvider, _

ByVal snippetcode As String) As Calculator(Of Decimal, Decimal)

Dim compilerargs = New CompilerParameters()

Dim code = BuildCodeString("Solver", inputname, snippetcode)

Dim currassembly = Reflection.Assembly.GetAssembly(GetType(FormulaCompiler))

With compilerargs

.TreatWarningsAsErrors = False

.ReferencedAssemblies.Add("System.dll")

.GenerateInMemory = True

.WarningLevel = 4

End With

Dim ss As Func(Of Dictionary(Of String, Decimal), Decimal)

Dim compiledresults = compiler.CompileAssemblyFromSource(compilerargs, code)

With compiledresults

If .Errors.HasErrors Then

Throw New InvalidExpressionException()

Else

Dim inputtypes = New Type() {GetType(Dictionary(Of String, Decimal))}

Dim formss = compiledresults.CompiledAssembly.GetType(String.Format("Formula.{0}", "Solver"))

Dim evalinfo = formss.GetMethod("Evaluate", inputtypes)

ss = CType([Delegate].CreateDelegate(GetType(Func(Of Dictionary(Of String, Decimal), Decimal)) _

, evalinfo), Func(Of Dictionary(Of String, Decimal), Decimal))

End If

End With

Dim calculator As New Calculator(Of Decimal, Decimal)(classname, ss)

Return calculator

End Function

Did is miss some assemblies?

Cheers!

A: 

Hi guys,

I've finally found the solution to my problem. I've discovered lately that the codedom by default uses the 2.0 compilers, instead of the latest ones (vb compiler for .net 3.5). You have to explicitly specify that you would be using the 3.5 VB Compiler via a dictionary (of string, sting) in creating an instance of the VB compiler...

cless