Thursday, May 1, 2008

Sample code for adding/deleting MOSS alerts

Please somebody tell me there's a better way to delete an alert. I'm too lazy to spend more time on this...

Create an alert...

   1: try
   2: {
   3:     string[] alertUsers = web.Alerts.GetUniqueUsers();
   4:     Guid alertGuid = web.Alerts.Add(
   5:         web.Lists[_documentLibraryName], 
   6:         SPEventType.Add, 
   7:         SPAlertFrequency.Immediate);
   8:     SPAlert alert = web.Alerts[alertGuid];
   9:     alert.User = web.SiteUsers[roleName];
  10:     alert.Update();
  11: }
  12: catch (Exception e)
  13: {
  14:     throw new Exception("Error creating document library notification for company.", e);
  15: }


Delete an alert...





   1: string[] usersWithAlerts = web.Alerts.GetUniqueUsers();
   2: //check to see if there is an alert configured for this role
   3: if (Array.IndexOf(userName) >= 0)
   4: {
   5:     SPList docList = web.Lists[_documentLibraryName];
   6:     for( int i = web.Alerts.Count -1; i >= 0; i--)
   7:     {
   8:         SPAlert alert = web.Alerts[i];
   9:         if (alert.List = docList)
  10:         {
  11:             if (alert.User.Name == roleUserName)
  12:             {
  13:                 web.Alerts.Delete(alert.ID);
  14:             }
  15:         }
  16:     }
  17: }