Click here to Skip to main content
15,881,089 members
Articles / Programming Languages / C#

How To Manage Windows Service Application on our Local Computer

Rate me:
Please Sign up or sign in to vote.
4.91/5 (26 votes)
4 Aug 2009CPOL2 min read 48.5K   1.6K   74   13
This article will demonstrate how we can manage Windows service application on our local computer.

Table of Contents

Image 1
Figure 1: Windows service application controller.

Introduction

Microsoft Windows services, formerly known as NT services, enable you to create long-running executable applications that run in their own Windows sessions. These services can be automatically started when the computer boots, can be paused and restarted, and do not show any user interface. These features make services ideal for use on a server or whenever you need long-running functionality that does not interfere with other users who are working on the same computer.

Reference - MSDN

In this article, we are going to create an application to get a list of service applications currently installed with the status and how to control (i.e., we can simultaneously Stop or Start multiple Services) each service application in your local computer.

Background

Windows service application is often used for various purposes like push pull data transfer, email, system monitor, etc. My concern is how to manage all the customized service applications in a local server / a remote server as well, that’s why I need to create tools where I can get all the status of specified service applications on a local / remote computer.

Types of Services

There are two types of services you can create in Visual Studio using the .NET Framework.

  1. Win32OwnProcess: Services that are the only service in a process are assigned the type Win32OwnProcess.
  2. Win32ShareProcess: Services that share a process with another service are assigned the type Win32ShareProcess.

*Note: You can retrieve the service type by querying the ServiceType property.
You might occasionally see other service types if you query existing services that were not created in Visual Studio. For more information on these, see the ServiceType.

Using the Code

Microsoft Visual Studio .NET Framework 2.0 / update version provides the namespace System.ServiceProcess and we are going to use ServiceController class found in the mentioned namespace. This class represents a Windows Service and allows you to connect to a Windows Service, to manipulate the service and get information about the service.

You can download the sample source code to get a complete picture of the program.

Sample Example

C#
public partial class Manager : Form
   {
       //string strServiceName = "";
       public string strServerName = "Local";
       class ServiceInfo
       {
           private string strName, strStatus;
           public ServiceInfo(string sName, string sStatus)
           {
               strName = sName;
               strStatus = sStatus;
           }
           public string ServiceName
           {
               get { return strName; }
           }
           public string ServiceStatus
           {
               get { return strStatus; }
           }
       }

       private ArrayList ALWServiceInfo;
       public Manager()
       {
           InitializeComponent();
           ALWServiceInfo = new ArrayList();
       }
       private void Manager_Load(object sender, EventArgs e)
       {
       }
       private void getWindowsServices()
       {
               ServiceController[] objArrServices;
               try
               {
                   if ((this.comboBoxServerNameOrIPs.Text == "Local")
                       || this.comboBoxServerNameOrIPs.Text ==
               System.Environment.MachineName.ToString ()
                       || this.comboBoxServerNameOrIPs.Text == "127.0.0.1")
                   {
                       objArrServices = ServiceController.GetServices();
                   }
                   else
                       objArrServices = ServiceController.GetServices
                   (comboBoxServerNameOrIPs.Text);
                   ALWServiceInfo.Clear();
                   foreach (ServiceController objServiceController in objArrServices)
                   {
                       ALWServiceInfo.Add(new ServiceInfo
           (objServiceController.ServiceName,
           objServiceController.Status.ToString()));
                   }
                   dgServices.DataSource = ALWServiceInfo;
                   dgServices.Refresh();
               }
               catch (Exception ex)
               {
                   MessageBox.Show("Error Occurred: " + ex.Message);
               }
       }
       private void buttonConnect_Click(object sender, EventArgs e)
       {
           this.getWindowsServices();
       }
       private void buttonClose_Click(object sender, EventArgs e)
       {
           Application.Exit();
       }
       private void setCommandButton()
       {
           //get the status of the service.
           string strServerStatus = WSControllerAgent.Status.ToString();
           //check the status of the service and enable the
           //command buttons accordingly.
           if (strServerStatus == "Running")
           {
               //check to see if the service can be paused
               if (WSControllerAgent.CanPauseAndContinue == true)
               {
                   ButtonPause.Enabled = true;
               }
               else
               {
                   ButtonPause.Enabled = false;
               }
               ButtonStop.Enabled = true;
               ButtonStart.Enabled = false;
           }
           else if (strServerStatus == "Paused")
           {
               ButtonStart.Enabled = true;
               ButtonPause.Enabled = false;
               ButtonStop.Enabled = true;
           }
           else if (strServerStatus == "Stopped")
           {
               ButtonStart.Enabled = true;
               ButtonPause.Enabled = false;
               ButtonStop.Enabled = false;
           }
       }
       private void getSelectedServiceStatus()
       {
           try
           {
           }
           catch (Exception ex)
           {
               MessageBox.Show("Error Occurred: " + ex.Message);
           }
       }
       private void dgServices_MouseClick(object sender, MouseEventArgs e)
       {
           this.onLoadWServices(this.dgServices.CurrentCell.Value.ToString());
       }
       private void onLoadWServices(string strServiceName)
       {
           try
           {
               ServiceController[] AvailableServices =
               ServiceController.GetServices(".");
               if (strServiceName != "")
               {
                   foreach (ServiceController AvailableService in AvailableServices)
                   {
                       //Check the service
                       if (AvailableService.ServiceName == strServiceName)
                       {
                           this.WSControllerAgent.ServiceName = strServiceName;
                           this.setCommandButton();
                           return;
                       }
                   }
               }
           }
           catch
           {
               MessageBox.Show("The Service is not installed on this Machine",
                       "Service is not available");
               this.Close();
               Application.Exit();
           }
       }
       private void ButtonStart_Click(object sender, EventArgs e)
       {
           //check the status of the service
           if (WSControllerAgent.Status.ToString() == "Paused")
           {
               WSControllerAgent.Continue();
           }
           else if (WSControllerAgent.Status.ToString() == "Stopped")
           {
               //get an array of services this service depends upon, loop through
               //the array and prompt the user to start all required services.
               ServiceController[] ParentServices = WSControllerAgent.ServicesDependedOn;
               try
               {
                   //if the length of the array is greater than or equal to 1.
                   if (ParentServices.Length >= 1)
                   {
                       foreach (ServiceController ParentService in ParentServices)
                       {
                           //make sure the parent service is running or at least paused.
                           if (ParentService.Status.ToString() != "Running" ||
               ParentService.Status.ToString() != "Paused")
                           {
                               if (MessageBox.Show("This service is required.
               Would you like to also start this service?\n" +
               ParentService.DisplayName, "Required Service",
               MessageBoxButtons.YesNo).ToString() == "Yes")
                               {
                                   //if the user chooses to start the service
                                   ParentService.Start();
                                   ParentService.WaitForStatus
                   (ServiceControllerStatus.Running);
                               }
                               else
                               {
                                   //otherwise just return.
                                   return;
                               }
                           }
                       }
                   }
                   WSControllerAgent.Start();
                   WSControllerAgent.WaitForStatus
           (System.ServiceProcess.ServiceControllerStatus.Running);
               }
               catch (Exception ex)
               {
                   MessageBox.Show("Error Occurred: " + ex.Message.ToString());
               }
               this.setCommandButton();
           }
       }
       private void ButtonPause_Click(object sender, EventArgs e)
       {
           //check to see if the service can be paused and continue
           if (WSControllerAgent.CanPauseAndContinue == true)
           {
               //check the status of the service
               if (WSControllerAgent.Status.ToString() == "Running")
               {
                   WSControllerAgent.Pause();
               }
               WSControllerAgent.WaitForStatus
           (System.ServiceProcess.ServiceControllerStatus.Paused);
               this.setCommandButton();
           }
       }
       private void ButtonStop_Click(object sender, EventArgs e)
       {
           //check to see if the service can be stopped.
           if (WSControllerAgent.CanStop == true)
           {
               //get an array of dependent services, loop through the array and
               //prompt the user to stop all dependent services.
               ServiceController[] DependentServices =
               WSControllerAgent.DependentServices;
               //if the length of the array is greater than or equal to 1.
               if (DependentServices.Length >= 1)
               {
                   foreach (ServiceController DependentService in DependentServices)
                   {
                       //make sure the dependent service is not already stopped.
                       if (DependentService.Status.ToString() != "Stopped")
                       {
                           if (MessageBox.Show("Would you like to also
                   stop this dependent service?\n"
                               + DependentService.DisplayName
                               , "Dependent Service"
                               , MessageBoxButtons.YesNo).ToString() == "Yes")
                           {
                               // not checking at this point whether the
                               // dependent service can be stopped.
                               // developer may want to include this check
                               // to avoid exception.
                               DependentService.Stop();
                               DependentService.WaitForStatus
                   (ServiceControllerStatus.Stopped);
                           }
                           else
                           {
                               return;
                           }
                       }
                   }
               }
               //check the status of the service
               if (WSControllerAgent.Status.ToString() ==
       "Running" || WSControllerAgent.Status.ToString() == "Paused")
               {
                   WSControllerAgent.Stop();
               }
               WSControllerAgent.WaitForStatus
           (System.ServiceProcess.ServiceControllerStatus.Stopped);
               this.setCommandButton();
           }
       }
    }

Conclusion

I hope it might be helpful to you. Enjoy!

History

  • 5th August 2009: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
QuestionCom+ monitor c# Pin
Didier Monge1-Sep-13 14:09
Didier Monge1-Sep-13 14:09 
GeneralMy vote of 4 Pin
Zdeněk Gold15-May-13 23:50
Zdeněk Gold15-May-13 23:50 
GeneralRe: My vote of 4 Pin
Md. Marufuzzaman16-May-13 0:36
professionalMd. Marufuzzaman16-May-13 0:36 
QuestionGreat Work !!! Pin
Amaan2329-Nov-12 4:14
Amaan2329-Nov-12 4:14 
AnswerRe: Great Work !!! Pin
Md. Marufuzzaman29-Nov-12 6:05
professionalMd. Marufuzzaman29-Nov-12 6:05 
Questionthank you Pin
computermorabbi@yahoo.com14-Oct-11 10:19
computermorabbi@yahoo.com14-Oct-11 10:19 
AnswerRe: thank you Pin
Md. Marufuzzaman15-Oct-11 0:52
professionalMd. Marufuzzaman15-Oct-11 0:52 
QuestionException Details Pin
computermorabbi@yahoo.com14-Oct-11 4:51
computermorabbi@yahoo.com14-Oct-11 4:51 
AnswerRe: Exception Details Pin
Md. Marufuzzaman14-Oct-11 5:01
professionalMd. Marufuzzaman14-Oct-11 5:01 
Questionplease help me. Pin
computermorabbi@yahoo.com14-Oct-11 1:54
computermorabbi@yahoo.com14-Oct-11 1:54 
AnswerRe: please help me. Pin
Md. Marufuzzaman14-Oct-11 2:17
professionalMd. Marufuzzaman14-Oct-11 2:17 
GeneralMy vote of 5 Pin
khalidC#22-Dec-10 19:08
khalidC#22-Dec-10 19:08 
GeneralRe: My vote of 5 Pin
Md. Marufuzzaman5-Oct-11 23:13
professionalMd. Marufuzzaman5-Oct-11 23:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.