Avoid hardcoding - Early binding types in CRM 2011/2013 Plugins
Early bound classes will contains the objects of entities in
which it can be used to do the CRUD operation etc. in which it will give all
the attribute values as well. But however, if checking for entity.Attributes.Contains
like the below example, usually most of the developers uses hardcoding the
attribute schema names.
protected void ExecuteTestPlugin(LocalPluginContext localContext)
{
if (localContext == null)
{
throw new ArgumentNullException("localContext");
}
IPluginExecutionContext context = localContext.PluginExecutionContext;
IOrganizationService service = localContext.OrganizationService;
XrmServiceContext sContext = new XrmServiceContext (service);
Opportunity opportunity = ((Entity)context.InputParameters["Target"]).ToEntity< XrmServiceContext >();
if (pluginContext.MessageName.ToLowerInvariant() == "update")
{
if (opportunity.Attributes.Contains("name")
{
//To do Business logic
}
}
}
Instead of highlighted code, the hardcoded values can be
avoided by using the reflection concept as below.
Create a class which should have the following methods.
public class CommonFramework
{
public string ReflectionPropertyName<T>(Expression<Func<T>> expression)
{
MemberExpression member = (MemberExpression)expression.Body;
return member.Member.Name.ToLower();
}
}
Consume the above class in the highlighted area to avoid
hardcoding.
if (pluginContext.MessageName.ToLowerInvariant() == "update")
{
if (opportunity.Attributes.Contains(new CommonFramework().ReflectionPropertyName(()
=> opportunity.EstimatedCloseDate)))
{
//To do business logic
}
}
}
Happy Coding :)