Jean Paul's Blog

There are 2 types of People in the World, One who Likes SharePoint and..

    Advertisements
  • Microsoft MVP

  • MindCracker MVP

  • CodeProject MVP

  • eBook on SharePoint 2010

  • eBook on Design Patterns

  • eBook on Windows Azure

  • NLayers Framework @ CodePlex

  • MSDN Forums

  • .Net vs. Java

    Due to Public Demand
  • Advertisements

Archive for the ‘Reflection’ Category

Reflection–Copy Properties

Posted by Paul on November 22, 2011

Often in enterprise standard projects, we will be dealing with converting one entity into another.  Most of the cases the properties will be of same name and type.  In this case the following method is useful. 

The method saves the time of assigning each properties line by line.  Reflection is implemented to achieve this.

Reflection is upto 8 times slower than normal code but for a few dozen of entities the slowness does not arise.

 

  public static void CopyProperties(object source, object dest)
        {
System.Type type1 = source.GetType();
            System.Type type2 = dest.GetType();

            foreach (PropertyInfo pInfo1 in type1.GetProperties())
                foreach (PropertyInfo pInfo2 in type2.GetProperties())
                    if (pInfo1.Name == pInfo2.Name)
                    {
                        if (pInfo1.CanRead && pInfo2.CanWrite)
                            pInfo2.SetValue(dest, pInfo1.GetValue(source, null), null);
                        break;
                    }
        }

Usage:

public class Person
{
    public int Id
    {
        get;
        set;   
    }

    public string Name
    {
        get;
        set;   
    }
}

// Code

Person p1 = new Person ();

p1.Name = “Person Name”;

Person p2 = new Person();

CopyProperties(p1, p2);

Advertisements

Posted in C#, Reflection | Tagged: | Leave a Comment »

Reflection–Copy Properties

Posted by Paul on November 22, 2011

Often in enterprise standard projects, we will be dealing with converting one entity into another.  Most of the cases the properties will be of same name and type.  In this case the following method is useful. 

The method saves the time of assigning each properties line by line.  Reflection is implemented to achieve this.

Reflection is upto 8 times slower than normal code but for a few dozen of entities the slowness does not arise.

 

  public static void CopyProperties(object source, object dest)
        {
System.Type type1 = source.GetType();
            System.Type type2 = dest.GetType();

            foreach (PropertyInfo pInfo1 in type1.GetProperties())
                foreach (PropertyInfo pInfo2 in type2.GetProperties())
                    if (pInfo1.Name == pInfo2.Name)
                    {
                        if (pInfo1.CanRead && pInfo2.CanWrite)
                            pInfo2.SetValue(dest, pInfo1.GetValue(source, null), null);
                        break;
                    }
        }

Usage:

public class Person
{
    public int Id
    {
        get;
        set;   
    }

    public string Name
    {
        get;
        set;   
    }
}

// Code

Person p1 = new Person ();

p1.Name = “Person Name”;

Person p2 = new Person();

CopyProperties(p1, p2);

Posted in C#, Reflection | Tagged: | Leave a Comment »

Reflection Comparer in C#

Posted by Paul on December 30, 2010

I would like to share a piece of code that can save good amount of time.

Scenario

You are having a Customer class with properties Ag, Dob, Name which are int, datetime and string respectively.

The Customer objects are stored in a list and for custom sorting them based on different properties, we need to write code by implementing IComparer.  This could be a tedious task if lots of UI screens are there and you need to write specific code for each screen.  The problem is worse if you wanted to sort ascending/descending and based on multiple properties.

image

Solution

You can accomplish the above by using the following class which implements IComparer interface.

image

The above class ‘ReflectionComparer’ has constructor which takes the property on which the object to be sorted.

The constructor takes multiple property names so that we can sort on multiple items.  There is one overloaded constructor too, which takes the SortOrder (Ascending/Descending).

Invoking

You can just call the Sort method of the array/ArrayList and pass the instance of above class to it.

Eg: list.Sort(new ReflectionComparer("Age"));

ReflectionComparer Class Explained

It contains 2 constructors which are explained above.

There is one core method named Compare() which takes arguments x and y.

public int Compare(object x, object y)

For each objects passed – the corresponding CompareTo() method is called using Reflection.

The method GetMethodInfo() returns the “CompareTo” method info object.  Some optimizations were used there to reuse the same CompareTo() MethodInfo object to speed up the sorting process.

The method GetValue() returns the value of property to be compared.  Here also Reflection is the underlying mechanism.

Test Application

The attachment contains the test application which was created in Visual Studio 2008.  The test application provides us the UI to test various scenarios and their corresponding time taken for execution in seconds.

image

Summary

Eventhough Reflection comparison will be slower than normal comparisons, we can judiciously use the code above if the sorting speed is within our expectations.  The idea for the above comparer class is to minimize the coding effort on doing the comparison code infra.   In the above screen shot, 10 thousand records were sorted within 1 second in my computer having 3GHz speed.  Reflection is slower but your computer is many times faster than your requirement – then it is a right choice to use the code above.  Happy Coding.

Source

You can download the source from: www.c-sharpcorner.com rocks!!

Posted in Reflection | Tagged: , , , | Leave a Comment »

C# Generic Method for Parsing Value Types

Posted by Paul on October 8, 2010

In this article I am going to explain how to create a generic method named GetValue() that can parse int, float, long, double data types. The method would parse any value objects passed through it and prevents throwing errors in case of invalid data. When invalid data is passed the method will return the default value of type passed.

Code Detailed

The int, long, float and double data types contains TryParse() and Parse() methods in common which are static. Our GetValue() method takes the object to be parsed and identifies the return type through Generic Argument T.

In case of errors like the TryParse or Parse methods are missing in the type T, an exception is thrown. In case of errors data errors like argument is null or invalid data the default(T) would be returned.

public T GetValue<T>(object obj)
{
   
if (obj != null
)
    {
       
Type type = typeof
(T);
 
        T value =
default
(T);
       
var methodInfo = (from m in type.GetMethods(BindingFlags.Public | BindingFlags
.Static)
                         
where m.Name ==
"TryParse"
                          select
m).FirstOrDefault();
 
       
if (methodInfo == null
)
           
throw new ApplicationException("Unable to find TryParse method!");

        object result = methodInfo.Invoke(null, new object[] { obj, value });
       
if ((result != null) && ((bool
)result))
        {
            methodInfo = (
from m in type.GetMethods(BindingFlags.Public | BindingFlags
.Static)
                             
where m.Name ==
"Parse"
                              select m).FirstOrDefault();

            if (methodInfo == null)
               
throw new ApplicationException("Unable to find Parse method!");

            value = (T)methodInfo.Invoke(null, new object[] { obj });

            return (T)value;
        }
    }
 
   
return default
(T);
}

Invoking the Method

The following code can be used to invoke the above method:

int i = _util.GetValue<int>("123");

long j = _util.GetValue<long>("abcd");

float k = _util.GetValue<float>("100.01");

double l = _util.GetValue<double>("200.20");

Point of Note

.Net Reflection is used to implement this method. I would like to say that in case fast performance is required, this method is not advisable.

Posted in Reflection | Tagged: , , , | Leave a Comment »