SharePoint Sharpener

Obsessively Sharpening SharePoint

Elevation: Run Code as an Administrator

with one comment


Sometimes you may need your web part to perform tasks for which the current user doesn’t have priviliges. For instance, we needed a sign up form for our WCM web site where the user could enter contact information that should be stored in a list.

Naturally, our web site runs with anonymous access and the the anonymous users do not have access to the underlying lists, including the list where the contact information goes.

Thus, submitting to the list is not just a matter of doing an Items.Add() because this causes a login dialogue to pop up and ultimately a 401 Unauthorized error.

Normally you’d create an element in the list with code similar to this:

image

 

However, if the logged-in user doesn’t have sufficient credentials to write to the list, a login dialogue will pop up.

 

Run with Elevation

To get around this problem you can use SPSecurity.RunWithElevatedPriviliges() like this:

image

 

For this to work, you need to instantiate the SPSite and SPWeb objects inside delegate():

image

 

Now the list will be updated with a new element, created by the system account.

Advertisements

Written by Thomas Sondergaard

August 27, 2008 at 6:56 am

One Response

Subscribe to comments with RSS.

  1. […] For instance, you may have created a newsletter signup web part which posts data to a list (using elevation). In time, the list fills up with more or less sensitive information about your newsletter […]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: