using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Configuration; using System.Data; using System.Diagnostics; using System.Drawing; using System.Drawing.Printing; using System.IO; using System.Media; using System.Net; using System.Net.Mail; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; using System.Timers; using System.Windows.Forms; namespace LabelMonitor { public partial class LabelMonitor : Form { #region Booleans //Bool to decide if files should be deleted/cleaned out from data directory after processing run. bool cleanAfterBuilding = true; bool found = false; bool driveScanFail = false; //boolean to show whether or not network drives were available during scan bool slamOnTheBrakes = false; bool labelRunBefore = false; public static bool isOdd(int value) { return value % 2 != 0; } #endregion //Create a string array to hold delimiters to use when scanning files char[] delims = new char[] { ';' }; #region DateTimes //Var to hold on to regular time. Used in regular auto mode processing. DateTime autoTime; DateTime runStartTime; DateTime runEndTime; DateTime last_driveScanFailTimeStamp = DateTime.MinValue; DateTime driveScanFailTimeStamp = new DateTime(); #endregion DirectoryInfo dip = new DirectoryInfo(@"" + ConfigurationManager.AppSettings["prepDataPath"]); DirectoryInfo dicps = new DirectoryInfo(@"" + ConfigurationManager.AppSettings["prepDataPathCPS"]); DirectoryInfo didr = new DirectoryInfo(@"" + ConfigurationManager.AppSettings["dumpReportPath"]); DirectoryInfo dibf = new DirectoryInfo(@"" + ConfigurationManager.AppSettings["boomerangFilesPath"]); #region List List processList = new List(); List lineData = new List(); List cartonLineData = new List(); List inFileList = new List(); List outFileList = new List(); List firstLastList = new List(); List boomerangList = new List(); List dumpReportList = new List(); List reportListFile = new List(); List reportListFileUpdate = new List(); List newReportList = new List(); List tempOut = new List(); List boomerangFormatFile = new List(); #endregion #region Integers and Doubles int look = 0; //int slvPerCarton = Int32.Parse(ConfigurationManager.AppSettings["slvPerCarton"]); int slvPerCarton = 0; int totalRecs = 0; int recordCount = 0; int lineCount = 0; int acctField = 0; int bundleAmt = 0; int nameField = 0; int pinField = 0; //added for new QC label (2017-07-13, jae) int firstCardSeqNum = 0; int lastCardSeqNum = 0; int specQCCount = 0; int specQCSlvCount = 1; double autoDelayTime = Double.Parse(ConfigurationManager.AppSettings["autoTimeDelay"]); //Month values as integers, for maintenance operations. // * -1 inverts the parsed value to a negative number, as required for DateTime.Now.AddMonths() // (i.e. DateTime.Now.AddMonths(-1) for 1 month back) int shortDate = Int16.Parse(ConfigurationManager.AppSettings["shortDate"]) * -1; int longDate = Int16.Parse(ConfigurationManager.AppSettings["longDate"]) * -1; #endregion IntPtr invalidHandle = IntPtr.Zero; #region Strings string cpsDataPath = @"" + ConfigurationManager.AppSettings["cpsDataPath"]; string prepDataPath = @"" + ConfigurationManager.AppSettings["prepDataPath"]; string prepDataPathCPS = @"" + ConfigurationManager.AppSettings["prepDataPathCPS"]; string vendor = ""; string batch = ""; string chunkFile = ""; string fileToDelete = ""; //strings for vendor commander paths string commDataPath = @"" + ConfigurationManager.AppSettings["commDataPath"]; string JSPPathCommander = @"" + ConfigurationManager.AppSettings["JSPPathCommander"]; string lraPathCommander = @"" + ConfigurationManager.AppSettings["lraPathCommander"]; string verizonPathCommander = @"" + ConfigurationManager.AppSettings["verizonPathCommander"]; string GandDPathCommander = @"" + ConfigurationManager.AppSettings["GandDPathCommander"]; string cpsPathCommander = @"" + ConfigurationManager.AppSettings["cpsPathCommander"]; string labelPath = @"" + ConfigurationManager.AppSettings["labelPath"]; string logFile = ""; string logFilePath = @"" + ConfigurationManager.AppSettings["logFilePath"]; string logFilePathCPS = @"" + ConfigurationManager.AppSettings["logFilePathCPS"]; string newLabelPath = ""; // Print spool path string printSpoolPath = @"" + ConfigurationManager.AppSettings["printSpoolPath"]; string fileName = ""; string jobNum = ""; string descript = ""; string customer = ""; string inFile = ""; string outFile = ""; string poNumber = ""; string firstRec = ""; string lastRec = ""; string formatFile = @"" + ConfigurationManager.AppSettings["formatFile"]; string labelPathCPS = @"" + ConfigurationManager.AppSettings["labelPathCPS"]; string dumpReportPath = @"" + ConfigurationManager.AppSettings["dumpReportPath"]; string dumpReportListFile = @"" + ConfigurationManager.AppSettings["dumpReportListFile"]; string boomerangFilesPath = @"" + ConfigurationManager.AppSettings["boomerangFilesPath"]; string boomerangSlvLog = @"" + ConfigurationManager.AppSettings["boomerangSlvLog"]; string cust = ""; string kit = ""; string db = ""; string totRecs = ""; string misc = ""; string customFormatsPath = @"" + ConfigurationManager.AppSettings["customFormatsPath"]; string jobDivider = "|----------------------------------------------------------------------------------------------------|"; string jJill4435Header = @"" + ConfigurationManager.AppSettings["jJill4435Header"]; string jJill4435Trailer = @"" + ConfigurationManager.AppSettings["jJill4435Trailer"]; string jJill5850Header = @"" + ConfigurationManager.AppSettings["jJill5850Header"]; string jJill5850Trailer = @"" + ConfigurationManager.AppSettings["jJill5850Trailer"]; string jJill6080Header = @"" + ConfigurationManager.AppSettings["jJill6080Header"]; string jJill6080Trailer = @"" + ConfigurationManager.AppSettings["jJill6080Trailer"]; string jJill6198Header = @"" + ConfigurationManager.AppSettings["jJill6198Header"]; string jJill6198Trailer = @"" + ConfigurationManager.AppSettings["jJill6198Trailer"]; #endregion //Boomerang queue timer, to check if the data\boomerang folder is empty System.Windows.Forms.Timer queueTimer = new System.Windows.Forms.Timer(); #region Window Finders WindowFinder main = new WindowFinder(); WindowFinder textBox = new WindowFinder(); WindowFinder overWrite = new WindowFinder();//added to force overwrite of all pdfs while in automation WindowFinder okButton = new WindowFinder(); WindowFinder yesButton = new WindowFinder();//added to force overwrite of all pdfs while in automation #endregion public LabelMonitor() { InitializeComponent(); string[] args = Environment.GetCommandLineArgs(); // The first commandline argument is always the executable path itself. if (args.Length > 1) { if (Array.IndexOf(args, "/auto") != -1) { checkBoxAutoMode.Checked = true; // The "/auto" switch was used. } } AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.UnhandledException += new UnhandledExceptionEventHandler(catchAllHandler); this.listBoxStatus.DrawMode = DrawMode.OwnerDrawFixed;//v 1.5.5 } public void catchAllHandler(object sender, UnhandledExceptionEventArgs args) { Exception e = (Exception)args.ExceptionObject; emailEmergency("ERROR! - Catch-all Handler: " + e.Message + Environment.NewLine + e.ToString(), ""); } private void LabelMonitor_Load(object sender, EventArgs e) { string startupMsg = "LabelMonitor started."; this.Text = Application.ProductName + " v." + Application.ProductVersion; statusStripStatusLabel.Text = Application.ProductName + " v. " + Application.ProductVersion + " loaded..."; AddMsg(statusStripStatusLabel.Text); writeToLog(startupMsg + "\r\n " + statusStripStatusLabel.Text, logFilePath); writeToLog(startupMsg + "\r\n " + statusStripStatusLabel.Text, logFilePathCPS); statusStripStatusLabel.Text = "Authored by J. Edwards, 2015. Rights applicable."; AddMsg(statusStripStatusLabel.Text); buttonRun.Enabled = false; runToolStripMenuItem.Enabled = false; cleanAfterBuildingToolStripMenuItem.Enabled = false; lookForPalletLabelsToolStripMenuItem.Enabled = false; lookForSleeveCartonLabelsToolStripMenuItem.Enabled = false; checkBoxCleanAfterBuilding.Enabled = false; checkBoxCPSLabels.Enabled = false; checkBoxPalletLabels.Enabled = false; checkBoxReprint.Enabled = false; chkBoxRebuild.Enabled = false; chkBoxRebuild.Visible = false; lblSlvPerCarton.Enabled = false; txtBoxSlvPerCarton.Enabled = false; txtBoxSlvPerCarton.Text = ConfigurationManager.AppSettings["slvPerCarton"]; ToolTip ToolTip = new System.Windows.Forms.ToolTip(); ToolTip.SetToolTip(this.chkBoxRebuild, "Check this box and Run to ONLY rebuild a broken list."); if (checkBoxAutoMode.Checked) { startupMsg = "Auto Mode active."; AddMsg(startupMsg); writeToLog(startupMsg, logFilePath); writeToLog(startupMsg, logFilePathCPS); labelAutoTime.Text = ""; checkApps(); autoTime = DateTime.Now.AddSeconds(5D); boomerangQueueTimer(0); // timer is in seconds //queueTimer.Interval = 5000; //queueTimer.Start(); //timerQueue.Start(); //startAutoProcessing(); } else { startupMsg = "Auto Mode inactive."; AddMsg(startupMsg); writeToLog(startupMsg, logFilePath); writeToLog(startupMsg, logFilePathCPS); labelAutoTime.Text = ""; checkApps(); } } //-------------------------------------------------------------------------------------------------// private void LabelMonitor_Resize(object sender, EventArgs e) { if (FormWindowState.Minimized == this.WindowState) { notifyIconLabelMonitor.Visible = true; this.Hide(); } } private void notifyIconLabelMonitor_Click(object sender, EventArgs e) { this.Show(); notifyIconLabelMonitor.Visible = false; this.WindowState = FormWindowState.Normal; } //-------------------------------------------------------------------------------------------------// //-----Begin primary Label Monitor Code //-------------------------------------------------------------------------------------------------// private void startAutoProcessing(object sender, EventArgs e) { if (queueTimer.Enabled == false) { if (((autoTime.Hour == DateTime.Now.Hour) && (autoTime.Minute == DateTime.Now.Minute) && (autoTime.Second == DateTime.Now.Second))) //We've waited and now the auto-run process begins... { AddMsg(jobDivider); writeToLog(jobDivider, logFilePath); writeToLog(jobDivider, logFilePathCPS); runStartTime = DateTime.Now; statusStripStatusLabel.Text = "Auto-processing started: " + runStartTime.ToString("F"); AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePath); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); //runningCode(); boomerangQueueCheck(sender, e); if (driveScanFail == false) //Run successful! Drives, folders, files 100% analyzed, checked, and iterated) { autoTime = DateTime.Now.AddMinutes(autoDelayTime); //Next run will be in xD minutes } } else { labelAutoTime.Text = "Next autorun is at " + autoTime.Hour.ToString("00") + ":" + autoTime.Minute.ToString("00") + ":" + autoTime.Second.ToString("00") + "; Currently " + DateTime.Now.Hour.ToString("00") + ":" + DateTime.Now.Minute.ToString("00") + ":" + DateTime.Now.Second.ToString("00"); } } else if (queueTimer.Enabled == true && DateTime.Now > autoTime) { autoTime = DateTime.Now.AddMinutes(2D); //add 2 minutes to the timer labelAutoTime.Text = "Next Boomerang queue check is at " + autoTime.ToString("hh:mm:ss") + Environment.NewLine + "Currently " + DateTime.Now.ToString("hh:mm:ss"); statusStripStatusLabel.Text = "Boomerang queue check ran longer than the next scheduled check."; AddMsg(statusStripStatusLabel.Text); statusStripStatusLabel.Text = "The Boomerang queue check timer has been reset."; writeToLog(statusStripStatusLabel.Text, logFilePath); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); } else { labelAutoTime.Text = "Next autorun is at " + autoTime.Hour.ToString("00") + ":" + autoTime.Minute.ToString("00") + ":" + autoTime.Second.ToString("00") + "; Currently " + DateTime.Now.Hour.ToString("00") + ":" + DateTime.Now.Minute.ToString("00") + ":" + DateTime.Now.Second.ToString("00"); } } private void runningCode() { if (timerAutoMode.Enabled == false) { AddMsg("|----------------------------------------------------------------------------------------------------|"); runStartTime = DateTime.Now; statusStripStatusLabel.Text = "Manual processing started: " + runStartTime.ToString("F"); AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePath); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); labelAutoTime.Visible = false; } if (queueTimer.Enabled == false) { //timerAutoMode.Stop();//stop the auto timer //labelAutoTime.Visible = false; //boomerangQueueTimer(0); //check the boomerang folder //if (queueTimer.Enabled == false) //if (timerQueue.Enabled == false) //{ // timerQueue.Start(); //boomerangQueueCheck(); //} //step 1 checkDrives(); //step 2 - Gemalto pallet labels if (checkBoxPalletLabels.Checked == true) { if (timerAutoMode.Enabled) { timerAutoMode.Enabled = false;//stop the auto timer labelAutoTime.Visible = false; reprocessPallet(); } else { reprocessPallet(); } } //step 3 - CPS (internal) sleeve and carton labels //if (queueTimer.Enabled == false) if (timerQueue.Enabled == false) { if (checkBoxCPSLabels.Checked == true) { //check if the sleeve per carton count has been manually changed before the run if (Int16.Parse(txtBoxSlvPerCarton.Text) != Int16.Parse(ConfigurationManager.AppSettings["slvPerCarton"])) { slvPerCarton = Int16.Parse(txtBoxSlvPerCarton.Text); } else { slvPerCarton = Int16.Parse(ConfigurationManager.AppSettings["slvPerCarton"]); } FileInfo[] dpt = dicps.GetFiles(); if (dpt.Length != 0)//if cps prep folder is not empty { if (timerAutoMode.Enabled) { timerAutoMode.Stop();//stop the auto timer labelAutoTime.Visible = false; reprocessCPSLabels();//check for and run reprints first } else { reprocessCPSLabels();//check for and run reprints first } } else//if cps prep folder is empty { statusStripStatusLabel.Text = "No CPS reprint labels to do."; AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); statusStripStatusLabel.Text = ""; if (timerAutoMode.Enabled) { timerAutoMode.Enabled = false;//stop the auto timer labelAutoTime.Visible = false; processCPSLabels();//check for and run new labels } else { processCPSLabels();//check for and run new labels } } } } //step 4 - Cleanup variable data and perform maintenance endBatchProcessing(); if (checkBoxAutoMode.Checked == true && timerAutoMode.Enabled == false) { autoTime = DateTime.Now.AddMinutes(autoDelayTime); timerAutoMode.Enabled = true;//start the auto timer labelAutoTime.Visible = true; } } else if (queueTimer.Enabled == true) { labelAutoTime.Text = "Rechecking the boomerang queue at " + autoTime.ToString("hh:mm:ss") + Environment.NewLine + "Currently " + DateTime.Now.ToString("hh:mm:ss"); } } private void checkDrives() { statusStripStatusLabel.Text = "LabelMonitor is checking drive locations, please stand by..."; AddMsg(statusStripStatusLabel.Text); // Check G:\Apps if (!Directory.Exists(commDataPath)) { statusStripStatusLabel.Text = "Commander paths cannot be reached."; AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePath); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); driveScanFail = true; } else if (!Directory.Exists(prepDataPath)) { statusStripStatusLabel.Text = "Prep data path cannot be reached."; AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePath); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); driveScanFail = true; } if (driveScanFail == true) //If checkDrives() produced a bad scan because a location was down/unavailable... { emailEmergency("WARNING!!!\n\n" + "LabelMonitor has detected that " + batch + " is " + "unavailable, or has encountered a system error while checking drives at " + DateTime.Now + ".\n\n" + "Please check network drives and/or the log file as soon as possible.\n\n", batch); last_driveScanFailTimeStamp = driveScanFailTimeStamp; //Exit the function return; } else { statusStripStatusLabel.Text = "Network folders are currently available."; AddMsg(statusStripStatusLabel.Text); } } /// /// Check Apps /// Function to check if Commander is running. /// private void checkApps() { //load a list with running processes foreach (Process runningProcesses in Process.GetProcesses()) { processList.Add(runningProcesses.ProcessName); } try { //check if Bartender/Commander isn't running if (!processList.Contains("Cmdr.exe")) { openCommander(); } } catch (Exception err) { statusStripStatusLabel.Text = "Cannot start Commander."; AddMsg(statusStripStatusLabel.Text); AddMsg(err.ToString()); writeToLog("Cannot start Commander. \r\n" + err.ToString(), logFilePath); writeToLog("Cannot start Commander. \r\n" + err.ToString(), logFilePathCPS); } } /// /// Checks for Gemalto/GandD (lbp and ldp) updated files /// This uses the G:\Apps\Gemalto\Raw_Data\prep folder /// private void reprocessPallet() { FileInfo[] dpf = dip.GetFiles(); if (dpf.Length == 1) //if prep folder only has one file in it { if (dpf[0].Name.ToUpper().EndsWith(".LDP") || dpf[0].Name.ToUpper().EndsWith(".LBP")) //if file is a pallet label file { batch = dpf[0].Name.ToString().Substring(0, dpf[0].Name.ToString().Length - 4); fileToDelete = batch.ToUpper() + ".da4"; string palletLabelPath = ""; if (batch.ToUpper().Contains("VZW")) { palletLabelPath = verizonPathCommander; vendor = "VZW"; } if (batch.ToUpper().Contains("N0")) { palletLabelPath = GandDPathCommander; vendor = "GND"; } if (batch.ToUpper().Contains("JSP")) { palletLabelPath = JSPPathCommander; vendor = "JSP"; } if (batch.ToUpper().Contains("LRA")) { palletLabelPath = lraPathCommander; vendor = "LRA"; } try { copyOutAndWait(dpf[0].FullName, dpf[0].Name, palletLabelPath, logFilePath); if (cleanAfterBuilding == true) { File.Delete(dpf[0].FullName);//remove from Raw_Data\prep } statusStripStatusLabel.Text = batch + " pallet reprint processing complete."; AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePath); } catch { statusStripStatusLabel.Text = batch + " pallet reprint failed! Please check the file before trying again."; AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePath); emailEmergency("ERROR: " + MethodBase.GetCurrentMethod().Name + ": " + statusStripStatusLabel.Text, dpf[0].Name); } } else { statusStripStatusLabel.Text = "The Gemalto prep folder contains a file that is not for pallet labels."; AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePath); statusStripStatusLabel.Text = ""; } } else if (dpf.Length == 0) { statusStripStatusLabel.Text = "No Gemalto pallet labels to do."; AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePath); statusStripStatusLabel.Text = ""; } Application.DoEvents(); } /// /// Processes the BarTender formated text files and preps them for commander /// This uses the G:\Apps\PDF_Labels\CPS\prep folder /// private void processCPSLabels() { lineData.Clear(); //Step 1. check for new data reports checkDumpReports();//look for new labels if (reportListFileUpdate.Count > 0) { foreach (string fileToUpdate in reportListFileUpdate) { string[] newFileName = fileToUpdate.Split(';'); //create bartender formatted file from file count check sheet and boomerang format(archive) file openAndReadFiles(newFileName[0]); } // Checks the CPS prep folder for any labels FileInfo[] dpf = dicps.GetFiles(); if (dpf.Length > 0) { for (int i = 0; i < dpf.Length; i++) { string labelType = ""; if (dpf[i].Name.ToLower().Contains("carton")) { labelType = "Carton"; } else if (dpf[i].Name.ToLower().Contains("sleeve")) { labelType = "Sleeve"; } if (dpf[i].Name.EndsWith(".txt")) { fileToDelete = dpf[i].Name.Replace(".txt", ".done"); } openBoomerangSlvLog(dpf[i].Name.Split('.')[0]); string commanderPathToRun = ""; if (fileToDelete.Contains("b435") || fileToDelete.Contains("b850") || fileToDelete.Contains("b080") || fileToDelete.Contains("b198"))//for J.Jill { commanderPathToRun = commDataPath + @"\JJill\"; } else { commanderPathToRun = cpsPathCommander + "\\"; } //check commander path and boomerang log if this is a reprint job if (File.Exists(commanderPathToRun + labelType + "Labels\\" + fileToDelete) || labelRunBefore == true) { try { copyOutAndWait(dpf[i].FullName, dpf[i].Name, commanderPathToRun + labelType + "Labels\\", logFilePathCPS); File.Copy(dpf[i].FullName, cpsDataPath + "\\" + dpf[i].Name, true);//copy prep file to data, for retention if (cleanAfterBuilding == true) { File.Delete(dpf[i].FullName);//remove from CPS\prep } statusStripStatusLabel.Text = dpf[i].Name + " deleted from CPS prep folder. Reprinting."; AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); } catch { statusStripStatusLabel.Text = dpf[i].FullName + " failed to delete! Please check the file before trying again."; AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); emailEmergency("ERROR: " + MethodBase.GetCurrentMethod().Name + ": " + statusStripStatusLabel.Text, dpf[i].Name); } } else//this is a new print job { try { copyOutAndWait(dpf[i].FullName, dpf[i].Name, commanderPathToRun + labelType + "Labels\\", logFilePathCPS); File.Copy(dpf[i].FullName, cpsDataPath, true);//copy prep file to data, for retention if (cleanAfterBuilding == true) { File.Delete(dpf[i].FullName);//remove from CPS\prep } statusStripStatusLabel.Text = batch + " " + labelType + " label print processing complete."; AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); } catch { statusStripStatusLabel.Text = batch + " " + labelType + " label print failed! Please check the file before trying again."; AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); emailEmergency("ERROR: " + MethodBase.GetCurrentMethod().Name + ": " + statusStripStatusLabel.Text, dpf[i].Name); } } Application.DoEvents(); } writeToDumpReportListFile();//finally update dumpReportList.txt for the next run } } else { statusStripStatusLabel.Text = "No CPS labels to do."; AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); statusStripStatusLabel.Text = ""; } } /// /// Checks for updated Carton/Sleeve Label files (i.e. slvPerCarton change) /// This uses the G:\Apps\PDF_Labels\CPS\prep folder /// and contains conditional handling for FORD custom labels /// private void reprocessCPSLabels() { FileInfo[] dpr = dicps.GetFiles(); if (dpr.Length != 0)//if cps prep folder is not empty { statusStripStatusLabel.Text = "Found " + dpr.Length + " CPS labels to update first."; AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); foreach (FileInfo file in dpr) { fileToDelete = file.Name; string commanderPath = ""; if (fileToDelete.Contains("Sleeve")) { if (fileToDelete.Contains("b435") || fileToDelete.Contains("b850") || fileToDelete.Contains("b080") || fileToDelete.Contains("b198")) //for J.Jill { commanderPath = commDataPath + @"\JJill\SleeveLabels"; } else { commanderPath = cpsPathCommander + @"\SleeveLabels"; } //check the previous run's file for a change in slvPerCarton string prevSlvLabelFile = commanderPath + "\\" + fileToDelete.Replace(".txt", ".done"); int lineCount = 0; string prevLine = ""; string[] prevLineData; int prevSlvPerCartonCount = 0; if (File.Exists(prevSlvLabelFile)) { using (FileStream fsPf = new FileStream(prevSlvLabelFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (StreamReader sr0 = new StreamReader(fsPf)) { while ((prevLine = sr0.ReadLine()) != null) { if (lineCount > 0)//skip the header row { //Create string array of file data prevLineData = prevLine.Split(';'); if (prevSlvLabelFile.Contains("b435") || prevSlvLabelFile.Contains("b850") || prevSlvLabelFile.Contains("b080") || prevSlvLabelFile.Contains("b198"))// for J.Jill { prevSlvPerCartonCount = 8; } else//for everything else { prevSlvPerCartonCount = Int16.Parse(prevLineData[8].ToString()); } } lineCount++; } sr0.Close(); sr0.Dispose(); fsPf.Close(); fsPf.Dispose(); } } //check current sleeve file for comparison lineCount = 0; string line = ""; string[] lineData; int slvPerCartonCount = 0; using (FileStream fsCf = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (StreamReader sr1 = new StreamReader(fsCf)) { while ((line = sr1.ReadLine()) != null) { if (lineCount > 0)//skip the header row { //Create string array of file data lineData = line.Split(';'); if (file.FullName.Contains("b435") || file.FullName.Contains("b850") || file.FullName.Contains("b080") || file.FullName.Contains("b198"))// for J.Jill { slvPerCartonCount = 8; } else { slvPerCartonCount = Int16.Parse(lineData[8].ToString()); } customer = lineData[0].ToString(); } lineCount++; } sr1.Close(); sr1.Dispose(); fsCf.Close(); fsCf.Dispose(); } if (prevSlvPerCartonCount != slvPerCartonCount)//if slvPerCartonCount values don't match (as in a reprocess is required) { statusStripStatusLabel.Text = "Rebuilding " + fileToDelete + "..."; AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); writeSleeveLabels(file.Name.Split('_')[0]); writeCartonLabels(file.Name.Split('_')[0]); FileInfo[] dpr2 = dicps.GetFiles(); if (dpr2.Length != 0)//if cps prep folder is not empty { statusStripStatusLabel.Text = "Rechecking prep... found " + dpr2.Length + " CPS label files to update first."; AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); foreach (FileInfo file2 in dpr2) { try { if (file2.Name.Contains("Sleeve")) { commanderPath = cpsPathCommander + @"\SleeveLabels"; } //copyOutAndWait(file2.FullName, file2.Name, commanderPath, logFilePathCPS); if (cleanAfterBuilding == true) { File.Delete(file2.FullName);//remove from CPS\prep } statusStripStatusLabel.Text = file2.Name + " reprint processing complete."; AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); } catch { statusStripStatusLabel.Text = file2.Name + " reprint failed! Please check the file before trying again."; AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); emailEmergency("ERROR: " + MethodBase.GetCurrentMethod().Name + ": " + statusStripStatusLabel.Text, file2.Name); } } } emailSlvUpdate("J" + file.Name.Substring(1, 4), "Sleeves Per Carton has been changed from " + prevSlvPerCartonCount + " to " + slvPerCartonCount + ".\r\n" + "Verify with production and/or shipping if this is a permanent change.\r\n" + "An update to the Boomerang format may be required."); } else { try { copyOutAndWait(file.FullName, file.Name, commanderPath, logFilePathCPS); if (cleanAfterBuilding == true) { File.Delete(file.FullName);//remove from CPS\prep } statusStripStatusLabel.Text = file.Name + " reprint processing complete."; AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); } catch { statusStripStatusLabel.Text = file.Name + " reprint failed! Please check the file before trying again."; AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); emailEmergency("ERROR: " + MethodBase.GetCurrentMethod().Name + ": " + statusStripStatusLabel.Text, file.Name); } } } else if (fileToDelete.Contains("Carton")) { if (fileToDelete.Contains("b435") || fileToDelete.Contains("b850") || fileToDelete.Contains("b080") || fileToDelete.Contains("b198")) //for J.Jill { commanderPath = commDataPath + @"\JJill\CartonLabels"; } else { commanderPath = cpsPathCommander + @"\CartonLabels"; } try { copyOutAndWait(file.FullName, file.Name, commanderPath, logFilePathCPS); if (cleanAfterBuilding == true) { File.Delete(file.FullName);//remove from CPS\prep } statusStripStatusLabel.Text = file.Name + " reprint processing complete."; AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); } catch { statusStripStatusLabel.Text = file.Name + " reprint failed! Please check the file before trying again."; AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); emailEmergency("ERROR: " + MethodBase.GetCurrentMethod().Name + ": " + statusStripStatusLabel.Text, file.Name); } } } if (cleanAfterBuilding == true && dpr.Length > 0) { foreach (FileInfo file in dpr) { file.Delete();//cleanout cps\prep } } } else if (dpr.Length == 0) { statusStripStatusLabel.Text = "No CPS labels to update, continuing..."; AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); statusStripStatusLabel.Text = ""; } } /// /// Checks for new jobs needing lables and updates the dumpReportList.txt file /// The dumpReportList.txt file makes a copy of the previous run's BAS_Folder contents /// This uses the G:\Apps\BAS_Reports folder /// private void checkDumpReports() { FileInfo[] fi; fi = didr.GetFiles(); int fiCount = 0; dumpReportList.Clear(); reportListFile.Clear(); statusStripStatusLabel.Text = ""; statusStripStatusLabel.Text = "Scanning File Count Check Sheets."; //create a list of existing report files in BAS_Files foreach (FileInfo file in fi) { if (file.Name.Contains("Dump")) { fiCount++; if (!statusStripStatusLabel.Text.Contains(" . . . . . . . . . . . . . . . . . . . .")) { if (fiCount % 50 == 0) { statusStripStatusLabel.Text += " ."; } } else { statusStripStatusLabel.Text = statusStripStatusLabel.Text.Replace(" . . . . . . . . . . . . . . . . . . . .", " ."); } Application.DoEvents(); FileStream testStream = null; bool fileInUse = false; try { testStream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None); } catch (IOException ioEx) { //do nothing with this file, just record the reason fileInUse = true; statusStripStatusLabel.Text = "BAS report file " + file.Name + " is in use and will not be processed at this time."; AddMsg(statusStripStatusLabel.Text); writeToLog("ERROR: " + MethodBase.GetCurrentMethod().Name + ": " + statusStripStatusLabel.Text + "\r\n" + ioEx.ToString(), logFilePathCPS); } finally { if (testStream != null) { testStream.Close(); } } if (fileInUse == true) { continue; } else { dumpReportList.Add(file.Name + ";" + file.CreationTime + ";" + file.LastWriteTime + ";" + file.Length); } } } //if the report list file is missing or empty if (!File.Exists(dumpReportListFile) || new FileInfo(dumpReportListFile).Length == 0) { writeToDumpReportListFile(); } try { using (FileStream fsDr = new FileStream(dumpReportListFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (StreamReader sr = new StreamReader(fsDr))//open and read the report list file { string line = ""; while ((line = sr.ReadLine()) != null) { if (line.StartsWith("J"))//skip the header line { reportListFile.Add(line); } } sr.Close(); sr.Dispose(); fsDr.Close(); fsDr.Dispose(); } } catch (Exception err) { statusStripStatusLabel.Text = "Dump report list file " + dumpReportListFile + " cannot be read at this time."; AddMsg(statusStripStatusLabel.Text); writeToLog("ERROR: " + MethodBase.GetCurrentMethod().Name + ": " + statusStripStatusLabel.Text + "\r\n" + err.ToString(), logFilePathCPS); } //read through the dumpReportListFile's file names //and compare to the files on the network drive int matchCount = 0; for (int i = 0; i < dumpReportList.Count; i++) { try { string[] readLineChunk = dumpReportList[i].Split(';'); for (int j = 0; j < reportListFile.Count; j++) { string[] lineChunk = reportListFile[j].Split(';'); if (dumpReportList[i] != reportListFile[j]) { //if this is a new report, not in the list file if (lineChunk[0] != readLineChunk[0]) { if (j == (reportListFile.Count - 1)) { matchCount++; reportListFileUpdate.Add(dumpReportList[i]); } } else if (lineChunk[0] == readLineChunk[0])//if the actual report file is in the list file {//if anything is a mismatch, or an update in any way if (lineChunk[1] != readLineChunk[1] || lineChunk[2] != readLineChunk[2] || lineChunk[3] != readLineChunk[3]) { matchCount++; reportListFileUpdate.Add(dumpReportList[i]);//add to the update list if the current record has been changed break; } } } else if (dumpReportList[i] == reportListFile[j]) { break; } Application.DoEvents(); } } catch (System.ArgumentOutOfRangeException) { reportListFileUpdate.Add(dumpReportList[i]); } } checkBoomerangFiles(); //verify the files in dumpReportList exist in G:\data //dumpReportList.Clear(); int fileListCount = 0; statusStripStatusLabel.Text = ""; statusStripStatusLabel.Text = "Building list of files to do."; foreach (string newFile in newReportList) { if (!dumpReportList.Contains(newFile)) { fileListCount++; if (!statusStripStatusLabel.Text.Contains(" . . . . . . . . . . . . . . . . . . . .")) { if (fileListCount % 20 == 0) { statusStripStatusLabel.Text += " ."; } } else { statusStripStatusLabel.Text = statusStripStatusLabel.Text.Replace(" . . . . . . . . . . . . . . . . . . . .", " ."); } Application.DoEvents(); dumpReportList.Add(newFile); } } } /// /// Checks for existing Boomerang output files, to strip unnecessary items /// from the dumpReportList array, before processing /// This uses the G:\data folder /// private void checkBoomerangFiles() { FileInfo[] fib; fib = dibf.GetFiles();//check txt files in G:\data int fibCount = 0; List temp = new List(); statusStripStatusLabel.Text = ""; statusStripStatusLabel.Text = "Prepping Boomerang database files."; //foreach (FileInfo file in fib) foreach (string file in reportListFileUpdate) { try { fibCount++; if (!statusStripStatusLabel.Text.Contains(" . . . . . . . . . . . . . . . . . . . .")) { if (fibCount % 2 == 0) { statusStripStatusLabel.Text += " ."; } } else { statusStripStatusLabel.Text = statusStripStatusLabel.Text.Replace(" . . . . . . . . . . . . . . . . . . . .", " ."); } Application.DoEvents(); //temp.Add(file.Name); temp.Add(file.Split(';')[0]); //Any encoded/Duffy's Jobs (encoded track data in files purposely pipe delimited) if (file.Split(';')[0].Contains("3806") || file.Split(';')[0].Contains("3808") || file.Split(';')[0].Contains("4941") || file.Split(';')[0].Contains("4942") || file.Split(';')[0].Contains("3600")) { string tempFile = file.Replace(";", "|"); tempOut.Add(tempFile + "|" + File.ReadAllText(dumpReportPath + "\\" + tempFile.Split('|')[0])); } else { tempOut.Add(file + ";" + File.ReadAllText(dumpReportPath + "\\" + file.Split(';')[0])); } } catch (IndexOutOfRangeException err) { AddMsg(file + " is out of the bounds of the array, exportListFileUpdate, in the foreach loop."); writeToLog("ERROR: " + MethodBase.GetCurrentMethod().Name + ": " + file + " is out of the bounds of the array, exportListFileUpdate, in the foreach loop.\r\n" + err.ToString(), logFilePathCPS); } } //List tempOut = new List(); //if G:\data equals BAS_Report //foreach (string fileToRead in dumpReportList) //{ // tempOut.Add(fileToRead + ";" + File.ReadAllText(dumpReportPath + "\\" + fileToRead.Split(';')[0])); //} statusStripStatusLabel.Text = ""; statusStripStatusLabel.Text = "Scanning Boomerang database files."; Application.DoEvents(); for (int i = 0; i < temp.Count; i++) { string fileToFind = temp[i].ToLower().Substring(0, temp[i].Length - 4); for (int j = 0; j < tempOut.Count; j++) { try { if (tempOut[j].ToLower().Contains(fileToFind)) { if (tempOut[j].Contains("3806") || tempOut[j].Contains("3808") || tempOut[j].Contains("4941") || tempOut[j].Contains("4942") || tempOut[j].Contains("3600")) { newReportList.Add(tempOut[j].Split('|')[0] + ";" + tempOut[j].Split('|')[1] + ";" + tempOut[j].Split('|')[2] + ";" + tempOut[j].Split('|')[3]); } else { newReportList.Add(tempOut[j].Split(';')[0] + ";" + tempOut[j].Split(';')[1] + ";" + tempOut[j].Split(';')[2] + ";" + tempOut[j].Split(';')[3]); } break; } } catch (IndexOutOfRangeException err) { AddMsg(fileToFind + " (tempOut[j]) is out of the bounds of the array, exportListFileUpdate, in the foreach loop."); writeToLog(fileToFind + " (tempOut[j]) is out of the bounds of the array, exportListFileUpdate, in the foreach loop.\r\n" + err.ToString(), logFilePathCPS); } } if (!statusStripStatusLabel.Text.Contains(" . . . . . . . . . . . . . . . . . . . .")) { if (i % 2 == 0) { statusStripStatusLabel.Text += " ."; } } else { statusStripStatusLabel.Text = statusStripStatusLabel.Text.Replace(" . . . . . . . . . . . . . . . . . . . .", " ."); } Application.DoEvents(); } temp.Clear(); temp.TrimExcess(); //tempOut.Clear(); //tempOut.TrimExcess(); } private void endBatchProcessing() { bundleAmt = 0; reportListFile.Clear(); reportListFile.TrimExcess(); reportListFileUpdate.Clear(); reportListFileUpdate.TrimExcess(); dumpReportList.Clear(); dumpReportList.TrimExcess(); newReportList.Clear(); newReportList.TrimExcess(); firstLastList.Clear(); firstLastList.TrimExcess(); inFileList.Clear(); inFileList.TrimExcess(); outFileList.Clear(); outFileList.TrimExcess(); boomerangList.Clear(); boomerangList.TrimExcess(); lineData.Clear(); lineData.TrimExcess(); cartonLineData.Clear(); cartonLineData.TrimExcess(); tempOut.Clear(); tempOut.TrimExcess(); boomerangFormatFile.Clear(); boomerangFormatFile.TrimExcess(); fileName = ""; vendor = ""; batch = ""; cust = ""; kit = ""; db = ""; totRecs = ""; firstRec = ""; lastRec = ""; poNumber = ""; spoolTimer.Stop(); spoolTimer.Enabled = false; spoolTimer.Interval = 1; if (checkBoxAutoMode.Checked) { buttonRun.Enabled = false; } else { buttonRun.Enabled = true; checkBoxCPSLabels.Enabled = true; checkBoxPalletLabels.Enabled = true; txtBoxSlvPerCarton.Enabled = true; lblSlvPerCarton.Enabled = true; runToolStripMenuItem.Enabled = true; cleanAfterBuildingToolStripMenuItem.Enabled = true; lookForPalletLabelsToolStripMenuItem.Enabled = true; lookForSleeveCartonLabelsToolStripMenuItem.Enabled = true; checkBoxCleanAfterBuilding.Enabled = true; } runEndTime = DateTime.Now; statusStripStatusLabel.Text = "Processing completed: " + runEndTime.ToString("F"); TimeSpan ts = runEndTime - runStartTime; AddMsg(statusStripStatusLabel.Text); if (lineCount > 0) { AddMsg(lineCount + " CPS labels created."); writeToLog(lineCount + " CPS labels created.", logFilePathCPS); } AddMsg("Total run time: " + ts.Minutes + " minutes and " + ts.Seconds + " seconds."); writeToLog("Total run time: " + ts.Minutes + " minutes and " + ts.Seconds + " seconds.", logFilePathCPS); //Post job maintenance AddMsg(jobDivider); writeToLog(jobDivider, logFilePathCPS); statusStripStatusLabel.Text = "Post job maintenance started."; AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); commanderFolderMaintenance(); dataFolderMaintenance(); labelFolderMaintenance(); logFolderMaintenance(); statusStripStatusLabel.Text = "Ready."; AddMsg(statusStripStatusLabel.Text); lineCount = 0; GC.Collect(); } //-------------------------------------------------------------------------------------------------// //-----Begin secondary Label Monitor Code //-------------------------------------------------------------------------------------------------// #region .bat File Functions private void openCommander() { Process commander = new Process(); //for 64bit if ((Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE") == "AMD64") || (Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432") == "AMD64")) { commander.StartInfo.FileName = "commanderStart64.bat"; } else //for 32bit { commander.StartInfo.FileName = "commanderStart.bat"; //commander needs an external batch file or it is started as a service and breaks } commander.Start(); } private void closeCommander() { Process commander = new Process(); commander.StartInfo.FileName = "commanderStop.bat"; commander.Start(); } #endregion #region Email and Messaging private void AddMsg(string msgData) { listBoxStatus.Items.Add(msgData/* + " (" + DateTime.Now.ToLongTimeString() + ")"*/); listBoxStatus.SetSelected(listBoxStatus.Items.Count - 1, true); //auto-scroll listbox //auto clean up... if more than 500 lines of text exist in the status box, remove them starting with the oldest record if (listBoxStatus.Items.Count > 500) { listBoxStatus.Items.RemoveAt(0); } } private void emailSlvUpdate(string jobNO, string notice) { try { MailMessage oMsg = new MailMessage(); oMsg.From = new MailAddress("GemaltoNET@cpscards.com"); string[] appSettings = ConfigurationManager.AppSettings.AllKeys; foreach (string key in appSettings) { if (key.ToLower().StartsWith("mailto")) { oMsg.To.Add(ConfigurationManager.AppSettings[key]); } } oMsg.Subject = "LabelMonitor Notice: " + jobNO + " Sleeve Per Carton Change"; oMsg.Body = " LabelMonitor Automation email\r\n" + " ================================== \r\n" + "> Job " + jobNO + "_CartonLabel\n\n" + notice + "\r\n\n\n" + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString() + "\n" + " ================================== \r\n"; oMsg.Priority = MailPriority.Normal; SmtpClient mySMTP = new SmtpClient(ConfigurationManager.AppSettings["smtp"]); mySMTP.Credentials = new NetworkCredential("gemaltonet@cpscards.com", "sonsverb1"); mySMTP.Send(oMsg); oMsg = null; } catch (Exception e) { statusStripStatusLabel.Text = "Error occurred when sending sleeve per carton update email."; AddMsg(statusStripStatusLabel.Text); writeToLog("ERROR: " + MethodBase.GetCurrentMethod().Name + ": " + statusStripStatusLabel.Text + e.ToString(), logFilePathCPS); } } private void emailEmergency(string message, string batch) { bool emailSentOK = false; //just to make sure emergency email was sent 2013-10-22 bool emailBackupPlanDidNotWork = false; //if there is a problem sending email, so we don't infinitely loop 2013-10-22 int numberOfTries = 1; //how many times we tried to send email 2013-10-22 while ((emailSentOK == false) && (emailBackupPlanDidNotWork == false)) { try { MailMessage oMsg = new MailMessage(); oMsg.From = new MailAddress("GemaltoNET@cpscards.com"); string[] appSettings = ConfigurationManager.AppSettings.AllKeys; foreach (string key in appSettings) { if (key.ToLower().StartsWith("alertmailto")) { oMsg.To.Add(ConfigurationManager.AppSettings[key]); } } if (string.IsNullOrEmpty(batch)) { oMsg.From = new MailAddress("MIS@cpscards.com"); oMsg.Subject = "CPS LabelMonitor - Emergency MIS Notice"; } else { //if a cps label if (batch.ToUpper().Contains("F") || (batch.ToUpper().StartsWith("A") && !(batch.ToUpper().Contains("ALD")))) { oMsg.From = new MailAddress("MIS@cpscards.com"); oMsg.Subject = "CPS LabelMonitor - Emergency MIS Notice - Batch: " + batch.Substring(0, batch.LastIndexOf(".")); } else //a gemalto pallet label { oMsg.From = new MailAddress("GemaltoNET@cpscards.com"); oMsg.Subject = "CPS GemaltoNET:LabelMonitor - Emergency MIS Notice - Batch: " + batch.Substring(0, batch.LastIndexOf(".")); } } //Body of email (passed in to emailNetworkDrivesError method) oMsg.Body = message + "\r\n\n For more details, follow this link to the log: " + logFile; oMsg.Priority = MailPriority.High; SmtpClient mySMTP = new SmtpClient(ConfigurationManager.AppSettings["smtp"]); mySMTP.Credentials = new NetworkCredential("gemaltonet@cpscards.com", "sonsverb1"); mySMTP.Send(oMsg); oMsg = null; emailSentOK = true; //email was sent ok, we can break out of while loop 2013-10-22 } catch (Exception e) { statusStripStatusLabel.Text = "Error occurred when sending emergency email, attempt " + numberOfTries.ToString() + "..."; AddMsg(statusStripStatusLabel.Text); writeToLog("ERROR: " + MethodBase.GetCurrentMethod().Name + ": " + statusStripStatusLabel.Text + e.ToString(), logFilePathCPS); System.Threading.Thread.Sleep(3000); //wait three seconds before trying again numberOfTries++; if (numberOfTries > 21) //if we tried to send emergency email for 60 seconds solid and failed... { emailBackupPlanDidNotWork = true; } } } if (emailBackupPlanDidNotWork == true) //Email failed to send after a period of time { statusStripStatusLabel.Text = "Emergency email backup loop failed (email was not sent)..."; AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); numberOfTries = 0; } } #endregion #region File Copying and IO /// /// A method to copy out a file to a specific Commander watch directory and wait for doPDF. /// /// Path string of file to be copied /// Only the filename string of the file to be copied /// Path string to the required Commander directory /// Path string to the job log file private void copyOutAndWait(string fileToCopyFULL, string fileToCopyNAMEONLY, string CommanderDirectory, string logPath) { int fileExtensionIndex = fileToCopyNAMEONLY.LastIndexOf("."); string fileWithoutExtension = fileToCopyNAMEONLY.Substring(0, fileExtensionIndex); string fileExtension = fileToCopyNAMEONLY.Substring(fileExtensionIndex); string fileToCopyEXTENSION = fileToCopyNAMEONLY.Substring(fileToCopyNAMEONLY.Length - 3, 3); string fileToCopyNAMEWITHNOEXTENSION = fileToCopyNAMEONLY.Substring(0, 8); //Copy the file to the Commander directory try { string fileToWorkWith = CommanderDirectory + "\\" + fileToCopyNAMEONLY.Replace(".txt", ".done"); if (File.Exists(fileToWorkWith)) { File.Delete(fileToWorkWith); } statusStripStatusLabel.Text = fileToDelete.Replace(".txt", ".done") + " deleted for rerun processing."; AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logPath); File.Copy(fileToCopyFULL, CommanderDirectory + "\\" + fileToCopyNAMEONLY, true); } catch (Exception copyFail) { if (/*timerAutoMode.Enabled*/ checkBoxAutoMode.Checked == true) { statusStripStatusLabel.Text = "Failure to copy " + fileToCopyNAMEONLY + " to Commander folder!"; AddMsg(statusStripStatusLabel.Text); writeToLog("ERROR: " + MethodBase.GetCurrentMethod().Name + ": " + statusStripStatusLabel.Text + copyFail.ToString(), logPath); } else { MessageBox.Show("LabelMonitor failed to copy file " + fileToCopyNAMEONLY + " to Commander for processing.\n" + "Please check the file and copy it manually.", "Error copying file to Commander watch folder", MessageBoxButtons.OK, MessageBoxIcon.Error); } return; } if (fileToCopyNAMEONLY.ToUpper().StartsWith("LRA")) { newLabelPath = labelPath + "\\LRA"; } else if (fileToCopyNAMEONLY.ToUpper().StartsWith("JSP")) { newLabelPath = labelPath + "\\JSP"; } else if (fileToCopyNAMEONLY.ToUpper().StartsWith("VZW")) { newLabelPath = labelPath + "\\VZW"; } else if (fileToCopyNAMEONLY.ToUpper().Contains("N0")) { newLabelPath = labelPath + "\\GandD"; } else if (fileToCopyNAMEONLY.Contains("CartonLabel")) { newLabelPath = labelPathCPS + "\\CartonLabels"; } else if (fileToCopyNAMEONLY.Contains("SleeveLabel")) { newLabelPath = labelPathCPS + "\\SleeveLabels"; } try { if ((fileToCopyNAMEONLY.ToUpper().Contains(".LDP")) || (fileToCopyNAMEONLY.ToUpper().Contains(".LBP"))) //AT&T (NSM) carton labels and/or JSP carton labels + LBP or LDP file { string pdfToDelete = newLabelPath + "\\" + fileWithoutExtension.ToUpper() + "_Pallet.pdf"; try { File.Delete(pdfToDelete);//delete the existing pallet label first } catch (Exception ex) { statusStripStatusLabel.Text = "LabelMonitor failed to delete Gemalto pallet file " + pdfToDelete + ",\r\n halting the pre-processing for copyOutAndWait() procedure. \r\n" + ex.ToString(); AddMsg(statusStripStatusLabel.Text); writeToLog("ERROR: " + MethodBase.GetCurrentMethod().Name + ": " + statusStripStatusLabel.Text, logPath); endBatchProcessing(); return; } //Waiting for a DoPDF window found = false; look = 0; timerDoPDF.Enabled = true; if (fileToCopyNAMEONLY.ToUpper().Contains(".LBP") || fileToCopyNAMEONLY.ToUpper().Contains(".LDP")) { chunkFile = newLabelPath + "\\" + fileWithoutExtension.ToUpper() + "_Pallet.pdf"; } holdOn(); if (slamOnTheBrakes == true) { //Major problem - stop chunkifying IMMEDIATELY! statusStripStatusLabel.Text = "DoPDF FAILED! Chunkify process aborted for " + fileToCopyNAMEONLY + "..."; writeToLog(statusStripStatusLabel.Text, logPath); AddMsg(statusStripStatusLabel.Text); slamOnTheBrakes = false; //come out of auto mode //we are no longer busy return; } } else if (fileToCopyNAMEONLY.Contains("CartonLabel") || fileToCopyNAMEONLY.Contains("SleeveLabel")) { string pdfToDelete = newLabelPath + "\\" + fileWithoutExtension + ".pdf"; try { File.Delete(pdfToDelete);//delete the existing CPS label first } catch (Exception ex) { statusStripStatusLabel.Text = "LabelMonitor failed to delete CPS file " + pdfToDelete + ",\r\n halting the pre-processing for copyOutAndWait() procedure. \r\n" + ex.ToString(); AddMsg(statusStripStatusLabel.Text); writeToLog("ERROR: " + MethodBase.GetCurrentMethod().Name + ": " + statusStripStatusLabel.Text, logPath); endBatchProcessing(); return; } //Waiting for a DoPDF window found = false; look = 0; timerDoPDF.Enabled = true; chunkFile = newLabelPath + "\\" + fileWithoutExtension + ".pdf"; holdOn(); if (slamOnTheBrakes == true) { //Major problem - stop chunkifying IMMEDIATELY! statusStripStatusLabel.Text = "DoPDF FAILED! CPS chunkify process aborted for " + fileToCopyNAMEONLY + "..."; writeToLog(statusStripStatusLabel.Text, logPath); AddMsg(statusStripStatusLabel.Text); slamOnTheBrakes = false; //come out of auto mode //we are no longer busy return; } } } catch (Exception waitFail) { if (timerAutoMode.Enabled) { statusStripStatusLabel.Text = "Unknown error while waiting for CPS chunk processing!"; AddMsg(statusStripStatusLabel.Text); writeToLog("ERROR: " + MethodBase.GetCurrentMethod().Name + ": " + statusStripStatusLabel.Text, logPath); } else { MessageBox.Show(waitFail.ToString(), "Unknown error while waiting for CPS chunk processing to finish", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } /// /// Get content from a BAS Report file /// /// Name string of the BAS Report file to be read private void openAndReadFiles(string newFile) { //open first/last log (BAS report) file first fileName = newFile; int labelCount = 0; List outCounter = new List(); try { if (fileName.Contains("DumpReport"))//for automation "a" files { string[] dumpFileContents = new string[0]; foreach (string tempOutFile in tempOut)//get dump report file contents { string tempOutFileName = ""; string tempOutFileContents = ""; //for testing only //statusStripStatusLabel.Text = "Reading dump report " + tempOutFile.Split(';')[0] + "."; //AddMsg(statusStripStatusLabel.Text); //Application.DoEvents(); //for mag/Duffy's jobs (encoded track data in files purposely pipe delimited) if (tempOutFile.Split('_')[0].Contains("3806") || tempOutFile.Split('_')[0].Contains("3808") || tempOutFile.Split('_')[0].Contains("4941") || tempOutFile.Split('_')[0].Contains("4942") || tempOutFile.Split('_')[0].Contains("3600")) { tempOutFileName = tempOutFile.Split('|')[0]; tempOutFileContents = tempOutFile.Split('|')[4]; } else { tempOutFileName = tempOutFile.Split(';')[0]; tempOutFileContents = tempOutFile.Split(';')[4]; } if (tempOutFileName == fileName) { dumpFileContents = tempOutFileContents.Split(new string[] { Environment.NewLine }, StringSplitOptions.None); } } foreach (string s in dumpFileContents) { //do minimal amount of work here if (s.StartsWith("> Job number : ")) { jobNum = "J" + s.Substring(19); } //use this if for description from output log if (s.StartsWith("> Description : ")) { customer = s.Substring(17).Split(new String[] { " - " }, StringSplitOptions.None)[0]; descript = ""; } if (s.StartsWith("> In file name : ")) { lineCount++; //Added infile string.replace for files with " - " (2016-04-08, jae) inFile = s.Substring(17, s.Substring(17).Length - 4).Replace(" ", "_").Replace("-", "_"); //labelCount++; //for Duffy's jobs (pipe delimited files) if (jobNum.Contains("3806") || jobNum.Contains("3808") || jobNum.Contains("4941") || jobNum.Contains("4942")) { if (inFile.Contains("(cards)")) { inFileList.Add(inFile); } } else { inFileList.Add(inFile); } labelCount++; } if (s.StartsWith("> Out file name: ")) { outFile = s.Substring(17, s.Substring(17).Length - 4); if (jobNum.Contains("3806") || jobNum.Contains("3808") || jobNum.Contains("4941") || jobNum.Contains("4942")) { if (inFile.Contains("(cards)")) { outFileList.Add(outFile); } } else { outFileList.Add(outFile); } } if (s.StartsWith("> PO number : "))//added ponumber (2016-06-02, jae) { poNumber = s.Substring(17); } if (s.StartsWith("> Record count : ")) { recordCount = Int32.Parse(s.Substring(17).Replace(",", "")); //lineData.Add(jobNum + ";" + inFile + ";" + outFile + ";" + recordCount); outCounter.Add(recordCount); for (int i = 0; i < outFileList.Count; i++) { lineData.Add(jobNum + ";" + inFileList[i] + ";" + outFileList[i] + ";" + outCounter[i]); } } } if (labelCount == 1) { AddMsg("1 label file to make for " + outFile + "."); } else if (labelCount > 1) { AddMsg(labelCount.ToString() + " label files to make for " + outFile + "."); } } else if (fileName.Contains("DataDump"))//for manual jobs { string[] dumpFileContents = new string[0]; foreach (string tempOutFile in tempOut)//get dump report file contents { statusStripStatusLabel.Text = "Reading dump report " + tempOutFile + "."; AddMsg(statusStripStatusLabel.Text); Application.DoEvents(); string tempOutFileName = tempOutFile.Split(';')[0]; string tempOutFileContents = tempOutFile.Split(';')[4]; if (tempOutFileName == fileName) { dumpFileContents = tempOutFile.Split(new string[] { Environment.NewLine }, StringSplitOptions.None); } } foreach (string s in dumpFileContents) { //do minimal amount of work here if (s.StartsWith("File name :"))//input/output files { lineCount++; int inFileLength = s.Length; if (inFileLength < 27) { inFile = s.Substring(14, 12); outFile = inFile; } else { //Added infile string.replace for files with " - " (2016-04-08, jae) inFile = s.Substring(14, s.Substring(14).Length - 15).Replace(" ", "_").Replace("-", "_"); outFile = s.Substring(s.Length - 9, 8); } inFileList.Add(inFile); outFileList.Add(outFile); labelCount++; } if (s.StartsWith("PO Number :")) { poNumber = s.Substring(14); } if (s.StartsWith("Record count:")) { recordCount = Int32.Parse(s.Substring(14).Replace(",", "")); //lineData.Add(jobNum + ";" + inFile + ";" + outFile + ";" + recordCount); outCounter.Add(recordCount); } if (s.StartsWith("> Add. info :")) { jobNum = s.Substring(14, 5); if (s.Contains("_")) { customer = s.Substring(20).Split('_')[0].Trim();//setup for use in writeCartonLabels() } else if (s.Contains("-")) { customer = s.Substring(20).Split('-')[0].Trim();//setup for use in writeCartonLabels() } for (int i = 0; i < outFileList.Count; i++) { lineData.Add(jobNum + ";" + inFileList[i] + ";" + outFileList[i] + ";" + outCounter[i]); } } } if (labelCount == 1) { AddMsg("1 label file to make for " + outFile + "."); } else if (labelCount > 1) { AddMsg(labelCount.ToString() + " label files to make for " + outFile + "."); } } Application.DoEvents(); //open boomerang archive (formats) file next openBoomerangArchive(); //open boomerang output (corrections) file last if (inFileList.Count > 1)//for multiple file jobs { foreach (string outFileItem in outFileList) { openBoomerangFile(outFileItem); } } else//for automation jobs { if (jobNum.Contains("3806") || jobNum.Contains("3808") || jobNum.Contains("4941") || jobNum.Contains("4942"))//for duffy's (cards) files { openBoomerangFile(outFileList[0]); } else { openBoomerangFile(outFile); } } inFileList.Clear(); inFileList.TrimExcess(); outFileList.Clear(); outFileList.TrimExcess(); outCounter.Clear(); outCounter.TrimExcess(); } catch (Exception err) { statusStripStatusLabel.Text = "The BAS report " + fileName + " could not be found!"; AddMsg(statusStripStatusLabel.Text); writeToLog("ERROR: " + MethodBase.GetCurrentMethod().Name + ": " + statusStripStatusLabel.Text + "\r\n" + err.ToString(), logFilePathCPS); } } /// /// Get bundleAmt, acctField and description content from Boomerang formats file /// private void openBoomerangArchive() { if (boomerangFormatFile.Count == 0)//format file is not loaded { try { using (FileStream fsFr = new FileStream(formatFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (StreamReader sr1 = new StreamReader(fsFr)) { string s = ""; while ((s = sr1.ReadLine()) != null) { boomerangFormatFile.Add(s); } sr1.Close(); sr1.Dispose(); fsFr.Close(); fsFr.Dispose(); } } catch (Exception ex) { if (ex is ArgumentOutOfRangeException) { statusStripStatusLabel.Text = "The Boomerang format for " + formatFile + " is missing inforamtion, or argument out of range!"; } else if (ex is IndexOutOfRangeException) { statusStripStatusLabel.Text = "The Boomerang format for " + formatFile + " is missing fields and needs to be updated!"; } else { statusStripStatusLabel.Text = "The Boomerang format archive could not be found!"; } AddMsg(statusStripStatusLabel.Text); writeToLog("ERROR: " + MethodBase.GetCurrentMethod().Name + ": " + statusStripStatusLabel.Text + "\r\n" + ex.ToString(), logFilePathCPS); } } foreach (string outFile in outFileList) { string formatPrefix = ""; { foreach (string s in boomerangFormatFile) { if (outFile.StartsWith("a") && s.Contains(outFile.Substring(0, 5)))//check "a" formats for automation jobs { string[] formatLine = s.Split(delims); formatPrefix = formatLine[0]; bundleAmt = Int16.Parse(formatLine[1]); //get bundle amount pinField = Int16.Parse(formatLine[3]); //get pin field nameField = Int16.Parse(formatLine[6]); //get name field if (formatLine[7].Length != 0) { acctField = Int16.Parse(formatLine[7]); //get acct# field } else { acctField = pinField; } //use the description from the format file if (formatLine[5].Length != 0) { descript = formatLine[5]; } else { descript = "EMPTY"; } //sleeves pre carton if (formatLine[9].Length != 0) { slvPerCarton = Int16.Parse(formatLine[9]); } else { slvPerCarton = Int32.Parse(ConfigurationManager.AppSettings["slvPerCarton"]);//setting a default if empty } boomerangList.Add(bundleAmt + ";" + acctField + ";" + descript + ";" + slvPerCarton); } else if (!outFile.StartsWith("a") && s.Contains(outFile.Substring(0, 4)))//check other formats { string[] formatLine = s.Split(delims); formatPrefix = formatLine[0]; bundleAmt = Int16.Parse(formatLine[1]); //get bundle amount pinField = Int16.Parse(formatLine[3]); //get pin field nameField = Int16.Parse(formatLine[6]); //get name field if (formatLine.Length < 7) { acctField = Int16.Parse(formatLine[7]); //get acct# field } else { acctField = pinField; } //use the description from the format file if (formatLine.Length < 5) { descript = "EMPTY"; } else { descript = formatLine[5]; } if (formatLine.Length < 8) { slvPerCarton = Int32.Parse(ConfigurationManager.AppSettings["slvPerCarton"]);//setting a default if missing } else { slvPerCarton = Int16.Parse(formatLine[9]); } //set the special QC count (for QC label every Nth) (2017-07-13, jae) if (!(String.IsNullOrEmpty(formatLine[10])) && Int16.Parse(formatLine[10]) != 0) { specQCCount = Int16.Parse(formatLine[10]); } else { specQCCount = 0; } boomerangList.Add(bundleAmt + ";" + acctField + ";" + descript + ";" + slvPerCarton); } txtBoxSlvPerCarton.Text = slvPerCarton.ToString(); } } } } /// /// Get First/Last content from Boomerang output text file /// Triggers writeSleeveLabels(), then writeCartonLabels() /// /// Name string of the required .txt file from G:\data private void openBoomerangFile(string currFile) { for (int j = 0; j < lineData.Count; j++) { string[] item = lineData[j].Split(';'); if (currFile.Contains(item[2])) { cust = item[0]; kit = item[1]; db = item[2]; totRecs = item[3]; string boomerangFile = ""; string boomTextFile = boomerangFilesPath + "\\" + db + ".txt"; string boomDoneFile = boomerangFilesPath + "\\" + db + ".done"; try { //added to allow reprinting even if the job has been locked out. (09-14-17, jae) if (!File.Exists(boomTextFile)) { statusStripStatusLabel.Text = "The Boomerang database file " + boomTextFile + " doesn't exist!"; AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); statusStripStatusLabel.Text = "Checking for locked-out database file " + boomDoneFile + "."; AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); if (!File.Exists(boomDoneFile)) { statusStripStatusLabel.Text = "Database file " + boomDoneFile + " does not exist either."; AddMsg(statusStripStatusLabel.Text); AddMsg("Continuing..."); writeToLog(statusStripStatusLabel.Text + "\r\nContinuing...", logFilePathCPS); continue; } else { boomerangFile = boomDoneFile; } } else { boomerangFile = boomTextFile; } // using (FileStream fsBf = new FileStream(boomerangFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (StreamReader sr2 = new StreamReader(fsBf)) { int lineCount = 0; string s = ""; string firstAcctNum = ""; string firstName = ""; while ((s = sr2.ReadLine()) != null) { //string acctFieldPreamble = ""; lineCount++; /*if (acctField.ToString().Length > 1) { acctFieldPreamble = "F";//if the bartender field used is higher than 01-09 } else { acctFieldPreamble = "F0"; }*/ //configure misc field for JSM J5830 requirement of pallet# to carton labels int acctIndex = s.IndexOf("L01|"); int nameIndex = s.IndexOf("L02|"); int miscIndex = s.IndexOf("L03|"); int lineLength = s.Length; //string miscString = ""; if (miscIndex < lineLength) { /*if (currFile.Contains("j830") || currFile.Contains("a5830"))//added 2017-09-19, jae { miscString = s.Substring(miscIndex + 4); misc = miscString.Split('|')[0];//add 1 to handle the zero based counting of source fields }*/ } if (isOdd(lineCount)) { firstRec = s.Substring(0, 6).TrimStart('0'); //firstAcctNum = s.Substring(s.IndexOf(acctFieldPreamble + (acctField + 1) + "|") + 4).Split('|')[0];//add 1 to handle the zero based counting of source fields //for the acct num field if (acctIndex < lineLength) { if (currFile.Contains("5469") || currFile.Contains("5749") || currFile.Contains("5751"))//added 2017-09-19, jae { string[] regexSpaces = Regex.Split(s.Substring(s.IndexOf("L01|") + 4).Split('|')[0], @"\s{3,}");//split at 3 or more spaces firstAcctNum = regexSpaces[1]; } else if (currFile.Contains("5830"))//JSM AARP - added 2017-10-04, jae { firstAcctNum = s.Substring(s.IndexOf("L01|") + 4).Split('|')[0] + "|" + s.Substring(s.IndexOf("L01|") + 4).Split('|')[1]; } else { firstAcctNum = s.Substring(s.IndexOf("L01|") + 4).Split('|')[0];//add 1 to handle the zero based counting of source fields } } else { //firstAcctNum = s.Substring(s.IndexOf(acctFieldPreamble + (acctField + 1) + "|") + 4).Split('|')[0];//add 1 to handle the zero based counting of source fields firstAcctNum = ""; } //for the name field if (nameIndex < lineLength) { firstName = s.Substring(s.IndexOf("L02|") + 4).Split('|')[0]; } else { //firstName = s.Substring(s.IndexOf(acctFieldPreamble + (acctField + 1) + "|") + 4).Split('|')[1];//add 1 to handle the zero based counting of source fields firstName = ""; } } else { lastRec = s.Substring(0, 6).TrimStart('0'); string lastAcctNum = ""; if (s.IndexOf("L01|") < s.Length) { if (currFile.Contains("5469") || currFile.Contains("5749") || currFile.Contains("5751"))//added 2017-09-19, jae { string[] regexSpaces = Regex.Split(s.Substring(s.IndexOf("L01|") + 4).Split('|')[0], @"\s{3,}");//split at 3 or more spaces lastAcctNum = regexSpaces[1]; } else if (currFile.Contains("5830"))//JSM AARP - added 2017-10-04, jae { lastAcctNum = s.Substring(s.IndexOf("L01|") + 4).Split('|')[0] + "|" + s.Substring(s.IndexOf("L01|") + 4).Split('|')[1]; } else { lastAcctNum = s.Substring(s.IndexOf("L01|") + 4).Split('|')[0];//add 1 to handle the zero based counting of source fields } } else { //lastAcctNum = s.Substring(s.IndexOf(acctFieldPreamble + (acctField + 1) + "|") + 4).Split('|')[0];//add 1 to handle the zero based counting of source fields lastAcctNum = ""; } string lastName = ""; if (s.IndexOf("L02|") < s.Length) { lastName = s.Substring(s.IndexOf("L02|") + 4).Split('|')[0]; } else { //lastName = s.Substring(s.IndexOf(acctFieldPreamble + (acctField + 1) + "|") + 4).Split('|')[1];//add 1 to handle the zero based counting of source fields lastName = ""; } if (s.IndexOf("L03|") < s.Length) { misc = s.Substring(s.IndexOf("L03|") + 4).Split('|')[0]; } else { misc = ""; } //substring added to trim down for long descriptions (2015-11-12, jae) if (descript.Length > 24) { firstLastList.Add("DESC: " + descript.Substring(0, 24) + ";" + firstAcctNum + ";" + lastAcctNum + ";REC: " + firstRec + " to " + lastRec + ";" + firstName + ";" + lastName); } else { firstLastList.Add("DESC: " + descript + ";" + firstAcctNum + ";" + lastAcctNum + ";REC: " + firstRec + " to " + lastRec + ";" + firstName + ";" + lastName); } } } sr2.Close(); sr2.Dispose(); fsBf.Close(); fsBf.Dispose(); } writeSleeveLabels(db); //sleeve labels power the carton labels writeCartonLabels(db); } catch (Exception ex) { if (ex.InnerException is IndexOutOfRangeException) { statusStripStatusLabel.Text = "The Boomerang database file " + boomerangFile + " could not be opened!"; } AddMsg(statusStripStatusLabel.Text); writeToLog("ERROR: " + MethodBase.GetCurrentMethod().Name + ": " + statusStripStatusLabel.Text + "\r\n" + ex.ToString(), logFilePathCPS); } firstLastList.Clear(); } } } /// /// Check Boomerang cards per sleeve log, to see if job has been run before /// /// Job name string to scan for in the Boomerang sleeve log private void openBoomerangSlvLog(string fileToFind) { labelRunBefore = false; try { using (FileStream fsBs = new FileStream(boomerangSlvLog, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (StreamReader sr3 = new StreamReader(fsBs)) { int lineCount = 0; string s = ""; while ((s = sr3.ReadLine()) != null) { string tempSplit = s.Split(';')[2]; string tempFileToFind = fileToFind.Split('_')[0]; //if (s.Split('.')[0] == fileToFind.Split('_')[0]) if (tempSplit.Contains(tempFileToFind)) { lineCount++; } if (lineCount > 0) { labelRunBefore = true; } } sr3.Close(); sr3.Dispose(); fsBs.Close(); fsBs.Dispose(); } } catch (Exception ex) { if (timerAutoMode.Enabled) { statusStripStatusLabel.Text = "The Boomerang sleeve log file " + boomerangSlvLog + " could not be found!"; AddMsg(statusStripStatusLabel.Text); writeToLog("ERROR: " + MethodBase.GetCurrentMethod().Name + ": " + statusStripStatusLabel.Text + "\r\n" + ex.ToString(), logFilePathCPS); } else { MessageBox.Show("The Boomerang sleeve log file " + boomerangSlvLog + " could not be found!\r\n" + ex.ToString(), "Can't find the Boomerang sleeve log file", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } private void writeToDumpReportListFile() { try { if (!File.Exists(dumpReportListFile) || new FileInfo(dumpReportListFile).Length == 0)//if the report list file is missing or empty { using (StreamWriter sw = new StreamWriter(dumpReportListFile, false)) { //write header sw.WriteLine("FileName;CreateDateTime;ModifiedDateTime;FileSize"); //write existing lines foreach (string writeLine in dumpReportList) { if (chkBoxRebuild.Checked) { sw.WriteLine(writeLine.Split(';')[0] + ";" + writeLine.Split(';')[1] + ";" + writeLine.Split(';')[2] + ";" + writeLine.Split(';')[3]); } else { sw.WriteLine(writeLine.Split(';')[0] + ";" + writeLine.Split(';')[1] + ";" + writeLine.Split(';')[2] + ";0"); } } sw.Close(); sw.Dispose(); } } else { using (StreamWriter sw = new StreamWriter(dumpReportListFile, false)) { //write header sw.WriteLine("FileName;CreateDateTime;ModifiedDateTime;FileSize"); //write existing lines foreach (string writeLine in dumpReportList) { sw.WriteLine(writeLine); } sw.Close(); sw.Dispose(); } } } catch (Exception ex) { if (checkBoxAutoMode.Checked) { statusStripStatusLabel.Text = "The dump report list file " + dumpReportListFile + " could not be found!"; AddMsg(statusStripStatusLabel.Text); writeToLog("ERROR: " + MethodBase.GetCurrentMethod().Name + ": " + statusStripStatusLabel.Text + "\r\n" + ex.ToString(), logFilePathCPS); } else { MessageBox.Show("The dump report list file " + dumpReportListFile + " could not be found!\r\n" + ex.ToString(), "Can't find the Boomerang database file", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } /// /// Writes bartender formatted sleeve file to G:\Apps\PDF_Labels\CPS\prep /// /// File name string to use for output private void writeSleeveLabels(string currentFile) { int sleeve_counter = 1; if (currentFile.Contains("b435") || currentFile.Contains("b850") || currentFile.Contains("b080") || currentFile.Contains("b198"))//for J.Jill custom labels { try { #region J.Jill Labels //string customFormatData = File.ReadAllText(customFormatsPath + "J4435_Config.txt"); string customFormatData = ""; string itemNumber = ""; #region Old JJill filter /* if (currentFile.Contains("b435")) { //customFormatData = File.ReadAllText(customFormatsPath + "J4435_Config.txt"); customFormatData = jJill4435Header; itemNumber = jJill4435Trailer; } else if (currentFile.Contains("b850")) { //customFormatData = File.ReadAllText(customFormatsPath + "J5850_Config.txt"); customFormatData = jJill5850Header; itemNumber = jJill5850Trailer; } else if (currentFile.Contains("b080")) { customFormatData = jJill6080Header; itemNumber = jJill6080Trailer; } */ #endregion //New JJill filter switch (currentFile.Substring(0, 4)) { case "b435": customFormatData = jJill4435Header; itemNumber = jJill4435Trailer; break; case "b850": customFormatData = jJill5850Header; itemNumber = jJill5850Trailer; break; case "b080": customFormatData = jJill6080Header; itemNumber = jJill6080Trailer; break; case "b198": customFormatData = jJill6198Header; itemNumber = jJill6198Trailer; break; } //using (StreamWriter swj = new StreamWriter(commDataPath + @"\JJill\SleeveLabels\" + currentFile + "_SleeveLabel.txt", false)) using (StreamWriter swj = new StreamWriter(prepDataPathCPS + "\\" + currentFile + "_SleeveLabel.txt", false)) { //write header swj.WriteLine("HEADER,FIRSTREC,LASTREC,BUNNUM,SEQRANGE,QUANTITY,CARTON,TRAILER"); for (int j = 0; j < firstLastList.Count; j++) { string[] recInfo = firstLastList[j].Split(';'); swj.Write(customFormatData + ",");//write the HEADER info swj.Write(recInfo[1] + ","); //write the FIRSTREC swj.Write(recInfo[2] + ","); //write the LASTREC swj.Write((j + 1) + " of " + firstLastList.Count.ToString() + ","); //write the BUNNUM swj.Write(recInfo[3] + ","); //write the SEQRANGE totalRecs = Int32.Parse(totRecs); //QUANTITY if (j == (firstLastList.Count - 1))//if the last sleeve { swj.Write(((Int32.Parse(recInfo[3].Split(' ')[3]) - Int32.Parse(recInfo[3].Split(' ')[1])) + 1) + ","); } else { swj.Write((totalRecs / firstLastList.Count) + ","); } if ((j) % slvPerCarton == 0)//change the carton number every sleeve per carton { if (j != 0) { sleeve_counter++; } } swj.Write(sleeve_counter + ",");//write the CARTON number //write the TRAILER info swj.WriteLine("Item# " + itemNumber); } swj.Close(); swj.Dispose(); } #endregion } catch (Exception jjill) { statusStripStatusLabel.Text = "There is a problem with JJill sleeve data."; AddMsg(statusStripStatusLabel.Text); writeToLog("ERROR: " + MethodBase.GetCurrentMethod().Name + ": " + statusStripStatusLabel.Text + " - " + jjill.ToString(), logFilePathCPS); } } else//everything else { try { #region Regular Labels //variables to keep track of the labels to print string[] alphabet = new string[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" }; int alpha_counter = 0; //headerRecordKit added for header card labels (2016-02-12, jae) string headerRecordKit = ""; using (StreamWriter sw = new StreamWriter(prepDataPathCPS + "\\" + currentFile + "_SleeveLabel.txt", false)) { //write header sw.WriteLine("cust;kit;misc;sleeve;box;qty;db;totRecs;slvPerCarton;desc;firstAcct;lastAcct;sleeveRecs;firstName;lastName"); if (!(currentFile.Contains("e566")) || !(currentFile.Contains("e446")))//do not add header card labels for Ford Custom labels { //added 2 label entries for header card labels (2016-02-12, jae) string headRecordKit = ""; string[] tempHeadRecKit; string headRecKitTrim = ""; if (kit.Contains("_")) { tempHeadRecKit = kit.Split('_'); if (currentFile.Contains("j830") || currentFile.Contains("a5830")) { headRecordKit = tempHeadRecKit[1] + "-" + tempHeadRecKit[2]; } else { //headRecordKit = tempHeadRecKit[0] + " " + tempHeadRecKit[1]; //changed for continuity (2016-09-21, jae) headRecordKit = tempHeadRecKit[0] + "_" + tempHeadRecKit[1]; } } else if (kit.Contains(" - ")) { tempHeadRecKit = kit.Substring(0, 32).Split(new String[] { " - " }, StringSplitOptions.None); headRecordKit = tempHeadRecKit[0] + "-" + tempHeadRecKit[1]; } if (headerRecordKit.Length > 28) { headRecKitTrim = headRecordKit.Substring(0, 28); } else { headRecKitTrim = headRecordKit; } sw.WriteLine("CUST/Job#: " + cust + ";" + "KIT : " + headRecKitTrim + ";" + "CCRD: " + alphabet[0] + ";" + ";" + "[+];" + "[+];" + "DB: " + db + ";" + totalRecs + ";" + slvPerCarton + ";" + firstLastList[0].ToString().Split(';')[0] + ";" + "[+][+][+][+][+][+][+];" + "[+][+][+][+][+][+][+];" + "[+];" + "[+][+][+][+][+][+][+];" + "[+][+][+][+][+][+][+];"); sw.WriteLine("CUST/Job#: " + cust + ";" + "KIT : " + headRecKitTrim + ";" + "CCRD: " + alphabet[0] + ";" + ";" + "[+];" + "[+];" + "DB: " + db + ";" + totalRecs + ";" + slvPerCarton + ";" + firstLastList[0].ToString().Split(';')[0] + ";" + "[+][+][+][+][+][+][+];" + "[+][+][+][+][+][+][+];" + "[+];" + "[+][+][+][+][+][+][+];" + "[+][+][+][+][+][+][+];"); } //SPECIAL QC SIGN OFF label for first piece if (specQCCount != 0)//add a special QC signoff label (2017-07-13, jae) { sw.WriteLine(/*cust*/"-------\\ FIRST QC SIGN-OFF REQUIRED //--------;" + /*kit*/";" + /*misc*/"WITNESS INITIALS;" + /*sleeve*/";" + /*box*/";" + /*qty*/";" + /*db*/"TESTER INITIALS;" + /*totalRecs*/";" + /*slvPerCarton*/";" + /*desc*/"DB: " + db + " | BOX: 1A | Piece: 1;" + /*firstAcct*/";" + /*lastAcct*/";" + /*sleeveRecs*/";" + /*firstName*/"______________;" + /*lastName*/"______________;"); } for (int i = 0; i < firstLastList.Count; i++) { string clientJobNum = ""; string[] subKitNo; string subKitTrim = ""; sw.Write("CUST/Job#: " + cust + ";");//customer or job number //substring added to trim down for long kits (2015-11-12, jae) if (kit.Contains(" - "))//for automation jobs { subKitNo = kit.Split(new String[] { " - " }, StringSplitOptions.None); //subKitTrim = subKitNo[0] + " " + subKitNo[1]; subKitTrim = subKitNo[0] + "_" + subKitNo[1];//changed for continuity (2016-09-21, jae) if (subKitTrim.Length > 28) { sw.Write("KIT : " + subKitTrim.Substring(0, 28) + ";");//kit or input file headerRecordKit = subKitTrim.Substring(0, 28); } else { sw.Write("KIT : " + subKitTrim + ";"); headerRecordKit = subKitTrim; } } #region commented out for continuity //commented out for continuity and requirements by our larger customers //as per B. Bench (2016-09-21, jae) /*else if (kit.Contains("_")) { subKitNo = kit.Split('_'); subKitTrim = subKitNo[0] + " " + subKitNo[1]; if (subKitTrim.Length > 32) { sw.Write(subKitTrim.Substring(0, 32) + ";");//kit or input file headerRecordKit = subKitTrim.Substring(0, 32); } else { sw.Write(subKitTrim + ";"); headerRecordKit = subKitTrim; } }*/ #endregion else { if (kit.Length > 28)//was 40 (2017-09-28, jae) { sw.Write("KIT : " + kit.Substring(0, 28) + ";"); headerRecordKit = kit.Substring(0, 28); } else { if (currentFile.Contains("j830") || currentFile.Contains("a5830"))//for JSM/AARP J5830 { //KIT field ie - 02995-2001-CO1F clientJobNum = kit.Split('_')[0]; sw.Write("KIT : " + kit.Split('_')[1] + "-" + kit.Split('_')[2] + ";"); headerRecordKit = kit.Split('_')[1] + "-" + kit.Split('_')[2]; } else { sw.Write("KIT : " + kit + ";"); headerRecordKit = kit; } } } //misc field //removed (2017-10-04, jae) //if (currentFile.Contains("j830") || currentFile.Contains("a5830"))//for JSM/AARP J5830 //{ //sw.Write("JSM# : " + clientJobNum + " | Pallet# : " + misc + ";"); //} //else //{ sw.Write(";"); //} sw.Write("SLV#: " + (i + 1) + " of " + firstLastList.Count + ";");//sleeve number sw.Write("BOX : " + alphabet[alpha_counter] + sleeve_counter + ";");//box (switched from 1A to A1. 2017-09-19, jae) if (i == firstLastList.Count - 1)//for the last sleeve record { if (i == 0)//if only 1 record/sleeve for the job { sw.Write("QTY: " + Int32.Parse(lastRec) + ";"); } else { sw.Write("QTY: " + (Int32.Parse(lastRec) - Int32.Parse(firstRec) + 1) + ";");//if we have a partial sleeve } } else { sw.Write("QTY: " + bundleAmt + ";");//qty per sleeve } sw.Write("DB: " + db + ";");//db or output file totalRecs = Int32.Parse(totRecs); sw.Write(totalRecs + ";");//total records per file/kit sw.Write(slvPerCarton + ";"); sw.WriteLine(firstLastList[i]);//desc - lastName fields if (specQCCount != 0)//add a special QC signoff label (2017-07-13, jae) { string[] tempArray = firstLastList[i].Split(';')[3].Split(' '); firstCardSeqNum = Int16.Parse(tempArray[1]); lastCardSeqNum = Int16.Parse(tempArray[3]); if (specQCCount > firstCardSeqNum) { specQCSlvCount = 1; } else { specQCSlvCount = (int)Math.Floor((double)(firstCardSeqNum / specQCCount)); } //SPECIAL QC SIGN OFF label if (((specQCCount * specQCSlvCount) >= firstCardSeqNum && (specQCCount * specQCSlvCount) <= lastCardSeqNum) || i >= firstLastList.Count) { string piece = firstLastList[i].Split(';')[3].Split(' ')[3]; if (i >= firstLastList.Count)//print Final QC SIGN-OFF Label { sw.Write(/*cust*/"-------\\ FINAL QC SIGN-OFF REQUIRED //--------;"); } else// print a QC Label { sw.Write(/*cust*/"------\\ SPECIAL QC SIGN-OFF REQUIRED //-------;"); } sw.WriteLine(/*kit*/";" + /*misc*/"WITNESS INITIALS;" + /*sleeve*/";" + /*box*/";" + /*qty*/";" + /*db*/"TESTER INITIALS;" + /*totalRecs*/";" + /*slvPerCarton*/";" + /*desc*/"DB: " + db + " | BOX: " + sleeve_counter + alphabet[alpha_counter] + " | Piece: " + piece + ";" + /*firstAcct*/";" + /*lastAcct*/";" + /*sleeveRecs*/";" + /*firstName*/"______________;" + /*lastName*/"______________;"); } } if ((i + 1) % 150 == 0)//change the box letter every 150 sleeve labels { alpha_counter++; //added 2 label entries for header card labels (2016-02-12, jae) //format - cust;kit;misc;sleeve;box;qty;db;totRecs;slvPerCarton;desc;firstAcct;lastAcct;sleeveRecs;firstName;lastName sw.WriteLine("CUST/Job#: " + cust + ";" + "KIT : " + headerRecordKit + ";" + "CCRD: " + alphabet[alpha_counter] + ";" + ";" + "[+];" + "[+];" + db + ";" + totalRecs + ";" + slvPerCarton + ";" + firstLastList[i].ToString().Split(';')[0] + ";" + "[+][+][+][+][+][+][+];" + "[+][+][+][+][+][+][+];" + "[+];" + "[+][+][+][+][+][+][+];" + "[+][+][+][+][+][+][+];"); sw.WriteLine("CUST/Job#: " + cust + ";" + "KIT : " + headerRecordKit + ";" + "CCRD: " + alphabet[alpha_counter] + ";" + ";" + "[+];" + "[+];" + db + ";" + totalRecs + ";" + slvPerCarton + ";" + firstLastList[i].ToString().Split(';')[0] + ";" + "[+][+][+][+][+][+][+];" + "[+][+][+][+][+][+][+];" + "[+];" + "[+][+][+][+][+][+][+];" + "[+][+][+][+][+][+][+];"); sleeve_counter = 1; } else { sleeve_counter++; } } sw.Close(); sw.Dispose(); } #endregion } catch (Exception err) { statusStripStatusLabel.Text = "Stream writer could not write to sleeve label file: " + currentFile + "_SleeveLabel.txt"; AddMsg(statusStripStatusLabel.Text); writeToLog("ERROR: " + MethodBase.GetCurrentMethod().Name + ": " + statusStripStatusLabel.Text + " - " + err.ToString(), logFilePathCPS); } try { #region Ford labels //add a (custom) copy for FORD (J4566) custom labels (& J4446 - added 2017-07-10, jae) if (currentFile.Contains("e566") || currentFile.Contains("e446")) { File.Copy(prepDataPathCPS + "\\" + currentFile + "_SleeveLabel.txt", prepDataPathCPS + "\\" + currentFile + "_SleeveLabel(custom).txt"); } #endregion } catch (Exception ford) { statusStripStatusLabel.Text = "There is a problem with Ford sleeve data."; AddMsg(statusStripStatusLabel.Text); writeToLog("ERROR: " + MethodBase.GetCurrentMethod().Name + ": " + statusStripStatusLabel.Text + " - " + ford.ToString(), logFilePathCPS); } } } /// /// Writes bartender formatted carton file to G:\Apps\PDF_Labels\CPS\prep /// This uses the sleeve lable file to complete its build /// /// File name string to use for output private void writeCartonLabels(string currentFile) { cartonLineData.Clear(); //open sleevelabel file string sleeveLabelFile = prepDataPathCPS + "\\" + currentFile + "_SleeveLabel.txt"; int totalLines = 0; int lineCount = 0; if (firstLastList.Count == 0)//if this is a reprint/update { using (FileStream fsFLL = new FileStream(sleeveLabelFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (StreamReader sr5 = new StreamReader(fsFLL)) { string t = ""; string placeHolder = "0000;"; while ((t = sr5.ReadLine()) != null) { if (t.Contains("[+]") == false)//ignore header card labels { if (lineCount > 0) { firstLastList.Add(placeHolder); } lineCount++; } } lineCount = 0; sr5.Close(); sr5.Dispose(); fsFLL.Close(); fsFLL.Dispose(); } } if (currentFile.Contains("b435") || currentFile.Contains("b850") || currentFile.Contains("b080") || currentFile.Contains("b198"))//for J.Jill custom labels { try { #region J.Jill Labels string jJillBuff = ""; List listJJill = new List(); string customFormatData = ""; string itemNumber = ""; #region Old Jjill filter /* if (currentFile.Contains("b435")) { //customFormatData = File.ReadAllText(customFormatsPath + "J4435_Config.txt"); customFormatData = jJill4435Header; itemNumber = jJill4435Trailer; } else if (currentFile.Contains("b850")) { //customFormatData = File.ReadAllText(customFormatsPath + "J5850_Config.txt"); customFormatData = jJill5850Header; itemNumber = jJill5850Trailer; } else if (currentFile.Contains("b080")) { customFormatData = jJill6080Header; itemNumber = jJill6080Trailer; } */ #endregion //New JJill filter switch (currentFile.Substring(0, 4)) { case "b435": customFormatData = jJill4435Header; itemNumber = jJill4435Trailer; break; case "b850": customFormatData = jJill5850Header; itemNumber = jJill5850Trailer; break; case "b080": customFormatData = jJill6080Header; itemNumber = jJill6080Trailer; break; case "b198": customFormatData = jJill6198Header; itemNumber = jJill6198Trailer; break; } //using (StreamWriter swj = new StreamWriter(commDataPath + @"\JJill\CartonLabels\" + currentFile + "_CartonLabel.txt", false)) using (StreamWriter swj = new StreamWriter(prepDataPathCPS + "\\" + currentFile + "_CartonLabel.txt", false)) { //write header swj.WriteLine("HEADER,FIRSTREC,LASTREC,BUNNUM,SEQRANGE,QUANTITY,CARTON,TRAILER"); int cardsPerSleeve = 0; int cartonTotalRecs = 0; totalRecs = Int32.Parse(totRecs); int writeLineCount = 0; for (int j = 0; j < firstLastList.Count; j++) { string[] recInfo; //int nextCardRecord = (Int16.Parse(recInfo[3].Split(' ')[1])); int bunCount = 0; jJillBuff = ""; jJillBuff = customFormatData + ","; if (j == 0)//for first carton, or a single carton only { recInfo = firstLastList[j].Split(';'); cardsPerSleeve = Int16.Parse(recInfo[3].Split(' ')[3]); cartonTotalRecs = cardsPerSleeve * slvPerCarton; #region commented code 1 //swj.Write(customFormatData + ",");//write the HEADER info //swj.Write((j + 1) + "AW,"); //write the FIRSTREC //jJillBuff += recInfo[3].Split(' ')[1] + "AW" + ","; //swj.Write(slvPerCarton + "AW,"); //write the LASTREC //jJillBuff += slvPerCarton + "AW" + ","; //swj.Write((j + 1) + " of " + Math.Ceiling((double)firstLastList.Count / slvPerCarton) + ","); //write the BUNNUM //jJillBuff += (j + 1) + " of " + Math.Ceiling((double)firstLastList.Count / slvPerCarton) + ","; //swj.Write((j + 1) + " to " + cartonTotalRecs.ToString() + ","); //write the SEQRANGE //jJillBuff += (j + 1) + " to " + cartonTotalRecs.ToString() + ","; //totalRecs = Int32.Parse(totRecs); //swj.Write(cartonTotalRecs + ",");//QUANTITY //jJillBuff += cartonTotalRecs + ","; //swj.Write((j + 1) + "W,");//write the CARTON number //jJillBuff += (j + 1) + "W" + ","; //write the TRAILER info //swj.WriteLine("Item# " + itemNumber); //jJillBuff += "Item# " + itemNumber; //write the built output line //swj.WriteLine(jJillBuff); #endregion bunCount = Convert.ToInt32(Math.Ceiling((double)firstLastList.Count / slvPerCarton)); jJillBuff += (writeLineCount + 1) + "AW" + ",";//first rec jJillBuff += slvPerCarton + "AW" + ",";//last rec jJillBuff += "1 of " + bunCount + ",";//bundle jJillBuff += "1 to " + cartonTotalRecs.ToString() + ",";//seq range jJillBuff += cartonTotalRecs.ToString() + ",";//qty jJillBuff += (writeLineCount + 1) + "W" + ",";//carton jJillBuff += "Item# " + itemNumber;//trailer swj.WriteLine(jJillBuff); writeLineCount++; } else { recInfo = firstLastList[j - 1].Split(';'); bunCount = Convert.ToInt32(Math.Ceiling((double)firstLastList.Count / slvPerCarton)); int awCount = ((slvPerCarton * writeLineCount) + 1); jJillBuff += awCount + "AW" + ",";//first rec if ((j % slvPerCarton) == 0)//last sleeve rec before the next carton { jJillBuff += ((awCount + slvPerCarton) - 1) + "AW" + ",";//last rec jJillBuff += (writeLineCount + 1) + " of " + bunCount + ",";//bundle jJillBuff += ((writeLineCount * cartonTotalRecs) + 1) + " to " + ((writeLineCount * cartonTotalRecs) + cartonTotalRecs) + ",";//seq range } else if (j == (writeLineCount + 1))//for the last carton, accurately handling partials { jJillBuff += ((awCount + slvPerCarton) - 1) + "AW" + ",";//last rec jJillBuff += (writeLineCount + 1) + " of " + bunCount + ",";//bundle jJillBuff += ((writeLineCount * cartonTotalRecs) + 1) + " to " + ((writeLineCount * cartonTotalRecs) + cartonTotalRecs) + ",";//seq range } jJillBuff += cartonTotalRecs.ToString() + ",";//qty jJillBuff += (writeLineCount + 1) + "W" + ",";//carton jJillBuff += "Item# " + itemNumber;//trailer swj.WriteLine(jJillBuff); writeLineCount++; } } swj.Close(); swj.Dispose(); } #endregion } catch (Exception jjill) { statusStripStatusLabel.Text = "There is a problem with JJill carton data."; AddMsg(statusStripStatusLabel.Text); writeToLog("ERROR: " + MethodBase.GetCurrentMethod().Name + ": " + statusStripStatusLabel.Text + " - " + jjill.ToString(), logFilePathCPS); } } else //everything else { if (!File.Exists(sleeveLabelFile)) { statusStripStatusLabel.Text = "The sleeve label file " + sleeveLabelFile + " does not exist!"; AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); } else { try { #region Regular Labels using (FileStream fsLf = new FileStream(sleeveLabelFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (StreamReader sr3 = new StreamReader(fsLf)) { string s = ""; string desc = ""; //string cardType = "";//commented out cardtype (2016-06-02, jae) string job = ""; string purchaseOrder = ""; string file = ""; string kit = ""; string misc = ""; string sleeveRange = ""; string seqRange = ""; string firstRec = ""; string firstName = ""; string firstSleeve = ""; string lastRec = ""; string lastName = ""; string lastSleeve = ""; string carton = ""; int qty = 0; int firstSleeveQty = 0; int lastSleeveQty = 0; int lastCarton = 0; int qtyPerCarton = bundleAmt * slvPerCarton; int nextSleeve = 0; //int headerLabelCount = 0; //prep/trim customer name while ((s = sr3.ReadLine()) != null) { //ignore header card labels AND Special QC labels if (s.Contains("[+]") || s.Contains("SPECIAL QC")) { // wtf?? } else { if (lineCount > 0)//skip the first three rows, for the file header and header card labels { //if (s.Contains("[+]") == false)//ignore header card labels //{ string[] lineItems = s.Split(';'); if (qtyPerCarton == 0)//if a reprint job and no bundleAmt is found { bundleAmt = Int16.Parse(lineItems[5].Split(' ')[1]); slvPerCarton = Int16.Parse(lineItems[8]); totalRecs = Int16.Parse(lineItems[7]); qtyPerCarton = bundleAmt * slvPerCarton; } totalLines = (int)Math.Ceiling((double)totalRecs / (double)qtyPerCarton); desc = lineItems[9].Replace("DESC: ", "Description: "); //commented out cardtype (2016-06-02, jae) /*if (currentFile.ToLower().StartsWith("a")) { cardType = "Job#" + lineItems[1].Substring(0, lineItems[1].Length - 3); } else { if (lineItems[1].Length < 15) { cardType = "Job#" + lineItems[1]; } else { cardType = "Job#" + lineItems[1].Substring(0, 15); } }*/ job = lineItems[0].Replace("CUST/Job#: ", "Job#: "); file = lineItems[6]; if (!string.IsNullOrEmpty(poNumber)) { purchaseOrder = "PO #: " + poNumber; } if (lineItems[1].Length > 46) { kit = lineItems[1].Substring(0, 40); } else { kit = lineItems[1]; } if (lineCount == 0 || lineCount == nextSleeve) { firstRec = "First Acct: " + lineItems[10]; firstName = "First Rec : " + lineItems[13]; if (lineCount == 0) { if (lineCount == firstLastList.Count)//for sample files or files with only one record { sleeveRange = "A1 to A1"; if (string.IsNullOrEmpty(lineItems[10]))//is first acct field blank? { firstRec = ""; } else { firstRec = "First Acct: " + lineItems[10]; } if (string.IsNullOrEmpty(lineItems[11]))//is last acct field blank? { lastRec = ""; } else { lastRec = "Last Acct : " + lineItems[11]; } firstSleeveQty = lastSleeveQty + 1; string qtySplit = lineItems[12].Substring(lineItems[12].LastIndexOf(" ") + 1); lastSleeveQty = Int32.Parse(qtySplit); if (string.IsNullOrEmpty(lineItems[13]))//is first name field blank? { firstName = ""; } else { firstName = "First Rec : " + lineItems[13]; } if (string.IsNullOrEmpty(lineItems[14]))//is last name field blank? { lastName = ""; } else { lastName = "Last Rec : " + lineItems[14]; } seqRange = firstSleeveQty + " to " + lastSleeveQty; carton = "1 of 1"; qty = (lastSleeveQty - firstSleeveQty) + 1; cartonLineData.Add("Customer: " + customer + ";" + desc + ";" + /*cardType*/purchaseOrder + ";" + job + ";" + file + ";" + kit + ";" + misc + ";" + sleeveRange + ";" + seqRange + ";" + firstRec + ";" + lastRec + ";" + carton + ";" + qty + ";" + totRecs + ";" + slvPerCarton + ";" + firstName + ";" + lastName); } else { firstSleeve = lineItems[4].Replace("BOX : ", ""); firstSleeveQty = Int32.Parse(lineItems[12].Split(' ')[1]); } } else if (lineCount == firstLastList.Count)//for last record if its the first record after a new carton { sleeveRange = lineItems[4].Replace("BOX : ", "") + " to " + lineItems[4].Replace("BOX : ", ""); if (string.IsNullOrEmpty(lineItems[10]))//is first acct field blank? { firstRec = ""; } else { firstRec = "First Acct: " + lineItems[10]; } if (string.IsNullOrEmpty(lineItems[11]))//is last acct field blank? { lastRec = ""; } else { lastRec = "Last Acct : " + lineItems[11]; } firstSleeveQty = lastSleeveQty + 1; string qtySplit = lineItems[12].Substring(lineItems[12].LastIndexOf(" ") + 1); lastSleeveQty = Int32.Parse(qtySplit); if (string.IsNullOrEmpty(lineItems[13]))//is first name field blank? { firstName = ""; } else { firstName = "First Rec : " + lineItems[13]; } if (string.IsNullOrEmpty(lineItems[14]))//is last name field blank? { lastName = ""; } else { lastName = "Last Rec : " + lineItems[14]; } seqRange = firstSleeveQty + " to " + lastSleeveQty; carton = lastCarton + " of " + totalLines; qty = (lastSleeveQty - firstSleeveQty) + 1; cartonLineData.Add("Customer: " + customer + ";" + desc + ";" + /*cardType*/purchaseOrder + ";" + job + ";" + file + ";" + kit + ";" + misc + ";" + sleeveRange + ";" + seqRange + ";" + firstRec + ";" + lastRec + ";" + carton + ";" + qty + ";" + totRecs + ";" + slvPerCarton + ";" + firstName + ";" + lastName); } else { firstSleeve = lineItems[4].Replace("BOX : ", ""); firstSleeveQty = (Int32.Parse(lineItems[12].Split(' ')[1])); } } else if (lineCount == 1) { if (lineCount == firstLastList.Count)//for sample files or files with only one record { sleeveRange = "A1 to A1"; if (string.IsNullOrEmpty(lineItems[10]))//is first acct field blank? { firstRec = ""; } else { firstRec = "First Acct: " + lineItems[10]; } if (string.IsNullOrEmpty(lineItems[11]))//is last acct field blank? { lastRec = ""; } else { lastRec = "Last Acct : " + lineItems[11]; } firstSleeveQty = lastSleeveQty + 1; string qtySplit = lineItems[12].Substring(lineItems[12].LastIndexOf(" ") + 1); lastSleeveQty = Int32.Parse(qtySplit); if (string.IsNullOrEmpty(lineItems[13]))//is first name field blank? { firstName = ""; } else { firstName = "First Rec : " + lineItems[13]; } if (string.IsNullOrEmpty(lineItems[14]))//is last name field blank? { lastName = ""; } else { lastName = "Last Rec : " + lineItems[14]; } seqRange = firstSleeveQty + " to " + lastSleeveQty; carton = "1 of 1"; qty = (lastSleeveQty - firstSleeveQty) + 1; cartonLineData.Add("Customer: " + customer + ";" + desc + ";" + /*cardType*/purchaseOrder + ";" + job + ";" + file + ";" + kit + ";" + misc + ";" + sleeveRange + ";" + seqRange + ";" + firstRec + ";" + lastRec + ";" + carton + ";" + qty + ";" + totRecs + ";" + slvPerCarton + ";" + firstName + ";" + lastName); } else { firstSleeve = "A1"; firstRec = "First Acct: " + lineItems[10]; firstName = "First Rec : " + lineItems[13]; } } else if (lineCount % slvPerCarton == 0)//every X { nextSleeve = lineCount + 1; lastSleeve = lineItems[4].Replace("BOX : ", ""); /*if (string.IsNullOrEmpty(lineItems[10]))//is first acct field blank? { firstRec = ""; } else { firstRec = "First Acct: " + lineItems[10]; }*/ if (string.IsNullOrEmpty(lineItems[11]))//is last acct field blank? { lastRec = ""; } else { lastRec = "Last Acct : " + lineItems[11]; } firstSleeveQty = lastSleeveQty + 1; string qtySplit = lineItems[12].Substring(lineItems[12].LastIndexOf(" ") + 1); lastSleeveQty = Int32.Parse(qtySplit); if (string.IsNullOrEmpty(lineItems[13]))//is first name field blank? { firstName = ""; } /*else { firstName = "First Rec : " + lineItems[13]; }*/ if (string.IsNullOrEmpty(lineItems[14]))//is last name field blank? { lastName = ""; } else { lastName = "Last Rec : " + lineItems[14]; } lastCarton = (int)Math.Ceiling(Double.Parse(lineItems[7]) / (Double.Parse(lineItems[5].Split(' ')[1]) * slvPerCarton)); if (String.IsNullOrEmpty(firstSleeve)) { firstSleeve = "A1"; } sleeveRange = firstSleeve + " to " + lastSleeve; seqRange = firstSleeveQty + " to " + lastSleeveQty; carton = (lineCount / slvPerCarton) + " of " + totalLines; qty = (lastSleeveQty - firstSleeveQty) + 1; cartonLineData.Add("Customer: " + customer + ";" + desc + ";" + /*cardType*/purchaseOrder + ";" + job + ";" + file + ";" + kit + ";" + misc + ";" + sleeveRange + ";" + seqRange + ";" + firstRec + ";" + lastRec + ";" + carton + ";" + qty + ";" + totRecs + ";" + slvPerCarton + ";" + firstName + ";" + lastName); } else if (lineCount == firstLastList.Count)//for the last line item if a partial { lastSleeve = lineItems[4].Replace("BOX : ", ""); if (String.IsNullOrEmpty(firstSleeve)) { firstSleeve = lastSleeve; } sleeveRange = firstSleeve + " to " + lastSleeve; if (string.IsNullOrEmpty(firstRec))//is first acct field blank? { firstRec = ""; } //else //{ // firstRec = "First Acct: " + lineItems[10]; //} if (string.IsNullOrEmpty(lineItems[11]))//is last acct field blank? { lastRec = ""; } else { lastRec = "Last Acct : " + lineItems[11]; } firstSleeveQty = lastSleeveQty + 1; string qtySplit = lineItems[12].Substring(lineItems[12].LastIndexOf(" ") + 1); lastSleeveQty = Int32.Parse(qtySplit); if (string.IsNullOrEmpty(firstName))//is first name field blank? { firstName = ""; } //else //{ // firstName = "First Rec : " + lineItems[13]; //} if (string.IsNullOrEmpty(lineItems[14]))//is last name field blank? { lastName = ""; } else { lastName = "Last Rec : " + lineItems[14]; } seqRange = firstSleeveQty + " to " + lastSleeveQty; if (totalLines == 1) { carton = "1 of 1"; } else { carton = lastCarton + " of " + totalLines; } qty = (lastSleeveQty - firstSleeveQty) + 1; cartonLineData.Add("Customer: " + customer + ";" + desc + ";" + /*cardType*/purchaseOrder + ";" + job + ";" + file + ";" + kit + ";" + misc + ";" + sleeveRange + ";" + seqRange + ";" + firstRec + ";" + lastRec + ";" + carton + ";" + qty + ";" + totRecs + ";" + slvPerCarton + ";" + firstName + ";" + lastName); } //} //else //trim the label count if a header card label //{ //lineCount--; //} } lineCount++; } } sr3.Close(); sr3.Dispose(); fsLf.Close(); fsLf.Dispose(); } #endregion } catch (Exception ex) { statusStripStatusLabel.Text = "Stream reader could not read from carton label file: " + sleeveLabelFile; AddMsg(statusStripStatusLabel.Text); writeToLog("ERROR: " + MethodBase.GetCurrentMethod().Name + ": " + statusStripStatusLabel.Text + " - " + ex.ToString(), logFilePathCPS); } try { using (StreamWriter sw1 = new StreamWriter(prepDataPathCPS + "\\" + currentFile + "_CartonLabel.txt", false)) { //write header sw1.WriteLine("cust;desc;purchaseOrder;job;file;kit;misc;sleeveRange;seqRange;firstRec;lastRec;carton;qty;totRecs;slvPerCarton;firstName;lastName"); for (int i = 0; i < totalLines; i++) { sw1.WriteLine(cartonLineData[i]); } sw1.Close(); sw1.Dispose(); } } catch (Exception ev) { statusStripStatusLabel.Text = "Stream writer could not write to carton label file: " + currentFile + "_CartonLabel.txt"; AddMsg(statusStripStatusLabel.Text); writeToLog("ERROR: " + MethodBase.GetCurrentMethod().Name + ": " + statusStripStatusLabel.Text + " - " + ev.ToString(), logFilePathCPS); } } cartonLineData.Clear(); } } /// /// Writes information to the job log file /// /// String info to write /// Path to the job log file private void writeToLog(string information, string path) { logFile = path + "\\" + DateTime.Today.ToString("yyyyMMdd") + "_logfile.txt"; try { using (StreamWriter w = File.AppendText(logFile)) { w.WriteLine(" {0}: {1}", DateTime.Now, information); w.Close(); w.Dispose(); } } catch { statusStripStatusLabel.Text = "Unable to write to " + path + "! Please check log file..."; AddMsg(statusStripStatusLabel.Text); } } #endregion #region Maintenance Operations //Cleanup the BarTender/Commander data folders, removing all files older than X months private void commanderFolderMaintenance() { string[] appSettings = ConfigurationManager.AppSettings.AllKeys; List folderList = new List(); foreach (string key in appSettings) { if (key.ToLower().Contains("pathcommander")) { if (key.ToLower().Contains("cps")) { folderList.Add(ConfigurationManager.AppSettings[key] + "\\SleeveLabels"); folderList.Add(ConfigurationManager.AppSettings[key] + "\\CartonLabels"); } else { folderList.Add(ConfigurationManager.AppSettings[key]); } } } try { statusStripStatusLabel.Text = "Commander folders cleanup started."; AddMsg(statusStripStatusLabel.Text); foreach (string folder in folderList) { string[] files = Directory.GetFiles(folder); foreach (string file in files) { FileInfo fi = new FileInfo(file); if (File.GetLastWriteTime(fi.FullName) < DateTime.Now.AddMonths(longDate)) { statusStripStatusLabel.Text = "Stale file " + fi.Name + " removed from the CPS Commander folder."; AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); fi.Delete(); } } } statusStripStatusLabel.Text = "Commander folders cleanup complete."; AddMsg(statusStripStatusLabel.Text); } catch { statusStripStatusLabel.Text = "Commander folders cleanup could not be performed."; AddMsg(statusStripStatusLabel.Text); writeToLog("ERROR: " + MethodBase.GetCurrentMethod().Name + ": " + statusStripStatusLabel.Text, logFilePathCPS); } } //Cleanup the CPS data folder, removing all files older than X months private void dataFolderMaintenance() { string[] appSettings = ConfigurationManager.AppSettings.AllKeys; List folderList = new List(); foreach (string key in appSettings) { if (key.ToLower().Contains("cpsdatapath")) { folderList.Add(ConfigurationManager.AppSettings[key]); } } try { statusStripStatusLabel.Text = "CPS data folder cleanup started."; AddMsg(statusStripStatusLabel.Text); foreach (string folder in folderList) { string[] files = Directory.GetFiles(folder); foreach (string file in files) { FileInfo fi = new FileInfo(file); if (File.GetLastWriteTime(fi.FullName) < DateTime.Now.AddMonths(longDate)) { statusStripStatusLabel.Text = "Stale file " + fi.Name + " removed from the CPS data folder."; AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); fi.Delete(); } } } statusStripStatusLabel.Text = "CPS data folder cleanup complete."; AddMsg(statusStripStatusLabel.Text); } catch { statusStripStatusLabel.Text = "CPS data folder cleanup could not be performed."; AddMsg(statusStripStatusLabel.Text); writeToLog("ERROR: " + MethodBase.GetCurrentMethod().Name + ": " + statusStripStatusLabel.Text, logFilePathCPS); } } //Cleanup the label folders, removing PDF files older than X month(s) private void labelFolderMaintenance() { string[] folders = Directory.GetDirectories(labelPathCPS); string folderName = ""; try { statusStripStatusLabel.Text = "Label folder cleanup started."; AddMsg(statusStripStatusLabel.Text); foreach (string folder in folders) { if (folder.EndsWith("Labels")) { folderName = folder; string[] files = Directory.GetFiles(folder); foreach (string file in files) { FileInfo fi = new FileInfo(file); if ((File.GetLastWriteTime(fi.FullName) < DateTime.Now.AddMonths(shortDate)) && (!fi.Name.Contains("Empty"))) { statusStripStatusLabel.Text = "Stale file " + fi.Name + " removed from the PDF_Labels folder."; AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); fi.Delete(); } } statusStripStatusLabel.Text = folder + " folder cleanup complete."; AddMsg(statusStripStatusLabel.Text); } } } catch { statusStripStatusLabel.Text = folderName + " folder cleanup could not be performed."; AddMsg(statusStripStatusLabel.Text); writeToLog("ERROR: " + MethodBase.GetCurrentMethod().Name + ": " + statusStripStatusLabel.Text, logFilePathCPS); } } //Cleanup the joblog folders, removing all files older than X months private void logFolderMaintenance() { string[] appSettings = ConfigurationManager.AppSettings.AllKeys; List folderList = new List(); foreach (string key in appSettings) { if (key.ToLower().Contains("logfilepath")) { folderList.Add(ConfigurationManager.AppSettings[key]); } } try { statusStripStatusLabel.Text = "Joblog folder cleanup started."; AddMsg(statusStripStatusLabel.Text); //cleanup vendor folders foreach (string folder in folderList) { string[] files = Directory.GetFiles(folder); foreach (string file in files) { FileInfo fi = new FileInfo(file); if (File.GetLastWriteTime(fi.FullName) < DateTime.Now.AddMonths(longDate)) { statusStripStatusLabel.Text = "Stale file " + fi.Name + @" removed from the LabelMonitor job log folders."; AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePath); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); fi.Delete(); } } } //cleanup main folder string[] parentFiles = Directory.GetFiles(logFilePath); foreach (string pfile in parentFiles) { FileInfo pfi = new FileInfo(pfile); if (File.GetLastWriteTime(pfi.FullName) < DateTime.Now.AddMonths(longDate)) { statusStripStatusLabel.Text = "Stale file " + pfi.Name + @" removed from the Gemalto\LabelMonitor job log folder."; AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePath); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); pfi.Delete(); } } statusStripStatusLabel.Text = "Joblog folder cleanup complete."; AddMsg(statusStripStatusLabel.Text); } catch { statusStripStatusLabel.Text = "Joblog folder cleanup could not be performed."; AddMsg(statusStripStatusLabel.Text); writeToLog("ERROR: " + MethodBase.GetCurrentMethod().Name + ": " + statusStripStatusLabel.Text, logFilePathCPS); } } #endregion // Check to see if the print spool directory is empty, or spool job(s) are 0 //private void boomerangQueueCheck() private void boomerangQueueCheck(object sender, EventArgs e) { if (((autoTime.Hour == DateTime.Now.Hour) && (autoTime.Minute == DateTime.Now.Minute) && (autoTime.Second == DateTime.Now.Second))) //We've waited X minutes for the boomerang folder/queue to empty { string[] queueFiles = Directory.GetFiles(boomerangFilesPath + @"\boomerang", "*.*"); long total = 0; foreach (string name in queueFiles) { FileInfo info = new FileInfo(name); total += info.Length; } if (total == 0) { if (checkBoxAutoMode.Checked) { runToolStripMenuItem.Enabled = false; exitToolStripMenuItem.Enabled = true; autoModeToolStripMenuItem.Enabled = true; cleanAfterBuildingToolStripMenuItem.Enabled = false; lookForPalletLabelsToolStripMenuItem.Enabled = false; lookForSleeveCartonLabelsToolStripMenuItem.Enabled = false; checkBoxAutoMode.Enabled = true; checkBoxCleanAfterBuilding.Enabled = false; checkBoxCPSLabels.Enabled = false; checkBoxPalletLabels.Enabled = false; checkBoxReprint.Enabled = false; txtBoxSlvPerCarton.Enabled = false; buttonRun.Enabled = false; buttonExit.Enabled = true; } else { runToolStripMenuItem.Enabled = true; exitToolStripMenuItem.Enabled = true; autoModeToolStripMenuItem.Enabled = true; cleanAfterBuildingToolStripMenuItem.Enabled = true; lookForPalletLabelsToolStripMenuItem.Enabled = true; lookForSleeveCartonLabelsToolStripMenuItem.Enabled = true; checkBoxAutoMode.Enabled = true; checkBoxCleanAfterBuilding.Enabled = true; checkBoxCPSLabels.Enabled = true; checkBoxPalletLabels.Enabled = true; checkBoxReprint.Enabled = true; txtBoxSlvPerCarton.Enabled = true; buttonRun.Enabled = true; buttonExit.Enabled = true; } statusStripStatusLabel.Text = "The Boomerang queue is empty. Continuing..."; AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); Application.DoEvents(); queueTimer.Stop(); timerQueue.Stop(); //if (checkBoxAutoMode.Checked) //{ // timerAutoMode.Start(); // labelAutoTime.Visible = true; // autoTime = DateTime.Now.AddSeconds(30D);//30 sec run delay after boomerang folder is empty // labelAutoTime.Text = "LabelMonitor will process, at " + autoTime.ToString("hh:mm:ss") + Environment.NewLine + // "Currently " + DateTime.Now.ToString("hh:mm:ss"); //} //else //{ runningCode(); //} } else if (total > 0) { timerAutoMode.Enabled = false; labelAutoTime.Visible = false; runToolStripMenuItem.Enabled = false; exitToolStripMenuItem.Enabled = false; autoModeToolStripMenuItem.Enabled = false; cleanAfterBuildingToolStripMenuItem.Enabled = false; lookForPalletLabelsToolStripMenuItem.Enabled = false; lookForSleeveCartonLabelsToolStripMenuItem.Enabled = false; checkBoxAutoMode.Enabled = false; checkBoxCleanAfterBuilding.Enabled = false; checkBoxCPSLabels.Enabled = false; checkBoxPalletLabels.Enabled = false; checkBoxReprint.Enabled = false; txtBoxSlvPerCarton.Enabled = false; buttonRun.Enabled = false; buttonExit.Enabled = false; if (checkBoxAutoMode.Checked) { statusStripStatusLabel.Text = "Waiting two minutes. Boomerang is still busy..."; queueTimer.Interval = 120000; // wait 120 seconds //timerQueue.Interval = 120000; // wait 120 seconds autoTime = DateTime.Now.AddSeconds(120D);//120 sec run delay waiting for boomerang folder to empty } else { statusStripStatusLabel.Text = "Wait a minute. Boomerang is still busy..."; queueTimer.Interval = 60000; // wait 60 seconds //timerQueue.Interval = 60000; // wait 60 seconds autoTime = DateTime.Now.AddSeconds(60D);//36 sec run delay waiting for boomerang folder to empty } AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); labelAutoTime.Visible = true; timerQueue.Start(); labelAutoTime.Text = "Checking the boomerang queue at " + autoTime.ToString("hh:mm:ss") + Environment.NewLine + "Currently " + DateTime.Now.ToString("hh:mm:ss"); } } else { timerQueue.Start(); labelAutoTime.Text = "Rechecking the boomerang queue at " + autoTime.ToString("hh:mm:ss") + Environment.NewLine + "Currently " + DateTime.Now.ToString("hh:mm:ss"); } } #region Timers, Ticks and Holds private void boomerangQueueTimer(int delay) { if (timerAutoMode.Enabled) { timerAutoMode.Stop(); } if (timerAutoMode.Enabled == false) { statusStripStatusLabel.Text = "Checking if the Boomerang queue is empty..."; AddMsg(statusStripStatusLabel.Text); queueTimer.Tick += new EventHandler(boomerangQueueCheck); if (delay == 0)//automode has no delay { queueTimer.Interval = 1000; queueTimer.Start(); } else { queueTimer.Interval = delay * 1000; //check the print spool every X seconds queueTimer.Start(); } } } private void timerQueue_Tick(object sender, EventArgs e) { //checkBoxAutoMode.Enabled = false; //boomerangQueueCheck(); /*if (timerAutoMode.Enabled == false) { if (((autoTime.Hour == DateTime.Now.Hour) && (autoTime.Minute == DateTime.Now.Minute) && (autoTime.Second == DateTime.Now.Second))) //We've waited X minutes for the boomerang folder/queue to empty { runningCode(); } else { labelAutoTime.Text = "Rechecking the boomerang queue at " + autoTime.ToString("hh:mm:ss") + "; Currently " + DateTime.Now.ToString("hh:mm:ss"); } }*/ boomerangQueueCheck(sender, e); } private void timerDoPDF_Tick(object sender, EventArgs e) { //When this timer's interval is up, here is what we do... //We are processing... have the program autosend the file info to DoPDF if (!found) { look++; statusStripStatusLabel.Text = "Looking for DoPDF window, attempt #" + look; Application.DoEvents(); if (look > 90) { //Tried to pull up DoPDF window and couldn't find anything. //Tell the user through the status bar and exit Automation Mode statusStripStatusLabel.Text = "DoPDF window not found. Aborting auto mode."; AddMsg(statusStripStatusLabel.Text); timerDoPDF.Enabled = false; } else { main.Window = main.Find("#32770", "doPDF - Save PDF file"); if (main.Window == invalidHandle) { //window does not exist statusStripStatusLabel.Text = "DoPDF window not found yet..."; Application.DoEvents(); } else { textBox.Window = textBox.Find(main.Window, IntPtr.Zero, "Edit", null); if (textBox.Window == invalidHandle) { statusStripStatusLabel.Text = "Text window not found yet..."; Application.DoEvents(); } else { statusStripStatusLabel.Text = "DoPDF window found, entering info."; found = true; timerDoPDF.Enabled = false; textBox.SetEditText(chunkFile); okButton.Window = okButton.Find(main.Window, IntPtr.Zero, "Button", "OK"); if (okButton.Window == invalidHandle) { //unable to hook onto OK button statusStripStatusLabel.Text = "Couldn't find OK button!"; Application.DoEvents(); } else { statusStripStatusLabel.Text = "Found OK button."; okButton.ClickButton(); } } overWrite.Window = overWrite.Find("#2300", "BarTender: Information Message"); if (overWrite.Window == invalidHandle) { statusStripStatusLabel.Text = "Overwrite window not found yet..."; Application.DoEvents(); } else { statusStripStatusLabel.Text = "Overwrite window found."; yesButton.Window = yesButton.Find(overWrite.Window, IntPtr.Zero, "Button", "Yes"); if (yesButton.Window == invalidHandle) { //unable to hook onto OK button statusStripStatusLabel.Text = "Couldn't find Yes button!"; Application.DoEvents(); } else { statusStripStatusLabel.Text = "Found Yes button."; yesButton.ClickButton(); } } } } } } private void timerAutoMode_Tick(object sender, EventArgs e) { startAutoProcessing(sender, e); } /// /// A function which is called when the computer is in auto mode and a chunk was successfully created. /// The function is explicitly called to slow down processing and wait for the DoPDF window, without /// causing everything to stop (we are not using the sleep command). /// private void holdOn() { while (timerDoPDF.Enabled == true) { Application.DoEvents(); } if (statusStripStatusLabel.Text == "DoPDF window not found. Aborting auto mode...") { //DoPDF caused a problem or was not executable; Stop EVERYTHING slamOnTheBrakes = true; return; } } #endregion //-------------------------------------------------------------------------------------------------// //-----Begin tertiary Code //-------------------------------------------------------------------------------------------------// private void buttonRun_Click(object sender, EventArgs e) { if (checkBoxReprint.Checked) { bulkReprint reprint = new bulkReprint(); reprint.ShowDialog(this); checkBoxReprint.Checked = false; } else if (chkBoxRebuild.Checked) { checkDumpReports(); writeToDumpReportListFile(); } else { buttonRun.Enabled = false; checkBoxCPSLabels.Enabled = false; checkBoxPalletLabels.Enabled = false; txtBoxSlvPerCarton.Enabled = false; lblSlvPerCarton.Enabled = false; runToolStripMenuItem.Enabled = false; autoModeToolStripMenuItem.Enabled = false; cleanAfterBuildingToolStripMenuItem.Enabled = false; lookForPalletLabelsToolStripMenuItem.Enabled = false; lookForSleeveCartonLabelsToolStripMenuItem.Enabled = false; checkBoxCleanAfterBuilding.Enabled = false; //check data\boomerang folder first boomerangQueueTimer(2); // timer is in seconds //autoTime = DateTime.Now.AddSeconds(5D); //timerQueue.Start(); /* AddMsg("|----------------------------------------------------------------------------------------------------|"); runStartTime = DateTime.Now; statusStripStatusLabel.Text = "Manual processing started: " + runStartTime.ToString("F"); AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePath); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); */ } } private void buttonExit_Click(object sender, EventArgs e) { writeToLog("LabelMonitor closing.\n\n----------------------------------------\n", logFilePath); writeToLog("LabelMonitor closing.\n\n----------------------------------------\n", logFilePathCPS); GC.Collect(); closeCommander(); Application.Exit(); } #region Checkboxes private void checkBoxAutoMode_Click(object sender, EventArgs e) { if (timerAutoMode.Enabled == false) { timerAutoMode.Enabled = true; labelAutoTime.Visible = true; //autoTime = DateTime.Now.AddMinutes(1D); autoTime = DateTime.Now.AddSeconds(30D); buttonRun.Enabled = false; checkBoxCPSLabels.Enabled = false; checkBoxPalletLabels.Enabled = false; checkBoxReprint.Enabled = false; chkBoxRebuild.Enabled = false; chkBoxRebuild.Visible = false; txtBoxSlvPerCarton.Enabled = false; lblSlvPerCarton.Enabled = false; autoModeToolStripMenuItem.Checked = true; runToolStripMenuItem.Enabled = false; cleanAfterBuildingToolStripMenuItem.Enabled = false; lookForPalletLabelsToolStripMenuItem.Enabled = false; lookForSleeveCartonLabelsToolStripMenuItem.Enabled = false; if (checkBoxCleanAfterBuilding.Checked == false) {// Turn on clean files after building automatically checkBoxCleanAfterBuilding.Checked = true; checkBoxCleanAfterBuilding_Click(checkBoxCleanAfterBuilding, e); } checkBoxCleanAfterBuilding.Enabled = false; statusStripStatusLabel.Text = "Auto mode: online."; AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePath); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); } else { timerAutoMode.Enabled = false; buttonRun.Enabled = true; labelAutoTime.Text = "Auto mode: offline!"; statusStripStatusLabel.Text = "Auto mode: offline!"; AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePath); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); chkBoxRebuild.Enabled = true; chkBoxRebuild.Visible = true; checkBoxCleanAfterBuilding.Enabled = true; checkBoxCPSLabels.Enabled = true; checkBoxPalletLabels.Enabled = true; checkBoxReprint.Enabled = true; txtBoxSlvPerCarton.Enabled = true; lblSlvPerCarton.Enabled = true; autoModeToolStripMenuItem.Checked = false; runToolStripMenuItem.Enabled = true; cleanAfterBuildingToolStripMenuItem.Enabled = true; lookForPalletLabelsToolStripMenuItem.Enabled = true; lookForSleeveCartonLabelsToolStripMenuItem.Enabled = true; } } private void checkBoxCleanAfterBuilding_Click(object sender, EventArgs e) { if (cleanAfterBuilding == false) { cleanAfterBuildingToolStripMenuItem.Checked = true; cleanAfterBuilding = true; statusStripStatusLabel.Text = "Cleanup mode: ACTIVATED."; AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePath); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); } else if (cleanAfterBuilding == true) { cleanAfterBuildingToolStripMenuItem.Checked = false; cleanAfterBuilding = false; statusStripStatusLabel.Text = "Cleanup mode: DEACTIVATED!"; AddMsg(statusStripStatusLabel.Text); } } private void checkBoxPalletLabels_Click(object sender, EventArgs e) { if (checkBoxPalletLabels.Checked) { statusStripStatusLabel.Text = "LabelMonitor will look for Pallet labels."; } else { statusStripStatusLabel.Text = "LabelMonitor will NOT look for Pallet labels!"; } AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePath); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); } private void checkBoxCPSLabels_Click(object sender, EventArgs e) { if (checkBoxCPSLabels.Checked) { statusStripStatusLabel.Text = "LabelMonitor will look for CPS labels."; txtBoxSlvPerCarton.Text = ConfigurationManager.AppSettings["slvPerCarton"]; txtBoxSlvPerCarton.Enabled = true; } else { statusStripStatusLabel.Text = "LabelMonitor will NOT look for CPS labels!"; txtBoxSlvPerCarton.Text = ""; txtBoxSlvPerCarton.Enabled = false; } AddMsg(statusStripStatusLabel.Text); writeToLog(statusStripStatusLabel.Text, logFilePath); writeToLog(statusStripStatusLabel.Text, logFilePathCPS); } #endregion #region ToolStrip Menu Items #region File Menu private void runToolStripMenuItem_Click(object sender, EventArgs e) { buttonRun_Click(sender, e); } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { buttonExit_Click(sender, e); } #endregion #region Options Menu private void autoModeToolStripMenuItem_Click(object sender, EventArgs e) { if (autoModeToolStripMenuItem.Checked == true) { autoModeToolStripMenuItem.Checked = false; checkBoxAutoMode_Click(sender, e); checkBoxAutoMode.Checked = false; } else if (autoModeToolStripMenuItem.Checked == false) { autoModeToolStripMenuItem.Checked = true; checkBoxAutoMode_Click(sender, e); checkBoxAutoMode.Checked = true; } } private void cleanAfterBuildingToolStripMenuItem_Click(object sender, EventArgs e) { if (cleanAfterBuildingToolStripMenuItem.Checked == true) { cleanAfterBuildingToolStripMenuItem.Checked = false; checkBoxCleanAfterBuilding_Click(sender, e); checkBoxCleanAfterBuilding.Checked = false; } else if (cleanAfterBuildingToolStripMenuItem.Checked == false) { cleanAfterBuildingToolStripMenuItem.Checked = true; checkBoxCleanAfterBuilding_Click(sender, e); checkBoxCleanAfterBuilding.Checked = true; } } private void lookForPalletLabelsToolStripMenuItem_Click(object sender, EventArgs e) { if (lookForPalletLabelsToolStripMenuItem.Checked == true) { lookForPalletLabelsToolStripMenuItem.Checked = false; checkBoxPalletLabels_Click(sender, e); checkBoxPalletLabels.Checked = false; } else if (lookForPalletLabelsToolStripMenuItem.Checked == false) { lookForPalletLabelsToolStripMenuItem.Checked = true; checkBoxPalletLabels_Click(sender, e); checkBoxPalletLabels.Checked = true; } } private void lookForSleeveCartonLabelsToolStripMenuItem_Click(object sender, EventArgs e) { if (lookForSleeveCartonLabelsToolStripMenuItem.Checked == true) { lookForSleeveCartonLabelsToolStripMenuItem.Checked = false; checkBoxCPSLabels_Click(sender, e); checkBoxCPSLabels.Checked = false; } else if (lookForSleeveCartonLabelsToolStripMenuItem.Checked == false) { lookForSleeveCartonLabelsToolStripMenuItem.Checked = true; checkBoxCPSLabels_Click(sender, e); checkBoxCPSLabels.Checked = true; } } #endregion private void usingLabelMonitorToolStripMenuItem_Click(object sender, EventArgs e) { Process.Start(@"" + ConfigurationManager.AppSettings["manualFile"]); } private void aboutLabelToolStripMenuItem_Click(object sender, EventArgs e) { AboutLabelMonitor about = new AboutLabelMonitor(); about.ShowDialog(this); } #endregion private void txtBoxSlvPerCarton_TextChanged(object sender, EventArgs e) { if (txtBoxSlvPerCarton.Text == ConfigurationManager.AppSettings["slvPerCarton"]) { lblSlvPerCarton.Text = "Sleeves per carton (default)"; } else { lblSlvPerCarton.Text = "Sleeves per carton"; } } /// /// Adds custom color to the listbox highlight and text color /// for environments with limited style /// /// /// private void listBoxStatus_DrawItem(object sender, DrawItemEventArgs e) { //if (e.Index < 0) return; bool isItemSelected = ((e.State & DrawItemState.Selected) == DrawItemState.Selected); int itemIndex = e.Index; //if the item state is selected them change the back color //if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) if (itemIndex >= 0 && itemIndex < listBoxStatus.Items.Count) { Graphics g = e.Graphics; // Background Color SolidBrush backgroundColorBrush = new SolidBrush((isItemSelected) ? Color.FromArgb(245, 175, 41) : Color.White); g.FillRectangle(backgroundColorBrush, e.Bounds); // Set text color string itemText = listBoxStatus.Items[itemIndex].ToString(); SolidBrush itemTextColorBrush = (isItemSelected) ? new SolidBrush(Color.Black) : new SolidBrush(Color.Black); g.DrawString(itemText, e.Font, itemTextColorBrush, listBoxStatus.GetItemRectangle(itemIndex).Location); // Clean up backgroundColorBrush.Dispose(); itemTextColorBrush.Dispose(); } // If the ListBox has focus, draw a focus rectangle around the selected item. e.DrawFocusRectangle(); } private void chkBoxRebuild_Click(object sender, EventArgs e) { if (chkBoxRebuild.Checked) { checkBoxCPSLabels.Enabled = false; checkBoxPalletLabels.Enabled = false; checkBoxReprint.Enabled = false; checkBoxCleanAfterBuilding.Enabled = false; txtBoxSlvPerCarton.Enabled = false; lblSlvPerCarton.Enabled = false; cleanAfterBuildingToolStripMenuItem.Enabled = false; lookForPalletLabelsToolStripMenuItem.Enabled = false; lookForSleeveCartonLabelsToolStripMenuItem.Enabled = false; } else { checkBoxCPSLabels.Enabled = true; checkBoxPalletLabels.Enabled = true; checkBoxReprint.Enabled = true; checkBoxCleanAfterBuilding.Enabled = true; txtBoxSlvPerCarton.Enabled = true; lblSlvPerCarton.Enabled = true; cleanAfterBuildingToolStripMenuItem.Enabled = true; lookForPalletLabelsToolStripMenuItem.Enabled = true; lookForSleeveCartonLabelsToolStripMenuItem.Enabled = true; } } } }