Click here to Skip to main content
Click here to Skip to main content
Go to top

How To Manage Windows Service Application on our Local Computer

, 4 Aug 2009
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Md. Marufuzzaman
CEO
Bangladesh Bangladesh
A highly experienced leader with successful track record of software development, product innovations, brand management and corporate communication etc. Some successful product innovations have also achieved and awards “Most Valuable Professional” (MVP) at 2010 and 2011 by codeproject.com and also selected as a mentor of codeproject.com. Published over 100 technical articles in various software development resource sites (i.e., codeprojetc.com, Microsoft MSDN, and IEEE & IBM (In progress)) and various IT Forums, Blogs etc.
 
Over ten years of professional experiences in ICT field having extensive experience in formulating corporate vision and long term strategy. Leading development related functions including design, development, services, data management and analytics, customer experience management, content services, digital analytics and optimization.
 
An individual with results-driven approach and relentless in pursuit of excellence from a business and organizational standpoint. Believes in transparency, commitment and teamwork.
 
Expertise: Software/Solution Architect, SaaS platform base application, Large scale win32/web based business software solutions, enterprise applications, integration, etc.
 
Technologies/Tools: Microsoft.Net version 05/08/10/12, Microsoft SQL Server version 7/2K/05/08/12 , Oracle version 10/11, MySql version 5.1, 5.5, PS2, Visual C#, R, VB.NET, ASP.NET, PHP, API, MVC, WebAPI , Add-In Visual Basic etc.,. I have also more than two years’ of strong experience in mobile-VAS (platform development).
 
Points of Interest: Technology and research & development especially focused on business functionalities and social business areas as well, few stuff including:
 
1.R&D on new techniques as required to increase business revenue.
2.Urban and rural sectors to improve people’s lifestyle, better medical facilities, education, social business etc., using innovative technical solutions.
3.Research and innovative product development.
4.Etc.
Follow on   Twitter   LinkedIn

Comments and Discussions

 
QuestionCom+ monitor c# PinmemberDidier Monge1-Sep-13 14:09 
GeneralMy vote of 4 PinmemberZigi3415-May-13 23:50 
GeneralRe: My vote of 4 PinmentorMd. Marufuzzaman16-May-13 0:36 
QuestionGreat Work !!! PinmemberAmaan2329-Nov-12 4:14 
AnswerRe: Great Work !!! PinmentorMd. Marufuzzaman29-Nov-12 6:05 
Questionthank you Pinmembercomputermorabbi@yahoo.com14-Oct-11 10:19 
AnswerRe: thank you PinmvpMd. Marufuzzaman15-Oct-11 0:52 
QuestionException Details Pinmembercomputermorabbi@yahoo.com14-Oct-11 4:51 
AnswerRe: Exception Details PinmvpMd. Marufuzzaman14-Oct-11 5:01 
Questionplease help me. Pinmembercomputermorabbi@yahoo.com14-Oct-11 1:54 
AnswerRe: please help me. PinmvpMd. Marufuzzaman14-Oct-11 2:17 
GeneralMy vote of 5 PinmemberkhalidC#22-Dec-10 19:08 
GeneralRe: My vote of 5 PinmvpMd. Marufuzzaman5-Oct-11 23:13 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140922.1 | Last Updated 4 Aug 2009
Article Copyright 2009 by Md. Marufuzzaman
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid