Tuesday 11 October 2011

RunWithElevatedPrivileges - another encounter and something you should know

I have been previously complaining about SPSecurity.RunWithElevatedPrivileges as being a load of tosh. I might have been a tad harsh as I employed it just yesterday and got it working - almost.

I needed to do two things - copy over a file and update fields. The file copy bit worked well - I had an impersonation block for that - but the bit where a non-admin user updates the fields was, alas, a bit of a dud. Until I put the field update section into a RunWithElevatedPrivilege delegate block and all looked fine.

But in addition to the native data types I was using, I also had four user fields I was obtaining from a web service off somewhere else. In order to update these, I had to get the username and call the EnsureUser method on my elevated privileges SPWeb object. This was still failing, even within the privileged user wrapper. It either said I couldn't find the user or that I wasn't allowed to get it. This even though I had, as Google's wisdom advised, wrapped the EnsureUser method call with AllowUnsafeUpdates = true on either side.

Then I commented out the web.AllowUnsafeUpdates = true line and its corresponding AllowUnsafeUpdates=false on the other side. Ran it again. Worked perfectly. I had been trying this for days!

So, you heard it here first - when using the delegate, try not setting the AllowUnsafeUpdates property. And definitely don't set it on the Site object or the whole thing will break completely. SharePoint seems perfectly capable of deciding for itself, in this case, whether the update is safe or not.

No comments:

Post a Comment