Saturday, December 6, 2008

Create SharePoint Alerts Programmatically

Using following code you can create alerts

SPUser user = mySite.Users["domain\user"];
SPAlert newAlert = user.Alerts.Add();
newAlert.Title = list.Title;
newAlert.AlertType = SPAlertType.List;
newAlert.List = list;
newAlert.Properties["eventtypeindex"] = "1";
newAlert.AlertFrequency = SPAlertFrequency.Immediate;
newAlert.Update(false);
 
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.
 
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, in that your code should be
 
newAlert.AlertType = SPAlertType.Item;
newAlert.Item = item;
 
You can change following codes depending on what action you want to set alert using "eventtypeindex"
 
all = 0
added = 1
modify = 2
deleted = 3
web discussions = 4

If you want to send Alert daily you can change the AlertFrequency as mentioned below

newAlert.AlertFrequency = SPAlertFrequency.Daily;
newAlert.AlertTime = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, 8, 0, 0);

If you are subscribing alerts for some other user, you should be the administrator or should have permisssions to manage alerts thne add your code with following code

SPSecurity.RunWithElevatedPrevilages(delegate()
{

web.AllowUnSafeUpdates=true;
  // Add your code here
});

0 comments:

Post a Comment