You are on page 1of 158

Building Workflows in Dynamics CRM 4.

0
Learn how to perform intelligent data updates, work more efficiently, and automate business processes, using Dynamics CRM 4.0 Workflows

2009, Richard Knudson and the Information Management Group (IMG)

Contact IMG 1415 West 22nd Street, Suite 280E Oak Brook, IL 60523

www.IMGinc.com www.DynamicsCRMTrickBag.com

Solutions and Skills for SharePoint and Dynamics CRM

Contents
Contents ............................................................................................................................................................... 2 Forward ................................................................................................................................................................ 6 Getting the most out of the book ...................................................................................................................... 6 A little bit about me ............................................................................................................................................ 7 Chapter 1 - Introduction ....................................................................................................................................... 9 Why is Workflow important? ........................................................................................................................... 9 How Workflow is Implemented in Dynamics CRM.................................................................................... 10 Contrast with SharePoint Workflows ........................................................................................................ 10 Improvements compared to CRM 3.0............................................................................................................ 11 Dynamics CRM Entities and Common Workflow Scenarios ..................................................................... 11 Accounts, Contacts ....................................................................................................................................... 12 Leads............................................................................................................................................................... 12 Opportunities ................................................................................................................................................ 13 Cases ............................................................................................................................................................... 13 Activities......................................................................................................................................................... 13 Record Assignment in Workflows ................................................................................................................. 15 Chapter 1 Summary.......................................................................................................................................... 15 Chapter 2 - Dynamics CRM 4.0 Workflow Basics ........................................................................................ 17 Workflow Properties ........................................................................................................................................ 17 Name, Primary Entity, and Type................................................................................................................ 17 Options for Automatic Workflows............................................................................................................. 19 Available to Run -- On Demand ................................................................................................................. 21 Available to Run -- Child Workflows ........................................................................................................ 23 Using the Workflow Step Editor..................................................................................................................... 23 Workflow Steps ............................................................................................................................................. 27 Insert Before Step; After Step ...................................................................................................................... 27
2 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Workflow Stages ........................................................................................................................................... 28 Workflow Actions............................................................................................................................................. 28 Create Record ................................................................................................................................................ 29 Update Record............................................................................................................................................... 32 Assign Record................................................................................................................................................ 35 Send Email ..................................................................................................................................................... 37 Start Child Workflow ................................................................................................................................... 39 Change Status ................................................................................................................................................ 40 Stop Workflow .............................................................................................................................................. 41 Monitoring Workflows..................................................................................................................................... 41 Monitoring Workflows from the Workflow Record ................................................................................ 42 Monitoring Workflows from an Entity Record ........................................................................................ 42 Monitoring Workflows from System Jobs................................................................................................. 43 Chapter Two Summary.................................................................................................................................... 44 Demonstrations for Chapter 2......................................................................................................................... 45 Demonstration 2.1 Configuration Workflow for the User Entity ....................................................... 45 Demonstration 2.2 Basic Lead Assignment Workflow......................................................................... 47 Demonstration 2.3 Case Assignment and Routing Workflow ............................................................ 51 Demonstration 2.4: Setting Default Values for Account Records .......................................................... 54 Chapter 3 - Dynamic Values and Flow of Control ........................................................................................ 57 Introduction ....................................................................................................................................................... 57 Entity Relationships, Record Assignment and Ownership ........................................................................ 57 Entity Relationships...................................................................................................................................... 57 Record Assignment....................................................................................................................................... 58 Assigning Records to Queues ..................................................................................................................... 58 Dynamic Values ................................................................................................................................................ 61 Dynamic Values are Context Sensitive ...................................................................................................... 66 Using Increment, Decrement and Multiply Operators............................................................................ 66 Dynamic Values: Related Entities............................................................................................................... 72

3 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Dynamic Values: Local Values.................................................................................................................... 75 Flow of Control Check Conditions.............................................................................................................. 76 Check Condition: Building out your Workflow Logic ............................................................................ 77 Working with Conditions: Building out your Workflow........................................................................ 78 Nesting Conditional Branches .................................................................................................................... 80 Flow of Control - Wait Conditions ................................................................................................................. 84 Adding Wait Conditions.............................................................................................................................. 84 Configuring Wait Conditions...................................................................................................................... 86 Parallel Wait Branch ..................................................................................................................................... 89 Stages and Wait Conditions ............................................................................................................................ 91 Demonstrations for Chapter 3......................................................................................................................... 94 Demonstration 3.1: Escalation Workflow for Past-Due Opportunities................................................. 94 Demonstration 3.2 Task-Based Staged Sales Process Workflow..................................................... 98 Demonstration 3.3 New Lead Auto-Responder Workflow ............................................................... 102 Demonstration 3.4 Marketing Campaign Audit Trail for Campaign Activities ............................. 107 Chapter 4 - Advanced Topics........................................................................................................................... 111 Recursive Workflows ..................................................................................................................................... 111 Recursive Workflow Mechanics ............................................................................................................... 111 Counting Workflow Loops........................................................................................................................ 113 Automatic Workflows, Business Units and Security................................................................................. 116 Using Workflows to Audit Records ............................................................................................................. 119 Creating Audit Trails for Changes to Records........................................................................................ 119 Creating Audit Trails for Deleted Records.............................................................................................. 120 Demonstrations for Chapter 4....................................................................................................................... 122 Demonstration 4.1 - Assigning Leads on a First-Come First-Served Basis......................................... 122 Demonstration 4.2 - Assigning Leads on a Round-Robin Basis........................................................... 126 Demonstration 4-3 Recursive Workflow for Case Escalation............................................................ 131 Demonstration 4.4 Manual Sales Process Workflow with Stages................................................. 135 Demonstration 4.5 Creating Audit Records for Deleted Opportunities ............................................. 138

4 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Demonstration 4.6 Opportunity Audit Workflow ................................................................................. 143 Demonstration 4.7: Creating a Record from an Unrelated Entity........................................................ 145 Chapter 5 - Tips, Tricks and Traps ................................................................................................................. 148 Importing and Exporting Workflows .......................................................................................................... 148 Workflow Names ........................................................................................................................................ 148 Workflow Status Values............................................................................................................................. 148 Workflows and Dependent Customizations........................................................................................... 148 Referring to Named Objects in Workflows................................................................................................. 151 Advanced Find and Workflows.................................................................................................................... 151 Advanced Find Queries for System Jobs ................................................................................................. 151 Activity Records have an Is Workflow Created Attribute ................................................................ 153 Workflows and Entities are Related to Each Other................................................................................ 154 Working with Workflow Templates ............................................................................................................ 155 Workflow Security.......................................................................................................................................... 155 Workflows and Importing Records.............................................................................................................. 157 Summary .......................................................................................................................................................... 157

5 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Forward
Im Richard Knudson and I wrote this book. Ive been working with Dynamics CRM since the 1.2 release, and if you have some history with the product I think youll agree with me that its come a long way in the last few years. In particular, the improvements in workflow capabilities from the 3.0 to the 4.0 release are dramatic, and when I wrote this book they were still relatively undocumented. I believe that the workflow functionality in Dynamics CRM from time-saving utility workflows to complex business processes is one of the most important reasons to implement the product, and my goal for this book is to help you understand it. In Chapter 1 I start with a few examples to help you get a feel for the kinds of business problems you can solve with workflows, and then in Chapters 2 and 3 I focus on mostly on implementation details of Dynamics CRM 4.0 workflows. Chapter 4 is intended as a kind of case study, where I present a number of more advanced topics and (hopefully!) useful applications of the foundation skills presented earlier in the book. Finally, Chapter 5 is a collection of tips, tricks and other useful tidbits that didnt fit neatly anywhere else.

Getting the most out of the book


I originally wrote this book as courseware for an instructor-led training class, and while it can be used as courseware I think it works as well as a standalone book. One benefit of the courseware legacy is the demonstrations that are included at the end of each chapter. I know that I learn best by a combination of reading, discussing, and doing, and I encourage you to go through the Example Workflows yourself. The demonstrations were designed to work with the Dynamics CRM 4.0 Virtual Machine, which is a Virtual PC image you can freely download from this site: http://www.microsoft.com/downloads/details.aspx?FamilyID=DD939ED9-87A5-4C13-B212A922CC02B469&displaylang=en. For each demonstration, Ive indicated what if any customizations you may need to make to get it to work, but if you have questions about anything or if the VPC image changes, feel free to email me at richardk@imginc.com These are all available for you to download from the online version of this book, which is available for free to purchasers, and you can access through what we call our Student Portal at www.IMGinc.com. The online version includes the book content itself, and the workflows in the form of downloadable customizations you can import into Dynamics CRM. It is somewhat easier to update the content on the Student Portal than on www.Lulu.com so you should check the Student Portal site if you want to see the very latest version.

6 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

But heres the caveat: the book publishing site I used to bring this book to the market www.Lulu.com is excellent, but I do NOT get personal information about people who purchase this book. Thats just the way Lulu works, and I suppose its the right way to do it (Ive read plenty of books by authors I wouldnt want to have my personal information!). But it does limit my ability to automatically set you up with a subscription to our Student Portal. So if you purchased this book from www.lulu.com and you want access to the online content, Id love to get you set up, but you need to email me at richardk@imginc.com to request access.

A little bit about me


Im the president of Chicago-based IMG (The Information Management Group); we provide consulting and mentoring services on SharePoint and Dynamics CRM. I personally focus almost exclusively on Dynamics CRM and on integrating CRM and SharePoint. One of the most interesting projects my firm has been involved with is in managing and delivering Microsofts Dynamics CRM Partner Academy program, which is a certification-focused training program for Microsoft Partner firms. Ive enjoyed that program immensely, and Ive certainly learned as much from our students as theyve learned from me! One of my most important takeaways is how enthusiastic the partner community is about the Dynamics CRM 4.0 release. Ive been working in the Microsoft channel for a long time, and in my experience partner adoption is always a leading indicator of customer adoption; if this rule holds true we Dynamics CRM specialists are going to be busy for some time to come! Although I still refer to IMG as a Chicago-based firm, we actually have our headquarters in suburban Oak Brook, IL. We recently sold the training piece of our business so we can focus exclusively on consulting and related mentoring services, and the move of our sprawling HQ to Oak Brook was part of that transaction. I also have a blog which will probably be of interest to anybody who would purchase this book: www.DynamicsCRMTrickBag.com. Plus, I recently started up a user group www.DynamicsCRMUserGroup.com with monthly (free!) meetings in person or online. I invite you to visit my blog, and I invite you to attend our user group meetings. I transplanted to Chicago a long time ago from my native Seattle, and I live with my family in Winnetka, IL. When Im not doing CRM consulting and training, Im generally in Winnetka being a soccer dad, more or less. Anyway, enough about me, and on to the book! I hope you get lots out of the book, and remember: Ill be adding and tweaking content all the time on the Student Portal site, so please let me know if you have feedback, constructive criticism, or any other comments or suggestions. Regards,

7 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Richard Knudson, richardk@imginc.com

8 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Chapter 1 - Introduction
Why is Workflow important?
Lets start with a simple definition of the word workflow. How about the following: A workflow is a business process, with a starting point and an outcome, consisting of one or more related tasks. This definition, while both general and unrelated to any particular technical platform, does capture the essence of what we mean by workflow. Its so general, in fact, that its hard to imagine work without this notion of workflow. And of course theres nothing new about workflow; whats an HR manual other than the codification of rules, regulations and processes? And when people work together collaboratively, there are obvious advantages from documenting these shared processes. People and organizations create value in different ways. One of the most important and obvious is in intellectual property. The Microsoft Windows and Office platforms come to mind, and of course there are as many examples as there are things you can buy in a store. But another way value gets created is in work process. Wal-Mart is probably one of the best examples of this: its not so much that the things you can buy there cant be found anywhere else, its the efficiency of their operation real estate, supply chain management, store layout, employee training that gave them the edge over competitors. Any business that has competitors (and who doesnt?) needs to differentiate itself; you can think of work processes as one of the important ways to accomplish this. The so-called Solution Selling Process is well known to many Microsoft partners and customers; firms which have implemented consistent, repeatable sales processes based on this or other models may well gain competitive advantage. Here are just a few of the advantages an organization might gain from doing so: Faster lead followup Consistent processes for assigning leads and opportunities Improved pipeline velocity Better pre- and post-sales reporting and analytics A more consistent customer experience Improved ability of management to control pricing and discounting Better measurement of the impact of marketing campaigns And of course sales processes arent the only ones that can be automated! Customer service, service scheduling and management, case and contract management, time tracking and billing, marketing,
9 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

production processesvirtually any area of business can be improved by implementation of repeatable processes, and one of the major areas I focus on in this book is how to do that using Dynamics CRM 4.0 workflows. While business processes per se generally get the most attention when it comes to workflows, they arent the only thing you can automate with Dynamics CRM workflows. Another important category is what you might refer to as utility workflows. In this category Ill include workflows that perform intelligent data updates, set default values for records -- virtually any action that might be performed on more than one record of Dynamics CRM data at a time is a candidate for doing with a workflow.

How Workflow is Implemented in Dynamics CRM


The approach we will focus on in this class is to use the Dynamics CRM 4.0 built-in user interface tools. With this approach, almost all of your work can be done with your choice of the Dynamics CRM web or Outlook clients. There are many advantages to this approach, but its important to know that its not the only way you can do workflows in CRM. Dynamics CRM is built squarely on top of the .NET platform, and its workflow engine in particular is built on the Windows Workflow Foundation. So while you can build very complex and comprehensive workflows using the Dynamics CRM user interface exclusively, you can also write custom workflows with Visual Studio and .NET programming. Generally speaking, any limitations you encounter using the out of the box approach I take in this book can be overcome with the custom .NET workflow approach.

Contrast with SharePoint Workflows


Workflows created using the Dynamics CRM 4.0 user interface are all created for a specific entity, referred to as the primary entity for the workflow. Superficially this might seem similar to the approach in SharePoint, where with a tool like SharePoint Designer you can create a workflow specific to a SharePoint document library or list. By way of contrast, however, here are a couple of big advantages of Dynamics CRM workflows over SharePoint workflows: Dynamics CRM entities are much more specific than SharePoint lists or libraries. For example, compare the CRM Opportunity entity to a SharePoint list configured with similar columns and youll start to appreciate what CRMs specificity gives you. Think about the interplay of the CRM Status and Status Reason attributes and their potential usefulness in workflows, and then think about how you might implement something like that in SharePoint. Probably even more important is the ability of Dynamics CRM to manage relationships between different entities. Even if you configure SharePoint lists and libraries with all of the columns you need to manage your data, since theres no built-in relationship between lists and libraries

10 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

in SharePoint its much harder to create complex workflows. As youll see, CRMs ability to manage related entities is well-exploited by the workflow engine!

Improvements compared to CRM 3.0


If you have some experience with Dynamics CRM 3.0, you will appreciate the many advantages of the 4.0 version when it comes to workflows. Here are some of the most important: All of the tools you need to create, manage and monitor your workflows are available now through the web client. This is an improvement over 3.0, which had separate executables for both creating and monitoring workflows. Workflows can now be exposed as a tool for end-users. This is optional, and can be controlled via permissions and security roles. While creating workflows isnt for everybody, there are plenty of power-users who will appreciate the personal automation possibilities workflows can give them. In CRM 3.0, only system administrators could create workflows. The workflow design environment is dramatically improved in 4.0 compared to 3.0. Two big improvements in this area are the improved ability to leverage entity relationships, and the new Dynamic Values functionality. There are more events you can use as triggers for automatic workflows. In particular, workflows can now be triggered when a record is deleted, and when any attribute (a.k.a. field) value changes for an entity. Combined with the triggers that were already available in 3.0 (create, assign, and status change), these new triggers let create more comprehensive workflows than previously. All entities now support Stages. In 3.0 only the Opportunity entity could have workflow stages. Stages are useful in organizing complex workflows. You can create workflows against many more entities in CRM 4.0 than in 3.0. This is a general theme throughout CRM 4.0: many more system entities are exposed in customizing, creating entity relationships, as well as in workflows than in 3.0. Well see many examples of where workflows created against a system entity can be useful, and these might not occur to you since they werent available in 3.0.

Dynamics CRM Entities and Common Workflow Scenarios


One good way to get some intuition about Dynamics CRM workflows is to think about the different entities you will write them for, and how the characteristics of those entities influence the kinds of workflows you might create. Here is an overview of some of the most important and common entities youll work with, and some of the typical kinds of workflows youll write for them.

11 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Accounts, Contacts
These are generally static records, and dont necessarily have a process directly attached to them. These are also referred to as Customer records in Dynamics CRM, and are generally permanent. CRM status values can be Active or Inactive. Suppose an important goal of your business is to have longterm relationships with your customers (and if you find any businesses that say thats not one of their goals, let me know!). The Dynamics CRM analogy would be that the Status value of the Account or Contact entities stays Active for a long time. Of course, youd want other things to happen as well (sales, for example), but this makes the point that for these static kinds of entities, you wont typically write workflows whose goal it is to transition the Status value of the record. Also, for these customer records, you want to have as much good data about each record as possible. Typical workflows we encounter for these customer records will do things like: When a record is created, update certain field values automatically, based on the values of other ones. For example, if a sales rep creates an account and enters a zip code, a workflow can enter the appropriate territory value automatically. If an account record has a certain value for the industry picklist, or has annual revenue above a certain level, a workflow might assign the record to the appropriate sales rep or sales manager. Workflows can send emails to Account or Contact records, and when you send an email with a workflow you can use an email template. Since you cant use an email template when you distribute an email activity from a marketing campaign, if you want to personalize an email blast, a workflow is sometimes the best way to do it.

Leads
Leads are potential Customers and generally become (are Converted to) Customers after some kind of qualification process. Status values are Open, Qualified, Disqualified. Unlike the customer (Account, Contact) records we just discussed, most organizations dont want Lead records to remain Lead records -- we want to convert them into customer records. In Dynamics CRM, the goal will generally be to Convert a Lead record into an Opportunity (which must be associated with a customer record), or into an Account or Contact recordor both. But for the purposes of this discussion, the main point is that Lead workflows tend to be processcentric: theres a goal (convert into an Opportunity or customer record), and a process to help achieve that goal. Also, Lead workflows will often have record assignment (in CRM terms, updating the Owner value) as an important first step, and it may be important to un-assign Lead records that are not properly handled.

12 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Opportunities
In Dynamics CRM, the Opportunity entity represents a potential sale and will often have a sales process. Opportunities are always attached to an Account or Contact record. Status values are Open, Won, or Lost. Opportunity records are if anything even more process-centric than Lead records, with the desired outcome generally being to close the sale (change the Opportunity Status value to Won). Since Open Opportunity records are what go into the Sales Pipeline report, many sales organizations go to great lengths to make sure opportunities are accurate and up to date. One important aspect of this is the Estimated Close Date field, and part of a sales process might be to take some kind of escalation action as an opportunitys estimated close date approaches, or passes. Also, since the Opportunity record has to do with something as important as revenue, and since Dynamics CRM doesnt have any built-in auditing capabilities, the Opportunity entity is often one of the first things organizations want to build audit capabilities for. Theres a good way to do this with a workflow, and I will present some examples of this later in the book.

Cases
The Dynamics CRM Case entity is used to keep track of customer incidents, issues and, well cases. Just like the Opportunity entity, Case records must always be attached to an Account or Contact. Case records have status values of Active or Resolved. The goal of most customer service organizations is to resolve a case so although we think of cases as being reactive, as compared to the proactive sales nature of opportunities, theyre similar to opportunities in the sense of being very process-centric, and generally have a well-defined end-point. Also, the Case is the only entity in Dynamics CRM apart from activities that can be assigned to a Queue. In Dynamics CRM, a Queue is essentially a holding place certain records (including Case records) can be exposed to multiple users. A specific user can Accept an item from a queue and take ownership of it. So, assignment and routing scenarios are characteristic of Case workflows. In a business situation where a Case record needs to be resolved in a specific timeframe say because of a service level agreement, a contractual obligation, or plain old good customer service you might want to have an escalation process defined. In Dynamics CRM, we can use a workflow to manage this process for us. There are some important techniques we will later in the book that will manage a Case escalation business process, and they can be applied to lots of different entities in addition to service cases.

Activities
Dynamics CRM has a number of different record types all classified under the Activity category. The simplest way to see this is to simply click New Activity on the global toolbar, as you see here:

13 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 1-1- New Activity Pull-down Menu

You never actually create an Activity record; you can see from Figure 1-1 that the user interface allows you to create one of eight specific kinds of activities. This can be somewhat confusing even for an experienced user, since there actually is a so-called Activity entity in Dynamics CRM. You can see this by clicking Workplace in the Site Map, and then clicking on the Activities tab. Notice that in the Type drop-down menu the default category is All, and in addition to that and the eight activity types shown in the previous figure, theres also a Campaign Activity type listed:
Figure 1-2 - Activity Types

Although this might seem a little arcane, its important background information for workflow designers. Dynamics CRM workflows can both create activity records, and can be made to run automatically when an activity record is created. Both are important scenarios and you will see many examples in the rest of the book. In addition to Case records, Activity records are the only records that can be assigned to a Dynamics CRM Queue. Here are some common workflow scenarios involving activity records:

14 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Activities such as emails, phone calls and appointments often make up the actual work of a business process. So, workflows for opportunities and cases will often create and assign those activities.

A workflow might create an activity record, assign it to a user or a queue, and then wait until the activity is completed. In Dynamics CRM terms, an activity is completed when its Activity Status value is equal to Completed, so thats a condition your workflows will often check for.

Another equally common scenario is for the workflow to both create and complete an activity. Probably the most frequent example of this is with email. Dynamics CRM workflows can automatically send emails; for example, to notify a user of an important event, or to send an auto-responder email to a web site visitor who filled out a form requesting information.

In general, while Activity records are often created as part of a workflow, you generally dont write workflows to implement a complex business process specifically for one of these Activity record types.

Record Assignment in Workflows


Adam Smith was one of the first commentators, and certainly the most forceful, to articulate the powerful effect incentives have on behavior, and in turn the critically important role of ownership on incentives. This lesson was never lost on business people; it is a central tenant of customer relationship management generally, and of Dynamics CRM in particular. In Dynamics CRM, every entity has one of two ownership types: organization owned, or user owned. The most common entities Leads, Accounts, Contacts, Opportunities, Cases are all user owned. To assign an entity like one of these is the same thing as to establish its ownerthese are essentially synonymous. And in case a little review is in order, most user owned entities can only be assigned to a Dynamics CRM user. This sounds a little redundant but its important because there are a few entities the Case entity and all Activity entities, specifically that can be assigned to a Dynamics CRM queue. We will see a few examples in the rest of the book of how workflows can take advantage of this.

Chapter 1 Summary
Before diving down into detail, I wanted to start with some intuition. My goals arent as grandiose as to put forth a General Theory of Workflowsbut on the other hand, I would like to give you a good feel for what you can do, and the business problems you can solve with workflows. Think of it as the Zen of Dynamics CRM workflows, and try to see things from the perspective of the entities you will be writing workflows for: Account and Contact records want to be with you for a long time. They need good owners and good data.

15 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Lead records long to be Converted to Accounts or Contacts (or both, not to mention Opportunities). They need a good process to help them in their conversion. Opportunities ache to be Closed as Won. They often need a process to get them there, and although they do not necessarily care about being closed by a specific date, they dont want to be late! They do not like being Deleted, and if they are, they like to leave a legacy (in the form of an audit record).

Cases yearn to be Resolved. Similar to Opportunities, they often need a well-defined process to help them get there. Unlike opportunities, cases can be directly assigned to a Queue for firstcome first-served assignment. Also unlike Opportunities, Cases generally want to be Resolved by a specific date and want to be escalated if they arent! Case records also dont like being Deleted, and if they are they like to leave some legacy information behind.

Workflows can also be written for any custom entities you create. And since the characteristics of your custom entities are only limited by your imagination (and your business requirements), the same can be said of the processes you might want to apply to them, in the form of Dynamics CRM 4.0 workflows.

16 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Chapter 2 - Dynamics CRM 4.0 Workflow Basics


Workflow Properties
Every workflow in Dynamics CRM has eight basic properties you need to specify when you create a workflow. We describe these briefly in the following table, and cover them in detail in the rest of this section.
Table 2-1 Workflow Properties

Property Name Primary Entity Type Scope Trigger Available on demand? Available as child workflow? Publish as

Description The name of the workflow The primary entity the workflow is designed for Whether youre creating a brand new workflow, or based on an existing template Only applies to automatic workflows: which users will they run for? Only applies to automatic workflows: what events will cause them to run? Can the workflow be run manually? Can the workflow be called from another workflow? Is it a workflow, or a template to be used to create other workflows?

Name, Primary Entity, and Type


Assuming your security role allows you to create a new workflow (more on this later!), you can create one by navigating to Settings and clicking the Workflows tab, then clicking the New button. You will see a figure like the following one:

17 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 2-1 - Naming a Workflow and Specifying its Entity

Name Choose a name that is short and descriptive. If you are going to be creating many workflows for your organization its best to come up with naming conventions before starting out. One important thing to keep in mind is that the value you enter for Name is not required to be unique. But it will obviously be very confusing to have multiple workflows doing different thingsbut all with the same name! So however you define your workflow naming conventions, we recommend you start with a rule saying no two workflows shall have the same name. (And unfortunately, you cannot use Dynamics CRM built-in duplicate checking to create a duplicate detection rule on the Workflow entity, so you will need to enforce a rule like this manually.) Primary Entity One of the most basic facts about Dynamics CRM workflows is that they are always associated with a primary entity. So when you create a new workflow, one of the required properties you need to set is the entity Account, Contact, Opportunity, Case, or any custom entity that the workflow is designed for. Workflows and Workflow Templates Dynamics CRM workflows can be created from scratch, or from a pre-existing template. And, an existing workflow can be saved as a template. Templates are often helpful if you need to create many workflows with a similar structure, and especially so if the structure is complex or the workflow large. Rather than create a complex workflow ten times with just a few differences, you can create a template, and then create the ten workflows based on the template. Then you only need to implement the differences between the workflows, and can save yourself some time. A good example of when a template is helpful is useful is with a multi-stage sales process workflow. Suppose you always have the
18 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

same basic structure, but certain kinds of opportunities have slightly different permutations on the basic process. For now we will focus on the New blank workflow option; later in the book well discuss using templates. If you pull down the Entity list in this dialog you can see all of the entities you can create workflows for. Depending on your security role you will be able to create workflows for different entities. For example, if youre signed in with the Sales Person role, you wont see Price List or Territory entities in the list; if youre signed in as a System Administrator you will see a complete list of everything workflows can be created against. After clicking OK in the New Workflow dialog, you will see the workflow design environment. In the example here weve selected Lead as the primary entity, and named the new workflow Lead Distribution.
Figure 2-2 Workflow Properties

Options for Automatic Workflows


Notice that by default the Scope value is set to User, and Start when is set to Record is created. These are both in the Options for Automatic Workflows section, since both of these settings only apply to workflows that will run automatically. We will cover each of these in turn. Workflow Scope When you create an automatic workflow for a user-owned entities, you will see four values you can select from the Scope list: User, Business Unit, Parent: Child Business Unit, and Organization. This scope value refers to the level of availability of the workflow who in the organization it will run for.

19 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Its analogous to the Access Level concept from the security model, although its important to note that Scope can never supersede security.
Table 2-2 Workflow Scopes

Scope User Business Unit Parent: Child Business Unit Organization

Who will it run for? Just the user who owns the workflow The user who owns the workflow plus anybody else in the same business unit The user who owns the workflow, anybody else in the same business unit, plus anybody in a child business unit Everybody in the organization

A good way to understand this is the following exercise: 1. Sign in as a user who is not in the root business unit, and create a simple notification workflow to send out an email whenever a new Account record is created. Set the Scope value to Business Unit, and publish the workflow. 2. Create a new Account record and verify that the workflow performs as expected. 3. Sign in as the System Administrator, or any user who is associated with the root business unit. Create a new Account record and accept the default ownership (assigned to you), and verify that the workflow does not get triggered. 4. Next, while still signed in as the System Administrator, create a new Account record and assign it to the user who created the workflow, or anybody else in the same business unit. Verify that the workflow does get triggered in that case. We will present a detailed demonstration to illustrate this at the end of the chapter. Triggering Automatic Workflows After setting the Scope for an automatic workflow, you need to decide what event will cause it to run what should trigger the workflow?
Table 2-3 Triggers for Automatic Workflows

Trigger Record is created

Important Points to Keep in Mind Workflows triggered by Record is created are useful for automating everything that should happen when a new record is created. Default values in the primary or related entities, notifications, task assignments, are all good candidates for automation with a Record is created workflow. The status referred to here is the Status, not the Status Reason we
20

Record status

Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

changes

discussed above. This is an important distinction, because you will often have multiple Status Reason values for the same Status value. Only if the Status value changes will this workflow trigger fire. This becomes important in workflows that route Case or Activity records to Users or Queues. Remember that assigning a record to a Queue doesnt actually change the records Owner, even though in the user interface its referred to as assigning. Since this workflow trigger only happens when the actual value of the Owner field changes, its important to keep this distinction in mind. This is a new feature in Dynamics CRM 4.0, and allows you to create richly complex workflows that werent possible in CRM 3.0. Essentially, you can make a workflow sit and listen until any field on any record changes, and have workflow processes take appropriate actions. For example, if what you need to trigger a workflow is a change in the Status Reason attribute, use this trigger. This is also a new feature in CRM 4.0, and allows you to trigger an action after a record is deleted. Its important to stress after, since by the time a workflow on the delete trigger runs, the record it runs against is already deleted. But that doesnt mean you dont know anything about that record. In fact, you can have a workflow extract any value you want from a deleted record, including the Status or Status Reason values at the time the record was deleted!

Record is assigned

Record attributes change

Record is deleted

Available to Run -- On Demand


If you want a workflow to be available for a user to run manually, make sure the On demand checkbox is selected in the Workflow Properties section. If (and only if) there is a published workflow with this property turned on, the Run Workflow button will appear at the top of the data grid for that entity. There are many instances when On Demand workflows are useful. Sometimes you will want to update multiple records at the same time, rather than one by one. On Demand workflows can be used for this. You might think that you could simply select the records you want to update, and use the More Actions/Edit menu command for so-called bulk editing of records. In many cases this nice function will work, but not always. Here are two cases where it wont:

21 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

1. Suppose youre the System Administrator and you want to update multiple User records at once (e.g., youve just configured your email router and discover that the default User settings for email configuration are all incorrect and need to be fixed!). Bulk edit is not available for the User entity (along with plenty of other entities in CRM), so your best option here would be an on demand workflow. 2. Suppose you want to update many records at once, but with different values, based on some other attribute of the records or related records. The bulk edit function described above only lets you enter a single value, but an on demand workflow can make update values depend dynamically on other values. For example, you might implement a territory-based sales model after youre already up and running in CRM, and need to update all kinds of legacy Account or Contact records with new territory values. With an on demand workflow, you could use a range of values in the Zip Code field to update Territory with the appropriate value, running one workflow against any or all records. This kind of dynamic data updating wouldnt be possible with bulk edit. Sometimes business processes need to involve discretion or are difficult to automate. For example, a sales manager might want to audit opportunities, emailing reminders out to the sales team to close out past-due opportunity records. Well see later how to implement this functionality as part of a process, with an automatic workflow. But with an on demand workflow, a sales manager could reserve the option to only perform this audit periodically, making the decision when to do so based on factors that might change from time to time or might be hard to model in an automatic process. Another Workflow Security Issue Theres an important security-related point you need to understand when contrasting Automatic with On Demand workflows: Automatic workflows run in the security context of the owner of the workflow; On Demand workflows run in the security context of the user who runs the workflow. This is important since a workflow can break if a user running it doesnt have sufficient privileges for actions the workflow might perform against CRM entities. So, generally speaking, automatic workflows created by a System Administrator will always work, since they are always run in the security context of the System Administrator. And on demand workflows will always work for the user who created them, since the workflow design environment wont expose to you actions your security role disallows. On the other hand, on demand workflows created by a System Administrator and exposed to everybody, by setting Scope to Organization, often will not work for certain users, since many users will be in security roles without permissions to perform actions the workflow might take.

22 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Available to Run -- Child Workflows


If you want a workflow to be able to be called from another workflow, make sure As a child workflow is checked in. Child workflows are useful for a series of workflow actions that need to always be performed together, and can be re-used in different contexts. Rather than reproduce the workflow steps in many different workflows, you can maintain them in one place a separate child workflow and call it from various other workflows. Another scenario we will examine that will make use of this capability is when a workflow needs to call itself, recursively. This is useful for looping situations, when a process needs to run continuously until some exit condition happens, and when you want some flexibility in jumping around to different stages of the process. We will examine this somewhat advanced topic in Chapters 3 and see an example of a Staged Opportunity Sales Process workflow that uses it in Chapter 4. Remember that regardless of whether your workflow is Automatic, or On Demand, it wont run unless its published. So when youre ready to test or deploy a workflow, save it and then publish it.

Using the Workflow Step Editor


After you configure the basic Properties for a workflow, you will use the Step Editor to add and configure the Actions it will perform, and the workflows logical flow. To see the Step Editor in action, heres a step by step example of how we create a workflow to assign new leads based on attributes of the Lead entity such as industry and company size.

1. First, create a new workflow by navigating to Settings, clicking on the Workflows tab, and click New. Name the workflow Lead Assignment, select Lead as the Entity, and make sure New blank workflow is selected as the Type. Then click OK. 2. In the Options for Automatic Workflows section, select Organization for Scope, and Record is created for the trigger (Start when).Then click on the button to the left of Hide Workflow Properties, to free up more space to work in the Step Editor. (Remember that this is a toggle switch, so you can click it repeatedly to minimize or maximize the Properties section.)

23 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 2-3 - Workflow Designer with Properties Minimized

3. Pull down the Add Step menu, and select Check Condition. 4. Now position your cursor where it says Type a step description here, and enter descriptive text. (This is optional, but you should always do this as a best practice.) 5. Click the link that says <condition> (click to configure) to access the Specify Workflow Condition dialog:
Figure 2-4 Specifying Workflow Conditions

24 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

6. Position your cursor over Select and youll see a pull down menu that allows you to select from various entities. For now, select the Lead entity, then tab to the next column. 7. These are the fields attributes of the Lead entity. Select the Industry value, then tab to the next column. 8. This is where you select the comparison operator. Select Equals for this simple workflow, then tab to the next column. 9. Notice that on the next column an ellipsis appears, indicating you can select from a list of values. This is because the Industry field is a picklist, and illustrates how contextual the workflow design process is in CRM 4.0. Suppose you have a vertical sales model, where certain sales reps focus on specific industries or groups of industries. Ill select multiple values here like Accounting, Brokers, Business Services, and Consulting to suggest such a scenario.
Figure 2-5 - Selecting Multiple Values from Specify Workflow Condition Dialog

10. After clicking OK, you can click Save and Close to return to the Step Editor. 11. Now, position your cursor on Select this row and click Add Step (make sure you follow instructions closely and click deliberately on that row the first few times until you get used to it) 12. Once you have the right row selected, click Add Step, and select Assign Record from that menu. Fill in the step description if you like, and then click to the right of to to assign the new lead record. If you type Alan and tab off you can verify that the user name resolves. (Later well see what happens if you click Set Properties)
25 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

At this point, we have a well-defined workflow that will assign financial and business services leads to Alan Jackson. But what about all of the other leads? Suppose that Alans our only vertical industry specialist for now, and that all other leads get assigned to the sales manager who can assign them out manually. To see what that might look like, follow these steps: 1. Carefully select the first line of the If block click on If or then, for example. 2. Then click Add Step again, and select Default Action this time. 3. This puts in an Otherwise step that we can use to handle all other conditions. Again, click on the instructive text Select this row and click Add Step, click Add Step again, and select Assign Record. This time, enter Gail in the to box.
Figure 2-6

4. Then save the workflow, publish it, and close the window.

Now you can test the workflow, and verify that it works as expected. So without too much work, you can create an automatic lead assignment workflow. Most entities in CRM come preconfigured with lots of fields (also referred to as attributes) that can be useful in workflow scenarios like this one. In fact, until you start understanding what you can do with workflows, you might not appreciate the value of some of the fields you have to work with. For example, some of the other fields on the Lead entity you might use in similar ways include the Annual
26 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Revenue and Number of Employees fields (if account size determines lead assignments), or the City, State, or Zip Code fields if your sales model is territory based. Well see plenty of other examples like this as we move ahead.

Workflow Steps
Lets focus in just a little more detail on the mechanics of using the Step Editor. In Dynamics CRM 4.0, all workflows will have Steps, which is where conditions are checked and appropriate actions taken. Workflow Steps can be contained within Stages, although Stages are not required. (In Dynamics CRM 3.0, only the Opportunity entity could have staged workflows, which were specifically referred to as sales processes.) Weve already mentioned that workflow Steps are not required to have descriptive text, but its a good practice to supply it. But if you add Stages to your workflows, those are required to have text that describes each Stage. To see how this works, well make some changes to the Lead Assignment workflow. Start by navigating to the Workflows tab on Settings, and double-clicking on the workflow to open it up. A workflow must be in draft status to be edited, so we unpublish it to make it editable.

Insert Before Step; After Step


Suppose that in addition to assigning all of those financial and business services leads to Alan, we also wanted to automatically send an email to the new lead, acknowledging that weve received the lead, thanking them for their interest and telling them how well follow up. 1. Select the step in the workflow where we assign the leads to Alan, and now pull down the Insert menu. Notice that the default selection is After Step, and change it to Before Step. 2. Now go to the Add Step menu again, and this time select Send Email. 3. After doing this, you will notice that the new step has been inserted before the previous step. As you will see, the order in which actions happen, or conditions are evaluated, will often have important implications for how your workflows behave, so its important to remember whether you want to insert before or after and how this setting is currently configured. The workflow step weve just created will send an acknowledgment email to the new lead, and as youll see later the new Dynamic Values features in CRM 4.0 will allow you to configure emails (and pretty much every other record type in CRM!) very flexibly. For now, were focused on the mechanics of the Step Editor, so well leave that part for later.

27 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Workflow Stages
We mentioned before that In Dynamics CRM 4.0, all workflows can have Stages. Workflow Stages are essentially containers for all of the Steps in your workflow, and you can add them at any time. You can add a Stage to an existing workflow and the Step Editor will wrap all of your existing Steps in the new Stage. For example, we can add Stages to our Lead workflow like this: Select the first workflow step in the Step Editor, pull down the Add Step menu and select Stage. Youll get a dialog telling you what will happen, and if you click OK, youll see that two Stages have been added to the workflow. (Depending on whether Insert is set to Before Step or After Step, this will behave slightly differently.) Here are a few things you should know about workflow Stages in Dynamics CRM 4.0: If you have Stages in a workflow, every workflow Step must be contained within a Stage. You can save a workflow without entering descriptions for Stages, but you cant publish it. So in effect, Stage descriptions are required, unlike Step descriptions. You can add as many Stages as you like, and you dont have to add Steps for a Stage. So, for example, you might want to start by adding all of the Stages to a complex workflow before you add the Steps (conditions and actions), so that you have placeholders for everything, and get a feel for what needs to happen where. You can delete a Stage. If you do, all of the Steps within that Stage will be placed in the previous Stage, rather than deleted. In Dynamics CRM 4.0, Stages are mainly for organizing the Steps of workflows into logical groups of conditions and actions; by themselves, they dont really change the behavior of a workflow. For example, you might have a sales process workflow with multiple stages (Identify, Qualify, Propose, Negotiate, etc.). But theres nothing about Stages that will make a workflow stop within a Stage. Well see some of the implications of that behavior later in the class.

Workflow Actions
After our introduction of basic workflow properties and how to use the Step Editor, we can start putting workflows to work. This is where Actions come in. You can think of these as the work in workflow, the actions they can perform. (The flow of your workflows is controlled by Conditions and Waits we will discuss these in the next chapter.) A good way to see a complete list of all the actions a Dynamics CRM workflow can perform is to open up the Step Editor and pull down the Add Step menu. You will see something like the following figure, where the actions are the seven menu commands in the section beneath Parallel Wait Branch:

28 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 2-7 Workflow Actions Available from Add Step Menu

As you can see from the figure, the actions are: Create Record Update Record Assign Record Send Email Start Child Workflow Change Status Stop Workflow

Well cover these in turn.

Create Record
As youd expect, this action allows a workflow to create a new record in Dynamics CRM. Assuming you have sufficient security privileges, you can create a new record for any custom entity, plus for most of the core entities of the CRM user experience. In the following figure you can see the Step Editor open, in the process of adding a Create Record step.

29 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 2-8 Selecting the Entity for Create Record

30 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

What Records can be created from a Workflow? All custom entities can have records created by a workflow, as well as core entities such as Account, Contact, and Opportunity. Cases and all Activity record types can be created with a workflow, as well as many other record types. Here is a complete list of the record types a workflow can create. Notice that while some system records Territory, Site, and Queue can be created, many others User, Workflow cannot be. Also, notice that you cant do much with the Product Catalog, other than create a Product record, since Unit Groups, Units, Price Lists and Price List items cannot be created with a workflow.
Table 2-4 Records You Can Create in Workflows

Record Type Core

Activity

Sales

Marketing

Service Miscellaneous

Record Account Contact Opportunity Lead Note Email Phone Call Fax Letter Appointment Campaign Response Service Activity Task Invoice Quote Order Sales Literature Competitor Product Marketing List Campaign Campaign Activity Case Contract Territory Site Queue
31

Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Here is an important point that arises in the context of creating records in a workflow, which also has implications for other workflow scenarios: If a workflow is based on a primary entity, it wont know anything about child records of the primary record. For example, you can create a record such as a Contact from a workflow on the Account entity, but Dynamics CRM wont create that record as a child of the Account record automatically your workflow will need to do that. So, for example, if you have a workflow for the Account entity and you use the Create Record action in the workflow, the workflow design environment will NOT generally assume that the record being created is related to the Account record. There is one important exception, however: for Activity records (Email, Phone Call, Appointment, etc.), Dynamics CRM will by default insert the Account record into the Regarding field for the Activity record, making the latter a child of the Account. You can see the difference in the following two Create Record workflow forms, both from a workflow on the Contact entity:
Activity Record Assumes Workflow Entity is the Parent Other Records do NOT

Security and Workflows. This entire discussion assumes you have security privileges to create all these records in the real world this wont always be the case. For workflows, the main thing to remember about security is this: Automatic workflows run in the security context of the user who created the workflow; On Demand workflows run in the security context of the user who runs the workflow.

Update Record
Use this action when you want a workflow to change values of attributes (fields, in workflow parlance) for a record. You can change the values of fields for the entity the workflow is created on, as well as for any Related Entities. And remember the discussion above about entity relationships and
32 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

workflows: in this context, a Related Entity means a parent record of the workflow record. So, for example, a workflow written against the Opportunity entity will be able to update values on the current Opportunity record as well as any records that are parent records of that Opportunity, such as Account, Contact, and so forth. Here are a couple of important topics that arise in the context of updating records, which as you will see are important in many other workflow scenarios: The Additional Fields tab. Much of your work in creating workflows will take place in the workflow version of the entity forms. These look superficially similar to the user experience of working with records through an entitys main form, but they are actually quite different. One of the most obvious things you notice in the workflow design environment is the Additional Fields tab. For example, here is the workflow design form for the Opportunity entity, with the General tab selected:
Figure 2-9 Using the Update Record Workflow Action

In the next figure, you see the Update Opportunity workflow form, but with the Additional Fields tab selected:

33 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 2-10 Additional Fields Tab Shows Fields NOT Exposed on Entity Form

The importance of the Additional Fields tab is that it gives you as the workflow designer the ability to update fields that are not exposed as part of the user experience of updating a record. So you can take out of the hands of users much of the data entry associated with updating Opportunities (or any other record) that might be tedious or error prone. When to use Update Record, Assign Record, Change Status You might wonder why there are separate workflow actions for Update Record, Assign Record, and Change Status. After all, arent assigning records and changing their status values really just specific kinds of updates? While that may be true, they are specific enough to have their own workflow actions, and if those are the things you want to do, you must use those actions! For example, if you use the Update Record action and in the workflow design environment try to change the value for the Owner attribute, youll get an error message. And if you look within the Update Record form for the Status value, you wont see it. It only shows up when you specifically select the Change Status action. Examples 1. Basic Step by step example showing how to cc a record owners manager for an app or case escalation scenario. Makes point that manager field on user record is important! 2. Step by step example of incrementing a times referred field on the Lead entity. 3. SHOW (skip the walkthrough) example of built-out email for a registration confirmation. Show subject line dynamically filled in, as well as complex email message body. Illustrates custom entity also. As a general rule, just remember that that you need to use the Update Record action to change the value of any attribute on a recordEXCEPT for Status (thats what Change Status is for), and Owner (thats what Assign Record is for).
34 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Assign Record
Use this action when you want to automatically change the value of the Owner attribute that is, assign a record. As we noted previously, you cannot update the Owner value using the Update Record action if you try to do that youll get an error in the workflow design environment. The following figure shows the Step Editor after weve selected the Assign Record action from the Add Step menu:
Figure 2-11 Using the Assign Record Action

You can use the lookup icon to select a specific user to assign the record to. If you want to assign the record to a logical user (e.g., a users Manager), use the Set Properties button and the Dynamic Values function. Heres an interesting example of when you might use Dynamic Values in the Assign Record action. Suppose that in your organization you have what we might call a strong named account business rule, that says every child record created for an Account record automatically has the Account owner assigned as its owner as well. By default, Dynamics CRM does not do this; its default is that the creator of a record is the records Owner. To implement this strong named account business rule, you can click Set Properties on the Assign Record step (above example), and configure it like this:
Figure 2-12 Assigning Contact Record to Owner of Parent Account Record

Assuming the Contact record being created by the workflow actually contains a value in the Parent Customer field, this workflow will work correctly, assigning the Contact record to the same user who is
35 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

the Owner of the Parent Customer. But what if the Contact record is created as a standalone record that is, without anything in the Parent Customer field? Heres an instructive exercise you should try various permutations on, to see how workflows adapt to unexpected conditions: 1. Create a workflow like the one we just showed, and run it against a Contact record that has a Parent Customer. You will see that it works as expected. 2. Now run it for a standalone Contact record one that does not have anything in the Parent Customer field. You will see that the workflow doesnt work it gets stuck with a status of Waiting since theres nothing in the Parent Customer field and it doesnt know who to assign the record to. (There are various ways of handling this, but thats not the point of this exercise.) 3. While the workflow is still in its Waiting status, open up the Contact record and assign it to a Parent Customer. Save the record. 4. Then open the workflow and click Resume from the toolbar, as we indicate in the following figure. Youll see that after resuming, it works correctly and the Contact record will be assigned to the same Owner as the Account record!
Figure 2-13 - Workflow Error

One more interesting point about this has to do with the topic we discussed earlier, Monitoring Workflows. As we mentioned in that section, workflow status can be viewed from a number of different places. In the current example, if you view the workflow from the Contact record, you will see this one with a status value of Waiting (assuming you havent fixed it yet by adding a value to the Parent Customer field). As an alternative, you could navigate to Settings/System Jobs, and then filter the list to see a view like the following:

36 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 2-14 - Viewing Workflow Status from System Jobs

Notice here that weve selected Workflow from the Type pull down list, and Suspended System Jobs from the View. While it might be heartening to know that even if you dont fix it, this workflow will run again on December 30, 9999, it will run a lot sooner if you assign the Parent Customer and then click Resume!

Send Email
Use this action to send an email message automatically as part of a workflow. You can either create a new email message, or use an existing email template for the entity the workflow is created for. Heres what it looks like in the Step Editor, after using the Add Step menu to add a Send Email step, and then pulling down the Send Email menu:
Figure 2-15 Using Send Email Action Select Create New Message or Use Template

You can configure the email who it will go to, the subject and body of the message, and so forth, by clicking the Set Properties button. In the next figure, you see an example of the workflow design form for an email being created for a custom entity. The example here is a Registration entity, which our company uses to track information about the registration of contacts into IMG training classes.

37 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 2-16- Using Dynamic Values to Construct Email

You can see from this form the extensive use of Dynamic Values to mix static and dynamic content into both the Subject and the message body (attribute: Description) of the email record. Also, notice that you can even use the workflow design environment to attach a document to a workflow. A good example of where you might use this functionality is in a so-called auto-responder email for a new Lead record. Suppose you have a form a visitor to your web site can fill in and behind the scenes a new Lead record in your CRM database is created. You might allow them to request a white paper on the form, and have an automatic workflow on the Lead create trigger send an acknowledgment email with the white paper as an attachment! We will show a demonstration of this at the end of the chapter. Who can you send emails to? You can only send an email directly to a limited number of record types, including Account, Contact, Lead, and User. (Note that each of these entities has a built-in Email attribute.) We will discuss this in more detail in Chapter 4, in the Dynamic Values section. __presents a brief summary of the kinds of records you can use the Send Email action on.
Table 2-5- Which Records does Send Email Work for?

Entity Account Contact

Send Email Directly? Send Email Indirectly? Yes Yes


38

Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Lead User Opportunity, Quote, Order, Invoice Case Any User-owned Entity Any Organization-owned Entity Custom Entities

Yes Yes No No No No No

Send to Customer/Potential Customer Send to Customer Send to Owner, Created By, Modified By Send to Created By, Modified By Send to Owner, Created By, Modified By Create 1:N relationship from Contact and Send Email to Contact

One example of where these limitations are important is for custom entities. Figure 2-16 illustrates constructing an email for a custom entity. But notice that the To value is actually for the Contact. This can be confusing the first time you encounter it, since although you can add an attribute with a type of Email to a custom entity, you cannot actually send an email directly to a record for that entity using the value of that custom attribute! But you can create a relationship between a custom entity and one of the entities usually Contact that you can send an email directly to, and then exploit the relationship within the workflow design environment to send an email. Again, I wanted to point this out here, but we will cover it in more detail in the next chapter.

Start Child Workflow


There are a number of scenarios where you might need to use the Start Child Workflow action. One frequently mentioned example is when you have a common piece of functionality that can be executed by a workflow, and it can be used by many different workflows. In this scenario, rather than implement the functionality repeated times in many different workflows, you can write it once and simply call it from other workflows. Then, if you ever need to change it, you change it in one spot and youre done. Another, perhaps more interesting example, is for what is generally referred to as a recursive workflow. That is, a workflow that calls itself. This is often used for escalating scenarios. For example, if a service case record is created and not resolved within a certain period of time, you might have a workflow that progressively escalates the case perhaps alerting supervisors, assigning it to different users or queues, etc. Heres an example of what the Step Editor might look like in such a scenario. Focus for now on the last step shown in the next figure, where you can see that the Start Child Workflow action is used to call the Case Escalation workflow from within the Case Escalation workflow the definition of recursion in this context.

39 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 2-17 - A Workflow Starting Itself as a Child Workflow

We will discuss this topic more thoroughly in the next chapter, and will see lots of examples of the general technique.

Change Status
Use the Change Status action when you want a workflow to change the Status of a Dynamics CRM record. Although this might sound obvious, there are some subtleties around this important workflow action. Probably the easiest thing to get confused about is the distinction between the Status and Status Reason attributes. These attributes exist for every entity in Dynamics CRM, and in all cases work the same way: for each value of the Status attribute, there are one or more values of the Status Reason attribute, one of which must be selected to change the Status value. For example, an Opportunity record can only have one of three potential values for the Status field: Open, Lost, or Won. These values can never be customized. But for each of these Status values, you can have one or many Status Reason values, and these can be customized. These are especially important to understand in the workflow context, because changes in status when an Opportunity is Won or Lost, when a Case is Resolved, or when a Lead is Qualified are often important triggers for business processes, or important outcomes of a process. Consider the following figure, which shows a Change Status step for a workflow on the Opportunity entity:

40 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 2-18 Using the Change Status Workflow Action

The pull down list allows you to select the value you want for the Status Reason attribute; since it determines the Status (Open, Won or Lost for Opportunity), you dont select Status directly. And notice the custom values for the Status Reason. Weve added values specific to our business (e.g., Class Cancelled), and one that is relatively generic (Manually closed past Est. Close Date). The scenario we illustrate here might be that a sales manager goes into Advanced Find and does a query to find all of the Opportunity records whose Est. Close Date is already past. Then he or she can exercise discretion about which ones to close out. If this is done in an on-demand workflow against selected records, those records could then be included in a report, circulated to the sales team who then might be responsible at the next sales meeting for explaining to everybody why they neglected their opportunities so badly! Obviously there are many scenarios and business processes which would result in changes to a records Status value. But this simple example makes the point that sometimes manual processes can be used to complement automated ones, and preserve some flexibility and judgment within a process. It also makes the point that to change the Status, you have to change the Status Reason!

Stop Workflow
The Stop Workflow action performs as advertised, stopping the current workflow. Sometimes this is a housekeeping exercise at the end of a workflow. Sometimes its not, however. For example, as youll see in Chapter 4, you can have a workflow recursively call itself. When you do this, you can get into a situation where multiple versions of the same workflow process are in memory, so heres one example where you will need to make sure to add a Stop Workflow action immediately after the recursive call.

Monitoring Workflows
In Dynamics CRM 4.0, a special application known as a service (specifically, the Microsoft CRM Asynchronous Processing Service) runs behind the scenes, evaluating and monitoring workflows along with any other CRM functions that run asynchronously. This architecture makes it easy to monitor
41 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

workflows from within the CRM user interface unlike CRM 3.0, theres no need for a separate application to monitor workflows. There are three basic ways you can see the progress of workflows: 1. Navigate to the workflow record and monitor jobs 2. Navigate to an Entity record and monitoring workflow jobs running on that entity 3. Navigate to System Jobs and monitor the progress of all workflows.

Monitoring Workflows from the Workflow Record


Assuming you have Read privileges on the Workflow entity, click Settings, then Workflows, and double-click the workflow youre interested in. If you click Workflows in the System Jobs section, you will see a list of all running and executed instances (jobs) of that workflow. If a workflow is still running, you can open up the record for that job and see what its currently doing. If a workflow is completed, you can open up the record and see whether it was successful, what actions were taken and so forth.
Figure 2-19 - Monitoring Workflows from the Workflow Record

Monitoring Workflows from an Entity Record


You can navigate to a specific record on which a workflow has been run or is running, and click on Workflows in the Details section to see a list of all the running or completed workflow jobs.

42 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 2-20 - Monitoring from the Entity Record

Monitoring Workflows from System Jobs


If you have at least Read privilege on the System Job entity, you can click System Jobs from the Settings area, and monitor all workflows in your system, along with all other asynchronous processing jobs. For example, if you select Workflow from the Type pull down list, and Lead from the Entity pull down, you can see and access to all of the workflows that are either in process or completed against the Lead entity.

43 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 2-21 - Monitoring from System Jobs

Chapter Summary
In this chapter we started with the basics the properties a workflow can have, and some typical scenarios that can be addressed by workflows with those properties. Next we introduced the mechanics of using the Step Editor. Most of your work as a designer of workflows will be performed in the Step Editor, so you need to be familiar with it. After that we covered in some detail the seven actions an out of the box workflow can perform; finally we ended up with a discussion of how you can monitor workflows, and some of the most important improvements of monitoring in CRM 4.0 compared to the previous version. As I mentioned, the seven actions a Dynamics CRM workflow can perform can be thought of as the work in workflow. The most important topic in the next chapter is the flow in workflow, represented by so-called Check Conditions and Wait Conditions. Before going on, make sure you review the demonstrations for chapter 2 (next). You will see a few examples in the demonstrations of conditional checking and some other topics that will be covered in detail in chapter 3. I did that on purpose, partly to make the demonstrations more interesting, and partly to motivate the discussion in the next chapter. I kept them pretty basic, however, so if necessary, review them quickly for now, and come back and study them in more detail after chapter 3.

44 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Demonstrations for Chapter 2


Demonstration 2.1 Configuration Workflow for the User Entity
Workflows are often used to create automated business processes, but sometimes theyre useful for more mundane tasks, such as updating data. A good example of this is a workflow that updates values for the User entity. If all or many of the Users in your organization will share the same values for Main Phone, or Address, or (even more likely) Incoming and Outgoing Email Delivery Method, setting them with a workflow can save you a lot of time. I will present an example workflow here, created for the User entity, with the following characteristics: Any time a new User record is created, set the incoming and outgoing Email configuration settings to Email Router. Set some of the address or other profile values that will be shared by all users on a default basis. It will run automatically on the Create trigger, but will also be available to run on demand, so that it can be used to fix up any previously-entered User records that did not have these values correctly set. Heres a step-by-step process you can use to do this: 1. Click Settings on the site map, then click Workflows, then click the New button. 2. Give it an appropriate name (I used Configuration User for this example), select User as the entity, make sure New blank workflow is selected as the Type, then click OK. 3. In the Workflow Properties section, select Organization for the Scope, select the Record is created checkbox to make it run on the Create trigger, and select On demand in the Available to Run section. These settings are illustrated in Figure 2-22:
Figure 2-22 - Configuration Workflow Properties

45 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

4. In the Step Editor, select Update Record from the Add Step menu, then supply appropriate descriptive text, as is illustrated in Figure 2-23.
Figure 2-23 - Update Record for User Configuration

5. Click Set Properties. In the Update User dialog select the values that all Users will have in common. Figure 2-24 shows an example, with some of the more common shared values (main phone, email settings, license type) filled in.
Figure 2-24 - Setting Shared Attribute Values for User Records

6. Click Save and Close once to close the Update User dialog. Then click Save and Close again to close the workflow environment. Then select the workflow and click Publish. This workflow will run automatically on all new user records as they are created. But its also available for on demand use, in case you have previously created User records with attribute values that need updating. In Figure 2-25 you can see a number of User records selected and the availability of the Run Workflow button on the toolbar. Remember this will only be available if there is an on demand workflow in a published state.

46 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 2-25 - Selecting User Records for On-demand Workflow

Demonstration 2.2 Basic Lead Assignment Workflow


In this demonstration Ill show you a characteristic assignment workflow. Well use the Lead entity for the example, but the same basic techniques will apply any time you need to assign a record to a user based on some criteria. And that happens a lot! Although we havent yet discussed conditional branching and some of the other functions this workflow includes, Ill go through it step-by-step so you can follow along, and well cover those topics thoroughly in the next chapter. In this example, lets assume that leads are assigned on the basis of industry. In Dynamics CRM, the Lead entity comes pre-configured with an Industry attribute, which is a picklist on the Lead form:

47 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 2-26 - Industry Pick-List on Lead Form

It comes pre-populated with thirty-three industries, which you can customize, delete, or add your own. Suppose for this example that we have two lead qualifiers; each of which specializes in certain related industries. When a new Lead record is created, the value of the Industry field will determine who gets the new lead. Figure 2-27 shows a simple workflow that will perform this assignment process, with descriptive text so we can remember what it does!
Figure 2-27 - Assigning Leads by Industry

To create a workflow like this, follow these steps: 1. Create a new workflow, give it an appropriate name, and select Lead as its entity.
48 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

2. Give it a Scope value of Organization, and configure it to run automatically when a new Lead record is created. (For an assignment workflow like this, I will often make it available for running on demand, in case there are already records in CRM that I want to run it against.). You can see these settings in Figure 2-28.
Figure 2-28 - Lead Assignment Workflow Properties

3. Optionally minimize the Properties section, and click Add Step. Select Check Condition, and then click <condition>(click to configure). 4. In the Specify Workflow Condition dialog, select Lead in the first column, Industry in the second, and Equals in the third:
Figure 2-29 - Specifying Workflow Condition

5. Click the ellipsis in the fourth column, and as youll see, when specifying a condition for a multi-valued picklist, you can select one or more values in a dialog that looks like this. I show it here with specific industry values selected for our financial, insurance and business services lead qualifier:

49 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 2-30 - Checking for Multiple Values

6.

Click OK, then click Save and Close in the Specify Workflow Conditions dialog to return to the Step Editor.

7. I repeated steps 3-6 for the next lead qualifier, selecting different industries.

Notice in Figure 2-27 the final part of the If block is an Otherwise condition. This is whats known as a Default Action, since any actions specified within this clause will execute if and only if none of the previous conditions are satisfied. For the lead assignment process I described above, this default condition effectively assigns any lead that hasnt already been assigned to either Amy or Anton to Chris. He might be the sales manager, or he might be an all-purpose qualifier; there are obviously many different ways of doing this, but this approach illustrates a few important points we will review in more detail throughout the rest of the book: One of the most important is how Conditional blocks work in Dynamics CRM workflows. If one of the conditions is satisfied (evaluates to true) the workflow actions within that conditional (you can tell because theyre indented underneath it) will all execute. Then, all of the other conditions are skipped. Effectively, these operate similarly to Case or Switch blocks in some programming languages. So, if you accidentally add Durable Manufacturing to the list of industrys in Amys conditional checking, this workflow will assign any of those new leads to Amy, then it will drop out and Anton will never get those. This means the order of your conditional blocks is important!

50 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Another perhaps more obvious point is that when you have a conditional check for multiple values from a list, as we do here, these are all Or comparisons: if any one of the values is satisfied, the condition evaluates to true they dont all need to be satisfied!

Demonstration 2.3 Case Assignment and Routing Workflow


As I will mention more than a couple of times in this book, Case records are different in important ways from other records. One of the most important differences is that cases in addition only to the Activity record types can be assigned directly to a Dynamics CRM Queue. This is an important part of many workflows having to do with Case, Activity and other record types, so well review a simple example here. Suppose your firm uses the Case entity to track service requests for customers, and that you need to implement a simple Case routing workflow: If a new Case record has to do with Dynamics CRM, assign it to the CRM queue If it has to do with SharePoint, assign it to the SharePoint queue All other cases go into a general purpose Customer Service queue.

Heres how the queues will look in this scenario:


Figure 2-31 - Dynamics CRM Queues for Case Routing

I will use a slightly modified Subject Tree for this example. As you can see from the following figure, I added custom subjects for CRM and SharePoint these are what we will route cases according to:

51 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 2-32 - Subject Tree

To create the simple Case routing workflow for this scenario, follow these steps: 1. Click Settings on the Site Map; then click the Workflows tab; then click the New button. 2. In the Create Workflow dialog, supply an appropriate name and select Case as the entity for the workflow. Select New blank workflow for the Type:
Figure 2-33 - Supply Name and Select Case Entity

3. Click OK to open the workflow design environment. 4. In the workflow Properties section, select Organization for the Scope value, and click on the Record is created checkbox. Although you dont see the word trigger in this dialog, that is conventional way of referring to the four options in the Start when section, so thats the convention I will adopt for the rest of the book.

52 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 2-34 - Specify Scope and Trigger

5. I usually click the expand/collapse button to the left of the Hide Workflow Properties text in the previous figure, to free up screen real estate. Heres what the design environment will look like when you do that:
Figure 2-35 - Collapse the Properties Section for More Room

6. In the chapter 3 Ill spend more time with step by step explanations, for now Ill give you the summary version. The next figure shows how the Step Editor will look after building out the basic Check Condition statement for this workflow, and including within each condition an appropriate Assign Record action:
Figure 2-36 - Assigning Case Records to Queues Based on Subject Value

53 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

7. Although its note required, its bad form and definitely not a best practice to leave workflows uncommented, so in the next figure you can see an example of how much better the same workflow looks if its properly commented:
Figure 2-37 - Same Workflow, with Comments

8. This is a perfectly functional workflow, if somewhat simplistic, and if you saved it and published it, you could test that it routes Case records appropriately, based on the value entered for the Subject field. There are a few subtleties about the workflow that this executive summary version doesnt addressbut as I said, weve got plenty of time for those in the rest of the book!

Demonstration 2.4: Setting Default Values for Account Records


Account and Contact records generally referred to in Dynamics CRM as customer records are examples of relatively static records. Characteristic workflows for these entities often have to do with setup, filling in default values, assigning records to the right sales person, and so forth. The Account Setup workflow we review now is an Automatic workflow, scoped at the Organization level, and it runs on the Record is created and Record attributes change triggers. The attributes whose changes will trigger the workflow are the Zip/postal code and the Account Category fields. When its triggered, the workflow does the following: uses conditional logic to assign an Account record to a territory, based on the value entered for the zip code; uses conditional logic on Account Category, to fill in default values and assign to a specific account manager if the value is set to Preferred Customer;

54 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

if anything other than Preferred Customer is selected, it sets appropriate values and uses the Queue technique introduced in the Lead Assignment workflow to put a task in an Unassigned Accounts Queue and let the sales team accept these new accounts on a first-come first-served basis.

Heres a screenshot of the Step Editor for this workflow:


Figure 2-38 - Step Editor for Account Assignment Workflow

First, notice that the workflow consists of a series of what we refer to as conditional blocks. This structure is different from the process-style workflows characteristic of the Case or Opportunity entities. Each of these conditional blocks is for a specific attribute the first one for ZIP/Postal Code and the second for Account Category and populates certain values and takes specific actions depending on the values selected. So you could consider simplifying the Account form, for example, having a section on the first tab with a small number of required fields, and then using a workflow like this to do most of the data entry automatically. Once the workflow is Published, you can test it by creating a new account record. In the example here, if the Account Category selected is not Preferred Customer, a Task record associated with the Account is created, and assigned to the Account Assignment queue. Then the workflow waits until the Task record is accepted, and assigns the Account record to whoever accepted the task. Heres a good way to get a better view of a running workflow:

55 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

1. After youve created an account record and triggered the workflow, click on Settings, then Workflows, then double-click the workflow. 2. Under System Jobs, click Workflows. 3. Youll see a list of the running or completed instances of the workflow, and you can double-click any of them to check the status. Open the current one. 4. From the File menu (upper left corner of the dialog, with the Dynamics logo icon), select Print Not only will you get a printable report of the running workflow, but the visual display is generally better than youll see elsewhere this is a good thing to have in your bag of tricks! Heres an example:
2-39 - Printable Workflow "Report" View

56 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Chapter 3 - Dynamic Values and Flow of Control


Introduction
Now that weve reviewed some of the basic uses of workflows, well go into more detail. After covering two important background topics, we will examine one of the most important new features in Dynamics CRM 4.0 workflows: Dynamic Values. We examined those briefly in the previous chapter; here we will cover them in more detail. Then, we will cover the conditional logic you can use to control the flow of your workflows. There are two main areas here: conditional checking, such as we saw previously in the Lead assignment workflow; and the important new wait conditions that allow your workflows to wait for periods of time or timeout until various date/time conditions are met.

Entity Relationships, Record Assignment and Ownership


Entity Relationships
One of the most important aspects of Dynamics CRM is how easy it is to create relationships between system and custom entities. In an important sense, Dynamics CRM can be thought of as a development platform for custom database applications. In all relational databases, including Dynamics CRM, the most common relationship between entities is a one-to-many, or parent-child relationship, such as exists out of the box in CRM between Account and Contact, or Contact and Opportunity. The jargon around this can be inconsistent; for example sometimes the entity on the 1 side of a 1:N relationship will be referred to as the Primary entity, sometimes as the Parent, and so forth. Its especially important to understand how entities are related in Dynamics CRM when youre designing workflows. For example, if you create a workflow on the Opportunity entity, you can refer in the workflow to values on the related Account or Contact records. This is because both Account and Contact have a 1:N relationship to the Opportunity entity; in the Dynamics CRM workflow environment they will be referred to as having a Primary relationship to Opportunity. So if you have a workflow for an Opportunity, it can check conditions or update values on the Account record its a child of. But it doesnt work the other way: a workflow created for the Account entity cannot access or update values on any of the related Opportunity records. (Although it can create child records well discuss this in detail a little later.)

57 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Note that Advanced Find works in much the same way. If youre using Advanced Find to query against Opportunity, you can filter on and display columns from Account, but not the other way around. And as long as were on this topic, it might be interesting to note that the Report Wizard (new in Dynamics CRM 4.0) does not work this way. In the Report Wizard youll want to pick as your primary entity the 1 side of the 1:N relationship. You can think heuristically of looping through all of the Opportunity records related as child records to their parent Account record.

Record Assignment
There are two basic kinds of entities in Dynamics CRM organization owned, and user owned. In most cases, the so-called user owned entities can only be assigned to a CRM user that is, a specific record of the User entity. But there is one important exception to this: the Case and Activity entities (Task, Email, Phone Call, Fax, Appointment, Campaign Response, Service Activity) can be assigned to either a User, or a Queue. This can be confusing for a number of reasons. One is the obvious difference between this and all of the other entities in CRM, which can only be assigned to a User, not to a Queue. Another is that assigning a Case or Activity record to a Queue doesnt really assign it the Owner value doesnt change when its assigned to a Queue it simply places the record in the Queue, where it will be available for any User with the appropriate permissions to Accept and place in his or her personal (In Progress) queue. (At which point it does change ownership.) As you will see, this issue of how records are assigned to users (or queues) has lots of important applications in Dynamics CRM workflows. For example, cases or activities can be routed (assigned to users or queues) according to conditions such as which subjects or products they concern, severity level, or a customers contract status.

Assigning Records to Queues


Previously we discussed the Assign Record action, and showed how you can use it to have a workflow assign a record to a user based on certain criteria, such as attribute values for the record. Remember that a few entities (all the Activity type entities, plus the Case entity) can be assigned to a User or a Queue. (All other records can be assigned only to a User.) __ shows a workflow typical of a case routing scenario. In this example, when a new Case record is created this workflow will run, and it will check the value of the Case Type picklist. Depending on the value, the Case record will be assigned to one of two queues.

58 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 3-1 Assigning a Case to a Queue Based on Case Type

In the previous sentence, I put assigned in quotation marks on purpose, to emphasize that even though assigning a record to a queue will place it in the queue, it does not change the Owner of the record. EVERY (user-owned) entity will ALWAYS have one and only one User as the value for the Owner field. To illustrate, suppose Amy Alberts creates a new Case record, and records its Case Type as Problem. The Case Routing workflow will place that new record into the Problem Reports queue, according to the logic of the workflow just shown. But if you examine the record in the queue, you can see that its Owner is still Amy Alberts:
Figure 3-2 - Queue Items are NOT Owned by the Queue!

In this regard, its also important to understand that a record can only be in one queue at a time. So for example, if you have an escalation workflow that assigns a Case record to a high-priority queue if too

59 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

much time has elapsed since it was opened, you dont need to worry about unassigning it from any other queue it might have been in previously! Since this can be a confusing topic, lets extend the Case Routing workflow slightly to illustrate one more point about working with queues. Suppose all Case records with the Problem Case Type need management attention. If Paul West is the Customer Service Manager, the following workflow will, in addition to placing the new Case record into the appropriate queue, create a followup task for Paul only if the Case Type is Problem:
Figure 3-3 - Create a Task Record after Placing in Queue

If you click the Set Properties button, you will see that you can simultaneously give the new Task record some initial values, as well as assigning it to a user, like this figure shows:
Figure 3-4 - Assigning Task to User

60 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

But suppose instead of assigning this task to a user, you wanted to assign it to a queue. If you click on the lookup button on the Owner field, you will notice that in this context using the Create action to make a new record you cannot select a Queue: only Users will be selectable. This can be confusing, as you find yourself thinking, Wait a second. I know I can assign a Task to a Queue! Why isnt that an option? The reason for this has to do with the rule we proclaimed previously, EVERY entity will ALWAYS have one and only one User as the value for the Owner field. In this context, this means that a real Owner (i.e., a User) must be assigned before a record can be assigned to a queue.

Dynamic Values
In the previous examples weve seen that there are two main work areas in the workflow design environment: the Properties area and the Step Editor. Most of your work in customizing workflows will be in the Step Editor, and much of that work will be in the workflow design environment version of the CRM entity forms. The entity forms you will see as a workflow designer bear superficial resemblance to their analogy in the user experience. For example, you can tab between the fields on a form, and you can use the key combination ctrl-shift-F as a toggle switch to toggle so-called Form Assistant. For example, compare the user version of the Lead form with the workflow design version:

User version of Lead form

Workflow Design version of Lead form

61 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

The most obvious differences are that data arent exposed, the form toolbar isnt exposed, and the Details and other sections for related records arent exposed on the workflow version of the form. Slightly more subtle differences are that the Notes tab isnt exposed on the workflow form, and that the workflow form has an additional tab Additional Fields that is used to expose all of the fields that are NOT exposed on the user form. Well discuss that in detail later. Note that the Form Assistant is exposed on both versions of the form. This is much more important in workflow design than in the user experience, because it exposes the critically important Dynamic Values feature one of the most important new feature areas in Dynamics CRM 4.0 workflow. It allows you to update field values dynamically, from other fields in the same or related records, to increment or decrement numeric fields, and to assign complex wait conditions to date/time fields. Dynamic Values plays a role in workflow design similar to Advanced Find in the user experience: its a foundation tool you will use over and over again, in many different contexts. Using Dynamic Values can be confusing at first, partly because it is very context sensitive: you will see different options in the various lists as you tab between the different fields on the workflow design form. The following figure isolates just the Form Assistant in the workflow design environment, where youll set dynamic values. There are four main options for you to use:

62 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Table 3-1: Dynamic Values Form Assistant

Dynamic Values Form Assistant

What the Tools are used for

Operator. Determines which operation will be performed against the currently selected field. Set to is the default operator. Increment by, Decrement by, and Multiply by are all available only for numeric fields when the Update Record action has been selected. Clear will remove any existing value from the field, and is only available for the Update Record action.

Look for. The Look for section has two pull-down lists. In the first one, select the primary entity, any related entities, or Workflow. (Well discuss the Workflow option in a separate section.) The second is the field list it exposes attributes of the selected entity, but only attributes of the same data type as the currently selected field.

Dynamic Values box. Once youve selected the Operator and Look for values, click the Add button to get them in the Dynamic Values box. Once theyre in the Dynamic Values box you can click the OK button to insert them into the selected field. This UI device seems cumbersome at first, but you get used to it the more you do it.

Default value. This is important when the Dynamic Value youve configured might not contain data. For example, the figure shows a common scenario: we want an email to start with Dear, and then concatenate a Contacts First Name, but substitute colleague if the record doesnt contain a First Name value.

63 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Well go through a step by step example to show you the basic use of these options, using the familiar Lead entity to illustrate. 1. Create a new workflow on the Lead entity, giving it Organization scope, and make it an automatic workflow on the Create trigger. 2. Pull down the Add Step menu and select Send Email. Provide some (optional) descriptive text, and then click the Set Properties button. This will open up the Send Email Webpage Dialog you see here:
Figure 3-5 - Send Email Dialog

3. Tab through the From, To, Cc, and Bcc fields and notice that the Forms Assistant values dont change. Then tab to the Subject field and notice the difference. If youre on User, or other people fields (From, To, etc.) youll have Dynamic Value options relevant to that context. But if youre on a text field such as the Subject line or the message body of the email, youll have Dynamic Values you can use to populate text fields. 4. With the cursor on the Subject line, enter the text Thank you for your recent inquiry regarding . Then keep your cursor positioned at the end of the subject line and in the Forms Assistant pull down the second list in the Look for section. (Remember this exposes all of the fields for the selected Entity, in this case the Lead entity). Select Topic from the list and click the Add button to move it into the Dynamic Values box. 5. Then click the OK button and you should see it inserted as dynamic text at the end of your Subject line, as the following figure shows:

64 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 3-6 - Inserting Dynamic Values into Email

You can use the same technique to build out the body of the message, and can freely intersperse static text with Dynamic Values. And note that even in this simple example we are exploiting the built-in support that Dynamics CRM workflows have for related entities: this workflow is written for the Lead entity, but were creating a record (Email) that has a N:1 relationship to Lead, so within the Email record we can place values from the primary (Lead) record. Next well build out the message body, and illustrate the use of the Default value option. 6. Position the cursor in the message body, and type Dear and press the space bar. 7. In the Dynamic Values field list select the First Name field, click Add, and then type the text colleague in the Default value field. Then click OK. 8. Then type a comma as static text, and your form should look like this:

65 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 3-7 - More Dynamic Values

Dynamic Values are Context Sensitive


This important point is worth repeating in more detail. The field type you have selected in the workflow designer will determine what Dynamic Values you can select from. Selected Field Data Type Text Date/Time Numeric Customer (Composite Customer record) Lookup User Lookup Dynamic Values Available All fields (text, date/time, numeric) Date/Time fields only Numeric fields only Customer Lookup only User Lookup only

Using Increment, Decrement and Multiply Operators


Table 3-1 included a brief description of the Dynamic Values Operator settings. The Increment by, Decrement by and Multiply by operators can all be used on numeric fields. In addition, you can use Increment by on a text field to maintain the previous value and concatenate a new value to it. Using Increment by to add values to numeric fields One good example of when you might need to do this is for a recursive workflow one that calls itself repeatedly. You can use recursive workflows to implement escalation business processes. For example, you might have a service level agreement that specifies a Case record must be resolved within a certain period of time, or the Case gets escalated to a senior support technician. There are many
66 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

scenarios that require this kind of recursive workflow and we will look at some in detail later in the book. Regardless of the specifics of the business process, it will often be important to know how many times one of these recursive workflows has recursed, so to speak, and the Increment by operator gives us a way to do that. To illustrate with an example we will finish later, suppose you have a recursive workflow on the Case entity, and you need to know how many times the workflow has been escalated. In Figure 3-8 you see the Dynamic Values Form Assistant open with a numeric field selected. (Escalation Counter is a custom attribute.) The default Operator is Set to, but if what you need to do is keep track of how many times a recursive workflow has called itself, you can use Increment by for that. In Figure 3-9 you can see how it looks after you follow these steps: 1. Make sure the cursor is positioned on the numeric field you want to increment. 2. Select Increment by in the Operator pull-down list. 3. Enter the value you want to increment by (1, in this example) in the Default value text box. 4. Click OK.
Figure 3-9: Using "Increment by" Operator

Figure 3-8: Dynamic Values with Numeric Field Selected

Using Multiply by Dynamics CRM does not have a built-in calculated field type, but you can use the Multiply by operator and a workflow to get something close to it. For example, the Opportunity entity has built in attributes Est. Revenue (attribute name estimatedvalue) and Probability (attribute name closeprobability). Suppose you wanted a probability-weighted revenue forecast. You can create a
67 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

custom attribute, and then use a workflow to multiply the built-in fields by each other to update the custom attribute. Here are the three attributes I will use to illustrate, all on the Opportunity entity:
Table 3-2 - Opportunity Attributes for "Calculated" Field

Attribute Display Name/Entity Name Est. Revenue/estimatedvalue Probability/closeprobability Weighted Revenue/new_weightedrevenue (depends on your customization prefix)

Data Type Money Int Money

Description Built-in Built-in Custom attribute to update in workflow. The value it contains should be Est. Revenue multiplied by Probability

After adding the custom attribute, we need to build a workflow to update its value with the product of the Est. Revenue and Probability attributes. The Multiply by operator works by multiplying the current value of a field by a single numeric value. What this means is that you cannot enter a formula as you might think. My inclination was to have a workflow update the weighted revenue value with something like this: =(est. revenue)*(probability) Unfortunately its not quite that easy! Since the Multiply by operator only allows you to update the current value by multiplying it by something else, the workflow needs to perform three consecutive Update actions: 1. Update weighted revenue with the current value of Est. Revenue. 2. Update its new value by multiplying it by Probability. 3. Update its new value by multiplying it by .01 (since Probability is an integer value!) Figure 3-10 shows a simple example of this, with three Update actions generously commented to make it somewhat self-documenting.

68 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 3-10 - Three Update Actions to Calculate "Weighted Revenue"

Figure 3-11 illustrates how to configure the Update Record action for step 2. In step 1, the Weighted Revenue field was updated with the value of Est. Revenue, so in step 2 we need to multiply it by Probability:
Figure 3-11 - Multiplying Current Value of Field by Probability

After that, the Update Record action in step 3 will account for the fact that Probability is an integer (e.g., 50% is represented by the integer value 50). To do that, multiply by .01, as we illustrate in the next figure.

69 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 3-12 - Multiplying Current Value by .01

Here are a few comments and suggestions in case you need to implement functionality like this: The reason it takes three Update Record actions to perform the calculation is that youre always updating the current value of the field, and you can only perform one operation at a time. It would be better if you could use formulas, but you cant. You can imagine a more complicated calculation might take many more Update Record actions. This might become clunky or impractical in the workflow approach I discussed here. If it does, it might turn out that using client-side (Jscript behind form events) is a better approach. While some people might argue that its ALWAYS better to use the client-side script approach, I dont agree with that. For a problem like the one were trying to solve here, you can use either, and which one is better depends on your requirementsas well as your skill-set! Another disadvantage of the workflow approach to calculating fields is the latency problem: Dynamics CRM workflows run asynchronously, one implication of which is that calculated fields will take some time to update on the form, generally from 15 to 30 seconds. If you use the workflow approach, you will probably want to take the calculated field off the form, or maybe hide it on another tab. How should a workflow like this one be triggered? You might need to run it manually for records that were created before you implemented it. On an ongoing basis you might want to run it when a new record is created, or when the Est. Revenue or Probability attributes change. Again, the specifics will be determined by your business requirements. This figure shows what would be a reasonable configuration of an automatic workflow to do this:

70 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 3-13 - Automatic Workflow to Calculated "Probability-Weighted Revenue"

Using Increment by to concatenate text fields While the Increment by operator may be more commonly used to manipulate numeric fields, you can use it to good effect on text fields as well. One technique I like is to use Increment by on a records Description field, to create an informal audit-trail regarding status changes and so forth. For example, Figure 3-14 shows how you might use an Update Record action to update the Description field on the Campaign entity with information from a Campaign Activity record.
Figure 3-14 - Using Increment by to Add on to Existing Text

71 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

The key thing to note here is that if you use Increment by rather than the default Set to, the text you increment by gets concatenated at the end of any previously existing text; if you use Set to it will replace it. The workflow I discuss here is created for the Campaign Activity entity. Since every Campaign Activity is associated with a Parent Campaign record, a workflow running against Campaign Activity can update the Parent Campaign. I include a more detailed discussion of this workflow in the demonstrations at the end of the chapter, but for now, you can see the end result of an audit workflow like this, after two Campaign Activities have been added to a Dynamics CRM Marketing Campaign. This is shown in Figure 3-15.
Figure 3-15 - Marketing Campaign with Informal Audit Trail in Description Field

Dynamic Values: Related Entities


One of the most important and frequently used aspects of Dynamic Values is the ability to exploit the database relationships between Dynamics CRM entities, including built-in CRM entities such as Account, Contact, and Opportunity, as well as custom entities you create. The basic rule of how you can use database relationships in Dynamics CRM 4.0 workflows is this: If the entity your workflow rule is created on has an N:1 relationship with another entity, you can use attributes from the entity on the 1 side of that relationship in your workflow rule. Again, the jargon around this can be inconsistent at times. You will sometimes see a one-to-many relationship referred to as a parent-child, sometimes as a primary-related, and so forth. You will
72 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

also sometimes see statements such as you can use the Dynamic Values Look for lists to include fields from any related entities in your workflows. You should understand now that this last statement isnt quite true: you can only include attributes from the entities the workflow entity is related to with an N:1 relationship. Well go through an example now to clarify this important point. One frequently used workflow feature is to create tasks for users. For example, a follow-up task might be created for a sales rep when a new Opportunity record is created. You can do this with a workflow rule on the Opportunity entity, and exploit the fact that it has an N:1 relationship with the Contact and the Account entities to put lots of useful information into the task record itself. The following figure shows the workflow form design environment for the task entity, in the process of creating a Task record for a workflow on the Opportunity entity:
Figure 3-16 - Even More Dynamic Values

In the Look for drop-down, you can see that in addition to being able to select the Primary Entity (Opportunity, in this case), you can select from the Related Entities. These are all of the entities with which the workflow entity has an N:1 relationship, as discussed above. The syntax within this list is in the form of Field Name (Entity). So in this case, since the Opportunity entity has an N:1 relationship with the so-called Composite Customer entity (which can be either an Account or a Contact), you see Potential Customer (Account) as well as Potential Customer (Contact). If you select any of these Related Entities in the first of the two look for lists, the second list will update and expose all of the fields of the related entity. In the figure above, you can see weve selected both of the following fields and placed them on the same line:

73 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Account(Potential Customer (Account())) Contact(Potential Customer(Contact())) This syntax might look odd the first time you see it; its structure is: Field name from related entity([display name of link field](entity name))) Lets take a closer look at this by focusing in on the first of the two Look for lists, the one in which you identify the entity you want to pull a field from:
Remember: these related entities must have a 1:N relationship to the workflow entity. Its confusing because the entity the workflow is written for (in this case, Opportunity) is referred to here as the Primary Entity for the workflow. But from the standpoint of the database relationships within Dynamics CRM, each of these related entities is really the primary entity

To include fields from the primary entity for the workflow, you can select it (or just tab through it since its the default), and then the second list will display all of the fields for it. To select fields from entities with a 1:N relationship to the workflow entity, you select the entity you want from the Related Entities section So in the first of these two lines, Account is the field name we selected from the second list (the name from the Account entity), Potential Customer is the display name of the linking field from the workflow entity (Opportunity), and Account is also the name of the related entity. Since in the case of the Opportunity entity, the Potential Customer attribute is the composite customer entity that gives you either a Contact or an Account record, weve placed them consecutively, with no spaces between them, on the same line. So when the workflow runs and generates the task related to the Opportunity record, it will look like the following figure:

74 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 3-17 - Dynamic Values Inserted into Task

Dynamic Values: Local Values


In Figure 3-19 you can see that the Dynamic Values Look for drop-down menu has a Local Values section. Local Values will always include a selection for Workflow.
Figure 3-18 - Local Values

If you select the Workflow option you will see one or more of three options to select, depending on the field youve selected for updating: Activity Count Activity Count Including Workflow Execution Time

I will discuss the Workflow options in Chapter 4. Here I want to focus on the other option, which in Error! Reference source not found. is Lead record created from . In addition to the Workflow options, the Local Values section gives you access to any records that have been created within the
75 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

running workflow. This is important because it allows your workflows to respond to and interact with records created within the workflow, even if they dont have a relationship to the workflows primary entity! We will see many examples of this throughout the rest of the book; for now I want to make two related points on this topic: You will only see Local Values (other than the Workflow options) if you are at or after the workflow Step in which they are created. For example, if you are working within a multiple stage workflow and have Task records created in each stage, you will only be able to select tasks that were created in previous stages. The name of the Local Values you select from is the descriptive text for the task (or any other record you create). So even though this descriptive text is optional, you should always use a good, systematic naming convention. Its especially important in a scenario like this one where you might need to select from multiple Local Values in different contexts. In the worst case, if you left them all blank as you can do since they are optional youll find yourself selecting from a list like this one:
Figure 3-19 - Local Values and Naming Practices

Flow of Control Check Conditions


If Actions are the work in workflow, the Conditional statements we discuss here (along with the Wait Conditions in the next section) are the flow. These provide the logical structure for your workflows, and control what actions get executed under what conditions. There are three: Check Condition Conditional Branch Default Action

76 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

In the Step Editor, these are accessible from the Add Step menu. In the second section of that menu youll see commands for Check Condition, Conditional Branch, and Default Action. Notice that unless you already have a Condition line selected in the editor, Conditional Branch and Default Action will be unavailable. Also, if you havent selected a step at which its possible to insert a conditional, even the Check Condition command will be unavailable. This is a good illustration of how contextual the Step Editor is.

Check Condition: Building out your Workflow Logic


A good way to understand how to work with conditionals in Dynamics CRM 4.0 workflows is to start with the mechanics of the Step Editor, building out workflow logic without putting in any Actions at first. Heres a step by step example: 1. Create a new workflow on the Case entity. For workflow Properties, set Scope to Organization, and make sure that Record is created is checked for the Start when trigger. 2. Pull down the Add Step menu, and select Check Condition. 3. Then select the Ifthen line (be careful to select the line itself, by clicking on If, or then. If you click the <condition> (click to configure) link youll go to another window.) 4. Pull down the Add Step menu again, and this time select Conditional Branch. 5. Repeat step 4. Notice how each conditional branch is simply added to the current If condition, as an Otherwise clause. 6. After doing that a couple of times, pull down the Add Step menu and click Default Action. Since the first Check Condition and each subsequent Conditional Branch checks for specific conditions, this last Otherwise clause is a catch-all that will get everything else, essentially. When youre done with those steps, the Step Editor will look like this:
Figure 3-20 - Building out If Conditions

All weve done so far is to familiarize ourselves with the mechanics of adding conditions and branches. Notice that this entire If/Otherwise structure is considered one step in the workflow. We could supply a step description, and collapse or expand the entire step by clicking the down-arrow on the step
77 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

description line. This workflow wont do anything yet, since none of the conditions have been configured and there are no actions in the workflow. But it can be saved. A workflow like this cannot be published, however only saved in Draft status.

Working with Conditions: Building out your Workflow


Suppose the business scenario we want to support is the assignment of a new Case to the appropriate CSR, based on certain criteria expressed in Dynamics CRM terms as specific values of Case record attributes. Specifically, suppose that any Case flagged as high priority gets assigned to an appropriate queue for immediate attention. Other cases will be assigned to a specific CSR based on product knowledge requirements. Finally, all other cases will be assigned to a general purpose queue for case follow-up. For this example, youll need to queues, one called High Priority Service, and one called Standard Service. If necessary, go to Settings/Business Management, and click Queues, then create the two queues before proceeding. And remember that along with Activity records (email, letter, fax, etc.), Cases are the only entity that can be assigned to a queue rather than directly to a User. Then, follow these steps: 1. Enter an appropriate step description. 2. Click the <condition> (click to configure) link on the first ifthen line. 3. Click Select, and then select Case. 4. Tab to the next column and select Priority from the list (or just type P as a shortcut) 5. Tab to the next column and select Equals (or just type E as a shortcut) 6. Tab to the next field and click the ellipsis. Then select High as the selected value in the dialog, and click OK. Click Save and Close to lock in that condition. 7. Now you have to specify what Action will be taken for Case records meeting that criterion. Carefully click on the Select this row and click Add Step line immediately underneath the condition you just configured, click Add Step, and click Assign Record. 8. Optionally (remember, this is a best practice!) enter appropriate descriptive text, then note that the Case entity is suggested as the default record to assign, which is what we want to do here. Click in the lookup box immediately to the right of to on that line, and type in the name of the queue to which these Case records will be assigned. If you enter the name of an existing queue, this text will resolve, as you see in the following figure:

78 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 3-21 - Assigning a Case Record to a Queue

Now, suppose we want to assign other Case records based on more specific criteria, such as product knowledge. There are lots of ways to accomplish this, but one that works well in Dynamics CRM is to take advantage of the so-called Subject Tree. (You can configure this in Settings/Business Management.) 1. Click the <condition> (click to configure) link on the first Otherwise line in the above figure. 2. Click Select, and then select the Case entity as before. 3. Tab to the next column, and select the Subject field. 4. Tab to the next column and select Equals. 5. Tab to the next column and either type bikes, or click the lookup button and select it from the list. Then click Save and Close. 6. Now click the immediately following line (Select this row and click Add Step), and use the Add Step menu to add an Assign Record Action. 7. We could assign these Bike cases to a different queue, but for now lets assume a specific user say, Alan Jackson is our bike expert. In the Adventure Works data set you can simply enter Alan in the to box. After doing this, and entering some descriptive text, the Step Editor will look like this:
Figure 3-22 - Assigning in an "Otherwise" Condition

79 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

We can finish this workflow off by doing two more things: 1. Select the second (currently not configured) Otherwise step and delete it. 2. Click on the Select this row and click Add Step in the last one (the Default Action), and configure it to assign all other Case records to the Standard Service Queue. Heres the finished workflow in the Step Editor:
Figure 3-23 - Assigning Cases with Conditional Checking

Nesting Conditional Branches


You can nest conditional branches within a Dynamics CRM 4.0 workflow. Nesting is useful when you need to check for conditions of different levels. For example, in the previous Case assignment workflow, suppose as an alternative you wanted to first check the priority level, and assign the high priority bike cases to a new queue called High Priority Bike Service, and all other high priority cases to the High Priority Service queue. Next, for all non-high priority cases, you will assign those to either the Standard Service queue or to a queue called Standard Bike Service. To create a nested conditional statement, you need to remember how contextual the Step Editor is. Suppose youve created a new workflow on the Case entity and configured it with a scope of Organization and an automatic Start when trigger of Record is created. Next youve added the first Check Condition for priority level. The Step Editor will look like this:

80 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 3-24 - Depending on which Step you have Selected...

Notice that the highlighted line in the editor is Select this row and click Add Step. If you have this line selected and pull down the Add Step menu, youll notice that the Conditional Branch and Default Action commands are grayed out, but that you can add a new Check Condition. You can see that here:
Figure 3-25 - Different Options will be Available from Add Step Menu

On the other hand, if the If Case:Priority equals [High}, then: line had been selected, the Conditional Branch and Default Action commands will be available and Check Condition will be grayed out. Remembering these two rules, well now configure the first nested conditional check, which will assign all of the high priority cases to the appropriate queue. Heres what the Step Editor will look like at this point. Notice that the selected line is now the first If line.

81 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 3-26 - Building a Nested Conditional Clause

Now all we need to do is add the second branch for the first-level check on Priority. Well just use the Default Action, although if we had more priority levels we needed to check and take different nested actions for we could use the Conditional Branch action for that. After pulling down the Add Step menu and selecting Default Action, the Step Editor will look like this:
Figure 3-27 - "If" and "Otherwise" Lines Line Up within a Clause

Notice that within both conditional branches, the If and Otherwise" lines are at the same level. Now we add the second of the nested conditional branches, this one to handle all of the non-high priority requests:

82 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 3-28 - Continuing to Build Out Nested Case Assignment

Notice that you can collapse any of these conditional branches to give you more room within the Step Editor. For example, clicking on the down-pointing arrow on the first branch of the Priority check will give you the following view. This is a toggle switch you can use at any time.
Figure 3-29 - Collapse and Expand Conditional Branches

These nested conditionals can get confusing, so its a good idea to map out your logic beforehand. One thing weve found helpful is to use the Step Editor as a prototyping tool. You can build out a purely logical structure with as much nested conditional branching as you think youll need in your workflow before figuring out the details of the workflow actions themselves. Heres a simple example that really just illustrates the mechanics of setting this up:

83 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 3-30 - Building Structure with no Workflow Actions

The red x icons indicate that those actions still need to be configured, and if you try to publish a workflow like this youll get an error message. But you can save it, refer back to it, and get input from colleagues and so forth.

Flow of Control - Wait Conditions


In Dynamics CRM 3.0, there was a Wait for Timer condition that allowed you to wait for a period of time before executing more actions in a workflow. In the 4.0 release, this has been replaced by a much more flexible Wait Condition. When you configure a Wait condition in Dynamics CRM 4.0, there are a number of different conditions you can instruct the workflow to wait for: You can have the workflow wait until one or more fields on the primary entity have specified values. You can have the workflow wait until a Task or some other Activity record has an Activity Status value of Completed. You can have the workflow wait until field values in related entities meet certain conditions. You can have the workflow wait for a specified period of time. You can have the workflow time out until a specified period of time before or after the value of a date field on the primary entity or a related entity.

Adding Wait Conditions


Within the Workflow design environment, you add a Wait condition by placing the cursor immediately above where you want the Wait condition placed (assuming the default Insert After Step is currently selected!), and then selecting Wait Condition from the Add Step menu.
84 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

For example, Figure 3-31 shows the design environment with a Create Record action selected.
Figure 3-31: Make Sure "Insert" is set to "After Step", then Position Cursor

To add a Wait Condition immediately after that action, pull down the Add Step menu, and select Wait Condition, as we illustrate in Figure 3-32.
Figure 3-32: Adding a Wait Condition

After you select Wait Condition from the Add Step menu, you will see the yet-to-be specified condition added to your design environment:
Figure 3-33: A Not-yet-specified Wait Condition

85 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Configuring Wait Conditions


Adding a Wait Condition is the easy part configuring them takes a little more work! When you click the link <condition> (click to configure) from within the design environment, you will open up the Specify Workflow Condition dialog. You see an example of this in Figure 3-34. In the demonstrations at the end of the chapter we will work these in to real-world examples, but for now, lets focus in specifically on how to configure some common Wait conditions. Example 1: Wait until a value on the primary entity changes Suppose you have a sales process workflow that uses a drop-down list on the Opportunity entity to advance the record through stages according to the value the user selects. This is often referred to as a manual sales process, and the Opportunity entity has a built-in attribute called Process Code (entity name salesstagecode) that can be used for this. In Figure 3-34, you can see that the first column in the Specify Workflow Condition dialog gives you a drop-down list, from which you can select the entity you want to base your condition on. You can select the primary entity for the workflow, any entity that has a 1:N relationship to the workflows entity (in the Related Entities section), or you can select something from the Local Values section. If you select either the primary or related entities in the first column, the second column will allow you to select from a list of the selected entitys attributes. The third column will let you select from a list of operators, and again, these will depend on the data type of the selected attribute. The fourth column will allow you to enter a comparison value, or select a value from a list. In the example shown here, the Process Code attribute is a picklist, weve selected Does Not Equal as the operator, and thus can select the comparison value (column four) from the available picklist values.
Figure 3-34: Wait until a Field Value Changes

This example is for a sales process workflow, and if you refer back to Figure 3-31 you can see for that the stage the workflow is in here, the value of the Process Code attribute will always start as 1. Gather
86 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Requirements, because the preceding If condition specifically checks for that. So this Wait condition will force the workflow to wait here until that condition is no longer met that is, until somebody selects a different value from the Opportunity forms Process Code picklist. Example 2: Wait for a specified period of time A good example of when you want a workflow to wait for a specified period of time is for a servicelevel agreement, when you need to resolve a case within twenty-four hours or else. Of course, the or else depends on the service level agreement; in the demonstrations for this chapter we will present a Case workflow that implements a progressive escalation process depending on the amount of time a Case has been open and unresolved. Here, lets focus in on how to configure the Wait condition. Figure 3-35 shows what the Step Editor looks like with a Wait condition configured to wait for one day after the date (and time) the Case record was created.
Figure 3-35: Wait for a Specified Period

To configure this, you can follow these steps once youve opened the Specify Workflow Condition dialog, as you can see in Figure 3-36: 1. Instead of selecting the primary entity in the first column, select Workflow. 2. Then in the second column, select Timeout. 3. The operator column only has one option in this case, so accept Equals. The comparison value will be a date field, and the only thing available in the Look for section will be date attributes. 4. Make sure your cursor is in the date field in the fourth column, and perform the following steps in this exact order: a. Click the combination of Months, Days, Hours and Minutes that adds up to how long you want it to wait. b. Select Before or After. c. Then in the Look for section, select the date attribute you want your Wait condition to key off of. As soon as you single click it, notice that the comparison value updates automatically. This takes a little getting used to, but you get used to it after a few times through.
87 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 3-36: Configuring a Twenty-Four Hour Case Escalation

In Figure 3-37, you can see a slightly different version of this, one thats probably just as common. In this example the important thing for the business process isnt when the Opportunity record is created; rather, its when the salesperson says its due to close!
Figure 3-37: Timeout until One Day before Opportunity Est. Close Date

Example 3: Wait Until a Task is Completed Another very common situation is to have a workflow wait for a Task record to be completed. Remember the discussion above in the Dynamic Values section, where I mentioned that Local Values will allow you to select records that have been created previously within the workflow. Figure 3-38 shows an example, using just the first stage of what might be a Sales Process workflow.

88 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 3-38 - Wait Condition in a Sales Process Workflow

To configure this Wait condition, you can click the link right after the Wait until text, and use the Specify Workflow Condition dialog as you see in Figure 3-39. As I mentioned above, you will only be able to select records created previously in the workflow.
Figure 3-39 - A Previously Created Task is a Local Value

Parallel Wait Branch


A Parallel Wait Branch for a Wait Condition is analogous to a Conditional Branch for a Check Condition. For example, suppose that in addition to checking to see if the Est. Close Date is approaching, you also wanted to make sure Opportunities arent simply ignored after theyre opened. You could insert a Parallel Wait Branch to Timeout until a specific amount of time after the Opportunity record is created, and take some action at that time. To do this, follow these steps, picking up where we left off in the last example: 1. Select the Timeout until line in the Step Editor.

89 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

2. Pull down the Add Step menu and select Parallel Wait Branch. Youll see that the Step Editor places a Wait until condition on the step immediately preceding the Timeout until. (It goes here regardless of whether Before Step or After Step is selected on the Insert menu.) 3. Select the Wait until line, or simply click the <condition> (click to configure) link. 4. Click Select, and then select Workflow from the Local Values section. 5. Tab to the next column and select Timeout. 6. Tab to the next column and select Equals. 7. Now use Dynamic Values to make the timeout equal to 7 days after the record was created. (There are a number of ways to do this. Try this: enter 7 in the Days field, then tab to get to the comparison field and type A for After then click Record Created On, and you should see the condition filled in.) 8. Click Save and Close, and youll see the Step Editor filled in with the original timeout condition and the new parallel wait condition:
Figure 3-40 - Parallel Wait Branch

Here are a few important points that this example surfaces: Notice that were building the logic of our workflow the conditions that will govern its behavior before adding the workflow Actions. If youre creating complex workflows consider this approach. Its often easier to plan and prototype your workflow logic before getting bogged down in details of your workflow Actions. Notice that these are Or conditions. The way this workflow is constructed, only one of these conditions will ever happen; whichever one happens first, the workflow will execute the Actions under that branch, and then proceed along. If you wanted both Actions to happen, there are a number of approaches you could take; well examine some of those alternatives later. Theres no rule that only Timeout conditions can be the logical alternatives in a Wait. For example, suppose instead of the condition we just configured, we wanted the workflow to wait until one day before the Est. Close date, OR the workflow Status was changed. We could delete the first Timeout line in the above figure, and add a new one to make it look like this:

90 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 3-41 - Mixing Wait and Timeout

Stages and Wait Conditions


Weve mentioned previously that all entities in Dynamics CRM 4.0 can have staged workflows, and that at one level, workflow stages are primarily for organizing your workflows into logical sections or stages. We also mentioned that theres nothing about a workflow stage that will cause a workflow to stay within that stage. You can see this by creating a simple workflow for any entity with multiple stages, each of which contains a single step, say, to assign a task for the stage. Suppose you have a sales process that should be applied to the Opportunity entity, with these stages: Identify, Qualify, Propose, and Close. You can prototype this sales process by creating an organization scoped automatic workflow triggered by the Record is created event, and make it something like this:
Figure 3-42 - Creating Workflow Stages

Provided that the required fields for each Task record have been filled in (Subject is the only required field that you need to go in to the task form and enter a value for), you can save and publish this workflow. If you do, and then create a new opportunity, it will work, but not very well! The problem is that since nothing makes this workflow wait within a stage, every task is simply assigned all at the same time, and the workflow is done. Heres what it might look like, after the opportunity record has been created:

91 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 3-43 - By Default, Workflows do not Wait in Stages

What we need is a way to make the workflow wait in each stage, and not proceed to the next stage of the sales process until the tasks for each stage are completed. To accomplish this, we can use a Wait Condition, and use Local Values as we discussed previously to instruct the workflow to wait until a Task created by the workflow has been completed. We will present a detailed demonstration of this at the end of the chapter; for now examine Figure 3-44 to see how one of these task-based workflows looks in the Step Editor.
Figure 3-44 - Workflow Creating Task and Waiting until Completed

One of the important reasons for implementing a sales process workflow in this way can be seen if you run the built-in Dynamics CRM 4.0 Sales Pipeline report. (Workplace, Reports, Sales Pipeline). If you run this report after publishing a sales process workflow like this one, youll notice that you can select the workflow from the Group by Sales Process pull-down list that comes preconfigured for that report! This is quite specific: its having a staged workflow published on the Opportunity entity that makes this possible, and until you have a workflow like that published you wont see anything in that pull-down list. In our experience, many organizations dont realize how
92 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

potentially valuable the Sales Pipeline report can be until they discover this connection; conversely many organizations find this reporting capability so potentially valuable that they implement a sales process (that can be expressed as a staged workflow) explicitly to take advantage of the reporting feature! Just remember: your staged workflow on the Opportunity entity doesnt have to be complicated even if you only have two stages in your workflow it might be a good starting point.

93 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Demonstrations for Chapter 3


Demonstration 3.1: Escalation Workflow for Past-Due Opportunities
In this demonstration we will create a workflow on the Opportunity entity that will perform two main functions: 1. When an Opportunity record is within a day of its Est. Close Date, a reminder email will be sent out. 2. If it becomes past due, in the sense that its Est. Close Date is more than a week in the past, the Opportunity record will be closed out. The business process implicit in a workflow like this is potentially contentious: how many sales reps like it when their opportunities get closed out by some automated process? But even if this is a little too harsh for your sales team, its still a good illustration of the potential for workflows to enforce certain practices. And in any case, you can always re-open a closed Opportunity! 1. Create a new workflow on the Opportunity entity. Set its properties as Automatic with a Record is created trigger. Set the Scope to Organization. The Workflow Properties section should look like this:
Figure 3-45- Workflow Properties

2. In the Step Editor, pull down Add Step and select Wait Condition. The Step Editor will look like this:

94 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 3-46 - Configuring Wait Condition

3. Click <condition> (click to configure) to open the Specify Workflow Condition dialog. 4. Click Select, and then select Workflow from the Local Values section:
Figure 3-47 - Condition using Workflow Values

5. Tab to the next column and select Timeout. 6. Tab to the next column and select Equals. It should look like this:
Figure 3-48 - Specifying a Timeout Condition

7. Tab to the next column and notice that the field dynamically changes to a date picker control. Use the Dynamic Values area to select 1 in the Days field, Before in the drop-down immediately beneath, Opportunity in the Look for, and Est. Close Date as the field. As soon as you do that, it should look like this:

95 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 3-49 - Timeout Until Specified Time Period Before "Est. Close Date"

8. Click Save and Close to lock in this Wait condition. Youll then see Step Editor again, looking something like this:
Figure 3-50 - How it Looks in Step Editor

At this point weve configured the Wait condition to wait until one day before the estimated close date. Now what? Even though you might think were almost done at this point, we need to do a little more work! Before sending out the email reminder, we need to check to see if the Opportunity record is still open, and only send the reminder if it is. Picking up where we left off, heres a somewhat condensed step-by-step procedure to set this up: 9. Click Add Step, and then select Check Condition. 10. In the Specify Workflow Condition dialog, do the following: a. In the first column, select Opportunity. b. In the second column, locate Status and select it. c. In the third column, select Equals. d. In the fourth column, select Open from the available Status values. e. Then click Save and Close. The Step Editor should look like this:

96 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 3-51 - Check if Opportunity Record Still Open

11. If its still open at this point, a reminder email to the opportunity owner is in order. Click Add Step, then Set Properties to configure the email. 12. In the next part of the workflow, Ill add another Wait condition. This one will be a little different, and will wait until a specified period after the estimated close date of the opportunity. In the example I show here, Im going to have the workflow actually close the opportunity out by changing its Activity Status to Canceled. Some sales organizations might consider this a little draconian. Some might not, however it all depends on your sales organization. The next figure shows the entire Step Editor with the rest of the logic of the workflow built out.
Figure 3-52 - Two Wait Conditions: One to remind, One to close Opportunity

97 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Demonstration 3.2 Task-Based Staged Sales Process Workflow


In this demonstration we will create what I refer to as a task-based workflow. Basically, the workflow will create tasks, assign them to users, and wait for the tasks to be completed before proceeding. We will implement a common scenario of this kind of workflow, on the Opportunity entity, in which case its often referred to as a sales process workflow. We will use stages, although this isnt required In the next chapter, we will demonstrate what I refer to as a manual sales process, where rather than waiting for tasks to be completed, the workflow advances based on the value of a picklist on the Opportunity form, manually selected by users. The current demonstration and the one you will see in Chapter 4 are at two different ends of the spectrum and its a useful learning exercise to compare them, but its worth noting that in the real world work processes are generally not as cleanly categorized as these two examples are! In this demonstration I will use a simple three-stage sales process, with stages for qualifying the opportunity, preparing the potential solution, and negotiating and closing the sale. We will assume that certain tasks need to be performed in each stage of the process, and that the workflow should not proceed until those tasks are completed. 1. Create a new workflow, based on the Opportunity entity, and give it an appropriate name. 2. In the workflow properties section, specify its Scope as Organization, and have it start automatically, on the Record is created trigger. 3. Add the stages of the sales process, by clicking Add Step and selecting Stage from the menu. For the present example, you should shoot for something like

98 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 3-53 - Task-Based Sales Process Workflow Properties and Stages

4. Minimize the Properties section and the Prepare and Negotiate stages in the step editor by clicking the expand/collapse buttons, so you have more screen real estate to work on the Qualify stage:
Figure 3-54 - Maximizing Room in Step Editor

5. Within the Qualify stage, click Add Step and select Create Record. Enter an appropriate description and select Task from the Create menu. 6. Click Set Properties to configure the workflow task for the current stage. Figure 3-55 illustrates some characteristic options, including:

99 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

a. The Subject. Try to come up with some naming conventions for Subject lines, such as including a combination of boilerplate text and the Opportunity Topic attribute as I show here. b. To some extent you can make a business process self-documenting if you use fields such as Description to include instructions regarding what should be done to complete the task. c. I usually make the owner of the Task record the same as the owner of the Opportunity record, as you see here, although this certainly isnt a requirement. d. Notice that in this example I used Dynamic Values to set the due date of the task to be seven days after the opportunity was created.
Figure 3-55 - Configuring a Sales Process Task

7. Click Save and Close to return to the Step Editor. 8. Click Add Step and select Wait Condition. 9. Provide appropriate descriptive text, then click <condition> (click to configure). 10. In the Specify Workflow Condition dialog, select the name of the task (the descriptive text you entered in step 5) from the Local Values section in the pull-down menu in the first column, and then select Status Reason in the second column. Select Equals in the next column, and finally select Completed from the available status reason values.

100 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 3-56 - Specify Condition: Wait until Task Completed

11. Click Save and Close to return to the Step Editor, which should now look like Figure 3-57.
Figure 3-57 - Stage 1 Task Created and Wait Condition Specified

Thats how you can make a workflow stay in a stage. I made the point earlier, but its worth repeating: if you dont put the Wait in there, nothing makes the workflow stop. In the version of the workflow you can download, I include the rest of the stages, but I want to point out one more important point before going on. The way I configured the Wait condition in the Qualify stage will work as long as somebody completes the task. But what if they dont? Or what if they cancel it instead of completing it? I wrote it like that to make this point, which you can see if you compare it to how I configured the Wait condition for the Prepare stage:

101 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 3-58 - A Better Way to Configure Wait Condition

Rather than waiting until the task is completed, the first Wait condition waits until its no longer open. Then it checks to see if it was canceled, in which case the workflow stops with a status of Canceled. Otherwise, it proceeds to the next stage, and so on.

Demonstration 3.3 New Lead Auto-Responder Workflow


As I mentioned in Chapter 2, the Lead entity is one you can use the Send Email action on directly. A good example of when you need to do this is with a so-called auto-responder email. You might have a business process that sends an acknowledgement email to a new Lead; one particularly useful situation is for a Lead record created after a visitor fills in a form on your web site. I will present an example workflow here that illustrates two main points: 1. How (and why!) to create a Lead record based on the information entered into a custom entity. 2. How to send an email with a file attachment to a new Lead record. The scenario presented here starts with what many refer to as a web to lead function: a visitor to a web site fills out a form and the information they enter is used to add a new record to Dynamics CRM. At the time I wrote this (May 2009), this general functionality was not available in Dynamics CRM. A limited web to lead function has been included in the Dynamics CRM Online version (the one hosted by Microsoft), but if youre working with the on-premise edition of Dynamics CRM, you really have two options for this functionality: you can write a custom ASP.NET application, or you can use a thirdparty tool. I use and recommend a tool called Web2CRM, from a company called CRM Innovation. You can find out more at www.CRMInnovation.com The example I demonstrate here is one I use for my business. For example, in an article on my blog about a workflow, I might include a link at the end of the article that says click here to get this workflow emailed to you Figure 3-59 shows what one of these web forms might look like. Notice the 3+2 = text box at the bottom of the form. Thats a so-called captcha function, to make it difficult for automated programs
102 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

(so-called bots) to clutter your CRM with spam. Its not a bad idea to include something like that on your forms, but you might want to point out to your visitors what it is Ive had people email me there were errors on my forms, when in fact they simply hadnt done the little math problem this captcha implementation requires!
Figure 3-59 - Web Form Created with Web2CRM

The way Ive configured this Request Information function is to have the information in this form get written to a custom entity Ive created in my CRM called Information Requester. So as far as my CRM workflow is concerned, the process starts when a new Information Requester record is created, and you can follow this step-by-step process to create a workflow like this one: 1. Click Settings on the site map, then click Workflows, then click the New button. 2. Give it an appropriate name (I used Request Information for this example), select the entity (Information Requester in this example), make sure New blank workflow is selected as the Type, then click OK. 3. In the Workflow Properties section, select Organization for the Scope, select the Record is created checkbox to make it run on the Create trigger, as you see in Figure 3-60.

103 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 3-60 - Auto-Responder Workflow Properties

4. To create the Lead record from the Information Requester record, click Add Step and select Create Record. Select Lead as the record type, and then click Set Properties. 5. Figure 3-61 shows how you can use Dynamic Values to populate fields on the Lead record being created with information from the workflows primary entity, the custom Information Requester. (I will explain Dynamic Values in detail in the next chapter). Click Save and Close to continue.
Figure 3-61 - Creating the Lead Record from the Custom Entity

6. Once the Lead record is created the workflow can send an email, so for the next step, click Add Step and select Send Email. Select the Create New Message option, and then click Set Properties.

104 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

7. Figure 3-62 illustrates how you can configure a Send Email workflow action. Notice first that the To line is to the Lead record that was created within the workflow. Again, I will explain this in more detail in the next chapter. The text of the email starts with a salutation that will include the value of the First Name field (populated to Lead from the custom entity as you can see in Figure 3-61). But notice the text that says colleague at the end of the salutation. Thats the default value, in case the First Name field is empty. In practice, you should consider requiring fields like that on your web forms (refer back to Figure 3-59 to see the fields I required there), in which case they will always contain data, but I usually like to include the default colleague salutation, just in case.
Figure 3-62 - Configure the Auto-Responder Email

8. If you want to have one or more attachments on your email, click the Attachments tab. Figure 3-63 shows what this looks like. You can simply click New Email Attachment, browse out to wherever the file is located and select it. Dynamics CRM customizations (including workflows) can be exported as zipped XML files, which are reasonably small and generally acceptable by your recipients email servers. After you attach the files you want, click Save and Close, then Publish to make your workflow active.

105 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 3-63 - Add an Attachment to a Workflow-generated Email

With the workflow published, any time a visitor fills out the form, the end result will be a brand-new Lead record created and an email sent. I usually verify that it works by entering some (a lot!) of test data. Make sure you test it for different email account types, since email that looks great in Exchange, for example, doesnt always look the same in Gmail or Yahoo. Figure 3-64 shows an example Lead record, Figure 3-65 shows the Email history item attached to the Lead record, and Figure 3-66 shows what the email looks like in the recipients email environment.
Figure 3-64 - Workflow-Created Lead Record

106 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 3-65 - Sent Email Attached to Lead Record

Figure 3-66 - Email with Attachment as Recipient Sees it

Demonstration 3.4 Marketing Campaign Audit Trail for Campaign Activities


In Figure 3-15, I showed an illustration of using the Append to operator to create an informal audit capability. In this demonstration Ill present in more detail how to build a workflow that can help make marketing campaigns somewhat self-documenting. Even if you dont use the Marketing Campaign entity, there are lots of other uses for this technique. The workflow will actually be written for the Campaign Activity entity. If you havent worked with Dynamics CRM marketing, you might not even know this entity exists, since its not one of the basic eight Activity records you can create by selecting New Activity anywhere in CRM! Thats because a Campaign Activity record can only be created in the context of a Campaign record theres a 1:N
107 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

relationship between Campaign and Campaign Activity, and in this context the Campaign is referred to as the Parent Campaign of the Campaign Activity record. Follow these steps to create the workflow: 1. Create a new workflow on the Campaign Activity entity, giving it an appropriate name. Click OK in the Create Workflow dialog. 2. Give it a scope of Organization, and select Record is created and Record status changes in the Start When section:
Figure 3-67 - Campaign Activity Workflow Properties

3. Click Add Step, and select Update Record. 4. Click the drop-down menu to the right of Update, and notice that Parent Campaign is exposed as one of only two related entities. Remember: these are the entities that have a 1:N relationship to the workflow entity (Campaign Activity, in this example). Select Parent Campaign:
Figure 3-68 - Select Parent Campaign to Update

5. Click Set Properties. Your goal is to make the Update Campaign dialog look like Figure 3-69. Since the values we want to display in the Description field are all from the Campaign Activity record, you can simply keep Campaign Activity selected in the Look for pull-down menu, and then select the fields you want, one after the other, in the field drop-down immediately underneath it. You can intersperse text with these dynamic values as weve seen a few times,
108 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

but you might need to experiment a little to get successive records to appear neatly and consistently, as you saw in Figure 3-15.
Figure 3-69 - Using Increment By to Add Informal "Audit Trail"

6. After you select the values, enter fixed text and make your best guess about how it will be formatted, make sure to select Increment by from the Operator pull-down. Its easy to forget this, since Set to is the default, and if you have it selected, it does not display above the field! Only if you select Increment by will that display as you see in Figure 3-69. Also remember that you cant mix and match Increment by and Set to within a single text field one operator will apply to the entire field no matter how many dynamic values you substitute into it.

Ill conclude this demonstration with a couple of comments, and an interesting permutation of this technique you might encounter a need for. One potential limitation of using a Description field in this way is that you may run out of room in the field! Many text fields have a maximum amount of data they can hold, and while there are workarounds, they might be tricky to implement. If you run into this problem, consider adding a Note record rather than incrementing a text field the way I showed here. In some ways, the example I showed for Campaign Activity was easy, since the only record a Campaign Activity record can be created for is a Campaign. But consider the case of a more general Activity-type record, such as a Phone Call. Suppose you wanted to create an audit trail for Phone Call activities, but you only wanted to write out audit records for certain phone calls, say, those made regarding an Account or a Contact. In Figure 3-70 you can see an example of how you might do that. Test first for the condition you need to write out a record for, and make

109 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

sure you check for a required field! The example I show here will always work, since Account Name is required. This last point is important because your workflow will break if it attempts to update a record that doesnt exist. Youll see what I mean if you write a test workflow on the Phone Call entity and use the Update Record action to update the Regarding(Account) record as Ive done hereand then create a Phone Call activity that does NOT have an Account in the Regarding field. Try it, and let me know if you have questions!
Figure 3-70 - Test Condition for a more Selective Audit Trail

110 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Chapter 4 - Advanced Topics


Now that youve got your basic workflow skills in place, lets put them to work! In this chapter we will review a number of different workflows, most of which are more advanced than what weve done so far, and all of which include real-world examples of things weve covered previously. The goal of this chapter, while short of a General Theory of Workflows, is to put some business strategy behind the mainly technical concepts weve discussed so far.

Recursive Workflows
I mentioned previously that by allowing a workflow to call itself as a child workflow, you can create a recursive, or looping process. Once you understand the techniques involved in creating recursive workflows, youll be surprised how many business processes can be implemented using them. Here are a couple of examples that we will develop throughout the rest of the book: Case escalation processes. Suppose you have a service level agreement that says service cases must be resolved within a specified period of time. What happens if they arent resolved? After spending two days in a first-level support queue, a yet-unresolved case might need to be escalated to a second-level queue. If yet another day goes by and still no resolution, maybe the customer service VP needs to take action. Whatever the specifics of your service level agreements, escalating processes like these can be handled nicely with recursive workflows in Dynamics CRM. Opportunity sales processes. Business processes around the Opportunity entity are a little different than ones for Cases. For example, most organizations dont have a service level agreement that guarantees opportunities will close after two business days! Many sales organizations are more concerned about the process itself than about an arbitrarily specified time period an opportunity should close by. For example, the Solution Selling Process is familiar to many sales teams, and in some incarnations has 8-10 stages, each of which might involve multiple actions. As you will see, to implement a flexible sales process will often require a recursive workflow.

Recursive Workflow Mechanics


Before we dive in to real business uses of recursive workflows, lets start with some exercises to illustrate the mechanics of working with them. I think the easiest way to start is by creating a simple
111 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

workflow that really only does one thing: calls itself as a child workflow. In fact, it doesnt even matter which entity you create the workflow for, but since we will be using the Case entity to illustrate many of these recursive workflows we will start with that one. Create a new workflow on the Case entity. Make sure that As a child workflow is checked in the Available to Run section. Since this example is definitely NOT something I want to have happen every time a new Case record is created, Ive scoped this to the User level, and only made it available as an On demand workflow. You can see this in Figure 4-1.
Figure 4-1- Mechanics of "Recursive" Workflow

Notice that the single action is Start child workflow. The current workflow is supplied as the one to be started thats the definition of a recursive workflow. (When you create this, notice that if As a child workflow is not selected, this workflow will not be selectable in the Start child workflow lookup.) Save and publish this workflow, and then navigate to a Case record to run it. In Figure 4-2, you can see the results of opening up a Case form, and running this workflow on demand, by clicking the Run Workflow toolbar button.

112 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 4-2 - "Infinite Loop" Detection at Work

You can see the workflow runs six times in succession, and then fails on the seventh run. This is built in loop detection at work, and illustrates the point that you need to be careful and test thoroughly before publishing recursive workflows into a production environment!

Counting Workflow Loops


Sometimes its important to know how many times a recursive workflow has been through the looping process. For example, we will shortly examine a real Case escalation workflow that will take different actions depending on how many times a case has been escalated (that is: how many times the workflow has looped). There are a few ways to do this, but the easiest way Ive found is to create a custom attribute on the workflow entity and have the workflow perform an Update action on it every time through so you can keep track. Heres a step-by-step example, building on the Case escalation scenario: 1. Customize the Case entity by adding a new Attribute. Give it a Type of int, and name it appropriately, as you can see in Figure 4-3. Optionally, you might supply minimum and maximum values for it, but thats not required.

113 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 4-3 - Custom Attribute to Count Loops

2. Unlike most custom attributes you create, a counter attribute like this one probably should NOT appear on the form when you go to production! However, when youre building and testing a workflow like this, its not a bad idea to place it in an innocuous location on the form so you can easily see what its value is. For now, I will add it to the Administration tab. 3. After creating the custom attribute and placing it on the form (Figure 4-4), save and publish the Case entity.
Figure 4-4 - Counter Attribute on the Form for Testing Purposes

4. Now we need to modify the workflow to update the counter attribute. I will add an Update Record action after the workflow calls itself, as you can see in Figure 4-5.

114 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 4-5 - Update the Escalation Counter Attribute

5. This is a good illustration of when you need to use the Increment by operator in Dynamic Values. Each time through we want the counter to increase by one, so after clicking Set Properties in the Step Editor you can increment the counter as illustrated in Figure 4-6.
Figure 4-6 - Using Increment by on Escalation Counter

6. After you do that, save, close and publish the workflow, and then run it again on a test record. You can see it in action if youre quick enough, by running it with the Case form open, and pressing F5 repeatedly to refresh the browser. You can watch it change every few seconds as the workflow runs. When you run this workflow again, the results will be the same and it will fail after loop detection kicks in. But now that were storing the loop count in an attribute, our workflows will be able to implement Check conditions and respond appropriately.
Figure 4-7 - Escalation Counter after Workflow Runs

115 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Automatic Workflows, Business Units and Security


We discussed this in the book, but its a complex enough topic to warrant going through a more complete example. Consider the following business requirements: Your organization will make extensive use of service cases, and will use the Case entity to track them. Most users throughout the organization will be able to create a Case record (in CRM security-speak, they will have Create privilege on the Case entity), but when a Customer Service Representative opens a Case for a customer, an automatic workflow implementing an official service level agreement will run. A user in another department can create Case records for their own purposes, but the automatic SLA workflow should not run when anybody other than a CSR opens a Case. Using the public VPC image for Dynamics CRM 4.0, we will create two child business units (Service and Sales) underneath the root business unit (MicrosoftCRM):
Figure 4-8 - Business Units

We will have some users assigned to each of these business units, as you can see here:
Figure 4-9 Users Are Always Associated with Business Units

We have a workflow that will implement our official SLA, which we can see in the All Workflows view here:
116 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 4-10 The Owner of a Workflow Determines the Owning Business Unit

Notice here that the Standard SLA workflow is owned by Paul West. Paul is playing the role of Customer Service Manager, but the important thing is that he is assigned to the Service business unit. Since hes in that business unit, that is also the Owning Business Unit of the workflow. Heres how the properties of the Standard SLA workflow are configured:
Figure 4-11 Automatic Workflow Scoped to Business Unit

This workflow is scoped at the Business Unit level, and it runs automatically, whenever a new Case record is created. So, whenever any user in the Service business unit creates a Case record, the Standard SLA workflow will fire. Whenever any user in any other business unit creates a Case record, nothing will happen. So this is all set up to solve the business problem outlined above, but heres the catch: only the Owner of a workflow can publish the workflow! So unless Paul West (in this example), is a very technical Customer Service Manager, somebody else is going to have to create the workflow for him. Suppose that the user creating the workflow is a System Administrator, associated with the root business unit. This is a very typical configuration in many CRM organizations. The System Administrator can create the workflow, but if he publishes it, it wont run for customer service reps, because the administrator is
117 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

in the root business unit! And if the administrator assigns it to Paul West, the administrator cant publish it because, like I said, you can only publish a workflow you own! There are a couple different approaches to this, but on the whole, I think the best one is to assign the workflow to the most senior manager (user) in the business unit you want the workflow to run automatically for, and instruct that person how to publish it. (An alternative would be to move the administrator to that business unit, but that would probably cause more problems than it would solve!) In any case, once Paul publishes the workflow, you get the results you want. Suppose Angela creates a new case. The workflow will run automatically, as she could see by clicking the Workflows link on the Case left-navigation as you see here:
Figure 4-12 This Workflow will be Triggered if Case is Created by User in the Owning Business Unit

But if anybody outside the Service business unit creates a Case record, nothing happens, just as it shouldnt. (in terms of the workflow, anyway). Again, this takes a little getting used to especially if youre in the habit of thinking that System Administrators can do anything. They cant publish somebody elses workflow, and they cant trigger automatic workflows owned by somebody in a different business unit, as is illustrated by the following screenshot of a Case record created by the administrator:
Figure 4-13 - But will not be Triggered if Case Created by User in a Different Business Unit!

118 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Using Workflows to Audit Records


One of the big gaps in Dynamics CRM is the lack of any kind of built-in auditing features. Every entity has the following four attributes: Created By Created On Modified By Modified On

But theres no history of anything other than the current state of the record. This can be a problem in many different situations, especially in todays audit-conscious business environment.

Creating Audit Trails for Changes to Records


One important scenario in Dynamics CRM where this can arise is in working with the Opportunity entity. Many users are aware that Opportunity records can be closed and reopened. For example, an opportunity closed as Lost at one point can be reopened later and eventually closed with a Status of Won. But opportunities closed as Won can also be reopened; for example, the accounting staff may need to reopen opportunity records to clean up the data after the fact, and then of course theyll need to close out the opportunity when theyre done. In doing this, many people at first dont realize that the new Close Date will default to todays date. If you forget this and go ahead and close the opportunity record a second time with a new date, what youll do is effectively ruin the usefulness of the Sales History report, since that report uses the Actual Close Date to group opportunities by the months they closed in! This is a great example of why you might want an Opportunity Audit workflow (combined with some user education!). You can add some auditing capabilities to just about any workflow in a quick & dirty way by using the Note record. As long as you workflow entity can have Notes attached, you can always add a Note record and use Dynamic Values to populate it with just about anything you need from the present state of the record. Remember that since the Note record is time-stamped, this can get you some nice functionality. But if you want a more robust audit approach, with a specific set of attributes from the audited entity available for reporting and querying purposes, follow the steps we lay out here. Well use the Opportunity entity as an example. 1. Create a custom entity, Opportunity Audit. Add to it the fields from the Opportunity entity you want to audit, and make sure you give them the same names and the same field types.
119 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Keep this one simple for now and only add two fields to audit: Est. Value and Probability. Also: if youve customized the Status Reason values for Opportunity, give Opportunity Audit the same set of values. 2. Create a new workflow on the Opportunity entity, giving it a scope of organization. The changes you want to audit will determine which triggers should run it. For this example, make it triggered by Status change and Attributes change events, with the Attributes youre looking for as Est. Value and Probability. 3. Add a Create Record action to the workflow, with the created record being for the Opportunity Audit entity. Then use Dynamic Values to pull from Opportunity the values of the attributes you want to store in the audit record. Remember that since you only added a subset of the attributes from the Opportunity entity, you wont have much work to do in this step! Those are the basic steps, so you can now test it and verify that everything works as expected. There are a couple of nuances you could add on to this simple example: You can make an argument that the Opportunity Audit record should be created in an Inactive state, so it will be apparent that it shouldnt be saved. You can have the workflow do that by adding it as a step 4 above. If you do that, and try to see the audit records in the Associated View youll notice that that view only shows active records! Heres a case where a small unsupported customization might come in handy. For extra credit, export the Opportunity Audit entity as a customization (customizations.zip is the file youll export, by default), and edit the XML file. Find the savedquery node for the Associated View and remove the <filter></filter> node you will find there. Be careful to remove the correct one and then reimport and publish the custom Opportunity Audit entity. Again, this last little trick is unsupported, but it might be in the category of a forgivable transgression, plus its a handy trick to know about.

Creating Audit Trails for Deleted Records


One thing I get asked a lot is what good the Delete trigger is, if you cant use it to un-delete a record. Remember, since it runs on the Delete event, the record in question really will be deleted when the workflow runs. While that statement is true, it doesnt mean the Delete trigger isnt useful. In fact, even though the record is deleted, the workflow instance has all of the values of the fields of the deleted record. So what this means is that you could simply use a permutation of the techniques we discussed in the previous section to create an audit record for every deleted Opportunity. You could create an appropriate Status Reason value for the Opportunity Audit entity, such as Deleted, to flag audit records that were created when an Opportunity record was deleted.

120 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

We will present a detailed step-by-step example at the end of the chapter, but for now, let me make a few general points on this topic: Different Approaches for Creating Audit Trails There are a number of different ways you can create audit records, and which approach is right depends on various factors. For example, you might characterize three different approaches like this: 1. Whenever certain values of a record change, use Increment by to add appropriate text (using Dynamics Values) to either a Description field or as a Note record. This is the informal approach we discussed in Chapter 3. 2. For a more robust auditing capability, create a custom entity for the entity for which you want to create audit records (e.g. Opportunity Audit) and create a 1:N relationship from the primary entity to this custom entity. Build an automatic workflow triggered by Status changes and Record is deleted events, and write out values to the custom entity when those events occur. 3. A slightly easier version might be to only create audit records on the Record is deleted trigger. If you take this approach, you could create a custom entity specifically designed to store a snapshot of any record that gets deleted. Youd decide which attributes you wanted to store, and then create a standalone entity (e.g., Deleted Opportunities), adding those attributes to it. Then youd build an automatic workflow triggered by the Record is deleted event, and write out one record to it any time an Opportunity is deleted. In the demonstration I think youll see why the third approach is somewhat easier than the second, and given the potential harm accidental (or on purpose, for that matter!) deletes can cause, I recommend you consider implementing something like this sooner rather than later!

121 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Demonstrations for Chapter 4


In chapter 3 we demonstrated a Lead assignment workflow that assigned a new Lead record on the basis of attribute values. In what follows we will demonstrate two workflows that perform the same essential function assigning a new Lead record to a sales rep but do so in very different ways: The first one will use a Dynamics CRM Queue to assign Leads on a first-come first-served basis The second will use an interesting technique to assign Leads on a round-robin basis

Demonstration 4.1 - Assigning Leads on a First-Come First-Served Basis


As weve mentioned a few times, Dynamics CRM queues can be used to expose Activity and Case records to multiple users. When a user accepts a record from a queue, the record is assigned to that user. We can refer to this as assigning on a first-come first-served basis, since whoever accepts the record first gets it. We can use queues to assign Lead records in this wayeven though Lead records themselves cannot be assigned to a queue! We will use an automatic workflow that runs when a new Lead record is created. It will create a Task record and assign it to a queue. A user will be able to see the new Task record in the queue, and will be instructed to accept and complete the task in order to claim the new Lead. The workflow will wait until the task is completed, and then assign the Lead record to whichever user completed the task. This is actually a general technique and can be used to assign ANY record in Dynamics CRM, but we will use the Lead entity to illustrate. Heres how to do it: Start by creating a queue appropriate for this process. Navigate to the Business Management tab in Settings, click Queues, and click New from the Queues grid. We will call our new queue Open Leads, and assign it to the root business unit.

122 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 4-14 - Create a New Queue

Once the queue is created, follow these steps to create the workflow: 1. Create a new workflow on the Lead entity with an appropriate name, scope it at the Organization level, and have it run automatically on the Record is created trigger. You can see these in the Workflow Properties section in Figure 4-15.
Figure 4-15 - First-come First-served Assignment Workflow

2. The first action in the workflow will be Create Task. Click Set Properties on the Create: Task line to open the Create Task dialog, which you can see in Figure 4-16. The Regarding field will already be filled in with the Lead. We used Dynamic Values to pop the Lead Topic onto the end of the Subject line, but thats optional.

123 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Notice that this workflow makes Amy Alberts the Owner of the task. In the CRM organization this was created for, she is assigned to the Sales business unit, and has a security role of Sales Manager. We could leave the Owner field empty here, but that would cause other problems we will discuss below. The reason the Owner field is not required in automatic workflows like this one is that the workflow runs in the security context of the workflows owner. Since this workflow is owned by the system administrator, any record it creates that does not have a different user specified as the owner will be owned by the administrator.
Figure 4-16 - Create Task Record

3. After the Task record is created, the next action in the workflow is to assign that Task record to the Open Leads queue. Remember, assigning to a queue doesnt change the owner of the task. (I always put assign in quotation marks to remind myself so I dont forget!) On this step you dont need to use Dynamic Properties since you can simply enter the name of the queue onto the lookup field you see in Figure 4-15. 4. After putting the Task record into the queue, add a Wait condition. The workflow will wait until the Owner of the Task record changes which will happen when any user other than Amy the Sales Manager accepts the Task record from the queue. Figure 4-17 shows how you can specify that Wait Condition. Notice you need to identify the Task in the Local Values section of the drop-down menu. Any record that a workflow creates will be available in Local Values, and once you select it you can access its attributes in this example, to specify the condition the workflow will wait for.

124 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 4-17 - Wait Until Task Owner Changes

5. After specifying this condition, save, close and publish the workflow to see how it works. Note: this workflow raises some interesting issues regarding queues, record assignment, security roles, and how they interact with workflows. Basically, any user who will accept one of these tasks to get the lead assigned to them must have sufficient Assign privilege on the Activity entity. The standard Salesperson security role only has User-level Assign privilege on Activity (along with most of the other core records, including Lead). What this means is that by default, a user assigned to the Salesperson security role will not be able to accept activity records from a queue (such as the Task record we used in this example). Suppose that we had not specified the Sales Manager as the owner of the task record created in the workflow as we discussed above in reference to Figure 4-16. In that case the task would be owned by the system administrator, who is assigned to the root business unit. If a user assigned to the Sales business unit with a Salesperson security role attempts to accept the task from the queue, he or she would see this dramatic error message:

125 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

This is why we assigned the new Lead records to the Sales Manager, who is in the same business unit as the Salesperson(s). We then needed to make one change to the Salesperson security role: elevate the Assign privilege on Activity from User to Business Unit. We highlight this in Figure 4-18.
Figure 4-18 - Modifying the Salesperson Security Role

After making this change, a Salesperson in the same business unit as the user to whom the activity has been assigned (Sales Manager Amy, in our example) can accept the task record from the queue successfully. You might think they also need Business Unit level Assign for Lead, but they dont. This is because its the workflow that does the assigning of the Lead record, and the workflow runs in the security context of the owner of the workflow! Since the user has to manually accept the Task record from the queue that happens in their security context and they need these slightly higher privileges on the Activity entity.

Demonstration 4.2 - Assigning Leads on a Round-Robin Basis


An alternative to assigning records on a first-come first-served basis is to assign them sequentially, first to one sales rep, then to the next one, and so forth. Many people refer to this as round robin record assignment. Conceptually, the way to do this in a workflow is obvious: the first time you create a Lead record, assign it to sales rep 1, the second time to sales rep 2, and so forth, until you get to sales rep n, at which point you start over. It might sound easy, but its not. The problem is that the Dynamics CRM workflow engine doesnt know anything about any records of the primary entity other than the one its running on. Put differently, one running workflow instance doesnt know anything about any others. So theres no way of knowing that this is the first or second or nth time a Lead record has been created. You might think you can write out a number to a disk file and check to see what was written the last time a workflow ranbut you cant do this either. Theres a workaround, however, that subject to a few limitations can accomplish the goal. We cant write to or read from a disk file to count records, but we can use a custom entity with a 1:N relationship
126 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

to the Lead entity to accomplish essentially the same objective. There are lots of variations on the basic approach, but the one I use in this example can be broken down into two parts: first, create and configure the custom entity; second, create the main Lead assignment workflow. Follow these steps to create and configure the custom entity: 1. Create a new entity, called Lead Assignment Counter. You can accept all the defaults when you create this custom entity, although as youll see theres no real reason to turn on support for Notes and Activities. 2. Create one custom attribute for this entity and name it Counter, as is illustrated in the next figure. It should have a Type of int, for integer. You can give it a minimum value of 0 or 1 if you like but thats not required.

Figure 4-19- Lead Assignment Counter Entity

3. Create a new 1:N relationship from Lead Assignment Counter to Lead, by clicking the 1:N Relationships button, then New. Configure the relationship as we show in the following figure, by selecting Lead in the Related Entity pull-down list.

127 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 4-20 - Create a 1:N Relationship from Custom Entity to Lead

4.

Save and close the Relationship window, then click on the Information tab for the custom entity and select Settings in the Areas that display this entity section.

5. Save and close the custom entity window, and then publish the Lead Assignment Counter entity. 6. Finally, refresh the browser window if necessary, and navigate to the Settings area, where you should see the new entity. Click the New button to add one record. In the example here, we kept the default settings for the Name attribute. This is obviously not required, but to make a point we entered a short note in that field, and seeded the Counter field with a starting value:
Figure 4-21 - Enter a Single Record with a Starting Counter Value

Once the Lead Assignment Counter entity is created, were ready to create the Lead Assignment workflow. 1. Create a new workflow on the Lead entity with an appropriate name, give it a Scope of Organization, and have it run automatically when a new record is created:

128 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 4-22 - Workflow Properties

2.

The workflow itself will consist of two parts. The first part is a single Update Action that will use the 1:N relationship we created from Lead Assignment Counter to Lead. Effectively, we will make every Lead record a child record of the single Lead Assignment Counter record. Remember the primary entity for this workflow is Lead, but the Lead entity is a child entity in this particular 1:N relationship. This way we will have access to the Counter field in the parent entity, and can use it to keep track of whose turn it is to get the Lead assignment! The first part updates the Lead record, so pull down the Add Step menu and select Update Record, to make it look like this:
Figure 4-23 - Associate the Lead Entity with the Custom Counter Entity

3. Then click Set Properties, and navigate to the Additional Fields tab. The Assignment Counter lookup field should be there. This is the Display Name of the 1:N relationship we created (see Figure 4-20 above). And in this case since theres only going to be one record on the parent entity, you can simply use the lookup field to associate the Lead record with the record from the parent entity, as the next figure shows. Click Save and Close after selecting this.

129 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 4-24 - Associating Lead Record as a Child of Lead Assignment Counter

4. The second part of the workflow is a series of conditional branches, one for each of the sales reps who will be getting the lead assignments. Each branch uses a Check Condition to see what the current value of the Counter field is. If its current 1, the assignment in this example goes to Amy; if its 2, it goes to Andreas, and so forth, as you see here:
Figure 4-25 - Conditional Branches to Assign Leads

5. After each Assign action, the next action will be an Update Record. We need to reach back up into the parent record we use for counting and increment the Counter field, as you see in the next figure. An alternative approach would be to hardwire each of these steps, with the first one setting the value to 2, the next step setting it to 3 and so forth. On the whole I prefer the approach we show here, since it makes it a little easier to keep track of things if you need to add or remove sales reps or make other changes.

130 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 4-26 - Each Step Increments the Counter Field

6. The only conditional branch thats different is the last one. On the last one you need to reset the counter value to 1, so the next record that gets created essentially starts the process over again. You can see that as the last Action in the workflow (in the Otherwise conditional branch) in Figure 4-25. After saving and publishing the workflow, you can test it by adding a few Lead records. In Figure 4-27 you can see some test data that illustrate how it might work.
Figure 4-27 - Leads Assigned Round-Robin Style

Demonstration 4-3 Recursive Workflow for Case Escalation


This demonstration builds on the discussion in chapter 4 of recursive workflows, showing an actual business use of the techniques we discussed rather than simple mechanics!
131 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Business Scenario Suppose your call center has service level agreements that require cases be resolved in specified periods of time. You might implement an SLA with three levels of support: standard support is for new cases, most of which will be resolved within one day; level 1 support is an escalation, for cases that are not resolved within a day to be assigned to more senior staff; level 2 support represents another escalation level, with the highest level attention for cases that have been unresolved in level 1 for too long. Building the Workflow Building on the techniques we discussed in this chapter, this is actually a relatively straightforward workflow to implement. If you want to implement this yourself, the only customization you need to make first is the custom counter attribute we added to the Case entity. If necessary, refer back to the Recursive Workflows section in the book to remind yourself how to do that. In the example here we will use three Dynamics CRM Queues for the three levels of escalation. As you work through this yourself, remember two important and easy to forget facts about queues: 1. When a record is assigned to a queue, the value of the Owner attribute doesnt actually change. 2. A record can only be in one queue at a time, so when you assign it to one queue you dont need to worry about unassigning it from anywhere else. Here are the queues we will use for this example:
Figure 4-28 - Using CRM Queues for Case "Assignment"

After creating these queues, you can build the workflow by following these steps:

132 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

1. Create a new workflow for the Case entity and configure it to run automatically whenever a new record is created. Give it a scope of organization and make it available as a child workflow, as we highlight in Figure 4-29.
Figure 4-29 - Case Escalation Workflow Properties

2. The actual workflow consists of two main parts: an If condition checks to see if the Case is still in Active status, and then a Timeout enforces the terms of the service level agreement. Start by adding these two conditions to the workflow; we focus more specifically on these in Figure 4-30.
Figure 4-30 - Two Main Parts of Workflow

3. Of course, the real work is what happens within those two conditional blocks! Well examine them in detail now, starting with the Check Condition block. Notice in Figure 4-31 that most of the work is done by checking the value of the Escalation Counter attribute, and conditionally assigning the Case record to the appropriate queue. One interesting aspect of this that might not be obvious if you havent encountered it before is illustrated in the First time in check. Notice there that the condition to check for is does not contain data. Thats because the Escalation
133 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Counter attribute doesnt contain a 0 when a new record is created, as you might think. Rather, it doesnt contain anything (technically, its got a value of Null), and in Dynamics CRM that condition is conventionally referred to as does not contain data. After three levels of escalations, the workflow cancels. The Case remains in the Escalation level 2 queue, however, and the fact that the workflow cancelled doesnt have any impact on the Status of the Case record.
Figure 4-31 - Breaking Down First Conditional Block

4. In Figure 4-32 you can see how the Timeout block makes the workflow wait until the SLA period has elapsed, then checks to see if the Case is still Active. If it is, it uses the Update action to increment the Escalation Counter attribute, then starts another escalation by calling the workflow recursively.
Figure 4-32 - Breaking Down Timeout Block

Running the Workflow I should mention that even the most efficient call center probably wont have a service level agreement based on a one-minute resolution time as I show in this example. But its a lot quicker to test a workflow like this with shorter periods than long ones; I usually use one minute periods like this for

134 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

testing. After you save and publish the workflow, create a Case record to see how it actually works. There are lots of things you might do to test it, but in the next three figures, you can see a graphical illustration of what happens as a newly created Case record is gradually escalated through the three queues:

Figure 4-33 - New Case Record starts in Standard Service

Figure 4-34 - After SLA Period, Escalates to level 1 Queue

Figure 4-35 - Then to level 2 Queue, where it stays until Resolved

Demonstration 4.4 Manual Sales Process Workflow with Stages


Background In this demonstration, we will create whats known as a manual sales process workflow. But before we dive in, a little background is in order: in Dynamics CRM 3.0, the Opportunity entity behaved differently than others when it came to workflows, in that you could create a special workflow for an Opportunity known as a sales process workflow. This was the only kind of workflow in the 3.0

135 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

version that included stages, and that included a built-in ability to move back and forth manually between stages, by simply selecting the stage you wanted to move to. In Dynamics CRM 4.0, this somewhat ad-hoc treatment of the Opportunity entity went away, and now all entities are (at least in this sense) all created equal. This is generally a good thing, but what if you really want the ability to implement a workflow like this? For example, suppose for the sake of simplicity we have a 3-stage sales process: 1. Gather Requirements 2. Prepare Proposal 3. Negotiate and Close And that within each stage the workflow should wait until a user manually advances the workflow by selecting the appropriate value from a picklist available on the Opportunity form. Further, suppose we need the ability to both move forward in the process as well as backward. There are plenty of sales processes that might require this kind of flexible moving around within the various stages, skipping one or more if necessary, or going back to a previous stage. As we will see, the price we pay for no longer treating the Opportunity entity as special is that the more general approach we need to implement can get a little complicated. But its not too bad once you get used to it, and we will try to take an approach you can adapt to lots of situations in a fairly flexible way. Implementation We will create a workflow on the Opportunity entity named Basic Sales Process , with the following characteristics: Scope Starts when Available to run Organization Record is created Attributes change: Process Code (salesstagecode) As a child workflow

It will be a three-stage workflow, one for each of the sales process stages mentioned above, and within each stage the workflow will have a Wait condition that forces it to stay within that stage until a user manually changes the stage. In Figure 4-36 you can see the Workflow Properties, along with the first two stages.

136 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 4-36: Staged Sales Process Workflow

Here are some the most important points about this workflow: 1. Weve used the field Process Code (attribute name salesstage code) for the stages of the workflow. If you examine that attribute on the Opportunity entity, you will see that it is built-in, and its description indicates this is what its intended to be used for. Since this attribute already exists for this purpose, I recommend you use it rather than create your own custom attribute. 2. The workflow needs to be available As a child workflow since we need to call it recursively. This is only required if you want the ability to move backwards in the sales process. 3. Within each stage, the first thing we do is check to see if the workflow should stop within that stage. This too is only required for workflows that have this flexible jump from one stage to another functionality. 4. Notice that within each stage in the workflow we assign a task appropriate for that stage, but that the Wait condition doesnt have anything to do with that task being complete! In this kind of manual sales process, its changing the sales stage manually that advances the workflow,
137 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

so the Wait condition simply makes the workflow stop within the stage until the Process Code attribute changes. 5. In the first stage, the Wait condition causes the workflow to go into a Wait state, and it will stay in that state as long as the sales stage doesnt change. As soon as a user selects something other than Gather Requirements in the picklist exposed on the Opportunity form, the workflow will advance to the next stage. 6. But notice in the second stage, there is a nested If condition underneath the Wait. This is how we can move backwards: if the sales stage has been changed back to Gather Requirements, the workflow calls itself, essentially starting back at the top again. And any time a workflow does this, we want to then add a Stop workflow action, so we dont get two instances of the workflow both running at the same time!

Demonstration 4.5 Creating Audit Records for Deleted Opportunities


The approach we will take here is to create a custom entity that can be used to store information about deleted Opportunity records. As I mentioned earlier, its a little easier to create a workflow specifically to handle deleted records than it is to create a more general one, so well start with the easy one. (We can extend it without too much work, however, and well tackle that in the next demonstration.) Since a custom entity needs to be created, I generally think of this as a two-part process: 1. Design and create the custom entity, including the attributes you want to create a record of when an Opportunity record is deleted. 2. Build the workflow to create the audit records whenever an Opportunity record is deleted. Design and Create the Audit Entity Start by selecting from the 36 attributes available in the un-customized CRM Opportunity entity and determining the ones you want to store values of in your audit trail. This will obviously be determined by your business requirements, and will generally be a longer list than the one I propose in Table 4-1!

138 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Table 4-1 - Which Opportunity Attributes to Audit?

Display Name Potential Customer Est. Close Date Est. Revenue Modified by Owner Topic

Type Lookup against customer Date/Time Money Lookup against user Lookup against user Nvarchar (300)

To create and configure the custom audit attribute, follow these steps: 1. On the Dynamics CRM site map, click Settings, then click the Customization tab. 2. Click Customize Entities, then click New. 3. Name it Opportunity Audit, and (optionally) change the name of the default primary key label to Topic, so it matches up to the corresponding attribute in Opportunity. 4. Specify that the entity is to be organization-owned, that it does need support for Notes and Activities, and that it will only appear in the Settings area. Click Save. After the custom entity is saved, your entity form should look like the following:

139 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 4-37 - Custom Entity for Auditing Opportunity Records

140 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

5. After the entity is created, the next step is to add the required custom attributes. Of the six attributes indicated above in, one (Name/Topic) is already created, three (Potential Customer, Modified By, and Owner) will be created by creating custom relationships, and the Estimated Close Date and Estimated Revenue attributes need to be created by hand. 6. shows what a subset of the Opportunity Audit records (the ones I created) look like once theyre created.

Figure 4-38 - Custom Attributes of Audit Entity

7. Rather than go through a detailed step-by-step recitation of how to create each one, Ill provide high-level instructions here: a. To create Est. Close Date and Est. Revenue, simply click New, enter the Display Name and select the appropriate type. Remember what you want to do is have these match up exactly to the corresponding attributes in Opportunity, so if necessary, open it up in another window to make sure! b. The three lookup attributes (Deleted by, Owned by, and Potential Customer) provide a good example of Dynamics CRMs custom database features. Both Deleted by and Owned by should be filled in automatically, respectively, with the user who deleted the record, and the records owner at the time it was deleted. In CRM 4, you can create a new relationship between a System entity like User and a custom entity like Opportunity Audit to get this done. Since we will potentially have many audit records for a single user, click N:1 Relationships, and then click New Many-to-1 Relationship. For the Deleted by attribute, you want the form to look like Figure 4-39. The Owned

141 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

by will be identical (except for the name of the attribute), and the Potential Customer needs to be a lookup against either Account or Contact. Ill use Contact for this example.
Figure 4-39 - Configuring a N:1 Relationship to User Entity

8. After creating the custom attributes you want to track, you can add the attributes as fields on the entitys form. This isnt a real requirement, but its helpful to have a form to look at in certain circumstances and it doesnt take much work, so I generally do it. 9. Finally, save and publish the Audit Entity.

Build the Delete Workflow In this example, all the hard works essentially done. To build the workflow, follow these steps: 1. Create a new workflow with a scope of Organization and automatically triggered on the Record is deleted trigger. It only needs one action, which will create an audit record:

142 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 4-40 - Workflow to Audit Deleted Records

2. To populate the Opportunity Audit record with the values you need, click Set Properties. 3. Use Dynamic Values to configure the values you want. I often use a mix of static text and the audited records Topic field to construct a sufficiently eye-catching Topic. Remember this is supposed to flag deleted records and make them stand out, so in this example I included some *** asterisks on the front of the Topic field.
Figure 4-41 - Configuring Audit Record Values

4. Click Save and Close, then Publish the workflow. Test it to make sure it works as expected. The simplicity of a workflow like this one is due to its singleness of purpose, so to speak. One of the best reasons to take this approach rather than writing a more complex workflow that performs more functions is that its easier to understand.

Demonstration 4.6 Opportunity Audit Workflow


As you will see here, once weve got a workflow to create audit records for deletes, its almost trivial to add on a more general audit capability. In the example here, we will also write out audit records any

143 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

time the value of the Status attribute changes on Opportunity. It would be easy to extend this to audit changes in other values (estimated close date, revenue and probability all come to mind). In Figure 4-42, you can see the only difference between this and the previous workflow is the trigger: this one is triggered by a Record status changes event. Remember that for Opportunity, the values the Status attribute can take are Open, Won and Lost. As with all entities the Status attribute is NOT customizable (Status Reason, on the other hand, is), so all you need to do is click the checkbox.
Figure 4-42 - Audit Workflow Triggered by Status Changes

Heres how I configured the Set Properties in this example:


Figure 4-43 - Audit Record Values for Status Change Events

The only significant difference between this and the delete workflow is that in this case we probably should be concerned about the value of the Status attribute. The first time I tried this, I expected Id have to create custom Status Reason values for the Audit entity and somehow update them with the Status values from Opportunity. But I was pleasantly surprised to discover I could update any text field with the value from a picklist attribute so all I needed to do was to use Dynamic Values to construct a Topic value combining static text, the new value of the Status (from Opportunity), and the Opportunity Topic. Save and close and then publish the workflow, and test it. Figure 4-44 shows a few sample records.
144 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 4-44 - Sample Audit Records

And just for good measure, shows what one of those deleted records will look like at least, what it contained at the time it was deleted. If you ever encounter a situation where a significant number of important records get deleted accidentally or on purpose! you will be glad to have functionality like this in place.
Figure 4-45 - The Opportunity Record is Deleted, but its Values Remain

Demonstration 4.7: Creating a Record from an Unrelated Entity


This is an interesting technique that, once you understand how it works, youll be surprised how many scenarios there are for it. Well exploit the fact that workflows can create new records, and that they can insert field values from the primary entity of the workflow into the records created. Again: simple, but often quite useful. For example, we had a recent situation where records that had been imported into a custom entity (Class) also needed to be added as Opportunity records. (Since there was revenue associated with each Class record, the Opportunity pipeline would not have reflected an accurate revenue forecast otherwise). One way to add the Opportunity records would be manual, but that takes too much time. Another way would be to import the same data into the Opportunity entity, but importing is generally more timeconsuming. The best way to accomplish this is with a workflow: create an on-demand workflow on the Class entity, and the single action in the workflow is to create an Opportunity record. All we need to do is fill in the fields in Opportunity with information from Class. Heres an example of how it can look:

145 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 4-46 - Creating a Record without a Relationship

Since this workflow is written against the Class entity, when were creating the Opportunity record we have access to the field values from the current Class record, and we can simply fill in the appropriate fields on Opportunity. In some cases you wont be able to populate every field. For example, in this case our Class entity is organization owned, and the Opportunity entity is of course user-owned. So the workflow wont be able to dynamically populate the Owner field, but its generally a lot quicker to go back and update a couple of fields manually than it is to enter everything by hand! Once this workflow is published, we then simply go and use an Advanced Find to identify the Class records that need corresponding Opportunity records, and run the workflow manually:

146 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 4-47 - Running Workflow On-Demand

147 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Chapter 5 - Tips, Tricks and Traps


Importing and Exporting Workflows
Workflows are treated as customizations in Dynamics CRM 4.0, and the same as other customizations, can be exported from one CRM organization and imported into another. If you want to take advantage of the workflows I wrote for this book, for example, you can download any of them from the Student Portal site at www.IMGinc.com (remember: since we dont get your personal information from Lulu, if you purchased the book on www.Lulu.com , send me an email and Ill set up your subscription to the online version of the book.) But as you export and import workflows you may run into a few glitches, so in this section Ill provide some tips and tricks that can make re-using workflows somewhat easier.

Workflow Names
When you export a workflow (Settings, Customization, Export Customizations) CRM will suggest an export file name of customizations.zip. This isnt very descriptive, so I usually will change the name to something like Case-Escalation.zip instead.

Workflow Status Values


Again upon export, only the most recently published version of the workflow is exported. Suppose you unpublish a workflow, make some changes to it, save it, but do not publish it again. Then you export the workflow. None of the saved changes are in the exported workflow, since you havent yet published them. Suppose after exporting a workflow from what Ill call the source organization, you import it into the target organization. Immediately after import, the workflow will have a Status value of Draft. So you will need to publish it (change its Status value to Published) before it will run.

Workflows and Dependent Customizations


Many workflows will only work if certain customizations or configurations are in place. Many of the workflows I wrote for this book require custom attributes for existing entities, or custom entities, or relationships between entities. Some of the more obvious configuration settings workflows can be dependent upon include the existence of specific queues, users, and specific values for the lookup fields (Territory, Subject).

148 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

If you import a workflow that depends on customizations or configuration settings you havent made yet, its not a crisis youll generally be able to get it to work! Here are a few tips to get you started: Before you import, check the description. Many people dont provide enough in the way of descriptive text with their workflows, but if they do, make use of it! For example, just before you import a workflow, youll see it in the Import Customizations list. If you hover your mouse over the visible text on the Description field, you can actually see the entire description! So, for the workflows accompanying this book, Ive tried to provide as complete a set of instructions as possible in the description field. If youre careful, you could follow these instructions and make all of the required customizations before you import the workflows, and then they will work as soon as you publish them.

Figure 5-1 - Using the Description Field to Document Dependent Customizations

Suppose you do import a workflow dependent on customizations that havent been made. What then? Its usually not to difficult to fix things up; Ill walk through an example from the book the Case Escalation workflow from chapter 4. That workflow requires one customization (a custom attribute on the Case entity called Escalation Counter), and three queues. In you can see what the workflow looks like in the workflow design environment after its been imported into a Dynamics CRM organization that doesnt have those yet.

149 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 5-2 - Imported Workflow with Dependent Customizations

You might think you could simply close the workflow, create the necessary customizations and configurations, and then publish the workflow. Unfortunately its not quite that easy! First, notice that in what I refer to as Problem 1, the workflow has a condition that depends on a non-existent attribute. We need to add the attribute, then come back into the workflow and recreate the condition expression. Second, to fix Problem 2, we need to create the queues, then come back into the workflow and reselect them wherever they are referred to. Assuming you want to get the workflow working without changing the workflow itself, there are a couple of approaches you can use to fix problems like this one. In either one, you need to make the required customizations or configurations, so in this case, that means adding the custom attribute (Escalation Counter, type of int) to the Case entity, and creating the three queues. Once you do that, you can simply go into the workflow design environment and fix it up. That can be tedious, especially if its a complex workflow and it refers to lots of different entities and attributes in condition expressions. Fortunately, theres another option: delete the workflow and import it again! In my experience, for anything beyond a moderately complicated workflow, you will be better off if you simply re-import the workflow, and keep your manual workflow fix-up work to a minimum.

150 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Referring to Named Objects in Workflows


Workflows are not brittle with respect to names of entities they refer to. For example, if you have a workflow that routes service cases to different queues depending on certain conditions, and then you change the name of the queues, it still works just fine and will display the new name of the queues the next time you open the workflow. Another example of this is if you modify something like the display name of an attribute used in a workflow (e.g., on a link field in an entity relationship) that also doesnt hurt anything and will display correctly the next time you open the workflow. Suppose you have a workflow on the Opportunity entity and it creates a Task record, in which you use Dynamic Values to put Account(Potential Customer(Account)) into the workflow. Potential Customer is the default display name of the composite customer entity that is included as a lookup on the Opportunity entity. Suppose you change its display name to foo by modifying and publishing the Opportunity entity. The next time you come in to the workflow it will show up as Account(foo(Account)) and still work just fine. One interesting thing about this is that you dont even have to close the workflow! If you publish the entity after making your changes, all you have to do is refresh the list in the workflow design environment and it will pick up the new name.

Advanced Find and Workflows


Many people use the Dynamics CRM Advanced Find utility to do ad-hoc querying against familiar CRM entities such as Account, Contact, and so on. In this section Ill describe three of my favorite uses of Advanced Find when it comes to Dynamics CRM 4.0 workflows.

Advanced Find Queries for System Jobs


For workflows, all you need to do is go into Advanced Find and select System Jobs as the Look for value. For example, the following picture shows an Advanced Find query that looks up against the System Job entity with the System Job Type value equal to Workflow, and the Status Reason equal to Waiting.

151 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Figure 5-3 - Advanced Find for Workflows in Waiting Status

Figure 5-4 - Advanced Find Results

152 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

You can even narrow down the results set to see only the Workflow jobs currently Waiting which are related to Opportunity records. Do this by pulling down the Select list and selecting Regarding (Opportunity) (or any other entity youre interested in) from the list you dont need to set any criteria for it since this will automatically filter out anything that doesnt have an Opportunity record in its Regarding field. The next two figures illustrate this.
Figure 5-5 - Using Advanced Find to look up Opportunity Workflow Jobs

Figure 5-6 - Results Set -- All "Regarding" Values are Opportunities

Activity Records have an Is Workflow Created Attribute


Another interesting aspect of workflows that you can see using Advanced Find is this: all activity records (Phone Call, Email, Appointment, etc.) have a special attribute called Is Workflow Created

153 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

you can use to, well, see if the thing was created by a workflow! Figure 5-7 Shows an Advanced Find query in process that does this.
Figure 5-7 - Is that Activity Created by a Workflow?

There are lots of situations where this might be useful. Just remember its only available for Activity record types, unfortunately.

Workflows and Entities are Related to Each Other


I mean this in the Dynamics CRM sense of an N:N relationship. This is nice because you can exploit these relationships in Advanced Find. For example, suppose you wanted to see all of the Opportunity records that had ever had a workflow run against them. You can create an Advanced Find view on Opportunity, and then use the System Jobs entity to run a query for all opportunity records that are related to System Job records of the workflow type:
Figure 5-8 - Filter by System Job Type Equals Workflow

154 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Working with Workflow Templates


Suppose you create a sales process workflow for your organization, and then receive requirements for a slightly different sales process say, for a different product or service line. In some scenarios you might be able to add logic to the workflow so that a single workflow can accommodate different product or service lines. But in other scenarios you might want to make a copy of the sales process workflow and then make changes to the copy. Certainly if the workflow is complex, and the changes are minor, this will be quicker than starting from scratch. And remember the Sales Pipeline report we saw in the previous example. If you have two different sales process workflows, then you can select either of them from that Group by list we saw, and examine your pipeline along these alternative sales process groupings. In a scenario like the second one making a copy of a workflow you can use a workflow template. The easiest way to do this is to follow these steps: 1. Open an existing workflow, change the name if necessary, and in the Publish as list select Workflow template. 2. Then save and publish it. 3. To create your new workflow based on this template, navigate to Settings/Workflows and click New, select the New Workflow from Template option in the dialog, select the entity you want to create it for, and click OK.

Workflow Security
Workflow security is controlled primarily through security roles. On the Customization tab of each security role, you can see that the Workflow entity can be configured like most of the others:

155 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

In this screenshot you can see that the CSR security role has User level access for Workflow permissions. This is typical of most security roles, and means that they can create and manage their own workflows only. However, they can only create a workflow for an entity they have permissions to! So for example, if someone in the CSR role you see above did not have at least User-level Read permissions on the Opportunity entity, they wouldnt see Opportunity in the list in the New Workflow dialog. Heres an example to see how this works: 1. Signed in as a System Administrator, open up a security role and remove all permissions for the Workflow entity. 2. Then sign in as a user with that security role (and only that security role!) and verify that you wont be able to create any workflows. 3. Then sign in as the System Administrator again, and reset permissions for the Workflow entity to User-level across the board, as you see in the screenshot above. 4. Then go to the Core Records tab for that security role and remove all permissions for an entity, for example, the Lead entity. Then switch security roles again and verify that you can now create workflows, but that the Lead entity will not appear in the Entity list. Theres a general way to understand security roles and workflows, if you compare the workflow permissions available to the different security roles: Type of security role User role Roles of this type Salesperson, Customer Service Workflow Privileges User
156 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

Manager role VP role Administrator role

Representative CSR Manager, Sales Manager Vice President of Marketing, Vice President of Sales System Administrator, System Customizer, CEO-Business Manager

Business Unit Parent-Child Business Unit Organization

Notice that the lowest level security roles (nothing personal against salespersons!) have User level workflow privileges only, and each successively higher group of security roles has, in turn, Business Unit, Parent-Child Business Unit, and Organization privilege.

Workflows and Importing Records


Heres something thats important to remember and easy to forget: automatic workflows triggered by the Record is created event run any time a new record is created, even if its created by Dynamics CRMs Data Management/Import feature. Heres a common business scenario where this might be important: Suppose you have a number of processes that happen in the normal course of business when new Lead records are created. And suppose in the normal course of business means when leads are created in the following ways: Someone visits your web site and fills out a request information form. Someone calls on the phone in response to a magazine ad. Your marketing manager returns from a tradeshow with a big stack of business cards.

Contrast those with purchasing a list of hundreds or thousands of names and importing them all as Lead records. Probably because the Lead record is a nice, flexible, general-purpose entity that can be used for lots of different kinds of leads, it tends to be used for records that might really require significantly different kinds of followup. If you have a characteristic lead qualification process that is implemented as an automatic workflow on the Lead records create trigger, you might consider temporarily turning it off (unpublishing it) before you import those thousands of Jigsaw leadsotherwise it will run for all of them!

Summary
I wanted to end the book with this Tips, Tricks and Traps chapter, but now I think it may have been a mistake at least for me as the author. I say this because it forced me to realize theres really no end to the topics I could include here, so in a sense the book can never really be complete. On the other hand, one of the advantages of the digital age in which we live is that its a lot easier to update content
157 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

than it used to be. And since purchasers of this book get access to the content in the even easier-toupdate online format, you can stay up to date as I add more content online. And by all means: email me (richardk@imginc.com) your favorite tips, tricks and traps about Dynamics CRM workflows, and Ill include them as we build out our collaborative CRM learning community.

158 Building Workflows in Dynamics CRM 4 Richard Knudson and IMG, 2009 www.IMGinc.com

You might also like