none
Windows service not working/starting automatically after reboot, have to start it from vs

    Question

  • The start type is set to automatically but when i reboot my computer the service is showing started in (SERVICE TAB) but the work which is assign to it is not getting done, i have to start the service from Visual Studio to do the work.

    **Service1.cs**

        protected override void OnStart(string[] args)
                {
                    timer1 = new Timer();
                    //timer1.Start();
                    this.timer1.Interval = 300000; //5 min
                    this.timer1.Elapsed +=new System.Timers.ElapsedEventHandler(this.timer1_Tick);
               
                timer1.Enabled = true;
                timer1.AutoReset = true;
                if (this.timer1.Interval > 60000)
                {
                   
                    int res = resultrelease();
                
                
                }
                
                Library.WriteErrorLog("test windows service started");
     }

            protected override void OnStop()
            {
                timer1.Enabled = false;
                Library.WriteErrorLog("Test Service ended");
            }
            public Int32 resultrelease()
            {
                var result = RunProcess(@"C:\\Webdata", "cmd.exe", "C:\\Webdata\\CopyJHData.bat", false); // working with local host bat file
                // my path C:\Abhay\batfile
                if (result == 0)
                {
                    // success
                    Console.WriteLine("Sucess");
                }
                else
                {
                    // failed ErrorLevel / app ExitCode
                }

                return result;
            }


            public  void timer1_Tick(object sender, ElapsedEventArgs e)
            {
                //job
                 
          /* var result = RunProcess(@"C:\Webdata", "cmd.exe", "C:\\Webdata\\Copy_All.bat", false);
                                         // my path C:\Abhay\batfile
                  if (result == 0)
                  {
                      // success
                      Console.WriteLine("Sucess");
                  }
                  else
                  {
                      // failed ErrorLevel / app ExitCode
                      Console.WriteLine("failed try again");
                  }*/

                
            }

            public int RunProcess(string workDir, string appName, string args, bool hide = false)
                {
                       
                        Process proc = new Process();
                        proc.StartInfo.UseShellExecute = false;   //addition       
                        args = "/c";
                        appName = "C:\\Webdata\\CopyJHData.bat";// working with local host bat file
                        workDir = @"C:\\Webdata";
                        proc.StartInfo.WorkingDirectory = workDir;//batrun
                        proc.StartInfo.FileName = appName;
                        proc.StartInfo.Arguments = args;
                        proc.StartInfo.CreateNoWindow = hide;
                        
                        proc.Start();
                        proc.WaitForExit();
        
                        return proc.ExitCode;
                   }
           }
    }

    **Program.cs**

        static void Main(String[] args)
                {
                    // Initialize the service to start
                    ServiceBase[] ServicesToRun;
                    ServicesToRun = new ServiceBase[]
            {
                new Service1()
            };

                // In interactive mode ?
                if (Environment.UserInteractive)
                {
                    // In debug mode ?
                    if (System.Diagnostics.Debugger.IsAttached)
                    {
                        // Simulate the services execution
                        RunInteractiveServices(ServicesToRun);
                    }
                    else
                    {
                        try
                        {
                            bool hasCommands = false;
                            // Having an install command ?
                            if (HasCommand(args, "install"))
                            {
                                ManagedInstallerClass.InstallHelper(new String[] { typeof(Program).Assembly.Location });
                                hasCommands = true;
                                // Having a start command ?
                                if (HasCommand(args, "start"))
                                {
                                    foreach (var service in ServicesToRun)
                                    {
                                        ServiceController sc = new ServiceController(service.ServiceName);
                                        sc.Start();
                                        sc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(10));
                                    }
                                    hasCommands = true;
                                }
                            }
                            // Having a stop command ?
                            if (HasCommand(args, "stop"))
                            {
                                foreach (var service in ServicesToRun)
                                {
                                    ServiceController sc = new ServiceController(service.ServiceName);
                                    sc.Stop();
                                    sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10000));// change
                                }
                                hasCommands = false;
                            }
                            // Having an uninstall command ?
                            if (HasCommand(args, "uninstall"))
                            {
                                ManagedInstallerClass.InstallHelper(new String[] { "/u", typeof(Program).Assembly.Location });
                                hasCommands = true;


                            }
                            // If we don't have commands we print usage message
                            if (!hasCommands)
                            {
                                Console.WriteLine("Usage : {0} [command] [command ...]", Environment.GetCommandLineArgs());
                                Console.WriteLine("Commands : ");
                                Console.WriteLine(" - install : Install the services");
                                Console.WriteLine(" - uninstall : Uninstall the services");
                            }
                        }
                        catch (Exception ex)
                        {
                            var oldColor = Console.ForegroundColor;
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("Error : {0}", ex.GetBaseException().Message);
                            Console.ForegroundColor = oldColor;
                        }
                    }
                }
                else
                {
                    // Normal service execution
                    ServiceBase.Run(ServicesToRun);
                }
            }

            static void RunInteractiveServices(ServiceBase[] servicesToRun)
            {
                Console.WriteLine();
                Console.WriteLine("Start the services in interactive mode.");
                Console.WriteLine();

                // Get the method to invoke on each service to start it
                MethodInfo onStartMethod = typeof(ServiceBase).GetMethod("OnStart", BindingFlags.Instance | BindingFlags.NonPublic);

                // Start services loop
                foreach (ServiceBase service in servicesToRun)
                {
                    Console.Write("Starting {0} ... ", service.ServiceName);
                    onStartMethod.Invoke(service, new object[] { new string[] { } });
                    Console.WriteLine("Started");
                }

                // Waiting the end
                Console.WriteLine();
                Console.WriteLine("Press a key to stop services et finish process...");
                Console.ReadKey();
                Console.WriteLine();

                // Get the method to invoke on each service to stop it
                MethodInfo onStopMethod = typeof(ServiceBase).GetMethod("OnStop", BindingFlags.Instance | BindingFlags.NonPublic);

                // Stop loop
                foreach (ServiceBase service in servicesToRun)
                {
                    Console.Write("Stopping {0} ... ", service.ServiceName);
                    onStopMethod.Invoke(service, null);
                    Console.WriteLine("Stopped");
                }

                Console.WriteLine();
                Console.WriteLine("All services are stopped.");

                // Waiting a key press to not return to VS directly
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    Console.WriteLine();
                    Console.Write("=== Press a key to quit ===");
                    Console.ReadKey();
                }
            }
            static bool HasCommand(String[] args, String command)
            {
                if (args == null || args.Length == 0 || String.IsNullOrWhiteSpace(command)) return false;
                return args.Any(a => String.Equals(a, command, StringComparison.OrdinalIgnoreCase));


            }
            
        }
    }

    **Library.cs**

         public static void WriteErrorLog(Exception ex)
                {
                    StreamWriter sw = null;
                    try
                    {
                        sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\ Logfile.txt", true);
                        sw.WriteLine(DateTime.Now.ToString() + ":" + ex.Source.ToString().Trim() + ";" + ex.Message.ToString().Trim());
                        sw.Flush();
                        sw.Close();
        
                    }
                    catch
                    {
        
                    }
                }
        
                public static void WriteErrorLog(string Message)
                {
                    StreamWriter sw = null;
                    try
                    {
                    
                        sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\ Logfile.txt", true);
                        sw.WriteLine(DateTime.Now.ToString() + ":" + Message);
                        sw.Flush();
                        sw.Close();
                }
                catch
                {

                }
            }

    The above service is running a batch file(Service1.cs) which includes a path of ftp server, from the ftp server the files are getting downloading to another path. This Process is done when i run the service from visual studio but is it possible to do at a particular time or every day??
    • Edited by Abhay2594 Wednesday, March 29, 2017 9:23 AM
    Wednesday, March 29, 2017 9:19 AM

Answers

  • Your OnStart method looks wrong to me. A service has a small amount of time to start up. If it doesn't then the SCM shuts it down. You are correct in your use of a timer (although I generally prefer a thread). But inside your OnStart you have an if statement that is always true. You set the Interval to 300,000 and then check to see if it is > 60,000. That's always true so it triggers a call to your resultrelease method. This method starts a new process and then blocks until it completes. Therefore your service stalls and the SCM will end up terminating it.

    You need to remove this if statement. I suspect you'll find that your event log message you're writing at the bottom of OnStart isn't getting called (at least until after the process is run).

    Michael Taylor
    http://www.michaeltaylorp3.net

    Wednesday, March 29, 2017 2:03 PM
    Moderator

All replies

  • Hi Abhay,

    Please make sure that user service has administrator permission/ try to add your service username into local machine admin user group.

    You could use Task Scheduler to schedule the task.


    Thanks,
    Sabah Shariq

    [If a post helps to resolve your issue, please click the "Mark as Answer" of that post or click Answered "Vote as helpful" button of that post. By marking a post as Answered or Helpful, you help others find the answer faster. ]

    Wednesday, March 29, 2017 9:26 AM
    Moderator
  • Thank you for your ans Sir,

    it will be easy  but my Team Head said the project shouldn't run on task scheduler.

    where can I find the local machine use group? can you please inform this?

    Thanking You,

    Abhay Singhania

    Wednesday, March 29, 2017 10:39 AM
  • Hi Abhay,

    Then you could user Timer Class to scheduling. Please see the below sample project how to use timer class for scheduling that I created.

    C# Timer: Schedule a Task

    Add A User To Administrator Group


    Thanks,
    Sabah Shariq

    [If a post helps to resolve your issue, please click the "Mark as Answer" of that post or click Answered"Vote as helpful" button of that post. By marking a post as Answered or Helpful, you help others find the answer faster. ]



    Wednesday, March 29, 2017 12:44 PM
    Moderator
  • Your OnStart method looks wrong to me. A service has a small amount of time to start up. If it doesn't then the SCM shuts it down. You are correct in your use of a timer (although I generally prefer a thread). But inside your OnStart you have an if statement that is always true. You set the Interval to 300,000 and then check to see if it is > 60,000. That's always true so it triggers a call to your resultrelease method. This method starts a new process and then blocks until it completes. Therefore your service stalls and the SCM will end up terminating it.

    You need to remove this if statement. I suspect you'll find that your event log message you're writing at the bottom of OnStart isn't getting called (at least until after the process is run).

    Michael Taylor
    http://www.michaeltaylorp3.net

    Wednesday, March 29, 2017 2:03 PM
    Moderator