Solved

window service in c#

Posted on 2014-10-10
8
193 Views
Last Modified: 2014-10-24
I have below codes working fine in window service. Can you show me how to use timer?
My goal is to send email daily at 1:00 am (PST).

Thanks


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceProcess;
using System.Net.Mail;
using System.Threading;

namespace ConsoleApplication1
{
    class Program : ServiceBase
    {
        static void Main(string[] args)
        {
            ServiceBase.Run(new Program());
        }
        public Program()
        {
            this.ServiceName = "My Service";
        }

       protected override void OnStart(string[] args)
          {
            base.OnStart(args);
            //TODO: place your start code here
             
            #region main code
            sendSingleEmail("email", "email", "test", "test", true);
            #endregion



          }
        protected override void OnStop()
          {
            base.OnStop();
            //TODO: clean up any variables and stop any threads
          }

        #region method:send email
        public static void sendSingleEmail(string from, string to, string subject, string body, bool isHtml)
        {
            String smtpServer = "smtp.com";
            System.Net.Mail.MailMessage MyMessage = new System.Net.Mail.MailMessage();
            MyMessage.Subject = subject;
            MyMessage.Body = body;
            MyMessage.From = new MailAddress(from);
            MyMessage.To.Add(to);
            MyMessage.IsBodyHtml = isHtml;
            SmtpClient emailClient = new SmtpClient(smtpServer,25);
            emailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            emailClient.EnableSsl = false;
            emailClient.Send(MyMessage);            
        }
        #endregion
    }
     
}
0
Comment
Question by:ITsolutionWizard
  • 3
  • 2
  • 2
  • +1
8 Comments
 
LVL 40

Expert Comment

by:Kyle Abrahams
ID: 40373987
You shouldn't use a service for this.  A service is something that runs constantly, looping at an interval to perform tasks.  There is no reason to keep your program in memory for that long if all your doing is sending an email once every day.

What I would recommend is a windows console application that when launched will send your email.  This is then scheduled via a scheduled task on a server/workstation.
0
 
LVL 69

Expert Comment

by:Éric Moreau
ID: 40374046
I have applications like this that need to run at interval. I always build plain-old Windows Forms and I schedule them in the Windows Tasks Scheduler. This way, it is easy for me to run anytime, to debug, ...

Check http://emoreau.com/Entries/Articles/2008/11/Passing-arguments-to-an-application-startup.aspx
0
 

Expert Comment

by:CHARU T
ID: 40377723
Its best written as a winforms program with Timer class and its tick() used to send the email with smtpclient. Registering as a service is needed when it actually is a product. It can be run as a background task as well thats starts at windows restart.
0
 
LVL 69

Expert Comment

by:Éric Moreau
ID: 40378216
what I don't like about a Windows app with a Timer is if an error occurs, it is sometime not able to restart properly. If it is a scheduler that runs it, it always starts fresh. Also, a schedule task can run even if the computer is not logged on.
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 

Expert Comment

by:CHARU T
ID: 40378342
You can handle all the errors and what to do, if conditions. Also, whether the system is logged on or restarted, such things can also be tested by subscribing to windows events in C# code itself. You can log errors onto a text file, and proceed. Make sure there is no pop-up message boxes so its run in the background without user intervention.
0
 

Author Comment

by:ITsolutionWizard
ID: 40378521
Need codes sample
0
 

Expert Comment

by:CHARU T
ID: 40378674
If you need code sample for Timer (?), then there are plenty in the web. Add a timer and do your email fn in the tick() event. You can also write a console app, and use a timer in it, log msgs and errors to a text file so there are no pop-ups.

What is your q exactly here?
0
 
LVL 40

Accepted Solution

by:
Kyle Abrahams earned 500 total points
ID: 40380107
I would agree with Eric on this . . . if there's an error the code might exit and not be called again.  With a scheduled task you're relying on the windows scheduler to call the executable.

For a console application:
sendSingleEmail  becomes the main of the program.  Then schedule the task on the computer and you're done.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
This is a video that shows how the OnPage alerts system integrates into ConnectWise, how a trigger is set, how a page is sent via the trigger, and how the SENT, DELIVERED, READ & REPLIED receipts get entered into the internal tab of the ConnectWise …
Need to grow your business through quality cloud solutions? With everything required to build a cloud platform and solution, you may feel like the distance between you and the cloud is quite long. Help is here. Spend some time learning about the Con…

914 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now