August 28, 2007

MOSS: SPLimitedWebPartManager.SaveChanges throws security exception

Problem:
When modifying Web Part properties programmatically and trying to save changes, an exception is thrown saying that "Security validation for this page is invalid." You have also set the AllowUnsafeUpdates to true on the current web.

Something like this:
private void SetWebPartAudience(string webUrl)
{
    SPWeb tempWeb = null;
 
    try
    {
        tempWeb = new SPSite("http://mysite/myweb").OpenWeb();                
 
        SPLimitedWebPartManager wm = page.GetLimitedWebPartManager("Pages/default.aspx", 
            System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
 
        foreach (System.Web.UI.WebControls.WebParts.WebPart wp in wm.WebParts)
        {
            if (wp.GetType().Equals(typeof(KPIListWebPart)))
            {
                wp.AuthorizationFilter = ";;;;" + "Internal Users";
 
                tempWeb.AllowUnsafeUpdates = true;
                wm.SaveChanges(wp);
                tempWeb.AllowUnsafeUpdates = false;
 
                break;
            }
        }
    }
    catch (Exception e)
    {
    }
    finally
    {
        if (tempWeb != null)
        {
            tempWeb.Dispose();
        }
    } 
}

Solution:
Set AllowUnsafeUpdates on the SPLimitedWebPartManager's Web object like this:

wm.Web.AllowUnsafeUpdates = true;
wm.SaveChanges(wp);
wm.Web.AllowUnsafeUpdates = false;

August 24, 2007

MOSS: All web parts appear as ErrorWebPart

Problem:
When trying to enumerate web parts on a site all web parts appear as ErrorWebPart. There are OOB and custom web parts on the site.

In my case I have a Web Service that is used to create new MOSS sites. At some stage I need to define the Audience setting of some web parts and it has to be done programmatically. As far as I know, Audience settings cannot be set in Site Definitions. Please let me know if it is possible.

Solution:
Put all custom web parts in GAC. It appears that if even one custom web part has problems with permissions (not in GAC or otherwise not trusted), all web parts appear as ErrorWebPart.

August 21, 2007

MOSS: BreakRoleInheritance throws exception

Problem:
Calling BreakRoleInheritance on a list throws exception if the method's CopyRoleAssignments parameter is set to false. Exception thrown is "The security validation for this page is invalid."

Workaround:
Use true as the parameter and remove all permissions later in code.

Solution:
Unknown