次の方法で共有


SharePoint Timer Job to get weekly updates

Timer Jobs are jobs that run periodically at specific time (scheduled times).

Recently I worked on a project where we need to get weekly updates of the Wiki Pages created and modified in a SharePoint site. So we created a timer job that runs a CAML query to get the created and modified items from the Wiki Page library.

(The below can be used to get updates for any list. I will talk about it at the end of this blog post.)

BELOW IS THE CODE

 

 using System;

 using System.Collections.Generic;

 using System.Linq;

 using System.Text;

 using Microsoft.SharePoint;

 using System.Net.Mail;

 using System.Configuration;

 

namespace Timerjob1

{

     class Program

     {

         static void Main(string[] args)

         {

             LogInfo("Job Started" + System.DateTime.Now.ToLongDateString());

             StringBuilder stBody = null; 

             SPQuery createdquery = new SPQuery();

             SPQuery modifiedquery = new SPQuery();

             SPSite site = new SPSite(ConfigurationSettings.AppSettings["SiteURL"].ToString());

             SPWeb web = site.OpenWeb();

             SPList list = web.Lists[ConfigurationSettings.AppSettings["ListName"].ToString()];

             int CreatedCount, ModifiedCount;

             SPListItem newlistitem = null;

             SPListItem updatedlistitem = null;

             if (list != null)

             {

                         stBody = new StringBuilder();

                         stBody.Append("<HTML><BODY style=\"font-family:Verdana;font-size:9pt;\" ><br>");

                         stBody.Append("<br>Here are the newest posts on the Codehouse Wiki this week.<br>");

                         stBody.Append("<br><table width=\"100%\" style=\"font-family:Verdana;font-size:9pt;\"><tr><U><b>New Entries</b></U></tr>");

                       createdquery.Query = "<Where><Gt><FieldRef Name='Created' /><Value IncludeTimeValue='TRUE' Type='DateTime'>" + System.DateTime.Now.AddDays(-7).Year.ToString() + "-" + System.DateTime.Now.AddDays(-7).Month.ToString() + "-" + System.DateTime.Now.AddDays(-7) + "T" + "00:00:00Z</Value></Gt></Where>";

                         modifiedquery.Query = "<Where><Gt><FieldRef Name='Modified' /><Value IncludeTimeValue='TRUE' Type='DateTime'>" + System.DateTime.Now.AddDays(-7).Year.ToString() + "-" + System.DateTime.Now.AddDays(-7).Month.ToString() + "-" + System.DateTime.Now.AddDays(-7) + "T" + "00:00:00Z</Value></Gt></Where>";

             }

       //Created Items in Announcements

            SPListItemCollection createditems = list.GetItems(createdquery);

           CreatedCount = createditems.Count;

           if (CreatedCount > 0)

           {

            //   Console.WriteLine("Created Items are as below :");

               for (int i = 0; i < CreatedCount; i++)

               {

                    newlistitem = createditems[i];

                  // Console.WriteLine(newlistitem.Name);

                   stBody.Append("<tr>" + "<a href='" + ConfigurationSettings.AppSettings["ListURL"].ToString() + newlistitem.Name + "'><b>" + newlistitem.Name + "</b></a></tr>");

               }

            }

       else

           {

               Console.WriteLine("No Wiki Entries have been added this week");

                stBody.Append("<tr>No Wiki Entries have been added this week</tr>");

           }

            Console.Read();

           //Modified Items in Announcements

           stBody.Append("<br><br>");

           stBody.Append("<tr><U><b>Updated Entries</b></U></tr>");

           SPListItemCollection modifieditems = list.GetItems(modifiedquery);

           ModifiedCount = modifieditems.Count;

           CreatedCount = createditems.Count;

           bool flag = false;

           int checkmodified = ModifiedCount;

           if (ModifiedCount > 0)

           {

             // Console.WriteLine("Modified Items are as below :");

               for (int i = 0; i < ModifiedCount; i++)

                {

                   for (int j = 0; j < CreatedCount; j++)

                    {

                       if (modifieditems[i].Name == createditems[j].Name)

                        {

                            flag = true;

                            checkmodified--;

                            break;

                       }

 

                   }

 

                   if (!flag)

                    {

                        updatedlistitem = modifieditems[i];

                       //Console.WriteLine(updatedlistitem.Name);

                        stBody.Append("<tr>" + "<a href='" + ConfigurationSettings.AppSettings["ListURL"].ToString() + updatedlistitem.Name + "'><b>" + updatedlistitem.Name + "</b></a></tr>");

                    }

            }

    }

 else

           {

                //Console.WriteLine("No Wiki pages have been modified this week");

                stBody.Append("<tr>No Wiki Entries have been added this week</tr>");

            }

            if (checkmodified == 0)

             {

               //Console.WriteLine("No Wiki pages have been modified this week");

               stBody.Append("<tr>No Wiki Entries have been added this week</tr>");

            }

       stBody.Append("</table></BODY></HTML>");

       //   Console.Read();

        SendMail(ConfigurationSettings.AppSettings["ToUser"].ToString(), "", "", ConfigurationSettings.AppSettings["Subject"].ToString(), stBody.ToString());

          LogInfo("Job Ended" + System.DateTime.Now.ToLongDateString());

        }

        public static void SendMail(string strToUsers, string strCcUsers, string strBCcUsers, string strSubject, string strMailBody)

         {

           try

            {

                SmtpClient smtpClient = new SmtpClient();

               MailMessage message = new MailMessage();

                 //From Address

                 //MailAddress fromAddress = new MailAddress(ConfigurationManager.AppSettings["FromAddress"].ToString());

                 MailAddress fromAddress = new MailAddress(ConfigurationSettings.AppSettings["FromAddress"].ToString());

                // You can specify the host name or ipaddress of your server

                 // Default in IIS will be localhost 

                smtpClient.Host = ConfigurationSettings.AppSettings["SMTP IP"].ToString();

                 //Default port will be 25

                 smtpClient.Port = 25;

                 //From address will be given as a MailAddress Object

                 message.From = fromAddress;

                 //To Users

                 if (strToUsers.IndexOf(',') != -1)

                 {

                     string[] strToMailIds = strToUsers.Split(',');

                    for (int intCount = 0; intCount < strToMailIds.Length; intCount++)

                     {

                        message.To.Add(strToMailIds[intCount]);

                     }

                 }

                 else 

                {

                    // To address collection of MailAddress

                    message.To.Add(strToUsers);

                }

                //Email Subject

                message.Subject = strSubject;

                //Cc Users

                if (strCcUsers != string.Empty)

                {

                    if (strCcUsers.IndexOf(',') != -1)

                    {

                        string[] strCcMailIds = strCcUsers.Split(',');

                        for (int intCount = 0; intCount < strCcMailIds.Length; intCount++)

                        {

                            message.CC.Add(strCcMailIds[intCount]);

                        }

                    }

                    else

                    {

                        // To address collection of MailAddress

                        message.CC.Add(strCcUsers);

                    }

                 }

                //BCc Users

                if (strBCcUsers != string.Empty)

                {

                    if (strBCcUsers.IndexOf(',') != -1)

                    {

                        string[] strBCcMailIds = strBCcUsers.Split(',');

                        for (int intCount = 0; intCount < strBCcMailIds.Length; intCount++)

                        {

                            message.Bcc.Add(strBCcMailIds[intCount]);

                        }

                    }

                    else

                    {

                       // To address collection of MailAddress

                        message.Bcc.Add(strBCcUsers);

                    }

                }

 

                //Body can be Html or text format

                //Specify true if it  is html message

                message.IsBodyHtml = true;

                // Message body content

                message.Body = strMailBody;

                // Send SMTP mail

                smtpClient.Send(message);

            }

            catch (Exception ex)

            {

                LogInfo(ex.Message);

            }

 

        }

  public static void LogInfo(string strMessage)

        {

            System.IO.StreamWriter objWriter = new System.IO.StreamWriter(ConfigurationSettings.AppSettings["Loginfofile"].ToString(), true);

            objWriter.WriteLine(strMessage);

            objWriter.Close();

        }

 

    }

 

}

  

You will also need to create application configuration file where you need to add the below code.

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

   <appSettings>

       <add key="ToUser" value="adam@sample.com"/>

      <add key="Subject" value="Wiki Articles"/>

      <add key="Loginfofile" value="C://Logfile/log.txt"/>

       <add key="SiteURL" value="https://sp1/"/>

       <add key="ListName" value="Wiki Pages"/>

       <add key="SMTP IP" value="158.152.10.8"/>

       <add key ="FromAddress" value="sharepointadmin@sample.com"/>

       <add key="ListURL" value="https://sp1/Wiki%20Pages/"/> 

  </appSettings>

</configuration>

  

In the above code, you can enter your List such as announcement or Tasks or any custom list name. Enter the from and to address and you are ready to use it.

*Also do change the SMTP IP address to your SMTP server IP.

Once its complied and runs successfully, give the generated exe to Windows Task Scheduler and specify the date when this should run.

Hope this was helpful.

 

TimerJob.docx