Topshelf service wont start as a service: Error 1053 The service did not respond.."
Asked Answered
P

0

0

I can run this service directly from a console window by invoking the executable using the same account that the service is supposed to run as. But when I install it as service and when I try to run it it displays following message:

enter image description here

Before I post my code this is what I've tried:

Here is full exception message:

The transacted install has completed. Topshelf.Hosts.StartHost Error: 0 : The service failed to start., System.InvalidOperationException: Cannot start service MyCabinet on computer '.'. ---> System.ComponentModel.Win32Exception: The service did not respond to the start or control request in a timely fashion --- End of inner exception stack trace --- at System.ServiceProcess.ServiceController.Start(String[] args) at System.ServiceProcess.ServiceController.Start() at Topshelf.Runtime.Windows.WindowsHostEnvironment.StartService(String serviceName, TimeSpan startTimeOut) at Topshelf.Hosts.StartHost.Run()

Here is the code:

Program.cs below:

using SmartCabinet.Core.Domain.Entities;
using SmartCabinet.Infrastructure.Database;
using System;
using System.IO;
using Topshelf;

namespace SmartCabinet
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
                HostFactory.Run(serviceConfig =>                                   
                {
                    serviceConfig.Service<FilesProcessor>(s =>                                   
                    {
                        s.ConstructUsing(name => new FilesProcessor());
                        s.WhenStarted(execute => execute.Start());       //.BeforeStartingService(a => a.RequestAdditionalTime(TimeSpan.FromSeconds(120)));                         
                        s.WhenStopped(execute => execute.Stop());                          
                    });

                    //serviceConfig.SetServiceName("MyCabinet");
                    serviceConfig.SetDisplayName("Files Processor.");
                    serviceConfig.SetDescription("Windows service for files processing.");
                    serviceConfig.StartAutomatically();
                });                                                            
            }
            catch(Exception ex)
            {
                var error = new ErrorLog()
                {
                    ExceptionTitle = ex.Message,
                    ExceptionDescription = ex.InnerException?.Message,
                    CreatedDate = DateTime.Now
                };

                using (var context = new SmartCabinetDBContext())
                {
                    context.ErrorLogs.Add(error);
                    context.SaveChanges();
                }
            }
        }
    }
}

FilesProcessor.cs below:

namespace MyCabinet
{
    class FileProcessor
    {
        readonly System.Timers.Timer _timer;
        public FileProcessor()
        {
            ProcessAndImportData();

            _timer = new System.Timers.Timer(120000) { AutoReset = true };
            _timer.Elapsed += (sender, eventArgs) => ProcessAndImportData();

            //_timer.Elapsed += Timer_Elapsed;
            //_timer.Enabled = true;
        }

        private void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
           ProcessAndImportData();
        }

        public void ProcessAndImportData()
        {
            Console.WriteLine("It is {0} and processing has started", DateTime.Now);
            // ... rest of the code

        }

        private void Download(string site, string itemPath, string file)
        {
            // .. some code
        }

        private void Upload(byte[] buffer, string pathToUpload, string site)
        {
           // .. some code
        }
        
        
        

        public bool Start() { _timer.Start(); return true; }
        public bool Stop() { _timer.Stop(); return true; }

        /* PREVIOUS UNUSED CODE:
        
        public void foreverWhile()
        {
            while (true)
            {
                // to do something forever
            }
        }
        
        public bool Start()
        {
            try
            {
                var myThread = new Thread(new ThreadStart(foreverWhile));
                myThread.IsBackground = true;  // This line will prevent thread from working after service stop.
                myThread.Start();
                return true;

                //_timer.Start();
                //return true;
            }
            catch(Exception ex)
            {
                var error = new ErrorLog()
                {
                    ExceptionTitle = ex.Message,
                    ExceptionDescription = ex.InnerException?.Message,
                    CreatedDate = DateTime.Now
                };

                using (var context = new SmartCabinetDBContext())
                {
                    context.ErrorLogs.Add(error);
                    context.SaveChanges();
                }
            }
            return true;
        }
        public bool Stop() { _timer.Stop(); return true; }END OF PREVIOUS UNUSED CODE */
    }
}
Pipit answered 21/8, 2020 at 11:28 Comment(6)
Tow things 1) Check Event Viewer to see if there is more details in the Event 2) Get Last Error : learn.microsoft.com/en-us/dotnet/api/…Pejoration
@Pejoration I've checked, there is no errors in event viewer.Sinusitis
What about get last error which return a window error number.Pejoration
@Pejoration where should I implement it ? any tips please? I will try it in a moment..Sinusitis
Immediately after the line of code that is giving an error (or as close as possible).Pejoration
You're not specifying what account to run under - like s.RunAsLocalSystem(); - I can't remember what the default is, so are you sure that not specifying the account isn't the problem?Fructificative

© 2022 - 2024 — McMap. All rights reserved.