Tuesday, 28 April 2015

Plug-ins vs. Workflows in Microsoft Dynamics CRM


Both workflows and plug-ins can attach to exactly the same events. Well, plug-ins have available a couple of more events but essentially both work on top of the same event model.Remember also that workflows always run asynchronous and hence, the Asynchronous Processing Service must be running on the server in order to run.
 
Workflows are more suitable if:
 
  • you want to achieve simple tasks faster, such as sending an e-mail or creating / updating assigning records. These actions can be set up very quickly with a workflow without any need of writing code.
  • you want to easily scale things to managers (if they were setup for user records), as it is possible to assign records to them.
  • you want to allow an advanced user to make changes to logic. As using the integrated workflow designer is user-friendly, an advanced user would be able to edit an existing workflow and change some rules according to business changes.
  • the logic should be available to be run on demand. I mean, when you are within an entity and navigates to “workflows” option in the left pane, all workflows marked as available to run on demand can be executed making them independent of an event trigger.
  • you want to send emails making use of templates and attaching files.
Workflows also allow running child workflows which may make a lot of sense in some scenarios. Nevertheless, be careful if you need the child workflow results in order to make decisions on your main workflow, as child workflows always run asynchronous, which means that it will trigger the child workflow and continue. If you need your primary workflow to wait until child ends, you will need to write a custom activity.
 
 plug-ins are more suitable if:
  • you need to manipulate data before is saved.
  • you need to make validations before submitting the operation.
  • you want to be able to cancel an operation based on your validations.
  • immediate response to the user is needed.
  • you need retrieve values and/or take actions after operation has been completed (i.e. getting and autogenerated id)
It is important to note that since Dynamics CRM 4, plug-ins can also be configured to run asynchronous (Mode attribute while registering plug-in). Nevertheless, pre-event asynchronous plug-ins are not supported. In this case, you will have to set it up as synchronous mode.
 
Another important thing about plug-ins is the Deployment option which says if the plug-in is going to be executed on the server and/or Outlook client. If both executions are set up and client goes offline and online, plug-in calls are triggered after synchronization so be prepared in this case to execute your code twice!

Regarding to security:
Workflows triggered automatically will run under the security context of the workflow owner. On the contrary, if executed on demand, the security context of the user who executed the workflow will be used. 
Plug-ins execute under the security context of the CRM Web application pool identity (typically NETWORK SERVICE). As this account typically maps to generic CRM SYSTEM user this typically works fine.
 
However, within plug-ins you can make use of impersonation to work under the credentials of the user who is making the request. For doing so, you just need to pass True to the CreatCrmService method under the context object.If you need to always impersonate with a specific user, you can do that by passing True as above and setting impersonatinguserid attribute while registering the plug-in.It is important to know that plug-in impersonation does not work offline. The logged on user credentials are always used in this case.

Dynamics CRM Plugin Stages

Pipeline stages
The event pipeline is divided into multiple stages, of which 4 are available to register custom developed or 3rd party plug-ins. Multiple plug-ins that are registered in each stage can be further be ordered (ranked) within that stage during plug-in registration.
 
 • PreEvent
              • Stage :10
               • Stage Name: Pre-validation
 
Stage in the pipeline for plug-ins that are to execute before the main system operation. Plug-ins registered in this stage may execute outside the database transaction.
The pre-validation stage occurs prior to security checks being performed to verify the calling or logged on user has the correct permissions to perform the intended operation.

 • PreEvent

              • Stage :20
               • Stage Name: Pre-operation
Stage in the pipeline for plug-ins that are to execute before the main system operation. Plug-ins registered in this stage are executed within the database transaction.
 
 • Platform Core Operation
              • Stage :30
               • Stage Name: MainOperation
In-transaction main operation of the system, such as create, update, delete, and so on. No custom plug-ins can be registered in this stage. For internal use only.
 
 • Post-Event
              • Stage :40
               • Stage Name: Post-operation

Stage in the pipeline for plug-ins which are to execute after the main operation. Plug-ins registered in this stage are executed within the database transaction.
 

Message processing
Whenever application code or a workflow invokes a Microsoft Dynamics CRM Web service method, a state change in the system occurs that raises an event. The information passed as a parameter to the Web service method is internally packaged up into a OrganizationRequest message and processed by the pipeline. The information in the OrganizationRequest message is passed to the first plug-in registered for that event where it can be read or modified before being passed to the next registered plug-in for that event and so on. Plug-ins receive the message information in the form of context that is passed to their Execute method. The message is also passed to the platform core operation.

Plug-in registration
Plug-ins can be registered to execute before or after the core platform operation. Pre-event registered plug-ins receive the OrganizationRequest message first and can modify the message information before the message is passed to the core operation. After the core platform operation has completed, the message is then known as the OrganizationResponse. The response is passed to the registered post-event plug-ins. Post-event plug-ins have the opportunity to modify the message before a copy of the response is passed to any registered asynchronous plug-ins. Finally, the response is returned to the application or workflow that invoked the original Web service method call.

Because a single Microsoft Dynamics CRM server can host more than one organization, the execution pipeline is organization specific. There is a virtual pipeline for every organization. Plug-ins registered with the pipeline can only process business data for a single organization. A plug-in that is designed to work with multiple organizations must be registered with each organization's execution pipeline.
 






 

CRM Javascript Model

In this section of The CRM Book, we’ll go over the JavaScript CRM model. Microsoft Dynamics CRM uses the XRM Page Hierarchy JavaScript model as displayed below.


Prior to the introduction of this model in Dynamics CRM 2011, Microsoft Dynamics CRM 4.0 used the crmForm object to provide access to form fields. The crmForm object is deprecated in Microsoft Dynamics CRM 2011. Scripts that use the crmForm object will continue to work in Microsoft Dynamics CRM 2011 to support backward compatibility, but the new capabilities in Microsoft Dynamics CRM cannot be achieved by using the crmForm object. Please refer to the section of the book on JavaScript best practices for more information on this topic.
The Xrm.Page object serves as a namespace object to consolidate three objects on the form:
  • Xrm.Page.context Xrm.Page.context provides methods to retrieve information specific to an organization, a user, or parameters that were passed to the form in a query string.
  • Xrm.Page.data.entity: Xrm.Page.data provides an entity object that provides collections and methods to manage data within the entity form.
  • Xrm.Page.ui: Xrm.Page.ui provides collections and methods to manage the user interface of the form.

Collections

Below are the Xrm.Page object model collections.
  • Attributes: The Xrm.Page.data.entity.attributes Collection provides access to each entity attribute that is available on the form. Only those attributes that correspond to fields added to the form are available.
  • Controls: Three objects contain a controls collection:
    • ui.controls:  The Xrm.Page.ui.controls Collection provides access to each control present on the form.
    • attribute.controls: Because an attribute may have more than one control on the form, this collection provides access to each of them. This collection will contain only one item unless multiple controls for the attribute are added to the form.
    • section.controls: This collection only contains the controls found in the section.
  • Navigation.items:  The Xrm.Page.ui.navigation.items Collection provides access to navigation items that are visible on the left side of the form.
  • FormSelector.items:  When multiple forms are provided for an entity, you can associate each form with security roles. When the security roles associated with a user enable them to see more than one form, the Xrm.Page.ui.formSelector.Xrm.Page.ui.formSelector.items Collection provides access to each form definition available to that user.
  • Tabs: You can organize each form by using one or more tabs. The Xrm.Page.ui.tabs Collection provides access to each of these tabs.
  • Sections: You can organize each form tab by using one or more sections. The tab Xrm.Page.ui tab.sections Collection provides access to each of these sections.
Each object possesses several methods to retrieve data, get or set object properties, or perform actions. Generally speaking for majority of use cases a subset of methods utilizing these model hierarchy is utilized.  Given below are examples of some common methods that utilize the methods in this model.

Xrm.Page.context

Xrm.Page.context provides methods to retrieve information specific to an organization, a user, or parameters that were passed to the form in a query string. Some of the common methods used are:
  • getOrgUniqueName: Returns the unique text value of the organizations name.
    • var OrganizationUniqueName = context.getContext().getOrgUniqueName();
  • getClientUrl: Returns the base server URL. When a user is working offline with Microsoft Dynamics CRM for Microsoft Office Outlook, the URL is to the local Microsoft Dynamics CRM Web services.
  • getUserId: Returns the GUID value of the SystemUser.id value for the current user.
    • var userGUID = context.getContext().getUserId();
  • getUserRoles: Returns an array of strings representing the GUID values of each of the security roles that the user is associated with.
    • var currentUserRoles = Xrm.Page.context.getUserRoles();

Xrm.Page.data.entity

The Xrm.Page.data.entity Attribute Methods are frequently used to get and set propertied of various attributes on the form.  Few examples of the methods commonly used are:
  • Get the value from a CRM field
    • var varMyValue = Xrm.Page.getAttribute(“CRMFieldSchemaName”).getValue() ;
  • Set the value of a CRM field
    • Xrm.Page.getAttribute(“po_CRMFieldSchemaName”).setValue(‘My New Value’);
  • Get the selected value of an optionset
    • Xrm.Page.getAttribute(“CRMFieldSchemaName”).getSelectedOption().text;
  • Set the requirement level
    • Xrm.Page.getAttribute(“CRMFieldSchemaName”).setRequiredLevel(“none”);
    • Xrm.Page.getAttribute(“CRMFieldSchemaName”).setRequiredLevel(“required”);
    • Xrm.Page.getAttribute(“CRMFieldSchemaName”).setRequiredLevel(“recommended”);

Xrm.Page.ui

Xrm.Page.ui contains methods to retrieve information about the user interface as well as collections for several subcomponents of the form. Xrm.Page.ui provides access to the following collections:
  • Xrm.Page.ui.controls Collection: A collection of all the controls on the page. Given below are examples of common methods used in this collction:
    • Xrm.Page.ui.controls.get(“po_assignedtoteam”).setVisible(true); // Sets the field “po_assignedtoteam” to visible on the form
    • Xrm.Page.ui.controls.get(“po_assignedtoteam”).setDisabled(true); // Disables the field “po_assignedtoteam” on the form
  • Xrm.Page.ui.navigation.items Collection: Xrm.Page.ui.navigation.items does not contain any methods. Provides access to navigation items through the items collection
  • Xrm.Page.ui.formSelector: A common method used in this collection is the method to get the type of form currently in use as the example below illustrates:
    function checkFormType() {
    var formType = Xrm.Page.ui.getFormType();
    if (formType == 2) {
    // Code to execute some logic
    }
    }
  • Xrm.Page.ui.tabs Collection: A collection of all the tabs on the page. Some of most common examples are to use methods in this collection to hide/unhide tabs and sections within a tab. Here are few examples:
    • Xrm.Page.ui.tabs.get(“Financial Services”).setVisible(false);  // Hides the “Financial Service” tab
    • Xrm.Page.ui.tabs.get(“Territory-Info”).sections.get(“TerritoryChangeType”).setVisible(true); // Sets the section “TerritoryChangeType” to visible