Tuesday, April 7, 2009

When to use AllowUnsafeUpdates, ValidateFormDigest() or else

For scenarios in which your code is processing a POST request, ValidateFormDigest() will, behind the scenes, set AllowUnsafeUpdates to true.

But some scenarios (e.g. web services) are not a POST request, therefore ValidateFormDigest() will fail.

So, here's a simple decision tree to help:

HttpContext.Current is null => Do nothing, no need to set AllowUnsafeUpdates to true nor to call ValidateFormDigest() because update will be carried out (e.g. code being called from an .exe from a cmd prompt)

HttpContext.Current is NOT null
- SPContext.Current is null => Need to set AllowUnsafeUpdates to true (e.g. web service)
- SPContext.Current is NOT null => Call ValidateFormDigest() (e.g. POST request processing)

Monday, April 6, 2009

SPSecurity.RunWithElevatedPrivileges() throws InvalidOperationException, "Operation is not valid due to the current state of the object."

There are several reasons for this to happen.

1) HttpContext.Current.User == null
2) code running under impersonation.

If it's 2), here's one recipe, save HttpContext, set it to null, restore it back:

            HttpContext prev = HttpContext.Current;
HttpContext.Current = null;
HttpContext.Current = prev;