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

Update SharePoint UserInfo List with More Active Directory Info

Rate me:
Please Sign up or sign in to vote.
4.45/5 (5 votes)
19 Mar 2009CPOL2 min read 59.7K   371   16  
Shows how to write a job that updates the UserInfo list with more Active Directory information.
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.IO;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Mullivan.Collections.Generic;
using System.Net.Mail;
using System.Data;
using System.Diagnostics;
using System.Xml.Xsl;
using System.Net;

namespace Mullivan.SharePoint.Reminders
{
    public class RmdJobDefinition : SPJobDefinition
    {
        internal const string _JOBNAME = "Scheduled Reminder Job";

        public RmdJobDefinition () : base() { }

        public RmdJobDefinition(SPWebApplication webApp)
            : base(_JOBNAME, webApp, null, SPJobLockType.Job)
        {
            this.Title = _JOBNAME;
        }

        public override void Execute(Guid targetInstanceId)
        {
            int poolCount = 0;
            DateTime dtStart = DateTime.Now;
            RmdProcessCounter counter = new RmdProcessCounter();
            
            try
            {
                if (this.WebApplication.OutboundMailServiceInstance == null)
                    throw new Exception("E-mail is not set up for this Web Application.");
                if (string.IsNullOrEmpty(this.WebApplication.OutboundMailSenderAddress))
                    throw new Exception("Outbound mail sender address is required for this feature.");

                foreach (SPSite spSite in this.WebApplication.Sites)
                {
                    Trace(string.Format("Processing SPSite {0}", spSite.Url));
                    //Increment pool count so we have a reference to how many
                    //threads are running
                    poolCount++;

                    RmdProcessSPSiteContext context = new RmdProcessSPSiteContext();
                    //Pass the counter so that each thread can record
                    //when it is finished processing
                    context.Counter = counter;
                    context.Site = spSite;

                    ThreadPool.QueueUserWorkItem(ProcessSPSite, context);
                }
 

                //Wait until all threads are done processing
                while (counter.Count < poolCount)
                {
                    Thread.Sleep(1000);
                }
            }
            catch (Exception ex)
            {
                Logging.ServiceLog.LogException(ex);
            }

            base.Execute(targetInstanceId);
        }

        private void ProcessSPSite(object state)
        {
            RmdProcessSPSiteContext context = (RmdProcessSPSiteContext)state;
            SPSite spSite = null;
            try
            {
                spSite = context.Site;

                foreach (SPWeb spWeb in spSite.AllWebs)
                {
                    Trace(string.Format("Processing SPWeb {0}", spWeb.Url));
                    ProcessSPWeb(spWeb, context);
                    spWeb.Dispose();
                }
            }
            catch (Exception ex)
            {
                Logging.ServiceLog.LogException(ex);
            }
            finally
            {
                context.Counter.Increment();
                spSite.Dispose();
            }
        }

        private void ProcessSPWeb(SPWeb spWeb, RmdProcessSPSiteContext context)
        {
            foreach (SPList list in spWeb.Lists)
            {
                try
                {
                    Trace(string.Format("Processing SPList {0} in SPWeb {1}", list.Title, spWeb.Url));
                    ProcessList(list, context);
                }
                catch (Exception ex)
                {
                    Logging.ServiceLog.LogException(ex);
                }
            }
        }

        private void ProcessList(SPList list, RmdProcessSPSiteContext context)
        {
            string emailBody = string.Empty;
            string strXml = string.Empty;
            XsltArgumentList argList = null;
            MailAddress[] mailToAddresses = null;
            List<RmdConfiguration> rmdConfigs = null;
            SPListItemCollection items = null;

            rmdConfigs = RmdUtil.GetRmdConfigs(list);
            //There is no configuration so just move on
            if (rmdConfigs == null)
            {
                Trace(string.Format("Configuration not found for SPList {0}.", list.Title));
                return;
            }

            //Process each Reminder in the configuration
            foreach (RmdConfiguration rmdConfig in rmdConfigs)
            {

                //Check if it's eligable to run
                if (rmdConfig.Recurrence.CanRun(rmdConfig.LastRun))
                {
                    Trace(string.Format("RmdConfig {0} executing for SPList {0}.", rmdConfig.DisplayName, list.Title));
                    //Get the items for the list
                    items = MullivanUtility.ExecuteQuery(list, rmdConfig.Query, rmdConfig.ViewFields, 2000);

                    if (items.Count > 0 || rmdConfig.SendNoResults)
                    {
                        //Get the argument list for the transform
                        argList = RmdUtil.GetXsltArgList(list);

                        if (rmdConfig.Type == RmdType.Bulk)
                        {
                            //Convert the items to xml
                            strXml = RmdUtil.GetXml(items);

                            mailToAddresses = RmdUtil.GetMailToAddresses(rmdConfig.MailTo, null, list);

                            //Transform the items into html
                            emailBody = MullivanUtility.RenderHtml(strXml, argList, rmdConfig.XslTransform);

                            SendEmail(mailToAddresses, rmdConfig.Subject, emailBody);
                        }
                        else // Item Mode
                        {
                            //Go through each item and send the email
                            for (int i = 0; i < items.Count; i++)
                            {
                                SPListItem spItem = items[i];

                                strXml = RmdUtil.GetXml(spItem);

                                mailToAddresses = RmdUtil.GetMailToAddresses(rmdConfig.MailTo, spItem, list);
                                //Transform the item into html

                                emailBody = MullivanUtility.RenderHtml(strXml, argList, rmdConfig.XslTransform);

                                SendEmail(mailToAddresses, rmdConfig.Subject, emailBody);
                            }
                        }
                    }

                    //Set the LastRun to the current time and then save it back to the 
                    //ParentWeb PropertyBag
                    rmdConfig.LastRun = DateTime.Now;
                    RmdUtil.SetRmdConfigs(list, rmdConfigs);

                }
                else
                    Trace(string.Format("RmdConfig {0} is not ready to run for SPList {0}.", rmdConfig.DisplayName, list.Title));
            }
        }

        private void SendEmail(MailAddress[] masTo, string subject, string body)
        {
            using (MailMessage mail = new MailMessage())
            {
                mail.From = new MailAddress(this.WebApplication.OutboundMailSenderAddress);
                foreach (MailAddress ma in masTo)
                    mail.To.Add(ma);
                mail.Subject = subject;
                mail.IsBodyHtml = true;
                mail.Body = body;

                SmtpClient smtp = new SmtpClient(this.WebApplication.OutboundMailServiceInstance.Server.Address);
                
                smtp.UseDefaultCredentials = (smtp.Credentials == null);
                smtp.Send(mail);
            }
        }

        private void Trace(string message)
        {
            System.Diagnostics.Trace.WriteLine(message, _JOBNAME);
        }
    }
}

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