using Microsoft.SharePoint; using Microsoft.SharePoint.Utilities; using SPSolutions.Serialization; using SPSolutions.SharePoint.Logging; using System; using System.Collections.Generic; using System.Globalization; using System.IO; namespace SPSolutions.SharePoint.Alerts { public class CustomAlertHandler : IAlertNotifyHandler, IAlertUpdateHandler { private string m_amCustomPrefix = "amcustom "; public string ExeName { get { return "CustomAlertHandler"; } } public string ProductName { get { return "Alert Manager"; } } public bool PostUpdate(SPAlert a, SPWeb web, bool newAlert, string properties) { return true; } public bool PreUpdate(SPAlert a, SPWeb web, bool newAlert, string properties) { return !newAlert || web.Site.WebApplication.AlertsEnabled || true; } public bool OnNotification(SPAlertHandlerParams alertHandlerParams) { bool result; try { try { TraceProvider.RegisterTraceProvider(); } catch { } this.WriteTrace("CustomAlertHandler", "Begin Custom Alert Handler"); result = this.HandleOnNotification(alertHandlerParams); } catch (Exception ex) { this.WriteTrace("CustomAlertHandler", "Error generating CustomAlertHandler: " + ex.Message); result = false; } finally { this.WriteTrace("CustomAlertHandler", "End Custom Alert Handler"); try { TraceProvider.UnregisterTraceProvider(); } catch { } } return result; } public bool HandleOnNotification(SPAlertHandlerParams alertHandlerParams) { if (alertHandlerParams.a == null) { this.WriteTrace("CustomAlertHandler", "Alert not sent because no alert was provided."); return false; } try { using (SPSite sPSite = new SPSite(alertHandlerParams.siteId)) { using (SPWeb sPWeb = sPSite.OpenWeb(alertHandlerParams.webId)) { SPAlert sPAlert = sPWeb.Alerts[alertHandlerParams.a.ID]; DateTime now = DateTime.Now; try { sPAlert.Properties["p_lastnotificationtime"] = now.ToString(CultureInfo.InvariantCulture); sPAlert.Update(); } catch (Exception e) { this.WriteExceptionTrace("CustomAlertHandler", "The last notification time could not be updated", e); } AlertTemplateManager alertTemplateManager; try { alertTemplateManager = new AlertTemplateManager(sPAlert.AlertTemplate); } catch (Exception ex) { this.WriteExceptionTrace("CustomAlertHandler", "Error creating AlertTemplateManager: " + ex.Message, ex); bool result = false; return result; } try { alertTemplateManager.EnsureInnerAlertTemplate(); } catch (Exception ex2) { this.WriteExceptionTrace("CustomAlertHandler", string.Format("Error ensuring Inner Alert Template: {0}: {1}", ex2.Message, ex2.InnerException), ex2); bool result = false; return result; } try { alertTemplateManager.ProcessNotification(alertHandlerParams); } catch (Exception ex3) { this.WriteExceptionTrace("CustomAlertHandler", string.Format("Error getting atm.ProcessNotification(AlertTemplateParams): {0}: {1}", ex3.Message, ex3.InnerException), ex3); this.WriteExceptionTrace("CustomAlertHandler", string.Format("alertHandlerParams: {0}, {1}", alertHandlerParams.body, alertHandlerParams.ToString()), ex3); bool result = false; return result; } List list = null; try { list = this.GetAlertTargets(alertHandlerParams, sPWeb, sPAlert); } catch (Exception ex4) { this.WriteExceptionTrace("CustomAlertHandler", string.Format("Error getting alert targets: {0}: {1}", ex4.Message, ex4.InnerException), ex4); bool result = false; return result; } if (list != null && list.Count > 0) { foreach (string current in list) { string body = alertTemplateManager.NotificationMessageBody.Replace("", ""); //SPUtility.SendEmail(sPWeb, false, false, current, alertTemplateManager.NotificationMessageSubject, alertTemplateManager.NotificationMessageBody); SPUtility.SendEmail(sPWeb, false, false, current, alertTemplateManager.NotificationMessageSubject, body); this.WriteTrace("CustomAlertHandler", string.Format("The alert notification '{0}' was sent to '{1}'", alertTemplateManager.NotificationMessageSubject, current)); } } } } } catch (Exception ex5) { this.WriteExceptionTrace("CustomAlertHandler", "The alert notification could not be sent. " + ex5.Message + " at", ex5.InnerException); this.WriteStackTrace("CustomAlertHandler", ex5.InnerException.StackTrace); } return true; } private List GetAlertTargets(SPAlertHandlerParams alertHandlerParams, SPWeb web, SPAlert alert) { if (alert == null) { throw new ArgumentNullException("alert"); } List list = new List(); if (alert.Properties.ContainsKey("AlertGroups") && alert.Properties["AlertGroups"] != null) { string text = alert.Properties["AlertGroups"]; if (!string.IsNullOrEmpty(text)) { string[] array = SerializationUtil.Deserialize(text); if (array != null && array.Length > 0) { string[] notificationList = SPUserUtil.GetNotificationList(web, array); list.AddRange(notificationList); } } } else { if (!string.IsNullOrEmpty(alert.DynamicRecipient)) { if (alert.Properties.ContainsKey("AMCustomDynamicRecipient")) { if (alert.Properties["AMCustomDynamicRecipient"].ToLower().Contains(this.m_amCustomPrefix)) { SPListItem sPListItem = null; try { foreach (SPListItem sPListItem2 in alert.List.Items) { if (sPListItem2.ID == alertHandlerParams.eventData[0].itemId) { sPListItem = sPListItem2; break; } } } catch (Exception e) { this.WriteExceptionTrace("CustomAlertHandler", "Error getting list item for alert's list " + alert.List.Title + ". ", e); List result = list; return result; } if (!(sPListItem.ContentType.Name == "Message") || alert.List.ContentTypes["Discussion"] == null || !(alert.Properties["AMCustomDynamicRecipient"].ToLower().Replace(this.m_amCustomPrefix, "") == "discussion created by")) { return list; } SPListItem sPListItem3 = null; try { string text2 = SPUtility.GetUrlDirectory(sPListItem.Url); text2 = web.Url + "/" + text2; sPListItem3 = web.GetListItem(text2); goto IL_251; } catch (Exception e2) { this.WriteExceptionTrace("CustomAlertHandler", "Error getting item's parent Discussion folder for item " + sPListItem.Title + ". ", e2); List result = list; return result; } IL_228: SPListItem listItem = web.GetListItem(SPUtility.GetUrlDirectory(sPListItem3.Url)); if (listItem == null) { throw new Exception("Unable to obtain Message's parent Discussion folder."); } sPListItem3 = listItem; IL_251: if (!(sPListItem3.ContentType.Name != "Discussion")) { string text3 = sPListItem3["Author"].ToString(); SPUser sPUser = null; try { int length = text3.IndexOf(";"); int num = int.Parse(text3.Substring(0, length)); sPUser = web.AllUsers.GetByID(num); } catch (Exception e3) { this.WriteExceptionTrace("CustomAlertHandler", "Error getting Discussion Created By user object for " + text3 + ". ", e3); List result = list; return result; } list.Add(sPUser.Email); return list; } goto IL_228; } } else { if (alertHandlerParams.headers.ContainsKey("to") && !string.IsNullOrEmpty(alertHandlerParams.headers["to"])) { list.Add(alertHandlerParams.headers["to"]); } } } else { if (alert.User != null && !string.IsNullOrEmpty(alert.User.Email)) { list.Add(alert.User.Email); } } } return list; } public void WriteTrace(string category, string message) { TraceProvider.WriteTrace(0u, TraceProvider.TraceSeverity.Medium, Guid.Empty, this.ExeName, this.ProductName, category, message); WriteLogs(message); } public void WriteTrace(TraceProvider.TraceSeverity severity, string category, string message) { TraceProvider.WriteTrace(0u, severity, Guid.Empty, this.ExeName, this.ProductName, category, message); WriteLogs(message); } public void WriteErrorTrace(string category, string message) { TraceProvider.WriteTrace(0u, TraceProvider.TraceSeverity.Exception, Guid.Empty, this.ExeName, this.ProductName, category, message); WriteLogs(message); } public void WriteExceptionTrace(string category, string message, Exception e) { this.WriteErrorTrace(category, message); WriteLogs(message); if (e == null) { return; } this.WriteErrorTrace(category, e.Message); WriteLogs(e.ToString()); if (!string.IsNullOrEmpty(e.StackTrace)) { this.WriteErrorTrace(category, e.StackTrace); } } private void WriteStackTrace(string category, string stackTrace) { this.WriteErrorTrace(category, string.Format("Stack Trace:", new object[0])); int num = 700; int num2; for (int i = 0; i < stackTrace.Length; i += num2) { if (stackTrace.Length - i >= num) { num2 = num; } else { num2 = stackTrace.Length - i; } this.WriteErrorTrace(category, string.Format("....{0}", stackTrace.Substring(i, num2))); } } public void WriteLogs(string log) { FileStream fs = null; StreamWriter sw = null; try { string _strPath = "C://temp/SPSolutionsLogsAlerts.txt"; // string ColumnNames = "SiteName,PageName,Event/Method,QueryDetails,QueryLog,Date"; fs = File.Open(_strPath, FileMode.Append, FileAccess.Write); sw = new StreamWriter(fs); sw.WriteLine(log + "\n"); //sw.Close(); } catch (Exception) { // } finally { if (sw != null) { sw.Close(); } if (fs != null) { fs.Close(); } } } } }