views:

349

answers:

1

Using the SharePoint 2010 RC I am having issues canceling the deletion of a list item using event receivers. My code is firing, setting the cancel property of the SPItemEventProperties, setting an error message, and throwing an error back to the calling thread. This approach works fine in the adding/updating methods, however, when used in the deleting method I can watch the code fire in a debugger, but the item is still moved to the site's recycling bin.

Further, I am seeing this behavior in a site created from the "CMSPUBLISHINGSITE#2" template from stsadm, but not from a site created from the "Team Site" template via Central Administration.

The misbehaving code follows:

public override void ItemDeleting(SPItemEventProperties properties)
{
    if (!(properties.UserLoginName == "SHAREPOINT\\system"))
    {
        try
        {
            throw new CreatorIdAliasingException("Please contact support if you feel a release web site has been inappropriately assigned to your organization.");
        }
        catch (CreatorIdAliasingException ex)
        {
            properties.Cancel = true;
            properties.ErrorMessage = ex.ToString();
            properties.InvalidateListItem();
            throw;
        }
    }
}

For reference, identical code is contained in the ItemAdding method and works as expected.

public override void ItemAdding(SPItemEventProperties properties)
        {
            base.ItemAdding(properties);
            if (!(properties.UserLoginName == "SHAREPOINT\\system"))
            {
                try
                {
                    throw new InvalidCreatorIdException("Please contact support to add a known URL to your list of release web sites.");
                }
                catch (InvalidCreatorIdException ex)
                {
                    properties.Cancel = true;
                    properties.ErrorMessage = ex.ToString();
                    properties.InvalidateListItem();
                    throw;
                }
            }
        }
A: 

I would recommend you to not be using Exceptions as part of your business logic. Exceptions are expensive and should only be used in exceptional cases which are not handled by normal logic.
Instead, use something like this:

public override void ItemDeleting(SPItemEventProperties properties)
{
  if (properties.UserLoginName.ToLower().CompareTo("sharepoint\\system") != 0)
  {
    properties.Cancel = true;
    properties.ErrorMessage = "Some error has occured....";
  }
}

And, by the way, you are throwing an additional exception within the event handler which probably is the reason that you see this behavior you are experiencing.

Magnus Johansson
Not rethrowing the exception fixed the behavior for the publishing, but it for non-publishing sites it is not necessary to eat the exception for the code to function as intended.
OedipusPrime