List All Alerts in SharePoint site

You can use the below method in your webpart to display all alerts in your SharePoint SiteCollection.

public void GetAlerts(Button btn)
{

SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = mySite.OpenWeb();

//Using RunWithElevatedPrivileges

SPSecurity.RunWithElevatedPrivileges(delegate()
{
// Get references to the site collection and site for the current context.
// The using statement makes sure that these references are disposed properly.

SPList alertList = myWeb.Lists[LibName.Trim()];

using (SPSite siteCollection = new SPSite(mySite.ID))
{
foreach (SPWeb curretWeb in siteCollection.AllWebs) //Get alerts for each web
{
using (SPWeb web = siteCollection.OpenWeb(curretWeb.ID))
{
web.AllowUnsafeUpdates = true;

try
{
SPAlertCollection allAlerts = web.Alerts;

foreach (SPAlert AlertItem in allAlerts)
{
AddListItem(alertList, AlertItem);
}
}

catch (Exception ex)
{
Console.WriteLine("Delete failed: " + ex.Message);
throw;
}

web.AllowUnsafeUpdates = false;
}
}}});
}

1 comments:

  1. Where would one put this piece of code exactly? On the page that displays the user alerts one-by-one?

    ReplyDelete

Disclaimer

This is a personal weblog. The opinions expressed here represent my own and not those of my employer or anyone else. Should you have any questions or concerns please e-mail me at sharepointprogrammingblogger@gmail.com .

Copyright (c) 2010 @ myshaepointwork.blogspot.com. All rights are reserved.Do Not Copy.

@ Learning SharePoint.com