Friday, March 29, 2013

Interesting code usements, and structure:
Usement 1 - safely allowing unsafe updates

This is intended to be an ongoing series where I post code patterns that I find interesting.  Vets may find what I post here to be old hat, and newbs may find something useful.  Regardless, these are patterns that I have personally found to be interesting, for whatever reason.  If you have a helpful comment that will elaborate on what's here and educate me, bring it on.  My ultimate goal is to become a better coder.

The first code pattern in this series has to do with SharePoint, and the SPWeb.AllowUnsafeUpdates property.

AllowUnsafeUpdates = true.  We've all done it, despite the fact that it's there to protect us from cross-site scripting attacks.  There are just times when you want to update something and AllowUnsafeUpdates is set to false.  It happens.  And you need to get around it.

EDIT: Scott Brickey (see comments below) wanted me to remind all you SharePointers out there that changing the AllowUnsafeUpdates is only necessary when updating data in an HTTP GET request.  Any other time you are updating data, you should be able to do it without changing AllowUnsafeUpdates.

This is a pattern that leaves me feeling a little more reassured about protecting the safety of the SPweb object during an "unsafe" update.  The trick is to put your updating code in a try{} block, and whether or not you attempt to catch any exceptions, use a finally{} block to reset AllowUnsafeUpdates to false.  That way, if something goes wrong, at least your web object is re-protected.

EDIT: Thanks to an anonymous commenter for pointing out that the AllowUnsafeUpdates value does not persist outside the scope of the instance of SPWeb that you're working on.  So if you are not doing anything else with the SPWeb after you finish your updates, you don't need to set AllowUnsafeUpdates = false.

Here's an example:

using (SPSite site = new SPSite("http://asharepointsite"))
using (SPWeb web = site.OpenWeb())
{
    // do most of the work out here

    try
    {
        web.AllowUnsafeUpdates = true;

        // do the minimum amount of work that
        // necessitated allow unsafe updates

    }
    finally
    {
        web.AllowUnsafeUpdates = false;
    }

    // If you are still going to use your
    // SPWeb object here and do more work,
    // you want to use that finally above to
    // set AllowUnsafeUpdates to false.
    // But, if you are done with the object and
    // are going to let the SPWeb go out of scope
    // and get disposed, you don't need to worry
    // about setting it to false.
}

(Because of the using block, the web and site objects will be disposed of properly even if an exception is thrown, so you don't need to worry about that.)