0

I'm trying to use NCalc to parse some formula from JSON files.

However sometimes I'm needing to reference another object via GUID and get that objects formula:

public class FooObject
{
  NCalc.Expression expression;
  double Value;
  public void SetValue()
  {Value = (double)expression.Evaluate()} //this throws "Value was either too large or too small for a Double."

  public FooObject()
  { expression = new NCalc.Expression("TechData(b8ef73c7-2ef0-445e-8461-1e0508958a0e)")}
    expression.EvaluateFunction += NCalcFunctions;
  }
}

public static void NCalcFunctions(string name, FunctionArgs args)
{
  if (name == "TechData") //breakpoint shows we never get this far
  {
    Guid techGuid = new Guid(args.Parameters[0].ToString());
    TechSD techSD = _staticData.Techs[techGuid]; //this returns an TechSD object that matches the given guid.
    args.Result = techSD.DataExpression;//returns an NCalc expression from the techSD
  }
}

SetValue() throws an exception (Value was either too large or too small for a Double), and the custom function never gets called.

I'm suspecting it's trying to parse the GUID. Would this be correct? Is what I'm trying to do possible with NCalc? is there a better tool?

Adriano Repetti
  • 65,416
  • 20
  • 137
  • 208
se5a
  • 97
  • 10

1 Answers1

1

In this NCalc expression:

TechData(b8ef73c7-2ef0-445e-8461-1e0508958a0e)

GUID b8ef73c7-2ef0-445e-8461-1e0508958a0e is not parsed as a string (note there aren't single quotes), NCalc will then try to parse that expression as

  • b8ef73c7 variable name, undefined.
  • - subtraction operator.
  • 2ef0 syntax error, it's not an identifier (it starts with a number) and also it's not a valid number (because of e it'll try to parse it as double in scientific notation but it's not valid).
  • ...

You have to use quotes:

TechData('b8ef73c7-2ef0-445e-8461-1e0508958a0e')

Now NCalc will correctly parse this expression and your handler may simply:

var techGuid = Guid.Parse((string)args.EvaluateParameters()[0]);
Adriano Repetti
  • 65,416
  • 20
  • 137
  • 208
  • Ah! Excelent! single quotes! Thankyou! (though args.Parameters[0].ToString() is returning a string *with* the single quotes, and (string)args.Parameters[0]) does not work either. still this is a much easier problem to figure out :-) – se5a Sep 08 '15 at 07:52
  • 1
    Just use `args.EvaluateParameters()[0]` instead of `args.Parameters[0]` (they're raw unevaluated expressions). – Adriano Repetti Sep 08 '15 at 08:13
  • Ah I see, I didn't notice the EvaluateParameters. that's a lot nicer than using Trim. – se5a Sep 08 '15 at 09:32