Chapter 18. Advanced workflows

In this chapter, you will learn about some advanced topics and new features introduced with Microsoft SharePoint 2013. The chapter will explain how you can create custom actions by using declarative activities, as well as by writing code-based activities. You will learn about workflow security and how to use Workflow Services Manager from the client side. If you are working with SharePoint workflows for the first time, you may wish to postpone a careful reading of the material until after you have more experience with standard workflow features. If you’re comfortable with the basics of workflows and are ready to take your projects to the next level, however, read on now.

Custom actions

One of the main areas of extensibility for every workflow solution—not just SharePoint solutions—is developing custom activities. In Chapter 15, you learned the very basics of creating custom activities: simply defining a custom class that inherits from the System.Activities.Activity base class. Depending on your implementation, you may need to do more. In this section, you will learn how to develop custom activities targeting both SharePoint Designer 2013 and Microsoft Visual Studio 2012.

Let’s start with some useful definitions. As you know, an activity is a building block of a workflow and represents the minimal unit of workflow execution. An action is a high-level wrapper of one or more activities to provide a human-readable statement within SharePoint Designer 2013 or another client platform. Because in SharePoint 2013 the Workflow Manager engine is open for integration, you can implement workflow designers of your own that consume the Workflow Services Manager services (the section “Workflow Services Manager” will explain how).

You can define a custom action two ways. You can work declaratively in Visual Studio 2012, simply using the designer without writing any code, to create a declarative activity. Alternately, you can create some custom code to define a code activity that will enable you to use the whole .NET development environment. The code-activity scenario is suitable only for on-premises farms, because it requires you to deploy your custom code using a full-trust solution.

Creating a declarative activity

To create a declarative activity, you must have a development environment with SharePoint 2013 Server and Workflow Manager installed locally. On the same machine that houses SharePoint 2013, you must also install Visual Studio 2012 Professional or higher, as well as the Microsoft Office Developer Tools for Visual Studio 2012.

Imagine that you want to create a custom activity for consuming a list of customers from an external Representational State Transfer (REST) or OData service. For example, you can consume the publicly available OData service for reading the well-known Northwind database, which is available at http://services.odata.org/Northwind/Northwind.svc. To begin, launch Visual Studio 2012, create a new project of type SharePoint 2013 - Empty Project, and choose to produce a sandboxed solution. Next, add a new item of type Workflow Custom Activity to the project. You will be prompted with a workflow activity designer that already includes a Sequence activity.

The order-approval workflow needs to retrieve some data about the target customer of the order; it does so by querying the Northwind OData service using the CustomerID field. The REST URI for retrieving the customer data is http://services.odata.org/Northwind/Northwind.svc/Customers(’ALFKI’)?$select={CustomerID},CompanyName,ContactName,ContactTitle,Country.

Replace the {CustomerID} argument with the CustomerID value of the customer to look up. The JSON response of the Northwind OData service during a query for a specific customer instance shows the JavaScript Object Notation (JSON) result of the service invocation.

More Info

To check the output of the service, you can use the Fiddler2 tool (http://www.fiddler2.com/). To view the JSON output format, remember to configure an Accept HTTP header with a value of application/json.

To implement the custom activity (call it NWCustomerLookup), you first need to create an input argument with name CustomerID to receive the ID of the customer to look for in the Northwind database. You also need a set of output arguments for holding the return values, which are all of type String; name them CompanyName, ContactName, ContactTitle, and Country.

To effectively contact the remote OData service, you can use the HttpSend activity, available in Visual Studio 2012. Simply provide the target URL, as well as the Accept HTTP header (application/json). To create the set of HTTP headers, use a BuildDynamicValue activity and put the output into a responseHeaders variable of type DynamicValue. You can place the response in a variable of type DynamicValue, as well. Table 18-1 shows the configuration provided to the main properties of the HttpSend activity.

Table 18-1. The configuration provided to the main properties of the HttpSend activity

Attribute name

Description

Value

Method

Defines the HTTP method or verb

GET

Uri

Defines the URI to contact; in this example, it will be dynamically calculated using the input argument CustomerID

“http://services.odata.org/Northwind/Northwind.svc/Customers(’” + CustomerID + “’)?$select=CustomerID,CompanyName, ContactName,ContactTitle,Country

RequestHeaders

Declares the HTTP request headers that will be used to contact the remote endpoint

requestHeaders

ResponseContent

Represents the response, as a variable of type DynamicValue, returned by the remote service

responseContent

By using the GetDynamicValueProperties activity, you can retrieve the fields and place them inside the specific output arguments. Figure 18-1 illustrates the outline of the custom declarative activity.

A screen shot illustrating the custom declarative activity outline in the designer of Visual Studio 2012. It includes a Sequence activity containing a BuildDynamicValue activity, an HttpSend activity, and a ParseDynamicValue activity.

Figure 18-1. The outline of the custom declarative activity in the designer of Visual Studio 2012.

To deploy the custom activity, you need to do a little bit of work, which is covered in detail in the next section. For now, assume you have already deployed the custom declarative activity, and take a look at Figure 18-2 to see how the custom activity behaves in SharePoint Designer 2013.

A screen shot presenting how the custom declarative activity behaves in SharePoint Designer 2013. It shows a text expression accepting the configuration of the target CustomerID field, as well as the output variables for storing the activity results.

Figure 18-2. The custom declarative activity in the designer of SharePoint Designer 2013.

Important

Whenever you deploy custom actions or custom activities for SharePoint Designer 2013, the client tool will need to refresh its local cache; otherwise, the new elements will not be available. Luckily, SharePoint Designer 2013 informs you about this issue. Nevertheless, you must manually clear the cache. To accomplish this task, simply delete the folder with path user profileappdatalocalmicrosoftwebsitecachesitename.

The sample illustrated in Figure 18-2 defines a simple site workflow, which is defined just to test the custom declarative activity. As you can see, the activity is described using the following sentence:

Lookup for customer with CustomerID in Northwind (Output to: Variable: CompanyName, Variable:
ContactName, Variable: ContactTitle, Variable: Country).

The CustomerID token represents an input argument, while the CompanyName, ContactName, ContactTitle, and Country arguments are the output values that will be saved in workflow variables. Notice that inserting the action in the designer will automatically create the target variables for holding the output values. In the next section, you will learn how to achieve this automatic behavior.

Deployment of declarative actions

From a deployment and provisioning viewpoint, workflow actions and activities are defined in specific files with an .actions4 extension, which vary by language and which can be installed onto the SharePoint servers in the folder SharePoint15_RootTEMPLATELanguage LCIDWorkflow. The Language LCID represents the locale ID of the target language. For example, the English (LCID: 1033) version of the .actions4 files will be installed in the folder SharePoint15_RootTEMPLATE1033Workflow.

Note

SharePoint15_Root refers to the SharePoint root folder, which is typically located at C:Program FilesCommon FilesMicrosoft SharedWeb Server Extensions15.

In the same folder, you will also find some .actions files. However, those files are related to SharePoint 2010 and the legacy WF 3.x workflow engine, and you should not bother with them in this chapter. The .actions4 files can also be provisioned using sandboxed solutions, if you want to deploy custom declarative activities in Microsoft Office 365. A code excerpt of the workflow15.actions4 file for defining an action shows a code excerpt of the default workflow15.actions4 file, which contains the same out-of-the-box actions you saw while making your first workflow with SharePoint Designer 2013 in Chapter 16 A code excerpt of the workflow15.actions4 file for defining an action defines the native Set Field in Current Item action.

As you can see, the excerpt defines an Action element, which is the root element for any action definition. This element requires a ClassName attribute, which defines the underlying .NET type that effectively implements the action. The most common attributes of the Action element are illustrated in Table 18-2.

More Info

For further details about the workflow configuration schemas in SharePoint 2013, you can read “WorkflowActions4 schema reference,” available on MSDN at http://msdn.microsoft.com/en-us/library/jj583378.aspx.

Table 18-2. The main attributes for configuring a custom action in the .actions4 files

Attribute name

Description

Data type

__SolutionId

Specifies a GUID that the client application writes to the implementation-specific action. The server uses the GUID to help locate the assembly at workflow run time.

xsd:string

AppliesTo

Defines the target of the action. The available values are site, list, doclib, and all. They are all self-explanatory. Depending on the value provided to this attribute, the action will be visible and either available or not in the UI of SharePoint Designer 2013. It is a required attribute.

xsd:string, within a fixed set of available values: site, list, doclib, and all.

Assembly

Is the strong name (Name, Version, Culture, PublicKeyToken) of the assembly containing the type implementing the custom action.

xsd:string

Category

Provides the category where the action will show up in the UI of SharePoint Designer 2013.

xsd:string

ClassName

Is the fully qualified name of the class that implements the workflow action. It is a required attribute.

xsd:string

FunctionName

Specifies the name of a function to call. That function will be defined in the ClassName attribute, available in the assembly defined in the Assembly attribute.

xsd:string

Name

Is the descriptive name of the action, and is displayed in the UI of SharePoint Designer 2013. It is a required attribute.

xsd:string

SandboxedFunction

If true, calls a specific function defined in the class with name equal to the ClassName attribute. That class will be searched in the assembly with a strong name value equal to the content of the Assembly attribute. That assembly will by looked for in the solution with the ID value defined in the __SolutionId attribute.

xsd:boolean

ShapeImageUrl

Defines the URL of an image that will be used in the UI of SharePoint Designer 2013 to present the action.

xsd:string

UsesCurrentItem

Indicates whether the action targets a specific list item, or if it is suitable for a site workflow. If this attribute is configured with a value of false or is not configured, the action can be used in a site workflow. Otherwise, the action can only be used in a list workflow.

xsd:boolean

The main child elements of the Actions element are RuleDesigner and Parameters. The former defines the behavior of the custom action within SharePoint Designer 2013, and declares the sentence to prompt to the user designing the workflow, as well as any field to ask for. Reading A code excerpt of the workflow15.actions4 file for defining an action, you can see that the RuleDesigner element accepts a Sentence attribute, which defines a tokenized string. For example, the sentence for the Set Field in Current Item action is the following:

Set %1 to %2

where %1 and %2 correspond to two occurrences of children FieldBind elements. Every FieldBind element defines a field that matches a token in the sentence. The FieldBind element accepts a wide range of attributes, which are illustrated in Table 18-3.

Table 18-3. The main attributes for configuring the FieldBind element in the .actions4 files

Attribute name

Description

Data type

DesignerType

Defines the data type to use within the designer UI of SharePoint Designer 2013. The main available values are defined later in this section. It is a required attribute.

xsd:string

DisplayName

Represents the display name of the field in the UI of SharePoint Designer 2013.

xsd:string

EventCategory

Defines the event category type for instances of the FieldBind element with a DesignerType attribute with a value of ListItemEvent or EventDropdown.

xsd:string

Field

Declares the name of the field corresponding to the current FieldBind element. There will be a Parameter element (in the Parameters element section) with the Name attribute with the same value.

xsd:string

Id

Defines the numeric ID of the field, and will match the %Id token declared in the Sentence attribute of the RuleDesigner parent element.

xsd:positiveInteger

OperatorTypeFrom

When the DesignerType attribute has a value of Operator, declares the field from which the current field will retrieve its operator type.

xsd:string

Text

Declares the descriptive text used for presenting the field in the UI of SharePoint Designer 2013.

xsd:string

TypeFrom

When the DesignerType attribute has a value of Dependent, declares the field from which the current field will retrieve its type.

xsd:string

The Parameters element of the .actions4 file behaves similarly to the RuleDesigner element. In fact, the Parameters element is the parent of a set of Parameter elements, where each one describes a single parameter with a direction (input, output, or optional), name, type, and designer behavior. Table 18-4 lists the main attributes available for configuring each Parameter element.

Table 18-4. The main attributes for configuring the Parameter element in the .actions4 files

Attribute name

Description

Data type

Description

Defines the description of the current parameter.

xsd:string

DesignerType

Defines the data type to use within the designer UI of SharePoint Designer 2013. The main available values are defined later in this section. It is a required attribute.

xsd:string

Direction

Declares the direction (input, output, or optional) for the parameter.

xsd:string, within a fixed set of available values: In, Out, and Optional.

DisplayName

Represents the display name of the field in the UI of SharePoint Designer 2013.

xsd:string

InitialValue

Defines the initial and default value for the parameter.

xsd:string

Name

Defines the name of the parameter. The value of this attribute is used to reference the parameter in the FieldBind elements.

xsd:string

Type

Defines the underlying data type, represented as a .NET type with a name and container assembly.

xsd:string

Each Parameter element can be referenced by name in the FieldBind elements. In The content of the NWCustomerLookup.actions4 file for defining the NWCustomerLookup declarative activity, you can see the NWCustomerLookup.actions4 file, which defines the custom NWCustomerLookup declarative activity you created in the previous section.

To deploy the current custom activity, you simply need to package the resulting WSP file and upload the sandboxed solution to the target site collection. Visual Studio 2012 already does this for you, and also creates an .actions4 file in the project. That .actions4 file will be almost empty, however, so you will have to compile it manually, and without any kind of IntelliSense or syntax check. In case you are creating a declarative activity within a sandboxed solution, the .actions4 file, the XAML file, and any other elements are deployed to the content database of the target site collection through a sandboxed solution. Because you don’t need physical access to the file system of the target server farm, the declarative activities are the first choice for extending native activities in the context of a Office 365 cloud-hosted solution.

While compiling the .actions4 file, you must provide values for a variety of settings. For example, the DesignerType attribute accepts a long list of possible values. The most interesting and frequently used of these values are the following:

  • TextBox. Accepts a text value and presents a text box in the UI of the designer.

  • Operator. Allows for providing a set of values in a dedicated list of Option elements.

  • Dependent. Declares a field type that will retrieve its data type from another field, declared in a TypeFrom attribute.

  • Dropdown. Presents a drop-down list of values on the design surface.

  • SinglePerson. Provides a single-user lookup on the design surface.

  • Date. Provides a control for selecting a data value.

  • TextArea. Allows for setting a multiline text field.

  • RestCall. Defines the arguments of a REST/HTTP call.

  • ParameterNames. Creates a variable in the current workflow context, using the type and name of the current field or parameter.

  • StringBuilder. Provides a control for building a value of type String.

  • Dictionary. Allows for creating a collection of key/values pairs. Behind the scenes, it corresponds to a DynamicValue variable.

  • Hide. Prevents a field from being displayed on the design surface.

  • ListItem. Provides a lookup to a specific list item.

  • CreateListItem. Provides the UI for configuring the creation of a new list item.

  • UpdateListItem. Provides the UI for configuring the update of a list item.

  • ItemProperties. Provides the UI for configuring a set of fields for a list item.

  • ChooseListItem. Provides the UI for selecting a specific list item.

  • DocLibNames. Provides the UI for selecting a specific document library using a drop-down list of all the available document libraries.

  • Email. Provides the UI for defining an email address.

  • Person. Allows for providing a single person as the variable type.

  • WorkflowParameters. Provides a lookup to the workflow context parameters.

  • Float. Provides a numeric field or property of type float.

  • Stages. Provides a drop-down list for selecting a specific stage of the workflow definition.

Creating a code activity

A code activity, which is suitable only for on-premises scenarios, can be based on one or more code files. Let’s start with a simple example of a custom credit card validator activity. You can inherit from the base CodeActivity<T>, where the type of T will be Boolean and will return true if the argument named CreditCard, which is of type InArgument<String>, represents a real credit card number.

Create a new Visual Studio 2012 project of type Activity Library and add a new item of type Code Activity with the name CreditCardValidationActivity. The code template for a code activity item already includes a property of type InArgument<String> and overrides the Execute method of the base CodeActivity class. Change the base class of the CreditCardValidationActivity class to inherit from CodeActivity<Boolean>, and refresh the signature of the method overriding the Execute method of the base class. Now you are ready to implement the business logic of the custom code activity. The source code of the custom code activity for validating credit card numbers provides the code for implementing the custom activity, which internally uses the .NET 4.5 data validation framework to check the credit card number. For this purpose, you will need to reference the assembly System.ComponentModel.DataAnnotations with version 4.0.0.0.

More Info

The sample code activity uses a publicly available algorithm for validating the credit card numbers, which is mainly a kind of CRC (cyclic redundancy check). Called LUHN after its inventor, the algorithm is documented at http://en.wikipedia.org/wiki/Luhn_algorithm. On the Internet, you will find tons of code samples for validating credit card numbers using this algorithm. Starting in .NET 4.5, however, you have an alternative: using a native class called CreditCardAttribute, which is available in the System.ComponentModel.DataAnnotations namespace and is useful for validating credit card numbers.

As you can see, the custom code activity itself is very simple, in order to keep the focus on implementation and deployment.

Deployment of code activities

You can define a real custom activity with all the arguments that you like, whether they are of type InArgument<T>, OutArgument<T>, or InOutArgument<T>. You can implement the business logic with as much complexity as you like, but sooner or later you will need to deploy the activity.

The first step is still the creation of an .actions4 file. The content of the CreditCardValidationActivity.actions4 file for defining the CreditCardValidationActivity contains the .actions4 file for the CreditCardValidationActivity.

As you can see, the file is almost the same as the one defined in The content of the NWCustomerLookup.actions4 file for defining the NWCustomerLookup declarative activity. However, this time, the Action element is wrapped in an Actions parent element, and the XML file has a WorkflowInfo root element. Moreover, the Action element declares the Assembly attribute, which references the strong name of the assembly providing the custom activity class. The assembly will need to be strongly named, because it will have to be deployed in the GAC (Global Assembly Cache) of the SharePoint servers. This time, the custom .actions4 file will go to the file system, not to the content database of the target site collection through a sandboxed solution.

While developing custom code activities, you must define a second XML file, called AllowedTypes.xml, which declares the types allowed for loading in the Workflow Manager engine. The AllowedTypes.xml file defined for the CreditCardValidationActivity defines that file for the sample CreditCardValidationActivity class.

The file is simple, and declares the assembly, namespace, and class name of the types allowed to run in the workflow engine.

The following are the steps for deploying the custom code activity to Workflow Manager.

  1. Copy the assembly and the AllowedTypes.xml file into the following path locations:

    • %ProgramFiles%Workflow Manager1.0WorkflowArtifacts

    • %ProgramFiles%Workflow Manager1.0WorkflowWFWebRootin

  2. Restart the Workflow Manager engine (that is, the Workflow Manager Backend service).

  3. To make the custom activity available in SharePoint 2013, copy the assembly into the GAC of all the involved SharePoint servers.

  4. Add the .actions4 file to the path SharePoint15_RootTEMPLATELanguage LCIDWorkflow.

  5. Restart Internet Information Services (IIS) (execute an IISReset).

  6. Clean the client-side cache of SharePoint Designer 2013.

In the case of multiserver deployment, you must execute the preceding steps on each server of the farm.

More Info

For further details about deploying custom code-based activities, you can read the document “Defining and using custom code activities and types in a Workflow Manager 1.0 workflow,” at http://msdn.microsoft.com/en-us/library/windowsazure/jj193517(v=azure.10).aspx.

Now you are ready to play with your new custom activity in SharePoint Designer 2013.

Because some of the files have to be copied outside of the SharePoint15_Root path (that is, C:Program FilesCommon FilesMicrosoft SharedWeb Server Extensions15), you cannot create an automated setup-and-deployment process that uses a WSP file. Unfortunately, you will need to create a PowerShell file, or something similar, to replicate and automate the installation process. Nevertheless, for the SharePoint side of the deployment, you can use a farm-level solution—which will be capable of deploying the assembly to the GAC—to copy the .actions4 file to the Workflow folder of SharePoint 2013, as well as to recycle the IIS application pool process.

After deploying the custom code activity, you will be able to find it in SharePoint Designer 2013, as shown in Figure 18-3 (see the red outline).

A screen shot illustrating the list of available actions in SharePoint Designer 2013. The two custom activities defined in this chapter are outlined in red within the DevLeap group.

Figure 18-3. The custom code activity in the list of available actions in the designer of SharePoint Designer 2013.

Figure 18-4 shows the behavior of the custom code activity in SharePoint Designer 2013. From an end-user viewpoint, a custom activity is presented the same way whether it is declarative or code based. Behind the scenes, however, the deployment process is different, and the potentials are completely different, too. While a declarative action can use already existing actions only, a code-based activity can do whatever you want, because it uses custom code.

A screen shot illustrating how the custom code-based activity is presented in the UI of SharePoint Designer 2013. It displays the standard expression text with a couple of variables to fill out.

Figure 18-4. The custom code activity in the designer of SharePoint Designer 2013.

Security and workflow app principal

In SharePoint 2013, the workflow engine has been changed not only from an architectural viewpoint, but also from a security perspective.

In SharePoint 2010, the workflow instances run as the initiating user by default, or can run impersonating the publisher via the impersonation step, or can run acting with elevated privileges using some custom code. Now, in SharePoint 2013, workflows have their own identity, which is an app principal. To experience this behavior, open the web browser and navigate to the Site Settings page. There, under the Users And Permissions group of actions, click the Site App Permissions menu item. Figure 18-5 shows the output in the web browser.

A screen shot depicting the Site App Permissions page of a SharePoint 2013 site with workflow definitions. The Workflow app, with its own app identifier, is outlined in red in the list of apps.

Figure 18-5. The Site App Permissions page of a SharePoint 2013 site with workflow definitions.

Notice the app outlined in red, which has a display name value of Workflow and a dedicated app identifier. This is the app identity that will be used by the workflow engine for performing operations. For the sake of completeness, notice that in the Site App Permission page there is also an app identifier for SharePoint itself. To better prove the existence of an app principal dedicated to the workflow engine, start a workflow instance of a workflow definition created with SharePoint Designer 2013, targeting, for example, the Documents library of the current site. Imagine starting an instance of the sample approval workflow defined in Chapter 16. That workflow definition creates a task. Open the task and check the Created At and Last Modified At fields (see Figure 18-6).

A screen shot highlighting the Created At and Last Modified At properties of a task item created by a workflow instance. The image shows that the creator and last modifier comprise the Workflow app principal, acting on behalf of the real target user.

Figure 18-6. The display page of a task item created with a custom workflow definition.

As shown in Figure 18-6, the creator is “Workflow on behalf of Paolo Pialorsi” and the modifier is “Workflow on behalf of Paolo Pialorsi.” What you have just seen makes clear that the workflow engine has its own identity and acts on behalf of the target users. By default, any workflow instance will act on behalf of the current user, and consequently, any update or item creation will be marked as illustrated in Figure 18-6. From an authorization viewpoint, the item creation or modification will be authorized only if the workflow app permission and the user permission both have the right to do so. If the user or the workflow do not have the permission to perform an operation, then that operation will fail.

Occasionally, you may need to implement a workflow for performing actions that users can’t perform. For example, imagine an approval workflow that has to move a document from one library to another, where the target library is not directly accessible by the users of the workflow. In such situations, because of the authorization policy you have just seen, the file-move operation would fail. However, there is an option to execute a step with the identity of the workflow app only, without combining the workflow app identity with the user’s identity. The result will be a kind of elevation of permissions, from the workflow app perspective. To achieve this, you can use the App Step capability, which is available in SharePoint Designer 2013. First of all, you need to activate a specific site feature called Workflows Can Use App Permissions from the Site Features page (Figure 18-7).

A screen shot illustrating the Workflows Can Use App Permissions feature on the Site Features page of a SharePoint 2013 site. The feature description states, “Allow workflows to read from and to write to all items in this site.”

Figure 18-7. The Site Features page of a SharePoint 2013 site with the Workflows Can Use App Permissions feature highlighted.

Important

If you activate the Workflows Can Use App Permissions feature while editing an existing workflow definition in SharePoint Designer 2013, you will need to close and restart SharePoint Designer 2013 to make it aware of the availability of the App Step capability.

After activating the feature, insert an app step into the target workflow definition by clicking the ribbon button highlighted in Figure 18-8.

A screen shot showing the ribbon available while designing a workflow in SharePoint Designer 2013. The App Step button is highlighted.

Figure 18-8. The App Step ribbon button available in SharePoint Designer 2013.

An app step is just a container of actions and conditions that will be executed under the workflow app identity only. In Figure 18-9, you can see the outline of a sample workflow definition, which creates a list item in a fake target list of contacts by using the standard workflow app principal combined with the user’s identity. Then, using an app step, the workflow definition updates the just-created item by using the workflow app principal only.

A screen shot showing the outline of a sample workflow definition using an app step in SharePoint Designer 2013. There is a unique workflow stage, made of a Create Item activity followed by an app step. The app step contains an Update Item activity, which updates the newly created item.

Figure 18-9. The outline of a sample workflow definition using an app step in SharePoint Designer 2013.

As you can imagine, showing the properties of the item created and then updated by an instance of this sample workflow definition reveals that the item was created by “Workflow on behalf of Paolo Pialorsi,” as it was in the previous examples (see Figure 18-10). The same item was last modified by the workflow principal only, however.

A screen shot showing the Created At and Last Modified At properties of an item created and updated by a workflow definition that uses the app step for updating the item. The Created At value states “by Workflow on behalf of Paolo Pialorsi,” while the Last Modified At value states “by Workflow” only.

Figure 18-10. The security properties of an item created and updated by the sample workflow definition using the app step.

When you design a workflow definition that uses an app step, during the publishing phase, SharePoint Designer 2013 will warn you that you are publishing a potentially dangerous workflow (see Figure 18-11). In fact, the workflow app identity will have permissions to read and write any item in the target site. Thus, the app step provides a way of having a full elevation of privileges, and you should therefore use it carefully.

A screen shot illustrating the warning prompted by SharePoint Designer while publishing a workflow definition that includes one or more app steps. The warning states, “By publishing this workflow, conditions and actions inside App Steps will run using only application credentials. Only continue if this is the intended behavior.” You have the option of clicking OK or Cancel.

Figure 18-11. The warning prompted by SharePoint Designer 2013 while publishing a workflow definition that includes one or more app steps.

While developing workflows with Visual Studio 2012, the counterpart of the app step is the AppOnlySequence activity. As discussed in Chapter 17 the AppOnlySequence activity is a container activity that executes all activities inside of its scope with the identity of the workflow, instead of using the identity of the workflow initiator user.

When you create a workflow definition with Visual Studio 2012 inside a SharePoint app, the identity of that workflow will be the identity of the container app. Thus, any list or item inside the app website will be accessible for reading and writing to the workflow instances, too. Meanwhile, the contents in the host website will be accessible to the workflow definition only if the app has the proper permissions granted.

Starting from SharePoint 2013, you should create workflow definitions that target a site using SharePoint Designer 2013, in order to be able to use the same workflow definition and the new declarative model regardless of whether you are on-premises or on Office 365. When you are creating a custom SharePoint app, however, you should use a workflow definition created with Visual Studio 2012. In this last case, you should create workflow definitions that target the contents of your app website, not workflow definitions that write content of the host web. Because your app could be installed on any host web, you cannot make any assumptions about the data structures available in the host web. Nevertheless, under specific rights grants, you can also create a workflow that reads or writes content in the host web.

Workflow Services Manager

The new architecture of workflows in SharePoint 2013 introduces the Workflow Services Manager component, which (as you learned in Chapter 16, and in particular Figure 16-2) handles all the main tasks and activities related to the new workflow infrastructure. In SharePoint 2013, when you want to talk and interact with the workflow engine, you need to talk and interact with Workflow Services Manager, which will be the proxy to the Workflow Manager engine. Figure 18-12 depicts the main capabilities offered by Workflow Services Manager.

A schema illustrating the main capabilities of Workflow Services Manager: Deployment service, Instance service, Subscription service, Messaging service, and Interop service.

Figure 18-12. The main capabilities offered by Workflow Services Manager.

Workflow Services Manager provides a rich set of services and capabilities, which are

  • Deployment service. Enables saving, publishing, and updating properties of workflow definitions. It also offers methods for validating the XAML of workflow definitions.

  • Instance service. Enables managing and interacting with running workflow instances. It allows retrieving the list of running instances, a reference to a specific instance, and sending a direct message to a workflow instance.

  • Subscription service. Manages the associations between workflow definitions, deployed through the Deployment Service, and targets, which can be lists or sites.

  • Messaging service. Handles messaging from SharePoint to workflow instances via the Service Bus infrastructure.

  • Interop service. Allows executing legacy SharePoint 2010 and WF 3.x workflows from the new engine. It is fundamental to guarantee backward compatibility with workflows already defined in SharePoint 2010.

The goal of Workflow Services Manager is to provide a rich set of APIs, regardless of whether you are on the server side using the Server Side Object Model or on the client side using the Client-Side Object Model (CSOM), the JavaScript Client Object Model (JSOM), or REST. This rich set of APIs allows managing, deploying, provisioning, and communicating with workflow definitions and instances from any external SharePoint app, mobile device, custom tool, or whatever else.

More Info

For more information about the server-side object model for Workflow Services Manager, consult http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.workflowservices.aspx. To learn more about taking advantage of Workflow Services Manager from the CSOM, the JSOM, and REST, you should read the following protocol reference: http://msdn.microsoft.com/en-us/library/hh660550.aspx.

Using Workflow Services Manager

Let’s investigate how to use this new API while working on the client side. To execute the necessary code excerpts, first create a new console application in Visual Studio 2012 and reference at least the following assemblies:

  • Microsoft.SharePoint.Client.dll

  • Microsoft.SharePoint.Client.Runtime.dll

  • Microsoft.SharePoint.Client.WorkflowServices

To practice working with the Workflow Services Manager API, take a look at how to accomplish such common tasks as retrieving the workflow definitions associated with a target list or library, associating a workflow with a target, terminating a workflow, and publishing a custom workflow through XAML.

For example, A CSOM code excerpt for retrieving the list of workflow definitions associated with a target library enumerates the workflows associated with a specific target library.

Highlighted in bold, the code uses the Subscription service to retrieve the list of workflow subscriptions associated with the library with the title “Documents” in the target SharePoint site. Notice that the WorkflowServicesManager class must be created to provide the current instance of the ClientContext, as well as the target object of type Web. Through the WorkflowServicesManager class instance, you get access to the current Subscription service instance. In fact, the WorkflowServicesManager type provides all the useful entry points for using the whole Workflow Services Manager engine. Table 18-5 lists the main members of the WorkflowServicesManager type.

Table 18-5. The main members of the WorkflowServicesManager type

Member name

Description

AppId

Read-only property to retrieve the ID of the currently associated workflow app

IsConnected

Read-only property to determine if the current Workflow Services Manager instance is connected with a back-end Workflow Manager infrastructure

ScopePath

Read-only property to retrieve the path to the current scope in the workflow host

WorkflowServiceAddress

Read-only property to retrieve the URI of the workflow manager host

GetWorkflowDeploymentService

Method to retrieve an instance of the WorkflowDeploymentService class

GetWorkflowInstanceService

Method to retrieve an instance of the WorkflowInstanceService class

GetWorkflowInteropService

Method to retrieve an instance of the WorkflowInteropService class

GetWorkflowMessagingService

Method, available only in the Server Object Model, to retrieve an instance of the WorkflowMessagingService class

GetWorkflowSubscriptionService

Method to retrieve an instance of the WorkflowSubscriptionService class

Each service type provides a rich set of methods and properties to manage deployment, instances, interoperability, subscriptions, and messaging.

For example in A CSOM code excerpt for retrieving the list of workflow definitions associated with a target library, the code excerpt retrieves an instance of the WorkflowSubscriptionService class, in order to get the currently defined subscriptions for a target library, using the EnumerateSubscriptionsByList method. Each subscription is represented by an instance of the WorkflowSubscription type, which can be used not only for reading a subscription, but also for associating a new subscription to a target. Later in this section, you will learn more about creating workflow associations. In Table 18-6, you can see the main members of the WorkflowSubscription type.

Table 18-6. The main members of the WorkflowSubscription type

Member name

Description

DefinitionId

Property to get or set the ID (GUID) of the associated workflow definition.

Enabled

Property to define whether the current workflow subscription is active or not.

EventSourceId

Property to get or set the logical source instance name of the event. Usually corresponds to the GUID of the target list or site.

EventTypes

Property to get or set the list of events in target for the current subscription. The available values are WorkflowStarting, ItemAdded, and ItemUpdated.

ManualStartBypassesActivationLimit

Property to define whether multiple workflow instances can be started manually on the same list item at the same time. This property can be used for list workflows only.

Name

Property to get or set the descriptive name of the subscription.

PropertyDefinitions

Property to get a reference to a Dictionary<String, String> variable of key/value pairs of properties that represent the configuration of the subscription.

StatusColumnCreated

Property of type Boolean to define whether the workflow association will have to create a custom workflow status column in the target list or library. It is available only on the Server Object Model.

StatusFieldName

Property to get or set the name (String) of the field representing the workflow status.

GetProperty

Method to read a property from the configuration properties of the subscription. It is available only on the Server Object Model.

SetProperty

Method to write a property to the configuration properties of the subscription.

Through an instance of the WorkflowSubscriptionService class and with objects of type WorkflowSubscription, you can do many things. For example, the code excerpt of a workflow association page in A code excerpt taken from a workflow association page based on the JSOM takes advantage of the JSOM implementation of Workflow Services Manager to associate a workflow definition with a target.

To create a new instance of the WorkflowSubscription type, A code excerpt taken from a workflow association page based on the JSOM configures all the main properties (highlighted in bold) described in Table 18-6. The most important part of the code excerpt is the invocation of the publishSubscriptionForList method, which accepts the subscription and the ID of the associated list or library. As you might guess from the name of the method, it is suitable only for publishing subscriptions for lists or libraries. If you want to publish a subscription for a site workflow, use the publishSubscription method instead.

Another interesting use case is the starting of a new workflow instance. First, to create a new instance of a workflow definition, use the GetWorkflowInstanceService method of the WorkflowServicesManager class to reference an object of type WorkflowInstanceService. Next, as you learned in Chapter 17, you can use the StartWorkflow or the StartWorkflowOnListItem methods. The WorkflowInstanceService class provides many other helpful members, as well. Table 18-7 lists the most commonly used methods.

Table 18-7. The main members of the WorkflowInstanceService type

Member name

Description

CancelWorkflow

Sends a cancel message to a specified workflow instance, permitting the instance to execute a cancellation scope.

CountInstances

Retrieves the count of all the instances of a specified subscription.

CountInstancesWithStatus

Retrieves the count of all the instances of a specified subscription that have a specific internal status. The internal status can assume any of the following values: NotStarted, Started, Suspended, Canceling, Canceled, Terminated, Completed, NotSpecified, and Invalid.

EnumerateInstancesForListItem

Retrieves the instances running on a specific list item; allows multiple overloads.

EnumerateInstancesForSite

Retrieves the instances running on a specific site.

GetDebugInfo

Retrieves debug information, in JSON format, about a workflow instance.

GetInstance

Retrieves a workflow instance by ID; allows multiple overloads.

ResumeWorkflow

Resumes a workflow instance that is suspended.

StartWorkflow

Starts a site workflow.

StartWorkflowOnListItem

Starts a list workflow.

SuspendWorkflow

Suspends a workflow instance that is executing.

TerminateWorkflow

Terminates a workflow instance forcefully by deleting it from memory. The instance is not allowed to execute a cancellation scope.

For example, A CSOM code excerpt of a function that forcibly terminates all the workflow instances running on the items of a list contains a code excerpt of a function that forcibly terminates all the workflow instances running on the items of a target library.

The WorkflowDeploymentService class is also interesting. Through this service, you can deploy and manage the workflow definitions. Table 18-8 lists its main methods.

Table 18-8. The main members of the WorkflowDeploymentService type

Member name

Description

DeleteDefinition

Deletes a workflow definition.

DeprecateDefinition

Marks a workflow definition as deprecated. Currently running workflow instances are allowed to complete, but new instances of the workflow definition are prevented from starting. This method is useful for performing workflow versioning.

EnumerateDefinitions

Retrieves workflow definitions from the workflow store.

GetDefinition

Retrieves a specific workflow definition from the workflow store.

GetDesignerActions

Retrieves the list of valid Workflow Manager Client 1.0 actions for the specified server.

PackageDefinition

Packages a workflow definition into a WSP file that will be saved in the Site Assets library of the current site.

PublishDefinition

Publishes a workflow definition to the workflow store.

SaveDefinition

Saves a workflow definition to the workflow store.

ValidateActivity

Validates a workflow activity against workflow definitions stored in the target workflow store.

A CSOM code excerpt of a function that published the XAML of a workflow definition to the workflow store shows a code excerpt of a sample procedure for publishing the XAML of a workflow definition to the workflow store.

A CSOM code excerpt of a function that published the XAML of a workflow definition to the workflow store validates the XAML code, which is provided as an argument of type String to the sample PublishXamlWorkflowToWorkflowStore method, and then saves the workflow definition to the workflow store. After executing that code and providing a valid XAML workflow definition, you will find a new workflow definition available in SharePoint Designer 2013 for adding in the target SharePoint site.

The WorkflowInteropService class simply provides methods to start or cancel a legacy SharePoint 2010 and WF 3.x workflow instance. In particular, the StartWorkflow method accepts all the arguments useful to start a new workflow instance—which are the association name, the correlation ID, the target list ID, and the target item GUID—as well as any additional arguments or parameters for running the workflow. Meanwhile, the CancelWorkflow method accepts the GUID of the workflow instance to cancel. Lastly, the WorkflowMessagingService class, which is available only on the Server Object Model, provides the PublishEvent method, which allows publishing a message to the Service Bus, providing the GUID of the event source, the name of the event, and a collection of key/value pairs for providing a payload to the target subscribers of the event. Typically, the event source GUID should be the ID of the list, or of the site depending on the kind of workflow you are running, and the name of the event is the fully qualified name of the event.

Summary

In this chapter, you learned how to create custom activities, either declaratively or by writing code. You learned how to deploy both declarative and code-based activities, and you experimented with both of them. Then you saw how the new security infrastructure of workflows in SharePoint 2013 works, and how the authorization rules are applied. In particular, you saw how to use app steps, which are available in SharePoint Designer 2013, and the AppOnlySequence activity, which is available in Visual Studio 2012. Lastly, you learned about Workflow Services Manager by walking through some useful code excerpts for taking advantage of this powerful component from client code using the CSOM or the JSOM.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset