Archive for May, 2009

How to get property Name using Expression Tree

recently during some dynamic work in ado.net Entity framework i came across a problem…

suppose here is our class

public class User
{
    #region View Properties
    public long Id { get; set; }
    public String Email { get; set; }
    #endregion
}

 

now an instance of our class is always persisted in a Store… and at some point say when system updates the value of User we need to run some custom validation rules and if a property doesn’t comply we need to revert its value to older one….

public static class Store
{
    public static string GetPreviousValue(this class classobject,propertyname)
    {
        //Do something
    }
}

 

but you want to specify something like (don’t confuse i am using here)

userinstance.Email = this.GetPreviousValue(userinstance.Email);
Since Email is a property name it will return value of Email field but we want the property name not the value how this will be done…..
we don’t want to hard code the property names.. so what next…. ummm Reflection?? again a NO because through reflection we will be able to only iterate properties with there names but we don’t know which property is our required one……
 
public static string GetPropertyName()
{
PropertyInfo[] properties = this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
 for (int i = 0; i < properties.Length; i++)
    {
        object propValue = properties[i].GetValue(this, null);
        if (object.ReferenceEquals(propValue,value))     
           {
            return properties[i].Name;
            }
    }
return null;
}
one thing its not a good approach 2ndly it will fail in case if a class has more than one same value…. so this is so dead….
what next well after going through a lot i found some thing very interesting using (as it came up in 3.5)
public class TypeOf<T>
    {
        public static string Property<TProp>(Expression<Func<T, TProp>> expression)
        {
            var body = expression.Body as MemberExpression;
            if (body == null) throw new ArgumentException("'expression' should be a member expression");
            return body.Member.Name;
        }
    }

 

and with this it works like a charm…

var propName = Nameof<SampleClass>.Property(e => e.Email);
userinstance.Email= propName;

Shout it kick it on DotNetKicks.com

1 Comment

New Version of Ajax Control Toolkit

A new version of Ajax Control toolkit has been released and is now available for download on Codeplex.
This release includes three newer controls:
  • HTML Editor
  • Combo Box (behaves like windows Combo)
  • Color Picker

This release also includes a good amount of fixes and has decreased the need for script files.

The ASP.NET website has been updated with new videos and tutorials for these controls.

kick it on DotNetKicks.com

Shout it

Leave a comment