public string ExecuteCmd(string cmdStr, bool noEMail = false) { _rawCmd = cmdStr; var words = CmdMgr.GetWords(cmdStr); if (!ParseCmd(words)) { return("Try later."); } var result = _srcDelegateDict.TryGetValue(_cmdSrc, out HandleSrcDel cmdDel) ? cmdDel(words) : "Huh?"; if (!noEMail && (IsEMail(words) || (result.Length > 1800))) { CSEMail csEMail = new CSEMail(_config, _userManager); return(SrcTitle(_cmdSrc) + (csEMail.Send(_curUser.EMail, _curUser.EMail, "RE: " + _rawCmd, result) ? " successfully sent to " : " FAILED to be sent to ") + _curUser.EMail); } return((result.Length > 0) ? result : "No Results."); }
//*************************************************************** private string HandleCSTest(List <string> words) //*************************************************************** { var cse = new CSEMail(_config, _userManager); String report = ""; var eList = cse.ReadEMails(); foreach (var e in eList) { report += e.Subject + ".\n"; if ((e.HtmlBody != null) && (e.HtmlBody.Length > 5)) { e.AddHtmlAsPDFAttachment(); } if (e.Attachments.Count > 0) { var dbox = new CSDropBox(Startup.CSConfig); var destPath = "/Memorandums"; foreach (var a in e.Attachments) { string FileName = e.GetFinalFileName(Path.GetFileName(a)); if (dbox.FileExists(destPath + "/" + FileName)) { var fBody = Path.GetFileNameWithoutExtension(FileName); var fExt = Path.GetExtension(FileName); for (char j = 'B'; j < 'Z'; ++j) { FileName = fBody + "_Rev_" + j.ToString() + fExt; if (!dbox.FileExists(destPath + "/" + FileName)) { break; } } } dbox.UploadFile(a, destPath, FileName); File.Delete(a); } } } return(report); }
public async Task DoWork(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { DateTime enow = PropMgr.ESTNow; DateTime expected = new DateTime(enow.Year, enow.Month, enow.Day, 3, 0, 0); DateTime lastW = (_csSettings.LastTaskUpdate != null) ? _csSettings.LastTaskUpdate : new DateTime(2020, 1, 1); #if DEBUG double MinWait = 0; // for testing #else double MinWait = 720; // 12 hrs #endif if (((enow - lastW).TotalMinutes >= MinWait) || (Math.Abs((enow - expected).TotalMinutes) < 65)) // done not more than twice a day and covers DST change with delay/offset { // Check Stock for possibly needed items OrderedEvents ordEvs = new OrderedEvents(_context); IList <InventoryItem> InventoryItems = _context.InventoryItem.Include(i => i.Inventory).Include(i => i.Item).ToList(); foreach (var invIt in InventoryItems) { if (IndexInvModel.MayNeedItem(_context, invIt, ordEvs)) { // Item likely needs to be ordered. Mark as needed. if (invIt.State == IndexInvModel.STOCKED_STATE) { invIt.State = IndexInvModel.NEEDED_STATE; _context.Attach(invIt).State = EntityState.Modified; try { _context.SaveChanges(); _csSettings.LastStockUpdate = PropMgr.ESTNow; _csSettings.Save(); await Task.Run(() => IndexInvModel.NotifyNeedAsync(_hostEnv, _configuration, _userManager, "CStat:Stock> Needed : " + invIt.Item.Name, true)); // potentially clean Message log } catch (DbUpdateConcurrencyException) { continue; } } } } // Check for new Tasks AutoGen ag = new AutoGen(_context); _csSettings.LastTaskUpdate = PropMgr.ESTNow; _csSettings.Save(); ag.GenTasks(_hostEnv); // Notify users Tasks Due CTask.NotifyUserTaskDue(_hostEnv, _configuration, _userManager, _context, 24, true); // Potentially clean log // Persist Daily Reading and Notify if needed for Propane PropaneMgr pmgr = new PropaneMgr(_hostEnv, _configuration, _userManager); pmgr.CheckValue(pmgr.GetTUTank(true)); // get value, log to file and check // Check for any unexpected propane usage (not potentially impacted from events) from recent daily usage var plList = pmgr.GetAll(3); var plCnt = plList.Count; if (plCnt > 1) { for (int i = 0; i < plCnt - 1; ++i) { var plStart = plList[i]; var plEnd = plList[i + 1]; var dateRange = new DateRange(plStart.ReadingTime, plEnd.ReadingTime); var evList = ag.GetImpactingEvents(dateRange); if (evList.Count == 0) // no impacting events { var totalHrs = dateRange.TotalHours(); if ((totalHrs > 0) && _csSettings.GetPropaneProperties(out double tankGals, out double pricePerGal)) { var totalGals = ((plStart.LevelPct - plEnd.LevelPct) / 100) * tankGals; if ((totalGals / totalHrs) > ((double)2 / 24)) // averaging more than 2 gals/day? { // Send a one time alert (allowResend = false) CSSMS sms = new CSSMS(_hostEnv, _configuration, _userManager); sms.NotifyUsers(CSSMS.NotifyType.EquipNT, "CStat:Equip> " + "Non Event Propane Usage was " + totalGals.ToString("0.##") + " gals. during " + totalHrs.ToString("0.#") + " hours starting " + plStart.ReadingTime.Month + "/" + plStart.ReadingTime.Day + "/" + plStart.ReadingTime.Year % 100, false, true); // potentially clean Message Log } } } } } // Check for new EMails to store CSEMail.SaveEMails(_configuration, _userManager); // Check/Truncate Size of Arduino file ArdMgr amgr = new ArdMgr(_hostEnv, _configuration, _userManager); amgr.GetAll(true); // Clean/{Reset to full view} Camera using (var ptz = new PtzCamera()) { ptz.Cleanup(_hostEnv); } _logger.LogInformation($"CStat Daily Updates Completed at {PropMgr.ESTNow}"); } // Run again at 3:00 AM DateTime now = PropMgr.ESTNow; DateTime tom = now.AddDays(1); DateTime start = new DateTime(tom.Year, tom.Month, tom.Day, 3, 0, 0); // Restart at 3:00 AM tomorrow int MSecsToStart = (int)Math.Round((start - now).TotalMilliseconds); await System.Threading.Tasks.Task.Delay(MSecsToStart, stoppingToken); } }
public List <REMail> ReadEMails() { bool NeedSave = false; try { using (readClient = new Pop3Client()) { var Server = "mail.ccaserve.org"; var Port = "110"; var UseSsl = false; var credentials = new NetworkCredential(fromAdr, fromPass); var cancel = new CancellationTokenSource(); var uri = new Uri(string.Format("pop{0}://{1}:{2}", (UseSsl ? "s" : ""), Server, Port)); //Connect to email server readClient.Connect(uri, cancel.Token); readClient.AuthenticationMechanisms.Remove("XOAUTH2"); readClient.Authenticate(credentials, cancel.Token); // Read EMails roughly after those we read last var reList = new List <REMail>(); var LatestEMailRead = _settings.LastEMailRead; for (int i = 0; i < readClient.Count; i++) { var msg = readClient.GetMessage(i); // Get Received Date and use it to keep track of emails we have already read and processed. DateTime EMailReceived = default; if (msg.Headers != null) { if (msg.Headers["Received"] != null) { var rval = msg.Headers["Received"]; var rFields = rval.Split(";"); foreach (var f in rFields) { var fld = f.Trim(); if (fld.Length < 45) { EMailReceived = CSEMail.ParseDetailedDate(fld); if (EMailReceived != default) { break; } } } } } // Get DateTime Originally Sent if ((EMailReceived == default) || (EMailReceived <= LatestEMailRead)) { continue; // Either an Admin Delivery failure alert or already read. TBD : Case where multiple emails read the same second but on or more not proccessed. } var re = new REMail(i); re.Subject = msg.Subject; re.HtmlBody = msg.HtmlBody; re.TextBody = msg.TextBody; var tbFlds = msg.TextBody.Split("\r\n"); foreach (var t in tbFlds) { var tfld = t.Trim(); if (tfld.StartsWith("Sent:") || tfld.StartsWith("Date:")) { re.Date = CSEMail.ParseDetailedDate(tfld); } } re.From = (msg.Sender != null) ? msg.Sender.ToString() : (((msg.From != null) && (msg.From.Count > 0)) ? msg.From[0].ToString() : "unknown"); if (re.Date == default) { re.Date = PropMgr.UTCtoEST(msg.Date.DateTime); } re.Attachments = new List <string>(); foreach (var attachment in msg.Attachments) { var fileName = attachment.ContentDisposition?.FileName ?? attachment.ContentType.Name ?? "Att"; fileName = re.GetUniqueTempFileName(fileName, true); using (var stream = File.Create(fileName)) { if (attachment is MessagePart) { var part = (MessagePart)attachment; part.Message.WriteTo(stream); } else { var part = (MimePart)attachment; part.Content.DecodeTo(stream); } } re.Attachments.Add(fileName); } // Sometimes images are in BodyParts. filter out other content foreach (var attachment in msg.BodyParts) { var fileName = attachment.ContentDisposition?.FileName ?? attachment.ContentType.Name ?? ""; if (string.IsNullOrEmpty(fileName)) { continue; // filter out other non-file content } fileName = re.GetUniqueTempFileName(fileName, true); using (var stream = File.Create(fileName)) { if (attachment is MessagePart) { var part = (MessagePart)attachment; part.Message.WriteTo(stream); } else { var part = (MimePart)attachment; part.Content.DecodeTo(stream); } } re.Attachments.Add(fileName); } if (EMailReceived > _settings.LastEMailRead) { NeedSave = true; _settings.LastEMailRead = EMailReceived; } reList.Add(re); } readClient.Disconnect(true); if (NeedSave) { _settings.Save(); } return(reList); } } catch (Exception e) { _ = e; return(new List <REMail>()); // TBD Log failure } }