Friday, February 20, 2009

Accessing Object's Properties at Run Time using .NET Reflection

Hi to All.

In my last project suddenly during design face I came across some what a different scenerio. It was something like that my UI Layer invoked Service Layer (generated by MS Software factory-Modeling E dition) which then invoked Business Layer.

Between UI and Service Layer I had Service object s (i-e Data contracts) and between Service and Business Layer there were business objects. The Problem was that there were some common fields in all of my service objects for audit purpose and I dind’t want to explicity set these fields for each insert and update operation from UI. Since the Service objects were actually Data contracts that were generated by a tool so I also didn’t want to alter the generated code because tool overrided the code each time someone regenerated the data contracts. I didn’t find any inheretance feature between data contracts so otherwise I would have gone for Base/Child pattern.

So what to do ?? I have objects that all are of different types and have common fields that needed to be set from a single location.

The Solution is .Net Reflection. Using reflection one can access objects properties and any other meta data information at run time yes right at run time.

Consider the code below it will tell you the whole story by itself.

public void AddAuditInformation(object entityObject, bool isNewRecord, int userID)

{

if (entityObject != null)

{

PropertyInfo propertyInfo = null;

//if entity is new. Mean we have to insert Createdby and Createddate fields as well.

if (isNewRecord)

{

propertyInfo = entityObject.GetType().GetProperty("CreatedBy");

propertyInfo.SetValue(entityObject, userID, null);

propertyInfo = entityObject.GetType().GetProperty("CreationDate");

propertyInfo.SetValue(entityObject, System.DateTime.Now, null);

}

propertyInfo = entityObject.GetType().GetProperty("LastUpdatedBy");

propertyInfo.SetValue(entityObject, userID, null);

propertyInfo = entityObject.GetType().GetProperty("LastUpdateDate");

propertyInfo.SetValue(entityObject, System.DateTime.Now, null);

}

}