Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I am figuring out how to run my Windows Service twice a week(say on Tuesday and Friday)at 3 pm.

Please find below the code and suggest how can I implement it
C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Web;
using Excel = Microsoft.Office.Interop.Excel;
using System.Net.Mail;
using System.Configuration;
using System.Collections;
using System.Reflection;
using System.Xml;
using System.Xml.Xsl;
using System.IO;
namespace AutomationProcess
{
    public partial class Service1 : ServiceBase
    {
        // DateTime lastRun = DateTime.Now;

        public Service1()
        {
            InitializeComponent();
        }
        public void automate()
        {
            string filepath, filename, fileExcel;
            string ReportCount = "select count(rs.contactID) from tblReportLOg rs inner join tblContact c on c.contactID = rs.contactID where LogDate >= '2011-01-20 00:00:00.000' and c.email like '%micro%' and rs.contactid not in (39287,39286,27546)";
            string UserCount = "select count(distinct(rs.contactID)) from tblReportLOg rs inner join tblContact c on c.contactID = rs.contactID where LogDate >= '2011-01-20 00:00:00.000' and c.email like '%micro%' and rs.contactid not in (39287,39286,27546)";
            Random nRandom = new Random(DateTime.Now.Millisecond);
            //Create a random file name.
            fileExcel = "t" + nRandom.Next().ToString() + ".xls";
            filepath = "C:\\test";
            filename = filepath + "\\" + fileExcel;
            try
            {
                SqlConnection conn = new SqlConnection();
                conn.ConnectionString = ConfigurationManager.AppSettings["Connection"];
                SqlCommand cmd = new SqlCommand("select rs.contactID,SurveyType,ModuleName,LogDate from tblReportLOg rs inner join tblContact c on c.contactID = rs.contactID where LogDate >= '2011-01-20 00:00:00.000' and c.email like '%micro%' and rs.contactid not in (39287,39286,27546) order by LogDate ", conn);
                SqlCommand cmd1 = new SqlCommand(ReportCount, conn);
                SqlCommand cmd2 = new SqlCommand(UserCount, conn);
                SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(cmd);
                DataSet d = new DataSet();
                mySqlDataAdapter.Fill(d, "dataset");
                conn.Open();
                string reports = Convert.ToString(cmd1.ExecuteScalar());
                string users = Convert.ToString(cmd2.ExecuteScalar());
                ---------------------------some tasks to do-----------------------------
                
            }
            SendEmail(ReportCount, UserCount);
        }
        private static void WriteToLog(string message)
        {
            using (var fl = new StreamWriter("c:\\test\\test.log", true))
            {
                fl.WriteLine(message);
            }
        }

        private static void SendEmail(string reports, string users)
        {
            string filepath = "C:\\test";
            try
            {
                System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
                message.From = new MailAddress("lmn@poc.com");
                message.To.Add("xyz@abc.com");
                message.Subject = "Statistical Report";
                message.Body = "Please find attached the statistical report " +
                     "\nTotal number of reports downloaded by users is " + reports +
                     "\nTotal number of users who have downloaded reports is " + users;
                Attachment attach = new Attachment(filepath + @"\test.xlsx");
                WriteToLog("Mail check");
                message.Attachments.Add(attach);
                WriteToLog("Attached excel");
                System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("localhost");
                WriteToLog("Checking SMTP");
                smtp.Send(message);

            }
            catch (Exception ex)
            {
                WriteToLog(ex.Message);
                // Console.WriteLine(ex.ToString());
            }
        }

        protected override void OnStart(string[] args)
        {
            // WriteToLog("Calling Automate");
            //automate(); 
            //return;
            DateTime startTime;
            startTime = DateTime.Now;
            System.Timers.Timer time = new System.Timers.Timer();
            //Assuming that the service is started at 1 pm and mail needs to be sent at 4pm which makes the time interval=3hours
            time.Interval = 3*60*60*1000;
            time.Elapsed += new ElapsedEventHandler(time_Elapsed);
            //string startTimeString = ConfigurationManager.AppSettings["Interval"].ToString();
            
            time.Enabled = true;
        }


        void time_Elapsed(object sender, ElapsedEventArgs e)
        {
           DateTime startTime = DateTime.Now;
           string newStartTime;
            if ((startTime.Day == 2 || startTime.Day == 5))
             {
            automate();
             }
            newStartTime = ConfigurationManager.AppSettings["Interval"].ToString();
              
            //DateTime small = new DateTime();
            //DateTime large = new DateTime();
        }
        protected override void OnStop()
        {
        }

    }
}




Thanks
Posted
Updated 14-Feb-11 19:51pm
v2
Comments
Sandeep Mewara 15-Feb-11 3:49am    
It would be good if you add what issue you are facing.

Just posting the code would not encourage most of users. Any error? Issue?
Aksh@169 15-Feb-11 5:44am    
The issue is that I dont know how to schedule it biweekly at a specific time:(

1 solution

I would suggetst you to use Quartz.Net for this. It is an open source framework. Moreover it is best suited for small to big projects.

You can find more information on Quartz.Net at
1 . http://quartznet.sourceforge.net/tutorial/lesson_1.html[^]
2. http://blog.goyello.com/2009/09/21/how-to-use-quartz-net-in-pro-way/[^]

Hope this helps.
All the best.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900