I have some c# code that uses the Microsoft Scripting Control to evaluate some expressions:
using MSScriptControl; // references msscript.ocx
ScriptControlClass sc = new ScriptControlClass();
sc.Language = "VBScript";
sc.AllowUI = true;
try
{
Console.WriteLine(sc.Eval(txtEx.Text).ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
(txtEx is a simple text field)
Numerical expressions: "6+4", "cos(34)", "abs(-99)", "round(1.234, 2)" etc. are fine
Boolean expressions: "true or false", "1=2" are fine
But how can I evaluate a simple 'if'? I have tried "if(true, 2, 3)", "iif(true, 2, 3)", "if (true) then 2 else 3" and "if (true) then 2 else 3 endif"
Can anybody please help me to evaluate simple conditional expressions? Any help much appreciated!
RH
Try wrapping your IF-expression in a function
Function test
if (true) then
return true
else
return false
end if
End function
Add the function to the control and then use Run
Result = ScriptControl.Run("Test")
(the code above is not tested, but something along that way should work)
Check out this link for some more info
http://support.microsoft.com/kb/184740
using MSScriptControl; // references msscript.ocx
ScriptControlClass sc = new ScriptControlClass();
sc.Language = "VBScript";
sc.AllowUI = true;
// VBScript engine doesn’t have IIf function
// Adding wraper IIF function to script control.
// This IIF function will work just as VB6 IIf function.
sc.AddCode(@"Function IIF(Expression,TruePart,FalsePart)
If Expression Then
IIF=TruePart
Else
IIF=FalsePart
End IF
End Function");
try
{
//define x,y variable with value
sc.AddCode(@"x=5
y=6");
//test our IIF
Console.WriteLine(sc.Eval("IIF(x>y,x,y)").ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
You should consider using the expression evaluation engine that is part of Windows Workflow Foundation. Both the evaluator and the designer for it can be used separately from WF.
if (true) then return 2 else return 3
Thanks for the tips! After a bit more experimenting, based on Brummo's help, this seems to work:
txtEx contains this text:
function test
if (1=1) then
test = true
else
test = false
end if
end function
then
sc.AddCode(txtEx.Text);
and
object[] myParams = { };
Console.WriteLine(sc.Run("Test", ref myParams).ToString());
This isn't ideal, since I really wanted to evaluate an expression, without building, loading and evaluating a function. (I am surprised IIF doesn't work for simple one line if evaluation).