Pages

Thursday, June 12, 2014

SharePoint - Create and Delete Alerts on List Programatically

Generally when we require any action need to happen if we do any operation on List Items, we go with List Item Event Receivers. But if you have a requirement where just a notification need to go to some user with items added/changed, you can go with ALERTS in SharePoint which is OOB Feature.



In order to setup this on List, we dont have any way of declarative syntax[XML through Schema.xml]. We need to set this either Manually or through Programatically.

Let me explain you how to create and delete alerts on SharePoint List Programatically. In Google, you will able to get easily about how to Create alerts but I think I didn't find much info on Delete alerts. For this I will explain you both in below:-

Create Alerts:-

 private static void CreateAlert(SPUser user, SPList list)
        {
            SPAlert newAlert = user.Alerts.Add();
            //Here kept Alert Name same as List Name, but can give any Name
            newAlert.Title = list.Title;
            newAlert.AlertType = SPAlertType.List;
            newAlert.List = list;
            newAlert.DeliveryChannels = SPAlertDeliveryChannels.Email;
            newAlert.EventType = SPEventType.Add;
            newAlert.AlertFrequency = SPAlertFrequency.Immediate;
           //If we do False in below line, it will not send email notification to user when Alert has been sent.
            newAlert.Update(false);

        }

Delete Alerts:-

  private static void DeleteExistingAlert(SPWeb web, SPUser User, string strListTitle)
        {
            //Using this As we cant Delete in the Loop of Web.Alerts
            var col = new List<string>();
            foreach (SPAlert alert in web.Alerts)
            {
               // If You want to remove particular Alert, if not remove this If Condition
                if (alert.List.Title.Equals(strListTitle) 
                    && alert.Title.ToLower().Equals(strListTitle.ToLower()))
                {
                    col.Add(alert.ID.ToString());
                }
            }
            // If we use Delete Alert in above If Condition only, will get an error as Collection Cant be Modified
            foreach (var item in col)
            {
                web.Alerts.Delete(new Guid(item));
            }
        }

Once it gets Created, in order to verify you cant check in the same place of List All Items page. For this you need to go to Site Settings --> Click On User Alerts





Happy Programming..!

No comments:

Post a Comment