using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.IO; using System.Linq; using System.ServiceProcess; using System.Text; using System.Timers; using System.Threading.Tasks; using log4net; using bsmd.database; using bsmd.dakosy; namespace bsmd.dakosy.ResponseService { /// /// Windows service zum Abruf von NSW Response Dateien via SFTP und Import der Dateien in die DB /// public partial class SFTPService : ServiceBase { private Timer _timer; private object _timerlock = new object(); private bool processRunning = false; private ILog _log = LogManager.GetLogger(typeof(SFTPService)); public SFTPService() { Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory); InitializeComponent(); } protected override void OnStart(string[] args) { this.EventLog.Source = this.ServiceName; this.EventLog.Log = "Application"; this.EventLog.BeginInit(); if (!EventLog.SourceExists(this.EventLog.Source, this.EventLog.Log)) EventLog.CreateEventSource(this.EventLog.Source, this.EventLog.Log); this.EventLog.EndInit(); this.Init(args); this.EventLog.WriteEntry("NSW SFTP Response Service started.", EventLogEntryType.Information); } protected override void OnStop() { _log.Info("SFTPService stopped"); } public void Init(string[] args) { this._timer = new Timer(); this._timer.Interval = 600000; // 10 Min, TODO: Settings this._timer.Elapsed += _timer_Elapsed; this._timer.Enabled = true; if (Debugger.IsAttached) this._timer_Elapsed(null, null); } void _timer_Elapsed(object sender, ElapsedEventArgs e) { lock (this._timerlock) { if (this.processRunning) return; else this.processRunning = true; } string localDir = ""; // TBD if (DBManager.Instance.Connect(Properties.Settings.Default.ConnectionString)) { try { // SFTP verbindung öffnen und alle Dateien herunterladen sftp.GetAll(localDir); // lokale Dateien verarbeiten foreach(string inputFile in Directory.GetFiles(localDir)) { if (!Response.Read(inputFile)) _log.ErrorFormat("Error reading input file {0}", inputFile); else File.Delete(inputFile); // alternativ: move to archive folder } } catch (Exception ex) { _log.ErrorFormat("Exception occurred: {0}", ex.ToString()); } } else { this.EventLog.WriteEntry("FormService stopped: DB connection failed", EventLogEntryType.Error); this.Stop(); } lock (this._timerlock) { this.processRunning = false; } } } }