Elevated Code In SharePoint Workflows
Lately, I have been immersed in SharePoint WorkFlows, which in itself is not really a bad thing, however I am finding my own quirks as I run through it. And by some I mean a lot. For example, I was looking for an elegant way to run my work flow code with elevated privileges where I could separate my SharePoint work flow code method and call it with the relevant privileges to execute.
In order to do this, run the work flow code as elevated within the overriden ActivityExecutionStatus execute method. I spaced this for a while, and man it was driving me nuts. In order to get to this to work, you need to setup your activity class to run elevated code appropriately with the relevant method.
Firstly, in your execute method you are going to have nothing really besides a reference to the secure code that you are going to be running. In other words, you are going to create a method that is considered the elevated code in a seperate method that is going to be passed into the execution method of the activity.
It will look like this:
- protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
- this.executionContext = executionContext;
- SPSecurity.CodeToRunElevated myElevatedCode = new SPSecurity.CodeToRunElevated(this.secureElevatedCode);
- return ActivityExecutionStatus.Closed;
You can see that here we are using the SPSecurity.CodeToRunElevated Delegate and
SPSecurity.RunWithElevatedPrivileges Method which takes the secure code to be run as a parameter, which in this case equates to our major work flow method. Using this structure, you aren’t limited to building an impersonation.
Following, you build out the method that you want to pass in that equates to your secureElevatedCode method.
- private void myElevatedCode()
- // Your elevated workflow code goes here
This can contain an arbitrary set of functions. Within it you could start to establish your SharePoint references to consume within your workflow:
- using (SPSite site = new SPSite(this.YourWorkFlowSiteProperty))
- using (SPWeb web = site.OpenWeb(this.YourWorkFlowWebProperty))
- // Now that you are referenced, do your fun stuff here!
and start to do some fun stuff if you so choose :-)
If you would like to read more about these methods, in the Microsoft Windows SharePoint Services 3.0 SDK there is an example of an event handler which allows users to iterate through sites and groups as their current identity that uses the same tactic. It might be helpful to read through it to solidfy your understanding of the concept if needed.