Introducción Desarrollo de Windows Services Instalación
Servicio del sistema operativo Windows provee una consola que permite habilitar/deshabilitar, iniciar/detener/pausar También se pueden fijar la opciones de inicio del servicio Manual Automática Sin interacción con usuario
Monitoreo de dispositivos de hardware Escuchar peticiones a través de la red (Puerto tcp/udp a través de sockets) Antivirus Actualizaciones automáticas Análisis de algún componente de manera desatendida Procesamiento de datos en background
.Net provee la clase System.ServiceProcess.ServiceBase del cual heredan todos los servicios Provee instaladores que configuran el sistema operativo para ejecutar el servicio Visual Studio.Net provee una plantilla de proyecto para crear un servicio
Al heredar de la clase ServiceBase tenemos que sobreescribir los métodos OnStart Código que se ejecuta cuando se inicia el servicio OnStop Código que se ejecuta cuando se detiene el servicio También se pueden sobreescribir los métodos: OnShutDown, OnPause y OnContinue
namespace ServicioEjemplo { public partial class Service1 : ServiceBase { public Service1() { InitializeComponent(); } protected override void OnStart(string[] args) { // TODO: Add code here to start your service. } protected override void OnStop() { // TODO: Add code here to perform any tear-down necessary to stop your service. }
Agregar al proyecto una clase de tipo Installer Class
[RunInstaller(true)] public partial class InstalacionServicio : Installer { private ServiceInstaller serviceInstaller; private ServiceProcessInstaller processInstaller; public InstalacionServicio() { InitializeComponent(); processInstaller = new ServiceProcessInstaller(); serviceInstaller = new ServiceInstaller(); //processInstaller.Account = // System.ServiceProcess.ServiceAccount.User; processInstaller.Account = ServiceAccount.LocalSystem; serviceInstaller.StartType = ServiceStartMode.Automatic; serviceInstaller.ServiceName = "MiServicio"; Installers.Add(serviceInstaller); Installers.Add(processInstaller); }
Ejecutar la herramienta de instalación de servicios de.Net C:\WINDOWS\Microsoft.NET\Framework\v \Instal lUtil.exe Sintaxis Installutil /i MiService.exe (instalar) Installutil /u MiService.exe (desinstalar)
En OnStart() El servicio debe correr de manera indefinida Para esto lo mejorar es ejecutar el proceso con un bucle en otro thread. El método Run tendrá por ejemplo un bucle while(! bStop){ … }
private void Run() { server = new TcpListener(IPAddress.Loopback, 4444); server.Start(); System.Random r = new System.Random(); while (server != null) { if (serverPaused) { Thread.Sleep(10); continue; } Socket s = server.AcceptSocket(); EventLog.WriteEntry("Accepted " + ((IPEndPoint)s.RemoteEndPoint)); string ran = "" + r.NextDouble(); byte[] b = System.Text.Encoding.ASCII.GetBytes(ran); s.Send(b, b.Length, 0); EventLog.WriteEntry("Served " + ((IPEndPoint)s.RemoteEndPoint)); s.Close(); }