Using early bounds in plugin for multiple entities

Recently I was caught up in the discussion about early bound entities and late bound entities. One of the argument of the “late bound supporters” was the fact, that using late-bound allows reusing the same plugin for multiple entities (so for example create a plugin that runs for all activities or a common plugin for leads/opportunities/accounts). This argument is not valid, I will show you how to write a clean code, that uses modern approach for coding and is perfectly testable.

Let’s start with the late bound version of the plugin to give you an idea what are we trying to achieve here:


public class CalculateTotalAmountLateBoundPlugin : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
var context = serviceProvider.GetService(typeof(IPluginExecutionContext)) as IPluginExecutionContext;
var serviceFactory = serviceProvider.GetService(typeof(IOrganizationServiceFactory)) as IOrganizationServiceFactory;
var service = serviceFactory.CreateOrganizationService(context.UserId);
var lateBoundEntity = context.InputParameters["Target"] as Entity;
lateBoundEntity["new_totalsum"] = lateBoundEntity.GetAttributeValue<decimal>("new_netamount") + lateBoundEntity.GetAttributeValue<decimal>("new_margin");
}
}

The plugin simply adds values of “new_netamount” and “new_margin” fields on the entity and sets field “new_totalsum” to a resulting value. Of course this can be simply achieved by using calculated field, but I just want to show the basic idea here, real world scenario is usually much more complicated.

If we register this field on pre-update of any entity containing field “new_totalsum”, “new_netamount” and “new_margin” it would basically do its job. If you are not an experienced CRM Developer, who remembers CRM 3.0 or 4.0, just an ordinary .NET Developer, you would probably say, that this code looks ugly. It’s almost like it was taken from some JavaScript library – where are all the types, what is the type of “new_totalsum”, which year is that, are we still in 2017? And yes, you’ll be right – this code simply looks awful, does not allow to use any of great refactoring tools, because it uses some “magic” dictionaries and keys and without access to CRM you would not even have a clue, what are the proper types of the properties. It’s exactly the same story as with ORM – who of us still uses plain ADO .NET and not, for example, Entity Framework? Such approach is much less error prone, testable and also much more friendly for CRM newbies. Code using early bounds may look like that:


public class CalculateTotalAmountAccountPlugin : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
var context = serviceProvider.GetService(typeof(IPluginExecutionContext)) as IPluginExecutionContext;
var serviceFactory = serviceProvider.GetService(typeof(IOrganizationServiceFactory)) as IOrganizationServiceFactory;
var service = serviceFactory.CreateOrganizationService(context.UserId);
var account = (context.InputParameters["Target"] as Entity).ToEntity<Account>();
account.new_totalsum = account.new_netamount + account.new_margin;
}
}

Now it’s much better, but there is a significant problem with this code. We assumed that our plugin runs on Account entity. What if we will register it on Contact entity? Well, it will simply crash when we will try to convert our target!

So the basic approach would be to create a switch statement and simply check the entity type:


public class CalculateTotalAmountEarlyBoundBADPlugin : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
var context = serviceProvider.GetService(typeof(IPluginExecutionContext)) as IPluginExecutionContext;
var serviceFactory = serviceProvider.GetService(typeof(IOrganizationServiceFactory)) as IOrganizationServiceFactory;
var service = serviceFactory.CreateOrganizationService(context.UserId);
var lateBoundEntity = context.InputParameters["Target"] as Entity;
switch (lateBoundEntity.LogicalName)
{
case Account.EntityLogicalName:
var account = lateBoundEntity.ToEntity<Account>();
account.new_totalsum = account.new_netamount + account.new_margin;
break;
case Opportunity.EntityLogicalName:
var opportunity = lateBoundEntity.ToEntity<Opportunity>();
opportunity.new_totalsum = opportunity.new_netamount + opportunity.new_margin;
break;
default:
break;
}
}
}

Ok so now we can register the plugin on multiple entities, but our code looks even worse than the first version, because we have a lot of code that is copy-pasted. Imagine that the operation would be much more complex and would change frequently in time – we would have to change all the switch statements every time.

To overcome this problem we will take advantage of the fact that all early-bound classes are partial, so they can implement any interface we want. Let’s create such interface and some helper partial classes:


interface IEntityWithTotalSum
{
decimal new_totalsum { get; set; }
decimal new_netamount { get; set; }
decimal new_margin { get; set; }
}


public partial class Account : IEntityWithTotalSum {}
public partial class Opportunity : IEntityWithTotalSum {}

It would be great if we could use this like that:


public void Execute(IServiceProvider serviceProvider)
{
var context = serviceProvider.GetService(typeof(IPluginExecutionContext)) as IPluginExecutionContext;
var serviceFactory = serviceProvider.GetService(typeof(IOrganizationServiceFactory)) as IOrganizationServiceFactory;
var service = serviceFactory.CreateOrganizationService(context.UserId);
var entityWithTotalSum = context.InputParameters["Target"] as IEntityWithTotalSum;
entityWithTotalSum.new_totalsum = entityWithTotalSum.new_netamount + entityWithTotalSum.new_margin;
}

But unfortunately, our “Target” is an entity and we have to somehow convert it to an early bound. I developed a simple utility class that is capable of that:


public static class Extensions
{
public static T Mock<T>(this Entity entity)
{
return InterfaceMocker.Mock<T>(entity);
}
}

view raw

Extensions.cs

hosted with ❤ by GitHub


static class InterfaceMocker
{
public static T Mock<T>(Entity entity)
{
var type = ProxyTypesCache.GetProxyType(entity.LogicalName);
var copy = Activator.CreateInstance(type);
(copy as Entity).Attributes = entity.Attributes;
(copy as Entity).Id = entity.Id;
if (typeof(T).IsAssignableFrom(type))
{
return (T)copy;
}
else
{
throw new InvalidPluginExecutionException("Cannot mock interface. Target type does not implement interface " + typeof(T).Name);
}
}
}


static class ProxyTypesCache
{
private static Dictionary<string, Type> cachedTypes = new Dictionary<string, Type>();
static ProxyTypesCache()
{
var assembly = System.Reflection.Assembly.GetExecutingAssembly();
var allTypes = assembly.GetExportedTypes();
foreach (var type in allTypes)
{
if (typeof(Entity).IsAssignableFrom(type))
{
cachedTypes.Add(type.GetCustomAttribute<EntityLogicalNameAttribute>().LogicalName, type);
}
}
}
public static Type GetProxyType(string logicalName)
{
return cachedTypes[logicalName];
}
}

Simple explanation of the code – during first execution of the plugin, all the early-bound types are cached in a dictionary, that can be later fast accessed from the code (in this case it’s InterfaceMocker). It simply instantiates the early-bound and copies all attributes inside. There is also an extension method that simplifies the usage for Entity. Now our plugin can simply look like that:


public void Execute(IServiceProvider serviceProvider)
{
var context = serviceProvider.GetService(typeof(IPluginExecutionContext)) as IPluginExecutionContext;
var serviceFactory = serviceProvider.GetService(typeof(IOrganizationServiceFactory)) as IOrganizationServiceFactory;
var service = serviceFactory.CreateOrganizationService(context.UserId);
var earlyBound = (context.InputParameters["Target"] as Entity).Mock<IEntityWithTotalSum>();
earlyBound.new_totalsum = earlyBound.new_netamount + earlyBound.new_margin;
}

And that’s it! This code looks much better then late bound version, provides type-checking for entity attributes and also is very nice when we implement unit tests, as we have an interface to test, not a full early-bound. If our logic is more complex we can create some additional classes that will be dependent upon IEntityWithTotalSum interface, not Account or Opportunity entity.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s