First, a quick overview on what I'm trying to do: I want to take a C# expression, serialize it, send it to another process, de-serialize it, and use it to filter a list. Here's the caveat - when the expression is created it is done so going against a generic parameter type T but when it is de-serialized it needs to go against a dynamic instead. The reason for this is that when it is eventually used on a server in a different process it will be done so against a list of dynamics as I will not have type information in that context.
I feel like I'm close as I've used the Newtonsoft.Json and Serialize.Linq libraries to put together a proof of concept but I can only get it to work without using dynamics (e.g. I have the type T available on both the serializing side (client) and the de-serializing side (server). On to some code to show you what I have...
Given this:
public class Person
{
public string Name { get; set; }
public string Email { get; set; }
}
...as the type we are working with. I have a client that has interface:
public interface IClient
{
T Get<T>(Expression<Func<T, bool>> query);
}
...so that I can do this:
var client = new Client();
var john = client.Get<Person>(p => p.Name == "John");
...all is well and good so far. In the client.Get() method I am taking the passed expression and serializing it down and sending to the server. The server looks as such:
public dynamic Server(string serializedExpression)
{
var people = new List<dynamic>
{
new { Name = "John", Email = "john@stackoverflow.com" },
new { Name = "Jane", Email = "jane@stackoverflow.com" }
};
var serializer = new ExpressionSerializer(new JsonSerializer());
var deserializedExpression = (Expression<Func<dynamic, bool>>)serializer.DeserializeText(serializedExpression);
return people.FirstOrDefault(deserializedExpression.Compile());
}
...and here is where the problems happen because I'm trying to deserialize it into a type of
Expression<Func<dynamic, bool>>
...instead of...
Expression<Func<Person, bool>>.
So my questions are:
1) Is what I'm trying to do even possible? It seems like using an ExpressionVisitor you can change the generic parameter types and I've tried to do so to change from Person to dynamic before I serialize and send but have had no luck.
2) Is there a better way to do what I want to accomplish? I know the first question will be why don't I just get access to the type T specified in the expression Func<> on the server but that won't be possible due to the nature of the server. I basically want the luxury of using Linq on the client to specify query predicates while executing those predicates against dynamic lists.
Thanks in advance for any answers or ideas you can provide.
Regards,
Craig