Skip to content

Instantly share code, notes, and snippets.

@IAMPetro
Created December 11, 2016 09:39
Show Gist options
  • Save IAMPetro/9ef47a6a8ee68fb1efd6bbaf90fcb15b to your computer and use it in GitHub Desktop.
Save IAMPetro/9ef47a6a8ee68fb1efd6bbaf90fcb15b to your computer and use it in GitHub Desktop.
SharePoint: Elevated Perms Event Receiver
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
namespace SharePoint.Development.EventReceivers
{
///
/// List Item Events
///
public class ItemCheckedInEventReceiver : SPItemEventReceiver
{
private string newDocumentUrlExample = "http://newfilelocation/document.doc";
public override void ItemCheckedIn(SPItemEventProperties properties)
{
base.EventFiringEnabled = false; // Disable event receiver firing so that we do not accidentally kick off a different thread
try
{
// Check if user has a certain set of permissions, i.e. can they delete items? if not, then we will have to RunWithElevatedPrevileges
if (properties.Web.DoesUserHavePermissions(properties.UserLoginName, SPBasePermissions.DeleteListItems))
{
SPFile file = properties.ListItem.File; // Get the file
file.MoveTo(newDocumentUrlExample); // Move it to the new location
}
else
{
RunWithElevatedPrivileges(properties, newDocumentUrlExample); // User doesn't have required permissions and therefore the code must be executed with Elevated perms.
}
}
catch (Exception exception)
{
// Write exception to ULS and Event Logs
}
finally
{
base.EventFiringEnabled = true;
}
}
public static void RunWithElevatedPrivileges(SPItemEventProperties properties, string newURL)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate ()
{
// Everything executed here will be executed under the AppPool account and will have full permissions.. so becareful!!
using (SPSite site = new SPSite(properties.SiteId))
{
using (SPWeb web = site.OpenWeb(properties.Web.ID))
{
SPList list = web.Lists[properties.ListId];
SPListItem listItem = list.Items.GetItemById(properties.ListItemId);
SPFile file = listItem.File;
file.MoveTo(newURL);
}
}
});
}
catch (Exception exception)
{
// Write exception to ULS and Event Logs
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment