andrew4582

Windows Service (Basic)

Aug 26th, 2010
232
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.26 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Diagnostics;
  6. using System.Linq;
  7. using System.ServiceProcess;
  8. using System.Text;
  9.  
  10. namespace ProductivityWatcher.Services {
  11.  
  12.     partial class pwa:ServiceBase {
  13.          
  14.         readonly PWService _service;
  15.  
  16.         public pwa() {
  17.             InitializeComponent();
  18.             _service = new PWService();
  19.         }
  20.  
  21.         protected override void OnStart(string[] args) {
  22.  
  23.             try {
  24.  
  25.                 bool flag = _service.Start(args);
  26.  
  27.                 if(!flag) {
  28.                     LogError(message :"PWService failed to start, PWService->Start() returned 'false'",entryType :EventLogEntryType.FailureAudit);
  29.                     this.Stop();
  30.                     return;
  31.                 }
  32.  
  33.                 Debug.WriteLine("PWService started");
  34.             }
  35.             catch(Exception error) {
  36.  
  37.                 LogError(message :"PWService failed to start",error:error);
  38.  
  39.                 this.Stop();
  40.             }
  41.         }
  42.  
  43.         protected override void OnStop() {
  44.             try {
  45.  
  46.                 if(!_service.IsStarted)
  47.                     return;
  48.  
  49.                 bool flag = _service.Stop();
  50.  
  51.                 if(!flag) {
  52.                     LogError(message :"PWService failed to stop, PWService->Stop() returned 'false'");
  53.                     return;
  54.                 }
  55.  
  56.                 Debug.WriteLine("PWService stopped");
  57.             }
  58.             catch(Exception error) {
  59.                 LogError(message :"PWService failed to stop",error :error);
  60.             }
  61.  
  62.         }
  63.  
  64.         void LogError(string message = null,Exception error = null,EventLogEntryType entryType = EventLogEntryType.Error) {
  65.  
  66.             string msg = message ?? "[NO MESSAGE] ";
  67.             if(error != null) {
  68.                 msg += " - ";
  69.                 msg += error.Message;
  70.                 msg += Environment.NewLine;
  71.                 msg += error.ToString();
  72.             }
  73.             msg += " - Assembly Version: " + this.GetType().Assembly.GetName().Version.ToString();
  74.             this.EventLog.WriteEntry(msg,EventLogEntryType.Error,PWService.EVENTLOG_ID);
  75.            
  76.             Debug.WriteLine(msg);
  77.         }
  78.     }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment