Friday, April 27, 2012

How can I get a value of a property from an anonymous type (C#)

Last day I have faced a problem when working with  "Anonymous Type". In development procedure I have got  result from a service which return object made of anonymous type. The problem arise when I need to access property of anonymous type. After made some r&d I have got the solution. Now share with you ....

Solution 1: (use reflection to retrieve the values of the following anonymous type)


var obj = new { ClientId = 7, ClientName = "Ahsan", Jobs = 12,City="Dhaka" };
System.Type type = obj.GetType();
int clientid = (int)type.GetProperty("ClientId").GetValue(obj, null);
string clientname = (string)type.GetProperty("ClientName").GetValue(obj, null);
// clientname  return the result Ahsan

More generic solution:

public static T GetValueFromAnonymousType( object dataitem, string itemkey ) 
{
    System.Type type = dataitem.GetType();
    T itemvalue = (T)type.GetProperty(itemkey).GetValue(dataitem, null);
    return itemvalue;
}

Example:
 var obj = new { ClientId = 7, ClientName = "Ahsan", Jobs = 12,City="Dhaka" };
 string clientname = GetValueFromAnonymousType(obj, "ClientName");



Solution 2:

var obj = new { ClientId = 7, ClientName = "ACME Inc.", Jobs = 5 };
string clientname = TypeUtils.GetValueFromAnonymousType(obj, "ClientName");

var obj = new { ClientId = 7, ClientName = "ACME Inc.", Jobs = 5 };
Type t = obj.GetType();

//Then from that you look up a property:
PropertyInfo p = t.GetProperty("ClientName");

//Then from that you can get a value:
object v = p.GetValue(obj, null);

//This answer is long overdue for an update for C# 4:
dynamic d = obj;
object v = d.ClientName;

Hope that it may helpful for others.
Thanks

Monday, April 2, 2012

2012 Microsoft® MVP Award

Last night I have got this mail from Microsoft MVP award program manager.

“Dear Ahsan Murshed,

Congratulations! We are pleased to present you with the 2012 Microsoft® MVP Award! This award is given to exceptional technical community leaders who actively share their high quality, real world expertise with others. We appreciate your outstanding contributions in ASP.NET/IIS technical communities during the past year.”


Alhamdulillah,I am pleased to say that Microsoft has re-awarded me Microsoft MVP status again for 2012! This is my second consecutive MVP award, this year for Microsoft ASP.NET/IIS. I am really proud about this. This reward obviously motivated me to give more effort for community.

Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'

Exception: Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'...