Accessing Lookup Values fails with Exception when the connected user is not the SharePoint Site Collection administrator
-
16-10-2019 - |
Question
In sharepoint 2010 Foundation, after we installed a simple event receiver that mainly runs when certain items are added/modified, we noticed, during manual testing, that if we logged in as a user other than the sharepoint administrator account we would get an error whenever we tried retrieving to retrieve a simple lookup column information. The error Message said
Error loading and running event receiver EvozonAdministrationEventReceivers.StartEmailNotification.StartEmailNotification in EvozonAdministrationEventReceivers,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=918ea4bf742b9a3a. Additional information is below.
: Value does not fall within the expected range.
The same code run on Dev or with the Administrator logged in had no issues running.
Does anybody have any idea why. The server has Active Directory installed. It makes absolutely no sense to me. Are lookups executed in some type of sandbox?
Partial code listing below:
var Field = FieldResolver.On(_onBoardingChecklist);
SPSecurity.RunWithElevatedPrivileges(() =>
{
string computerType = LookupValue<Columns.ComputerType>();
// .. omitted for previty
public string LookupValue<SITECOLUMN>() where SITECOLUMN : new()
{
if (_Field == null)
_Field = FieldResolver.On(_onBoardingChecklist);
var value = (string)_onBoardingItem[_Field.For<SITECOLUMN>().InternalName];
value = new SPFieldLookupValue(value).LookupValue;
return value;
}
Solution
Looks like you have a piece of code in your event receiver, which requires elevated privilegies. You should use SPSecurity.RunWithElevatedPrivilegies for this piece of code.
Update:
Also, please make sure you have recreated all SharePoint objects inside the RunWithElevatedPrivilegies delegate, because, for example, this would work:
SPSecurity.RunWithElevatedPrivileges(() =>
{
using (SPSite site = new SPSite(properties.SiteId))
{
using (SPWeb web = site.OpenWeb(properties.RelativeWebUrl))
{
// ...
web.Update();
}
}
});
But this, wouldn't:
SPSecurity.RunWithElevatedPrivileges(() =>
{
// ...
properties.Web.Update();
});
Thanks Anders Rask for the important note about SPContext!