using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Linq; using System.IO; using System.ServiceProcess; using System.Text; using System.Threading.Tasks; using System.Timers; using log4net; using bsmd.database; using bsmd.email; namespace bsmd.ExcelReadService { public partial class ExcelReadService : ServiceBase { private Timer _timer; private object _timerlock = new object(); private bool processRunning = false; private ILog _log = LogManager.GetLogger(typeof(ExcelReadService)); public ExcelReadService() { Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory); InitializeComponent(); } protected override void OnStart(string[] args) { this.EventLog.Source = this.ServiceName; this.EventLog.Log = "Application"; this.Init(args); this.EventLog.WriteEntry("EU-NOAD Excel Read Service started.", EventLogEntryType.Information); this.DoOnce(); } private void Init(string[] args) { this._timer = new Timer(); this._timer.Interval = Properties.Settings.Default.SleepSeconds * 1000; this._timer.Elapsed += _timer_Elapsed; this._timer.Enabled = true; } private void _timer_Elapsed(object sender, ElapsedEventArgs e) { lock (this._timerlock) { if (this.processRunning) return; else this.processRunning = true; } if (DBManager.Instance.Connect(Properties.Settings.Default.ConnectionString)) { try { string messageId = ""; string attachmentLocalPath = ""; string mailSender = ""; using (BSMDPopClient bsmdPopClient = new BSMDPopClient()) { if (!bsmdPopClient.IsConnected) { _log.Error("cannot connect to pop3 server, aborting!"); this.Stop(); } // check and download next e-Mail, saving attachment while (bsmdPopClient.ReceiveSingleMail(out attachmentLocalPath, out messageId, out mailSender)) { bool readResult; string readMessage = ""; MessageCore messageCore = null; // try to read/import attachment using(ExcelReader reader = new ExcelReader(attachmentLocalPath)) { readResult = Util.ProcessSheet(reader, out readMessage, out messageCore); if(!readResult) _log.Error("Excel sheet could not be interpreted"); } // set messagecore to createreport and let reportGenerator create a reply // remove e-Mail _log.InfoFormat("deleting mail with messageId {0}", messageId); _log.InfoFormat("mail delete {0}", bsmdPopClient.DeleteMessageByMessageId(messageId) ? "successful" : "failed"); // remove attachment _log.InfoFormat("removing local file {0}", attachmentLocalPath); // File.Delete(attachmentLocalPath); } } DBManager.Instance.Disconnect(); } catch (Exception ex) { _log.ErrorFormat("Exception occurred: {0}", ex.ToString()); } } else { this.EventLog.WriteEntry("ReportService stopped: DB connection failed", EventLogEntryType.Error); this.Stop(); } lock (this._timerlock) { this.processRunning = false; } } protected override void OnStop() { } internal void DoOnce() { this._timer_Elapsed(null, null); } } }