zzzprojects / Eval-Expression.NET

C# Eval Expression | Evaluate, Compile, and Execute C# code and expression at runtime.
https://eval-expression.net/
Other
449 stars 86 forks source link

Problem with generic List in safe mode #143

Closed geoffsmith closed 1 year ago

geoffsmith commented 1 year ago

Hi,

I'm having some trouble after switching to safe mode. I think List<> should work, but I'm getting strange errors when I try to use it. It looks like it should be registered when i call context.RegisterDefaultAliasSafe(), but when I try and use it I get an error. I'm using 5.0.2.

Small example:

            var context = new EvalContext();
            context.SafeMode = true;
            context.UnregisterAll();
            context.RegisterDefaultAliasSafe();

            var result = context.Execute<string>(@"
var a = new List<string>();
return a.Count.ToString();
");
            Console.WriteLine($"Result: {result}");

This raises the following exception:

Unhandled Exception: System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.
   at System.Collections.Concurrent.ConcurrentDictionary`2.get_Item(TKey key)
   at ?.?(ExpressionScope ?, MemberInfo ?, SyntaxNode ?)
   at ?.?(ExpressionScope ?, SyntaxNode ?)
   at ?.?(ExpressionScope ?, SyntaxNode ?, Expression ?, Boolean ?)
   at ?.?(ExpressionScope ?, SyntaxNode ?)
   at ?.?(ExpressionScope ?, SyntaxNode ?, Expression ?, Boolean ?)
   at ?.?(ExpressionScope ?, SyntaxNode ?, Expression ?, Boolean ?)
   at ?.?(ExpressionScope ?, SyntaxNode ?, Expression ?, Boolean ?)
   at Z.Expressions.CodeCompiler.CSharp.ExpressionParser.ParseSyntax(ExpressionScope scope, SyntaxNode node, Type resultType)

Is there anything I should be doing differently?

Thanks!

JonathanMagnan commented 1 year ago

Hello @geoffsmith ,

You can fix this issue with

context.RegisterMember(typeof(List<string>));

Which will allow everything about the List<string>. We will check on our side if we can do something to better handle the generic type as at this moment, you need to register all of those that you want to use.

Best Regards,

Jon

geoffsmith commented 1 year ago

Ok, thanks for confirming. It would definitely be more convenient to be able to add a load at once, there are so many variations on IList, ICollection, IEnumerable - i'd struggle to make sure I'd covered them all!

JonathanMagnan commented 1 year ago

Hello @geoffsmith ,

The v5.0.3 is now available.

In this version, we added the logic that as long as all generic arguments have been registered as "Safe", you can also use the generic type.

So, in short, types such as List<string> and List<List<string> should now work correctly.

Let me know if that fixed your issue correctly.

Best Regards,

Jon

geoffsmith commented 1 year ago

@JonathanMagnan amazing, thank you! I'll check it out :)

geoffsmith commented 1 year ago

Finally got a chance to test your change and it works great - thanks again 👍