Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Failed DateTime.Now #22

Closed
trrahul opened this issue Mar 4, 2020 · 3 comments
Closed

Failed DateTime.Now #22

trrahul opened this issue Mar 4, 2020 · 3 comments
Labels

Comments

@trrahul
Copy link

trrahul commented Mar 4, 2020

I used the simple code but it resulted in a null reference exception. Is this supported?

var varContext = new Dictionary<string, object>();
var lambdaParser = new NReco.Linq.LambdaParser();
Console.WriteLine(lambdaParser.Eval("System.DateTime.Now", varContext));
Console.Read();

image

@VitaliyMF
Copy link
Contributor

You cannot access static methods / properties directly in the expression, this is by design (to guarantee that expressions may use only explicitly defined context).

It is possible to expose DateTime.Now in the following way:

varContext["DateTimeNow"] = (Func<DateTime>)(() => DateTime.Now);
Console.WriteLine(lambdaParser.Eval("DateTimeNow()", varContext));

another approach: usage of special 'API' objects in the context

public class DateTimeApi {
  public DateTime Now => DateTime.Now;
}

varContext["DateTime"] = new DateTimeApi();
Console.WriteLine(lambdaParser.Eval("DateTime.Now", varContext));

@trrahul
Copy link
Author

trrahul commented Mar 4, 2020

Thanks. If I were to something like this, would it work?

varContext["DateTime"] = (Func<DateTime>)(() => DateTime);
Console.WriteLine(lambdaParser.Eval("DateTime.Now", varContext));
Console.WriteLine(lambdaParser.Eval("DateTime.UtcNow", varContext));

If so, it would be possible to give more static class contexts. I understand that "DateTime.Now()" is needed instead of "DateTime.Now", but is it possible to do this some other way?

I ask this because I tried DynamicExpresso and Flee, but both of them were not able to do what I wanted. I assigned a=1, b=2, c=a+b and then d = c+a. DynamicExpresso and Flee evaluated d to a+b1 instead of 4. But lambdaparser did it correctly so I tried more examples but it failed when I tested the DateTime.

@VitaliyMF
Copy link
Contributor

varContext["DateTime"] = (Func)(() => DateTime);

this will not work because DateTime refers to System.Type. You need to pass an object that has properties/methods. You may use an approach with DateTimeApi to enable a syntax similar to C# (like "DateTime.Now") and add to DateTimeApi any properties/methods you want to expose for expressions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants