Thursday, April 12, 2012

Calculated Fields In Dynamics CRM Read Optimized Forms

The latest rollup update introduced a new feature called Read Optimized Forms. This enables a read-only version of the entity forms that optimized for users that want to rapidly read data instead of editing them.

One of the pre-requisites in the current implementation is that the form should be devoid of all script customizations. If so, how would you work around a situation where the form requires values to be dynamically calculated.

One of the recommended approaches, as defined in the SDK, is to use a synchronous sandbox plugin running on the Retrieve message of the entity.

The following code snippet demonstrates this:

  1. protected void ExecuteDynamicCalculationPlugin(LocalPluginContext localContext)
  2. {
  3.     if (localContext == null)
  4.         throw new ArgumentNullException("localContext");
  5.  
  6.     //The OutputParameters property bag contains the result of the core operation.
  7.     Entity outEntity = localContext.PluginExecutionContext.OutputParameters["BusinessEntity"] as Entity;
  8.  
  9.     //Ensure values are valid to perform calculation
  10.     if (outEntity.Attributes.Contains("null_hours") &&
  11.         outEntity.Attributes.Contains("null_days"))
  12.     {
  13.         int hours = (int)outEntity.Attributes["null_hours"];
  14.         int days = (int)outEntity.Attributes["null_days"];
  15.  
  16.         outEntity.Attributes["null_hours"] = hours * days;
  17.     }
  18. }

crm2011 post event registration

And the plugin is registered as PostOutsideTransaction on the Retrieve event of the entity with the assembly under Sandbox isolation. This approach would also work on Online solutions as well.

Please beware of long running calculations as they are now being done synchronously as opposed to being done asynchronously through JavaScript.

No comments: