Showing posts with label Extension Method. Show all posts
Showing posts with label Extension Method. Show all posts

Wednesday, October 19, 2016

Converting Object Specific Properties to IDictionary<string, Object> Using Lambda Expression

Below function will convert the specific properties of any class to IDictionary<string, object>

The function is  an extension method for object type and takes params array of Expression<Func<T, object>>. The reason for outputting object in Func is to output any primary type such int, long, string, float and etc.

Registration Example Class



public class Registration 
{
        public int RegId {get; set;}
        public string RegName {get; set;}
        public string RegNotRequired {get; set;}
        public DateTime RegDate {get; set;}
        public string RegLocation {get; set;}
}


Example



Registration reg = new Registration 
                            {RegId = 1,
                             RegName = "Murtaza", 
                             RegNotRequired="Not Important", 
                             RegDate="2012-09-19", 
                             RegLocation ="Pakistan"};
IDictionary<string, object> val = reg.AsKeyAndValue(
                                      r => r.RegId, r => r.RegName, 
                                      r => r.RegDate, r => r.RegLocation);




Extension Method


Following function converts the class properties into IDictionary<string, object>


  public static IDictionary<string,object> AsObjectValueDictionary(this T obj,
            params Expression<func<object,string>>[] source)
        {
            Dictionary objectValyeDictionary = new Dictionary();
            foreach (var src in source)
            {
                var keyValue = obj.AsKeyValuePair(src);
                if(!objectValyeDictionary.ContainsKey(keyValue.Key))
                    objectValyeDictionary.Add(keyValue.Key, keyValue.Value);
            }

            return objectValyeDictionary;
        }

Helper Fucntion For Property Name


The below helper method is use to extract the property name from lambda expression


        public static KeyValuePair AsKeyValuePair(this object obj, Expression<func<object, tproperty>> propertyLambda)
        {
            var me = propertyLambda.Body as MemberExpression;
            UnaryExpression ue;
            if (me == null)
            {
                ue = propertyLambda.Body as UnaryExpression;

                if(ue == null)
                    throw new ArgumentException("You must pass a lambda of the form: '() => Class.Property' or '() => object.Property'");

                me = (MemberExpression) ue.Operand;
            }

            string memberName = me.Member.Name;
            var value = obj.GetType().GetProperty(memberName).GetValue(obj, null);
            return new KeyValuePair(me.Member.Name, value);
        }

Thursday, July 7, 2011

Request.QueryString Extension Method

Below are two extension methods that I have created for Request.QueryString.. as I am passing many parameters and playing with querystring a lot and every where i had to put IF condition for null and other things..

In order save myself from checking and validating again and again i have designed these two extension Method using some help from internet to save time and reduce number of lines of code.. kindly check them and you are welcome to criticize in constructive way.

I have some more functions in my mind to overload for Request.QueryString and will add later As following two functions have fulfilled my need

How to use..
byte? valueByte  
Guid? valueGuid

//check if "Server" key exits if yes then return value else return default value of null that we have passed

valueByte = Request.QueryString.GetValue<byte?>(Constants.FilterServer, null);
valueGuid = Request.QueryString.GetValue<Guid?>(Constants.FilterGuid, null);

//checks if "Server" Key exists then out value to provided variable and return true to if condition, else return false and assign default value to provided out variable
if(Request.TryParse<byte?>(Constants.FilterServer, null, out valueByte)){}

if(Request.TryParse<Guid?>(Constants.FilterGuid, null, out valueGuid)){}



public static T GetValue<T>(this NameValueCollection collection, string key, T defaultValue)
{
if (collection == null)
{
throw new ArgumentNullException("collection");
}
var value = collection[key];
if (value == null) { return defaultValue; }
var converter = TypeDescriptor.GetConverter(typeof(T));
if (!converter.CanConvertFrom(typeof(string))) {
throw new ArgumentException(String.Format("Cannot convert ' {0} ' to {1} ", value, typeof(string))); }
return (T)converter.ConvertFrom(value); }


public static bool TryParse<T>(this NameValueCollection collection, string key, T defaultValue, out T returnValue)
{
returnValue = default(T);
try
{ if (collection == null) {
throw new ArgumentNullException("collection"); }
var value = collection[key];
if (value == null)
{ return false;}
var converter = TypeDescriptor.GetConverter(typeof(T)); if (!converter.CanConvertFrom(typeof(string)))
{ throw new ArgumentException(String.Format("Cannot convert ' {0}' to {1} ", value, typeof(string))); }
returnValue = (T)converter.ConvertFrom(value);
return true; }
catch (ArgumentNullException ex) { return false;}
catch (ArgumentException ex) { return false;}
catch (NotSupportedException ex) {return false;} }