HTML Dropdown

Thursday, 7 April 2016

Best Practices of WorkFlows in CRM


Avoid infinite loops


It’s possible to create logic in a workflow that initiates an infinite loop, which consumes server resources and affects performance. The typical situation where an infinite loop might occur is if you have a workflow configured to start when an attribute is updated and then updates that attribute in the logic of the workflow. The update action triggers the same workflow that updates the record and triggers the workflow again and again.

Microsoft Dynamics CRM includes logic to detect and stop infinite loops. If a workflow process is run more than a certain number of times on a specific record in a short period of time, the process fails with the following error: This workflow job was canceled because the workflow that started it included an infinite loop. Correct the workflow logic and try again. For Microsoft Dynamics CRM Online the limit of times is 16. For on-premises deployments of CRM, the limit is 8.

Use workflow templates


If you have workflows that are similar and you anticipate creating more workflows that follow the same pattern, save your workflow as a workflow template. This way, the next time you need to create a similar workflow, create the workflow using the template and avoid entering all the conditions and actions from scratch.

In the Create Process dialog, choose New  process from an existing template (select from list).

Use child workflows


If you apply the same logic in different workflows or in conditional branches, define that logic as a child workflow so you don’t have to replicate that logic manually in each workflow or conditional branch. This helps make your workflows easier to maintain. Instead of examining many workflows that may apply the same logic, you can just update one workflow.

Keep fewer logs and Purge Log Files


To save disk space, clear the Keep logs for workflow jobs that encounter errors check box if you don’t need to keep this data.

Log files created by workflows take up significant space. Purge all log files in the production that are not absolutely needed. It is ok to keep them in development for testing purposes.

To set the Purge function:

1.       Click on the Administration tab

2.       Set the Check Box called “Automatically delete completed workflow jobs(to save disk space)”.

3.       Save

4.       Activate




Minimize Wait State

Every workflow that is waiting for an event to occur takes processor time. Limit the number of workflows that must wait for something to occur. If you must wait for x days and there is possibility of the condition being met sooner, code the workflow to wake up and check more frequently.

Example: Original workflow is “Wait for 3 days on a case and wake up. If the Status is ‘In Process’, then escalate”.

Code the logic this way to reduce the number of cases in wait state:

Wait 1 day: If the status is not “In Process”, then end.

Wait 1 day: If the status is not “In Process”, then end.

Wait 1 day: If the status is not “In Process”, then escalate.

Keep Logic Flat and End Quickly

You cannot copy and paste or move code blocks within workflows to keep your nesting logic to minimum.

End the workflow as soon as possible. If you have large block of nested logic consider doing checks at the beginning to see if you can quit the workflow.

 
Use Notes to keep track of changes

When you edit workflows you should use the Notes tab and type what you did and why you did it. This allows someone else to understand the changes you made.

Awareness of persistence points in workflow definitions.

If you have a long workflow that might take a long time to execute you will need to consider whether the workflow will persist and what that implies. A workflow can be persisted because of multiple reasons: The workflow instance is waiting for some event to occur, the CrmAsyncService is stopped or the workflow instance explicitly requests to be persisted by executing an activity with the PersistOnCloseAttribute. In any case, the workflow engine unloads the workflow instance and persists it to the database until a user manually resumes the workflow or an event occurs which resumes the workflow automatically. The important considerations are

1)      At what point does the workflow persist? The workflow will persist up to the step when the last activity is marked as a persistence point. Therefore, when it resumes, it will re-execute all the steps after the last persistence point. This is important if you have logic in your workflow which you want to guarantee does not execute more than once. Note that workflow instances are automatically persisted after the following CRM steps: create, update, send email, send email from template, assign, change status, child workflow and stage. For custom activities you can add [PersistOnClose] attribute to the activity class. (see http://msdn.microsoft.com/en-us/library/system.workflow.componentmodel.persistoncloseattribute.aspx).

2)       When is the workflow going to resume? If the workflow will wait on an event that might never happen or take years to occur, then the database will soon contain thousands of waiting workflows which could affect performance. You should consider a design in which this situation is minimized. For example a workflow that waits on an opportunity to be marked as “won” can wait forever and the condition never meets. Instead wait on the opportunity to be closed and then check the status reason once it is marked as closed; if it was not marked as “won” you might want to add a Stop Workflow step at that point.

Write "atomic" custom activities

Custom workflow activities should not implement the entire logic of the workflow, they are ideally small "atomic" steps that will make part of larger workflows. Because custom activities don’t have the ability to control persistence, they should never cause the workflow to go idle or persist in the middle of a custom activity. Generally, it is better to have multiple custom activities that are called in sequence from a parent workflow than one large custom activity that implements all the logic in sequence. This also follows from the principle of workflow as a composition pattern. For example if your process is to take custom actions A, B and C when an account is opened, it is generally better to write a custom activity for each A, B and C separately and add a step for each activity in your workflow as opposed to writing a custom activity that implements A, B and C sequentially and then add a single step to the workflow to include this custom activity.

Correct use of "Execution Time".

The CRM workflow designer provides a property called "Execution Time" which can be used in dynamic expressions such as "if Account (Created On) + 10 days < workflow (Execution Time)".

- Create task X

- Wait until task X is completed

- Send email to you with subject = "Task completed on: " {workflow (Execution Time)}.

 The meaning of this property is neither the time at which the workflow is published nor the time the workflow instance starts. The actual value of this property is the real time when the workflow evaluates an expression that contains this property. Therefore, expressions such as "Wait until 1 day after workflow (Execution Time)" will never succeed and the workflow will wait and resume once a day forever causing performance problems. If you want your workflow to wait for a specific amount of time you should use the wait step and configure the condition as: workflow – timeout – equals – {Duration}. This will unload the workflow and resume execution after the specified time duration has passed.

 Naming Conventions

Required: Entity – the entity name you are creating against which workflow will run.

Example: All account workflows should start with “Account” in the name.

Optional: Group – used to group related logic together.

Example: On Accounts we have a workflow for the Account Setup grouping. The workflow would start with “Account-Account Setup”.

Required: if Email: E99 – for Email workflows. Start with “01” and work your way up.

Example: if this is the first email workflow for accounts, it should start with “Account-E01”. If the workflow is part of a group like the one above, it should start like this: “Account-Account Setup-E01”. Grouping or no grouping, the number represents the number for the Account entity in total.

Required: Description should briefly describe the action and purpose of the Workflow.

Example:

We are creating a workflow for Accounts that is part of the account setup group, and handles the validation of the credit approvals. The workflow should be named something like: “Account-Account Setup-Validation of Credit Approval”.

 
Create a CRM Admin Account

Have one user that owns all workflows and is not a regular user. In most cases create a CRM Admin user that has full system administrative access and the Email Router is setup and working for the user. Have all workflows owned by this user and not regular system users.

Create Separate Workflows for Emails

Place the generation of email in a separate workflow. Allow manual execution. Check each email recipient to see if they have email address. If they do not, send the record owner and email stating that the recipient doesn’t have an email address and that a workflow is attempting to send an email to this contact. Also, advise that once they have fixed the email address, the record owner should start this workflow again. The workflow will stop after the email is sent. Fill in the Category on the email with “WORKFLOW” and Sub-Category with “Entity-E99” from the naming convention. The example below is for a workflow called Account-Account Setup-E01-Send Credit Manager Actions.


Deciding between Plugins Vs. Workflows.

This is a common dilemma in CRM and there is no exact formula to find the best implementation method for a specific situation. However, this article provides some general rules of thumb that can be used to decide whether to use a plugin or a workflow. Before deciding lets understand the difference between plugin and workflow:

Differences between Workflow and Plugins in CRM 4.0
A common question I get is ‘what is the difference between workflow and plugins, and when should I use one or the other?’ This article is intended to be a comprehensive answer to these 2 questions.

First of all, I want to clarify the distinction between what I consider 3 distinct categories of workflow – the terminology is my own:

Simple workflow: This is one or more workflow rules created within the MSCRM interface, and which do not include custom workflow activities.
Workflow with custom workflow activities: I’ll explain more about custom workflow activities later in this article; for now the key point is that a custom workflow activity is .Net code that is written to perform functions not possible in simple workflow, and this code can be called from a workflow rule
Workflows created with the Workflow Designer: in Windows Workflow Foundation. It is possible to build workflows outside of the CRM user interface, but I’m not going to include them in this article.
Simple workflows
the main characteristics of simple workflows are:

* Creating a simple workflow involves no code

  • Workflows run only on the CRM server – workflow processing is not available within a client that is offline
  • Workflows run asynchronously – any data changes made within a workflow rule will not show up immediately within the CRM user interface
  • Workflows can be run manually or automatically. The automatic running of workflows is based on several data modification events
  • Workflow rules are entity specific
  • The state and stage of a workflow instance can be viewed within the CRM user interface by any CRM user with appropriate permissions
  • Some limitations of workflows are:
  • Workflow rules cannot be created for all entities
  • Although workflow rules can be triggered by the most common data modification events, there are some events that don’t trigger workflow rules
* Simple workflows offering limited capability to perform calculations

Characteristics and limitations marked with an asterix (*) do not apply if using custom workflow activities; the others do still apply.

Custom workflow activities
Custom workflow activities allow you to extend the capabilities of workflow rules. Three common uses are to perform calculations on CRM data, to access CRM functionality that is not available in the out-of-the-box workflow activities, and to access external data.

Custom workflow activities are written as .Net assemblies which have to be registered on the CRM server. These assemblies can include information about parameters that can be passed into or out of the activity.

Plugins
A plugin is .Net code that is registered on the CRM server. A plugin assembly can be registered for one or more steps – these steps correspond to the combination of the message (event), entity and stage. An example of a step would be the Create message for the account entity on the pre-event stage. Registration of the assembly and steps is part of the plugin deployment process, and there is no direct user interaction with plugins

the main characteristics of plugins are:

  • They have to be written as .Net code
  • Although they typically run on the CRM server, they can be deployed and configured to run on a CRM client that is offline
  • They can run either synchronously or asynchronously. If they run synchronously, any data changes made within the plugin will show up immediately within the CRM user interface
  • Synchronous plugins can run on either the pre-event or post-event stage. The pre-event stage happens before data is written to the CRM database, and a plugin registered on a pre-event step can cancel the data writing and provide an error message to the user.
  • More entities can have plugins registered for them than can have workflow rules
  • Plugins can run on more events than can workflow rules. An example is that plugins can run on data retrieval, not just modification events
  • The main limitations of plugins are:
  • Plugins cannot be run manually; they only run on the steps for which they are registered
  • There is no user interaction with plugins, other than error messages that might be throw by a synchronous plugin

Sample Scenarios
so, having covered the main characteristics and limitations of simple workflows, custom workflow activities and plugins, when should you choose one or another? Here are some common scenarios:

1. What you want to achieve can be done with a simple workflow, and it is acceptable or desirable for this to happen asynchronously and on the server only
In this case I’d go with simple workflows; there’s no point writing code if you don’t have to.

2.What you want to achieve has to run synchronously
if so, workflow won’t do, so it would have to be a plugin. An alternative could be to use client script, but I don’t intend to complicate this article by including this in any more detail

3.You need to be able to cancel the data operation
A pre-event plugin is the only option covered here, though again client script should be considered

4.You want to give users the discretion to run the operation manually
Here you’ll need a workflow. Whether or not you need a custom workflow activity depends on the complexity of the operations. Again, there may be an option outside of the scope of this article – to write an ASP .Net application that is called from an ISV Config button

5.You need to write custom code, but you want users to decide whether this code should run, and under what circumstances
In this case I’d go with a custom workflow activity, as you could make this available for users to add to their own workflows
 

When to write a plugin in Dynamics CRM and when to write/design a workflow instead?

With the CRM 4.0 enhancements to the plug-in and workflow engine as well as the introduction of the web based workflow designer I’ve seen many CRM developers asking the same question: When should I use workflow vs. plug-ins? The answer is “depends”; the right approach is determined by the characteristics of the task that you are trying to accomplish. The following matrix gives you my take on this:

 
Requirement

 
Plug-in

 
Workflow

 
 
Needs a synchronous action to happen before or after an event occurs

 
x

 


 
 
The same piece of logic will be executed for different events and possibly on different entities

 
x

 
x

 
 
The logic needs to be executed while offline

 
x

 


 
 
Needs elevation of privileges (impersonation)

 
x

 


 
 
Needs to execute on events other than assign, create, update, setstate

 
x

 


 
 
The process/logic may take a long time to complete or will be a persistent process (multiple long running steps)

 


 
x

 
 
Needs an asynchronous action

 
x

 
x

 
 
End users will need to modify the process logic

 


 
x

 
 
Child sub processes will be triggered

 


 
x

 

It may also be the case that a combination of both approaches is required; a plug-in can trigger a workflow and a vice versa. From the above matrix the most decisive factor is whether you need a synchronous action or not; if you do, plug-ins are the way to go, if you don’t then other factors need to be pondered.

Also, remember than both workflows and plugins can attach to exactly the same events. Well, plugins 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.

On the other hand, plug-ins is 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 auto generated id)

It is important to note that since Dynamics CRM 4, plugins can also be configured to run asynchronous (Mode attribute while registering plugin). Nevertheless, pre-event asynchronous plugins are not supported. In this case, you will have to set it up as synchronous mode.

Another important thing about plugins is the Deployment option which says if the plugin is going to be executed on the server and/or Outlook client. If both executions are set up and client goes offline and online, plugin calls are triggered after synchronization so is 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.

· Plugins execute under the security context of the CRM Web application pool identity (tipically NETWORK SERVICE). As this account typically maps to generic CRM SYSTEM user this typically works fine.
However, within plugins 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 plugin. It is important to know that plugin impersonation does not work offline. The logged on user credentials are always used in this case.

1. TIMEOUT VS. WAIT

While a timeout is technically a wait condition, it appears differently once saved. Unlike a standard wait condition, a timeouts wait condition cannot later be modified, unless it is to simply change the date it is waiting until (as in, it must remain a ‘timeout’).

A timeout also cannot have multiple conditions defined within the same timeout; for example waiting until a date is reached and the status is complete (meaning the condition won’t be met until both of these are true).



So when should you use a Timeout and when should you use a Wait?

A ‘Timeout’ should be used when waiting until a date. For example, if you need to wait until 1 day before the due date of an appointment to send a reminder email, you need to use a Timeout. Timeouts can also be used to wait a static number of days. For example waiting 7 days duration before performing some other logic.



A standard ‘Wait’ can be used to wait for any other conditions. For example, if you have an opportunity pipeline workflow which creates an activity, you can use a wait condition to wait until the activity is completed before continuing onto the next phase.

Avoid using Process Execution Time in wait conditions, as these conditions will never be met and the workflow will continue waiting forever. Instead, you should always timeout until a specific date using the form assistant or a static date.

2. ADD STEPS AFTER THE WAIT CONDITION INSTEAD OF INSIDE

Wait conditions with no steps defined inside the actual wait condition will still wait until the condition is met before processing any steps after the wait condition.



By using this approach, it means there aren’t as many nested conditions, which makes it a lot easier to make changes to the workflow later on. When you delete a wait condition, it also deletes any steps defined within the wait condition, which means you would have to recreate any of the steps defined within the wait condition. It also means you can add your steps in first, and then add in the wait condition later.

If you have a parallel wait condition, where one of the two branches end the workflow, you can add the steps to end the workflow inside the wait, and then the steps for the other wait can be added outside (after) the whole wait condition. This will never be hit when the other wait condition is met, as the workflow will have been ended.



3. WHAT IF THE DATE CHANGES OR THE SERVER GOES DOWN DURING A TIMEOUT?

If you’re using a Timeout to wait until a date, and that date changes, the timeout will automatically adjust and wait until the new date. Even if that date is changed to be in the past, the timeout will readjust to the new date, and will fire instantly.

If the server goes down, or the async service stops, any workflows that are ‘waiting’ will be resumed when the server/async service comes back up. If the server/async is down at the exact time as when a wait condition is waiting until, the workflow will continue again when the server/async comes back up, and it will process the wait conditions that were due during the down time.

4. TRIGGER WORKFLOWS ON CREATE WHEN USING A WAIT CONDITION

A Workflow triggered on Create will only ever run once for each record, whereas a workflow triggered by other means (such as field change) will fire a new instance of the workflow each time. If you are performing wait conditions, or sending emails for example, you don’t want these being sent twice for the same record.

If a date (such as an end date) won't be entered right away, and you only want to start waiting when this date is entered, you can still trigger the workflow on create, and just timeout until this date. Even if there is no value, the workflow will wait until there is a value, and until that value is reached. If the workflow was triggered on change of the end date, you could potentially have multiple instances of the workflow running if the date were to change after it was initially set.

There are a few issues with this approach however. The workflows could potentially be waiting a long time before the date is set and reached, or the date could never be set at all, in which case the workflow would continue to wait forever. There are 2 ways to avoid these issues:

• Add a parallel wait branch to the wait condition, so you can wait a static length (such as 3 months after the created on). If the end date is not set and reached by that time the workflow will end, and optionally send someone an email or perform some other action.



• Trigger the workflow on change of the end date, but create a new hidden date field on the entity to prevent multiple instances of the workflow running at once.



In the workflow, before the wait condition, set the hidden date field to equal the end date. Add a parallel wait condition to wait until the end date does not equal the hidden date field. If this condition is met, end the workflow (as another instance of the workflow will now be running). This will ensure only 1 instance of the workflow is running per record.



5. CHECK THE DATE IS IN THE FUTURE BEFORE WAITING

If historic records are being created/updated, you may not want your workflow to continue processing. This would require a simple check condition before the wait condition to check Process Execution time is BEFORE the date you are waiting for. If the date is not in the future, the workflow would not continue.

This would mean that if your workflow was running on change of the date field, and it was changed to a date/time before today, the new instance of the workflow would be ended as the date is not in the future. Assuming you had ended any earlier workflows, this would mean the steps defined after the wait condition would not fire for that record.

This check would be completely optional and dependant of your particular requirements, as you may need the workflow to fire even on records where the date is set in the past.

NOTE: Without the check condition, a Timeout waiting until the End Time will be met straight away, even though the date has passed.




 

 

1 comment:

  1. I followed the steps and created a workflow with wait and parallel timeout. For testing purpose I kept Timeout condition as 1 min after the Case created on. Expecting that it will do some operation after 1 min, nothing happened. Am I missing something over here.

    Thanks

    ReplyDelete