Win32Exception starting TopShelf 3.0.105 host from Nuget

1,475 views
Skip to first unread message

flipdoubt

unread,
Oct 21, 2012, 3:14:57 PM10/21/12
to topshelf...@googlegroups.com

Updated to TopShelf 3.0.105 via Nuget after updating all my projects to .NET 4.0. I did not change any of my code, so I start the host as follows:

private static void _TryRun(string fileName, string pluginDirectory, string serviceName)
{
    try
    {
        HostFactory.Run(x =>
                            {
                                x.Service<IScheduledCommandRunner>(configurator =>
                                                                        {
                                                                            configurator.ConstructUsing(
                                                                                name =>
                                                                                _TryRunBootstrapper(fileName,
                                                                                                    pluginDirectory,
                                                                                                    serviceName));
                                                                            configurator.WhenStarted(
                                                                                runner => runner.StartRunning());
                                                                            configurator.WhenStopped(
                                                                                runner => runner.StopRunning());
                                                                        });

                                x.SetServiceName(serviceName);
                                var displayName = GetConfigString("serviceDisplayName",
                                                                    "CEO Maintenance Service");
                                x.SetDisplayName(displayName);
                                var description = GetConfigString("serviceDescription",
                                                 "Runs scheduled tasks to maintain the Image Executive CEO document server.");
                                x.SetDescription(description);
                            }
            );
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
        throw;
    }
}

I try installing the service and auto-starting as NetworkService with the following:
CeoMaintenanceService.exe install --autostart --networkservice start

This produces the following output and error:

Configuration Result: 

[Success] Name CeoMaintenanceService

[Success] DisplayName CEO Maintenance Service

[Success] Description Runs scheduled tasks to maintain the Image Executive CEO document server.

[Success] ServiceName CeoMaintenanceService

Topshelf v3.0.105.0, .NET Framework v4.0.30319.18010

Running a transacted installation.

Beginning the Install phase of the installation.

Installing CEO Maintenance Service service

Installing service CeoMaintenanceService...

Service CeoMaintenanceService has been successfully installed.

Creating EventLog source CeoMaintenanceService in log Application...

The Install phase completed successfully, and the Commit phase is beginning.

The Commit phase completed successfully.

The transacted install has completed.

Topshelf.Hosts.StartHost Error: 0 : The service failed to start., System.Invalid

OperationException: Cannot start service CeoMaintenanceService on computer '.'.

---> System.ComponentModel.Win32Exception: The service did not respond to the st

art or control request in a timely fashion

--- End of inner exception stack trace ---

at System.ServiceProcess.ServiceController.Start(String[] args)

at Topshelf.Runtime.Windows.WindowsHostEnvironment.StartService(String serviceName)

at Topshelf.Hosts.StartHost.Run()

If I leave off the "start" verb and start the service from the service manager, I get a dialog with the following error message:

Windows could not start the CEO Maintenance Service service on Local Computer.

Error 1053: The service did not respond to the start or control request in a timely fashion.

Any clues as to what this could be? 
 
 

Travis Smith

unread,
Oct 21, 2012, 4:07:55 PM10/21/12
to topshelf...@googlegroups.com
The start action failed to complete or failed. It's not always easy to
tell here. Ensure the service has the prelivages it needs. Add logging
into your construction to makes sure that is working right. Most
common thing, I think, we see is that the account the service is
running under doesn't have access to a port or a file.

-Travis

flipdoubt

unread,
Oct 24, 2012, 11:56:37 AM10/24/12
to topshelf...@googlegroups.com
The error occurred because StructureMap's Registry.Scan was using a relative path, which resolved to one of the system directories when running as a service. I fixed this by setting the current directory as follows:

Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);

This fixed my problem and allows the app to start normally, but there seems to be a change in behavior between TopShelf 2.x and 3.x that I was not aware of, because our code did not change, only the TopShelf reference. 

Chris Patterson

unread,
Oct 24, 2012, 3:35:49 PM10/24/12
to topshelf...@googlegroups.com
Strange, that's the first line in the service Run() method...

WindowsServiceHost.cs(48):
public TopshelfExitCode Run()
{
Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);

Stefan Rinkes

unread,
Mar 21, 2013, 4:29:12 AM3/21/13
to topshelf...@googlegroups.com

Maybe you can provide some more informations, like your environment, Windows-Version, code and commands you tried.
This way we maybe can help you and you help Topshelf to get more awesome :)


Am Mittwoch, 20. März 2013 22:35:55 UTC+1 schrieb Jesse Beard:
There appears to be a lot of issues just getting the service to start after installing.  I have spent much time trying to get a very simple service to start.  I switched to TopShelf to eliminate maintaining a Windows Service and Console project, and it really helps things, but I am really fighting the way TopShelf handles the command line and actually starting the service.  Console running works fine.  I have tried so much and cannot get my service install to even start.  Even with nothing in my Start(), I get the startup timeout everyone mentions.  I'm almost ready to dump TopShelf if I can't get it solved within another day or so.  I have had to use custom PowerShell scripts to ease the install/uninstall process as well as adding custom command line arguments to the installed service's ImagePath in the registry.  TopShelf is getting there, but still nothing like having a custom Installer class and controlling it all yourself.  So...still digging trying to get my service to start.

Jesse Beard

unread,
Mar 21, 2013, 10:00:05 AM3/21/13
to topshelf...@googlegroups.com
Gladly, here are some details.

I have a single Console application that is used in development as a Console for easy testing.  In production, it's deployed as a Windows Service.  Pretty typical for most all of us I am sure.  Console version works great, however, I did have to do some slightly ugly stuff to get TopShelf to play nice with a custom command line argument that dictates how my process starts.  I have to manually extract the first command line argument passing it to my Autofac container prior to calling any TopShelf code.  It was very chicken before egg to get this to work, but as a Console application, it works great, but as a Windows Service, who knows.  I'm going to pull the source on github and start digging also.  Here is my actual Program.cs class.

        static void Main(string[] args)
        {
            // manually extract the supplied 'server' argument so it can be passed to GlobalContainer.
            var commandLineServerType = int.Parse(args.First().Split(new[] { '=' })[1]);
            
            using (var container = new GlobalContainer(commandLineServerType).Build())
            {
                var serviceBus = container.Resolve<IServiceBus>();
                var host = ConstructHost(container);
                host.Run();
            }
        }

        static Host ConstructHost(ILifetimeScope container)
        {
            var settings = container.Resolve<SocketServerSettings>();

            return HostFactory.New(
                cfg =>
                {
                    // register the custom command line option that dictates runtime server type.
                    // this registration also prevents TopShelf from rejecting the argument and stopping.
                    cfg.AddCommandLineDefinition("type", x => { /* do nothing */ });
                    cfg.ApplyCommandLine();

                    cfg.Service<IService>(
                        svc =>
                        {
                            svc.ConstructUsing(container.Resolve<IService>);
                            svc.WhenStarted(s => s.Start());
                            svc.WhenStopped(s => s.Stop());
                        });

                    cfg.SetDescription(settings.Description);
                    cfg.SetDisplayName(string.Format("X-{0}", settings.ServerName));
                    cfg.SetServiceName(string.Format("X-{0}", settings.ServerName));
                    cfg.DependsOn("LanmanWorkstation");
                    
                    // initially configure the Windows Services to install using Local System account.
                    // this should and will be changed post-deploy using a script.
                    cfg.RunAsLocalSystem();
                });            
        }

Thanks for any input and pointers to get my service to start.  I am happy to provide all details you need.  I also experience the KERNEL32.dll violations.  What other info do you need?

I load a lot into my Autofac container including MassTransit, among others.  BTW, MT is very awesome, thank you for that service!

Jesse Beard

unread,
Mar 21, 2013, 11:25:53 AM3/21/13
to topshelf...@googlegroups.com
My dev environment is Windows 7 and production deployments are to 2008R2

Jesse Beard

unread,
Mar 21, 2013, 4:11:36 PM3/21/13
to topshelf...@googlegroups.com
Something in my Autofac Container that I am loading is causing issues only when running/installed as WinSvc...not as Console.  I'll hunt it down and postback.  Commenting out all container loading/registrations allows the service to always start/stop.

On Thursday, March 21, 2013 10:00:05 AM UTC-4, Jesse Beard wrote:

Jesse Beard

unread,
Mar 21, 2013, 5:16:53 PM3/21/13
to topshelf...@googlegroups.com
So, this MassTransit call returns only every other time it is called.  The call into New() never returns when it does hangs.  The "done" log is never produced. The service is installed using an AD account that is admin on the machine.

            builder.Register(
                c =>
                    {
                        var logger = c.Resolve<ILog>();

                        logger.Info("MassModule: New() starting.");
                        var s = ServiceBusFactory.New(sb => this.ConfigureServiceBus(c, sb));
                        logger.Info("MassModule: New() done.");

                        return s;

                    }).As<IServiceBus>().SingleInstance();


What does ConfigureServiceBus() look like.... (zero issues with this code running as Console.)


        private void ConfigureServiceBus([NotNull] IComponentContext context, [NotNull] ServiceBusConfigurator configurator)
        {
            CodeContracts.VerifyNotNull(context, "context");
            CodeContracts.VerifyNotNull(configurator, "configurator");

            var logger = context.Resolve<ILog>();
            logger.Info("Service Bus: Starting service bus configuration.");

            var massModuleSettings = context.Resolve<IAppSettings>().ToTyped<MassModuleSettings>();
            
            configurator.UseRabbitMq();
            configurator.SetPurgeOnStartup(massModuleSettings.PurgeOnStartup);

            // set application queue name.
            configurator.ReceiveFrom(massModuleSettings.ReceiveFrom);

            switch (massModuleSettings.MessageSerializer)
            {
                case "binary":
                    configurator.UseBinarySerializer();
                    break;
                case "bson":
                    configurator.UseBsonSerializer();
                    break;
                case "json":
                    configurator.UseJsonSerializer();
                    break;
                case "xml":
                default:
                    configurator.UseXmlSerializer();
                    break;
            }

            logger.Info(
                string.Format(
                    "Service Bus: [{0}] receiving from [{1}] using [{2}] serialization. PurgeOnStartup: {3}",
                    massModuleSettings.ServiceBusNetwork,
                    massModuleSettings.ReceiveFrom,
                    massModuleSettings.MessageSerializer,
                    massModuleSettings.PurgeOnStartup));

            foreach (var setupServiceBus in context.Resolve<IEnumerable<ISetupServiceBus>>())
            {
                setupServiceBus.Setup(configurator);
            }

            logger.Info("Service Bus: Ending service bus configuration complete.");
        }

Chris Patterson

unread,
Mar 22, 2013, 4:21:35 PM3/22/13
to topshelf...@googlegroups.com
I replied in the MT mailing list, FYI.


--
You received this message because you are subscribed to the Google Groups "topshelf-discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email to topshelf-discu...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Reply all
Reply to author
Forward
0 new messages