Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Making of Windows Service

Posted on 2011-09-18
16
Medium Priority
?
278 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 7
16 Comments
 
LVL 38

Expert Comment

by:Gerwin Jansen, EE MVE
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 2000 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
NFR key for Veeam Agent for Linux

Veeam is happy to provide a free NFR license for one year.  It allows for the non‑production use and valid for five workstations and two servers. Veeam Agent for Linux is a simple backup tool for your Linux installations, both on‑premises and in the public cloud.

 
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
 
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

Get your Conversational Ransomware Defense e‑book

This e-book gives you an insight into the ransomware threat and reviews the fundamentals of top-notch ransomware preparedness and recovery. To help you protect yourself and your organization. The initial infection may be inevitable, so the best protection is to be fully prepared.

Question has a verified solution.

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

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…
In response to a need for security and privacy, and to continue fostering an environment members can turn to for support, solutions, and education, Experts Exchange has created anonymous question capabilities. This new feature is available to our Pr…

688 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