SharePoint Blogs / SharePoint University
SharePoint Blogs and SharePoint University - all in one place!
Need SharePoint Training? Attend a SharePoint Bootcamp!

Please delete cookies related to sharepointblogs.com and sharepointu.com to resolve login issues!

Automate server tasks using background Windows service

 

Overview

 

Windows service could be useful when a certain task needs to run in unattended manner.  This article covers how to programmatically start/stop windows service in remote machine within intranet so certain administration jobs can be automated.  The article will also cover some basic concept of Windows service so you can determine whether Window service is the right mechanism for your specific requirements.  The fact that you can have programming logic inside of Windows service is where we have big potential of doing many things with this.

 

Basic concepts on Windows service

 

-          Windows service is a service process running in the background within Windows server OS, so it cannot have its own user interface such as Web/Windows form.  However it can be invoked by users via Web/Windows forms interactively.

 

-          Again Windows service is a background process, it should use the Windows Event Log for possible output which can be, later, viewed by Windows event viewer.

 

-          Windows service is self-hosted, so it can be specifically useful in a situation where you cannot have a web server, for example, pure app server or file server.  Hence Windows service should be “installed” by its own installer provided by Visual Studio in conjunction with the command line utility named InstallUtil.exe.

 

Creating Windows service

-          Once you choose Windows service template, it will already have given you basic necessary details but if I re-capture:

 

1.       Reference (and corresponding using clause) to System.ServiceProcess namespace.

2.       create basic inheritance relationship to ServiceBase parent class.

3.       Misc items such as basic methods to override.

 

-          Add Installer

 

By right-clicking on the source code pane of the windows service, you can add Installer to the project.  There isn’t much details inside but it will be used by the InstallUtil.exe later when you install the service.

 

Install/Uninstall Windows service

-          Open up Visual Studio Command prompt and change the current folder to the one having the executable of the Windows service created.  Typical it’s under …\bin\Debug\ folder.

 

-          Type the following command to install your Windows service.

       InstallUtil  youWindowsService.exe 

 

-          In case you release updated version onto existing one, first uninstall using the following command and install again.  Installing is pretty straight-forward, however for any error during installation, check the log file - InstallUtil.InstallLog - in the same folder.  In case of Vista development environment, you should be aware of which account you are using for running the command prompt and run as in the properly permissioned “Run As”.

      InstallUtil/u  youWindowsService.exe 

 

-          Once this installation is done successfully, you will see your Windows service from the Services windows as in the following.

 

-          You can change the status and properties of the service including Start/Stop the service, Startup Type, Log on type and Recovery type.  These can be initially set programmatically and also changed later programmatically using service manager which is explained in the following section.

 

Create user interface remotely control the Windows service

-          Any interface, either Windows or Web forms, implementing System.ServiceProcess class can control Windows service programmatically.

 

-          Following is my demo windows form for handling some Windows service task remotely, where “bigbendvista” is the remote machine name and “AAADemoService” is the name of the service.

 

Windows service handler

 

-          First instantiate service controller as follows.

 

// Service in remote machine

ServiceController sc = new ServiceController(ServiceName, MachineName);

 

        //Service in local machine

ServiceController sc = new ServiceController(ServiceName);

 

-          Handles various status of the service.  For the switch statement handling all possible status can be easily written if you use a Visual Studio trick called "insert snippet" if you haven’t already noticed.  First Ctrl+K+X for the quick “insert snippet” tool come up and select switch statement and then simply type in the variable name into the “switch_on” placeholder and hit Enter.  Now ta-da!  You will have the beautiful switch statement automatically coded for you.  This is possible since ServiceController.Status is enum type.

            SetDisplay(sc);

       

 

        private void SetDisplay(ServiceController sc)

        {

            // Various service status

            this.labelStatus.Text = "Currently the service, " + ServiceName + ", in the machine, "

                + MachineName + " is " + sc.Status.ToString();

           

            switch (sc.Status)

            {

                case ServiceControllerStatus.ContinuePending:

                    break;

                case ServiceControllerStatus.PausePending:

                    break;

                case ServiceControllerStatus.Paused:

                    break;

                case ServiceControllerStatus.Running:

                    this.buttonStart.Enabled = false;

                    this.buttonStop.Enabled = true;

                    break;

                case ServiceControllerStatus.StartPending:

                    break;

                case ServiceControllerStatus.StopPending:

                    break;

                case ServiceControllerStatus.Stopped:

                    this.buttonStart.Enabled = true;

                    this.buttonStop.Enabled = false;

                    break;

                default:

                    break;

            }

  

-          Start or stop the service

 

        private void buttonStart_Click(object sender, EventArgs e)

        {

            try

            {

                // Prevent double clicks

                this.buttonStart.Enabled = false;

                this.buttonStop.Enabled = false;

               

                sc.Start();

                sc.WaitForStatus(ServiceControllerStatus.Running);

                SetDisplay(sc);

            }

            catch (Exception ex)

 

            {

                this.labelStatus.Text = "The service couldn't be started.  Error code:" + ex.Message;

            }

        }

 

-          WaitForStatus() is important since Starting or Stoping service requires time and the program execution does not wait for this result to come back – both operations cannot be synchronized.  This can mislead whole program execution if there are conditional logics below based upon the result.

 

sc.WaitForStatus(ServiceControllerStatus.Running);

 

Impersonation

 

-          In case the windows service is set with specific domain user having specific permission, then the user may need to be set into impersonation for running the control program.  In case of Web-based control program, it should have this impersonation information in the XML configuration file such as web.config.

 

Reference 

 

There is a very great blog post on Windows service with greater details.  Check the following and its threads upto part 8.

http://arcanecode.wordpress.com/2007/05/21/windows-services-in-c-getting-started-part-1/


Posted 11-11-2008 4:40 PM by michaelkim

Add a Comment

(required)  
(optional)
(required)  
Remember Me?
Need SharePoint Training? Attend a SharePoint Bootcamp!
Posts (c) their respective authors. Everything else (c) 2009 SharePoint Experts, Inc.