Tuesday, May 29, 2007

Custom Workflow , SPWorkflowActivationProperties and "Current user"

Today, I saw an interesting post in one of the newsgroups where someone was looking for a way get the identity of the current logged in user. The user tried getting the current user's Id by SPWorkflowActivationProperties .Web.CurentUser which in normal circumstances make sense but not in the case of the windows workflow. Why? Lets try to break down this problem.

First of all SharePoint is a hosting windows workflow which means its running the windows workflow runtime possibly in the same process as the current web application, however it is NOT necessarily sharing the same session or context, moreover , there is no sequence or direct corelation in the execution of a workflow activity and and a browser session. Also, a workflow activity can be invoked from any external program, it does NOT have to be the current session. E.g. If you are writing a workflow to approve an item, it can be triggered by Outlook, Word, SharePoint or any custom application for that matter.

Why SPWorkflowActivationProperties .Web.CurentUser returns SharePoint/System user ??

The simple answer is SPWeb and SPSite properties of SPWorkFlowActivationProperties are instantiated by the workflow runtime and workflow runtime impersonate the current "Process account" to create SharePoint objects, hence the "SharePoint\System" user

But I want the current logged-in user ?

I think the question should be rephrased, Instead of the currently logged in user, you may want to access the user who last edited one of the list item on which you are executing the workflow. If that's what your use case then there are multiple ways to get it. The simplest way is to use "Modified By" column of SPListItem. All SPListItems has this properties. This will give you the Id of the user who last touched your item in question.

5 comments:

Naren said...

Brilliant explaination. Probably saved me from a ton of wild goose chasing. Thank you.

justforkix said...

porsche911Hi,
But is there any way I can access the user object of the person activating the workflow.

If the workflow has started manually then the "modified by" field does not help.

I need to check out the user's permissions before doing some of the worklow's tasks.

Keith Dahlby said...

@justforkix: SPWorkflowActivationProperties has an OriginatorUser property:
"Gets the user who initiated the workflow instance."

Faheem said...

Hi Keith, is the only way to surface the property showing the wf originator to create a custom action or can we do it OOb with SPD? thx Faheem

Keith Dahlby said...

I'm not aware of any direct exposure of an SPD workflow originator, but any items created or updated by the workflow (including assigned tasks) will show the originator as Creator or Modifier.