Blue Theme Orange Theme Green Theme Red Theme
 
DevExpress Free UI Controls
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
DevExpress UI Controls
Search :       Advanced Search »
Home » Windows Services » Birthday Wish Scheduler in C#

Birthday Wish Scheduler in C#

In this article 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.

Author Rank :
Page Views : 46823
Downloads : 1903
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
BirthdayWish.zip
 
 
Team Foundation Server Hosting
Become a Sponsor
DevExpress Free UI Controls
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

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!

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Praveen Kumar
I have over 13 years of IT industry experience with Microsoft technologies. I hold Masters degree in Computer Science and Applications and Bachelor’s degree in Mathematics. I am responsible for content publishing, product development, and migration of existing contents. I am also responsible for hiring new team members and managing the existing team. I have been awarded Microsoft MVP for the year 2008, 2009, 2010.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
by vasanth On February 28, 2006

 

I am vasanth

I am new in .net.

Is Possible to retrive value from the service.

If it is possible,how to retrive values from windowsservice to windowsapplication.

reply ur sugession as soon as possible.

Reply | Email | Modify 
started and stopped by Ravindra On October 31, 2006

hello sir,

   I am Ravindra.Currently doing a project in asp.net and i am writing a windows service for my project .which is similar to the article you submitted.

 But sir,when I am starting windows service ,i am getting the following message

"the service1 service on local computer started and then stopped.some services stop automatically if they have no work to do,for example ,the performance logs and alert service"

             and I am not getting any email alerts .

          So, please help.thanks in advance

                                                                  -Ravindra

Reply | Email | Modify 
Re: started and stopped by Anik On November 2, 2006

Hello,

Use SmtpMail.SmtpServer = "smtp"; instead of writing SmtpMail.SmtpServer ="localhost" and the error will disappear and you will also get the email also.

Thanks

Anik

Reply | Email | Modify 
Re: Re: started and stopped by It On January 14, 2008
Hi Has anyone found an anser to the service starting and stopping? I would really like to use this neat little app! I have changed the smtp server from localhost to my smtp server but I think somthing else must be going on here. Thanks
Reply | Email | Modify 
Re: started and stopped by Rishi On October 10, 2008

Hi

I am also getting same error, even i have changed localhost to smtp but not able to startup the win service. Please let me know if some one found the solution.

 

Thanks

Rishi Gupta

Reply | Email | Modify 
Re: Re: started and stopped by Jason On October 17, 2008
any one found solution
same problem

Reply | Email | Modify 
Re: Re: Re: started and stopped by Khushbu On May 26, 2009
facing same problem...
anyone found solution...

its urgent....

khush
Reply | Email | Modify 
Re: Re: Re: Re: started and stopped by Harishankar On June 4, 2010
Same problem... Pl let me know any solution for this.....
Reply | Email | Modify 
You can try Quartz .net by kishan On December 12, 2010
This is great for scheduling process. Try http://quartznet.sourceforge.net
Reply | Email | Modify 
nice article by naresh On August 9, 2011
it is really nice article
Reply | Email | Modify 
Team Foundation Server Hosting
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.