create windows service project
add project installer
configure project installer
add setup project
add custom events to setup project (including project output to every event)
add code to enable debugging
static class Program
{
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger("YourProject");
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
m_log.Info("started");
if (Environment.UserInteractive)
{
// This used to run the service as a console (development phase only)
YourProject ServiceToRun = new YourProject();
ServiceToRun.callStart();
Console.WriteLine("Press Enter to terminate ...");
Console.ReadLine();
}
else
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]{new YourProject};
ServiceBase.Run(ServicesToRun);
}
}
public partial class YourApplication : ServiceBase
{
public static readonly log4net.ILog m_log = log4net.LogManager.GetLogger("YourApplication");
public YourApplication()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
m_log.Info("started");
}
protected override void OnStop()
{
m_log.Info("stoped");
}
private void fileSystemWatcher1_Created(object sender, System.IO.FileSystemEventArgs e)
{
m_log.Info("created");
}
//below is for debugging purpose
public void callStart()
{
m_log.Info("call start");
OnStart(new string[] { "" });
}
}
below is code to auto start the service after install
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using System.ServiceProcess;
using log4net;
using log4net.Config;
using log4net.Layout;
namespace YourApplication
{
[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer
{
private const string SERVICE_NAME = "YourApplication";
private ServiceController m_Service;
public ProjectInstaller()
{
InitializeComponent();
HandleService();
}
private void HandleService()
{
object[] parameters;
string sMeth = "HandleService";
string sCallingMethodName;
try
{
m_Service = new ServiceController(SERVICE_NAME);
if (m_Service != null)
{
m_Service.Start();
}
else
{
}
}
catch (Exception ex)
{
//
}
finally
{
//
}
}
}
}
No comments:
Post a Comment