Control Your Windows Service from a Asp.NET Web App, Start, Stop, Run A Method

  Maybe you find the need to; or you think of the possibilities of controlling a Windows Service from a Web App might be useful.  For me I like the idea of writing a Windows Service that does some server function but can be controlled or called by a user. This is a more detailed post on code examples from the previous post with some other considerations.

Examples Reasons?:

  1. Maybe a Administrator needs to start and stop services but doesn’t have access to the server by normal methods.
  2. A user that calls a Windows Service that performs some type of Emailing functionality such as a notifying users when they have a new Task.  Maybe this table is populated by many means. Win service would check the database every 30min and send off emails.  In your web app, your users are special, so every time they assign a task, you fire off the windows service right there and then. Or maybe sometimes you have the need to fire off a manual send and have written redundant code to do it.
  3. Windows service control center for developers? Or Support users?


Anyway, the process is quite easy.


Windows Service code, somewhere have a method like this…

Code Snippet
  1. Protected Overrides Sub OnCustomCommand(ByVal command As Integer)
  2.     MyBase.OnCustomCommand(command)
  3.     Select Case command
  4.         Case 130
  5.             'Call one of your other methods from here
  6.         Case 150
  7.             'Call some other method or command
  8.         Case Else
  9.             'Do Nothing
  10.     End Select
  11. End Sub

You can only call one CustomCommand, so you send in Command Integers and from there decided what you want to do.


In your ASP.Net app on a button click event..

Code Snippet
  1. Using sc As System.ServiceProcess.ServiceController = New System.ServiceProcess.ServiceController()
  2.     sc.MachineName = "Mastro-PC"
  3.     sc.ServiceName = "ComplyTrackMainTimer"
  4.     sc.ExecuteCommand(130)
  5.     'sc.Stop()
  6.     'sc.Start()
  7. End Using

This will work on a on a button click event. You have to set the MachineName and the ServiceName. You can also Stop() and Start() the Service or look up the Status.

You can get the MachineName of the server by opening a command prompt from the server and typing in “HostName”


You can get the ServiceName by opening up the server and looking at the name in Services. Don’t use the Display Name use the Service Name.


I have a previous post on this with more detailed information on valid Command Integers and Security.

Extending the ASP.NET MVC HtmlHelper in VB.NET Specifically

Cyclomatic and Maintenance Complexity using CodeRush per Mark Miller

Cyclomatic and Maintenance Complexity using CodeRush per Mark Miller