zoukankan      html  css  js  c++  java
  • Birthday Wish Scheduler in C#

    Here we are going to see how to build a windows service for fetching record from database and wishing the person whose birthday falls on that particular day.

    The following figure shows the snapshot of the table, which is being used with this application.

    The service fetches record for the employee whose birthday falls on particular day and sends him a birthday wish through mail.

    Note: Little bit lazy to change the name of the service in the attached code. You can give whatever name to the service that suits you.

    The default code of Service1.cs added by the Wizard looks like here

    using System;

    using System.Collections;

    using System.ComponentModel;

    using System.Data;

    using System.Diagnostics;

    using System.ServiceProcess;

    using System.Data.SqlClient;

    using System.Web.Mail;

    using System.IO;

    namespace BirthdayWish

    {

              public class Service1 : System.ServiceProcess.ServiceBase

              {

                        /// <summary>

                        /// Required designer variable.

                        /// </summary>

                        private System.ComponentModel.Container components = null; 

                        public Service1()

                        {

                                 // This call is required by the Windows.Forms Component Designer.

                                 InitializeComponent();

     

                                 // TODO: Add any initialization after the InitComponent call

                        } 

                        // The main entry point for the process

                        static void Main()

                        {

                                 System.ServiceProcess.ServiceBase[] ServicesToRun;

             

                                 // More than one user Service may run within the same process. To add

                                 // another service to this process, change the following line to

                                 // create a second service object. For example,

                                 //

                                 //   ServicesToRun = new System.ServiceProcess.ServiceBase[] {new Service1(), new

                                 MySecondUserService()};

                                 //

                                 ServicesToRun = new System.ServiceProcess.ServiceBase[] { new Service1() }; 

                                 System.ServiceProcess.ServiceBase.Run(ServicesToRun);

                        }

     

                        /// <summary>

                        /// Required method for Designer support - do not modify

                        /// the contents of this method with the code editor.

                        /// </summary>

                        private void InitializeComponent()

                        {

                                 //

                                 // Service1

                                 //

                                 this.ServiceName = "Service1"; 

                        }

     

                        /// <summary>

                        /// Clean up any resources being used.

                        /// </summary>

                        protected override void Dispose( bool disposing )

                        {

                                 if( disposing )

                                 {

                                           if (components != null)

                                           {

                                                    components.Dispose();

                                           }

                                 }

                                 base.Dispose( disposing );

                        }

     

                        /// <summary>

                        /// Set things in motion so your service can do its work.

                        /// </summary>

                        protected override void OnStart(string[] args)

                        {

                                 // TODO: Add code here to start your service.    

                        }

     

                        /// <summary>

                        /// Stop this service.

                        /// </summary>

                        protected override void OnStop()

                        {

                                 // TODO: Add code here to perform any tear-down necessary to stop your service.

                        }

     

    Adding functionality to the service

     

    /// <summary>

    /// Set things in motion so your service can do its work.

    /// </summary>

    protected override void OnStart(string[] args)

    {

           // TODO: Add code here to start your service.

           SqlConnection conn  = new SqlConnection("Server=localhost;UID=sa;pwd= ;Database=Birthday");

           SqlDataAdapter da = new SqlDataAdapter("select * from Empdata",conn);

           DataSet ds = new DataSet();

           da.Fill(ds);

           foreach(DataRow dr in ds.Tables[0].Rows)

           {

                           DateTime dtDob = (DateTime)dr["emp_dob"];

                           DateTime now = DateTime.Now;

                           string dow = now.DayOfWeek.ToString().ToLower();

                           if (dow=="monday")

                           {

                                        DateTime daybefore = now.AddDays(-1);

                                        if((dtDob.Day == daybefore.Day) && (dtDob.Month == daybefore.Month))

                                        {

                                                 sendmail(dr);

                                        }

                                        if((dtDob.Day == now.Day) && (dtDob.Month == now.Month))

                                        {

                                                 sendmail(dr);

                                        }

                           }

                           else

                           {

                               if((dtDob.Day == now.Day) && (dtDob.Month == now.Month))

                               {

                                       sendmail(dr);                            

                               }

                           }

           }

           ServiceController[] services=ServiceController.GetServices();

           // Iterating each service to check that if a service named

           // Service1 is found then check that its status whether

           // it is running or stopped. If found running then it will

           // stop that service; else it starts that service

           foreach(ServiceController x in services)

           {

                 if(x.DisplayName=="Service1")

                 {

                      if (x.Status==System.ServiceProcess.ServiceControllerStatus.Running)

                      {

                            x.Stop();

                      }

                      else

                      {

                            x.Start();

                      }

                 }

           }

    }

     

    public bool sendmail(DataRow dr1)

    {

              String mailtxt="";

              MailMessage mm = new MailMessage();

              mm.BodyFormat = MailFormat.Html;

              mm.To = dr1["emp_email"].ToString();

              mm.From = "abc@abc.com";

              mm.Subject="Happy Birthday";

              mailtxt = "<font face='verdana' color='#FF9900'><b>"+"Hi "+dr1["emp_name"].ToString()+"," +

              "</b></font><br><br>";

              mailtxt=mailtxt+"<font face='verdana' color='#FF0000'><b>"+"Wishing you a very HAPPY

              BIRTHDAY........and many more." + "</b></font><br><br>";

              mailtxt=mailtxt+"<font face='verdana' color='#008080'><b>"+"May today be filled with sunshine and

              smile, laughter and love." + "</b></font><br><br>";

              mailtxt=mailtxt+"<font face='verdana' color='#0000FF'><b>Cheers!" + "<br><br>";

              mm.Body = mailtxt;

              SmtpMail.SmtpServer = "localhost";

              SmtpMail.Send(mm);

              return(true);

    }

     

    Note: It also checks for person whose birthday falls on Sunday and wishes them on coming Monday.

     

    Install and Run the Service

     

    Build of this application makes one exe, BirthdayWish.exe. You need to call installutil to register this service from command line.

     

    installutil C:\BirthdayWish\ BirthdayWish\in\Debug\ BirthdayWish.exe

     

    You use /u option to uninstall the service.

     

    installutil /u C:\BirthdayWish\ BirthdayWish\in\Debug\ BirthdayWish.exe

     

    Run the application

     

    Note: Path for installutil is c:/windows/Microsoft.NET/Framework/V1.1.4322

     

    Start and Stop the Service

     

    You need to go to the Computer Management to Start to start and stop the service. You can use Manage menu item by right clicking on My Computer. 

     

    Or

     

    You can view the services through Start -> Control Panel -> Administrative Tool -> Services.

     


     

    Here you will see the service Service1. Start and Stop menu item starts and stops the service.

     

    You can also set the properties of the service by right clicking it and clicking the Properties menu.

     

     

    Test the Service

     

    Test by using your own email address and current date in your record. A mail will be sent to your email address. This means that the service is working fine.

     

    That's it.

     

    Until next time... Happy .NETing!

  • 相关阅读:
    新建maven web工程报错
    Linux的系统suspend和resume
    Linux内核配置---menuconfig
    printk()函数学习笔记
    驱动调试笔记
    i2c接口笔记
    无线路由器的加密模式WEP,WPA-PSK(TKIP),WPA2-PSK(AES) WPA-PSK(TKIP)+WPA2-PSK(AES)。
    Linux下sniffer实现(转)
    驱动模块(3)——Linux交叉编译工具链
    ehci ohci 驱动逻辑
  • 原文地址:https://www.cnblogs.com/adam/p/663239.html
Copyright © 2011-2022 走看看