-6

I am trying to building generic tool from which we can control any windows service in the window operating system using asp.net window app, i got this references but not able to start: control the Windows Service in window popup i have added two buttons start and stop but not able to start the code.

public partial class Form3 : Form
{
    public Form3()
    {
        InitializeComponent();
    }

    private void start_Click(object sender, EventArgs e)
    {
       // here can service will start
       var services = ServiceController.GetServices(machineName);
       var service = services.First(s => s.ServiceName == "MyServiceName");
        service.Start();
    }
    private void stop_Click(object sender, EventArgs e)
    {
       // here can service will stop
       var services = ServiceController.GetServices(machineName);
       var service = services.First(s => s.ServiceName == "MyServiceName");
      service.Stop();

    }
}
Mr doubt
  • 51
  • 1
  • 10
  • 42
  • I've used ServiceController before. Does that not work for you? What specific errors or event logs do you get? Is it a permissions problem? Are you running this code as a local admin user? – Rup Jun 30 '21 at 09:22
  • 2
    What did you try? What was the problem? Why can't you use the answer you linked to? Why shouldn't this question be closed as a duplicate of the question you already linked to? – Panagiotis Kanavos Jun 30 '21 at 09:29
  • 1
    The documentation of the [ServiceController](https://learn.microsoft.com/en-us/dotnet/api/system.serviceprocess.servicecontroller?view=dotnet-plat-ext-5.0) class mentioned in the duplicate question has a full example. – Panagiotis Kanavos Jun 30 '21 at 09:32
  • 2
    What's the real question? Have you tried to use the answer's code *at all*? Did you encounter a problem? What was it? – Panagiotis Kanavos Jun 30 '21 at 09:39
  • 1
    @mohdmazharkhan so what you really look for is a Windows Forms tutorial. You already have the code to start/stop services. You're asking how to add buttons to a form. This has nothing to do with services – Panagiotis Kanavos Jun 30 '21 at 09:43
  • Start with the [documentation's tutorial](https://learn.microsoft.com/en-us/visualstudio/ide/tutorial-1-create-a-picture-viewer?view=vs-2019). It shows how to create a Winforms app, how to [add controls including buttons](https://learn.microsoft.com/en-us/visualstudio/ide/step-5-add-controls-to-your-form?view=vs-2019) and how to [handle control events like clicks on buttons](https://learn.microsoft.com/en-us/visualstudio/ide/step-8-write-code-for-the-show-a-picture-button-event-handler?view=vs-2019) – Panagiotis Kanavos Jun 30 '21 at 09:45
  • So what's the problem????? You already linked to the answer. SO isn't a code-writing service. Have you tried *anything* yet? Have you tried using that code ? – Panagiotis Kanavos Jun 30 '21 at 09:54
  • @mohdmazharkhan you already linked to that answer yourself. Frankly, it looks like you're asking people to write your code for you. In this case, just copy/paste **two lines you already provided**. That's why you got so many downvotes already. It doesn't look like you've tried anything. The only reason for such a request is unfamiliarity with Windows Forms. The answer to *this* question contains **the same code** as the linked answer once it's cleaned up. `var service = new ServiceController(serviceName); service.Start();`. That's it – Panagiotis Kanavos Jun 30 '21 at 10:00
  • Machine name: you don't need to pass one to GetServices. [Here's the documentation](https://learn.microsoft.com/en-us/dotnet/api/system.serviceprocess.servicecontroller.getservices?view=netframework-4.8): if you don't specify a machine name parameter it will use the local computer. Or you can use [this constructor instead](https://learn.microsoft.com/en-us/dotnet/api/system.serviceprocess.servicecontroller.-ctor?view=netframework-4.8#System_ServiceProcess_ServiceController__ctor_System_String_) as in reas's answer. – Rup Jun 30 '21 at 11:44
  • Service name to start and stop: you'd need to get that from the UI. Do you have a list of services on the UI already? Which control are you using, how do you read the selection from that control? – Rup Jun 30 '21 at 11:44
  • @mohdmazharkhan that's not what you asked at all. Instead of trying to trick people into not closing your questions, *post a good question*. You posted code for a desktop application when you have a web site? Why???? Just to avoid people asking `what did you try?`? Well what *did* you try? Why didn't you try the code you already have in a controller action? Why mention Windows Forms at all? You could have asked `How can I control Windows services from an MVC action?`? – Panagiotis Kanavos Jun 30 '21 at 12:05
  • @mohdmazharkhan if you try to control a service from a controller action you may get an Access denied because your app pool account can't control services. That's a different issue, fixed by either giving it the necessary permissions or using a different account. – Panagiotis Kanavos Jun 30 '21 at 12:10

2 Answers2

0

The linked answer shows how to start and stop services. First, create an instance of the ServicesController class, passing the name of the service. You can use the controller to control the service by calling its methods, eg Start to start it, Stop to stop it.

Services don't start or stop instantly, so you should probably warn the user if it takes too long.

Try this:

    private void start_Click(object sender, EventArgs e)
    {
        string serviceName = "yourServiceName";
        double timeoutMilliseconds = 10_000;
        TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);   
        
        ServiceController service = new ServiceController(serviceName);
        try
        {
            service.Start();                
            service.WaitForStatus(ServiceControllerStatus.Running, timeout);
        }
        catch(InvalidOperationException exc)
        {
            MessageBox.Show($"The service failed to start in a timely manner\n\n{exc}");                
        }
    }

    private void stop_Click(object sender, EventArgs e)
    {
        string serviceName = "yourServiceName";
        double timeoutMilliseconds = 10_000;
        TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

        ServiceController service = new ServiceController(serviceName);
        try
        {
            service.Stop();
            service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
        }
        catch(InvalidOperationException exc)
        {
            MessageBox.Show($"The service failed to start in a timely manner\n\n{exc}");                
        }
    }
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
reas
  • 379
  • 1
  • 6
  • 1
    Why would that answer the question? It's a more complex version of what the linked duplicate already shows. There's no need for the tiemouts either – Panagiotis Kanavos Jun 30 '21 at 09:40
  • And that `catch{}` should never appear in real code – Panagiotis Kanavos Jun 30 '21 at 09:41
  • @PanagiotisKanavos this is just an example to get started and NOT production ready code. – reas Jun 30 '21 at 09:43
  • 1
    @mohdmazharkhan that answer is exactly what you already linked to. I'm asking for several minutes now just that - what's wrong with the answer you linked to? – Panagiotis Kanavos Jun 30 '21 at 09:46
  • @mohdmazharkhan the really bad thing is the `catch{}`. The timeout isn't really needed. What's the point of checking for a timeout if `catch{}` ignores it? The rest is **exactly** the same code you linked to. – Panagiotis Kanavos Jun 30 '21 at 09:47
  • 2
    @reas finally, questions that just ask people to write the code aren't good questions and shouldn't be answered. PS: instead of using `throw` inside `catch` remove the `try/catch` completely. – Panagiotis Kanavos Jun 30 '21 at 09:56
  • @mohdmazharkhan you said you have a Windows Forms application, not MVC. That's a *desktop* application, not a web site. There are no button events in ASP.NET MVC. There are controllers and actions. You *can* control services by using `ServiceController` in a controller action – Panagiotis Kanavos Jun 30 '21 at 11:58
  • @reas I edited the answer to show what a good answer would look like *and* upvoted. Someone else downvoted. It also looks like the OP wants something completely different though, and the question's code is just filler to avoid people asking `what did you try?`. All that effort to keep a bad question open instead of writing a good question – Panagiotis Kanavos Jun 30 '21 at 12:01
  • you are great thanks for your effort which i am not getting, i am getting exeception: "Service xyzService was not found on computer '.'." and run visual studio run as admin but also getting same error. @PanagiotisKanavos – Mr doubt Jun 30 '21 at 13:17
0

Starting a Windows Service using C# This method below will start the windows service “aspnet_state” and waits until the service is executing or a timeout halts it.

Before you get started, you will have to add the assembly System.ServiceProcess.dll to your solution, then add the namespace below:

using System.ServiceProcess; And the method to start windows services:

public static void StartWindowsService()
{
    string serviceName = "aspnet_state";
    ServiceController serviceController = new ServiceController(serviceName);
    TimeSpan timeout = TimeSpan.FromMilliseconds(1000);
    serviceController.Start();
    serviceController.WaitForStatus(ServiceControllerStatus.Running, timeout);
}

Stopping a Windows Service using C# The following method will stop the Windows Service “aspnet_state” and will wait until the service is stopped or a timeout event occurs.

public static void StopWindowsService()
{
    string serviceName = "aspnet_state";
    ServiceController serviceController = new ServiceController(serviceName);
    TimeSpan timeout = TimeSpan.FromMilliseconds(1000);
    serviceController.Stop();
    serviceController.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
}

Restarting a Windows Service using C# This method is a combination of the upper two methods. It will stop the service and then start it and waits until the service is running.

public static void RestartWindowsService()
{
    string serviceName = "aspnet_state";
    ServiceController serviceController = new ServiceController(serviceName);
    int tickCount1 = Environment.TickCount;
    int tickCount2 = Environment.TickCount;
    TimeSpan timeout = TimeSpan.FromMilliseconds(1000);
    serviceController.Stop();
    serviceController.WaitForStatus(ServiceControllerStatus.Stopped, timeout);

    timeout = TimeSpan.FromMilliseconds(1000 - (tickCount1 - tickCount2));
    serviceController.Start();
    serviceController.WaitForStatus(ServiceControllerStatus.Running, timeout);
}
Reza Faghani
  • 141
  • 1
  • 10
  • what is difference between your code and reas answer. @Reza Faghani – Mr doubt Jul 06 '21 at 13:58
  • with the WaitForStatus you can be sure that service start ,stop or restart correctly . – Reza Faghani Jul 06 '21 at 17:32
  • from first answer i am getting exception {"Cannot start service aspnet_state on computer '.'."}. @Reza Faghani – Mr doubt Jul 07 '21 at 13:28
  • from your answer : System.InvalidOperationException: 'Cannot start service aspnet_state on computer '.'.' Win32Exception: The service cannot be started, either because it is disabled or because it has no enabled devices associated with it. @Reza Faghani – Mr doubt Jul 07 '21 at 13:34
  • my service name is not working in system, i have added aspnet_state service name also not working, getting same eror above, do you have any service name to check working or not in local system. @Reza Faghani – Mr doubt Jul 07 '21 at 13:41
  • I wrote a sample for you to know how to use it. but remember that while you try to access system resources your app should have Administrator permission. cause that you should run your application as administrator. the sample in github : https://github.com/rezafaghani/ServiceControlApp – Reza Faghani Jul 08 '21 at 12:01
  • Is this code is working on your system. @Reza Faghani – Mr doubt Jul 08 '21 at 12:03
  • already i have did Administrator permission to visual studio but same error. You have given wrong url of github. @Reza Faghani – Mr doubt Jul 08 '21 at 12:13
  • are you kidding me ? just click on url it's send you to my repo. and yes its working on my system – Reza Faghani Jul 08 '21 at 12:16
  • can we chat i will share its showing 404 page error when i will click on your above url please check in other browser without github login. @Reza Faghani – Mr doubt Jul 08 '21 at 12:18