Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How To Manage Windows Service Application on our Local Computer

0.00/5 (No votes)
4 Aug 2009 1  
This article will demonstrate how we can manage Windows service application on our local computer.

Table of Contents

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

 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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here