Automating business processes in SharePoint: Visual Studio Workflows (Part 3 of 3)

Final part of a three-part series on automating business processes in SharePoint. We will explore three different methods of doing Business Process Management, or BPM, using SharePoint and available tools.

The scenario is a simple helpdesk application in which users should be able to send emails and have an issue be raised and sent to an appropriate agent for resolution. We will use an email enabled list to receive emails and then use automated processes to route that email into the issue tracking system. The system will make sure that the issue is tracked and escalated as appropriate.

Here are the links to the entire series:

Automating business processes in SharePoint: SharePoint Designer Workflows (Part 1 of 3)
Automating business processes in SharePoint: SharePoint Event Receivers (Part 2 of 3)
Automating business processes in SharePoint: Visual Studio Workflows (Part 3 of 3)

Oh, and make sure you subscribe to the feed to make sure you get updates and new articles as they become available.

A few things worth noticing. This series will not result in a production ready system. It is meant to show different aspects of process automation, not to create the best method of doing a specific task such as creating a help desk application. The series is meant to show the entire process of creating the application.

First of all, lets draw a simple diagram to explain how the system is supposed to work.

IssueFlow

So, in a few short sentences:

1. Receive a new email and start a new support issue (handled by SharePoint designer)

2. Escalate issue and find an available operative to handle the case (handled by an event receiver)

3. Update the issue, and if it is resolved, send a message to the customer. If not, go to step 2. (handled by a custom workflow in Visual Studio)

If you are going to do this in a production environment, don’t. Basically what we are doing here is demonstrating different aspects of business process management, not doing a best practice thing. In a production system you would likely want to do all of this in a state machine workflow, or at least not do three different approaches to automation in one single system.

On to lesson two

Not that this article is long. Very long. If I was writing a book it would be a full chapter. Lots of screenshots which may take time to load. You patience will be rewarded.

A recap from lesson one and two

In the last article we looked at using SharePoint Designer Workflows to route and categorize incoming email to our help desk system. We did this by creating different email enabled lists that had workflows attached. These workflows created new items in our issue list and categorized them by setting a Choice field to the correct value, depending on which list received the email, support or invoice. We should at this point have a simple email receiver and routing system ready for some additional development.

In the second article we expanded our solution by assigning new issues to employees based on what type of issue each employee handles. We did this using an event handler that triggers on the ItemAdded and ItemUpdated events. First we expanded our Users and groups list to include an Issue Type field to categorize the employees based on what issues they handle. Then we used a CAML query to find an eligible employee and assigned that employee to a new field in the Issues list called ‘Assigned to’. Or whatever you chose to call it.

This trip down memory lane is at an end, on with new stuff.

Workflow fundamentals

Before we can begin developing our workflow we need to do some dry stuff, also known as theory. The most principal thing is to learn about the two different ‘styles’ of workflow, sequential and state-machine workflows. Actually, that may not be the most principal thing, but I will assume that you know that a workflow is a set of activities that are connected in some fashion and are executed based on either sequence or changes in state. The activities can be virtually anything, including the built-in activities and custom built activities created by you or a third party. But you already knew that, you are a bright person.

Now, since you know all this stuff already I will also skip mentioning that there are multiple workflow engines, but that Microsoft has released their very own workflow engine as part of the .Net framework from version 3.0. Nor will I mention that there is a very rich editing experience that ships with Microsoft’s workflow engine, the one you see if you use Visual studio, that you can use to create your very own workflow designer.

If you, by chance, do not know all this stuff, let me know and I will have a topic for another show. For now, let’s get back to sequential and state-machine workflows.

Sequential workflows

Sequential workflows are a set of activities that are performed in sequence. Go figure, who would have thought, dress me up in whipped cream and call me a cupcake.

Conventional wisdom says that sequential workflows are best suited for machine-to-machine workflows, i.e. where computers are the principal participants of the workflow. That does not rule out human participants, but humans are unpredictable and sequential workflows wants to be predictable.

Sequential workflows are similar in concept to non-interfacing software programs. I have included below a simple workflow chart that can illustrate how a sequential workflow can be designed. The illustration shows a simple receive-verify-store function with some branching to handle errors. Click to enlarge it:

SequentialWF

You might think of sequential workflows like simple old console applications. You start the program, the program does something in sequence, and then ends.

State-Machine workflows

To contrast the console application example, State-Machine workflows are a lot more like event driven programs, such as a winforms application. Think of word, or your browser. You start the program and then manipulates what the program does into several different states. Not until you decide (or something goes terribly wrong) does the program end.

A state-machine workflow operates in very much the same manner and is thus the preferred method of operating when humans are the primary participants. Just like with a winforms application a state-machine workflow can have multiple states and only certain events, such as clicking a button in an application, setting a
certain value on an item, or uploading a document to a site will cause that state to change.

To illustrate a state-machine workflow we can look at the flowchart for this series. I have updated the chart a bit to illustrate where the events would occur:

state-machineWF

The events are the red text staring with ‘OnXXX’. So, when an email is received (OnEmailReceived), go into ‘Receive email’ state. That state can only, at least in our simple example, trigger the event ‘IssueReceived’ and when that happens (OnIssueReceived) go into the escalate state. Then, when the item is updated (OnItemUpdated) go into the Issue Update state.

State-machine workflows are more unpredictable than sequential workflows. It does have a beginning, it does have an end, but how it gets from beginning to end is not defined. There are multiple paths, loops, and events that can occur to alter the direction, even if it will ultimately result in reaching the goal.

State-machine workflows can take a bit of getting used to, just like migrating from console applications to event driven programming. However, once you do you will likely find out…

Why state-machine workflows are better in SharePoint

Why? Well, SharePoint is about collaboration, right? We want people to be the focus. Also, it fits better into the disconnected and state-less web thought…

What kind of workflows do you want to have in SharePoint? I guess you would want to work on an item, perhaps having a document written, sent to review, approved or rejected and based on that either re-write or publish the document. The actual publishing process, the actual ‘send for review’ process, the actual ‘approve or reject’ may be seen as sequential work, but the overall process is still at set of states and migrations between those states.

And that brings us to the final part of the theory bit. Hang on a little while longer at it will be time to do some fun stuff.

Combining sequential and state-machine workflows

Sequential workflows are good at performing simple and more or less atomic operations. Think of an online ordering system. When a new customer enters the store, they get a new shopping cart. Then they find their product and add it to the shopping cart. Now, adding that item to the cart is no simple matter. You must check that the item is actually available, you might need to reserve it in stock, you may want to freeze the price, you want to update the database containing the shopping cart, and you may want to update the customers profile so you can recommend similar products that the customer might like.

The adding of an item does not require user input, but it is a workflow. Thus, using a sequential workflow for this operation may be appropriate. Same applies for other phases of the shopping. After an item has been added, the user may chose to check out, which will put the cart in a ‘checking out’ state where tasks such as gathering shipping and billing info, getting the payment information, verifying credit card information, etc.

All these may be considered atomic processes, but are part of a larger process, that of shopping at the site. When a user adds an item, the workflow is not done, it simply transitions into a new state depending on what the user chooses to do next. If they go to check out you want to transition into a ‘get shipping and billing info’ state. If the user then chooses to go back to continue shopping you must handle that state. However, each of those state may comprise a sequential workflow to perform a series of actions.

See how this all adds up? You can use sequential workflows as part of a state-machine workflow, thus combining the best of both worlds.

On with the show, enough theory, let’s get down to business, shall we?

Solution overview

What we want to do in this article is to develop a workflow using Visual Studio. Our task to be solved is to track the issue status and when an issue reaches the ‘Solved’ state we want to send a message to the sender of the original email, presumably the customer.

Note that the tasks we will perform during the workflow are simple and hardly warrants a custom workflow at all. As for most of my articles, this is for illustrative purposes. We want to get started developing workflows, not find the cure for cancer.

Also, the word ‘State’ in the first paragraph should have tipped you off that this will indeed be a state-machine workflow.

First, we need to do some setup…

Requirements

For this solution we are going to use the Visual Studio Extensions for Windows SharePoint Services, or VSeWSS for short. The VSeWSS is a set of extensions from Microsoft that you can use to develop SharePoint solutions.

There are several reasons why I want to go with VSeWSS rather than WSPBuilder for this project. First of all, and the deal-breaker for me, is that the built-in Workflow templates in WSPBuilder are tied to MOSS rather than relying on WSS alone. Bummer. Granted, you can actually rewrite the generated feature files of the WSP solution, but we wont do that now.

The second reason for not using WSPBuilder is variety. I do think that WSPBuilder is far superior in most aspects to VSeWSS but not all. I will likely come back to the differences in a later article, but my most important reason is that I like the deployment options of VSeWSS better for Workflow development.

So, you need, at least if you are to follow every step of this article, to download and install Visual Studio Extensions for SharePoint.

Second you need the Visual Studio 2005 extensions for .NET Framework 3.0. These are the extensions that allow you to design workflows. Not to run them, the .Net 3.0 framework handles that, but to design them visually in Visual Studio. Get Visual Studio 2005 extensions for .NET Framework 3.0 here.

And, of course, the usual stuff. SharePoint. Visual Studio 2005. A computer. A brain. etc.

Oh, and note, I will be using Visual Studio 2005. Using Visual Studio 2008 is a bit of a different experience. But that’s another show. Perhaps next week.

Setup

First we want to have some way of tracking the state of the issue, so it makes sense to create a new field to hold that state. Make a new column, either a site or list column, for instance named ‘State’, type single line of text. We will just use this to update the progress of our workflow.

Second, we want some simple method of declaring the issue resolved. Simplest approach is to add a ‘Yes/no’ column. I called mine ‘Completed’. Go ahead and make one for your issues list.

Third I want to add a Response field that will be sent back to the customer when the issue is completed. Add a ‘Resolved’ column, multi-line text, to the issues list.

At this point, my Issues list looks like this:

Setup

Now we are ready to begin developing our Workflow.

Solution walkthrough

Step 1: Create and con
figure the Visual Studio solution

First, after installing the extensions mentioned above, create a new Visual Studio solution. You want to create a State Machine Workflow Library that should be available under the SharePoint project types. Give it a decent name:

step-1a

If you look at my screenshot you will notice both a State Machine Workflow Library and a SharePoint Server State Machine Workflow Library. Although it may be obvious I would just like to mention that one is for WSS (the one we will be using) and the other is for MOSS.

Ok, once the solution is created there are still several steps before we are ready to start working. Most of these tasks are done automatically by WSPBuilder, but you still should learn how to set this up manually. Or at least semi-manually.

Specifically we need to sign our assembly, update the Install.bat, and fill the workflow.xml and feature.xml with appropriate markup. But first of all, rename the default Workflow1.cs to something more intuitive. I call mine TrackIssues.cs.

Next, sign your assembly. Check out Basic setup of SharePoint Visual Studio project (opens in a new window) for instructions.

We need to update the Install.bat as well. Open the file from your solution explorer and follow the instructions there. You can ignore b) and c) since your files already have the correct names and are present. You need to search and replace MyFeature with a name of your choosing (I used ‘HelpDeskIssueTracking’) and also, if you want to deploy to anything other than http://localhost you need to replace that as well. Just make sure that you choose a site collection, not a site.

workflow.xml

Now we need to fill our feature.xml and workflow.xml with information. If you open these files you will find instructions on using snippets to add most of the code automatically, but before you do that, save yourself some time and start up .Net Reflector if you have it installed. Build your project and open the resulting .dll-file (it will be in the project directory, under bin\debug) in Reflector. Copy the PublicKeyToken to your clipboard, you will need it shortly.

step-1b

Now, open your workflow.xml file. Follow the instructions to insert the snippet. The snippet ‘fill-in-the-blanks’ mode should appear. Fill in the blanks.

Name and description should be intuitive, just add what your find descriptive for both. Skip the Guid for now if you have the public key token on the clipboard. For the CodeBesideClass, enter the name of your project and your class name. The former is likely the same as you called your solution and the latter is whatever you renamed the workflow1.cs file, minus the .cs. For me this is HelpDeskIssueTracking.TrackIssues.

In the next field paste in your public key token from .Net reflector. Then, generate a new guid (Tools->Create GUID from the menu), and insert in the ID attribute. You should remove the brackets from the generated guid.

You can also safely delete the attributes TaskListContentTypeId, AssociationUrl, InstantiationUrl, and ModificationUrl, but leave StatusUrl in place. The three Urls are used for customizing the workflow during different phases of the workflow life cycle, bith the first being used when you attach a workflow to a list, the second when you start a new instance of a workflow on an item, and the third when you modify a running workflow. We wont be doing neither of these so just delete them. You can also delete theName of Modificationline for the same reasons.

At this point, my workflow.xml looks like this:

step-1c

feature.xml

Luckily, feature.xml is far simpler. Just grab yourself a new Guid (not the same as for workflow.xml, mind you), open your feature.xml file and follow the instructions for inserting the feature.xml code. Once you do you should get the familiar snippets fill-in-the-blanks mode. Paste in your Guid, and write a nice title and description for your feature. Leave the workflow.xml attribute in place. Should look something like this:

Note that your feature cannot have a scope of web. If you create your features using WSPBuilder you will by default get a web-scoped feature which will result in an error.

Adding build events

Finally, to make development a bit easier on us we can automate the update of the assembly on each build. To do so, open the project properties and add the following lines to your post build activities:

“C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil.exe” /i “$(TargetPath)” /f
iisreset

These lines will reinstall our dll on every build as well as do an IISReset. We need to do an IISreset or at least recycle the app pools to ensure that our workflow is updated.

Step 2: Installing the feature

Remember that install.bat we created? It will handle the feature install and activation for us. Start a command prompt and change directory in the direction of your project directory, likely something along the lines of C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\Projects\HelpDeskIssueTracking\HelpDeskIssueTracking.

There, run the install.bat file and sit back for a few minutes. What will happen is that the workflow.xml and elements.xml files will be copied to the [12]\Template\Features\[YourFeature]. [12] means the 12-hive, by the way, usually at C:\Program Files\Common Files\Microsoft Shared\web server extensions\12, and [YourFeature] is the name you set for your feature name when you modified the install.bat file during step 1.

After the copying the script will install the dll assembly file to the global assembly cache. Actually, it will first uninstall the dll if it is already installed, but the end result is the same, your dll is installed.

Then the script will install and activate your feature on the site you specified or to http://localhost if you did not do anything during d) of the install.bat modification. Finally an IIS reset is performed.

You can check the successful installation and activation by doing to the site collection features of your root site. You should see something like this:

step-2

On with the show.

Step 3: Set up states

Open up your workflow cs file, mine is called TrackIssues.cs. The state machine
workflow designer should appear with a single state in place for you. this state, named Workflow1InitialState, is put there automatically by the project. You want to keep that state, but you can add more, and as many as you would like.

The Workflow1InitialState is the starting or initial state that every workflow instantiation will use as a starting point. All workflows need an initial state. For most SharePoint workflows you will want to leave this state as the initial state, but in other workflow scenarios you can change the starting state by right-clicking on any state and select

We want to add three additional states. To add a new state, right-click on an empty spot on the canvas and select Add state. The state will be called something like stateActivity1, but you can rename it in the Properties pane. Add a total of three states and name them as follows:

- stateIssueInProgress

- stateFinalizing

- stateCompleted

Finally, on the stateCompleted state, right-click and select ‘Set as Completed State’.

Your canvas should look something like this:

Step-3

Note that when you set the stateCompleted as completed state the state design changes. You cannot add activities to a completed state so it turns empty and changes the top-left icon.

Step-3b

Step 4: Set up initial state

Your canvas shows the broad overview of the workflow, but to see what actually happens in detail you need to double click any activity in a state. Do so now with the eventDrivenActivity1 of the initial state.

What you will see is the state designer that you can use to design the different activities of your state. Since the initial state is created for us we start there, but we will be creating our own activities in later steps.

You will notice an exclamation point over the onWorkflowActivated1 activity. These exclamation points show us where there are errors and when clicking an error you are often taken to the property that needs to be corrected. Concerning our error now, for some reason, Microsoft has opted to not rename every reference to the class name when you change the name, so our initial state has some errors, ‘Cannot resolve activity Workflow1′ and ‘The correlation token for Activity onworkflowActivated1 has an owner activity name whish is not its parent’.

Don’t worry, fixing the errors is real easy. Just open the properties or click on of the errors in the exclamation point pop-up and rename the OwnerActivityName under CorrelationToken and Name under WorkflowProperties to match your new class name:

step-4a

Once you do the exclamation point will disappear and we are ready to make this activity do something useful.

The only thing we actually want the initial activity to do is start our issue workflow and then change the state of our workflow to the stateInProgress state. To do this you have two options. You can drag-and-drop a SetState activity from the Toolbox into the eventDrivenActivity1 designer. Note that there are two SetState activities, one for SharePoint and one for Windows Workflow. You must use the one under Windows Workflow.

When you drag the SetState activity to the designer you will get the red exclamation point because you have not set a TargetStateName. Go to the properties and select the stateInProgress to set the correct target state.

step-4b

You can also go back to the top workflow overview by clicking the TrackIssues icon above the activity designer, click the eventDrivenActivity1, and drag a path from either the left or right middle anchor points of the activity to the title bar of the stateInProgress state. In this case the TargetStateName is set for you so no need to set it manually.

In either case we are now finished with our initial state. Click the TrackIssues to get back to the workflow overview. You should se an arrow going from Workflow1InitialState to the stateInProgress. Click on the screenshot below for a look.

step-4c

Step 5: Set up stateInProgress state

It is time to create a state from the start. To do so we simply drag-and-drop activities from the toolbox to our state, in this case stateInProgress. The state controls give us a few hints as to what activities we can actually drag-and-drop directly onto a state. Only activities that implement StateActivity, EventDrivenActivity, StateInitializationActivity, or StateFinalizationActivity are allows. What does this mean?

Each of these are actually not activities per se. They do not do anything on their own. They are containers for other activities. Remember that thing about combining state-machine workflows with sequential workflows? The container activities are actually designed contain their very own workflows that will be executed during that state. Remember when we double-clicked the eventDrivenActivity1 in the initial state? What we opened is actually a sequential workflow designer.

Let’s look at the different types a bit.

StateActivities are just that, states. You can have sub states within a state. This is incredibly powerful as you can basically create new state machine workflows inside another state. If you have a state called ‘Approval state’ that requires a range of states for the actual approval process you can design your entire approval workflow as a state machine workflow inside the Approval state, and only when that entire sub-workflow is finished should you move on. The mind boggles…

EventDrivenActivities fire when some event happens, such as changes to the item from which the workflow is launched, a task is updated, or the workflow is modified. You can generally assume that any activity having a name beginning with On is an eventdriven activity. You can have multiple StateActivities and EventDriven activities in one state.

The StateInitialization and StateFinalization can only appear once for each state and is fired when the state begins or ends, respectively.

StateInitialization

Now, we want to make sure that once we enter the stateInProgress state we update our item’s state field. The natural place for this is in the StateInitialization so drag a StateInitialization activity from the toolsbox into the stateInProgress state. You will find it in the Windows Workflow c
ategory. Next, change the name of the activity to something descriptive, like stateInitializationInProgress.

Double-click the stateInitializationInProgress activity to open the designer again. We want to set a field in an item and a good way to do so is with a code activity. Go ahead and drag a Code activity from the toolbox to the designer where it says ‘Drop Activities Here’. Also, give it a nice name, such as ‘codeActivitySetInProgress’

Notice the exclamation point again? We haven’t written any code yet, so no wonder it has problems validating. To fix this and set the code reference automatically, just double-click the Code activity. Suddenly you are faced with an automatically created code block that is references from your code activity.

Cool, eh?

Add the following piece of code to set the State field to a descriptive value:

private void codeActivitySetInProgress_ExecuteCode(object sender, EventArgs e)
{
    this.workflowProperties.Item["State"] = “In Progress”;
    this.workflowProperties.Item.Update();
}

So much for our initialization activity. We need, however, a way to get from our current state to the next state.

OnWorkflowItemChanged

Our requirements are that we want to enter the finalization state when we have clicked the Completed checkbox on our item. So it makes sense to detect changes to our item, and if the Completed field is set to true, ie it is clicked, we transition to the next state.

To accomplish this we want to add an OnWorkflowItemChanged event driven activity. This activity will be fired when the item that launches the workflow is changed. First, drag an EventDriven activity from the Windows Workflow category of the toolbox. By convention you want to name your activity On-something, such as OnItemChanged. Double-click your new EventDriven activity to open the designer.

Drag an OnWorkflowItemChanged activity from the SharePoint – workflow toolbox category onto the OnItemChanged state.

Step-5b

When you drag the OnWorkflowItemChanged onto the designer you will get a familiar exclamation point. Now, the reason for this is a bit more complex, but we will just solve it now and explain the details another time. The cause is a missing correlation token property. To solve it, start by not being incredibly disappointed that I will not explain correlation tokens at this point and the set the CorrelationToken property of the activity to workflowToken.

Next we want to add the actual activity that will happen when the workflow item is updated. We can use an IfElse activity to detect if the right value has been set, so drag the IfElse activity from the Windows Workflow category of your toolbox into the designer, below the onWorkflowItemChanged1 activity. You will see a green plus-sign on the right spot and your activity will snap in place when you hit that spot. Rename the activity to something descriptive, such as ‘ifElseCheckCompleted’.

Notice that you have two branches in the ifElse activity. The left, named ifElseBranchActivity1 initially, has a red exclamation point. That is because we have not set a condition for the branch activity to execute. Go ahead and do so now, by going to the properties of the branch activity or just click the error in the exclamation point.

The choices you have in the Condition property are Code condition which allows us to perform a piece of code returning either True or False, or a declarative rule condition which is basically simpler expressions used to return true or false. For this exercise, use a declarative rule. Notive that when you select declarative rule, the Condition property gets a small plus-sign in front of it. On expanding you see yet another red exclamation point before the ConditionName property. Click inside the textbox and then on the three-dotted button to open the Condition designer.

The Condition designer dialog allows you to create new conditions. Click on the New button to create a new rule condition, and enter

(bool)this.workflowProperties.Item["Completed"]

and then click Ok.

This rule just casts the Completed field of the workflow item to a boolean and returns that value. Feel free to rename the condition to something descriptive.

Step-5c

Click Ok to close the Condition designer dialog and return to the activity designer. Notice the red exclamation point is gone.

We have now ensured that the left branch of our IeElse activity is executed if the Completed checkbox is checked. Final task is to add a SetState activity to that branch to advance our workflow to the next state, the stateFinalizing state. Do so now, go back to step 4 if you need a refresher on how to add an SetState activity, and feel free to test the other method of setting the next state if you didn’t try both in step 4.

You might want to make the activity a bit cleaner. Since we do not need the right-hand branch we can just delete it. You might also want to rename the remaining, former left-hand branch to something descriptive, such as ‘ifIssueCompleted’

Your activity should look something like this:

Step-5d

Phew, done with the InProgress state. But the show must go on… Only a few more tasks now.

Step 6: Finalization state

Go back to the top level of the workflow and notice the new arrow leading frmo you stateInProgress to your stateFinalizing.

We want to finish up our workflow by setting the item field State to ‘Resolved’ and send an email to the customer. These are actually quite simple steps.

StateInitialization

First, add a StateInitialization activity to the stateFinalizing activity, just like we did in step 5 with the stateInProgress state. Then, add a code activity to that StateInitialization activity and set it to execute the following code, again more or less as in step 5:

private void codeActivitySetResolved_ExecuteCode(object sender, EventArgs e)
{
    this.workflowProperties.Item["State"] = “Resolved”;
    this.workflowProperties.Item.Update();
}

Next, while still inside the StateInitialization we want to set our next state to the stateCompleted state. Again, add a SetState activity, this time to the stateCompleted final state.

Nothing more to do in StateInitalization, just go back to the top.

StateFinalization

“But wait!” I hear you say. “Shouldn’t we send an email to the customer?”.

Ah, yes, I haven’t forgotten. I just thought we should look at the StateFinalization activity as well.

Drag a new StateFinalization activity from the Windows Workflow category of the toolbox into the stateFinalizing state and double-click it to open the activity designer. We want to
send an email and lo’ and behold, SharePoint has provided one for us, right in the SharePoint – Workflow category. Drag it onto the ‘Drag Activities Here’ spot.

Again we get the exclamation point and again it is because of a lacking CorrelationToken. Just set it to workflowToken and send me an email if you cant stand not knowing what a CorrelationToken actually is. I might explain in a later article. Perhaps.

Second thing we need to do with the sendEmail activity is to set a ton of other properties. Actually, we only need a few, but you may want to set more. Do this now for the To property of the sendEmail activity. To set these properties we will use Property binding. Nothing fancy, really, and you have probably experienced it before, but basically you just double-click on the little yellow symbol next to a property and in our case, go to the Bind to a new member tab. Write a descriptive name and chose either Field or Property. I prefer Property but you may not.

Step-6a

Do the same to Subject and Body, and if you like other fields as well, perhaps you would like to send a Cc to someone or set special header fields. Your end result should look something like this:

Step-6b

Now, with all these properties bound we need to actually set them. Let’s do simple again. Turns out, if you double-click the sendEmail activity it creates a MethodInvoking function for you. This method will be run before the actual sending of the email so it is a perfect time to set our properties.

Your code should resemble this, depending on what you called your properties:

private void sendEmailToCustomer_MethodInvoking(object sender, EventArgs e)
{
    // Set properties
    this.sendEmailToCustomer_CustomerEmail = workflowProperties.Item["Sender"].ToString();
    this.sendEmailToCustomer_EmailBody = workflowProperties.Item["Response"].ToString();

    // Add Re: if not present
    string subjectLine = workflowProperties.Item["Title"].ToString();
    if (!subjectLine.StartsWith(“Re: “))
    {
        subjectLine = “Re: ” + subjectLine;
    }
    this.sendEmailToCustomer_EmailSubject = subjectLine;

}

Note that I did some fancy subject line editing. The wonders that technology can accomplish…

Ok, I think we are actually done. Wohoo. Build and resolve any errors you have made and let’s see if we can get this working on the site.

Step 7: Attach workflow to Issues list

Start up your SharePoint site in a browser and navigate to the Issues list. Go to list settings and then to the Workflow settings. You will get the Add a workflow page if you have no other workflows attached already.

Select your new workflow and give it a name. Also, make sure you either set the option to start the workflow manually or to start the workflow automatically when an item is created. You can set both if you like, at least for debugging purposes.

DO NOT set the workflow to start when an item is changed, if you do your workflow will not work because we change the item inside our workflow and that would start a new workflow again in an endless loop.

Click Ok to attach the workflow to you Issues list.

Next, make sure there is an item in your issues list from which you can launch the workflow. If you have followed the three articles you should have no problem sending an email to you receiver list and get an Issue item, but you can, of course, manually create one if you like.

Now, open the open and click the Workflows link. You should have a link to start your new workflow, something along the lines of this:

Step-7

Click the link to start the workflow. If you have gotten everything down right you should see that the State has been set to In Progress. Notice also that your list now has a new column with the name of your workflow and the status of that workflow. You can click the link to see more details on the status. The page that opens when you click that link is actually a property we set in our workflow.xml, called StatusUrl=”_layouts/WrkStat.aspx”.

Go ahead, make some changes to your item, but do not click the Completed checkbox. You can even change the State field to something, for instance ‘I am handling this one’ or ‘Working on it’ to let any colleagues know that you are working on the issue.

Finally, edit the item again and check the Completed checkbox. You will, again if you have everything down right, see that your state changes to ‘Resolved’ and your workflow has a status of Completed. And, if you have your email set up right, the customer, or the sender, should within a few minutes have received an email with the contents of the Response field of your item.

Don’t believe me? Here’s a video that shows the entire process after an email has been received. I have set all workflows to start automatically. In case this video doesn’t work for you, you can view it from the Googlepages at http://furuknap.googlepages.com/WorkflowDemo.swf. It’s about 3 megs and runs for 1 minute.

 

Conclusion, further reading and final thoughts

It’s time to wrap up. This has been a long run but we have covered a lot of ground, looking at three different methods of automating business processes with SharePoint, SharePoint Designer, Event Receivers and today Visual Studio Workflows. Hopefully you have gotten a glimpse of what SharePoint and Workflows can do to make your business more effective.

Most of the things at which we have looked are simple demonstrations but should get you imagination and perhaps inspiration running. If you are looking to investigate the possibilities, experiment and ask questions if you get stuck. Remember that especially Workflow is a massive topic and can be the subject of several books. Actually, it already is. In preparing for this article series I have read plenty of books, but I do recommend the book Workflow in the 2007 Microsoft Office Systemabove any other book I have read.

Now, with that I would like to thank all who have read this stuff. If you like it, drop me a comment or send me an email at furuknapgmail.com.

Here are the links to the entire series:

Automating business processes in SharePoint: SharePoint Designer Workflows (Part 1 of 3)
Automating business processes in SharePoint: SharePoint Event Receivers (Part 2 of 3)
Automating business processes in SharePoint: Visual Studio Workflows (Part 3 of 3)

Oh, and make sure you subscribe to the feed to make sure you get updates and new articles as they become available.

Until next time…

Found this article valuable? Want to show your appreciation? Here are some options:

a) Click on the banners anywhere on the site to visit my blog's sponsors. They are all hand-picked and are selected based on providing great products and services to the SharePoint community.

b) Donate Bitcoins! I love Bitcoins, and you can donate if you'd like by clicking the button below.
Donate Bitcoins

c) Spread the word! Below, you should find links to sharing this article on your favorite social media sites. I'm an attention junkie, so sharing is caring in my book!

Pin It

Tags: , , , ,

Post Author

This post was written by who has written 415 posts on Furuknap's SharePoint Corner.

I do SharePoint. When I'm not doing SharePoint, I sleep, and then I dream about SharePoint. Oh, and I dabble a bit in cryptocurrencies (Bitcoin, Litecoin, etc)

9 Responses to “Automating business processes in SharePoint: Visual Studio Workflows (Part 3 of 3)”

  1. Andreas August 27, 2008 at 8:42 am #

    Bjoern,

    thanks so much for the last series. I have been watching your blog for a couple of weeks now and what makes it so special is the short, reliable, and very good structured content that is better than what some people publish in a book.
    I have already learned very much from you and wanted to thank you this way.

    Andreas

  2. Bjørn Furuknap August 27, 2008 at 11:24 am #

    I am glad you liked it, but however you came up with the description ‘short’ is beyond me :-)

    Thanks anyway for your encouraging comments.

  3. Andreas August 27, 2008 at 2:53 pm #

    Boern,

    Maybe I lack the correct english expressions. -You make great content and it is of an outstanding didactical quality – Maybe I had to read a book otherwise :-) .

    - A.

  4. Bjørn Furuknap August 28, 2008 at 12:59 pm #

    Hello, Andreas

    My bad, I just didn’t think that anyone would consider at least the last article short. It was way longer than I intended, but I felt I had to explain at least the basics of what we were doing.

    Thanks again for your comments :-)

    .b

  5. Screwed Pooch September 21, 2008 at 12:14 am #

    Thanks for the writeup but I can’t follow it. You are missing some key screen shots or something going from state to state. Can you add a final photo of the workflow? Or just the code behind
    ?

  6. Bjørn Furuknap September 22, 2008 at 10:35 am #

    Hello pooch,

    Thanks for your comments. I am unsure of what you think is missing, but it is a lot better that you specify with what you are having problems so I can target that specifically. Several people have completed the tasks without having problems, so it may be that you are overlooking something.

    If you are uncertain about transitioning from state to state you need to use the SetState activity. Search through the text of the article for the section covering the SetState activity. Note that there are two different versions, and only one of them will work as expected.

    .b

  7. Ashish Kanoongo December 23, 2008 at 7:53 pm #

    Hello

    In my form library, I am have enabled – email enabling list, where user email infopath form and it automatically adding in to form library. It is working very nicely. Now I want to extend this feature for some users, where user will mail an XML file in different format which is not same as form library have. I completed this also. Now I want to create an event handler where it will check the email attachment and transform XML into infomath library and thne uploaded revised xml on portal.

    Can you please help how do I check email using code or SPD and thne convert and upload it portal.

    Please………..Advise

  8. Bjørn Furuknap December 30, 2008 at 3:42 pm #

    Ani: As I see it you have two options. First, create an event receiver and handle your form creation there. The second part of the series covers event handlers.

    Second option is adding a custom email handler. You are not bound to use the built-in handler at all, in fact, adding your own custom email handler is done in one line of code.

    I show that in my new book, but I’ve also posted that exact section as an exclusive excerpt to mailing list members. All you need to do to learn how to set up email enable custom lists or any other list is to sign up and download the excerpt PDF :-)

    .b

Trackbacks/Pingbacks

  1. Automating business processes in SharePoint: SharePoint Event Receivers (Part 2 of 3) | Furuknap's SharePoint Corner - December 17, 2012

    [...] Automating business processes in SharePoint: SharePoint Designer Workflows (Part 1 of 3) Automating business processes in SharePoint: SharePoint Event Receivers (Part 2 of 3) Automating business processes in SharePoint: Visual Studio Workflows (Part 3 of 3) [...]

Leave a Reply