Solved

Making of Windows Service

Posted on 2011-09-18
16
270 Views
Last Modified: 2012-05-12
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


0
Comment
Question by:mahmood66
  • 8
  • 7
16 Comments
 
LVL 37

Expert Comment

by:Gerwin Jansen
ID: 36556403
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?

0
 
LVL 13

Accepted Solution

by:
jonnidip earned 500 total points
ID: 36556859
Maybe you want to develope a windows service with a Timer inside?
It would be as simple as adding a new "Windows service" project to your solution.
You can start your timer under OnStart method and your job under the timer's handler.
Another simple approach can be starting a loop with your job and a sleep of an hour.

I would suggest you to read from these links:
http://www.codeproject.com/KB/dotnet/Windows__Services.aspx

Regards.
http://www.codeproject.com/KB/system/WindowsService.aspx
0
 

Author Comment

by:mahmood66
ID: 36558439
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 Service Error
0
 
LVL 13

Expert Comment

by:jonnidip
ID: 36558515
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.
0
 

Author Comment

by:mahmood66
ID: 36559435
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
0
 

Author Comment

by:mahmood66
ID: 36559678
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
0
 
LVL 13

Expert Comment

by:jonnidip
ID: 36559784
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)
Attach to process- 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.
0
 

Author Comment

by:mahmood66
ID: 36559980
Dear Johnidip,
 I am using VS2008.There is no "Attach to process" option under Debug.
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
LVL 13

Expert Comment

by:jonnidip
ID: 36560023
Express?
0
 

Author Comment

by:mahmood66
ID: 36564786
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
0
 

Author Comment

by:mahmood66
ID: 36565278
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
0
 
LVL 13

Expert Comment

by:jonnidip
ID: 36565311
Could you please post your code?
0
 

Author Comment

by:mahmood66
ID: 36565485
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

0
 
LVL 13

Expert Comment

by:jonnidip
ID: 36565620
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.
0
 

Author Comment

by:mahmood66
ID: 36565927
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
0
 
LVL 13

Expert Comment

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

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

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

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…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This Micro Tutorial will give you a basic overview how to record your screen with Microsoft Expression Encoder. This program is still free and open for the public to download. This will be demonstrated using Microsoft Expression Encoder 4.
Internet Business Fax to Email Made Easy - With  eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, f…

910 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

22 Experts available now in Live!

Get 1:1 Help Now