Birthday Wish Scheduler in C#

Here we are going to see how to build a Windows service for fetching records from the 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.

Table design

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

Note. A 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 = "[email protected]";
    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 the person whose birthday falls on Sunday and wishes them on the coming Monday.

Install and Run the Service

The build of this application makes one example, BirthdayWish.exe. You need to call installutil to register this service from the 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. The path for installation is c:/windows/Microsoft.NET/Framework/V1.1.4322

Start and Stop the Service

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

Or

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

Control Panel

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.

Properties

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!


Similar Articles
C# Corner
C# Corner started as an online community for software developers in 1999.