Click here to Skip to main content
Click here to Skip to main content

How To Manage Windows Service Application on our Local Computer

By , 4 Aug 2009
 

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)

About the Author

Md. Marufuzzaman
CEO
Bangladesh Bangladesh
Member
He is the founder & CEO of MNH Technologies and working for urban and rural sectors to improve people’s lifestyle, better medical facilities, education, social business etc. He has over ten years of professional experiences in design and developing Client-Server, Multi-Tier, Database, Web based business software solutions, Enterprise Applications, API, WebAPI, Google Analytics implementation, Add-In, Documentation & Technical Writing etc for Windows / Mac using Microsoft SQL Server, Oracle, MySql, PS, C#, VB.NET, ASP.NET, PHP, RoR, Visual Basic etc. He has also more than two years experience in Mobile-VAS (Platform Development).
 
He worked for various software development & technology consulting. His core focus on technologies to create dynamic data-driven systems that add value to your business and dynamic technology consulting that builds advanced solutions for the industries across the various vertices.
 
He also work as a Solution Architect at Dhrupadi Techno Consortium Limited (DTCL) and responsible for analyzing business requirements and offered optimum solutions (multiple options), which would address all current requirements, provide flexibility for future growth and allow smooth transition between old system and new system.
 
He graduated with honors from The University of Asia Pacific, in Computer Science and Engineering. He was awarded as “Most Valuable Professional” (MVP) at 2010 and 2011 by CodeProject.com and also selected as a Mentor of CodeProject.com
 
Specialties: Software Development Management, System Integration, Data Warehouse Architecture, Virtualization.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 4memberZigi3415 May '13 - 23:50 
GeneralRe: My vote of 4mentorMd. Marufuzzaman16 May '13 - 0:36 
QuestionGreat Work !!!memberAmaan2329 Nov '12 - 4:14 
AnswerRe: Great Work !!!mentorMd. Marufuzzaman29 Nov '12 - 6:05 
Questionthank youmembercomputermorabbi@yahoo.com14 Oct '11 - 10:19 
AnswerRe: thank youmvpMd. Marufuzzaman15 Oct '11 - 0:52 
QuestionException Detailsmembercomputermorabbi@yahoo.com14 Oct '11 - 4:51 
AnswerRe: Exception DetailsmvpMd. Marufuzzaman14 Oct '11 - 5:01 
Questionplease help me.membercomputermorabbi@yahoo.com14 Oct '11 - 1:54 
AnswerRe: please help me.mvpMd. Marufuzzaman14 Oct '11 - 2:17 

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 4 Aug 2009
Article Copyright 2009 by Md. Marufuzzaman
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid