using Microsoft.Win32;
using mshtml;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Security.Principal;
using System.Text;
using System.Web;
using System.Windows.Forms;
namespace PSUpdater
{
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public partial class PSUpdater : Form
{
//
// source code obtained from http://www.codeproject.com/Articles/20379/Disabling-Close-Button-on-Forms
// Code Snippet
private const int CP_NOCLOSE_BUTTON = 0x200;
protected override CreateParams CreateParams
{
get
{
CreateParams myCp = base.CreateParams;
myCp.ClassStyle = myCp.ClassStyle | CP_NOCLOSE_BUTTON;
return myCp;
}
}
//
// end Code Snippet
bool updateAndPrint = false;
public static IHTMLDocument2 doc;
public static IHTMLSelectionObject select;
//public static HTMLDocumentEvents2_Event htmlClick;
DirectoryInfo dir;
DirectoryInfo di = new DirectoryInfo(@"" + ConfigurationManager.AppSettings["packingSlipFolder"]);
private Font printFont;
private StreamReader streamToPrint;
public static string userID = WindowsIdentity.GetCurrent().Name;
#region Strings
string fileName = "";
string fileContents = "";
string jobToAudit = "";
string logFile = "";
string path = @"" + ConfigurationManager.AppSettings["appPath"];
string slipFolder = @"" + ConfigurationManager.AppSettings["packingSlipFolder"];
public static string selectedFileInputFile = "";
string auditLogPath = @"" + ConfigurationManager.AppSettings["auditLogPath"];
#endregion
public PSUpdater()
{
InitializeComponent();
}
private void PSUpdater_Load(object sender, EventArgs e)
{
HTMLEditor.DocumentText = "";
doc = HTMLEditor.Document.DomDocument as IHTMLDocument2;
doc.designMode = "On";
HTMLEditor.ScriptErrorsSuppressed = true;
string startupMsg = "PSUpdater 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);
txtBoxScanner.Text = "Type (or scan) to search, or browse below...";
statusStripStatusLabel.Text = "Authored by J. Edwards, 2016. Rights applicable.";
loadSlips();
HTMLEditor.Parent.Enabled = false;
HTMLEditor.Navigate("");
btnPrint.Enabled = false;
btnReset.Enabled = false;
btnUpdate.Enabled = false;
}
//-------------------------------------------------------------------------------------------------//
//-----Begin primary Label Monitor Code
//-------------------------------------------------------------------------------------------------//
private void loadSlips()
{
listBoxPSlips.Items.Clear();
// load folders from pdfLabelFolderCPS
FileInfo[] dif = di.GetFiles(); //return an array of all html files
foreach (FileInfo file in dif)
{
if (file.Name.ToLower().EndsWith(".html"))//ignore the reprint prep folder and data folder
{
listBoxPSlips.Items.Add(file.Name);
}
}
}
private void listBoxPSlips_SelectedIndexChanged(object sender, EventArgs e)
{
fileName = slipFolder + "\\" + listBoxPSlips.SelectedItem.ToString();
jobToAudit = listBoxPSlips.SelectedItem.ToString().Substring(0, listBoxPSlips.SelectedItem.ToString().LastIndexOf("_"));
if (fileName != null)
{
string url = @"file:///" + fileName.Replace(@"\", @"/") + "";
try
{
HTMLEditor.Navigate(url);
AddMsg("File " + fileName + " selected.");
writeToLog("File " + fileName + " selected.");
}
catch (Exception ex)
{
statusStripStatusLabel.Text = "ERROR - Cannot load file " + fileName;
AddMsg(statusStripStatusLabel.Text);
writeToLog(statusStripStatusLabel.Text + "\r\n" + ex.ToString());
}
try
{
using (FileStream fsPsIn = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (StreamReader srPsIn = new StreamReader(fsPsIn))
{
string s = "";
while ((s = srPsIn.ReadLine()) != null)
{
if (s.Contains("input class=\"kit\""))
{
selectedFileInputFile = s.Substring(s.LastIndexOf("=") + 1).Replace("\"", "");
selectedFileInputFile = selectedFileInputFile.Replace(">", "");
}
}
srPsIn.Close();
srPsIn.Dispose();
fsPsIn.Close();
fsPsIn.Dispose();
}
}
catch(Exception err)
{
statusStripStatusLabel.Text = "ERROR - Cannot read file " + fileName + ", for job input (source) file(s).";
AddMsg(statusStripStatusLabel.Text);
writeToLog(statusStripStatusLabel.Text + "\r\n" + err.ToString());
}
btnPrint.Enabled = true;
btnReset.Enabled = true;
btnUpdate.Enabled = true;
}
}
//-------------------------------------------------------------------------------------------------//
//-----Begin secondary Label Monitor Code
//-------------------------------------------------------------------------------------------------//
#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);
}
}
#endregion
#region File Copying and IO
private void emailCompletedSlip()
{
try
{
File.Copy(fileName, slipFolder + "\\ToSend\\" + fileName.Substring(fileName.LastIndexOf("\\")), true);
statusStripStatusLabel.Text = "Packing Slip " + fileName + " copied to the 'ToSend' folder for emailing.";
writeToLog(statusStripStatusLabel.Text);
}
catch (Exception copyFail)
{
statusStripStatusLabel.Text = "Error - Could not copy the slip to the 'ToSend' folder for emailing.";
writeToLog("emailCompletedSlip()->" + statusStripStatusLabel.Text + "\r\n" + copyFail.ToString());
return;
}
try
{
File.Delete(fileName);
statusStripStatusLabel.Text = "Packing slip " + fileName + " removed from " + slipFolder;
writeToLog(statusStripStatusLabel.Text);
}
catch (Exception deleteFail)
{
statusStripStatusLabel.Text = "Error - Could not delete " + fileName + "from " + slipFolder;
writeToLog("emailCompletedSlip()->" + statusStripStatusLabel.Text + "\r\n" + deleteFail.ToString());
return;
}
}
///
/// Function to update the audit trail log file to track a job's progess through
/// production, corrections and shipping
///
private void updateAuditLogFile(string jobNum, string fileName)
{
DirectoryInfo diAl = new DirectoryInfo(@"" + ConfigurationManager.AppSettings["auditLogPath"]);
FileInfo[] fiAl = diAl.GetFiles();
List temp = new List();
//open audit log file first
foreach (FileInfo file in fiAl)
{
string fixedFilename = "";
if (!(jobNum.StartsWith("J00")))
{
fixedFilename = jobNum.Replace("J", "J00");
}
else if (jobNum.StartsWith("J00"))
{
fixedFilename = jobNum;
}
if (file.Name.StartsWith(fixedFilename) /*&& (file.LastWriteTime <= staleTime)*/)
{
try
{
using (FileStream fsAlIn = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (StreamReader srAlIn = new StreamReader(fsAlIn))
{
string s = "";
while ((s = srAlIn.ReadLine()) != null)
{
temp.Add(s);
}
srAlIn.Close();
srAlIn.Dispose();
fsAlIn.Close();
fsAlIn.Dispose();
}
//check for the .dat/.duf filename match
if (temp[2].Contains(fileName))
{
if ((temp[14].EndsWith(": 0%")) || (temp[14].EndsWith(": 50%")))
{
if (updateAndPrint == true)
{
if (temp[14].EndsWith(": 0%"))
{
temp[14] = temp[14].Replace(": 0%", ": 100%");//update the shipping complete percentage
}
else if (temp[14].EndsWith(": 50%"))
{
temp[14] = temp[14].Replace(": 50%", ": 100%");//update the shipping complete percentage
}
temp[16] = "Job Finished DateTime : " + DateTime.Now.ToString("M/d/yy h:mm:ss tt");//add a job completed date and time
}
else
{
temp[14] = temp[14].Replace(": 0%", ": 50%");//update the shipping complete percentage
}
using (StreamWriter fsAlOut = new StreamWriter(file.FullName, false))
{
for (int t = 0; temp.Count > t; t++)
{
fsAlOut.WriteLine(temp[t]);
}
fsAlOut.Close();
fsAlOut.Dispose();
}
}
}
temp.Clear();
statusStripStatusLabel.Text = "Audit log updates for " + fileName + " complete.";
writeToLog(statusStripStatusLabel.Text);
}
catch (Exception af)
{
statusStripStatusLabel.Text = "Error - Could not update the Audit log.";
writeToLog("updateAuditLogFile()->" + statusStripStatusLabel.Text + "\r\n" + af.ToString());
return;
}
}
}
}
///
/// 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 + "\\logs\\" + DateTime.Today.ToString("yyyyMMdd") + "_logfile.txt";
try
{
using (FileStream stream = new FileStream(logFile, FileMode.Append, FileAccess.Write, FileShare.Read))
using (StreamWriter w = new StreamWriter(stream))
{
w.WriteLine("{0} {1}: {2}", DateTime.Now, userID, information);
w.Close();
w.Dispose();
}
}
catch
{
statusStripStatusLabel.Text = "Unable to write to " + path + "! Please check log file...";
AddMsg(statusStripStatusLabel.Text);
}
}
#endregion
#region HTML Case Conversions
private static string properCaseHtml(string html)
{
string[] tags = new string[] {
"html", "head", "title", "style", "script", "body",
"p", "a", "br", "span", "div", "i", "u", "b", "h1", "h2",
"h3", "h4", "h5", "h6", "h7", "ul", "ol", "li", "img",
"tr", "table", "th", "td", "tbody", "thead", "tfoot",
"input", "select", "option", "textarea", "em", "strong"
};
foreach (string t in tags)
{
html = html.Replace("<" + t.ToUpper(), "<" + t).Replace("/" + t.ToUpper() + ">", "/" + t + ">"); ;
}
string[] attributes = new string[] {
"align", "cellspacing", "cellpadding", "valign", "border", "text-align",
"style", "alt", "title", "for", "col", "header", "clear", "class",
"colspan", "rows", "cols", "type", "name", "id", "target", "method"
};
foreach (string a in attributes)
{
html = html.Replace(a.ToUpper() + "=", a + "=");
}
return html;
}
#endregion
//-------------------------------------------------------------------------------------------------//
//-----Begin tertiary Code
//-------------------------------------------------------------------------------------------------//
#region Buttons
private void btnExit_Click(object sender, EventArgs e)
{
writeToLog("PSUpdater exiting.");
GC.Collect();
Application.Exit();
}
private void btnPrint_Click(object sender, EventArgs e)
{
string msgBoxMessage = "Are you SURE you want to print this file, marking this shipment as COMPLETE?";
if (MessageBox.Show(msgBoxMessage,
"Confirm File Print",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes)
{
updateAndPrint = true;//set the flag for a combo save and print, in case changes haven't been saved yet
btnUpdate_Click(sender, e);
HTMLEditor.ShowPrintPreviewDialog();
updateAuditLogFile(jobToAudit, selectedFileInputFile);
emailCompletedSlip();
updateAndPrint = false;
}
}
private void btnReset_Click(object sender, EventArgs e)
{
string msgBoxMessage = "Are you SURE you want to reset this file, losing all your changes?";
if (MessageBox.Show(msgBoxMessage,
"Confirm File Reset",
MessageBoxButtons.YesNo,
MessageBoxIcon.None) == DialogResult.Yes)
{
try
{
string url = @"file:///" + fileName.Replace(@"\", @"/") + "";
HTMLEditor.Navigate(url);
fileContents = properCaseHtml(HTMLEditor.Document.Body.Parent.OuterHtml);
}
catch (Exception ex)
{
statusStripStatusLabel.Text = "ERROR - Cannot reset/reload file " + fileName;
AddMsg(statusStripStatusLabel.Text);
writeToLog(statusStripStatusLabel.Text + "\r\n" + ex.ToString());
}
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
statusStripStatusLabel.Text = "Saving file: " + fileName;
File.WriteAllText(path + "\\" + listBoxPSlips.SelectedItem.ToString(), HTMLEditor.Document.Body.Parent.OuterHtml, Encoding.GetEncoding(HTMLEditor.Document.Encoding));
AddMsg(statusStripStatusLabel.Text);
writeToLog(statusStripStatusLabel.Text);
}
catch (Exception ex)
{
statusStripStatusLabel.Text = "ERROR - Cannot save file " + fileName + "\r\n" + ex.ToString();
AddMsg(statusStripStatusLabel.Text);
writeToLog(statusStripStatusLabel.Text);
return;
}
}
#endregion
private void HTMLEditor_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
HTMLEditor.Parent.Enabled = true;
txtBoxScanner.Focus();
txtBoxScanner.SelectAll();
}
private void txtBoxScanner_Click(object sender, EventArgs e)
{
txtBoxScanner.SelectAll();
txtBoxScanner.Focus();
}
private void txtBoxScanner_Enter(object sender, EventArgs e)
{
txtBoxScanner.SelectAll();
txtBoxScanner.Focus();
}
private void txtBoxScanner_KeyDown(object sender, KeyEventArgs e)
{
//handle return/enter key press or handheld scanner's carriage return
if (e.KeyValue == 13)
{
if (txtBoxScanner.Text != "Type (or scan) to search, or browse below...")
{
if (!String.IsNullOrEmpty(txtBoxScanner.Text))//text box is not empty
{
string fileName = sender.ToString();
int fL = 0;
List fileNameList = new List();
foreach (string fileNameItem in listBoxPSlips.Items)
{
fileNameList.Add(fileNameItem);
}
listBoxPSlips.Items.Clear();
foreach (string listItem in fileNameList)
{
if (listItem.Contains(txtBoxScanner.Text))
{
//repopulate the fileListBox with found items
listBoxPSlips.Items.Add(listItem);
}
}
Application.DoEvents();
if (listBoxPSlips.Items.Count == 0)
{
AddMsg("No results found for search: " + txtBoxScanner.Text + ".");
txtBoxScanner.Text = "Type (or scan) to search, or browse below...";
loadSlips();
btnPrint.Enabled = false;
btnReset.Enabled = false;
btnUpdate.Enabled = false;
txtBoxScanner.SelectAll();
}
else if (listBoxPSlips.Items.Count == 1)
{
fL = 0;
listBoxPSlips.Focus();
listBoxPSlips.SelectedIndex = fL;
}
else
{
listBoxPSlips.Focus();
listBoxPSlips.SelectedIndex = fL;
}
Application.DoEvents();
}
else
{
txtBoxScanner.Text = "Type (or scan) to search, or browse below...";
loadSlips();
btnPrint.Enabled = false;
btnReset.Enabled = false;
btnUpdate.Enabled = false;
}
}
}
}
#region Toolstrip Menu Items
private void updateToolStripMenuItem_Click(object sender, EventArgs e)
{
btnUpdate_Click(sender, e);
}
private void resetSlipToolStripMenuItem_Click(object sender, EventArgs e)
{
btnReset_Click(sender, e);
}
private void printSlipToolStripMenuItem_Click(object sender, EventArgs e)
{
btnPrint_Click(sender, e);
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
btnExit_Click(sender, e);
}
private void aboutPSUToolStripMenuItem_Click(object sender, EventArgs e)
{
About about = new About();
about.ShowDialog(this);
}
private void cutSlipToolStripMenuItem_Click(object sender, EventArgs e)
{
if (HTMLEditor.Focused == true)
{
doc.execCommand("Cut", false, null);
}
else if (txtBoxScanner.Focused == true)
{
txtBoxScanner.Cut();
}
}
private void copySlipToolStripMenuItem_Click(object sender, EventArgs e)
{
if (HTMLEditor.Focused == true)
{
doc.execCommand("Copy", false, null);
}
else if (txtBoxScanner.Focused == true)
{
txtBoxScanner.Copy();
}
}
private void pasteSlipToolStripMenuItem_Click(object sender, EventArgs e)
{
if (HTMLEditor.Focused == true)
{
doc.execCommand("Paste", false, null);
}
else if (txtBoxScanner.Focused == true)
{
txtBoxScanner.Paste();
}
}
#endregion
}
}