VB.NET • Override the Base Class Routines

Listing 1. You can define your own service event handlers by overriding the procedures defined in the service base class.

Protected Overrides Sub OnStart(ByVal args() As _
   String)
   ' Add code here to execute when service first 
   ' starts up. An example could be to spin off a 
   ' thread with a timer that does stuff in the 
   ' background.

   ' See if the path to the log file was sent as an 
   ' argument
   If (args.Length = 0) Then
      strLogDest = "\Monitor.txt"
   Else
      strLogDest = args(0).ToString
   End If
   WriteAuditEntry(Now.ToString + _
      ": Service Started")
End Sub

Protected Overrides Sub OnStop()
   ' Add code here to perform any tear-down necessary 
   ' to stop your service.
   WriteAuditEntry(Now.ToString + _
      ": Service Stopped")
End Sub

Protected Overrides Sub OnPause()
   ' Add code here to perform work needed to 
   ' pause the service
   WriteAuditEntry(Now.ToString + ": Service Paused")
End Sub

Protected Overrides Sub OnContinue()
   ' Add code here to perform work needed to 
   ' resume the service
   WriteAuditEntry(Now.ToString + _
      ": Service Resumed")
End Sub

Protected Overrides Sub OnCustomCommand( _
   ByVal iCommand As Integer)
   ' Add code here to perform work needed to 
   ' handle a custom command to the service from
   ' an external application.

   ' Determine the command and log the event
   Select Case iCommand
      Case MonitorWrapper.MonitorWrapper. _
         MonitorCode.MON_GATE_A_OPEN
         WriteAuditEntry(Now.ToString + _
            ": Gate A Opened")
      Case MonitorWrapper.MonitorWrapper. _
         MonitorCode.MON_GATE_B_OPEN
         WriteAuditEntry(Now.ToString + _
            ": Gate B Opened")
      Case MonitorWrapper.MonitorWrapper. _
         MonitorCode.MON_FIREALARM_A
         WriteAuditEntry(Now.ToString + _
            ": Zone A Fire Alarm Activated")
      Case MonitorWrapper.MonitorWrapper. _
         MonitorCode.MON_SPRINKLER_A
         WriteAuditEntry(Now.ToString + _
            ": Sprinkler System Zone A Activated")
      Case Else
         WriteAuditEntry(Now.ToString + _
            ": UNDEFINED COMMAND RECEIVED (" + _
            iCommand.ToString + ")")
   End Select
End Sub

Private Sub WriteAuditEntry(ByVal strMsg As String)
   Dim sw As StreamWriter

   If File.Exists(strLogDest) Then
      sw = New StreamWriter(strLogDest, True)
   Else
      sw = File.CreateText(strLogDest)
   End If
   sw.WriteLine(strMsg)
   sw.Close()
End Sub