Check if an item has been previously approved and approve again

Sometimes, you’ll have to check in an event receiver if an item has been previously approved and then do an action.

The following extension will return a boolean wether or not the item has been approved in the past or not.

public static bool HasBeenPreviouslyApproved(this SPListItem item)
    bool hasBeenPreviouslyApproved = false;
    if (item.Versions.Count > 1)
        var prevPublishedVer = item.Versions.Cast<SPListItemVersion>().Where(v => v.Level == SPFileLevel.Published).LastOrDefault();
        if (prevPublishedVer != null)
            hasBeenPreviouslyApproved = true;
    return hasBeenPreviouslyApproved;

As an example you can put the state back to approved if a modification was made. By default this always goes back to pending when an item gets edited, but in some cases you want to keep the state to approved.

if (properties.ListItem.HasBeenPreviouslyApproved())
    using (var web = properties.OpenWeb())
        this.EventFiringEnabled = false;
        properties.ListItem.ModerationInformation.Status = SPModerationStatusType.Approved;
        this.EventFiringEnabled = true;

Please note that when you use this code in an event receiver, it only works in the ItemUpdated event.

As a result, an announcement which was once approved, will always be approved, until a content editor decides to change the approval status back to pending or decline.

announcement approved


Prevent items from being deleted using an event receiver

One way to prevent item deletion is creating a custom permission level, where the item deletion permission is unchecked. When you use this method to prevent item deletion, you’ll have to break the permission inheritance of your list. Plus, you’ll create the permission level for the whole site collection. If that’s a problem you can also use an event receiver.

The following code snippet will prevent item deletion and also notify the user of what happened. If you simply use the properties.Cancel = true; property, then the item is prevented from deletion, but the user isn’t notified.

By setting the properties.Status = SPEventReceiverStatus.CancelWithError; property, we tell SharePoint to generate an error message. The properties.ErrorMessage = “This item cannot be deleted; Contact your administrator”; property defines the message the user sees.

/// <summary>
/// An item is being deleted.
/// </summary>
public override void ItemDeleting(SPItemEventProperties properties)
    properties.Status = SPEventReceiverStatus.CancelWithError;
    properties.ErrorMessage = "This item cannot be deleted; Contact your administrator";
    properties.Cancel = true;

The above snippet generates the following error when a user tries to delete an item in a list where the event receiver is active:

error screenshot from event receiver