Using refection to get all properties and pass each property in method - c#

I'm using simplemvvmtoolkit for validation (INotifyDataErrorInfo). Instead of me repeating my self over and over for each property within the view model, Id like to use reflection to get all the properties and validate them, I can't seem to figure out what to pass in the validateProperty method though.
private void ValidateInput()
{
var unitProperties = this.GetType().GetProperties()
.Where(x => x.CanRead);
foreach (var prop in unitProperties)
ValidateProperty(prop, prop.GetValue(this, null)); //????
//? ^ get errors here
}
ValidateProperty takes in:
protected virtual void ValidateProperty<TResult>(Expression<Func<TViewModel, TResult>> property, object value);

The problem is Expression<Func<TViewModel, TResult>> has absolutely no relation to PropertyInfo (the type returned by GetProperties). You'll also run into problems because the type of the result is not known at compile time.
The easiest solution would be to change ValidateProperty to accept a PropertyInfo:
protected virtual void ValidateProperty(PropertyInfo property, object value);
You could also convert the PropertyInfo to an Expression, but that's a bit more difficult:
var method = this.GetType().GetMethod("ValidateProperty");
foreach (var prop in unitProperties)
{
var parameter = Expression.Parameter(this.GetType(), "_");
var property = Expression.Property(parameter, prop);
var lambda = Expression.Lambda(property, parameter);
var genericMethod = method.MakeGenericMethod(prop.PropertyType);
genericMethod.Invoke(this, new object[] { lambda, prop.GetValue(this, null) });
}

Related

Dynamically creating an expression which selects an objects property

I want to be able to build up an expression dynamically, which is essentially a property selector.
I am trying to use this so I can provide a flexible search UI and then translate the selected search parameters to an Entity Framework query.
I have most of what I need thanks to another library I am using, but am missing the final part which translates my query string parameters to the appropriate expression selector the other library requires.
The library takes an argument of :
Expression<Func<TObject, TPropertyType>>
An example of how this would be coded if baked into an application would be :
Expression<Func<MyObject, int>> expression = x=> x.IntegerProperty;
However, I need to be able to generate this expression dynamically, as the important point is that all I will know is the type of object (MyObject) and the property name as a string value ("IntegerProperty"). The property value will obviously map to an property on the object which could be of any non complex type.
So essentially I think I am wanting to find a way to build up the expression dynamically which specifies the correct object property to return and where the return value is determined by that property type.
psuedo code :
string ObjectPropertyName
Type ObjectType
Type ObjectPropertyType = typeof(ObjectType).GetProperty(ObjectPropertyName).Property
Expression<Func<[ObjectType], [ObjectPropertyType]>> expression = x=> x.[ObjectPropertyName];
Update :
I have got as far as this
ParameterExpression objectParameter = Expression.Parameter(type, "x");
MemberExpression objectProperty = Expression.Property(objectParameter, "PropertyNameString");
Expression<Func<ObjectType, int>> expression = Expression.Lambda<Func<ObjectType, int>>(objectProperty, objectParameter);
But the problem I have with this is that the return type is not always an int but may be some other type.
Doing what you asked is bit tricky but not impossible. Since the property type is not known until run time so you can not declare the Expression<Func<,>> so it would be done by reflection.
public static class QueryableExtension
{
public static object Build<Tobject>(this Tobject source, string propertyName)
{
var propInfo = typeof(Tobject).GetProperty(propertyName);
var parameter = Expression.Parameter(typeof(Tobject), "x");
var property = Expression.Property(parameter, propInfo);
var delegateType = typeof(Func<,>)
.MakeGenericType(typeof(Tobject), propInfo.PropertyType);
var lambda = GetExpressionLambdaMethod()
.MakeGenericMethod(delegateType)
.Invoke(null, new object[] { property, new[] { parameter } });
return lambda;
}
public static MethodInfo GetExpressionLambdaMethod()
{
return typeof(Expression)
.GetMethods()
.Where(m => m.Name == "Lambda")
.Select(m => new
{
Method = m,
Params = m.GetParameters(),
Args = m.GetGenericArguments()
})
.Where(x => x.Params.Length == 2
&& x.Args.Length == 1
)
.Select(x => x.Method)
.First();
}
}
Usage -
var expression = testObject.Build("YourPropertyName");
Now this will build the Expression you desired with return type of property. But since we don't know about your library but I suggest you to call your library method via reflection and pass the expression wrapped under object.
As I mentioned in the comments, building expression without knowing the property type is easy (even with nested property support):
static LambdaExpression MakeSelector(Type objectType, string path)
{
var item = Expression.Parameter(objectType, "item");
var body = path.Split('.').Aggregate((Expression)item, Expression.PropertyOrField);
return Expression.Lambda(body, item);
}
But then you'll need to find a way to call your generic library method - using reflection or dynamic call.
If you have both ObjectType and ObjectPropertyType as generic type parameters, you can use the Expression class to do something like this:
public static Expression<Func<TObject, TPropertyType>> Generate<TObject, TPropertyType>(
string property_name)
{
var parameter = Expression.Parameter(typeof (TObject));
return Expression.Lambda<Func<TObject, TPropertyType>>(
Expression.Property(parameter, property_name), parameter);
}
There is old intresting library DynamicLinq. May be it will be useful for you. It extends System.Linq.Dynamic to support execution of Lambda expressions defined in a string. With use of DynamicLinq you can do somethink like:
public class IndexViewModel
{
public bool HasPassword { get; set; }
public string PhoneNumber { get; set; }
public bool TwoFactor { get; set; }
public bool BrowserRemembered { get; set; }
}
//...........
Expression<Func<IndexViewModel, bool>> ex =
System.Linq.Dynamic.DynamicExpression.ParseLambda<IndexViewModel, bool>("TwoFactor");
var model = new ReactJs.NET.Models.IndexViewModel() { TwoFactor = true };
var res = ex.Compile()(model);
// res == true
System.Diagnostics.Debug.Assert(res);

Dynamic delegate convert to dynamic function

I'd like to copy an object into a mock of the same Interface. The goal is, to do it dynamic. But it seems, that there is no way to convert a dynamic delegate into a function.
public static T GetCopiedMock<T>(T toCopy, T mockObject) where T : class
{
IEnumerable<PropertyInfo> properties = GetPropertyInfos(toCopy, typeof(T));
foreach (var property in properties)
{
var parameter = Expression.Parameter(typeof(T));
var result = Expression.Property(parameter, property);
var lamda = Expression.Lambda(result, parameter);
var compilat = lamda.Compile();
var funcType = typeof(Func<,>).MakeGenericType(typeof(T), property.PropertyType);
//Here is my problem
mockObject.Expect(new Func<T, property.PropertyType>(compilat));
}
return mockObject;
}
I know its not possible directly since propertytype is at runtime but is there is any workaround?
By the way, this is my first post. So if you see something terrible which i have to do better, tell me!

Programmatically Create Collection of Property Accessor Functions

What I want to do is take any class type and create a list of 'get' accessors to all of the properties in the object graph.
The exact format, order, etc of the collection doesn't matter, I just don't quite know how to start off identifying and creating accessors to all of the properties. It might take the form of something like this:
public static List<Func<T,object>> CreateAccessors<T>()
{
Type t = typeof(T);
// Identify all properties and properties of properties (etc.) of T
// Return list of lambda functions to access each one given an instance of T
}
public void MyTest()
{
MyClass object1;
var accessors = CreateAccessors<MyClass>();
var myVal1 = accessors[0](object1);
var myVal2 = accessors[1](object1);
// myVal1 might now contain the value of object1.Property1
// myVal2 might now contain the value of object1.Property4.ThirdValue.Alpha
}
You can use reflection to extract the properties and expression-trees to help build the delegates targeting the property getters:
// Start with all public instance properties of type
var accessors = from property in type.GetProperties
(BindingFlags.Instance | BindingFlags.Public)
// Property must be readable
where property.CanRead
//Assemble expression tree of the form:
// foo => (object) foo.Property
// foo
let parameter = Expression.Parameter(type, "foo")
// foo.Property
let propertyEx = Expression.Property(parameter, property)
// (object)foo.Property - We need this conversion
// because the property may be a value-type.
let body = Expression.Convert(propertyEx, typeof(object))
// foo => (object) foo.Property
let expr = Expression.Lambda<Func<T,object>>(body, parameter)
// Compile tree to Func<T,object> delegate
select expr.Compile();
return accessors.ToList();
Note that although Delegate.CreateDelegate seems like an obvious choice, you will have some problems boxing value-type properties. Expression-trees dodge this problem elegantly.
Note that you'll need some more work to be able to get "nested" properties out too, but hopefully I've given ypu enough to get you started (hint: recurse). One final pointer with that: watch out for cycles in the object graph!
public static List<Func<T, object>> CreateAccessors<T>()
{
var accessors = new List<Func<T, object>>();
Type t = typeof(T);
foreach (PropertyInfo prop in t.GetProperties(BindingFlags.Instance | BindingFlags.Public)) {
if (prop.CanRead) {
var p = prop;
accessors.Add(x => p.GetValue(x, null));
}
}
return accessors;
}
EDIT:
Here is a variant which returns compiled expressions and should be much faster than the previous one using reflection
public static List<Func<T, object>> CreateAccessorsCompiled<T>()
{
var accessors = new List<Func<T, object>>();
Type t = typeof(T);
foreach (PropertyInfo prop in t.GetProperties(BindingFlags.Instance | BindingFlags.Public)) {
if (prop.CanRead) {
ParameterExpression lambdaParam = Expression.Parameter(t, "instance");
Expression bodyExpression;
MemberExpression memberAccessExpression = Expression.MakeMemberAccess(Expression.Convert(lambdaParam, t), prop);
if (prop.PropertyType == typeof(object)) { // Create lambda expression: (instance) => ((T)instance).Member
bodyExpression = memberAccessExpression;
} else { // Create lambda expression: (instance) => (object)((T)instance).Member
bodyExpression = Expression.Convert(memberAccessExpression, typeof(object));
}
var lambda = Expression.Lambda<Func<T, object>>(bodyExpression, lambdaParam);
accessors.Add(lambda.Compile());
}
}
return accessors;
}

Matching an interface's ProperyInfo with a class's PropertyInfo

I use a method similar to the following to get some precomputed metadata related to a Type's properties.
MyData GetProperty<T, U>(Expression<Func<T, U>> member)
{
// Get the property referenced in the lambda expression
MemberExpression expression = member.Body as MemberExpression;
PropertyInfo property = expression.Member as PropertyInfo;
// get the properties in the type T
PropertyInfo[] candidates = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
// Find the match
foreach (PropertyInfo candidate in candidates)
if (candidate == property)
return GetMetaData<T>(candidate);
throw new Exception("Property not found.");
}
// Returns precomputed metadata
MyData GetMetaData<T>(PropertyInfo property) { ... }
As you would expect, it works when used as follows:
var data = PropertyInfo((Employee e) => e.Name);
But not when used in the following generic method:
void MyGenericMethod<T>(int id) where T : IEmployee
{
var data = PropertyInfo((T e) => e.Name);
}
It fails because the declaring type of property in the first method is now IEmployee, so the property in the lambda doesn't match the property in the type. How can I get them to match, without relying on the names of the properties? (There can be multiple properties with the same name if interfaces are implemented explicitly, so p1.Name == p2.Name won't cut it).
What you'd probably need is an InterfaceMapping. You can get that from the actual type by calling GetInterfaceMap(typeof(interface)), i.e.,
InterfaceMapping mapping = typeof(Employee).GetInterfaceMap(typeof(IEmployee));
Now, the mapping will contain the fields InterfaceMethods which will contain the methods you see when reflecting the interface, and TargetMethods which are the class's implementing methods. Note that this maps the the getter methods from the interface to the getter methods from the target class. You'll need to find the proper interface property by mapping the getter method of the various properties of the class to the found getter method.
Type interfaceType = typeof(IEmployee);
Type classType = typeof(Employee);
PropertyInfo nameProperty = interfaceType.GetProperty("Name");
MethodInfo nameGetter = nameProperty.GetGetMethod();
InterfaceMapping mapping = classType.GetInterfaceMap(interfaceType);
MethodInfo targetMethod = null;
for (int i = 0; i < mapping.InterfaceMethods.Length; i++)
{
if (mapping.InterfaceMethods[i] == nameGetter)
{
targetMethod = mapping.TargetMethods[i];
break;
}
}
PropertyInfo targetProperty = null;
foreach (PropertyInfo property in classType.GetProperties(
BindingFlags.Instance | BindingFlags.GetProperty |
BindingFlags.Public | BindingFlags.NonPublic)) // include non-public!
{
if (targetMethod == property.GetGetMethod(true)) // include non-public!
{
targetProperty = property;
break;
}
}
// targetProperty is the actual property
Caution: Note the use of BindingFlags.NonPublic and GetGetMethod(true) here, for accessing private members. If you've got an explicit interface implementation, there isn't really a public property matching the interface's property, instead there is a private property named Some.NameSpace.IEmployee.Name that is mapped (which is, of course, your explicit implementation).
When you've found the right property, you can just call
ParameterExpression p = Expression.Parameter("e", typeof(T));
Expression<Func<T, U>> lambda = Expression.Lambda<Func<T, U>>(
Expression.Property(p, targetProperty), p);
and you've got yourself a lambda expression that uses the class's properties rather than the interface's properties.
Does BindingFlags.FlattenHierarchy work? If not, you could always iterate through typeof(T).GetInterfaces and call GetProperties on each of them.
You'll need to get the member name from the lambda expression, and use reflection to get that member off of the type you've been given:
public static PropertyInfo PropInfo<TContainer, TMember>(
Expression<Func<TContainer, TMember>> memberGetter)
{
var memberName = GetExpressionMemberName(memberGetter);
return typeof(TContainer).GetProperty(memberName);
}
public static string GetExpressionMemberName<TContainer, TMember>(
Expression<Func<TContainer, TMember>> memberGetter)
{
var expressionType = memberGetter.Body.NodeType;
switch (expressionType)
{
case ExpressionType.MemberAccess:
{
var memberExpr = (MemberExpression) memberGetter.Body;
return memberExpr.Member.Name;
}
case ExpressionType.Convert:
{
var convertExpr = (UnaryExpression) memberGetter.Body;
var memberExpr = (MemberExpression) convertExpr.Operand;
return memberExpr.Member.Name;
}
default:
throw new InvalidOperationException("Expression {0} does not represent a simple member access.");
}
}
Here's proof that it works:
void Main()
{
Console.WriteLine(
MyGenericMethod<Employee>()
.GetGetMethod()
.Invoke(
new Employee {Name = "Bill"},
new object[] {}));
}
public class Employee : IEmployee {
public string Name {get;set;}
string IEmployee.Name { get { throw new Exception(); } }
}
public interface IEmployee {string Name {get;}}
public PropertyInfo MyGenericMethod<T>() where T : IEmployee
{
return PropInfo((T e) => e.Name);
}
Console output:
Bill

Get the name of a property by passing it to a method

StackOverflow user jolson had a very nice piece of code that exemplifies how one can register menthods without using strings, but expression trees here.
Is it possible to have something similar for properties instead of methods? To pass a property (not the name of the property) and inside the method to obtain the property name?
Something like this:
RegisterMethod(p => p.Name)
void RegisterMethod(Expression??? propertyExpression) where T : Property ???
{
string propName = propertyExpression.Name;
}
Thanks.
I posted a full example of this here (see also the post about "this" underneath it)
Note it deals with the LambdaExpression etc. As an update to the code as posted, you can add a bit more to make it easier to use in some scenarios:
static class MemberUtil<TType>
{
public static string MemberName<TResult>(Expression<Func<TType, TResult>> member)
{
return MemberUtil.MemberName<TType, TResult>(member);
}
}
Then you can use generic type-inference for the return value:
string test1 = MemberUtil<Foo>.MemberName(x => x.Bar);
string test2 = MemberUtil<Foo>.MemberName(x => x.Bloop());
You can write something along this:
static void RegisterMethod<TSelf, TProp> (Expression<Func<TSelf, TProp>> expression)
{
var member_expression = expression.Body as MemberExpression;
if (member_expression == null)
return;
var member = member_expression.Member;
if (member.MemberType != MemberTypes.Property)
return;
var property = member as PropertyInfo;
var name = property.Name;
// ...
}

Categories