Advertisement
Guest User

ap3rus

a guest
Aug 27th, 2010
1,630
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 8.04 KB | None | 0 0
  1. // WindowsService.cs
  2.  
  3. using System;
  4. using System.Collections.Generic;
  5. using System.ComponentModel;
  6. using System.Data;
  7. using System.Diagnostics;
  8. using System.Linq;
  9. using System.ServiceProcess;
  10. using System.Text;
  11. using System.IO;
  12.  
  13. namespace Foobar.Service
  14. {
  15.     public class WindowsService : ServiceBase
  16.     {
  17.         protected override void OnStart(string[] args)
  18.         {
  19.             Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
  20.             try
  21.             {
  22.                 if (_OnStart != null)
  23.                 {
  24.                     _OnStart(args);
  25.                 }
  26.             }
  27.             catch (Exception ex)
  28.             {
  29.                 _Log.Fatal("Could not properly start the service.", ex);
  30.                 _EventLog.WriteEntry("Could not properly start the service. " + ex, EventLogEntryType.Error);
  31.                 Stop();
  32.             }
  33.         }
  34.  
  35.         protected override void OnStop()
  36.         {
  37.             try
  38.             {
  39.                 if (_OnStop != null)
  40.                 {
  41.                     _OnStop();
  42.                 }
  43.             }
  44.             catch (Exception ex)
  45.             {
  46.                 _Log.Fatal("Could not properly stop the service.", ex);
  47.                 _EventLog.WriteEntry("Could not properly stop the service. " + ex, EventLogEntryType.Error);
  48.             }
  49.         }
  50.  
  51.         private readonly Action<string[]> _OnStart;
  52.  
  53.         private readonly Action _OnStop;
  54.  
  55.         private readonly EventLog _EventLog;
  56.  
  57.         private static readonly log4net.ILog _Log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  58.  
  59.         public WindowsService(Action<string[]> onStart, Action onStop, string serviceName)
  60.         {
  61.             InitializeComponent();
  62.             _OnStart = onStart;
  63.             _OnStop = onStop;
  64.             ServiceName = serviceName;
  65.             _EventLog = new EventLog("Application");
  66.             if (!System.Diagnostics.EventLog.SourceExists(serviceName))
  67.             {
  68.                 System.Diagnostics.EventLog.CreateEventSource(serviceName, "Application");
  69.             }
  70.  
  71.             _EventLog.Source = serviceName;
  72.         }
  73.  
  74.         #region Component Designer generated code
  75.  
  76.         /// <summary>
  77.         /// Required designer variable.
  78.         /// </summary>
  79.         private System.ComponentModel.IContainer components = null;
  80.  
  81.         /// <summary>
  82.         /// Clean up any resources being used.
  83.         /// </summary>
  84.         /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
  85.         protected override void Dispose(bool disposing)
  86.         {
  87.             if (disposing && (components != null))
  88.             {
  89.                 components.Dispose();
  90.             }
  91.             base.Dispose(disposing);
  92.         }
  93.  
  94.         /// <summary>
  95.         /// Required method for Designer support - do not modify
  96.         /// the contents of this method with the code editor.
  97.         /// </summary>
  98.         private void InitializeComponent()
  99.         {
  100.             components = new System.ComponentModel.Container();
  101.             this.ServiceName = "WindowsService";
  102.         }
  103.  
  104.         #endregion
  105.     }
  106. }
  107.  
  108. // WindowsServiceInstaller.cs
  109.  
  110. using System;
  111. using System.Collections;
  112. using System.Collections.Generic;
  113. using System.ComponentModel;
  114. using System.Configuration.Install;
  115. using System.Linq;
  116. using System.ServiceProcess;
  117.  
  118. namespace Foobar.Service
  119. {
  120.     [RunInstaller(true)]
  121.     public abstract class WindowsServiceInstaller : System.Configuration.Install.Installer
  122.     {
  123.         private ServiceProcessInstaller _ServiceProcessInstaller;
  124.  
  125.         private ServiceInstaller _ServiceInstaller;
  126.  
  127.         public override void Uninstall(System.Collections.IDictionary savedState)
  128.         {
  129.             var svcName = GetContextParameter("serviceName");
  130.             if (!string.IsNullOrEmpty(svcName))
  131.             {
  132.                 _ServiceInstaller.ServiceName = svcName;
  133.             }
  134.  
  135.             base.Uninstall(savedState);
  136.         }
  137.  
  138.         public override void Install(System.Collections.IDictionary stateSaver)
  139.         {
  140.             var svcName = GetContextParameter("serviceName");
  141.             if (!string.IsNullOrEmpty(svcName))
  142.             {
  143.                 _ServiceInstaller.ServiceName = svcName;
  144.             }
  145.  
  146.             base.Install(stateSaver);
  147.         }
  148.  
  149.         private string GetContextParameter(string key)
  150.         {
  151.             string sValue;
  152.             try
  153.             {
  154.                 sValue = this.Context.Parameters[key].ToString();
  155.             }
  156.             catch
  157.             {
  158.                 sValue = string.Empty;
  159.             }
  160.  
  161.             return sValue;
  162.         }
  163.  
  164.  
  165.         public WindowsServiceInstaller(string serviceName)
  166.         {
  167.             InitializeComponent();
  168.             _ServiceProcessInstaller = new ServiceProcessInstaller();
  169.             _ServiceProcessInstaller.Account = ServiceAccount.LocalSystem;
  170.             _ServiceProcessInstaller.Password = null;
  171.             _ServiceProcessInstaller.Username = null;
  172.  
  173.             _ServiceInstaller = new ServiceInstaller();
  174.             _ServiceInstaller.ServiceName = serviceName;
  175.             _ServiceInstaller.StartType = ServiceStartMode.Automatic;
  176.             Installers.AddRange(new Installer[]
  177.                                     {
  178.                                         _ServiceProcessInstaller,
  179.                                         _ServiceInstaller
  180.                                     });
  181.         }
  182.  
  183.         #region Component Designer generated code
  184.  
  185.         /// <summary>
  186.         /// Required designer variable.
  187.         /// </summary>
  188.         private System.ComponentModel.IContainer components = null;
  189.  
  190.         /// <summary>
  191.         /// Clean up any resources being used.
  192.         /// </summary>
  193.         /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
  194.         protected override void Dispose(bool disposing)
  195.         {
  196.             if (disposing && (components != null))
  197.             {
  198.                 components.Dispose();
  199.             }
  200.             base.Dispose(disposing);
  201.         }
  202.  
  203.         /// <summary>
  204.         /// Required method for Designer support - do not modify
  205.         /// the contents of this method with the code editor.
  206.         /// </summary>
  207.         private void InitializeComponent()
  208.         {
  209.             components = new System.ComponentModel.Container();
  210.         }
  211.  
  212.         #endregion
  213.     }
  214. }
  215.  
  216.  
  217. // Пример класса инсталлера который нужно добавить в главную сборку приложения, обязательно public:
  218.  
  219.     public class RouterWindowsServiceInstaller : Foobar.Service.WindowsServiceInstaller
  220.     {
  221.         public RouterWindowsServiceInstaller()
  222.             : base("Router")
  223.         {
  224.         }
  225.     }
  226.  
  227. // Ну и пример использования запуска службы :)
  228.  
  229.     class Program
  230.     {
  231.         static void Start()
  232.         {
  233. // ...
  234.         }
  235.  
  236.         static void Stop()
  237.         {
  238. // ...
  239.         }
  240.  
  241.         static void Main(string[] args)
  242.         {
  243.             XmlConfigurator.Configure();
  244.             if (Environment.UserInteractive)
  245.             {
  246.                 try
  247.                 {
  248.                     Start();
  249.                     Console.WriteLine("Service is working, press enter to leave.");
  250.                     Console.ReadLine();
  251.                     Stop();
  252.                 }
  253.                 catch (Exception ex)
  254.                 {
  255.                     _Log.Fatal("Fatal exception in main thread.", ex);
  256.                 }
  257.             }
  258.             else
  259.             {
  260.                 _Log.Info("Starting service.");
  261.                 ServiceBase.Run(new ServiceBase[] {
  262.                     new Foobar.WindowsService(a => Start(), () => Stop(), "Router") });
  263.             }
  264.         }
  265.  
  266.         private static readonly log4net.ILog _Log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  267.  
  268.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement