Blue Theme Orange Theme Green Theme Red Theme
 
Click Here for 3 Month Free of ASP.NET Hosting!
Home | Forums | Videos | Photos | Downloads | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
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:
Technologies: ,Visual C# .NET
Total downloads : 1159
Total page views :  30175
Rating :
 4.75/5
This article has been rated :  4 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
BirthdayWish.zip
 
Become a Sponsor



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!


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Praveen Moosad
I have over 10 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 MVP for the year 2008.
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.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Microsoft Visual Studio 2010 offers more to developers than any other Visual Studio release. Work more productively and collaboratively-with greater control over your work at every step. The Beta 2 can give you a head start on achieving efficiency.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
BirthdayWish.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Dundas Dashboard
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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | Modify | 
Re: Re: started and stopped by Jason On October 17, 2008
any one found solution
same problem

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

its urgent....

khush
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved