User Tools

Site Tools


notes:sharepoint2010:eventreceivers

SharePoint 2010 Event Receivers

The ListItem event receiver invoked on ItemUpdated:

// The custom list 'ListOfLists' stores the IDs of all lists in the website and their 'Hidden' property value. 
// It has the following columns:
// - ListId (Guid) 
// - IsHidden (bool)
public class CustomListItemEventReceiver : SPItemEventReceiver
{
    public override void ItemUpdated(SPItemEventProperties properties)
    {
        base.ItemUpdated(properties);
 
        // Check if the list 'ListOfLists' has been updated.
        if (properties.ListTitle == "ListOfLists")
        {
            // Grab the listId from the ListOfLists.
            Guid listId = new Guid((string)properties.ListItem["ListId"]);
 
            // Grab the 'IsHidden' flag from the ListOfLists.
            bool isHidden = (bool)properties.ListItem["IsHidden"];
 
            // Grab the actual list.
            SPList list = properties.Web.Lists[listId];
 
            // Change the 'Hidden' property of the list.
            // This way it is synchronized with the 'IsHidden' flag
            // in the ListOfLists.
            list.Hidden = isHidden;
 
            try
            {
                this.EventFiringEnabled = false;
                list.Update(); // update the list
            }
            finally
            {
                this.EventFiringEnabled = true;
            }
        }
    }
}

The List event receiver invoked when a new list is added to the website:

// The custom list 'ListOfLists' stores information regarding all lists in the website. 
// It has the following columns:
// - Title (string)
// - ListId (Guid) 
// - IsHidden (bool)
// - ListUrl (string)
public class CustomListEventReceiver : SPListEventReceiver
{
    public override void ListAdded(SPListEventProperties properties)
    {
        base.ListAdded(properties);
 
        // Get the current website.
        using (SPWeb web = properties.Web)
        {
            // Make sure the 'ListOfLists' exists in the current website.
            if (web.Lists.TryGetList('ListOfLists') == null)
                return;
 
            // Get the items of 'ListOfLists'.
            SPListItemCollection items = web.Lists['ListOfLists'].Items;
 
            // Add the new list to 'ListOfLists'.
            SPListItem item = items.Add();
            item["Title"] = properties.ListTitle;
            item["ListId"] = properties.ListId;
            item["IsHidden"] = properties.List.Hidden;
            item["ListUrl"] = properties.List.DefaultViewUrl;
 
            try
            {
                this.EventFiringEnabled = false;
                item.Update();
            }
            finally
            {
                this.EventFiringEnabled = true;
            }
        }
    }
}

The List event receiver invoked when a list is deleted from the website.

public class CustomListEventReceiver : SPListEventReceiver
{
    public override void ListDeleted(SPListEventProperties properties)
    {
        base.ListDeleted(properties);
 
        // Get the current website.
        using (SPWeb web = properties.Web)
        {
            // Make sure the 'ListOfLists' exists in the current website.
            if (web.Lists.TryGetList('ListOfLists') == null)
                return;
 
            // Get the items of 'ListOfLists'.
            SPListItemCollection items = web.Lists['ListOfLists'].Items;
 
            // Get the list item to remove.
            var listItemToRemove = 
                items.Cast<SPListItem>()
                .Where(item => new Guid((string)item["ListId"]) == properties.ListId).FirstOrDefault();
 
            // Check if the list being removed exists in the 'ListOfLists'. 
            // If so, remove the corresponding item by its integer ID.
            if (listItemToRemove != null)
            {
                try
                {
                    this.EventFiringEnabled = false;
                    items.DeleteItemById(listItemToRemove.ID);
                }
                finally
                {
                    this.EventFiringEnabled = true;
                }
            }
        }
    }
}

Determine the content type name of the list item in an SPItemEventReceiver:

public class CustomListItemEventReceiver : SPItemEventReceiver
{
    public override void ItemAdded(SPItemEventProperties properties)
    {
        string contentTypeIdStr = properties.AfterProperties["ContentTypeId"].ToString();
        SPContentTypeId contentTypeId = new SPContentTypeId(contentTypeIdStr);
        SPContentType contentTypeType = properties.List.ContentTypes[contentTypeId];
        string contentTypeName = contentTypeType.Name.ToLower();
        // ...
 
        // Check if the content type derives from DocumentSet.
        if (contentTypeId.IsChildOf(SPBuiltInContentTypeId.DocumentSet))
        {
            // ...
        }
    }
}
 
// The same code wrapped into a method.
private string GetContentTypeName(SPItemEventProperties properties)
{
    if (properties.AfterProperties["ContentTypeId"] != null)
    {
        string contentTypeIdStr = properties.AfterProperties["ContentTypeId"].ToString();
        SPContentTypeId contentTypeId = new SPContentTypeId(contentTypeIdStr);
        SPContentType contentType = properties.List.ContentTypes[contentTypeId];
        string contentTypeName = contentType.Name.ToLower();
        return contentTypeName;
    }
    else
    {
        return null;
    }
}

Assign the today's date to a field:

string internalName = properties.List.Fields['MyFieldName'].InternalName;
properties.AfterProperties[internalName] = 
    Microsoft.SharePoint.Utilities.SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Today);

Compare 'before' and 'after' values of a field in an event receiver:

private bool AreEqual(SPItemEventProperties properties, string fieldName)
{
    string internalName = properties.List.Fields[fieldName].InternalName;
    object beforeVal = properties.BeforeProperties[internalName];
    object afterVal = properties.AfterProperties[internalName];
 
    if (beforeVal == null) return (afterVal == null);
    if (afterVal == null) return false;
 
    SPField field = properties.List.Fields.GetField(fieldName);
 
    if (field is SPFieldDateTime)
    {
        string beforeDate = beforeVal.ToString().Substring(0, 10);
        string afterDate = afterVal.ToString().Substring(0, 10);
        return (beforeDate == afterDate);
    }
    else if (field is SPFieldUser)
    {
        SPFieldUserValue beforeUser = (SPFieldUserValue)field.GetFieldValue(beforeVal.ToString());
        SPFieldUserValue afterUser = (SPFieldUserValue)field.GetFieldValue(afterVal.ToString());
        return (beforeUser.User.ID == afterUser.User.ID);
    }
    else
    {
        return (beforeVal.ToString() == afterVal.ToString());
    }
}

Add or remove (i.e. toggle) an event receiver of type SPEventReceiverType.EmailReceived:

// listName - the name of the list the event receiver is attached to.
// className - the name of the event receiver class 
// asmName - the assembly the event receiver resides
SPWeb web = SPContext.Current.Web;
 
try
{
    web.AllowUnsafeUpdates = true;
 
    SPList list = web.Lists[listName];
    if (list != null)
    {
        int receivers = list.EventReceivers.Count;
        string className = "WBS.EventReceivers.MyEmailEventReceiver";
        string asmName = "WBS.EventReceivers, Version=1.0.0.0, " +
            "Culture=neutral, PublicKeyToken=6844b077a905c051";
 
        SPEventReceiverDefinition emailReceiver = null;
        for (int i = 0; i < receivers; i++)
        {
            SPEventReceiverDefinition eventReceiver = list.EventReceivers[i];
            if (eventReceiver.Class == className && 
                eventReceiver.Type == SPEventReceiverType.EmailReceived)
            {
                emailReceiver = eventReceiver;
                break;
            }
        }
 
        if (emailReceiver == null)
        {
            // Add the event receiver.
            list.EventReceivers.Add(SPEventReceiverType.EmailReceived, asmName, className);
        }
        else
        {
            // Remove the event receiver.
            emailReceiver.Delete();
            list.Update();
        }
    }
}
finally
{
    web.AllowUnsafeUpdates = false;
}

List event receivers of a given class registered for a list:

// listName - the name of the list the event receiver is attached to.
// className - the name of the event receiver class 
SPWeb web = SPContext.Current.Web;
 
try
{
    web.AllowUnsafeUpdates = true;
 
    SPList list = web.Lists[listName];
    if (list != null)
    {
        int receivers = list.EventReceivers.Count;
        string className = "WBS.EventReceivers.MyEventReceiver";
 
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < receivers; i++)
        {
            SPEventReceiverDefinition eventReceiver = list.EventReceivers[i];
            if (eventReceiver.Class == className)
            {
                sb.Append(String.Format("Name: {0}, Type: {1}; ", 
                    eventReceiver.Name, eventReceiver.Type.ToString()));
            }
        }
 
        // sb.ToString() contains info regarding the event receivers.
        // ...
    }
}
finally
{
    web.AllowUnsafeUpdates = false;
}

Remove event receivers of a given class from a list:

// listName - the name of the list the event receiver is attached to.
// className - the name of the event receiver class 
SPWeb web = SPContext.Current.Web;
 
try
{
    web.AllowUnsafeUpdates = true;
 
    SPList list = web.Lists[listName];
    if (list != null)
    {
        int receivers = list.EventReceivers.Count;
        string className = "WBS.EventReceivers.MyEventReceiver";
 
        // Collect receivers to remove.
        List<SPEventReceiverDefinition> removeReceivers = new List<SPEventReceiverDefinition>();
        for (int i = 0; i < receivers; i++)
        {
            SPEventReceiverDefinition eventReceiver = list.EventReceivers[i];
            if (eventReceiver.Class == className)
            {
                removeReceivers.Add(eventReceiver);
            }
        }
 
        // Remove the collected receivers.
        foreach(SPEventReceiverDefinition rec in removeReceivers)
        {
            rec.Delete();
            list.Update();
        }
    }
}
finally
{
    web.AllowUnsafeUpdates = false;
}

Attach event receivers programmatically to a list:

// "WBS.EventReceivers" - a fully qualified namespace of the event receivers we want to attach to the list
list.EventReceivers.Add(SPEventReceiverType.ItemAdded, 
    Assembly.GetExecutingAssembly().FullName, "WBS.EventReceivers");
list.EventReceivers.Add(SPEventReceiverType.ItemAdding, 
    Assembly.GetExecutingAssembly().FullName, "WBS.EventReceivers");
notes/sharepoint2010/eventreceivers.txt · Last modified: 2020/08/26 (external edit)