windows service 开发参考
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using Tba.Logging;
using tba.eisuite.utils.logging;
using tba.zap.process.zaps;
using ILogger = Tba.Interfaces.Logging.ILogger;
//using tba
namespace ZAPS
{
partial class ZAPS : ServiceBase
{
public ZAPS()
{
InitializeComponent();
_logger = LoggingFactory.GetLogger("nlogLog");
}
private string _odsConnectionString = ConfigurationManager.ConnectionStrings["ODS"].ConnectionString;
#region Logger File Setting
// Log file name key in app.config
private const String LoggerFileConfig = "LogDirectory";
private const String LoggerFileSuffix = "ZAPS";
//log for create declaration period
private const String LoggerFileForDeclarationPeriodSuffix = "ZAPSDeclaretiePeriode";
// Date format string key in app.config
private const String LoggerFileNameDateFormatConfig = "LoggerFileNameDateFormat";
private const String LogLevelConfigName = "LogLevel";
// Logger file name and date format
private String _loggerFilePathConfig;
private String _loggerFileNameDateFormatConfig;
private ILogger _logger;
private void LogException(LogLevel level, String msg, Exception ex, params Object[] args)
{
try
{
using (Logger logger = Logger.GetLogger(CurrentLoggerFileName, CurrentLogLevel))
{
logger.LogException(level, msg, ex, args);
}
using (Logger logger = Logger.GetLogger(DeclarationPeriodLoggerFileName, CurrentLogLevel))
{
logger.LogException(level, msg, ex, args);
}
}
catch
{
}
}
private String DateSuffix
{
get
{
return DateTime.Now.ToString(_loggerFileNameDateFormatConfig, CultureInfo.InvariantCulture) + @".log";
}
}
private String CurrentLoggerFileName
{
get
{
return _loggerFilePathConfig + LoggerFileSuffix + DateSuffix;
}
}
private String DeclarationPeriodLoggerFileName
{
get
{
return _loggerFilePathConfig + LoggerFileForDeclarationPeriodSuffix + DateSuffix;
}
}
private void GetLogFileNameConfig()
{
_loggerFileNameDateFormatConfig = ConfigurationManager.AppSettings[LoggerFileNameDateFormatConfig];
_loggerFilePathConfig = ConfigurationManager.AppSettings[LoggerFileConfig];
}
private static LogLevel CurrentLogLevel
{
get
{
return ConfigHelper.ReadEnumConfigWithDefault(
ConfigurationManager.AppSettings[LogLevelConfigName],
LogLevel.Debug, // Info by default
null // no log
);
}
}
#endregion
#region Set up event viewer log
internal const String EventLogSourceName = "EISuite.REGAS.Windows.Service";
internal const String EventLogEntryName = "ZAPS.eisuite.tba.Log";
private void SetupEventLogEntry()
{
eventLogZAPS.Source = EventLogSourceName;
eventLogZAPS.Log = EventLogEntryName;
_isEventLogAvailable = true;
}
private Boolean _isEventLogAvailable;
private void WriteEventLogEntry(String message)
{
if (_isEventLogAvailable)
{
try
{
eventLogZAPS.WriteEntry(message);
}
catch (Exception ex)
{
// Failed to write to event log
_isEventLogAvailable = false;
ExceptionSentEmail(ex.Message, ex.StackTrace, ex.Source);
}
}
}
private void ExceptionSentEmail(string exceptionMsg, string exceptionStackTrace, string exceptionSource)
{
if (bool.Parse(ConfigurationManager.AppSettings["mailExceptions"]))
{
var sb = new StringBuilder();
sb.AppendLine("Exception Message: " + exceptionMsg);
sb.AppendLine("\r\n Exception stacktrace: " + exceptionStackTrace);
sb.AppendLine("\r\n Exception source: " + exceptionSource);
var mail = new MailMessage();
mail.From = new MailAddress(ConfigurationManager.AppSettings["mailfrom"]);
mail.To.Add(new MailAddress(ConfigurationManager.AppSettings["mailto"]));
//mail.To.Add(new MailAddress(ConfigurationManager.AppSettings["MailExceptionsREGAS"]));
mail.Subject = "ZAPLive! ZAPS fout [" + Environment.MachineName + "]";
mail.Body = sb.ToString();
var smtpClient = new SmtpClient(ConfigurationManager.AppSettings["SmtpServer"]
, Int32.Parse(ConfigurationManager.AppSettings["SmtpServerPort"]));
if (ConfigurationManager.AppSettings["UserName"] != null && ConfigurationManager.AppSettings["Password"] != null)
{
smtpClient.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["UserName"],
ConfigurationManager.AppSettings["Password"]);
}
else
{
smtpClient.UseDefaultCredentials = false;
}
smtpClient.Send(mail);
}
}
#endregion
#region Load Timer interval key in app.config
private const String ServiceTimerIntervalConfig = "ServiceTimerIntervalConfigName";
private Int32 _serviceTimerInterval = -1;
private const Int32 DefaultServiceTimerInterval = 60;
private Int32 ServiceTimerInterval
{
get
{
if (_serviceTimerInterval < 0)
{
if (!Int32.TryParse(ConfigurationManager.AppSettings[ServiceTimerIntervalConfig], out _serviceTimerInterval))
{
_serviceTimerInterval = DefaultServiceTimerInterval; // 60 seconds by default
WriteEventLogEntry(
String.Format(CultureInfo.InvariantCulture, "Invalid setting '{0}' for service interval, use default value {1}!",
ConfigurationManager.AppSettings[ServiceTimerIntervalConfig], DefaultServiceTimerInterval)
);
}
else
{
#if(!DEBUG)
_serviceTimerInterval *= 1000;
#else
_serviceTimerInterval *= 100;
#endif
}
}
return _serviceTimerInterval;
}
}
private const String ServiceTimerForCreatingDeclarationPeriodIntervalConfig = "ServiceTimerCreateDeclarantionPeriodIntervalConfigName";
private Int32 _serviceTimerForCreatingDeclarationPeriodInterval = -1;
private const Int32 DefaultServiceTimerForCreatingDeclarationPeriodInterval = 60;
private Int32 ServiceTimerForCreatingDeclarationPeriodInterval
{
get
{
if (_serviceTimerForCreatingDeclarationPeriodInterval < 0)
{
if (!Int32.TryParse(ConfigurationManager.AppSettings[ServiceTimerForCreatingDeclarationPeriodIntervalConfig], out _serviceTimerForCreatingDeclarationPeriodInterval))
{
_serviceTimerInterval = DefaultServiceTimerForCreatingDeclarationPeriodInterval; // 3600 seconds by default
WriteEventLogEntry(
String.Format(CultureInfo.InvariantCulture, "Invalid setting '{0}' for service interval, use default value {1}!",
ConfigurationManager.AppSettings[ServiceTimerIntervalConfig], DefaultServiceTimerInterval)
);
}
else
{
#if(!DEBUG)
_serviceTimerForCreatingDeclarationPeriodInterval *= 1000;
#else
_serviceTimerForCreatingDeclarationPeriodInterval *= 100;
#endif
}
}
return _serviceTimerForCreatingDeclarationPeriodInterval;
}
}
private Timer _serviceTimer;
private Timer _serviceTimeForCreatingDeclarationPeriod;
private DateTime _lastProcessedDate;
private void SetupTimer()
{
_serviceTimer = new Timer(ServiceTimerInterval);
_serviceTimer.Elapsed += new ElapsedEventHandler(ServiceTimerElapsed);
_serviceTimer.Start();
_serviceTimeForCreatingDeclarationPeriod = new Timer(ServiceTimerForCreatingDeclarationPeriodInterval);
_serviceTimeForCreatingDeclarationPeriod.Elapsed += new ElapsedEventHandler(ServiceTimerForCreatingDeclarationPeriodElapsed);
_serviceTimeForCreatingDeclarationPeriod.Start();
}
#endregion
private void ServiceTimerElapsed(object sender, ElapsedEventArgs e)
{
try
{
_serviceTimer.Stop();
using (var logger = Logger.GetLogger(CurrentLoggerFileName, CurrentLogLevel))
{
//var zorgaanbiederHandler =
// new tba.zap.business.ZorgaanbiederHandler(
// ConfigurationManager.ConnectionStrings["Repository"].ToString());
var args = new ZapsArgs();
args.RepositoryConnectionString = ConfigurationManager.ConnectionStrings["Repository"].ToString();
args.AW319Version = ConfigurationManager.AppSettings["AW319Version"];
args.AW319SubVersion = ConfigurationManager.AppSettings["Aw319SubVersion"];
args.AW319Flag = ConfigurationManager.AppSettings["Aw319Flag"];
args.ManufacturerInformation = ConfigurationManager.AppSettings["ManufacturerInformation"];
args.TorP = ConfigurationManager.AppSettings["TorP"];
using (var service = new ZAPSProcessor(args, logger, _odsConnectionString, _logger))
{
service.Svc();
}
}
}
catch (Exception ex)
{
try
{
LogException(LogLevel.Error, "ZAPS Error!", ex);
}
catch (Exception exLogger)
{
WriteEventLogEntry(
String.Format(CultureInfo.InvariantCulture,
@"Error writing log {0}. Please check the log file path setting in application configuration file.\n
Exception Details: {1}\r\n",
exLogger.Message, ex.StackTrace)
);
ExceptionSentEmail(ex.Message, ex.StackTrace, ex.Source);
}
ExceptionSentEmail(ex.Message, ex.StackTrace, ex.Source);
}
finally
{
_serviceTimer.Start();
}
}
private void ServiceTimerForCreatingDeclarationPeriodElapsed(object sender, ElapsedEventArgs e)
{
try
{
_serviceTimeForCreatingDeclarationPeriod.Stop();
if (DateTime.Now.Hour == 0 && _lastProcessedDate.AddDays(1).Date == DateTime.Now.Date)
{
_lastProcessedDate = DateTime.Now;
using (var logger = Logger.GetLogger(DeclarationPeriodLoggerFileName, CurrentLogLevel))
{
var args = new ZapsArgs();
args.RepositoryConnectionString =
ConfigurationManager.ConnectionStrings["Repository"].ToString();
using (var service = new ZAPSProcessor(args, logger, _odsConnectionString, _logger))
{
service.CreateDeclarantionPeriod();
}
}
}
}
catch (Exception ex)
{
try
{
LogException(LogLevel.Error, "ZAPS Error!", ex);
}
catch (Exception exLogger)
{
WriteEventLogEntry(
String.Format(CultureInfo.InvariantCulture,
@"Error writing log {0}. Please check the log file path setting in application configuration file.\n
Exception Details: {1}\r\n",exLogger.Message, ex.StackTrace));
ExceptionSentEmail(ex.Message, ex.StackTrace, ex.Source);
}
ExceptionSentEmail(ex.Message, ex.StackTrace, ex.Source);
}
finally
{
_serviceTimeForCreatingDeclarationPeriod.Start();
}
}
private void GetMailSettings()
{
if (EnableSMTPMailSending)
{
// ExceptionMailSettings.Initialize();
}
}
private Boolean EnableSMTPMailSending
{
get
{
Boolean b;
if (!Boolean.TryParse(ConfigurationManager.AppSettings["mailExceptions"], out b))
{
b = true; // default to true
}
return b;
}
}
protected override void OnStart(string[] args)
{
// Set up event log for debugging FIRST!
SetupEventLogEntry();
try
{
_lastProcessedDate = DateTime.Now;
GetLogFileNameConfig();
using (Logger logger = Logger.GetLogger(CurrentLoggerFileName, CurrentLogLevel))
{
logger.LogMessage(LogLevel.Info, "ZAPS service started!");
}
using (Logger logger = Logger.GetLogger(DeclarationPeriodLoggerFileName, CurrentLogLevel))
{
logger.LogMessage(LogLevel.Info, "ZAPS service started!");
}
GetMailSettings();
SetupTimer();
WriteEventLogEntry("ZAPS service started!");
}
catch (Exception ex)
{
LogException(LogLevel.Error, "ZAPS Error!", ex);
WriteEventLogEntry(
String.Format(CultureInfo.InvariantCulture, "Error during startup: {0} \r\n Stack trace: {1}\r\n",
ex.Message, ex.StackTrace)
);
ExceptionSentEmail(ex.Message, ex.StackTrace, ex.Source);
}
}
protected override void OnStop()
{
try
{
_serviceTimer.Stop();
_serviceTimer.Dispose();
_serviceTimeForCreatingDeclarationPeriod.Stop();
_serviceTimeForCreatingDeclarationPeriod.Dispose();
using (Logger logger = Logger.GetLogger(CurrentLoggerFileName, CurrentLogLevel))
{
logger.LogMessage(LogLevel.Info, "ZAPS service stopped!");
}
using (Logger logger = Logger.GetLogger(DeclarationPeriodLoggerFileName, CurrentLogLevel))
{
logger.LogMessage(LogLevel.Info, "ZAPS service stopped!");
}
WriteEventLogEntry("ZAPS service stopped!");
}
catch (Exception ex)
{
LogException(LogLevel.Error, "ZAPS Error!", ex);
WriteEventLogEntry(
String.Format(CultureInfo.InvariantCulture, "Error during shutdown: {0} \r\n Stack trace: {1}\r\n",
ex.Message, ex.StackTrace)
);
}
}
public void Start()
{
OnStart(null);
}
}
}
调试段代码:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
#if (!DEBUG)
//ServiceBase[] ServicesToRun;
//ServicesToRun = new ServiceBase[]
//{
// new EIREGAS()
//};
//ServiceBase.Run(ServicesToRun);
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new ZAPS()
};
ServiceBase.Run(ServicesToRun);
#else
//EIREGAS service = new EIREGAS();
//service.Start();
//System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
var service = new ZAPS();
service.Start();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#endif
}
}