zzzprojects / Eval-Expression.NET

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

Anonymous types in safe mode #144

Closed geoffsmith closed 1 year ago

geoffsmith commented 1 year ago

Hi,

I'm struggling to get the following code to work in safe mode:

            var context = new EvalContext();
            context.SafeMode = true;
            context.UnregisterAll();
            context.RegisterDefaultAliasSafe();
            context.RegisterType(typeof(List<>));
            context.RegisterNamespace(typeof(Enumerable).Assembly, "System.Linq");
            context.RegisterExtensionMethod(typeof(Enumerable));

            var result = context.Execute<string>(@"
var xs = new List<string> { ""Hello"", ""World"" };
var xs2 = xs.Select(x => new { Word = x, Length = x.Length });
var xs3 = xs2.OrderBy(x => x.Length);
return string.Join("", "", xs3);
");
            Console.WriteLine($"Result: {result}");

I get the following error Unhandled Exception: Z.Expressions.Compiler.Shared.EvalException: Oops! No applicable member has been found for the expression. The error occurred for expression "." at position 128 near ".OrderBy(x => x.Length);

My guess is that the compiler is struggling with the combination of the OrderBy extension method and the anonymous type. Is that correct? Is there a way to make this work? The code works fine when SafeMode = false.

JonathanMagnan commented 1 year ago

Hello @geoffsmith ,

Thank you for reporting.

My developer will look at it and try to fix it. I believe you are right fo the cause.

We will add an anonymous type created during the expression in the white list, so all members can be accessed.

Best Regards,

Jon

JonathanMagnan commented 1 year ago

Hello @geoffsmith ,

The v5.0.4 has been released.

Could you try it and let us know if everything is now working as expected in SafeMode?

Best Regards,

Jon