CRM Plugins – Input Parameters and Early Binding

I recently came across this problem looking at a CRM instance that had been upgraded to use early-binding. They had done something like below:

var accountInputParameters = ((Entity)context.InputParameters["Target"]).ToEntity<Account>();

This takes the InputParameters (which is of type Entity) and then bound it to the Account early-bound type.

While this seems like a good idea on the surface, as it allows all the fields of the Account to be accessed using strongly typed properties, the customer reported some strange behaviour on their Accounts.

The customer was using the Input Parameters to do some checks on Account Number and generate a new Account Number if necessary:

var accountInputParameters = ((Entity)context.InputParameters["Target"]).ToEntity<Account>();
if (string.IsNullOrEmpty(accountInputParameters.AccountNumber))
  // Generate an Account Number

This worked fine for the Create plugin; however, when they tried to use the same code for Update plugin message they started noticing that when updating their Accounts new Account Numbers were being generated each time.

The Input Parameters will only contain fields that have changed. This means that potentially the Account Number field won’t be included, but the accountInputParameters.AccountNumber will default the value to an empty string.

In the example above, it will mean that a new Account Number would be generated for an Account that could already have one.

You can continue to use early-binding, but you need to check whether the entity contains the attribute:

var accountInputParameters = ((Entity)context.InputParameters["Target"]).ToEntity<Account>();
if (accountInputParameters.Contains("accountnumber"))
  // Account has been saved and the Account Number is included in those changes

  if (string.IsNullOrEmpty(accountInputParameters.AccountNumber))
    // Account number has been explicitly set to null in CRM. Need to act on this
    // for example: generate an Account Number

For me, this detracts a little from the benefits of early-binding, as I have to use the Contains method to determine whether Account Number exists and to do that I need to know the schema-name of the Account Number field


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 )

Google+ photo

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

Connecting to %s