Get propertyinfo from lambda expression, but fails with int - c#

What is the best way to get to all the PropertyInfo of items in a lambda expression.
i want to set a filter on a xml field in a sql database.
var FilterBase = new FilterBase<SimpleItemSubObject>()
.SetSimpleFilter(x => x.ID, 123)
.SetSimpleFilter(x => x.Test.Name, "demo3");
in de analyser, i'm able to get the propertyinfo for the Name property.
internal IEnumerable<PropertyInfo> GetExpressionList()
{
return GetPropertyListfor(lambda.Body as MemberExpression);
}
private IEnumerable<PropertyInfo> GetPropertyListfor(MemberExpression body)
{
var result = new List<PropertyInfo>();
if (body != null && body.Expression != null)
{
result.AddRange(GetPropertyListfor(body.Expression as MemberExpression));
result.Add((body as MemberExpression).Member as PropertyInfo);
}
return result;
}
this will return the propertyinfo if it's a string property. but in case of a int the analyser fails because lambda has added a convert function.
{x => Convert(x.ID)}
It added a convert function.
so what is the best method of getting the propertyinfo in this case for the x.ID. and how do i prevent the use of the convert function

The fact that compiler adds Convert expression indicates that you are using non generic lambda expression with object return type. Something like this:
public class FilterBase<T>
{
public FilterBase<T> SetSimpleFilter(Expression<Func<T, object>> selector, object value)
{
// ...
return this;
}
}
One way to resolve the issue is to make the method generic (similar to LINQ OrderBy):
public FilterBase<T> SetSimpleFilter<V>(Expression<Func<T, V>> selector, V value)
so there will not be Convert anymore.
Another way is to keep the method as is, and strip the first Convert if any:
internal IEnumerable<PropertyInfo> GetExpressionList()
{
var body = lambda.Body;
if (body.NodeType == ExpressionType.Convert)
body = ((UnaryExpression)body).Operand;
return GetPropertyListfor(body as MemberExpression);
}

Related

Get JSON PropertyName from C# Class, like "nameof(class.prop)" for json properties?

How would I get the JSON PropertyName of the following class & Property? Something like a "nameof()" equivilent for JSON Properties?
ie, something like
var jsonName = GetJSONPropertyName(SampleClass.SampleClassID); //should return "jsoniD"
public class SampleClass
{
public SampleClass() { }
[JsonProperty(PropertyName = "jsoniD")]
public string SampleClassID { get; set; }
}
A good question would be, how do you pass a property in a type-safe way. Properties are not first-class objects in .NET.
One of the ways would be this:
using System.Linq.Expressions;
// ...
static string GetJsonPropertyName<TC, TP>(Expression<Func<TC, TP>> expr)
{
if (expr.Body is MemberExpression body)
return body.Member.GetCustomAttribute<JsonPropertyAttribute>()?.PropertyName;
else
throw new ArgumentException("expect field access lambda");
}
You'll need to call the function like this:
var jsonName = GetJsonPropertyName<SampleClass, string>(x => x.SampleClassID);
Yes, it doesn't feel very natural. Sorry for that.
Thanks to #elgonzo, the code can be simplified like this:
static string GetJsonPropertyName<TC>(Expression<Func<TC, object>> expr)
{
// in case the property type is a value type, the expression contains
// an outer Convert, so we need to remove it
var body = (expr.Body is UnaryExpression unary) ? unary.Operand : expr.Body;
if (body is System.Linq.Expressions.MemberExpression memberEx)
return memberEx.Member.GetCustomAttribute<JsonPropertyAttribute>()?.PropertyName;
else
throw new ArgumentException("expect field access lambda");
}
var jsonName = GetJsonPropertyName<SampleClass>(x => x.SampleClassID);
Working Value-Type Expression support based on #Vlad's solution
(with UnaryExpression pattern lifted from this SO POST)
public static string GetJsonPropertyName<T>(Expression<Func<T, object>> expr)
{
if (((expr.Body as UnaryExpression)?.Operand ?? expr.Body) is MemberExpression body)
return body.Member.GetCustomAttribute<JsonPropertyAttribute>()?.PropertyName;
else
throw new ArgumentException("expect field access lambda");
}

Using expressions to get intellisense support in C#

I'm trying use expressions in order to have strong typing over properties.
So I have this model.
public class Entity
{
public int Id { get; set; }
public string Name { get; set; }
}
And this method which should, well in the end I would like to use the properties in some way but for now I just want to return them.
public List<string> DoSomething<TEntity>(params Expression<Func<TEntity, object>>[] expressions)
{
List<string> props = new List<string>();
foreach (var expression in expressions)
{
var memberExpression = expression.Body as MemberExpression;
var q = memberExpression.Member.Name;
props.Add(q);
}
return props;
}
This is the usage
var props = DoSomething<Entity>(x => x.Id, x => x.Name);
Well, It works but only partially. What I mean by that is that it will work for reference types, for example it will work for Name property because it is a reference type, but it will return null for any value type, in this case for ID which is an int.
Why is that and what is the solution?
Expression<Func<TEntity, object>> is an Expression that builds a Func which returns an object (which is a reference type).
If you pass x => x.Id as value of that Expression, the return type of the resulting Func will not match, as int is a value type but the Func is expected to return a reference type.
C#'s compiler will see that and automatically build a Func that wraps the int inside an object (called boxing). But that Func no longer has a simple MemberExpression as its body, because the MemberExpression has to be wrapped in a "boxing expression".
That's basically what happens. So you have to handle the case where expression.Body is not of type MemberExpression to fix that.
This is untested, but it might help:
if (!(expression.Body is MemberExpression))
{
if (expression.Body is UnaryExpression unaryExpression && unaryExpression.NodeType == ExpressionType.TypeAs)
expression = unaryExpression.Operand as MemberExpression;
else
expression = null;
if (expression == null)
throw new ArgumentException("something happened");
}

MemberExpression as object of its type

I'm building Linq Extension methods.
Shortly, I've built an extension method in order to create a MemberExpression looks like:
public static Expression Field<T>(this object entity, string field)
{
Type entityType = entity.GetType();
PropertyInfo propertyInfo = entityType.GetProperty(field);
if (propertyInfo == null)
throw new ArgumentException(string.Format("{0} doesn't exist on {1}", field, entityType.Name));
ParameterExpression parameterExpression = Expression.Parameter(entityType, "e");
return Expression.Property(parameterExpression, propertyInfo);
}
So, I'm able to do that:
IEnumerable<C> classes = this.backend.cs.Where(
c => c.Field<C>("Matter").EndsWith(string.Empty)<<<<<<<< Compilation error.
);
Since MemberExpression have not EndsWith method, I'm not able to extend this MemberExpression like a String property access like:
IEnumerable<C> classes = this.backend.cs.Where(
c => c.Matter.EndsWith(string.Empty)
);
Is there some way to do that.
As you are able to figure out I'm trying to get something a bit more complex, Nevertheless, this example is for explaining the situation.
I hope it's enought clear.
Scope
My UI is using a backend.
This backend have three implementations. Each one of them provides a Linq implementation (Linq collections, NHibernate, custom-made Linq provider).
So, my UI is able to work on collections, a database or getting data from our server.
I'd like to provide util extension methods like AnyField().
So, after digging a bit I'm thinking on two approaches:
AnyField() generates an expression tree which is able to be translated by every Linq provider (first answer of this post).
Provide a default implementation of Anyfield() for Linq Collections, and then use each Linq provider extension mechanism for handle it. Or, if you are building a Linq Provider, support it on implementation.
Okay, so you're getting tripped up on the syntactic sugar that C# provides for you when building ExpressionTrees
Where expects Expression<Func<TObjectType, TReturnType>> or a compiled lambda; Func<TObjectType, TReturnType>.
Your method Field currently only returns an untyped Expression. That means your query is actually returning Expression<Func<TObjectType, Expression>>. That's not right! It should be returning a Expression<Func<TObjectType, string>>! But how do we do that? That would mean our method would have to return a string, but we want to build an expression tree.
To get it working as you're expecting, it's quite a bit more difficult than you would imagine, but that's only because we're so spoiled with the syntactic sugar.
What we actually need to do is write methods which accept lambda methods, and return lambda methods, each one re-writing the body a little bit.
So... what does that look like?
public static Expression<Func<TElementType, object>> Field<TElementType, TReturnType>(this Expression<Func<TElementType, TReturnType>> expr, string field)
{
Type entityType = expr.Body.Type;
PropertyInfo propertyInfo = entityType.GetProperty(field);
if (propertyInfo == null)
throw new ArgumentException(string.Format("{0} doesn't exist on {1}", field, entityType.Name));
ParameterExpression parameterExpression = Expression.Parameter(entityType, "e");
return Expression.Lambda<Func<TElementType, object>>(
Expression.Property(parameterExpression, propertyInfo),
parameterExpression
);
}
Notice that it's almost the exact same as what you wrote, but we wrap it with Lambda<Func<TElementType, TReturnType>>. And the signature is a bit different too.
Instead of operating on an object, we want to operate on a lambda expression. We also return a lambda expression.
So how do we use it?
var classes = objects.Where(
ExpressionExtensions.Field<Test, Test>(q => q, "Matter")
);
Great! Now we're passing Expression<Func<Test, string>> to Where, rather than Expression<Func<Test, MemberExpression>>. Making progress.
But that won't compile, and rightly so. We're returning a string, but we're using a filtering method, which requires a bool.
So let's now write EndsWith:
public static Expression<Func<T, bool>> EndsWith<T, TReturnType>(this Expression<Func<T, TReturnType>> expr, string str)
{
var endsWithMethod = typeof(string).GetMethod("EndsWith", new[] { typeof(string) });
var newBody = Expression.Call(expr.Body, endsWithMethod, Expression.Constant(str));
var result = Expression.Lambda<Func<T, bool>>(newBody, expr.Parameters);
return result;
}
And using it:
var classes = objects.Where(
ExpressionExtensions.Field<Test, Test>(q => q, "Matter")
.EndsWith("A")
);
Which is now compiling! And the expression tree looks like this:
UserQuery+Test[].Where(e => e.Matter.EndsWith("A"))
That's not too pretty, having Field take a redundant lambda, though. Let's add a helper method to make it look prettier:
public static Expression<Func<TElementType, TElementType>> Query<TElementType>(this Expression<Func<TElementType, TElementType>> expr)
{
return expr;
}
Putting it all together:
void Main()
{
var objects = new[] { new Test { Matter = "A" } }.AsQueryable();
var classes = objects.Where(
ExpressionExtensions.Query<Test>(q => q)
.Field("Matter")
.EndsWith("A")
);
classes.Expression.Dump();
}
public class Test
{
public string Matter { get; set;}
}
public static class ExpressionExtensions
{
public static Expression<Func<TElementType, TElementType>> Query<TElementType>(this Expression<Func<TElementType, TElementType>> expr)
{
return expr;
}
public static Expression<Func<TElementType, object>> Field<TElementType, TReturnType>(this Expression<Func<TElementType, TReturnType>> expr, string field)
{
Type entityType = expr.Body.Type;
PropertyInfo propertyInfo = entityType.GetProperty(field);
if (propertyInfo == null)
throw new ArgumentException(string.Format("{0} doesn't exist on {1}", field, entityType.Name));
ParameterExpression parameterExpression = Expression.Parameter(entityType, "e");
return Expression.Lambda<Func<TElementType, object>>(
Expression.Property(parameterExpression, propertyInfo),
parameterExpression
);
}
public static Expression<Func<T, bool>> EndsWith<T, TReturnType>(this Expression<Func<T, TReturnType>> expr, string str)
{
var endsWithMethod = typeof(string).GetMethod("EndsWith", new[] { typeof(string) });
var newBody = Expression.Call(expr.Body, endsWithMethod, Expression.Constant(str));
var result = Expression.Lambda<Func<T, bool>>(newBody, expr.Parameters);
return result;
}
}
I don't know if you mess the code to show a piece of code or if it was intended, but you have a generic extension that wants A T but you don't use it
Anyway if what you want is a method that returns you the value of a property, why don't you do a static exception that return T ?
public static class EntityExtension {
public static T Field<T>(this object entity, string field) {
Type entityType = entity.GetType();
PropertyInfo propertyInfo = entityType.GetProperty(field);
if (propertyInfo == null) {
throw new ArgumentException(string.Format("{0} doesn't exist on {1}", field, entityType.Name));
}
return (T)propertyInfo.GetValue(entity);
}
}
this is a fiddle i've done to show you the usage, pretty simple
https://dotnetfiddle.net/PoSfli
posting the code too in case fiddle get lost:
using System;
using System.Reflection;
using System.Linq.Expressions;
public class Program
{
public static void Main()
{
YourClass c = new YourClass() {
PropA = 1,
PropB = 2,
PropC = "ciao"
};
var propBValue = c.Field<int>("PropB");
Console.WriteLine("PropB value: {0}", propBValue);
var propCValue = c.Field<string>("PropC");
Console.WriteLine("PropC value: {0}", propCValue);
}
}
public static class EntityExtension {
public static T Field<T>(this object entity, string field) {
Type entityType = entity.GetType();
PropertyInfo propertyInfo = entityType.GetProperty(field);
if (propertyInfo == null) {
throw new ArgumentException(string.Format("{0} doesn't exist on {1}", field, entityType.Name));
}
return (T)propertyInfo.GetValue(entity);
}
}
public class YourClass {
public int PropA { get; set; }
public int PropB { get; set; }
public string PropC { get; set; }
}
nota that you can improve a lot, using a typed extension and a property expression as argument instead of a string
You can also do something really simple like if you want to use the property name:
IEnumerable<C> classes = this.backend.cs.Where(
c => c.Field<C>("Matter").ToString().EndsWith(string.Empty)
Or if your are filtering by property type:
IEnumerable<C> classes = this.backend.cs.Where(
c => c.Field<C>("Matter").Type.ToString().EndsWith(string.Empty)
How about something like this? Actually, your generic approach is not of use right now.
public static bool Evaluate<TField>(this object entity, string fieldName, Predicate<TField> condition)
{
Type entityType = entity.GetType();
PropertyInfo propertyInfo = entityType.GetProperty(field);
if (propertyInfo == null)
throw new ArgumentException(string.Format("{0} doesn't exist on {1}", field, entityType.Name));
var value = (TField)propertyInfo.GetValue(entity); //read the value and cast it to designated type, will raise invalid cast exception, if wrong
return condition.Invoke(value); //invoke the predicate to check the condition
}
Usage would be then.
.Where(item => item.Evaluate<string>("Matter", prop => prop.EndsWith(string.Empty))
You can add a new extension method which returns your desired type.
public static T Compile<T>(this Expression expression)
{
return Expression.Lambda<Func<T>>(expression).Compile()();
}
In your statement you just have to add .Compile<type>()
IEnumerable<C> classes = this.backend.cs.Where(
c => c.Field<C>("Matter").Compile<string>().EndsWith(string.Empty));

How to use expressions to sort a collection based on an inherited interface property

This problem has been discussed to an extent in this question: Create Generic Expression from string property name but perhaps I'm missing the answer, or it is subtly different.
I have the following queryable extension method:
public static IQueryable<TSource> OrderByPropertyDescending<TSource>(IQueryable<TSource> source, string propertyName)
{
var sourceType = typeof (TSource);
var parameter = Expression.Parameter(sourceType, "item");
var orderByProperty = Expression.Property(parameter, propertyName);
var orderBy = Expression.Lambda(orderByProperty, new[] { parameter });
return Queryable.OrderByDescending(source, (dynamic) orderBy);
}
For the purposes of this problem let us assume that the queryable source instance has a property called 'Created' which is a type of DateTime. If we define a class that has the property 'Created' on it and then OrderByDescending then the above will work fine. e.g.
var queryable = new List<EntityClassWithCreatedProperty>().AsQueryable();
var result = queryable.OrderByPropertyDescending("Created").ToList();
If we do the same thing but with an interface such as ICreated which has the Created property on it:
public interface ICreated
{
DateTime Created { get; }
}
Then the following also works:
var queryable = new List<ICreated>().AsQueryable();
var result = queryable.OrderByPropertyDescending("Created").ToList();
If however, you have the following interface hierarchy:
public interface ITimestamped : ICreated
{
...
}
Then the following will fail:
var queryable = new List<ITimestamped>().AsQueryable();
var result = queryable.OrderByPropertyDescending("Created").ToList();
With the similar error message to that of the other question: Instance property 'Created' is not defined for type ITimestamped. I'm assuming that I need to find the property on the declaring type of interface (which I can do by crawling the source type) but then what do I do with it? Most attempts I have tried result in the incorrect original source type not being cast-able back to the IQueryable. Do I need to use a ConvertType call somewhere? Thanks.
I would use the other Expression.Property() method that takes a propertyInfo, e.g
public static IQueryable<TSource> OrderByPropertyDescending<TSource>(IQueryable<TSource> source, string propertyName)
{
var sourceType = typeof (TSource);
var parameter = Expression.Parameter(sourceType, "item");
var propertyInfo = FindMyProperty(sourceType, propertyName);
var orderByProperty = Expression.Property(parameter, propertyInfo);
var orderBy = Expression.Lambda(orderByProperty, new[] { parameter });
return Queryable.OrderByDescending(source, (dynamic) orderBy);
}
private static PropertyInfo FindMyProperty(Type type, string propertyName)
{
return type.GetProperty(propertyName);
}
At this point your question has nothing to do with expressions, it's a simple reflection question, and you have to find the correct way to get the properties you want. There are a lot of scenarios here. For your exact one, meaning get property from parent interface, you can do something like:
private static PropertyInfo FindMyProperty(Type type, string propertyName)
{
var result = type.GetProperty(propertyName);
if (result == null)
{
foreach(var iface in type.GetInterfaces())
{
var ifaceProp = FindMyProperty(iface, propertyName);
if (ifaceProp != null)
return ifaceProp;
}
}
return result;
}
DISCLAIMER!
This is by no means the best way to get a property from a type, but it should work in your case. You should google around to find an implementation for FindMyProperty that satisfies all your requirements :)

Create safe deep property accessor from Lambda with Expressions

My goal is to use Lambdas to create a property binding object that can do a safe retrieval of a deep property value. By safe, it returns the default value of the property type if one of previous properties is null rather than throwing a null reference exception.
The method signature:
public static Func<TO, TP> BuildSafeAccessor<TO, TP>(this Expression<Func<TO, TP>> propertyExpression) where TO: class
{
}
*Edit: Clarify my question
So if I call:
var safeAccessor = BuildSafeAccessor<Person>(p => p.Address.Zip);
When safeAccessor is called, it's logic would be the following:
if (p.Address == null)
return default(TP);
return p.Address.Zip;
The key observation here is that you don't need “the ifFalse expression fully created already”, you can build it recursively.
The code could look like this:
public static Func<TO, TP> BuildSafeAccessor<TO, TP>(Expression<Func<TO, TP>> propertyExpression)
{
var properties = GetProperties(propertyExpression.Body);
var parameter = propertyExpression.Parameters.Single();
var nullExpression = Expression.Constant(default(TP), typeof(TP));
var lambdaBody = BuildSafeAccessorExpression(parameter, properties, nullExpression);
var lambda = Expression.Lambda<Func<TO, TP>>(lambdaBody, parameter);
return lambda.Compile();
}
private static Expression BuildSafeAccessorExpression(Expression init, IEnumerable<PropertyInfo> properties, Expression nullExpression)
{
if (!properties.Any())
return init;
var propertyAccess = Expression.Property(init, properties.First());
var nextStep = BuildSafeAccessorExpression(propertyAccess, properties.Skip(1), nullExpression);
return Expression.Condition(
Expression.ReferenceEqual(init, Expression.Constant(null)), nullExpression, nextStep);
}
private static IEnumerable<PropertyInfo> GetProperties(Expression expression)
{
var results = new List<PropertyInfo>();
while (expression is MemberExpression)
{
var memberExpression = (MemberExpression)expression;
results.Add((PropertyInfo)memberExpression.Member);
expression = memberExpression.Expression;
}
if (!(expression is ParameterExpression))
throw new ArgumentException();
results.Reverse();
return results;
}
(Note that this code uses LINQ inefficiently, to make it more readable.)
If you run it on the lambda a => a.B.C.D, it will create an expression (showing the result of ToString() on it):
a => IIF((a == null), null, IIF((a.B == null), null, IIF((a.B.C == null), null, a.B.C.D)))
Notice that this accesses a.B up to three times. If that property is slow or has side effects, that could be a problem. If this is a problem to you, I think you would need to use Blocks with local variables.

Categories

Resources