SharePoint–AllowUnsafeUpdates when using Object Model to Update Security

I have some code that will programmatically add a group to SharePoint via the object model.  When running this code I kept getting an error that I couldn’t do this.  The error/exception would get thrown whenever trying to add permissions to an existing collection via the SharePoint object model – apparently SharePoint Security likes to keep things in the UI.

I would run some code that looked a little like:

SPMember owner = rootWeb.Users["UserName"];
SPUser user = rootWeb.Users["UserName"];
rootWeb.SiteGroups.Add(groupName, user, null, description);

And the following exception would get thrown:

System.Runtime.InteropServices.COMException: The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again.

After digging around I discovered that you need to set SPWeb.AllowUnsafeUpdates = true.

"Setting this property to true opens security risks, potentially introducing cross-site scripting vulnerabilities."

So just a quick reminder that any time you want to deal with the Security of a site in the ObjectModel, always turn on the AllowUnsafeUpdates and when you’re done with it, set it back to false.

EDIT: If you forget to set it to false, never fear… After the object is disposed and you get another SPWeb the setting is set back to false.

SharePoint 2007–Cleaning Up After MOSS Uninstall

For those of us who don’t have the luxury of multiple servers that we can set up and tear down, we often find we are installing MOSS as a dev tool and often are uninstalling it at various intervals along the way.  Unfortunately the uninstall process is not completely clean and we’re left with some artifacts that we want to remove in order to run a clean box for some other project or product.  One of the artifacts that remain is the SQL Express instance of OFFICESERVERS that is installed during an install of WSS.

In order to remove this named instance, use the following steps:

  1. click Start->Run->regedit
  2. Navigate to hkey_local_machine\software\Microsoft\Windows\CurrentVersion\Uninstall
  3. Find the key which has a display name of OFFICESERVERS.
  4. Once you find the key in question (it’s usually a GUID), copy the text out of the ‘UninstallString’ key and paste it into a Start->Run dialog box.
  5. image
  6. Let the installer run and when prompted choose to remove the Sql Express instance.
  7. image

And now you’ve removed the named instance OFFICESERVERS from your system.