GetPropertyValue<T>
Get the base value of CrmProperty object. This is used for interacting with DynamicEntity on Microsoft CRM.
Source
public static T GetPropertyValue<T>(this DynamicEntity entity, string propertyName)
{
// Retrieve the matching property.
object theProperty = entity.Properties.FirstOrDefault(i => i.Name.EqualsIgnoreCase(propertyName));
// If property not found, return the default value.
if (theProperty == null) return default(T);
object value = null;
string strPropertyType = theProperty.GetType().Name;
switch (strPropertyType)
{
case "KeyProperty":
value = ((KeyProperty)theProperty).Value.Value;
break;
case "StringProperty":
value = ((StringProperty)theProperty).Value;
break;
case "PicklistProperty":
if (typeof(T).Equals(typeof(string)))
value = ((PicklistProperty)theProperty).Value.name;
else if (typeof(T).Equals(typeof(int)))
value = ((PicklistProperty)theProperty).Value.Value;
break;
case "CrmBooleanProperty":
value = ((CrmBooleanProperty)theProperty).Value.Value;
break;
case "CrmDateTimeProperty":
value = ((CrmDateTimeProperty)theProperty).Value.Value;
break;
case "CrmDecimalProperty":
value = ((CrmDecimalProperty)theProperty).Value.Value;
break;
case "CrmFloatProperty":
value = ((CrmFloatProperty)theProperty).Value.Value;
break;
case "CrmMoneyProperty":
value = ((CrmMoneyProperty)theProperty).Value.Value;
break;
case "CrmNumberProperty":
value = ((CrmNumberProperty)theProperty).Value.Value;
break;
case "LookupProperty":
if (typeof(T).Equals(typeof(string)))
value = ((LookupProperty)theProperty).Value.name;
else if (typeof(T).Equals(typeof(Guid)))
value = ((LookupProperty)theProperty).Value.Value;
break;
case "CustomerProperty":
if (typeof(T).Equals(typeof(string)))
value = ((CustomerProperty)theProperty).Value.name;
else if (typeof(T).Equals(typeof(Guid)))
value = ((CustomerProperty)theProperty).Value.Value;
break;
case "StatusProperty":
if (typeof(T).Equals(typeof(string)))
value = ((StatusProperty)theProperty).Value.name;
else if (typeof(T).Equals(typeof(Guid)))
value = ((StatusProperty)theProperty).Value.Value;
break;
case "StateProperty":
value = ((StateProperty)theProperty).Value;
break;
case "EntityNameReferenceProperty":
value = ((EntityNameReferenceProperty)theProperty).Value.Value;
break;
}
try
{
if (value != null)
{
return (T)value;
}
}
catch
{ }
return default(T);
}
Example
var dynamicContact = ...;
dynamicContact.GetPropertyValue<string>("firstname");
// Will retrieve the user id that modified this record last.
dynamicContact.GetPropertyValue<Guid>("modifiedby");
// Will retrieve the username that modified this record last.
dynamicContact.GetPropertyValue<string>("modifiedby");
Author: Dimaz Pramudya
Submitted on: 20 dec. 2009
Language: C#
Type: Microsoft.Crm.Sdk.DynamicEntity
Views: 4906