Monday, October 20, 2008

Sending Email From a Custom Workflow Activity

When creating custom workflows for your SharePoint server, you may find that you have a need to reuse the same set of activities over and over again. A perfect example of this is when you are using a repeater for an approval task to get approvals from multiple people. Another excellent use for a custom activity is when you are going to have multiple workflows using the same series of activities in a reusable sort of model.

One limitation I've found is that it's impossible to send email from your custom activity. The SendEmail activity requires that you have a reference to your Workflow token, but the activity doesn't have any knowledge of the workflow it's running within. You could use the SendEmail routine of the SPUtility class, but that requires a reference to the SPWeb object, which cannot be stored or passed to a custom activity because it's not serializable.

So, what's a developer to do, you ask...?

Events. It turns out that custom activities can raise events to the workflow which can then execute code at specific times. It's important to note that you cannot run activities in a workflow when an activity's event fires--the workflow is essentially halted, and will remain that way until your custom activity has completed. However, the event handler in your workflow can execute code behind the scenes, which will allow you to send an email with the SPUtility class.

I think it's important to point out that the Workflow Designer doesn't always like events mapping from your custom controls. They'll show up in the activity's properties, but will sometimes have the infamous red error icon indicating that the event could not be found. This shouldn't be a problem, and your DLL should compile just fine regardless of this error.

Also important to know is that your custom activity may not show up if you've already deployed your workflow to your SharePoint server. Sometimes it might also show up by throw an error when you try to drag the activity into your workflow. This is because the old version of the DLL is already in the GAC...and that version doesn't have your new activity in it. Simply deploy your workflow to your SharePoint server, or copy the DLL directly in the GAC and then try adding the activity again. With the custom activity now showing up in the assembly on the server, it should show up in your tool pane.

Good luck, and happy coding!

No comments: