Click here to Skip to main content
15,894,405 members
Articles / Web Development / ASP.NET

Send scheduled Reminder/Alerts by email in SharePoint

Rate me:
Please Sign up or sign in to vote.
4.87/5 (14 votes)
24 Mar 2009CPOL12 min read 593.7K   2.1K   67  
Learn how to create a SharePoint Job that queries lists and sends results via email.
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using Microsoft.SharePoint;
using System.IO;
using System.Web.UI;
using System.Xml.Xsl;
using System.Net.Mail;
using System.Data;
using Mullivan.Collections.Generic;
using Microsoft.SharePoint.Administration;
using System.Web;
using System.Reflection;

namespace Mullivan.SharePoint.Reminders
{
    public static class RmdUtil
    {
        public static string GetConfigName(Guid listId)
        {
            return listId.ToString().Replace("-","") + "_RmdConfig";
        }

        public static SPListItemCollection ExecuteQuery(SPList list, string query, string viewFields)
        {
            SPQuery spQuery = new SPQuery();

            if (query != null)
                query = query.Trim();
            if(viewFields != null)
                viewFields = viewFields.Trim();

            if (!string.IsNullOrEmpty(query))
                spQuery.Query = query;
            else
                spQuery.Query = "<Where></Where>";
            spQuery.IncludeAttachmentUrls = true;
            spQuery.ViewFields = viewFields;
            spQuery.ViewAttributes = "Scope=\"Recursive\"";
            return list.GetItems(spQuery);
        }

        public static string RenderHtml(string strXml, XsltArgumentList argList, string strXsl)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<html>");
            using (TextWriter textWriter = new StringWriter(sb))
            {
                using (HtmlTextWriter writer = new HtmlTextWriter(textWriter))
                {
                    using (StringReader srXsl = new StringReader(strXsl))
                    {
                        using (XmlTextReader xrXsl = new XmlTextReader(srXsl))
                        {
                            using (StringReader srXml = new StringReader(strXml))
                            {
                                using (XmlTextReader xrXml = new XmlTextReader(srXml))
                                {
                                    XslCompiledTransform cmplTrans = new XslCompiledTransform();

                                    cmplTrans.Load(xrXsl);


                                    XmlWriterSettings settings = new XmlWriterSettings();
                                    settings.CheckCharacters = false;
                                    settings.ConformanceLevel = ConformanceLevel.Fragment;
                                    using (XmlWriter xwHtml = XmlWriter.Create(writer, settings))
                                    {
                                        cmplTrans.Transform(xrXml, argList, xwHtml);
                                    }
                                }
                            }
                        }
                    }
                }
                textWriter.Flush();
            }
            sb.Append("</html>");
            return sb.ToString();
        }

        /// <summary>
        /// This method filters or sets and mail addresses that are related to items
        /// </summary>
        /// <param name="mailToAddresses"></param>
        /// <param name="item"></param>
        /// <returns></returns>
        public static MailAddress[] GetMailToAddresses(string[] mailToAddresses, SPListItem item, SPList list)
        {
            if (mailToAddresses == null || mailToAddresses.Length == 0)
                throw new Exception("Email can not be sent when there are no emails supplied.");
            List<MailAddress> addresses = new List<MailAddress>();

            foreach (string strAddress in mailToAddresses)
            {
                if (strAddress.StartsWith("[#") && strAddress.EndsWith("#]"))
                {
                    if (item == null)
                        continue;

                    MailAddress ma = GetMailAddress(strAddress, item, list);
                    if (ma != null)
                        addresses.Add(ma);
                }
                else
                    addresses.Add(new MailAddress(strAddress));
            }

            return addresses.ToArray();
        }

        private static MailAddress GetMailAddress(string strAddress, SPListItem item, SPList list)
        {
            try
            {
                string userName = string.Empty;
                string[] vals = null;
                switch (strAddress.ToLower())
                {
                    case "[#assign to#]":
                        vals = item.Properties["ows_AssignedTo"].ToString().Split(new string[1] { ";#" }, StringSplitOptions.RemoveEmptyEntries);
                        if (vals.Length > 1)
                            userName = vals[1];
                        break;
                    case "[#modified by#]":
                        vals = item.Properties["ows_Editor"].ToString().Split(new string[1] { ";#" }, StringSplitOptions.RemoveEmptyEntries);
                        if (vals.Length > 1)
                            userName = vals[1];
                        break;
                    case "[#author#]":
                        vals = item.Properties["ows_Author"].ToString().Split(new string[1] { ";#" }, StringSplitOptions.RemoveEmptyEntries);
                        if (vals.Length > 1)
                            userName = vals[1];
                        break;
                    case "[#checkout user#]":
                        if (item.File != null && item.File.CheckedOutBy != null)
                            return new MailAddress(item.File.CheckedOutBy.Email);
                        break;
                    default:
                        string fieldName = strAddress.Substring(2, strAddress.Length - 2);
                        fieldName = fieldName.Substring(0, fieldName.Length - 2);
                        vals = item.Properties["ows_" + fieldName].ToString().Split(new string[1] { ";#" }, StringSplitOptions.RemoveEmptyEntries);
                        if (vals.Length > 1)
                            userName = vals[1];
                        break;
                }

                using (SPWeb web = list.ParentWeb)
                {
                    SPListItem user = GetUserInfo(web, userName);

                    if (user == null)
                        return null;

                    object email = user["EMail"];
                    if (email != null)
                        return new MailAddress(email.ToString());
                    else
                        return null;
                }
            }
            catch (Exception ex)
            {
                Logging.ServiceLog.LogException(ex);
                return null;
            }
        }

        public static void GetFullListUrls(SPList list, out string defaultViewUrl, out string imageUrl, out string url, out string editFormUrl, out string siteUrl)
        {
            string serverUrl = string.Empty;
            defaultViewUrl = list.DefaultViewUrl;

            using (SPWeb web = list.ParentWeb)
            {
                using (SPSite site = web.Site)
                {
                    serverUrl = RmdUtil.GetServerUrl(site);
                    siteUrl = web.Url;
                    imageUrl = siteUrl + list.ImageUrl;
                    url = siteUrl + "/" + list.RootFolder.Url.Replace(" ", "%20");
                    editFormUrl = siteUrl + "/";
                    PropertyInfo piEditFormUrl = typeof(SPList).GetProperty("EditFormUrl", BindingFlags.NonPublic | BindingFlags.Instance);
                    editFormUrl += piEditFormUrl.GetValue(list, null).ToString().Replace(" ", "%20");

                    if (list.BaseTemplate == SPListTemplateType.UserInformation)
                    {
                        if (!(web.ServerRelativeUrl == "/"))
                            defaultViewUrl = web.ServerRelativeUrl + "/_layouts/people.aspx";
                        else
                            defaultViewUrl = web.ServerRelativeUrl + "_layouts/people.aspx";
                    }

                    defaultViewUrl = serverUrl + defaultViewUrl.Replace(" ", "%20");
                }
            }
        }

        public static string GetServerUrl(SPSite site)
        {
            string port = site.Port.ToString();

            if (port == null || port == "80" || port == "443")
                port = "";
            else
                port = ":" + port;

            string protocol = site.Protocol + "//";

            // *** Figure out the base Url which points at the application's root

            return (protocol + site.HostName + port).TrimEnd('/');
        }

        public static List<RmdConfiguration> GetRmdConfigs(SPList list)
        {
            string configName = GetConfigName(list.ID);
            string configuration = string.Empty;

            //I used the ParentWeb because the SPList object doesn't have a property bag
            using (SPWeb web = list.ParentWeb)
            {
                if (web.Properties.ContainsKey(configName))
                    configuration = list.ParentWeb.Properties[configName];
            }

            if (string.IsNullOrEmpty(configuration))
                return null;

            return RmdConfiguration.ReadConfigurations(configuration);
        }

        public static void SetRmdConfigs(SPList list, List<RmdConfiguration> rmdConfigs)
        {
            string configName = GetConfigName(list.ID);
            string configuration = string.Empty;

            //I used the ParentWeb because the SPList object doesn't have a property bag
            configuration = RmdConfiguration.WriteConfigurations(rmdConfigs);
            using (SPWeb web = list.ParentWeb)
            {
                if (!web.Properties.ContainsKey(configName))
                    web.Properties.Add(configName, configuration);
                else
                    web.Properties[configName] = configuration;
                web.Properties.Update();
                web.Update();
            }
        }

        public static RmdConfiguration FindReminder(Guid id, List<RmdConfiguration> rmdConfigs)
        {
            foreach(RmdConfiguration rmdConfig in rmdConfigs)
            {
                if (rmdConfig.Id == id)
                    return rmdConfig;
            }
            return null;
        }

        public static SPListItem GetUserInfo(SPWeb web, string loginName)
        {
            try
            {
                SPUser u = web.SiteUsers[loginName];
                
                if (u == null)
                    return null;

                SPList userList = web.SiteUserInfoList;
                SPQuery query = new SPQuery();

                query.ViewFields = "<FieldRef Name=\"ContentTypeId\"/><FieldRef Name=\"ContentType\"/><FieldRef Name=\"Title\"/><FieldRef Name=\"Name\"/><FieldRef Name=\"EMail\"/><FieldRef Name=\"JobTitle\"/><FieldRef Name=\"WorkCity\"/><FieldRef Name=\"WorkState\"/><FieldRef Name=\"WorkCountry\"/>";
                query.Query = string.Format(@"<Where><Eq><FieldRef Name='ID'/><Value Type='Int'>{0}</Value></Eq></Where>", u.ID); // u.ID is the ID of logged in user

                SPListItemCollection items = userList.GetItems(query);
                if(items.Count > 0)
                    return items[0];
            }
            catch (Exception ex)
            {
                Logging.ServiceLog.LogException(ex);
            }
            return null;
        }

        public static XsltArgumentList GetXsltArgList(SPList list)
        {
            XsltArgumentList argList = new XsltArgumentList();
            string defaultViewUrl, siteUrl, url, imageUrl, editFormUrl;

            RmdUtil.GetFullListUrls(list, out defaultViewUrl, out imageUrl, out url, out editFormUrl, out siteUrl);

            
            argList.AddParam("listId", "", list.ID.ToString());
            argList.AddParam("listTitle", "", list.Title);
            argList.AddParam("listUrl", "", url);
            argList.AddParam("listImageUrl", "", imageUrl);
            argList.AddParam("listEditFormUrl", "", editFormUrl);
            argList.AddParam("listDefaultViewUrl", "", defaultViewUrl);
            argList.AddParam("siteUrl", "", siteUrl);

            return argList;
        }

        public static string GetXml(SPListItem item)
        {
            return string.Format(
@"<xml xmlns:s='uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882' 
xmlns:dt='uuid:C2F41010-65B3-11d1-A29F-00AA00C14882' 
xmlns:rs='urn:schemas-microsoft-com:rowset' 
xmlns:z='#RowsetSchema'> 
<rs:data ItemCount=""1"">
{0} 
</rs:data> 
</xml>", item.Xml);
        }

        public static string GetXml(SPListItemCollection spItems)
        {
            string strXml = spItems.Xml;

            XmlDocument xDoc = new XmlDocument();
            xDoc.LoadXml(strXml);

            XmlNode xnSchema = xDoc.DocumentElement.ChildNodes[0];
            xDoc.DocumentElement.RemoveChild(xnSchema);

            return xDoc.InnerXml;
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions