/// <summary> /// Move Files to Production /// </summary> /// <param name="batch">Batch number for the process</param> /// <param name="run">Run number for the process</param> public static void MoveToProduction(string batch, string run) { int mergedPDFsCount = 0; int postageFileCount = 0; int JobTicketeFileCount = 0; int MailDatFileCount = 0; string copyfilefrom = string.Empty; string copyfileto = string.Empty; string copyfiletype = string.Empty; int totalOutputFileCount = 0; int PDFOuptutFileCount = 0; int mailDatFileCount = 0; int postagefileOutCount = 0; int jobTicketOutCount = 0; totalruntime = new Stopwatch(); totalruntime.Start(); ErrorMessages = new List <string>(); TotalErrorCount = 0; // Init AppStats info stats = new AppStats(DbAccess.GetConnectionString(), "AppStats"); if (string.IsNullOrEmpty(refID)) { refID = string.Format("{0:yyyyMMddHHmmssff}", DateTime.Now); } recordID = 0; appName = System.IO.Path.GetFileNameWithoutExtension(Application.ExecutablePath); // Record Statistics in AppStats Table stats.SetDefaults = true; stats.SetField("RefID", refID); stats.SetField("AppName", (string.IsNullOrEmpty(appName) ? "ReportsApplication1" : appName)); stats.SetField("AppSection", "MoveToProduction"); stats.SetField("Batch", batch); stats.SetField("Run", run); stats.SetField("TestProd", (UseTestDB) ? "TEST" : "PROD"); int?ret = stats.InsertRecord(); if (ret == null) { string s = string.Format("Error Inserting AppStats record: {0}", stats.Message); Log.Error(s); TotalErrorCount++; ErrorMessages.Add(s); } else { recordID = (int)ret; } try { if ((WT != null) && (WT.CancellationPending)) { Log.Error("MoveToProduction already canceled"); TotalErrorCount++; stats.SetField("Status", (TotalErrorCount == 0) ? "OK" : "ERRORS"); stats.SetField("ErrorCount", TotalErrorCount); stats.SetField("ErrorMessages", "MoveToProduction already canceled"); stats.SetField("TestProd", (UseTestDB) ? "TEST" : "PROD"); if (!stats.UpdateRecord()) { Log.Error(string.Format("Error Updating AppStats record: {0}", stats.Message)); } return; } Log.Info(string.Format("MoveToProduction starting for Batch: {0}, Run: {1}", batch, run)); string strpdffolder = strrootfolder + "\\MergedPDFs\\" + batch + run + "\\"; string srtpostagefolder = strrootfolder + "\\Postage Statements"; string srtJobTicketfolder = strrootfolder + "\\Job Tickets"; string srtMailDatfolder = strrootfolder + "\\Mail-Dat\\" + batch + run + "\\"; //handle each folder individually as each folder gets saved differently. // ------------------------------------------------------------ // Get merged PDFs, copy to LPrint copyfiletype = "MergedPDFs"; string[] pdffiles = Directory.GetFiles(strpdffolder); mergedPDFsCount = pdffiles.Length; string copyfile; for (int i = 0; i < pdffiles.Length; i++) { copyfile = pdffiles[i].Remove(0, pdffiles[i].LastIndexOf("\\") + 1); copyfilefrom = pdffiles[i]; copyfileto = srtLPrint + copyfile; if (!File.Exists(srtLPrint + copyfile)) { Log.Info(string.Format("Moving file for Batch: {0}, Run: {1}, File: {2}", batch, run, srtLPrint + copyfile)); File.Copy(pdffiles[i], srtLPrint + copyfile); } else { Log.Info(string.Format("File found, already in production. File: {2} Batch: {0}, Run: {1}", batch, run, srtLPrint + copyfile)); } totalOutputFileCount++; PDFOuptutFileCount++; } // ------------------------------------------------------------ // Copy Postage Statements to LPrint copyfiletype = "PostageStatements"; string[] postagefiles = Directory.GetFiles(srtpostagefolder); postageFileCount = postagefiles.Length; for (int i = 0; i < postagefiles.Length; i++) { copyfile = postagefiles[i].Remove(0, postagefiles[i].LastIndexOf("\\") + 1); if (copyfile == "PODFO_POSTAGE_" + batch + run + ".PDF") { copyfilefrom = postagefiles[i]; copyfileto = srtLPrint + copyfile; if (!File.Exists(srtLPrint + copyfile)) { Log.Info(string.Format("Moving file for Batch: {0}, Run: {1}, File: {2}", batch, run, srtLPrint + copyfile)); File.Copy(postagefiles[i], srtLPrint + copyfile); } else { Log.Info(string.Format("File found, already in production. File: {2} Batch: {0}, Run: {1}", batch, run, srtLPrint + copyfile)); } totalOutputFileCount++; postagefileOutCount++; break; } } // ------------------------------------------------------------ // Copy Job Ticket to LPrint copyfiletype = "JobTicket"; string[] JobTicketfiles = Directory.GetFiles(srtJobTicketfolder); JobTicketeFileCount = JobTicketfiles.Length; for (int i = 0; i < JobTicketfiles.Length; i++) { copyfile = JobTicketfiles[i].Remove(0, JobTicketfiles[i].LastIndexOf("\\") + 1); if (copyfile == "PODFO-" + batch + run + ".pdf") { copyfilefrom = JobTicketfiles[i]; copyfileto = srtLPrint + copyfile; if (!File.Exists(srtLPrint + copyfile)) { Log.Info(string.Format("Moving file for Batch: {0}, Run: {1}, File: {2}", batch, run, srtLPrint + copyfile)); File.Copy(JobTicketfiles[i], srtLPrint + copyfile); } else { Log.Info(string.Format("File found, already in production. File: {2} Batch: {0}, Run: {1}", batch, run, srtLPrint + copyfile)); } totalOutputFileCount++; jobTicketOutCount++; break; } } // ------------------------------------------------------------ // Copy Mail Dat files to Mail-Dat upload copyfiletype = "Mail-Dat"; string[] MailDatfiles = Directory.GetFiles(srtMailDatfolder); MailDatFileCount = MailDatfiles.Length; for (int i = 0; i < MailDatfiles.Length; i++) { copyfile = MailDatfiles[i].Remove(0, MailDatfiles[i].LastIndexOf("\\") + 1); copyfilefrom = MailDatfiles[i]; copyfileto = strMailDatUpload + "\\" + copyfile; File.Copy(MailDatfiles[i], strMailDatUpload + "\\" + copyfile); totalOutputFileCount++; mailDatFileCount++; } } catch (Exception ex) { // Format and log exception string s = string.Format("Error clsMove {0}: Batch: {1} Run: {2} : {3}", copyfiletype, batch, run, ex.Message); Log.Error(s); Log.Error(string.Format("Error on Copy {0} from: '{1}' to: '{2}'", copyfiletype, copyfilefrom, copyfileto)); ErrorMessages.Add(s); TotalErrorCount++; // Format and log inner exception if any string inner = string.Empty; if (ex.InnerException != null) { inner = string.Format("InnerEx.Message: {0}", ex.InnerException.Message); Log.Error(inner); } // Send Email message of exception clsEmail.EmailMessage(string.Format("Error from PODFO Batch {0} run {1} {2}", batch, run, (UseTestDB) ? " TESTING" : ""), string.Format("Error in clsMove.MoveToProduction: {0} \r\n" + "Copy {1} from: '{2}' to: '{3}' \r\n {4}", ex.Message, copyfiletype, copyfilefrom, copyfileto, inner)); } finally { totalruntime.Stop(); string s = string.Format("clsMove: MergedPDFs: {0} of {1}, PostageFiles: {2} of {3}, JobTicketFiles: {4} of {5}, " + "MailDatFiles: {6} of {7}, RunTime: {8}", PDFOuptutFileCount, mergedPDFsCount, postagefileOutCount, postageFileCount, jobTicketOutCount, JobTicketeFileCount, mailDatFileCount, MailDatFileCount, totalruntime.Elapsed.ToString(@"hh\:mm\:ss\.f")); Log.Info(s); // Limit Error messages string for DB string errorMessages = string.Empty; if (ErrorMessages.Count > 0) { errorMessages = ErrorMessages.Aggregate((a, b) => a + ", " + b); if (errorMessages.Length > 1023) { errorMessages = errorMessages.Substring(0, 1023); } } // Record Statistics in AppStats Table Process procObj = Process.GetCurrentProcess(); stats.SetField("Status", (TotalErrorCount == 0) ? "OK" : "ERRORS"); stats.SetField("ErrorCount", TotalErrorCount); stats.SetField("ErrorMessages", errorMessages); stats.SetField("TestProd", (UseTestDB) ? "TEST" : "PROD"); stats.SetField("AppNotes", s); stats.SetField("MaxMemUsedMB", (int)(procObj.PeakVirtualMemorySize64 / 1048576L)); stats.SetField("InputCount1", mergedPDFsCount + postageFileCount + JobTicketeFileCount + MailDatFileCount); stats.SetField("OutputCount1", totalOutputFileCount); stats.SetField("OutputCount2", PDFOuptutFileCount); stats.SetField("ProcessTimeSecs1", totalruntime.Elapsed.TotalSeconds); stats.SetField("TotalRunTimeSecs", totalruntime.Elapsed.TotalSeconds); stats.SetField("AppCount3", mailDatFileCount); bool rcstats = stats.UpdateRecord(); if (!rcstats) { Log.Error(string.Format("Error Updating AppStats record: {0}", stats.Message)); } } }
/// <summary> /// Make WC PDFs /// </summary> /// <param name="batch">Batch number</param> /// <param name="run">Run number</param> /// <param name="intStart">Range Start</param> /// <param name="intEnd">Range End</param> public static void MakePDFs(string batch, string run, int intStart = 0, int intEnd = 0) { int RecordsCount = 0; int RecordsDone = 0; DateTime lastRPMTime = DateTime.Now; int RPMCount = 0; Stopwatch totalruntime = new Stopwatch(); Stopwatch loadtime = new Stopwatch(); rpttime = new Stopwatch(); PDFtime = new Stopwatch(); int TimeoutErrorRecCount = 0; totalruntime.Start(); Log.SourceBase = "WCMakePDFs"; TotalErrorCount = 0; ErrorMessages = new List <string>(); // Init AppStats info stats = new AppStats(DbAccess.GetConnectionString(), "AppStats"); if (string.IsNullOrEmpty(refID)) { refID = string.Format("{0:yyyyMMddHHmmssff}", DateTime.Now); } recordID = 0; appName = System.IO.Path.GetFileNameWithoutExtension(Application.ExecutablePath); // Record Statistics in AppStats Table stats.SetDefaults = true; stats.SetField("RefID", refID); stats.SetField("AppName", (string.IsNullOrEmpty(appName) ? "ReportsApplication1" : appName)); stats.SetField("AppSection", "GenerateLettersWC"); stats.SetField("Batch", batch); stats.SetField("Run", run); stats.SetField("RangeStart", intStart); stats.SetField("RangeEnd", intEnd); stats.SetField("TestProd", (UseTestDB) ? "TEST" : "PROD"); int?ret = stats.InsertRecord(); if (ret == null) { string s = string.Format("Error Inserting AppStats record: {0}", stats.Message); Log.Error(s); TotalErrorCount++; ErrorMessages.Add(s); } else { recordID = (int)ret; } if ((WT != null) && (WT.CancellationPending)) { Log.Warn("MakePDFs already canceled"); TotalErrorCount++; stats.SetField("Status", (TotalErrorCount == 0) ? "OK" : "ERRORS"); stats.SetField("ErrorCount", TotalErrorCount); stats.SetField("ErrorMessages", "RunAutomated already canceled"); stats.SetField("TestProd", (UseTestDB) ? "TEST" : "PROD"); if (!stats.UpdateRecord()) { Log.Error(string.Format("Error Updating AppStats record: {0}", stats.Message)); } return; } if (WT != null) { WT.ReportProgress(-3, string.Format("R/M: {0:#.##}", 0.0)); WT.ReportProgress(0, string.Format("Loading Batch / Run rows")); } Log.Info(string.Format("Start MakePDFs for Batch: {0} Run: {1} in {2}", batch, run, (DbAccess.UseTestDB) ? "TEST" : "PROD")); try { // Insure Output Directory exists for the PDFs if (!Directory.Exists(strIndiviualPDFPath + "\\" + batch + run)) { DirectoryInfo di = Directory.CreateDirectory(strIndiviualPDFPath + "\\" + batch + run); } //string mConnectionString = "Data Source=usasql;Initial Catalog=PODFO;Integrated Security=True;"; //SqlConnection conn = new SqlConnection(mConnectionString); SqlConnection conn = DbAccess.GetConnection(); SqlCommand cmd; //conn.Open(); //Get all rows from the table based on the batch and run loadtime.Start(); if (intStart == 0 && intStart == 0) { cmd = new SqlCommand("USP_SELECT_WC_LETTERS_FOR_BATCH_RUN"); } else { cmd = new SqlCommand("USP_SELECT_WC_LETTERS_FOR_BATCH_RUN_RANGE"); cmd.Parameters.AddWithValue("@P_Start_MPresortID", intStart); cmd.Parameters.AddWithValue("@P_End_MPresortID", intEnd); } cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = conn; cmd.Parameters.AddWithValue("@P_PODBatchID", batch); cmd.Parameters.AddWithValue("@P_PODRunID", run); SqlDataAdapter adapter = new SqlDataAdapter(cmd); // Can timeout //ds = new DataSet(); //adapter.Fill(ds); DataSet ds = null; Exception lastex = null; bool rc = GetDataForWCLettersWithRetry(batch, run, adapter, out ds, out lastex); if (!rc || ds == null) { string s = string.Format("MakePDFs: Error SQL exceded retries loading letter data: {0}", lastex.Message); Log.Error(s); // Show Error if (WT != null) { WT.ReportProgress(-1, s); } clsEmail.EmailMessage(string.Format("Error from PODFO.MakePDFs {0}", (UseTestDB) ? "TESTING" : ""), s); TotalErrorCount++; TimeoutErrorRecCount++; stats.SetField("Status", (TotalErrorCount == 0) ? "OK" : "ERRORS"); stats.SetField("ErrorCount", TotalErrorCount); stats.SetField("ErrorMessages", s); stats.SetField("TestProd", (UseTestDB) ? "TEST" : "PROD"); stats.SetField("AppCount1", TimeoutErrorRecCount); if (!stats.UpdateRecord()) { Log.Error(string.Format("Error Updating AppStats record: {0}", stats.Message)); } return; } RecordsCount = ds.Tables[0].Rows.Count; loadtime.Stop(); lastRPMTime = DateTime.Now; RPMCount = 0; fileNotFoundCount = 0; if (WT != null) { WT.ReportProgress(0, string.Format("Recs Done {0} of {1}", RecordsDone, RecordsCount)); } rpttime.Start(); foreach (DataRow dr in ds.Tables[0].Rows) { //create the report CreateWCReport(dr); RecordsDone++; RPMCount++; if (WT != null) { // Check if cancel pending, set canceled flag if (WT.CancellationPending) { Log.Warn("MakePDFs: Canceled by Background Worker Request"); TotalErrorCount++; ErrorMessages.Add("MakePDFs: Canceled by Background Worker Request"); break; } // Report Background worker thread status int pcrecsdone = (RecordsDone * 100) / (RecordsCount); if (RecordsDone % ReportProgressCount == 0) { // Report Progress % and count of recs processed WT.ReportProgress(pcrecsdone, string.Format("Recs Done {0} of {1}", RecordsDone, RecordsCount)); // Report records per minute var rpm = RPMCount / (DateTime.Now - lastRPMTime).TotalMinutes; WT.ReportProgress(-3, string.Format("R/M: {0:#.##}", rpm)); lastRPMTime = DateTime.Now; RPMCount = 0; } } } rpttime.Stop(); } catch (Exception ex) { var log = new clsLog(); log.mstrLogFileLocation = batch + run + ".txt"; log.WriteToLogfile("clsGenerateLettersWC.MakePDFs " + ex.Message); string s = string.Format("Error: clsGenerateLettersWC.MakePDFs Batch: {0}, Run: {1} : {2}", batch, run, ex.Message); Log.Error(s); ErrorMessages.Add(s); TotalErrorCount++; clsEmail.EmailMessage(string.Format("Error from PODFO {0}", (UseTestDB) ? "TESTING" : ""), "clsGenerateLettersWC.MakePDFs " + ex.Message); } finally { // Show 100% done if (WT != null) { WT.ReportProgress(100, string.Format("Recs Done {0} of {1}", RecordsDone, RecordsCount)); } string s2 = string.Format("MakePDFs: Record count: {0}, Files not found count: {1}", RecordsCount, fileNotFoundCount); Log.Info(s2); if (fileNotFoundCount > 0) { string msg = string.Format("Error: clsGenerateLettersWC.MakePDFs: There were {0} WCZip files not found", fileNotFoundCount); Log.Error(msg); clsEmail.EmailMessage(string.Format("Error from PODFO {0}", (UseTestDB) ? "TESTING" : ""), msg); } // Count PDF files created var TotalPDFCount = Directory.EnumerateFiles(strIndiviualPDFPath + batch + run, "*.PDF").Where(x => x.ToUpper().Contains(".PDF")).Count(); Log.Info(string.Format("MakePDFs: Total PDFs in BatchRun Folder: {0}", TotalPDFCount)); totalruntime.Stop(); // Limit Error messages string for DB string errorMessages = string.Empty; if (ErrorMessages.Count > 0) { errorMessages = ErrorMessages.Aggregate((a, b) => a + ", " + b); if (errorMessages.Length > 1023) { errorMessages = errorMessages.Substring(0, 1023); } } string appnotes = string.Format("WC Recs Done {0} of {1}, files not found: {2}, PDF Files in folder: {3}", RecordsDone, RecordsCount, fileNotFoundCount, TotalPDFCount); // Record Statistics in AppStats Table Process procObj = Process.GetCurrentProcess(); stats.SetField("Status", (TotalErrorCount == 0) ? "OK" : "ERRORS"); stats.SetField("ErrorCount", TotalErrorCount); stats.SetField("ErrorMessages", errorMessages); stats.SetField("TestProd", (UseTestDB) ? "TEST" : "PROD"); stats.SetField("AppNotes", appnotes); stats.SetField("MaxMemUsedMB", (int)(procObj.PeakVirtualMemorySize64 / 1048576L)); stats.SetField("ExpectedCountOut", RecordsCount); stats.SetField("InputCount1", RecordsCount); stats.SetField("OutputCount1", TotalPDFCount); stats.SetField("OutputCount2", RecordsDone); stats.SetField("InputTimeSecs1", loadtime.Elapsed.TotalSeconds); stats.SetField("ProcessTimeSecs1", rpttime.Elapsed.TotalSeconds); stats.SetField("OutputTimeSecs1", PDFtime.Elapsed.TotalSeconds); stats.SetField("TotalRunTimeSecs", totalruntime.Elapsed.TotalSeconds); stats.SetField("AppCount2", fileNotFoundCount); bool rcstats = stats.UpdateRecord(); if (!rcstats) { Log.Error(string.Format("Error Updating AppStats record: {0}", stats.Message)); } Log.Info(string.Format("End MakePDFs for Batch: {0}, Run: {1}", batch, run)); } }
/// <summary> /// Create the Job Ticket for the Batch / Run /// </summary> /// <param name="batch">Batch number for process</param> /// <param name="run">Run number for process</param> public static void CreateJobTicket(string batch, string run) { totalruntime = new Stopwatch(); totalruntime.Start(); totalOutputFileCount = 0; ErrorMessages = new List <string>(); int mailScheduleID; // Init AppStats info stats = new AppStats(DbAccess.GetConnectionString(), "AppStats"); if (string.IsNullOrEmpty(refID)) { refID = string.Format("{0:yyyyMMddHHmmssff}", DateTime.Now); } recordID = 0; appName = System.IO.Path.GetFileNameWithoutExtension(Application.ExecutablePath); // Record Statistics in AppStats Table stats.SetDefaults = true; stats.SetField("RefID", refID); stats.SetField("AppName", (string.IsNullOrEmpty(appName) ? "ReportsApplication1" : appName)); stats.SetField("AppSection", "CreateJobTicket"); stats.SetField("Batch", batch); stats.SetField("Run", run); stats.SetField("TestProd", (UseTestDB) ? "TEST" : "PROD"); int?ret = stats.InsertRecord(); if (ret == null) { string s = string.Format("Error Inserting AppStats record: {0}", stats.Message); Log.Error(s); TotalErrorCount++; ErrorMessages.Add(s); } else { recordID = (int)ret; } // If already canceled if ((WT != null) && (WT.CancellationPending)) { Log.Error("CreateJobTicket already canceled"); TotalErrorCount++; stats.SetField("Status", (TotalErrorCount == 0) ? "OK" : "ERRORS"); stats.SetField("ErrorCount", TotalErrorCount); stats.SetField("ErrorMessages", "CreateJobTicket already canceled"); stats.SetField("TestProd", (UseTestDB) ? "TEST" : "PROD"); if (!stats.UpdateRecord()) { Log.Error(string.Format("Error Updating AppStats record: {0}", stats.Message)); } return; } Log.Info(string.Format("CreateJobTicket for Batch {0}, Run {1}", batch, run)); string strPDFName = "PODFO-" + batch + run; var log = new clsLog(); log.mstrLogFileLocation = batch + run + ".txt"; // Build document folder name for job ticket template string strRootFolder = string.Empty; strRootFolder = System.IO.Directory.GetCurrentDirectory().ToLower(); strRootFolder += "\\documents\\"; log.WriteToLogfile("Job ticket template location = " + strRootFolder); string strJob = "PODFO"; int intRun = Convert.ToInt16(run); SqlConnection conn = DbAccess.GetConnection(); StreamReader srReader; string strFile; StreamWriter swWriter; string strJobTicketName = ""; FileInfo fileinfo = new FileInfo(strPDFName); Dictionary <string, int> itemCodeDic = new Dictionary <string, int>(); string itemCode = string.Empty; int packets = 0; int images = 0; try { //Get record count and image count var DA = new clsGetBatchSort(); //update this query SqlDataAdapter adapter = new SqlDataAdapter(DA.dsBatch_Sort(batch, run)); DataSet ds = new DataSet(); adapter.Fill(ds); packets = ds.Tables[0].Rows.Count; foreach (DataRow dr in ds.Tables[0].Rows) { images += Convert.ToInt32(dr["PageCount"]); } // Get Must Mail Date SqlDataAdapter adapter2 = new SqlDataAdapter(DA.dsGet_MailDate(batch, run)); DataSet ds2 = new DataSet(); adapter2.Fill(ds2); DateTime dtMustMailDate = Convert.ToDateTime(ds2.Tables[0].Rows[0][0].ToString()); string Postage = string.Empty; if (intRun == 1) { Postage = ds2.Tables[0].Rows[0]["Postage"].ToString(); } //open the job ticket template, read in the entire file, close the template srReader = File.OpenText(strRootFolder + "PODFOJOBTICKET.rtf"); strFile = srReader.ReadToEnd(); srReader.Close(); strJobTicketName = strOutputFolder + fileinfo.Name + ".rtf"; swWriter = File.CreateText(strJobTicketName); //replace the variable data in the job ticket if (intRun == 1) { strFile = strFile.Replace("$RANGE$", "1 to 5"); if (packets >= 200) { itemCode = Conf.GetString("10_Envelope_IND", "1102000"); strFile = strFile.Replace("NVLP", string.Concat("#10 PODFO Window Envelope IND ", itemCode)); strFile = strFile.Replace("$ENVELOPE2$", "#10 PODFO Window Envelope IND"); } else { itemCode = Conf.GetString("10_Envelope_ND", "1103000"); strFile = strFile.Replace("NVLP", string.Concat("#10 PODFO Window Envelope NI", itemCode)); strFile = strFile.Replace("$ENVELOPE2$", "#10 PODFO Window Envelope NI"); } } else if (intRun == 2) { strFile = strFile.Replace("$RANGE$", "6 to 75"); if (packets >= 200) { itemCode = Conf.GetString("9x12_Envelope_IND", "1191000"); strFile = strFile.Replace("NVLP", string.Concat("PODFO #9 X 12 Window IND", itemCode)); strFile = strFile.Replace("$ENVELOPE2$", "PODFO #9 X 12 Window IND"); } else { itemCode = Conf.GetString("9x12_Envelope_ND", "1193000"); strFile = strFile.Replace("NVLP", string.Concat("PODFO #9 X 12 Window NI", itemCode)); strFile = strFile.Replace("$ENVELOPE2$", "PODFO #9 X 12 Window NI"); } } itemCodeDic.Add(itemCode, packets); itemCodeDic.Add(Conf.GetString("PaperItemCode", "2085011"), images / 2); mailScheduleID = InsertIntoPrintMailScan(strJob + batch.ToString() + "-R0" + intRun.ToString(), packets, batch, run, dtMustMailDate, Postage); strFile = strFile.Replace("NPACKS", packets.ToString()); strFile = strFile.Replace("$PACKETS$", packets.ToString()); strFile = strFile.Replace("$IMAGECOUNT$", images.ToString()); strFile = strFile.Replace("PKTS", packets.ToString()); //add up records for other thing strFile = strFile.Replace("$RUN$", "0" + intRun.ToString()); strFile = strFile.Replace("$BATCH$", batch); strFile = strFile.Replace("$FULLJOBTYPE$", strJob + " POD LETTERS"); strFile = strFile.Replace("$MAILDATE$", dtMustMailDate.ToString("MM/dd/yyyy")); strFile = strFile.Replace("$PDFNAME$", strPDFName + ".pdf"); strFile = strFile.Replace("StockBarcode", itemCode); // Write Job Ticket File swWriter.WriteLine(strFile); swWriter.Flush(); swWriter.Close(); totalOutputFileCount++; ConvertJobTicketToPdf(strJobTicketName, string.Concat(strJob, batch.ToString(), "-R0" + intRun.ToString(), "-", packets.ToString(), ";", mailScheduleID), itemCode); foreach (string itemKey in itemCodeDic.Keys) { InsertItemUsageIntoSage_Inventory(strJob, itemCodeDic[itemKey], batch, run, itemKey); } } catch (Exception ex) { string s = string.Format("Error in Batch: {0}, Run: {1} for clsJobTicket: {2}", batch, run, ex.Message); clsEmail.EmailMessage(string.Format("Error from PODFO Batch {0} run {1} {2}", batch, run, (UseTestDB) ? " TESTING" : ""), s); Log.Error(s); ErrorMessages.Add(s); TotalErrorCount++; // Format and log inner exception if any string inner = string.Empty; if (ex.InnerException != null) { inner = string.Format("InnerEx.Message: {0}", ex.InnerException.Message); Log.Error(inner); } } finally { totalruntime.Stop(); string s = string.Format("clsJobTicket: {0} Job Tickets, for {1} records, and {2} pages, RunTime: {3} ", totalOutputFileCount, packets, images, totalruntime.Elapsed.ToString(@"hh\:mm\:ss\.f")); Log.Info(s); // Limit Error messages string for DB string errorMessages = string.Empty; if (ErrorMessages.Count > 0) { errorMessages = ErrorMessages.Aggregate((a, b) => a + ", " + b); if (errorMessages.Length > 1023) { errorMessages = errorMessages.Substring(0, 1023); } } // Record Statistics in AppStats Table Process procObj = Process.GetCurrentProcess(); stats.SetField("Status", (TotalErrorCount == 0) ? "OK" : "ERRORS"); stats.SetField("ErrorCount", TotalErrorCount); stats.SetField("ErrorMessages", errorMessages); stats.SetField("TestProd", (UseTestDB) ? "TEST" : "PROD"); stats.SetField("AppNotes", s); stats.SetField("MaxMemUsedMB", (int)(procObj.PeakVirtualMemorySize64 / 1048576L)); stats.SetField("ExpectedCountOut", 1); stats.SetField("InputCount1", packets); stats.SetField("InputCount2", images); stats.SetField("OutputCount1", totalOutputFileCount); //stats.SetField("OutputCount2", PDFOuptutFileCount); //stats.SetField("InputTimeSecs1", loadtime.Elapsed.TotalSeconds); stats.SetField("ProcessTimeSecs1", totalruntime.Elapsed.TotalSeconds); //stats.SetField("OutputTimeSecs1", PDFtime.Elapsed.TotalSeconds); stats.SetField("TotalRunTimeSecs", totalruntime.Elapsed.TotalSeconds); //stats.SetField("AppCount3", mailDatFileCount); bool rcstats = stats.UpdateRecord(); if (!rcstats) { Log.Error(string.Format("Error Updating AppStats record: {0}", stats.Message)); } } }
/// <summary> /// Merge the individual PDFs /// </summary> /// <param name="batch">Batch number for this process</param> /// <param name="run">Run number for this process</param> public static void MergePDFs(string batch, string run) { int intcount = 0; int intEnd = 0; int intStart = 1; int introwcount = 0; int RecsDone = 0; //DateTime lastRPMTime = new DateTime(); int RPMCount = 0; int filesCountThisMerge = 0; int intDBpagecount = 0; int intPDFpagecount = 0; totalruntime = new Stopwatch(); totalruntime.Start(); int fileNotFoundCount = 0; int RecordsOuput = 0; loadtime = new Stopwatch(); mergetime = new Stopwatch(); PDFtime = new Stopwatch(); ErrorMessages = new List <string>(); // Init AppStats info stats = new AppStats(DbAccess.GetConnectionString(), "AppStats"); if (string.IsNullOrEmpty(refID)) { refID = string.Format("{0:yyyyMMddHHmmssff}", DateTime.Now); } recordID = 0; appName = System.IO.Path.GetFileNameWithoutExtension(Application.ExecutablePath); // Record Statistics in AppStats Table stats.SetDefaults = true; stats.SetField("RefID", refID); stats.SetField("AppName", (string.IsNullOrEmpty(appName) ? "ReportsApplication1" : appName)); stats.SetField("AppSection", "MergePDFs"); stats.SetField("Batch", batch); stats.SetField("Run", run); stats.SetField("TestProd", (UseTestDB) ? "TEST" : "PROD"); stats.SetField("AppCount3", FilesPerMerge); int?ret = stats.InsertRecord(); if (ret == null) { string s = string.Format("Error Inserting AppStats record: {0}", stats.Message); Log.Error(s); TotalErrorCount++; ErrorMessages.Add(s); } else { recordID = (int)ret; } if ((WT != null) && (WT.CancellationPending)) { Log.Error("MergePDFs already canceled"); TotalErrorCount++; stats.SetField("Status", (TotalErrorCount == 0) ? "OK" : "ERRORS"); stats.SetField("ErrorCount", TotalErrorCount); stats.SetField("ErrorMessages", "RunAutomated already canceled"); stats.SetField("TestProd", (UseTestDB) ? "TEST" : "PROD"); if (!stats.UpdateRecord()) { Log.Error(string.Format("Error Updating AppStats record: {0}", stats.Message)); } return; } if (WT != null) { WT.ReportProgress(-2, String.Format("Merge PDFs")); WT.ReportProgress(-3, string.Format("R/M: {0:#.##}", 0.0)); } try { Log.Info(string.Format("MergePDFs starting for Batch: {0}, Run: {1}, FilesPerMerge: {2}", batch, run, FilesPerMerge)); var log = new clsLog(); log.mstrLogFileLocation = batch + run + ".txt"; loadtime.Start(); var DA = new clsGetBatchSort(); SqlDataAdapter adapter = new SqlDataAdapter(DA.dsBatch_Sort(batch, run)); DataSet ds = new DataSet(); adapter.Fill(ds); introwcount = ds.Tables[0].Rows.Count; loadtime.Stop(); //int LetterTypeID = 0; if (WT != null) { WT.ReportProgress(0, string.Format("Collecting page count")); } foreach (DataRow dr in ds.Tables[0].Rows) { intDBpagecount += Convert.ToInt32(dr["PageCount"]); } ceTe.DynamicPDF.Document.AddLicense(ceTeLicense); //Dim intRecordCount As Integer = 1 //Dim rootValue As String string mergePath = strMergeFilePath + "\\" + batch + run; if (!Directory.Exists(mergePath)) { DirectoryInfo di = Directory.CreateDirectory(mergePath); } string[] fileEntries = Directory.GetFiles(strFilePath + "\\" + batch + run); string fmt = "00000000"; //string filename = Path.Combine("C:\\PDF\\", "report" + PreSortID.ToString(fmt) + ".pdf"); //string filename = Path.Combine(mstrFilePath + "\\" + batch + run + "\\" + PreSortID.ToString(fmt) + ".pdf"); string filename; ceTe.DynamicPDF.Merger.MergeDocument myTempDoc = new ceTe.DynamicPDF.Merger.MergeDocument(); string missingfiles = ""; mergetime.Start(); if (introwcount != 0) //make sure files where imported { if (fileEntries.Length == introwcount) //make sure file count matches pdf count { for (int i = 1; i < fileEntries.Length + 1; i++) { filename = strFilePath + "\\" + batch + run + "\\" + i.ToString(fmt) + ".PDF"; if (fileEntries[i - 1].ToString().Equals(filename)) { intcount += 1; intEnd += 1; // Merge file myTempDoc.Append(filename); filesCountThisMerge++; //shut pdf every "n" files to avoid errors //if ((myTempDoc.Pages.Count >= PagesPerMerge)) if (filesCountThisMerge >= FilesPerMerge) { PDFtime.Start(); log.WriteToLogfile("about to combine myTempDoc " + myTempDoc.Pages.Count + " Pages"); myTempDoc.CompressionLevel = 0; myTempDoc.PdfVersion = ceTe.DynamicPDF.PdfVersion.v1_3; intPDFpagecount += myTempDoc.Pages.Count; //creates pdf log.WriteToLogfile("myTempDoc.Draw(" + mergePath + "\\PODFO " + batch + run + " " + intStart + "-" + intEnd + ".Pdf)"); myTempDoc.Draw(mergePath + "\\PODFO " + batch + run + " " + intStart + "-" + intEnd + ".Pdf"); myTempDoc = null; GC.Collect(); intStart = intEnd + 1; intcount = 0; myTempDoc = new ceTe.DynamicPDF.Merger.MergeDocument(); log.WriteToLogfile("Finished Drawing"); Log.Info("myTempDoc.Draw(" + mergePath + "\\PODFO " + batch + run + " " + intStart + "-" + intEnd + ".Pdf)"); RecordsOuput++; PDFtime.Stop(); filesCountThisMerge = 0; } } else { missingfiles = missingfiles + ", " + i; log.WriteToLogfile("missing file: " + i.ToString()); // MessageBox.Show("missing file: " + i.ToString()); fileNotFoundCount++; } RecsDone++; RPMCount++; // Report Background worker thread status if (WT != null) { // Check if cancel pending, set canceled flag if (WT.CancellationPending) { BGWCanceled = true; break; } // Report Progress % and count of recs processed int pcrecsdone = (RecsDone * 100) / (introwcount); if (intcount % 20 == 0) { WT.ReportProgress(pcrecsdone, string.Format("Recs Done {0} of {1}", RecsDone, introwcount)); // Report records per minute //var rpm = RPMCount / (DateTime.Now - lastRPMTime).TotalMinutes; //BGW.ReportProgress(-3, string.Format("R/M: {0:#.##}", rpm)); //lastRPMTime = DateTime.Now; //RPMCount = 0; } } } // If merge in progress, write out last merge file //if ((myTempDoc.Pages.Count != PagesPerMerge)) if (filesCountThisMerge != FilesPerMerge) { PDFtime.Start(); log.WriteToLogfile("about to combine myTempDoc " + myTempDoc.Pages.Count + " Pages"); log.WriteToLogfile("myTempDoc.Draw(" + mergePath + "\\PODFO " + batch + run + " " + intStart + "-" + intEnd + ".Pdf)"); myTempDoc.CompressionLevel = 0; myTempDoc.PdfVersion = ceTe.DynamicPDF.PdfVersion.v1_3; intPDFpagecount += myTempDoc.Pages.Count; //creates pdf myTempDoc.Draw(mergePath + "\\PODFO " + batch + run + " " + intStart + "-" + intEnd + ".Pdf"); myTempDoc = null; GC.Collect(); log.WriteToLogfile("Finished Drawing"); Log.Info("myTempDoc.Draw(" + mergePath + "\\PODFO " + batch + run + " " + intStart + "-" + intEnd + ".Pdf)"); RecordsOuput++; PDFtime.Stop(); filesCountThisMerge = 0; } if (WT != null) { WT.ReportProgress(100, string.Format("Recs Done {0} of {1}", intEnd, introwcount)); } } else { //email string s = string.Format("clsMerge.MergePDFs: Missing file fileEntries.Length = {0} and introwcount = {1}", fileEntries.Length, introwcount); Log.Info(s); log.WriteToLogfile("Missing file fileEntries.Length = " + fileEntries.Length + " and introwcount = " + introwcount); // MessageBox.Show("Missing file fileEntries.Length = " + fileEntries.Length + " and introwcount = " + introwcount); if (WT != null) { WT.ReportProgress(100, string.Format("Record counts don't match: Files: {0}, DB Rows: {1}", fileEntries.Length, introwcount)); } } } else { Log.Info("MergePDFs: No files to process"); } } catch (Exception ex) { TotalErrorCount++; var log = new clsLog(); log.mstrLogFileLocation = batch + run + ".txt"; log.WriteToLogfile("clsMerge.MergePDFs " + ex.Message + " Stack trace " + ex.StackTrace + " Inner ex " + ex.InnerException); clsEmail.EmailMessage(string.Format("PODFO error {0}", (UseTestDB) ? " TESTING" : ""), "Error merging pdfs. Message: " + ex.Message + " The pdf count was " + intEnd); // MessageBox.Show("Error merging pdfs. Message: " + ex.Message + " The pdf count was " + intEnd); string s = string.Format("clsMerge.MergePDFs Exception: {0}", ex.Message); Log.Error(s); ErrorMessages.Add(s); s = string.Format("clsMerge.MergePDFs Exception Inner: {0}", ex.InnerException); Log.Error(s); s = string.Format("clsMerge.MergePDFs Exception Stack: {0}", ex.StackTrace); Log.Error(s); } finally { totalruntime.Stop(); mergetime.Stop(); string s = string.Format("clsMerge.MergePDFs: Rowount: {0}, DBPageCount: {1}, Time: {2}", introwcount, intDBpagecount, totalruntime.Elapsed.ToString(@"hh\:mm\:ss\.f")); Log.Info(s); // Limit Error messages string for DB string errorMessages = string.Empty; if (ErrorMessages.Count > 0) { errorMessages = ErrorMessages.Aggregate((a, b) => a + ", " + b); if (errorMessages.Length > 1023) { errorMessages = errorMessages.Substring(0, 1023); } } // Record Statistics in AppStats Table Process procObj = Process.GetCurrentProcess(); stats.SetField("Status", (TotalErrorCount == 0) ? "OK" : "ERRORS"); stats.SetField("ErrorCount", TotalErrorCount); stats.SetField("ErrorMessages", errorMessages); stats.SetField("TestProd", (UseTestDB) ? "TEST" : "PROD"); stats.SetField("AppNotes", s); stats.SetField("MaxMemUsedMB", (int)(procObj.PeakVirtualMemorySize64 / 1048576L)); //stats.SetField("ExpectedCountOut", RecordsCount); stats.SetField("InputCount1", RecsDone); stats.SetField("OutputCount1", RecordsOuput); stats.SetField("OutputCount2", intDBpagecount); stats.SetField("InputTimeSecs1", loadtime.Elapsed.TotalSeconds); stats.SetField("ProcessTimeSecs1", mergetime.Elapsed.TotalSeconds); stats.SetField("OutputTimeSecs1", PDFtime.Elapsed.TotalSeconds); stats.SetField("TotalRunTimeSecs", totalruntime.Elapsed.TotalSeconds); stats.SetField("AppCount2", fileNotFoundCount); bool rcstats = stats.UpdateRecord(); if (!rcstats) { Log.Error(string.Format("Error Updating AppStats record: {0}", stats.Message)); } } }