Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // WindowsService.cs
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Diagnostics;
- using System.Linq;
- using System.ServiceProcess;
- using System.Text;
- using System.IO;
- namespace Foobar.Service
- {
- public class WindowsService : ServiceBase
- {
- protected override void OnStart(string[] args)
- {
- Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
- try
- {
- if (_OnStart != null)
- {
- _OnStart(args);
- }
- }
- catch (Exception ex)
- {
- _Log.Fatal("Could not properly start the service.", ex);
- _EventLog.WriteEntry("Could not properly start the service. " + ex, EventLogEntryType.Error);
- Stop();
- }
- }
- protected override void OnStop()
- {
- try
- {
- if (_OnStop != null)
- {
- _OnStop();
- }
- }
- catch (Exception ex)
- {
- _Log.Fatal("Could not properly stop the service.", ex);
- _EventLog.WriteEntry("Could not properly stop the service. " + ex, EventLogEntryType.Error);
- }
- }
- private readonly Action<string[]> _OnStart;
- private readonly Action _OnStop;
- private readonly EventLog _EventLog;
- private static readonly log4net.ILog _Log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
- public WindowsService(Action<string[]> onStart, Action onStop, string serviceName)
- {
- InitializeComponent();
- _OnStart = onStart;
- _OnStop = onStop;
- ServiceName = serviceName;
- _EventLog = new EventLog("Application");
- if (!System.Diagnostics.EventLog.SourceExists(serviceName))
- {
- System.Diagnostics.EventLog.CreateEventSource(serviceName, "Application");
- }
- _EventLog.Source = serviceName;
- }
- #region Component Designer generated code
- /// <summary>
- /// Required designer variable.
- /// </summary>
- private System.ComponentModel.IContainer components = null;
- /// <summary>
- /// Clean up any resources being used.
- /// </summary>
- /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
- protected override void Dispose(bool disposing)
- {
- if (disposing && (components != null))
- {
- components.Dispose();
- }
- base.Dispose(disposing);
- }
- /// <summary>
- /// Required method for Designer support - do not modify
- /// the contents of this method with the code editor.
- /// </summary>
- private void InitializeComponent()
- {
- components = new System.ComponentModel.Container();
- this.ServiceName = "WindowsService";
- }
- #endregion
- }
- }
- // WindowsServiceInstaller.cs
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Configuration.Install;
- using System.Linq;
- using System.ServiceProcess;
- namespace Foobar.Service
- {
- [RunInstaller(true)]
- public abstract class WindowsServiceInstaller : System.Configuration.Install.Installer
- {
- private ServiceProcessInstaller _ServiceProcessInstaller;
- private ServiceInstaller _ServiceInstaller;
- public override void Uninstall(System.Collections.IDictionary savedState)
- {
- var svcName = GetContextParameter("serviceName");
- if (!string.IsNullOrEmpty(svcName))
- {
- _ServiceInstaller.ServiceName = svcName;
- }
- base.Uninstall(savedState);
- }
- public override void Install(System.Collections.IDictionary stateSaver)
- {
- var svcName = GetContextParameter("serviceName");
- if (!string.IsNullOrEmpty(svcName))
- {
- _ServiceInstaller.ServiceName = svcName;
- }
- base.Install(stateSaver);
- }
- private string GetContextParameter(string key)
- {
- string sValue;
- try
- {
- sValue = this.Context.Parameters[key].ToString();
- }
- catch
- {
- sValue = string.Empty;
- }
- return sValue;
- }
- public WindowsServiceInstaller(string serviceName)
- {
- InitializeComponent();
- _ServiceProcessInstaller = new ServiceProcessInstaller();
- _ServiceProcessInstaller.Account = ServiceAccount.LocalSystem;
- _ServiceProcessInstaller.Password = null;
- _ServiceProcessInstaller.Username = null;
- _ServiceInstaller = new ServiceInstaller();
- _ServiceInstaller.ServiceName = serviceName;
- _ServiceInstaller.StartType = ServiceStartMode.Automatic;
- Installers.AddRange(new Installer[]
- {
- _ServiceProcessInstaller,
- _ServiceInstaller
- });
- }
- #region Component Designer generated code
- /// <summary>
- /// Required designer variable.
- /// </summary>
- private System.ComponentModel.IContainer components = null;
- /// <summary>
- /// Clean up any resources being used.
- /// </summary>
- /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
- protected override void Dispose(bool disposing)
- {
- if (disposing && (components != null))
- {
- components.Dispose();
- }
- base.Dispose(disposing);
- }
- /// <summary>
- /// Required method for Designer support - do not modify
- /// the contents of this method with the code editor.
- /// </summary>
- private void InitializeComponent()
- {
- components = new System.ComponentModel.Container();
- }
- #endregion
- }
- }
- // Пример класса инсталлера который нужно добавить в главную сборку приложения, обязательно public:
- public class RouterWindowsServiceInstaller : Foobar.Service.WindowsServiceInstaller
- {
- public RouterWindowsServiceInstaller()
- : base("Router")
- {
- }
- }
- // Ну и пример использования запуска службы :)
- class Program
- {
- static void Start()
- {
- // ...
- }
- static void Stop()
- {
- // ...
- }
- static void Main(string[] args)
- {
- XmlConfigurator.Configure();
- if (Environment.UserInteractive)
- {
- try
- {
- Start();
- Console.WriteLine("Service is working, press enter to leave.");
- Console.ReadLine();
- Stop();
- }
- catch (Exception ex)
- {
- _Log.Fatal("Fatal exception in main thread.", ex);
- }
- }
- else
- {
- _Log.Info("Starting service.");
- ServiceBase.Run(new ServiceBase[] {
- new Foobar.WindowsService(a => Start(), () => Stop(), "Router") });
- }
- }
- private static readonly log4net.ILog _Log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement