// ======================================================================== // Copyright 2006 - Volian Enterprises, Inc. All rights reserved. // Volian Enterprises - Proprietary Information - DO NOT COPY OR DISTRIBUTE // ------------------------------------------------------------------------ // $Workfile: $ $Revision: $ // $Author: $ $Date: $ // // $History: $ // ======================================================================== using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Data.OleDb; using System.Collections.Specialized; using System.Collections.Generic; using System.Xml; using System.IO; using System.Text; using System.Text.RegularExpressions; using Volian.MSWord; using VEPROMS.CSLA.Library; namespace DataLoader { public partial class Loader { private void SaveSectionDocument(string fname, string stpseq, string stype, ref int cid, string sectName) { int docid = SaveWordDoc(fname, stype, sectName); switch (docid) { case 0: // could add the following back in - but many of these may be put out in the log, and // don't supply any pertinent info. //log.InfoFormat("Timing problem for save of word document, will retry. oldstepsequence = {0}", stpseq); break; case -1: log.ErrorFormat("Could not complete save of word document, oldstepsequence = {0}", stpseq); break; default: cid = docid; break; } } private int SaveWordDoc(string fname, string title, string stype, ConfigInfo ci, string sectName) { int docid = 0; if (System.IO.File.Exists(fname)) { FileInfo myFile = new FileInfo(fname); frmMain.AddInfo("Processing {0}", fname); //string tmpName = @"C:\Temp\DataLoader\" + myFile.Name.Replace(".", "_") + ".RTF"; string tmpName = Path.GetTempFileName(); string temppath = Path.GetTempFileName(); if (frmMain.cbSaveDocChecked) { FileInfo tmpFile = new FileInfo(tmpName); if (tmpFile.Exists) tmpFile.Delete(); myFile.CopyTo(tmpName); bool keepTrying = true; int attempt = 1; while (keepTrying) { WordDoc myWordDoc = null; try { myWordDoc = new WordDoc(tmpName); /* 16-bit's type[1] used the following codes to represent the respective lpi setting * * char far typestr[] = "*pP46f7L"; * * char * far printtypes[] = { * "Compressed, 8 lines per inch", * "Elite, 6 lines per inch", * "Pica, 6 lines per inch", * "Default font, 4 Lines Per Inch", * "Default font, 6 Lines Per Inch", * "Compressed 6 LPI", * "Default font, 7 Lines Per Inch", * "Special Landscape, Elite, 6 lines per inch" */ if (stype != null) { // stype[1] == 'p' or 'P' or '6' 'f' or 'L' get spc = 6 int lpi = 6; if (stype[1] == '*') lpi = 8; else if (stype[1] == '4') lpi = 4; else if (stype[1] == '7') lpi = 7; // if need landscape set too: bool landscape = (stype[1] == 'L'); myWordDoc.SetLineSpacing(lpi); // if need landscape set too: , landscape); ; } float docLen = 1.0f; try { docLen = myWordDoc.Length; } catch (Exception ex1) { frmMain.AddError("Length Exception {0}\r\n\r\n{1}", ex1.Message, ex1.StackTrace); } if (ci == null) ci = new ConfigInfo(null); ci.AddItem("Printing", "Length", string.Format("{0:0.0000}", docLen)); string ascii = myWordDoc.MyWordDoc.Ascii; string s = myWordDoc.Save(temppath); myWordDoc.Close(); WaitMS(wms); docid = SaveDoc(temppath, title, ci, ascii); DeleteFile(temppath); DeleteFile(tmpName); keepTrying = false; if (attempt == 2) { frmMain.AddError("Success: MSWord was able to process file"); frmMain.AddError("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"); } } catch (Exception ex) { //frmMain.AddError(ex, "SaveWordDoc"); frmMain.AddError("Convert Exception {0}\r\n\r\n{1}", ex.Message, ex.StackTrace); if (attempt == 1) frmMain.AddError("vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv"); else frmMain.AddError("============================================================================"); frmMain.AddError("Attempt {0} - File Could not be opened in Word", attempt); frmMain.AddError("{0}", fname); frmMain.AddError("Section: '{0}'", title == string.Empty ? sectName : title); log.Error("SaveWordDoc"); log.ErrorFormat("oldstepsequence = {0}", fname); log.ErrorFormat("{0}\r\n\r\n{1}", ex.Message, ex.InnerException); log.ErrorFormat(ex.StackTrace); MSWordToPDF.CloseApp(); switch (attempt) { case 1: // Covert using RTB CloseMSWord(myWordDoc); frmMain.AddError("Attempting to fix the file and try again."); // Get the rtf from the file string rtf = LoadFileRaw(tmpName); // Parse for margins because the RTB will remove them Match match = Regex.Match(rtf, @"((\\marg[^\\]+)+)", RegexOptions.Singleline); using (RichTextBox rtb = new RichTextBox()) { rtb.Rtf = rtf; // Allow the RichTextBox to parse the RTF rtf = rtb.Rtf; // Get the RTF back from the RichTextBox } // Add the margins to the RTB output rtf = rtf.Replace(@"\ansi", @"\ansi" + match.Value); // Save the modified rtf to the temporary file SaveFile(rtf, tmpName); attempt = 2; break; default: frmMain.AddError("MS Word cannot process the file"); if (myWordDoc != null) { TryToShowMSWord(myWordDoc); CloseMSWord(myWordDoc); } docid = SaveDoc(fname, title, ci, ""); // Save the original file keepTrying = false; DeleteFile(temppath); DeleteFile(tmpName); frmMain.AddError("Failure: Original contents saved to database"); frmMain.AddError("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"); break; } } } } else { if (frmMain.cbSaveRTFChecked) docid = SaveDoc(fname, title, ci,""); // Need to get Ascii Text from RTF } } else //log.ErrorFormat("Missing rtf file: {0}", fname); frmMain.AddError("Missing rtf file: {0}", fname); return docid; } private static void TryToShowMSWord(WordDoc myWordDoc) { try { if (MessageBox.Show("Word is having problems processing this file.\r\n\r\nDo you want to see?", "MS Word Failure", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { WordDoc.MyWordApp.Visible = true; MessageBox.Show("Click on OK when you are done with MS Word", "Wait until done with MS Word", MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch (Exception ex) { Console.WriteLine("{0} - {1}", ex.GetType().Name, ex.Message); } } private static void CloseMSWord(WordDoc myWordDoc) { try { // RHM 20100628 - All of a sudden, this was null and would not work. // I added the else clause so that the WinWord process would be terminated. if (myWordDoc != null) { WordDoc.CloseApp(); Application.DoEvents(); while (WordDoc.WordProcesses.Length > 0) Application.DoEvents(); } else { WordDoc.KillWordApps(); Application.DoEvents(); while (WordDoc.WordProcesses.Length > 0) Application.DoEvents(); } } catch (Exception ex) { Console.WriteLine("{0} - {1}", ex.GetType().Name, ex.Message); } } private static void DeleteFile(string fName) { if (File.Exists(fName)) File.Delete(fName); } private string LoadFileRaw(string fName) { try { FileInfo file = new FileInfo(fName); byte[] myBytes = new byte[file.Length]; using (FileStream fs = file.OpenRead()) { fs.Read(myBytes, 0, (int)file.Length); fs.Close(); } StringBuilder sb = new StringBuilder(); foreach (byte byt in myBytes) { int iByte = (int)byt; sb.Append((char)byt); } return sb.ToString(); } catch (Exception ex) { Console.WriteLine("{0} - {1}", ex.GetType().Name, ex.Message); Application.DoEvents(); return LoadFileRaw(fName); } } private void SaveFile(string str, string fName) { FileInfo file = new FileInfo(fName); using (StreamWriter sw = file.CreateText()) { sw.Write(str); sw.Close(); } } private int SaveWordDoc(string temppath, string stype, string sectName) { return SaveWordDoc(temppath, String.Empty, stype, null, sectName); } private int SaveTheDoc(string temppath, string title, ConfigInfo ci, string ascii) { try { FileStream fs = File.Open(temppath, FileMode.Open, FileAccess.Read, FileShare.None); long len = fs.Length + 1; byte[] ByteArray = new byte[len]; int nBytesRead = fs.Read(ByteArray, 0, (int)len); fs.Close(); string t1 = (title == null || title == "") ? null : title; Document doc = Document.MakeDocument(t1, ByteArray, null, ci == null ? null : ci.ToString(), DateTime.Now, "Migration", ".Doc",null); FileInfo tmpFile = new FileInfo(temppath); string docfile = temppath.Substring(0, temppath.LastIndexOf(".")) + @".doc"; if (File.Exists(docfile)) File.Delete(docfile); FileInfo doctmpFile = tmpFile.CopyTo(docfile); doc.DocAscii = ascii; doc.Save(); File.Delete(docfile); return doc.DocID; } // for an io exception, keep trying catch (IOException exio) { Console.WriteLine("IO: {0} - {1}", exio.GetType().Name, exio.Message); frmMain.AddError(exio, "SaveTheDoc('{0}','{1}')", temppath, title); Wait(2); return 0; } catch (Exception ex) { log.Error("Save Word Doc"); log.ErrorFormat("{0}\r\n\r\n{1}", ex.Message, ex.InnerException); frmMain.AddError(ex, "SaveTheDoc('{0}','{1}')", temppath, title); return -1; } } private int SaveDoc(string temppath, string title, ConfigInfo ci, string ascii) { int done = 0; int ntry = 0; while (done == 0 && ntry < 4) { ntry++; done = SaveTheDoc(temppath, title, ci, ascii); } return done; } } }