设为首页 收藏本站
查看: 665|回复: 0

[经验分享] sharepoint计时器(定时发邮件)

[复制链接]

尚未签到

发表于 2015-9-26 12:05:52 | 显示全部楼层 |阅读模式
做这个定时器Andrew Connell的博客给我很大的帮助。里面有所有的源代码,思路也很清晰
http://www.andrewconnell.com/blog/articles/CreatingCustomSharePointTimerJobs.aspx


主要是继承SpJobDefinition,改写几个构造体和Execute的方法.基本代码的模式就是这个样子:
下面是自己的一段代码有些凌乱:

  1 DSC0000.gif class EventCheckTimesSendEmail : SPJobDefinition
  2 DSC0001.gif DSC0002.gif     DSC0003.gif {
  3 DSC0004.gif DSC0005.gif         public EventCheckTimesSendEmail() : base() { }
  4 DSC0006.gif         public EventCheckTimesSendEmail(string _timername, SPWebApplication _wp)
  5            : base(_timername, _wp, null, SPJobLockType.ContentDatabase)
  6        {
  7            this.Title = "SendEmailEventCheckTime";
  8 DSC0007.gif         }
  9        public override void Execute(Guid targetInstanceId)
10        {
11//这些参数都是从OwsTimer.exe.config中读取的。这个文件是自己添加的。参数也可以自己写的。
12            SPWebApplication webApplication = this.Parent as SPWebApplication;
13            SPContentDatabase contentDb = webApplication.ContentDatabases[targetInstanceId];
14            string splistname = ConfigurationManager.AppSettings.Get("ListName");
15            string smtpHost = ConfigurationManager.AppSettings.Get("SmtpHost");
16            string smtpName = ConfigurationManager.AppSettings.Get("SmtpName");
17            string smtpPass = ConfigurationManager.AppSettings.Get("SmtpPass");
18            string emailTitle = ConfigurationManager.AppSettings.Get("EmailTitle");
19            string emailContent = ConfigurationManager.AppSettings.Get("EmailContent");                             
20            string spwebName = ConfigurationManager.AppSettings.Get("SpwebName");
21            SPWeb spweb = contentDb.Sites[0].AllWebs[spwebName];
22            DateTime dt;           
23            foreach (SPListItem spli in spweb.Lists[splistname].Items)
24            {
25                string spff = null;
26               
27                Stream stream = spli.File.OpenBinaryStream();
28                StreamReader sr = new StreamReader(stream);
29                XmlDocument xd = new XmlDocument();
30                xd.LoadXml(sr.ReadToEnd());
31                XmlNamespaceManager xnm = new XmlNamespaceManager(xd.NameTable);
32                xnm.AddNamespace(xd.DocumentElement.Prefix, xd.DocumentElement.NamespaceURI);
33             //XmlNode xnItemDateLine = xd.SelectSingleNode(ItemDateLine, xnm);
34                XmlNode xncommitteeAcion = xd.SelectSingleNode(committeeAcion, xnm);
35                XmlNode xnsubmissionType=xd.SelectSingleNode(submissionType,xnm);
36                dt = Convert.ToDateTime(xd.SelectSingleNode(ItemDateLine, xnm).InnerText);
37
38                TimeSpan ts;
39                DateTime dtNow = DateTime.Now;
40                string monthsStr = xd.SelectSingleNode(renewal, xnm).InnerText;
41                string toemail = itemEmail.ToString();
42
43                int otherMonthNum = 0;
44                string dateunit=null;
45                if (monthsStr.Equals("Other"))
46                {
47                    if (xd.SelectSingleNode(otherRenewal,xnm).InnerText.ToString().Trim() != null)
48                    {
49                        string DateUnits = xd.SelectSingleNode(ItemDateUnits, xnm).InnerText.ToString();
50                        string reOther = xd.SelectSingleNode(otherRenewal, xnm).InnerText.ToString();
51                        otherMonthNum = int.Parse(reOther);
52                        DateTime dtotherDate;
53                        if (DateUnits.Equals("Days"))
54                        {
55                            dtotherDate = dtNow.AddDays(otherMonthNum);
56                            dateunit = "Days";
57                        }
58                        else if (DateUnits.Equals("Months"))
59                        {
60                            dtotherDate = dtNow.AddMonths(otherMonthNum);
61                            dateunit = "Months";
62                        }
63                        else if (DateUnits.Equals("Years"))
64                        {
65                            dtotherDate = dtNow.AddYears(otherMonthNum);
66                            dateunit = "Years";
67                        }
68                        else
69                        { return; }
70                        ts = (dt.Date - dtotherDate.Date);
71                    }
72                    else { return; }
73                }
74                else
75                {
76                    //sendEmail time
77                    string[] monthss = monthsStr.ToString().Trim().Split('M');
78                    otherMonthNum = int.Parse(monthss[0].ToString());
79                    DateTime dtMoth = dtNow.AddMonths(otherMonthNum);
80                    dateunit = "Months";
81                    ts = (dtMoth.Date - dt.Date);                  
82                }
83                string sateTime = otherMonthNum + " " + dateunit + " mails reply";
84                //if (ts.Days == 0)
85                //{
86                //    string to = toemail;
87                //    string title = emailTitle;
88                //    string content = emailContent + ", This " + otherMonthNum + " " + dateunit + " mails reminds ahead of time";
89
90                //  //  string returnValues = SendEmial(smtpHost, smtpName, smtpPass, to, title, content);
91                //}
92                if (ts.Days == 0 && xncommitteeAcion.InnerText.ToString().Equals(actionSates) && !xnsubmissionType.InnerText.ToString().Equals(submissionTypeValue.ToString()) && spli["SatesOfTimer"] == null)
93                {
94                    //Send Email
95                    string to = toemail;
96                    string title = emailTitle;
97                    string content = emailContent + ", This " + otherMonthNum + " " + dateunit + " mails reminds ahead of time";
98                    string returnValues = SendEmial(smtpHost, smtpName, smtpPass, to, title, content);
99
100                    //add a listitem
101                    if (returnValues.Equals("OK"))
102                    {
103                        spli["SatesOfTimer"] = otherMonthNum + " " + dateunit + " mails reply";
104                        spli.Update();
105                        spweb.Update();
106
107                    }
108                }
109                else if (ts.Days == 0 && xncommitteeAcion.InnerText.ToString().Equals(actionSates) && !xnsubmissionType.InnerText.ToString().Equals(submissionTypeValue.ToString()) && !spli["SatesOfTimer"].ToString().Equals(sateTime))
110                {
111                    //Send Email
112                    string to = toemail;
113                    string title = emailTitle;
114                    string content = emailContent + ", This " + otherMonthNum + " " + dateunit + " mails reminds ahead of time";
115                    string returnValues = SendEmial(smtpHost, smtpName, smtpPass, to, title, content);
116
117                    //add a listitem
118                    if (returnValues.Equals("OK"))
119                    {
120                        spli["SatesOfTimer"] = otherMonthNum + " " + dateunit + " mails reply";
121                        spli.Update();
122                        spweb.Update();
123                    }
124                }
125
126            }
127        }
128     
129        private string  SendEmial(string smtpHost, string smtpName, string smtpPass, string to, string title, string content)
130        {
131            MailAddress sendto = new MailAddress(to);
132            MailAddress sendForm = new MailAddress(smtpName);
133            MailMessage _mailMessage = new MailMessage(sendForm, sendto);
134            _mailMessage.Subject = title;
135            _mailMessage.Body = content;
136            _mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
137            SmtpClient _smtpClient = new SmtpClient(smtpHost);
138            _smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;                    
139            _smtpClient.Credentials = new System.Net.NetworkCredential(smtpName, smtpPass);
140
141            try
142            {
143                _smtpClient.Send(_mailMessage);
144                return "OK";
145            }
146            catch (Exception ex)
147            {
148                return ex.Message;   
149            }
150 DSC0008.gif         }     
151
另外一个类就是:

1 class EventCheckTimersInstallerSendEmail : SPFeatureReceiver
2    {
3        const string MY_TASK = "EventCheckTimesSendEmail";
4        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
5        {
6
7        }
8        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
9        {
10
11        }
12        public override void FeatureActivated(SPFeatureReceiverProperties properties)
13        {
14            SPSite spsite = properties.Feature.Parent as SPSite;
15
16            foreach (SPJobDefinition job in spsite.WebApplication.JobDefinitions)
17            {
18                if (job.Name == MY_TASK)
19                    job.Delete();
20            }
21
22            EventCheckTimesSendEmail timer = new EventCheckTimesSendEmail(MY_TASK, spsite.WebApplication);
23
24            //时间写短点是为测试
25            SPMinuteSchedule schedule = new SPMinuteSchedule();
26            schedule.BeginSecond = 0;
27            schedule.EndSecond = 59;
28            schedule.Interval = 59;
29
30            timer.Schedule = schedule;
31            timer.Update();
32            
33        }
34
35        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
36        {
37            SPSite spsite = properties.Feature.Parent as SPSite;
38            foreach (SPJobDefinition job in spsite.WebApplication.JobDefinitions)
39            {
40                if (job.Name == MY_TASK)
41                    job.Delete();
42            }
43        }
44    }接下来就是部署这个写好的定时器。
用Stsadm.exe来部署
  代码写完了以后,还要写一个Feature,这个Feature比较简单,就一个XML文件
  Feature.xml:
  <?xml version="1.0" encoding="utf-8" ?>
  <Feature xmlns="http://schemas.microsoft.com/sharepoint/"
           Id="1F481C17-4FDA-4919-A64A-EAE5C1301B4B"
           Title="Image Validation Checker"
           Description="If any images in the top level site colleciton images are expiring soon,email relative person."
           Scope="Site"
           Hidden="TRUE"
           Version="1.0.0.0"
           ReceiverAssembly="TimerJobControl, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f2aef6a9088f714f"
  ReceiverClass="TimerJobControl.ImageValidationCheckerJobInstaller">
  </Feature>
  剩下的就是把feature装好就好了,假如代码没有出错的话。
  至于怎么Debug这个程序,走以下步骤
把Assembly DLL放到GAC

  • 命令行:iisreset
  • 先Deactivate feature, 然后activate feature.
  • 命令行:net stop SPTimerV3
  • 命令行:net start SPTimerV3
  • Visual Studio: Attach to process: OWSTIMER.EXE
  
这样就OK了。

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-119076-1-1.html 上篇帖子: SharePoint 2013 关于自定义显示列表表单的bug 下篇帖子: Sharepoint 页面里添加.net托管代码
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表