Link to home
Start Free TrialLog in
Avatar of mahmood66
mahmood66Flag for United Arab Emirates

asked on

Making of Windows Service

Dear Experts,

i have a small windows application which is developed in C# .net.
i need to make one service for that application with installation set up.
kindly suggest me the step by step process of service making.
Note:
1) The service should be run in in latest versions of Windows (windows 7)
2) The service should be run in timely manner (ex : after every 1 hr
[kind of reminder service])


thanks


Avatar of Gerwin Jansen
Gerwin Jansen
Flag of Netherlands image

Hi,

I believe this:
>> 1) The service should be run in in latest versions of Windows (windows 7)

is in conflict with this:
>> 2) The service should be run in timely manner (ex : after every 1 hr [kind of reminder service])

After a service has been installed, it is usually started (automatically) and keeps running.

To run something in a timely manner, the Windows Scheduler is used.

If you want your application to be registered/installed as a service, where/how do you imagine that the hourly 'trigger' should be defined?

ASKER CERTIFIED SOLUTION
Avatar of jonnidip
jonnidip
Flag of Italy image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of mahmood66

ASKER

Dear johnidip ,

thanks for your kind Reply i followed the same first link which you provide me
but while starting my service am getting following Error.

kindly suggest me the solution


thnaks User generated image
Your application (service) failed to startup because of errors in the OnStart method (or any method called by it).
The debug of windows services is not always simple.
In my experience I found basically 2 methods of debugging.
1) if the service starts normally --> you can use "Attach to process" in your VS project
2) if the service does not start --> you can modify your code in this way:
- move your code from the "OnStart" method to another one (the OnStart will call that method); for example: move to a method named "ServiceWork" and call it from the OnStart (it should be the only instruction in OnStart)
- insert a conditional debugging (#if DEBUG) clause in the "Main" method and write inside the call to your new "ServiceWork" method.
Here is an example:
static void Main()
{
   System.ServiceProcess.ServiceBase[] ServicesToRun;
   ServicesToRun = new System.ServiceProcess.ServiceBase[] { new MyService() };

#if DEBUG
   ServiceWork();
   return;
#endif

   System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}

protected override void OnStart(String[] args)
{
   ServiceWork();
}

private void ServiceWork()
{
   // Your code here...
}

Open in new window


In this way you will be able to run into the ServiceWork method by starting a debug on your service.
Be sure to compile in Release when you need to deploy it.

Regards.
Dear johnidip,

thanks for your last suggestion,using that i debugged my service.
i installed  and started my service.
in the onstart() event i have written log detail in a notepad for testing purpose.
but there is no data written i my notepad even i started my service.
 i think my service is started but nothing is executing which i have writtenin start event.
kindly suggest me some solution to find out whether my service is running properly or not.

while executing my service exe manually i am getting error like "Cannot start service from command line or debugger"
refer attached screen shot

kindly suggest me solution

Thanks


ServiceError1.jpg
Dear Johnidip,

after deployment of my serivce while starting my service i got the error like i attached

kindly suggest me a solution for htis.

thanks
ServiceError2.jpg
I never got these problems while debugging windows services.
Are you under VS2008 or VS2010?
I just tried to create a new solution and adding a new Windows Service project.
When I start debugging with F10, it goes into the Main() without problems.

You can even try the option to attach to process, but you will need to add a sleep in the OnStart method:
protected override void OnStart(string[] args)
{
   System.Threading.Thread.Sleep(20000);
   // existing code
}

Open in new window

It will add a delay to the code execution, leaving you the time to attach VS to the process.
After you modified the code you can:
- Install your service as usual
- Stop your service (NET STOP from cmd)
- In your project go to "Debug" - "Attach to process" (but don't choose anything, since your service has not yet been started)
User generated image- Start your service (NET START)
- You have now 20 sec. to refresh the processes list, select your service and chose "Attach".

It will point you to the first breakpoint.
Be sure that the code you deployed is the same you are using to debug.

Regards.
Dear Johnidip,
 I am using VS2008.There is no "Attach to process" option under Debug.
Express?
Dear Johnidip,

i am under VS2008 Professional Edition.

i have a timer control inside my service.
do you have any idea why that error ("Error 1053: Service did not respond to start"[i have attached screen shot in my previous post]) is appearing while starting my service after deployment?


thanks
Dear Experts,
after deployment my service is running successfully(i checked my customized event log).
i have a timer control inside my service.the event of timer_tick Where i have written my code, is not triggering.

kindly suggest  me
Could you please post your code?
Dear Johnidip,

Here is the Code.


 
static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
			{ 
				new TMSReminder() 
			};
//#if DEBUG
//            TMSReminder objTMSreminder = new TMSReminder();
//            objTMSreminder.TestService();
//            return;
//#endif

            ServiceBase.Run(ServicesToRun);
         }
    }

public partial class TMSReminder : ServiceBase
    {
        public TMSReminder()
        {
            InitializeComponent();
            if (!System.Diagnostics.EventLog.SourceExists("DoDyLogSourse"))
                System.Diagnostics.EventLog.CreateEventSource("DoDyLogSourse",
                                                                      "DoDyLog");

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


            //the application is registered on the computer


            eventLog1.Log = "DoDyLog";
        }

        protected override void OnStart(string[] args)
        {
            ServiceWork();
        }

        public void ServiceWork()
        {
            string ls_path = AppDomain.CurrentDomain.BaseDirectory;
            eventLog1.WriteEntry(ls_path + "---TMS Reminder Service Started");

            //#region "writting in Notepad for testing"
            //string strLogText = "Some details you want to log.";

            //// Create a writer and open the file:
            //StreamWriter log;

            //if (!File.Exists("ServiceLog.txt"))
            //{
            //    log = new StreamWriter("ServiceLog.txt");
            //}
            //else
            //{
            //    log = File.AppendText("ServiceLog.txt");
            //}

            //// Write to the file:
            //log.WriteLine(DateTime.Now);
            //log.WriteLine(strLogText);
            //log.WriteLine();

            //// Close the stream:
            //log.Close();
            //#endregion

            string ls_app_path = "";
            string ls_time_span = "";
            int li_time_span = 1;

            XmlDocument lobj_xml_doc = null;

            this.TimerTMS.Enabled = false;
            ls_app_path = AppDomain.CurrentDomain.BaseDirectory;
            lobj_xml_doc = new XmlDocument();

            lobj_xml_doc.Load(ls_app_path + "xml_reminder.xml");
            ls_time_span = lobj_xml_doc.SelectSingleNode("//configuration/time_span").InnerText;
            li_time_span = Convert.ToInt32(ls_time_span);
            li_time_span = (li_time_span * 60000);

            this.TimerTMS.Enabled = true;
            this.TimerTMS.Interval = li_time_span;
            TimerTMS.Start();
            TestService();
        }

        protected override void OnStop()
        {
            eventLog1.WriteEntry("TMS Reminder Service Stoped");
        }


        public void TestService()
        {
            XmlDocument lobj_xml_doc = null;
            int li_sync_time = 1;
            string ls_path = "";
            string ls_time_span = "";
            string ls_key = "";
            string ls_crypto = "";
            int li_time_span = 1;

            //cryptoservice lobj_cry = new cryptoservice();

            this.TimerTMS.Enabled = false;

            ls_path = AppDomain.CurrentDomain.BaseDirectory;

            lobj_xml_doc = new XmlDocument();
            lobj_xml_doc.Load(ls_path + "xml_reminder.xml");

            if (lobj_xml_doc.SelectSingleNode("//configuration/key").InnerText == "")
            {
                string ls_pidkey = "";
                //securitySrv lobj_security=new securitySrv();
                //EventLog.WriteEntry("A");
                ls_pidkey = "m3QMCSR7kP2IZB4/HNKY4jJfWl1lXdQc848loOAREKQ=";
                //EventLog.WriteEntry("B :" + ls_pidkey);
                lobj_xml_doc.SelectSingleNode("//configuration/key").InnerText = ls_pidkey;
                //EventLog.WriteEntry("C");
                lobj_xml_doc.Save(ls_path + "xml_reminder.xml");
                //EventLog.WriteEntry("D");
            }

            lobj_xml_doc = null;
            lobj_xml_doc = new XmlDocument();
            lobj_xml_doc.Load(ls_path + "xml_reminder.xml");

            ls_time_span = lobj_xml_doc.SelectSingleNode("//configuration/time_span").InnerText;
            ls_key = lobj_xml_doc.SelectSingleNode("//configuration/key").InnerText;
            //ls_crypto = lobj_cry.Decrypt(ls_key, "abc");

            try
            {
                //    //EventLog.WriteEntry("E");
                //    //if(Convert.ToDateTime(ls_crypto) < DateTime.Today || ls_crypto=="")
                //    //{
                //    //EventLog.WriteEntry("Version expired 1");
                //    //throw new Exception("Version expired");
                //    //}
                //    //else
                //    //{
                //    //EventLog.WriteEntry("F");
                //    if (lobj_xml_doc.SelectSingleNode("//configuration/con_str").InnerText == "")
                //    {
                //        //EventLog.WriteEntry("G");
                //        Application.Run(new reminder_settings());
                //        //EventLog.WriteEntry("H");
                //    }
                //    else
                //    {
                Process lobj_process = new Process();
                lobj_process.StartInfo.FileName = "tms_reminder_popup.exe";
                lobj_process.StartInfo.WorkingDirectory = ls_path;
                lobj_process.StartInfo.RedirectStandardInput = true;
                lobj_process.StartInfo.UseShellExecute = false;
                lobj_process.Start();
                lobj_process.WaitForExit();
                lobj_process.Close();
                //}
                //}
            }
            catch (Exception aobj_error)
            {
                //    if (ls_crypto != "TMSRemSrvKey@smst" || ls_crypto == "")
                //    {
                //        EventLog.WriteEntry("Version expired 2");
                //        //throw new Exception("Version expired");
                //    }
                //    else
                //    {
                //        if (lobj_xml_doc.SelectSingleNode("//configuration/con_str").InnerText == "")
                //            Application.Run(new reminder_settings());
                //        else
                //        {
                Process lobj_process = new Process();
                lobj_process.StartInfo.FileName = "tms_reminder_popup.exe";
                lobj_process.StartInfo.WorkingDirectory = ls_path;
                lobj_process.StartInfo.RedirectStandardInput = true;
                lobj_process.StartInfo.UseShellExecute = false;
                lobj_process.Start();
                lobj_process.WaitForExit();
                lobj_process.Close();
                //        }
                //    }
            }

            li_time_span = Convert.ToInt32(ls_time_span);
            li_time_span = (li_time_span * 60000);

            this.TimerTMS.Enabled = true;
            this.TimerTMS.Interval = li_time_span;
        }

        private void TimerTMS_Tick(object sender, EventArgs e)
        {
            eventLog1.WriteEntry("TMS Reminder Timer Tick on : " + DateTime.Now.ToString());
            XmlDocument lobj_xml_doc = null;
            int li_sync_time = 1;
            string ls_path = "";
            string ls_time_span = "";
            string ls_key = "";
            string ls_crypto = "";
            int li_time_span = 1;

            //cryptoservice lobj_cry = new cryptoservice();

            this.TimerTMS.Enabled = false;

            ls_path = AppDomain.CurrentDomain.BaseDirectory;

            lobj_xml_doc = new XmlDocument();
            lobj_xml_doc.Load(ls_path + "xml_reminder.xml");

            if (lobj_xml_doc.SelectSingleNode("//configuration/key").InnerText == "")
            {
                string ls_pidkey = "";
                //securitySrv lobj_security=new securitySrv();
                //EventLog.WriteEntry("A");
                ls_pidkey = "m3QMCSR7kP2IZB4/HNKY4jJfWl1lXdQc848loOAREKQ=";
                //EventLog.WriteEntry("B :" + ls_pidkey);
                lobj_xml_doc.SelectSingleNode("//configuration/key").InnerText = ls_pidkey;
                //EventLog.WriteEntry("C");
                lobj_xml_doc.Save(ls_path + "xml_reminder.xml");
                //EventLog.WriteEntry("D");
            }

            lobj_xml_doc = null;
            lobj_xml_doc = new XmlDocument();
            lobj_xml_doc.Load(ls_path + "xml_reminder.xml");

            ls_time_span = lobj_xml_doc.SelectSingleNode("//configuration/time_span").InnerText;
            ls_key = lobj_xml_doc.SelectSingleNode("//configuration/key").InnerText;
            //ls_crypto = lobj_cry.Decrypt(ls_key, "abc");

            try
            {
                //    //EventLog.WriteEntry("E");
                //    //if(Convert.ToDateTime(ls_crypto) < DateTime.Today || ls_crypto=="")
                //    //{
                //    //EventLog.WriteEntry("Version expired 1");
                //    //throw new Exception("Version expired");
                //    //}
                //    //else
                //    //{
                //    //EventLog.WriteEntry("F");
                //    if (lobj_xml_doc.SelectSingleNode("//configuration/con_str").InnerText == "")
                //    {
                //        //EventLog.WriteEntry("G");
                //        Application.Run(new reminder_settings());
                //        //EventLog.WriteEntry("H");
                //    }
                //    else
                //    {
                Process lobj_process = new Process();
                lobj_process.StartInfo.FileName = "tms_reminder_popup.exe";
                lobj_process.StartInfo.WorkingDirectory = ls_path;
                lobj_process.StartInfo.RedirectStandardInput = true;
                lobj_process.StartInfo.UseShellExecute = false;
                lobj_process.Start();
                lobj_process.WaitForExit();
                lobj_process.Close();
                //}
                //}
            }
            catch (Exception aobj_error)
            {
                //    if (ls_crypto != "TMSRemSrvKey@smst" || ls_crypto == "")
                //    {
                //        EventLog.WriteEntry("Version expired 2");
                //        //throw new Exception("Version expired");
                //    }
                //    else
                //    {
                //        if (lobj_xml_doc.SelectSingleNode("//configuration/con_str").InnerText == "")
                //            Application.Run(new reminder_settings());
                //        else
                //        {
                Process lobj_process = new Process();
                lobj_process.StartInfo.FileName = "tms_reminder_popup.exe";
                lobj_process.StartInfo.WorkingDirectory = ls_path;
                lobj_process.StartInfo.RedirectStandardInput = true;
                lobj_process.StartInfo.UseShellExecute = false;
                lobj_process.Start();
                lobj_process.WaitForExit();
                lobj_process.Close();
                //        }
                //    }
            }

            li_time_span = Convert.ToInt32(ls_time_span);
            li_time_span = (li_time_span * 60000);

            this.TimerTMS.Enabled = true;
            this.TimerTMS.Interval = li_time_span;
        }

        private void TimerTMS_Tick_1(object sender, EventArgs e)
        {
            eventLog1.WriteEntry("TMS Reminder Timer Tick on : " + DateTime.Now.ToString());
            TestService();
        }


    }

Open in new window

Try to move your EventLog initialization to the ServiceWork method.
I still don't understand why you don't see the "Attach to process" menu item.
Dear Johnidip,

Thanks for your kind Response and i helped me more.
insead of using timer now i have used Threading.
by using  following code,my code is executing in  timely manner.
Code:
in the onstart event am calling this function by using thread

function xxx()
{
while(true)
{
thread.sleep(60000);
myfunction();
}
}


thanks
I would swap these 2 lines, in order to get the job executed immediately when the service is started:
thread.sleep(60000);
myfunction();