Tuesday, September 17, 2013

Programmatically Create Alert for FBA User in SharePoint Claims Web Application

Assuming that you are using email Address as username for a claims authenticated SharePoint Web Application, you can use this simple code to programmatically create an Alert for a specific user.

using (SPSite site = new SPSite("http://fqdn.sharepoint.claims.webapp"))
{
 SPIisSettings settings = site.WebApplication.IisSettings[SPUrlZone.Default];
 MembershipProvider membership = System.Web.Security.Membership.Providers[settings.FormsClaimsAuthenticationProvider.MembershipProvider];
   
 using (SPWeb web = site.OpenWeb())
 {
  SPUser user = web.SiteUsers["i:0#.f|" + membership.Name + "|" + Email];
  SPAlert newAlert = user.Alerts.Add();
  newAlert.AlertType = SPAlertType.List;
  newAlert.List = web.Lists["List Name"];
  newAlert.EventType = SPEventType.All;
  newAlert.AlertFrequency = SPAlertFrequency.Immediate;
  //passing true to Update method will send alert confirmation mail
  newAlert.Update(false); // will not send alert confirm email
  //newAlert.Update(true);  // will send alert confirm email to subscribed user
 }
}


Hope this can help.