Windows Services in C#: Sending Commands to your Windows Service (part 7)

Yesterday we looked at starting and stopping your windows service from another application. It would also be helpful to be able to send other commands beyond the basic set of Start/Stop/Pause etc.

On the good side, there is an API through which it is possible to send a command to your windows service, fairly easily as a matter of fact. The down side is it’s a one way communication, through the built in mechanism it’s not possible to return any data. Even more limiting is the only data you are allowed to pass in is an integer, and it’s value must be between 128 and 255.

Even with those limitations, if all you need to do is execute a few simple commands the built in API can be more than enough to meet your needs.

To illustrate, we’ll expand the windows service we’ve been using as an example. We’ll add the ability to send a command that will force the event log to be updated immediately, rather than waiting on the timer to fire off its event.

First, we’ll add two items to the service. The first is a public enum. Strictly speaking we don’t have to use an enum, but it makes for more readability.

    // Must be int between 128 and 255

    public enum commands

    {

      LogIt = 255

    }

Next we’ll add a new method to the windows service called OnCustomCommand. This is an override to the base classes method. As you can see it first calls the base method, then checks the value of the integer that was passed in, in this case against our enum. If it finds a match, it calls the WriteToLog method immediately. (The WriteToLog was discussed yesterday, so I won’t reiterate here).

    protected override void OnCustomCommand(int command)

    {

      base.OnCustomCommand(command);

      if (command == (int)commands.LogIt)

      {

        WriteToLog(“Arcane LogIt:”);       

      }

    }

OK, that’s all that’s needed for the service. Let’s switch to our program, and add another button called LogIt.

[Pic of TLManager]

Now we’ll add a little code to the click event for the log it button.

    private void btnLogIt_Click(object sender, EventArgs e)

    {

      ServiceController sc = new ServiceController(“ArcaneTimeLogging”);

      sc.ExecuteCommand(255);

    }

Like in our other examples we create a reference to our service by creating a new ServiceController object and passing in the name of our service. Once we have an sc object we call the ExecuteCommand method. This allows us to send messages to a windows service.

Numbers 0-127 are reserved for windows, and are handled in the base class. 128 to 255 are there for your own use. In the example above I used 255 just to show that you could pass an integer value directly without using an enum.

One last small item, we don’t want the LogIt button to be enabled if our service isn’t running. We’ll add a little logic to the SetDisplay, Start and Stop methods to include setting the buttons enabled status properly. Here’s the updated routines.

    private void SetDisplay(ServiceController sc)

    {

      sc.Refresh();

      if (sc.Status == ServiceControllerStatus.Stopped)

      {

        btnStop.Enabled = false;

        btnStart.Enabled = true;

        btnLogIt.Enabled = false;

        lblStatus.Text = “Stopped”;

      }

      if (sc.Status == ServiceControllerStatus.Running)

      {

        btnStart.Enabled = false;

        btnStop.Enabled = true;

        btnLogIt.Enabled = true;

        lblStatus.Text = “Running”;

      }

    }

 

    private void btnStart_Click(object sender, EventArgs e)

    {

      ServiceController sc = new ServiceController(“ArcaneTimeLogging”);

      sc.Start();

      btnStart.Enabled = false;

      btnStop.Enabled = true;

      lblStatus.Text = “Running”;

      sc.Refresh();

    }

 

    private void btnStop_Click(object sender, EventArgs e)

    {

      ServiceController sc = new ServiceController(“ArcaneTimeLogging”);

      sc.Stop();

      btnStop.Enabled = false;

      btnStart.Enabled = true;

      lblStatus.Text = “Stopped”;

      sc.Refresh();

    }

And that’s all there is to it. Compile and reinstall your service, then launch your TLManager program. With the service started, click the LogIt button a few times then go into MMC and take a look at your event log. You should see a new message appear each time you click the LogIt button.

About these ads

16 Responses to “Windows Services in C#: Sending Commands to your Windows Service (part 7)”

  1. Ajit Kumar Thakur Says:

    Nice Article OnCustom Command

  2. Hagashen Says:

    Awesome article really useful.

  3. Roamar Says:

    Yep!

    Good work budy!

  4. Sameh Salem Says:

    amazing you really solve my problem

    oncustom commands wowwwww!!!

  5. vasek7 Says:

    Hi, how can I use this:
    ServiceController sc = new ServiceController(“ArcaneTimeLogging”);
    sc.ExecuteCommand(255);
    in my unmanaged C++ code?

  6. Sumit Says:

    Hi,

    I have one Windows Service say A.exe. This windows service is running properly. Now I want to pass three parameters to this service by command line only as follows:

    A.exe parameter1 parameter2 parameter3

    My Service A.exe should accept these parameters and should do some stuff on the basis of these parameters.

    And some external code would continuously execute command – A.exe parameter1 parameter2 parameter3 and each time value of these parameters would be different.

    Could you please suggest how to handle this kind of requirement?

    Thanks in Advance.

  7. Raj Says:

    Hey,
    The article was very useful..thank you so much. But I need to do something more. I have this windows service running along with my application and I can connect to it without any problem using ServiceController. But I want the service to return a value. Is there any way I can do it.. What is .net remoting. Can I make my service return a value using .net remoting….

  8. Ali Says:

    Excellent Stuff

  9. TJ Says:

    Help!!

    I built a windows service that i install from another application. the problem is when it gets installed, it isn’t visible to any .NET application unless i restart the computer, in other words, if I go to the windows services application that ships with windows I can see my service but not with: ServiceController sc = new ServiceController(“MyService”); It just doesnt find it unless I restart the system and it’s driving me nuts!!! can you please give some advice!?

  10. Shahrokh Says:

    Good Job .

  11. bharathi Says:

    how to pass values to a service which is running on remote system from a window application….. Please help

  12. Jonas Says:

    Thanks!

  13. shujaat Says:

    i have tried followed your instructions given above but it is saying ‘Cannot control service on computer ‘.’.’.
    Any help ?

  14. oxitamins.com Says:

    Thank you for sharing your thoughts. I truly appreciate your efforts and I am waiting for
    your further post thanks once again.

  15. larrybud Says:

    Not sure if anyone is monitoring this anymore, but is there a way to send a command to a service on a remote machine within the same domain?


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 93 other followers

%d bloggers like this: