PeterKottas / DotNetCore.WindowsService

Simple library that allows one to host dot net core application as windows services. Perfect solution to power micro-services architecture.
MIT License
568 stars 150 forks source link

The installed service did not respond to the start or control request in a timely fashion. #8

Closed Vladimir-Kharam closed 7 years ago

Vladimir-Kharam commented 7 years ago

Hi Peter.

Thank you in advance for your help.

I have installed your tool. The example service is working properly as console application. I can also successfully create window service using following command in administrator mode:

D:\Applications\DotNetCoreWindowService\DotNetCore.WindowsService\Source\PeterKottas.DotNetCore.Example\bin\Debug\netcoreapp1.1\win10-x64>sc create PeterKottas binPath= "C:\Program Files\dotnet\dotnet.exe D:\Applications\DotNetCoreWindowService\DotNetCore.WindowsService\Source\PeterKottas.DotNetCore.Example\bin\Debug\netcoreapp1.1\win10-x64\PeterKottas.DotNetCore.Example.dll --run-as-service"

[SC] CreateService SUCCESS

When I am trying run the service by command sc start PeterKottas (Administrator Mode)

I have the following error:

[SC] StartService FAILED 1053: The service did not respond to the start or control request in a timely fashion.

My working environment

Best Regards, Vladimir

PeterKottas commented 7 years ago

Hey mate, np. It's quite easy what went wrong. You actually overdid it. This is aimed at making your life easier so all you have to do is : D:\Applications\DotNetCoreWindowService\DotNetCore.WindowsService\Source\PeterKottas.DotNetCore.Example\bin\Debug\netcoreapp1.1\win10-x64>PeterKottas.DotNetCore.Example.exe action:install or D:\Applications\DotNetCoreWindowService\DotNetCore.WindowsService\Source\PeterKottas.DotNetCore.Example\bin\Debug\netcoreapp1.1\win10-x64\dotnet PeterKottas.DotNetCore.Example.dll action:install And ti will have your back with all of the windows command and so on. It will also take care of reinstalling, installing, stopping starting as necessary. Let me know if it helps.

Vladimir-Kharam commented 7 years ago

Thank you very much Peter for quick answer and good work

The following command: D:\Application\DotNetCoreWindowService\DotNetCore.WindowsService\Source\PeterKottas.DotNetCore.Example\bin\Debug\netcoreapp1.1\win10-x64>PeterKottas.DotNetCore.Example.exe action:install helps.

The response is following: Successfully registered and started service "PeterKottas.DotNetCore.Example.ExampleServiceTimer" ("No description"). You are right: after this we can reinstalling, installing, stopping starting as necessary.

This is enough for me

Simple question why we have error with sc.exe utility ?. This utility can change the display name of the Service and have the advantage.

PeterKottas commented 7 years ago

Simple question but the answer would be quite complicated. In essence, this util serves like a wrapper for windows layer that deals with services. Basically if you could do what you tried directly, this lib won't be needed at all. For convenience I've added the action:blabla (there's install uninstall stop start and so on, checkout the docs) to make it easier to work with. Glad that now it works for you ;) The error happens cause the app can't be hosted like that directly. Feel free to checkout the source code if you're interested in this. It's actually pretty straight forward (I think :) )

PeterKottas commented 7 years ago

Am I mad or was there an extra question that disappeared over night? Maybe you figured it out but I've reopened it just in case you wanted to discuss something extra about this.

Vladimir-Kharam commented 7 years ago

It was the question about Name of the Service and DisplayName of the Service. I have figured out how make this. Thanks again

PeterKottas commented 7 years ago

Cool, np. Closing for real now.

famous1234 commented 7 years ago

Hey Peter.Thanks for the project it has helped me a lot. But I'm having problem to connect with my database and post that data into notepad.Can You Help Me??? Thanks in Advance

PeterKottas commented 7 years ago

Sure I can help out but pls, create a new issue and give me some more info about the problem you are having @famous1234

famous1234 commented 7 years ago

Thank You For Your Reply... I'm not a pro I'm just a beginner and your project has helped me to create windows service in asp.net core But we are just writing the current time in our notepad But I need to post data from my database to API.So, Can You Please Help me or reference any project related to it. Thank You...

famous1234 commented 7 years ago

class Scheduler { System.Timers.Timer oTimer = null; double interval = 20000;

    public void Start()
    {
        oTimer = new System.Timers.Timer(interval);
        oTimer.AutoReset = true;
        oTimer.Enabled = true;
        oTimer.Start();

        oTimer.Elapsed += new System.Timers.ElapsedEventHandler(oTimer_Elapsed);
    }
    private void oTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        FileCreation();
    }
    void FileCreation()
    {
        DBLibrary oDBLibrary = new DBLibrary();
        DataTable dsPost = oDBLibrary.getPostDetails();
        if (dsPost != null)
        {
            if (dsPost.Rows.Count > 0)
            {
                string strCust = "";
                foreach (DataRow dr in dsPost.Rows)
                {
                    strCust += dr["PostID"].ToString()
                        + "," + dr["PostTitle"].ToString()
                        + "," + dr["PostText"].ToString() + Environment.NewLine;
                    //+ "," + dr["PhoneNo"].ToString()
                    //+ "," + dr["EmailID"].ToString()
                    //+ "," + dr["City"].ToString()
                    //+ "," + dr["Country"].ToString() + Environment.NewLine;
                }
                string sfilePath = @"C:\Users\FM12\Documents\visual studio 2015\Projects\SocialPostService\SocialPostServiceSetUp\Debug\Post.txt";
                System.IO.StreamWriter oFileWriter = new System.IO.StreamWriter(sfilePath, true);
famous1234 commented 7 years ago

class DBLibrary { string strConn = ConfigurationManager.ConnectionStrings["MyDBConfig"].ConnectionString;

    public DataTable getPostDetails()
    {

        DateTime TodayDate = new DateTime();
        TodayDate = DateTime.Now;
        TodayDate = TodayDate.AddMinutes(1);
        var datetime = TodayDate.ToString("yyyy-MM-dd HH:mm:ss");

        SqlConnection oSqlConnection = new SqlConnection(strConn);
        oSqlConnection.Open();

        SqlCommand oSqlCommand = new SqlCommand();
        oSqlCommand.CommandType = CommandType.StoredProcedure;
        oSqlCommand.CommandText = "pGetPostDetails";
        oSqlCommand.Connection = oSqlConnection;
        oSqlCommand.Parameters.AddWithValue("@SchedulDate", datetime);

        DataTable ds = new DataTable();
        SqlDataAdapter oSqlDataAdapter = new SqlDataAdapter(oSqlCommand);
        oSqlDataAdapter.Fill(ds);
        oSqlConnection.Close();
        return ds;
famous1234 commented 7 years ago

These are my classes that I created to get data from database and paste it to notepad but I created that in windows service template and I couldnt reference it to my asp.net core web application and post it to my facebook using API. Hence I found your project that just writes datetime to notepad. But I need to get data from database to post it in my API. Thank You...

samirbanjanovic commented 6 years ago

I don't know if this was resolved but I am able to run the application as a non service. However, the moment I try to install I receive a timeout error.

System.ComponentModel.Win32Exception (0x80004005): The service did not respond to the start or control request in a timely fashion at DasMulli.Win32.ServiceUtils.ServiceHandle.Start() at DasMulli.Win32.ServiceUtils.Win32ServiceManager.CreateService(String serviceName, String displayName, String description, String binaryPath, Win32ServiceCredentials credentials, Boolean autoStart, Boolean startImmediately, ErrorSeverity errorSeverity) at PeterKottas.DotNetCore.WindowsService.ServiceRunner'1.Install(HostConfiguration'1 config, ServiceController sc, Int32 counter) at PeterKottas.DotNetCore.WindowsService.ServiceRunner'1.UsingServiceController(HostConfiguration'1 config, Action'2 action) at PeterKottas.DotNetCore.WindowsService.ServiceRunner'1.Run(Action'1 runAction)

I will say I am using DI and I am not sure if that's the issue or if I am not configuring it correctly. `public class Program { static void Main(string[] args) { var services = new ServiceCollection();

        var startup = new Startup();

        startup.ConfigureServices(services);

        var provider = services.BuildServiceProvider();

        provider.GetService<ILoggerFactory>()
            .AddNLog()
            .ConfigureNLog(@"nlog.config");

        provider.GetService<IServiceHost>().Start();
    }
}`

`public class Startup { private IConfigurationRoot Configuration { get; }

    public Startup()
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile(@"appsettings.json", optional: false, reloadOnChange: true);

        Configuration = builder.Build();
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddTransient<IConfigurationRoot>(x => Configuration);

        services.AddLogging();

        services.AddTransient<IServiceHost, ServiceHost>();

        services.AddTransient<ICore.IIntegrationService, IntegrationService>();

        services.AddTransient<ICore.IConfiguration, Configuration>();

        services.AddTransient<IDataService>(x => new DataService(Configuration.GetConnectionString("ServiceConfig")));
    }
}`

`public class ServiceHost : IServiceHost { private readonly IIntegrationService _service; private readonly ILogger _hostLogger; private readonly IConfigurationSection _settings;

    public ServiceHost(IIntegrationService service, ILoggerFactory loggerFactory, IConfigurationRoot configRoot)
    {
        _service = service;
        _hostLogger = loggerFactory.CreateLogger<ServiceHost>();
        _settings = configRoot.GetSection("ServiceSettings");
    }

    public void Start()
    {
        try
        {
            ServiceRunner<IntegrationService>.Run(config =>
            {     
                config.SetName(_settings["Name"]);
                config.SetDisplayName(_settings["DisplayName"]);
                config.SetDescription(_settings["Description"]);

                config.Service(serviceConfig =>
                {
                    serviceConfig.ServiceFactory((extraArguments, controller) =>
                    {
                        return (IntegrationService)_service;
                    });

                    serviceConfig.OnStart((service, a) => service.Start());

                    serviceConfig.OnStop((service) => service.Stop());

                    serviceConfig.OnError((e) =>
                    {
                        _hostLogger.LogError(new EventId(100, "Failure"), e.InnerException, $"Service has crashed: {e.ToString()}");
                    });

                });

            });
        }
        catch (Exception e)
        {
            _hostLogger.LogError(new EventId(100, "Failure"), e.InnerException, "Host has crashed");
        }
    }
}`
sm-g commented 6 years ago

@SamirBanjanovic that is probably because Directory.GetCurrentDirectory() is C:\WINDOWS\system32 at runtime

sglcj commented 6 years ago

@PeterKottas thank you,your answer helped me

davelewis73 commented 5 years ago

@PeterKottas I am receiving the same 1503 error when I attempt to start my service. I have tried multiple ways to create my service, which all appear to work. I have tried using dotnet.exe and sc.exe. I can get the service to work in the background. However, I have never been able to create the service, have it show in the "Services" dialog, and start/stop it from there. This is very important because I need a way to easily see the state of the service. I get the same 1503 error every time when I try to start it there. I am not sure what I am doing wrong, because my console application follows the PeterKotas.DotNetCore.WindowsService example (with necessary content changes, of course). As an fyi, I am also trying to build this into a VSTS/Azure DevOps deployment pipeline.