Wrangling SharePoint Workflows with Visual Studio : Page 3

SharePoint and Workflow may be the most powerful combination since chocolate and peanut butter, but the trick is harnessing their combined power. That isn't as easy as it first seems, but in this article you'll learn how create a SharePoint workflow in Visual Studio from start to finish.

by Rob Bogue

Mar 15, 2007

Page 3 of 4

WEBINAR:

On-Demand

Full Text Search: The Key to Better Natural Language Queries for NoSQL in Node.js

Creating a Workflow Project in Visual Studio Above, we mentioned that you would need to install a few components in order to develop workflows with SharePoint and Workflow Foundation. Once those pieces are installed, an option to create a SharePoint Sequential workflow will appear as shown in Figure 1. The Grades workflow will perform a few basic steps. It will create a task, wait for the task to change, change the document with some code, and delete the task.

Create a sequential workflow by selecting the SharePoint (for WSS) or SharePoint Server (for MOSS) folder under Visual C#. Give the project a name of Grades, and select a folder to put the project in. Click the OK button.

Once the project has been created, double-click the Workflow1.cs file from the Solution Explorer to show the workflow that was automatically created. Figure 2shows what the workflow looks like as soon as it's created. Visual Studio has automatically created the workflow and added the required onWorkflowActivated activity as the first activity.

From the toolbox drag a CreateTask activity, a OnTaskChanged activity, a Code activity, and a DeleteTask activity in sequence to the design surface as shown in Figure 3.

You may notice that there are little red exclamation points next to each of the four activities that you added to the design surface. That is because they all failed validation. The design interface is warning you that, based on the current settings on the activities, they won't work. Next you're going to fix those errors and complete your workflow.

Completing the Create Task ActivityIn order to get a CreateTask activity working, three things are needed: a correlation token, a task properties object, and a task GUID. The easiest of these to take care of is the correlation token, which can be created with the following process:

Click on the createTask1 activity, then right-click and select Properties.

In the Properties pane, select the CorrelationToken box and type in taskToken and press Enter.

Now click the plus sign to the left of CorrelationToken and in the OwnerActivityName line that appears select Workflow1. Visual Studio has created a correlation token for you. Note that each item that will receive events needs its own correlation token. Thus the task correlation token you created is different than the workflow correlation token that was created automatically when the project was created.

Defining the task properties and the GUID are a bit more challenging. For that you'll need to right-click the activity and select view code. You need to add two lines underneath the lines that define the workflowId and workflowProperties. The lines will define the taskId and taskProperties like this:

Select the taskId property and click the OK button. You've just bound the taskId Property to the taskId that you created.

Perform steps 7 and 8 again on the TaskProperties activity property and taskProperties workflow property.

Next is setting the taskId correctly. To do this code will be added to the MethodInvoking event. Double-click the createTask1 activity so that it creates the default event handler, which is MethodInvoking. Methods that end in 'ing' happen before the main work of the activity so you can use this method to set the taskId. You need to do this because you didn't give it a unique ID originally—just the default for a GUID (all zeros). Add the following line to the createTask1_MethodInvoking method that was created when you double clicked:

taskId = Guid.NewGuid();

In order to set the task title to something meaningful, add the following line immediately following the line added in step 10:

taskProperties.Title = "Task for " + workflowProperties.Item.Name;

Switch back to the design view. You're done with the createTask. The red exclamation point that was on it should be gone now. (Actually, it disappeared when you set the correlation token.)

Completing OnTaskChangedFor the onTaskChanged1 activity you have essentially the same properties to set, however, because they are already created the process is much easier. In this case the correlation token must be set as well as the TaskId property. In addition, taskProperties is bound to AfterProperties so that the taskItemId value will be set.

Select the onTaskChanged1 activity, right-click and select Properties from the context menu.

In the CorrelationToken field click the drop-down list box arrow and select taskToken.

Click on the TaskId property field and then the ellipsis.

Select taskId from the binding dialog and click the OK button.

Select the AfterProperties field, and then click the ellipsis.

Select taskProperties from the binding dialog and click the OK button.

The onTaskChanged activity is done. The red exclamation point should be gone for this activity too.

Completing the Code ActivityThe final activity is the code activity where you're going to copy the fields from the task back to the document.

Double-click the codeActivity1 activity to create a handler for ExecuteCode. In this method you're adding these five lines:

These five lines get the item for which the workflow was started, the task that was created, and then copies two fields from the task into the item. Finally, it updates the fields without changing the modified information for the item.

The workflow is done. It should now build successfully. It's time to move on to deploying the workflow.

Completing the Delete Task ActivityCompleting the Delete Task activity is the same as completing the OnTaskChanged activity. You must set the CorrelationToken and the TaskId properties of the deleteTask1 activity so that the workflow will compile and so that the task will be deleted. You can refer back to Completing OnTaskChanged for the steps to bind these two properties.

Modifying the Feature to Deploy the WorkflowWhen Visual Studio created the project it automatically added three files that will help in the deployment process. They are:

Feature.xml—SharePoint needs this file to define the feature.

Workflow.xml—This element manifest file defines the workflow itself.

Install.bat—This batch file can be used to install the feature.

The following sections walk through each of these files and make the updates necessary to install the feature containing the Grades workflow.

Feature.xmlUpon opening feature.xml, you'll notice that there isn't much there besides a note telling you to use the snippets functionality with Visual Studio to add the nodes necessary in the feature.xml file. To create the feature.xml for the Grades Workflow follow these steps:

Add the feature from the Windows SharePoint Services SDK by right clicking, selecting Insert Snippet, Windows SharePoint Services Workflow, and finally Feature.xml Code. Figure 5shows what you'll see when you add the snippet. Once the snippet is added the green highlighted sections must be changed. Specifically the Id, Title, and Description must be changed. The default value for the <ElementManifest> Location attribute is correct. First up is changing the Id.

Verify that the Create GUID application has the Radio button for 4. Registry Format (ie. {xxxxxxxx-xxxx … xxxx })selected.

Click the Copy button in the Create GUID application.

Switch back to Visual Studio and the Feature.xml file.

Select the text in the quotes behind the Id attribute and paste the GUID in with Ctrl-V.

Strip the leading and closing braces from the GUID that was pasted in.

Enter a descriptive name for the feature and for the description. For the Grades workflow the feature is going to be called "Grades" and the description is "Enable assignment grading."

Because workflow.xml is the correct name of the element manifest that you want to create, you're done with Feature.xml. Save it and you can move on to workflow.xml.

Workflow.xmlWhen workflow.xml is opened, you'll find the situation very similar to the feature.xml. Workflow.xml is a mostly empty file with a few instructions on how to add the content to the file. We'll follow a similar procedure as with the feature.xml. To customize workflow.xml for the Grades workflow follow these steps:

Right-click and select Insert Snippet, Windows SharePoint Services Workflow, and finally Workflow.xml Code. This will result in a workflow.xml that looks like the one shown in Figure 6.

Enter the name and description for the workflow. For the Grades workflow, use "Grades" and "Enable assignment grading" respectively for the name and description. It isn't required that you enter either the same or unique names here versus the values that are used in the feature.xml file.

Use the Create GUID tool to create a new GUID. (See Steps 2-4 of the feature.xml procedure immediately above if you don't remember how.)

Switch back to Visual Studio and the workflow.xml file.

Paste the GUID into the ID attribute's value and delete the extra braces.

The next step is the code-behind class; in this case the project name is 'Grades' so the namespace is 'Grades.' For the CodeBesideClass enter "Grades.Workflow1." Workflow1 is the name of the workflow that was created by the Visual Studio SharePoint Sequential Workflow project.

Next we need to get the correct assembly name; the first part of the CodeBesideAssembly is "ProjectName." This is the name of the DLL for the project. In this case the assembly name is 'Grades,' so replace ProjectName with 'Grades.'

The last part of the CodeBesideAssembly is the PublicKeyToken. For this the assembly must be strong named. This is a requirement for all workflow DLLs since they must be installed into the GAC. In Visual Studio, right-click on the project name (Grades) and select properties. On the Properties page that appears, select the Signing tab, which is the last tab on the left. The result will be similar to the page shown in Figure 7.

From the drop-down box select 'Choose a strong name key file' and select New. A Create Strong Name Key dialog will appear.

Enter a key file name of Grades.

Uncheck the Protect my key file with a password checkbox and click the OK button.

Build the solution to get the public key token now. (Ctrl-Shift-B will build the solution.)

Next open a Visual Studio 2005 command prompt. This can be done by selecting it from the Start menu. The entry is located under Visual Studio 2005->Visual Studio Tools and is named Visual Studio 2005 Command Prompt.

Navigate to the directory where the project DLL is created. In our example I created the solution in C:\Work\Development\grades. The debug DLL is created under bin\debug by default so the command to change to the correct directory is 'CD \work\Development\grades\bin\debug'.

Type the command 'SN –T Grades.DLL.' SN responds with the public key token for the file as shown in Figure 8.

Right-click in the window and select Mark.

Click and drag across the public key token. When you're done let up the mouse and press Enter.

Switch back to Visual Studio and to the workflow.xml tab.

Select the green highlighted publicKeyToken text and then press Ctrl-V to paste the public key token.

One final edit for the CodeBesideAssembly attribute is to change the version number from 1.0.0.0 to 3.0.0.0.

Next set the TaskListContentTypeId. This is the Id shown above in the content type section. In this case the value was the 0x01080100B7336179CFFE43e59B86E241C767010E value from the content type tag, which is defined the content type for the task.

Delete the AssociationUrl, InstantiationUrl, ModificationUrl, and StatusUrl attributes because the Grades project doesn't implement any of these features.

Delete the whole MetaData node and the modification element under it because the Grades workflow doesn't implement a workflow modification either.

If you were just doing the workflow in this file you would be done. However, you're going to simplify things a bit and add your fields and content types to the top of this file. To do this, copy the field and content type nodes above the <Workflow> node you've been modifying. Figure 9 shows what the completed file should look like. Note that the formatting was changed and extraneous comments removed to get everything to fit on the screen.

Figure 9. The content type fragment of the completed workflow.xml is shown.

With workflow.xml done, there's only one more file to finish, the install.bat file.

Install.batThe Install.bat file opens when you double-click it in the Solution Explorer. It's a nice change from the feature.xml and workflow.xml files. The changes you need to make to the install.bat file are basically two global search and replaces. To customize the install.bat file follow these steps:

The first search and replace is for MyFeature and replace it with what you want to name your feature—in this case 'Grades.' To perform the search and replace start by pressing Ctrl-H.

Enter MyFeature in the "Find what" box and Grades in the "Replace with" box. Make sure that the Look in drop-down list is set to "Current Document." Press the Replace All button.

Click OK in the message box indicating 14 replacements were made.

The second search and replace is for http://localhost with the name of your server. In my case the server name is w2k3server so I’m replacing http://localhost with http://w2k3server.

Click the OK button in the message box indicating three replacements were made.

Once you've made all of the replacements select Save All in Visual Studio (File->Save All) and open a command prompt. (The Visual Studio 2005 command prompt used earlier will work fine.) Navigate to the project directory (C:\Work\Development\Grades) and run install by typing 'install' and pressing enter at a command prompt.