Export (0) Print
Expand All
Expand Minimize

Building Custom Workflow Conditions for SharePoint Designer

Windows SharePoint Services 3

Summary:  You can build custom workflow conditions for Microsoft Office SharePoint Designer 2007. Learn how to create a workflow condition assembly, sign the assembly, write the actual condition, and deploy the assembly to your SharePoint site.

Visual How To

Applies to:  2007 Microsoft Office System, Windows SharePoint Services 3.0, Microsoft Office SharePoint Designer 2007

Joel Krist, iSoftStone

January 2008

Overview

A workflow allows a business process to be attached to items in Windows SharePoint Services 3.0. This process can control almost any aspect of an item in Windows SharePoint Services 3.0, including the life cycle of that item. For example, you could create a simple workflow that routes a document to a series of users for approval. A workflow can be as simple or complex as a business process requires. Windows SharePoint Services 3.0 includes pre-built workflow templates, but you can create custom workflow templates in either Microsoft Visual Studio 2005 Designer for Windows Workflow Foundation, or in a declarative rules-based, code-free workflow editor, such as Microsoft Office SharePoint Designer 2007.

Conditions are one of the building blocks of workflows. When designing a workflow, you can create rules that apply conditional logic to SharePoint lists and items. A rule establishes a condition where the workflow performs the associated action only if that condition is true. Office SharePoint Designer 2007 provides several ready-made, reusable conditions that you can incorporate into a workflow. In addition, you can create custom conditions and advanced conditions that accept a wide range of parameters. This Visual How To illustrates how to build custom workflow conditions for Office SharePoint Designer 2007.

Code It

Download the Code Sample

To illustrate how to build custom workflow conditions for Office SharePoint Designer 2007, this section walks through six key steps:

  1. Creating a Class Library project in Microsoft Visual Studio 2005.

  2. Adding references to the required SharePoint assemblies to the Visual Studio project.

  3. Signing the class library assembly with a strong name.

  4. Creating a method that implements a custom workflow condition.

  5. Creating a .Actions file for the custom condition.

  6. Deploying the custom condition to a SharePoint site.

Creating a Class Library Project in Visual Studio 2005

An easy way to create a custom workflow condition assembly is to use the Visual Studio 2005 Class Library template. To create a Class Library project in Visual Studio 2005, do the following:

  1. Start Visual Studio.

  2. On the File menu, point to New, and then click Project. The New Project dialog box appears.

  3. In the Project Types pane, select Visual C# or Visual Basic and then select the Windows category.

  4. In the Templates pane, select Class Library.

  5. Specify WorkflowConditions for the Name of the project.

  6. Specify a location for the project and click OK. Visual Studio generates a Class Library project with a single source file named Class1.cs or Class1.vb, depending on the language that you selected in step 3.

  7. Rename the Class1.cs or Class1.vb source file to CustomConditions.cs or CustomConditions.vb, depending on the language being used, by right-clicking the mouse on the file in the Solution Explorer and clicking Rename

Adding a Reference to the SharePoint Workflow Actions Assembly

The method that implements the custom workflow condition uses several SharePoint classes. References to the required SharePoint assemblies need to be added to the project to allow these classes to be used. If Visual Studio is running on a computer that has Microsoft Office SharePoint Server 2007 installed, do the following:

  1. On the Project menu, click Add Reference. The Add Reference dialog box is displayed.

  2. Click the .NET tab, and then locate and select the Windows SharePoint Services component (Microsoft.SharePoint.dll) and the Windows SharePoint Services Workflow Actions component (Microsoft.SharePoint.WorkflowActions.dll). Select both components at the same time by holding down the CTRL key while clicking the names of the components.

  3. Click OK to add the references.

If Visual Studio is running on a computer that does not have Office SharePoint Server 2007 installed, the SharePoint assemblies are not available. In this case, copy the assemblies from a computer that has Office SharePoint Server 2007 installed to a local project folder on the development computer. The SharePoint assembly files needed to create the custom workflow condition are Microsoft.SharePoint.dll and Microsoft.SharePoint.WorkflowActions.dll. By default these assemblies are located in the following folder on a computer that has Office SharePoint Server 2007 installed:

%Program Files%\Common Files\Microsoft Shared\web server extensions\12\ISAPI

After you make local copies of the SharePoint assemblies, you can add references to them by browsing for the local files. To add references to local copies of the assemblies, do the following:

  1. On the Project menu, click Add Reference. The AddReference dialog box is displayed.

  2. Click the Browse tab, and then navigate to the local folder containing the copies of the SharePoint assemblies.

  3. Select the Microsoft.SharePoint.dll and Microsoft.SharePoint.WorkflowActions.dll files. You can select both files at the same time by holding down the CTRL key while clicking the names of the files.

  4. Click OK to add the references.

Signing the Class Library Assembly with a Strong Name

To allow the custom workflow condition assembly to be installed in the global assembly cache so that it can be used by SharePoint Designer, it must be signed with a strong name. A strong name consists of the assembly's identity—its simple text name, version number, and culture information (if provided)—plus a public key and a digital signature. To assign a strong name to the custom workflow condition assembly in Visual Studio, do the following:

  1. On the Project menu, click WorkflowConditions Properties.

  2. On the project properties page, click the Signing tab.

  3. Select the Sign the assembly check box.

  4. In the Choose a strong name key file list, select <New...>.

  5. In the Create Strong Name Key dialog box, type keypair as the key file name, and clear the Protect my key file with a password check box.

  6. Close the project properties page.

Creating a method that Implements the Custom Workflow Condition

After adding the reference to the required assembly and signing the assembly, the next step is to create the method that provides the implementation of the custom workflow condition. A custom workflow condition is implemented as a static method that evaluates a condition and returns a Boolean value representing the result of the evaluation. The default signature of a custom workflow condition method is:

Static Bool functionName(WorkflowContext context, string listId,

int itemId)

The context, listId, and itemId parameters are required by SharePoint Designer. You can add parameters to the method after the required parameters to allow the condition to have access to additional data. For a description of how custom data values are gathered by SharePoint Designer and then passed to the custom condition method, see the following section that covers creating a .Actions file for the custom condition.

The example custom workflow condition shown here works with the items in a fictional Project Status Report document library. One of the properties of items in the Project Status Report document library is the Last Status Date, which is the date and time the status of the project was last updated. The custom workflow condition accepts a single parameter, an integer representing a number of days. It determines whether the date span between the current date and the Last Status Date property of an item in the document library is greater than the number of days specified by the parameter. If the date span is greater than the value passed with the parameter, the condition returns True; otherwise it returns False.

Add the following Imports or using statements to the top of the CustomConditions.cs or CustomConditions.vb source file, replacing the Imports or using statements that were generated by Visual Studio when the project was created.

Imports System
Imports Microsoft.SharePoint
Imports Microsoft.SharePoint.Utilities
Imports Microsoft.SharePoint.Workflow
Imports Microsoft.SharePoint.WorkflowActions

The Imports and using statements let you use the classes and types defined in the referenced namespaces without having to use fully qualified namespace paths. The next step is to add the code for the method that implements the custom workflow condition. Add the following code to the CustomConditions class:

Public Shared Function StatusNeedsUpdating( _
    ByVal context As WorkflowContext, _
    ByVal listId As String, ByVal itemId As Integer, _
    ByVal days As Integer) As Boolean

    Dim retStatusNeedsUpdating As Boolean = True
    Dim dtNowUTC As DateTime = DateTime.Now.ToUniversalTime()
    Dim dtLastStatusDateUTC As DateTime

    Try
        ' Get the current web site the workflow is running on.
        Dim web As SPWeb = context.Web

        ' Get the Project Status Reports document library.
        Dim ProjectStatusReportDocLibrary As SPList = _
        web.Lists(Helper.GetListGuid(context, listId))

        ' Get the value of the Last Status Date property
        ' of the item in UTC.
        Dim spQuery As SPQuery = New SPQuery()
        spQuery.DatesInUtc = True

        spQuery.Query = "<Where><Eq><FieldRef Name='ID'/>" + _
                    "<Value Type='Integer'>" + itemId.ToString() + _
                    "</Value></Eq></Where>"

        Dim items As SPListItemCollection = _
            ProjectStatusReportDocLibrary.GetItems(spQuery)

        dtLastStatusDateUTC = _
            Convert.ToDateTime(items(0)("Last Status Date"))

        ' See if the Last Status Date of the item is greater than
        ' the current date minus the days value.
        ' If it is, return true; else return false.
        Dim tsDaysSinceLastStatusUpdate As TimeSpan = _
            New TimeSpan(dtNowUTC.Ticks - dtLastStatusDateUTC.Ticks)

        If tsDaysSinceLastStatusUpdate.Days >= days Then
            retStatusNeedsUpdating = True
        Else
            retStatusNeedsUpdating = False
        End If
    Catch ex As Exception
        System.Diagnostics.EventLog.WriteEntry( _
            "StatusNeedsUpdating Custom Workflow Condition", _
            "Message:\n" + ex.Message + "\nStackTrace:\n" + _
            ex.StackTrace)
    End Try

    Return retStatusNeedsUpdating

End Function

Creating a .Actions File for the Custom Condition

The next step in preparing a custom workflow condition to work with SharePoint Designer is to create a .Actions file. .Actions files are XML files that describe custom actions and conditions to SharePoint Designer.

First, use the Strong Name (sn.exe) utility that is included with Visual Studio to determine the public key token of the workflow condition assembly. Build the assembly in Visual Studio and then run sn.exe with the -T option, like this:

sn.exe -T WorkflowConditions.dll

Make a note of the returned public key token for later use.

Next, create a text file named CustomConditions.Actions and add the following XML to it:

<?xml version="1.0" encoding="utf-8"?>
<WorkflowInfo Language="en-us">
    <Conditions And="and" Or="or" Not="not" When="If" Else="Else if">
        <Condition Name="Project Status Needs Updating"
            FunctionName="StatusNeedsUpdating"
            ClassName="WorkflowConditions.CustomConditions"
            Assembly="WorkflowConditions, Version=1.0.0.0,
            Culture=neutral,
            PublicKeyToken=<Public Key token>"
            AppliesTo="all"
            UsesCurrentItem="true">
    
            <RuleDesigner Sentence="Project status has not been updated 
            in the past %1 days">
                <FieldBind Id="1" Field="_1_" Text="7"/>
            </RuleDesigner>
            <Parameters>
                <Parameter Name="_1_" Type="System.Int32, mscorlib"
                Direction="In" />
            </Parameters>
        </Condition>
    </Conditions>
</WorkflowInfo>

Replace the <Public Key Token> placeholder with the public key token for the condition assembly as returned previously by the Strong Name (sn.exe) utility.

The preceding XML markup contains tags and attributes that SharePoint Designer uses to determine how to display the condition as a rules sentence and how to bind a value to the parameters accepted by the condition.

The Conditions tag starts a list of available conditions. It is possible to put multiple conditions in the same actions file by including them inside this tag.

The Condition tag defines basic information about a condition via the following attributes:

  • Name   The name of the condition (what SharePoint Designer 2007 displays in its conditions list).

  • FunctionName   The name of the method that implements the condition.

  • ClassName   The name of the class that contains the condition method.

  • Assembly   The details of the condition assembly.

  • AppliesTo   The types of lists this condition can be used for. Possible values are "list", "doclib", or "all".

  • UsesCurrentItem   The condition uses the current item in the workflow.

The RuleDesigner tag describes a rule sentence for the condition and how to bind values to the parameters of the method that implements the condition. This is the sentence SharePoint Designer 2007 displays for the condition in its rules wizard. The variable parameters in the sentence (%1, %2, and so on) are exposed as customization links. When displayed, they are replaced by the FieldBind tags described below, where %1 is replaced by the FieldBind that has an Id = 1, and so forth.

The FieldBind tag describes each variable parameter. The Field attribute corresponds to the condition parameter as it is described in the Parameter tag in the markup. The Text attribute specifies how the field is initially displayed in the rule sentence.

Finally, the Parameters tag tells the RuleDesigner how to map the fields to the parameters of the method that implements the custom workflow condition. Each Parameter tag describes the name of the parameter as specified by the corresponding FieldBind, the system type of the parameter, and the direction. The order of Parameter tags maps to the order of parameters in the function after the default context, listId, and itemId parameters. In this example, because "days" is the first non-default parameter in the StatusNeedsUpdating function shown previously, it is mapped to the first Parameter tag in the Parameters section. From a coding perspective, the parameter names in the function declaration for the method that implements the custom workflow condition don't need to match anything in the Condition node in the .Actions file.

Deploying the Custom Condition to a SharePoint Site

Deploying the custom workflow condition to a SharePoint server involves three steps:

  1. Copying the .Action file for the condition to the server that is hosting the SharePoint site.

    Copy the CustomConditions.Action file created previously to the SharePoint Folder\TEMPLATE\LCID\Workflow folder on the server running the SharePoint site. By default, for a SharePoint installation using the US-English locale this folder is:

    %Program Files%\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\1033\Workflow

  2. Installing the condition assembly to the global assembly cache on the server.

    Install the WorkflowConditions.dll assembly into the global assembly cache (GAC) on the server running the SharePoint site. You can do This either by dragging and dropping the assembly into the GAC or by using the gacgutil.exe tool that is supplied with Visual Studio.

  3. Setting the WorkflowConditions.CustomConditions class as an authorized type on the SharePoint site.

    Edit the web.config file for the SharePoint site and add the following entry to the <authorizedTypes> group under the <System.Workflow.ComponentModel.WorkflowCompiler> section:

    <authorizedType Assembly="WorkflowConditions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=<Public Key Token>"

    Namespace="WorkflowConditions" TypeName="*" Authorized="True" />

    Be sure to replace the <Public Key Token> placeholder with the public key token for the condition assembly as returned previously by the Strong Name (sn.exe) tool. Reset Internet Information Server on the SharePoint site. If SharePoint Designer is currently running against the SharePoint site, quit and restart it so that the CustomConditions.Action file is picked up.

  4. At this point, the custom condition is ready to be used with SharePoint Designer to design workflows against the Project Status Report document library.

Read It

Because workflow authors in Office SharePoint Designer 2007 cannot create custom activities or conditions for use in their workflows, they are limited to the activities and conditions that appear on the "safe list" in Office SharePoint Designer 2007. Developers can create custom activities and conditions, and make them available on the safe list.

This article illustrated how to build custom workflow conditions for Office SharePoint Designer 2007. The key steps include:

  1. Creating a Class Library project in Microsoft Visual Studio 2005.

  2. Adding references to the required SharePoint assemblies to the Visual Studio project.

  3. Signing the class library assembly with a strong name.

  4. Creating a method that implements a custom workflow condition.

  5. Creating a .Actions file for the custom condition.

  6. Deploying the custom condition to a SharePoint site.

See It

Building Custom Workflow Conditions

Watch the Video

Length: 8:25 | Size: 9.8 MB | Type: WMV

Explore It
Show:
© 2014 Microsoft