This following piece of code will show you how to programmatically create a SharePoint alert:
First I will show you the code snippet to create the Alert, after that I will explain the code step by step.
SPAlert newAlert = user.Alerts.Add(); newAlert.Title = list.Title; newAlert.AlertType = SPAlertType.List; newAlert.List = list; //newAlert.EventType = SPEventType.Add; <= doesn’t work //use the following codes to set the "eventtypeindex" property //all =0, added = 1, modify = 2, deleted = 3, web discussions = 4 newAlert.Properties["eventtypeindex"] = "1"; newAlert.AlertFrequency = SPAlertFrequency.Immediate; //passing false to Update method will refrain from sending the alert confirmation mail newAlert.Update(false);
Step by step:
The first thing to create the alert is to use the Add method of the Alerts property of the SPUser class, in our example “user” is an instance of a SPUser class.
SPUser user = mySite.Users["domain\user"]; SPAlert newAlert = user.Alerts.Add();
If you want to set an alert for a list, you have to set the AlertType property to SPAlertType.List and set the List property to an instance of the SPList class.
newAlert.AlertType = SPAlertType.List; newAlert.List = list;
If you want to set an alert for a list item, you have to set the AlertType property to SPAlertType.Item and set the Item property to an instance of the SPListItem class.
newAlert.AlertType = SPAlertType.Item; newAlert.Item = item;
The next property you want to set is the EventType property, this didn’t work out the way I wanted it too. I was having a problem with setting the EventType on an SPAlert to SPEventType.Add.
My code wouldn’t throw an error but neither would it set the EventType to SPEventType.Add, in stead it would stay at SPEventType.All.
I fixed this by using the following codes to set the “eventtypeindex” property of the SPAlert:
- all = 0
- added = 1
- modify = 2
- deleted = 3
- web discussions = 4
//newAlert.EventType = SPEventType.Add; newAlert.Properties["eventtypeindex"] = "1";
The last properties to set is the AlertFrequency.
newAlert.AlertFrequency = SPAlertFrequency.Immediate;
If you AlertFrequency is different than Immediate you will have to set the AlertTime property, the AlertTime property defines the next time the alert will be sent.
newAlert.AlertFrequency = SPAlertFrequency.Daily; newAlert.AlertTime = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, 8, 0, 0);
Last but not least you will have to call the Update method of the instance of SPAlert. You can pass a bool parameter which tells the update if it needs to send an alert confirmation mail or not.
No related posts.