C# .NET - Window Service

Asked By .net developer
12-May-10 03:27 AM

Service is not working...(It works sometimes while debugging...i used the following way to debug
#if (!DEBUG)
   
ServiceBase[] ServicesToRun;
   
ServicesToRun = new ServiceBase[] { new PollingService() };
   
ServiceBase.Run(ServicesToRun);
#else
   
// Debug code: this allows the process to run as a non-service.
   
MyService service = new MyServiceService();
    service
.OnStart(null);

   
//Use this to make the service keep running
   
// Shut down the debugger to exit
   
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);

   
//Use this to make it stop
   
//System.Threading.Thread.Sleep(TimeSpan.FromSeconds(10));
   
//service.OnStop();
#endif
#if (!DEBUG)
   
protected override void OnStart(string[] args)
#else
   
public new void OnStart(string[] args)
#endif
)[My framework did not allow me to attach a process for debugging ]

Steps followed while creating window service..

http://www.codeproject.com/KB/dotnet/simplewindowsservice.aspx

Then added config and references coz i was linking the service with a website code.The connection string of the service and webite is the same.

Service1.cs code

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.Collections;
using System.Configuration;
......References from the website.....
using System.Timers;
using System.Xml;
using System.IO;
using System.Web;
using System.Globalization;

namespace ExactService
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
            //code to set timer
            InitializeComponent();
            if (!System.Diagnostics.EventLog.SourceExists("ExactServiceLog"))
                System.Diagnostics.EventLog.CreateEventSource("ExactServiceLog",
                                                                      "ESLOG");

            eventLog1.Source = "ExactServiceLog";
            // the event log source by which


            //the application is registered on the computer


            eventLog1.Log = "ESLOG";




            //code ends
        }
        private System.Timers.Timer MyTimer;



        protected override void OnStart(string[] args)
        {

            // Interval in milliseconds
            string myInterval = System.Configuration.ConfigurationManager.AppSettings["ServiceInterval"].ToString();

            double interval = Convert.ToDouble(myInterval);

            // Create timer object
            MyTimer = new System.Timers.Timer(interval);
            MyTimer = new System.Timers.Timer();
            // Set to run more than once
            MyTimer.AutoReset = true;

            MyTimer.Enabled = true;

            // Delegate to handle the timer event
            MyTimer.Elapsed += new ElapsedEventHandler(timer_Elapsed);

            // Start the timer
            MyTimer.Start();

            // Prevents garbage collection from occuring in long running methods
            GC.KeepAlive(MyTimer);
            // TODO: Add code here to start your service.
            //code for date check





            eventLog1.WriteEntry("ExactService started");



        }
        /// <summary>
        ///
        /// </summary>
        private void RunService()
        {

            string fileName = string.Format("customers_{0}.xml", DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss"));

            CustomerCollection customers = GetCustomers();
            string xml = ExactXMLFormatter.ExportCustomersToXML(customers);
            WriteResponseXML(xml, fileName);
            eventLog1.WriteEntry("Xml File written.");
        }
        public static void WriteResponseXML(string xml, string Filename)
        {
            if (!String.IsNullOrEmpty(xml))
            {
                String strFilePath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "/" + Filename;
                XmlDocument document = new XmlDocument();
                document.LoadXml(xml);
                document.Save(strFilePath);
                
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                MyTimer.Enabled = false;
                MyTimer.Stop();
                string startTimeString = ConfigurationSettings.AppSettings["StartTime"].ToString();
                DateTime startTime;
                startTime = DateTime.Now;
               
                //If timestamp = myDateTime.ToString("HH:mm")

            if(startTimeString==startTime.ToString("HH:mm"))
            {
                    RunService();

            }


            }
            catch (Exception ex)
            {
                System.IO.File.AppendAllText("C:\\CustomerList.txt", "Exact service threw Exception " + ex.Message + "\r\n");
            }
            finally
            {
                GC.Collect();
                MyTimer.Start();
            }
        }
        protected CustomerCollection GetCustomers()
        {
            //System.IO.File.AppendAllText("C:\\CustomerList.txt", "File is created at the follwing location: Customers started.\r\n");
            string customerType = string.Empty;
            if (customerType == string.Empty)
            {
                customerType = "Admin,Office,Customer";
            }
            //System.IO.File.AppendAllText("C:\\CustomerList.txt", "File is created at the follwing location: Customers 2nd step.\r\n");


            DateTime startDate = DateTime.Now;
            DateTime endDate = DateTime.Now;

            CustomerCollection customers = null;
            ////CustomerID Inserted            
            //System.IO.File.AppendAllText("C:\\CustomerList.txt", "File is created at the follwing location: Customers 3rd step.\r\n");
            //System.IO.File.AppendAllText("C:\\CustomerList.txt", "File is created at the follwing location: Customers 4th step." + startDate + ", " + endDate + ", " + int.MaxValue + ", " + customerType + "\r\n");

            int totalRecords = 0;
            customers = CustomerManager.GetAllCustomersByDate(startDate,
                endDate, "", "", 2147483, 0, out totalRecords, customerType);

            //System.IO.File.AppendAllText("C:\\CustomerList.txt", "File is created at the follwing location: Customers fetched.\r\n");

            return customers;
            


        }

        protected override void OnStop()
        {
            // TODO: Add code here to perform any tear-down necessary to stop your service.
            eventLog1.WriteEntry("Exact Service stopped");
            MyTimer.AutoReset = false;
            MyTimer.Enabled = false;
        }
    }
}

 app.config

  <appSettings>
    <add key="StartTime" value="2355" />
    <add key="ServiceInterval" value="60000" />
   
  </appSettings>
 
  Peter Bromberg replied to .net developer
12-May-10 11:03 AM
You can't put business logic in the OnStart method, because there is only 30 seconds for it to return to Service Control Manager.
Have your OnsStart method kick off a background thread where a separate class is instantiated that has the methods you want for your business logic.
Create New Account
help
MyTimer.AutoReset = true; MyTimer.Enabled = true; / / Delegate to handle the timer event MyTimer.Elapsed + = new ElapsedEventHandler(timer_Elapsed); / / Start the timer MyTimer.Start(); / / Prevents garbage collection from occuring in long running methods n"); eventLog1.WriteEntry("Exception:runservice"); } } public static void WriteResponseXML(string xml, string Filename) { if (!String.IsNullOrEmpty(xml)) { / / String strFilePath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + " / " + Filename; String strFilePath = "C: \ XML summary> / / / / / / < / summary> / / / <param name = "sender"> < / param> / / / <param name = "e"> < / param> private void timer_Elapsed(object sender, ElapsedEventArgs e) { try { MyTimer.Enabled = false; MyTimer.Stop(); string startTimeString = ConfigurationSettings.AppSettings["StartTime"].ToString(); DateTime startTime
objCommon.SendMail("namrata@infynita.com", "BroadCast", "Msg Sent To Namrata. . . . . . "); DriverIds + = lblMastID.Text + ", " ; if (! string .IsNullOrEmpty(DriverIds)) DriverIds = DriverIds.Substring(0, DriverIds.Length - 1); } if (! string .IsNullOrEmpty(DriverIds)) DriverIds = DriverIds.Substring(0, DriverIds.Length - 1); CIncident objForAdd = new CIncident (); SmsId = objForAdd.SendSms ToString()), lblMastID.Text, txtMessage.Text, Action); timer.Interval = 10000; timer.Enabled = true ; timer.Elapsed+ = new ElapsedEventHandler (timer_Elapsed); } } } if (SmsId > 0) { lblMessage.Visible = true ; lblMessage.CssClass = "class_success" ; lblMessage.Text = CMessages .Sms_Sent; } else lblMessage.Visible = true ; lblMessage.CssClass = "class_error" ; lblMessage.Text = CMessages .Sms_Not_Sent; } } protected void timer_Elapsed( object sender, ElapsedEventArgs e) { BindGrid(hidDriverID.Value); timer.Enabled = false ; } This is the code where I am binding gridview row by row it binds whole gride directly Pl help Rupa " timer.Elapsed+ = new ElapsedEventHandler (timer_Elapsed);" You CANNOT assign EventHandlers in Button_Click event. Obviously you're very uninformed of Page_Cycle
MyTimer.AutoReset = true; MyTimer.Enabled = true; / / Delegate to handle the timer event MyTimer.Elapsed + = new ElapsedEventHandler(timer_Elapsed); / / Start the timer MyTimer.Start(); / / Prevents garbage collection from occuring in long running methods MyTimer.AutoReset = true; MyTimer.Enabled = true; / / Delegate to handle the timer event MyTimer.Elapsed + = new ElapsedEventHandler(timer_Elapsed); / / Start the timer MyTimer.Start(); / / Prevents garbage collection from occuring in long running methods eventLog1.WriteEntry("Xml File written."); } public static void WriteResponseXML(string xml, string Filename) { if (!String.IsNullOrEmpty(xml)) { String strFilePath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + " / " + Filename; XmlDocument document = new XmlDocument summary> / / / / / / < / summary> / / / <param name = "sender"> < / param> / / / <param name = "e"> < / param> private void timer_Elapsed(object sender, ElapsedEventArgs e) { try { MyTimer.Enabled = false; MyTimer.Stop(); string startTimeString = ConfigurationSettings.AppSettings["StartTime"].ToString(); DateTime startTime
feature request] Array.IsNullOrEmpty .NET Framework starting from .NET 2.0 there is a nice IsNullOrEmpty static method on a System.String class which saves the time so instead of string theString; if ( theString ! = null && theString.Length > 0 ) you write if ( !string.IsNullOrEmpty( theString ) ) I belive that the same pattern could be adopted for arrays so that instead of T[] array; if ( array ! = null && array.Length > 0 ) you could write if ( !Array.IsNullOrEmpty( array ) ) Regards, Wiktor Zychla .NET Framework Discussions IsNullOrEmpty (1) Array (1) I'm not sure what your point it. If you want to valuable update idea. https: / / connect.microsoft.com / availableconnections.aspx Robin S. - -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- keywords: [feature, request], Array.IsNullOrEmpty description: starting from .NET 2.0 there is a nice IsNullOrEmpty static method on a System.String class which saves the time so instead of string