// --------------------------------------------- // Copy Documents // --------------------------------------------- public static object CopyDocument( string fromFileName, string destinationFileName, List <WordDocumentTasks.TagStructure> tag, IOutputMessage uioutput, string processName, string userID ) { var vkExcelApp = new Microsoft.Office.Interop.Excel.Application(); vkExcelApp.Visible = false; // Excel.ApplicationClass vkExcelApp = new Excel.ApplicationClass(); string saveFile = destinationFileName; object vkReadOnly = false; object vkVisible = true; object vkFalse = false; object vkTrue = true; object vkDynamic = 2; object vkMissing = System.Reflection.Missing.Value; // Let's make the excel application not visible // vkExcelApp.Visible = false; // vkExcelApp.Activate(); // Let's copy the document File.Copy(fromFileName, destinationFileName, true); // Let's open the DESTINATION document //Word.Document vkMyDoc = vkExcelApp.Documents.Open( // ref destinationFileName, ref vkMissing, ref vkReadOnly, // ref vkMissing, ref vkMissing, ref vkMissing, // ref vkMissing, ref vkMissing, ref vkMissing, // ref vkMissing, ref vkMissing, ref vkVisible ); Excel.Workbook vkMyDoc = vkExcelApp.Workbooks.Open( destinationFileName, vkMissing, false, vkMissing, vkMissing, vkMissing, true, vkMissing, "\t", vkMissing, vkMissing, vkMissing, vkMissing, vkMissing, vkMissing); foreach (var t in tag) { // 17/02/2013 // Ignore **MD** and other with ** because it is too risky // if (t.Tag == "**MD**" || t.Tag == "**PM**" || t.Tag == "**SM**" || t.Tag == "**ADDRESS**") { continue; } if (t.TagType == "IMAGE") { continue; } FindAndReplace(t.Tag, t.TagValue, 1, vkExcelApp, vkMyDoc); } try { vkMyDoc.Save(); } catch (Exception ex) { uioutput.AddOutputMessage("(Excel) ERROR in file: " + fromFileName + " --- Message: " + ex.ToString(), processName, userID); uioutput.AddErrorMessage("(Excel) ERROR in file: " + fromFileName + " --- Message: " + ex.ToString(), processName, userID); } // close the new document vkMyDoc.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject(vkMyDoc); // close excel application vkExcelApp.Quit(); return(saveFile); }
/// <summary> /// Load folder into FCM Database and into FCM folder /// </summary> /// <param name="sourceFolder"></param> /// <param name="uioutput"></param> /// <param name="parentUID"></param> /// <param name="sequenceNumber"></param> /// <param name="headerInfo"></param> /// <returns></returns> static public ResponseStatus LoadFolder(string sourceFolder, IOutputMessage uioutput, int parentUID, int sequenceNumber, HeaderInfo headerInfo) { ResponseStatus response = new ResponseStatus(); response.Message = "Folder loaded successfully."; if (!Directory.Exists(sourceFolder)) { response.ReturnCode = -0010; response.ReasonCode = -0001; response.Message = "Source folder does not exist."; response.UniqueCode = "E00.00.0001"; response.Icon = MessageBoxIcon.Error; return(response); } string[] folderNameSplit = sourceFolder.Split('\\'); string folderName = folderNameSplit[folderNameSplit.Length - 1]; uioutput.Activate(); string[] files = Directory.GetFiles(sourceFolder); // Create folder that contains files and keep the parent // // ... Model.ModelDocument.Document folder = new Model.ModelDocument.Document(); if (folderName.Length >= 7) { folder.CUID = folderName.Substring(0, 7); } else { folder.CUID = folderName; } folder.FileName = folderName; folder.Comments = "Loaded by batch"; folder.Name = folderName; folder.DisplayName = folderName; folder.FKClientUID = 0; folder.IssueNumber = 0; string refPath = MakHelperUtils.getReferenceFilePathName(sourceFolder); if (string.IsNullOrEmpty(refPath)) { response.ReturnCode = -0010; response.ReasonCode = -0002; response.Message = "Folder selected is not under managed template folder."; response.UniqueCode = "E00.00.0001"; return(response); } folder.Location = refPath; // Store the folder being loaded at the root level // folder.Location = MakConstant.SYSFOLDER.TEMPLATEFOLDER; folder.ParentUID = parentUID; folder.SequenceNumber = 0; folder.SourceCode = "FCM"; folder.UID = 0; folder.RecordType = MakHelperUtils.RecordType.FOLDER; folder.DocumentType = MakHelperUtils.DocumentType.FOLDER; folder.SimpleFileName = folder.Name; folder.FileExtension = "FOLDER"; folder.IsProjectPlan = "N"; // parentUID = folder.Save(headerInfo, MakHelperUtils.SaveType.NEWONLY); parentUID = RepDocument.Save(headerInfo, folder, MakHelperUtils.SaveType.NEWONLY); // Store each file // foreach (string file in files) { #region File Processing string name = Path.GetFileName(file); string fileName = Path.GetFileNameWithoutExtension(file); string fileExtension = Path.GetExtension(file); string validExtensions = ".doc .docx .xls .xlsx .pdf .dotx"; // Not every extension will be loaded // if (!validExtensions.Contains(fileExtension)) { continue; } string fileNameExt = Path.GetFileName(file); string simpleFileName = fileNameExt; if (fileNameExt.Length > 10) { simpleFileName = fileNameExt.Substring(10).Trim(); } Model.ModelDocument.Document document = new Model.ModelDocument.Document(); document.CUID = fileName.Substring(0, 6); document.FileName = fileNameExt; //string refPath = // Utils.getReferenceFilePathName(sourceFolder); document.Location = refPath; string issue = "1"; document.IssueNumber = Convert.ToInt32(issue); try { issue = fileName.Substring(7, 2); document.IssueNumber = Convert.ToInt32(issue); } catch (Exception ex) { LogFile.WriteToTodaysLogFile(ex.ToString()); } document.Name = fileName; document.SimpleFileName = simpleFileName; document.DisplayName = simpleFileName; document.SequenceNumber = sequenceNumber; document.ParentUID = parentUID; document.Comments = "Loaded via batch"; document.SourceCode = "FCM"; document.FKClientUID = 0; document.RecordType = MakHelperUtils.RecordType.DOCUMENT; document.FileExtension = fileExtension; document.Status = FCMUtils.FCMConstant.DocumentStatus.ACTIVE; document.IsProjectPlan = "N"; switch (fileExtension) { case ".doc": document.DocumentType = MakHelperUtils.DocumentType.WORD; break; case ".docx": document.DocumentType = MakHelperUtils.DocumentType.WORD; break; case ".dotx": document.DocumentType = MakHelperUtils.DocumentType.WORD; break; case ".xls": document.DocumentType = MakHelperUtils.DocumentType.EXCEL; break; case ".xlsx": document.DocumentType = MakHelperUtils.DocumentType.EXCEL; break; case ".pdf": document.DocumentType = MakHelperUtils.DocumentType.PDF; break; default: document.DocumentType = MakHelperUtils.DocumentType.UNDEFINED; break; } // document.Save(headerInfo, MakHelperUtils.SaveType.NEWONLY); RepDocument.Save(headerInfo, document, MakHelperUtils.SaveType.NEWONLY); uioutput.AddOutputMessage(document.Name, "", userID); sequenceNumber++; #endregion File Processing } // Recursion removed // string[] folders = Directory.GetDirectories(sourceFolder); foreach (string directory in folders) { string name = Path.GetFileName(directory); LoadFolder(directory, uioutput, parentUID, 0, headerInfo); } return(response); }
/// <summary> /// Generate documents selected for a client /// </summary> /// <param name="clientID"></param> /// <param name="clientDocSetID"></param> /// <param name="uioutput"></param> /// <param name="overrideDocuments"></param> private void TBD_GenerateDocumentsForClient( int clientID, int clientDocSetID, string overrideDocuments) { uioutput.AddOutputMessage("Start time: " + System.DateTime.Now.ToString()); // Instantiate Word // object vkFalse = false; Word.Application vkWordApp = new Word.Application(); // Make it not visible vkWordApp.Visible = false; Excel.Application vkExcelApp = new Excel.Application(); // Make it not visible vkExcelApp.Visible = false; // Get Metadata for client ReportMetadataList clientMetadata = new ReportMetadataList(); clientMetadata.ListMetadataForClient(clientID); var ts = new List <WordDocumentTasks.TagStructure>(); // Load variables/ metadata into memory // foreach (ReportMetadata metadata in clientMetadata.reportMetadataList) { // Retrieve value for the field selected // string value = metadata.GetValue(); // If the field is not enabled, the program has to replace the value with spaces. // var valueOfTag = metadata.Enabled == 'Y' ? value : string.Empty; // When the field is an image and it is not enable, do not include the "No image" icon in the list // if (metadata.InformationType == Utils.InformationType.IMAGE && metadata.Enabled == 'N') { continue; } ts.Add(new WordDocumentTasks.TagStructure() { TagType = metadata.InformationType, Tag = metadata.FieldCode, TagValue = valueOfTag }); } // Get Client Document Set Details // To get the source and destination folders ClientDocumentSet cds = new ClientDocumentSet(); cds.Get(clientID, clientDocSetID); // Get List of documents for a client // var cdl = new ClientDocument(); cdl.List(Utils.ClientID, Utils.ClientSetID); bool fileNotFound = false; // --------------------------------------------------------------------------- // Check if source files exist before generation starts // --------------------------------------------------------------------------- int filecount = 0; foreach (scClientDocSetDocLink doco in cdl.clientDocSetDocLink) { #region File Inspection filecount++; // Ignore for now // if (doco.clientDocument.RecordType.Trim() == Utils.RecordType.FOLDER) { string er = "Folder " + doco.document.Name; uioutput.AddOutputMessage(er); continue; } // Retrieve updated file name from source Document.Document document = new Document.Document(); document.UID = doco.clientDocument.FKDocumentUID; document.Read(); uioutput.AddOutputMessage("Inspecting file: " + document.UID + " === " + document.Name); // Client Document.SourceFileName is the name for the FCM File // Client Document.FileName is the client file name // Update client records with new file name // // Instantiate client document ClientDocument cd = new ClientDocument(); cd.UID = doco.clientDocument.UID; // cd.FileName = document.FileName; cd.SourceFileName = document.FileName; cd.UpdateSourceFileName(); // Update memory with latest file name // doco.clientDocument.SourceFileName = cd.FileName; doco.clientDocument.SourceFileName = cd.SourceFileName; string sourceFileLocationName = Utils.getFilePathName( doco.clientDocument.SourceLocation, doco.clientDocument.SourceFileName); // check if source folder/ file exists if (string.IsNullOrEmpty(doco.clientDocument.Location)) { MessageBox.Show("Document Location is empty."); return; } if (string.IsNullOrEmpty(doco.clientDocument.FileName)) { MessageBox.Show("File Name is empty."); return; } if (!File.Exists(sourceFileLocationName)) { string er = "File does not exist " + sourceFileLocationName + " - File Name: " + doco.clientDocument.SourceFileName; uioutput.AddOutputMessage(er); uioutput.AddErrorMessage(er); fileNotFound = true; continue; } #endregion File Inspection } // Can't proceed if file not found if (fileNotFound) { return; } // Check if destination folder exists // if (string.IsNullOrEmpty(cds.Folder)) { MessageBox.Show("Destination folder not set. Generation stopped."); return; } string PhysicalCDSFolder = Utils.GetPathName(cds.Folder); if (!Directory.Exists(PhysicalCDSFolder)) { Directory.CreateDirectory(PhysicalCDSFolder); } // ----------------------------------------------------------------------- // Generation starts here // ----------------------------------------------------------------------- fileprocessedcount = 0; valueForProgressBar = 0; startTime = System.DateTime.Now.ToString(); estimated = System.DateTime.Now.AddSeconds(5 * filecount); var previousTime = System.DateTime.Now; var agora = System.DateTime.Now; foreach (scClientDocSetDocLink doco in cdl.clientDocSetDocLink) { fileprocessedcount++; valueForProgressBar = (fileprocessedcount / filecount) * 100; // Get current time agora = System.DateTime.Now; // Get the time it took to process one file TimeSpan span = agora.Subtract(previousTime); // Calculate the estimated time to complete estimated = System.DateTime.Now.AddSeconds(span.TotalSeconds * filecount); uioutput.UpdateProgressBar(valueForProgressBar, estimated); previousTime = System.DateTime.Now; // Retrieve latest version // Document.Document document = new Document.Document(); document.UID = doco.clientDocument.FKDocumentUID; document.Read(); uioutput.AddOutputMessage(">>> Generating file: " + document.UID + " === " + document.SimpleFileName); string sourceFileLocationName = Utils.getFilePathName( doco.clientDocument.SourceLocation, doco.clientDocument.SourceFileName); // This is the client file name // string clientFileLocation = cds.Folder.Trim() + doco.clientDocument.Location.Trim(); string clientFileLocationName = Utils.getFilePathName( clientFileLocation, doco.clientDocument.FileName.Trim()); // Check if file destination directory exists // string PhysicalLocation = Utils.GetPathName(clientFileLocation); if (string.IsNullOrEmpty(PhysicalLocation)) { string er = "Location is empty " + doco.clientDocument.Location + "\n" + "File Name: " + doco.document.Name; uioutput.AddOutputMessage(er); continue; } if (!Directory.Exists(PhysicalLocation)) { Directory.CreateDirectory(PhysicalLocation); } if (File.Exists(clientFileLocationName)) { // Proceed but report in list // if (overrideDocuments == "Yes") { // Delete file try { File.Delete(clientFileLocationName); uioutput.AddOutputMessage("File replaced " + document.SimpleFileName); } catch (Exception) { uioutput.AddOutputMessage("Error deleting file " + document.SimpleFileName); uioutput.AddErrorMessage("Error deleting file " + document.SimpleFileName); continue; } } else { uioutput.AddOutputMessage("File already exists " + document.SimpleFileName); continue; } } // Copy and fix file // // Word Documents // if (doco.clientDocument.RecordType.Trim() == Utils.RecordType.FOLDER) { // Update file - set as GENERATED. // uioutput.AddOutputMessage("FOLDER: " + doco.clientDocument.SourceFileName); } else { // If is is not a folder, it must be a regular file. // Trying to copy it as well... // var currentDocumentPath = Path.GetExtension(doco.clientDocument.FileName); if (doco.clientDocument.DocumentType == Utils.DocumentType.WORD) { #region Word // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // Generate Document and replace tag values in new document generated // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ var results = WordDocumentTasks.CopyDocument(sourceFileLocationName, clientFileLocationName, ts, vkWordApp, uioutput); if (results.ReturnCode < 0) { // Error has occurred // var er = (System.Exception)results.Contents; uioutput.AddOutputMessage("ERROR: " + er.ToString()); uioutput.AddErrorMessage("ERROR: " + er.ToString()); continue; } // // Instantiate client document ClientDocument cd = new ClientDocument(); cd.UID = doco.clientDocument.UID; // Update file - set as GENERATED. // cd.SetGeneratedFlagVersion('Y', document.IssueNumber); uioutput.AddOutputMessage("Document generated: " + clientFileLocationName); #endregion Word } else if (doco.clientDocument.DocumentType == Utils.DocumentType.EXCEL) { // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // Generate Document and replace tag values in new document generated // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ ExcelSpreadsheetTasks.CopyDocument(sourceFileLocationName, clientFileLocationName, ts, vkExcelApp, uioutput); // // Instantiate client document ClientDocument cd = new ClientDocument(); cd.UID = doco.clientDocument.UID; // Update file - set as GENERATED. // cd.SetGeneratedFlagVersion('Y', document.IssueNumber); uioutput.AddOutputMessage("Document generated: " + clientFileLocationName); } else { File.Copy(sourceFileLocationName, clientFileLocationName); uioutput.AddOutputMessage("File copied but not modified: " + Path.GetExtension(doco.clientDocument.FileName) + " == File: " + clientFileLocationName); } } } // close word application vkWordApp.Quit(ref vkFalse, ref vkFalse, ref vkFalse); vkExcelApp.Quit(); uioutput.AddOutputMessage("End time: " + System.DateTime.Now.ToString()); }
// --------------------------------------------- // // --------------------------------------------- /// <summary> /// Create client document and replace document tags /// </summary> /// <param name="fromFileName"></param> /// <param name="destinationFileName"></param> /// <param name="tag"></param> /// <param name="vkWordApp"></param> /// <returns></returns> public static ResponseStatus CopyDocument( object fromFileName, object destinationFileName, List <WordDocumentTasks.TagStructure> tag, Word.Application vkWordApp, IOutputMessage uioutput, string processName, string userID ) { ResponseStatus ret = new ResponseStatus(); object saveFile = destinationFileName; object vkReadOnly = false; object vkVisible = true; object vkFalse = false; object vkTrue = true; object vkDynamic = 2; object vkMissing = System.Reflection.Missing.Value; // Let's make the word application not visible // vkWordApp.Visible = false; // vkWordApp.Activate(); // Let's copy the document if (uioutput != null) { uioutput.AddOutputMessage("Copying file from: " + fromFileName + " to: " + destinationFileName, processName, userID); } File.Copy(fromFileName.ToString(), destinationFileName.ToString(), true); // Let's open the DESTINATION document Word.Document vkMyDoc; try { //vkMyDoc = vkWordApp.Documents.Open( // ref destinationFileName, ref vkMissing, ref vkReadOnly, // ref vkMissing, ref vkMissing, ref vkMissing, // ref vkMissing, ref vkMissing, ref vkMissing, // ref vkMissing, ref vkMissing, ref vkVisible ); //vkMyDoc = vkWordApp.Documents.Open( // ref destinationFileName, ref vkMissing, ref vkReadOnly, // ref vkMissing, ref vkMissing, ref vkMissing, // ref vkMissing, ref vkMissing, ref vkMissing, // ref vkMissing, ref vkMissing, ref vkVisible ); if (uioutput != null) { uioutput.AddOutputMessage("Opening file: " + destinationFileName, processName, userID); } vkMyDoc = vkWordApp.Documents.Open( FileName: destinationFileName, ConfirmConversions: vkFalse, ReadOnly: vkFalse, AddToRecentFiles: vkMissing, PasswordDocument: vkMissing, PasswordTemplate: vkMissing, Revert: vkMissing, WritePasswordDocument: vkMissing, WritePasswordTemplate: vkMissing, Format: vkMissing, Encoding: vkMissing, Visible: vkFalse); } catch (Exception ex) { ret.ReturnCode = -1; ret.ReasonCode = 1000; ret.Message = "Error opening file." + destinationFileName; ret.Contents = ex; return(ret); } // // In case the file is still read-only... // if (uioutput != null) { uioutput.AddOutputMessage("Checking if file is read-only: " + destinationFileName, processName, userID); } if (vkMyDoc.ReadOnly) { uioutput.AddOutputMessage("(Word) File is Read-only contact support: " + fromFileName, processName, userID); vkMyDoc.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject(vkMyDoc); return(ret); } if (uioutput != null) { uioutput.AddOutputMessage("File is NOT read-only!! " + destinationFileName, processName, userID); } if (uioutput != null) { uioutput.AddOutputMessage("Starting find and replace loop", processName, userID); } // 18/04/2013 // vkMyDoc.Activate(); foreach (var t in tag) { if (t.TagType == Helper.Utils.InformationType.FIELD || t.TagType == Helper.Utils.InformationType.VARIABLE) { FindAndReplace(t.Tag, t.TagValue, 1, vkWordApp, vkMyDoc); // ReplaceProperty(t.Tag, t.TagValue, 1, vkWordApp, vkMyDoc); } else { insertPicture(vkMyDoc, t.TagValue, t.Tag); } } // 15/03/2013 // Force field update if (uioutput != null) { uioutput.AddOutputMessage("Force field updates.", processName, userID); } foreach (Word.Range myStoryRange in vkMyDoc.StoryRanges) { myStoryRange.Fields.Update(); } // 24/10/2010 - Modificado quando troquei a referencia do Word // //vkMyDoc.Sections.Item( 1 ).Headers.Item( Word.WdHeaderFooterIndex.wdHeaderFooterPrimary ).Range.Fields.Update(); //vkMyDoc.Sections.Item( 1 ).Footers.Item( Word.WdHeaderFooterIndex.wdHeaderFooterPrimary ).Range.Fields.Update(); try { if (vkMyDoc.ReadOnly) { if (uioutput != null) { uioutput.AddOutputMessage("(Word) File is Read-only contact support: " + fromFileName, processName, userID); } } else { if (uioutput != null) { uioutput.AddOutputMessage("Saving file, it is no read-only.", processName, userID); } vkMyDoc.Save(); } } catch (Exception ex) { if (uioutput != null) { uioutput.AddOutputMessage("(Word) ERROR Saving in file: " + fromFileName + " --- Message: " + ex.ToString(), processName, userID); } } // close the new document try { if (uioutput != null) { uioutput.AddOutputMessage("Closing file", processName, userID); } vkMyDoc.Close(SaveChanges: vkTrue); } catch (Exception ex) { if (uioutput != null) { uioutput.AddOutputMessage("(Word) ERROR Closing file: " + fromFileName + " --- Message: " + ex.ToString(), processName, userID); } } // Trying to release COM object if (uioutput != null) { uioutput.AddOutputMessage("Releasing COM object", processName, userID); } System.Runtime.InteropServices.Marshal.ReleaseComObject(vkMyDoc); return(ret); }
/// <summary> /// Generate register of systems document using existing file. /// </summary> /// <param name="tv"></param> /// <param name="clientFolder"></param> /// <param name="fileName"></param> /// <returns></returns> public ResponseStatus RegisterOfSytemDocuments2(TreeView tv, string clientFolder, string fileName, string processName, string userID) { uioutput.AddOutputMessage("Starting Register of Systems Documents generation...", processName, userID); uioutput.AddOutputMessage(clientFolder, processName, userID); uioutput.AddOutputMessage(fileName, processName, userID); ResponseStatus ret = new ResponseStatus(); object oMissing = System.Reflection.Missing.Value; object vkMissing = System.Reflection.Missing.Value; object vkReadOnly = false; object vkVisiblefalse = false; object vkFalse = false; var pastPlannedActivities = string.Empty; //Start Word and open the document. //WordNet._Application oApplication = new Application { Visible = false }; // string clientDestinationFileLocation = document.clientDocument.Location.Trim(); string clientDestinationFileLocation = clientFolder; //string clientDestinationFileLocationName = Utils.getFilePathName( // clientDestinationFileLocation, document.clientDocument.FileName.Trim() ); string clientDestinationFileLocationName = Utils.getFilePathName(clientDestinationFileLocation, fileName.Trim()); object destinationFileName = clientDestinationFileLocationName; if (!File.Exists(clientDestinationFileLocationName)) { uioutput.AddOutputMessage("File doesn't exist " + destinationFileName, processName: processName, userID: userID); uioutput.AddErrorMessage("File doesn't exist " + destinationFileName, processName: processName, userID: userID); var responseerror = new ResponseStatus(MessageType.Error); responseerror.Message = "File doesn't exist " + destinationFileName; return(responseerror); } WordNet._Document oDoc; try { uioutput.AddOutputMessage("Opening document in Word... " + destinationFileName, processName: processName, userID: userID); oDoc = oApplication.Documents.Open( ref destinationFileName, ref vkMissing, ref vkFalse, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkVisiblefalse); } catch (Exception ex) { var responseerror = new ResponseStatus(MessageType.Error); responseerror.ReturnCode = -1; responseerror.ReasonCode = 1000; responseerror.Message = "Error copying file."; responseerror.Contents = ex; return(responseerror); } if (oDoc.ReadOnly) { if (uioutput != null) { uioutput.AddOutputMessage("(Word) File is Read-only contact support: " + destinationFileName, processName, userID); } oDoc.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject(oDoc); var responseerror = new ResponseStatus(MessageType.Error); responseerror.Message = "(Word) File is Read-only contact support: " + destinationFileName; return(responseerror); } try { if (uioutput != null) { uioutput.AddOutputMessage("Saving document in Word... " + destinationFileName, processName, userID); } oDoc.Save(); } catch (Exception ex) { if (uioutput != null) { uioutput.AddOutputMessage("Error saving file " + clientDestinationFileLocationName, processName, userID); } var responseerror = new ResponseStatus(MessageType.Error); responseerror.Message = "Error saving file " + clientDestinationFileLocationName; return(responseerror); } string msg = ">>> Opening file... " + destinationFileName; if (uioutput != null) { uioutput.AddOutputMessage(msg, processName, userID); } PrintToWord(oDoc, " ", 8, 1); WordNet.Range wrdRng; WordNet.Table oTable; wrdRng = oDoc.Bookmarks.get_Item(oEndOfDoc).Range; int rowCount = 30; // Get number of rows for a client document, client document set // // var cds = new BUSClientDocumentSet( Utils.ClientID, Utils.ClientSetID XXXXXXXXXXXXXXX ); var cds = new BUSClientDocumentSet(clientID, clientDocSetID); rowCount = cds.DocumentCount; if (rowCount < 1) { return(new ResponseStatus(MessageType.Error)); } oTable = oDoc.Tables.Add(wrdRng, rowCount, 8, ref vkFalse, ref vkFalse); oTable.Borders.OutsideColor = WordNet.WdColor.wdColorBlack; oTable.Borders.InsideLineStyle = WordNet.WdLineStyle.wdLineStyleDouble; oTable.Borders.OutsideColor = WordNet.WdColor.wdColorBlueGray; oTable.Borders.OutsideLineStyle = WordNet.WdLineStyle.wdLineStyleEmboss3D; oTable.Rows [1].HeadingFormat = -1; WordNet.Row headingRow = oTable.Rows [1]; ApplyHeadingStyle(headingRow.Cells [1], 200); headingRow.Cells [1].Range.Text = "Directory"; ApplyHeadingStyle(headingRow.Cells [2], 60); headingRow.Cells [2].Range.Text = "Sub Directory"; ApplyHeadingStyle(headingRow.Cells [3], 80); headingRow.Cells [3].Range.Text = "Document Number"; ApplyHeadingStyle(headingRow.Cells [4], 30); headingRow.Cells [4].Range.Text = "Sml"; ApplyHeadingStyle(headingRow.Cells [5], 40); headingRow.Cells [5].Range.Text = "Med"; ApplyHeadingStyle(headingRow.Cells [6], 30); headingRow.Cells [6].Range.Text = "Lrg"; ApplyHeadingStyle(headingRow.Cells [7], 50); headingRow.Cells [7].Range.Text = "Version"; ApplyHeadingStyle(headingRow.Cells [8], 200); headingRow.Cells [8].Range.Text = "Document Name"; int line = 0; foreach (var treeNode in tv.Nodes) { line++; WriteLineToRoSD(tv.Nodes [0], oDoc, oTable, prefix: "", parent: "", seqnum: line); } msg = ">>> End "; if (uioutput != null) { uioutput.AddOutputMessage(msg, processName, userID); } PrintToWord(oDoc, " ", 12, 1); try { oDoc.Save(); } catch (Exception ex) { if (uioutput != null) { uioutput.AddOutputMessage("Error saving file again... " + clientDestinationFileLocationName, processName, userID); } var responseerror = new ResponseStatus(MessageType.Error); responseerror.Message = "Error saving file again... " + clientDestinationFileLocationName; return(responseerror); } oDoc.Close(); ResponseStatus goodresponse = new ResponseStatus(MessageType.Informational); goodresponse.Message = "Document SRG-01 generated successfully."; return(goodresponse); }
// --------------------------------------------- // Copy Documents // --------------------------------------------- public static object CopyDocument( string fromFileName, string destinationFileName, List <WordDocumentTasks.TagStructure> tag, Excel.Application vkExcelApp, IOutputMessage uioutput ) { // Excel.ApplicationClass vkExcelApp = new Excel.ApplicationClass(); string saveFile = destinationFileName; object vkReadOnly = false; object vkVisible = true; object vkFalse = false; object vkTrue = true; object vkDynamic = 2; object vkMissing = System.Reflection.Missing.Value; // Let's make the excel application not visible // vkExcelApp.Visible = false; // vkExcelApp.Activate(); // Let's copy the document File.Copy(fromFileName, destinationFileName, true); // Let's open the DESTINATION document //Word.Document vkMyDoc = vkExcelApp.Documents.Open( // ref destinationFileName, ref vkMissing, ref vkReadOnly, // ref vkMissing, ref vkMissing, ref vkMissing, // ref vkMissing, ref vkMissing, ref vkMissing, // ref vkMissing, ref vkMissing, ref vkVisible ); Excel.Workbook vkMyDoc = vkExcelApp.Workbooks.Open( destinationFileName, vkMissing, false, vkMissing, vkMissing, vkMissing, true, vkMissing, "\t", vkMissing, vkMissing, vkMissing, vkMissing, vkMissing, vkMissing); foreach (var t in tag) { FindAndReplace(t.Tag, t.TagValue, 1, vkExcelApp, vkMyDoc); } try { vkMyDoc.Save(); } catch (Exception ex) { uioutput.AddOutputMessage("(Excel) ERROR in file: " + fromFileName + " --- Message: " + ex.ToString()); uioutput.AddErrorMessage("(Excel) ERROR in file: " + fromFileName + " --- Message: " + ex.ToString()); } // close the new document vkMyDoc.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject(vkMyDoc); // close excel application // vkExcelApp.Quit(); return(saveFile); }
// --------------------------------------------- // // --------------------------------------------- /// <summary> /// Create client document and replace document tags /// </summary> /// <param name="fromFileName"></param> /// <param name="destinationFileName"></param> /// <param name="tag"></param> /// <param name="vkWordApp"></param> /// <returns></returns> public static ResponseStatus CopyDocument( object fromFileName, object destinationFileName, List <WordDocumentTasks.TagStructure> tag, Word.Application vkWordApp, IOutputMessage uioutput ) { ResponseStatus ret = new ResponseStatus(); object saveFile = destinationFileName; object vkReadOnly = false; object vkVisible = true; object vkFalse = false; object vkTrue = true; object vkDynamic = 2; object vkMissing = System.Reflection.Missing.Value; // Let's make the word application not visible // vkWordApp.Visible = false; // vkWordApp.Activate(); // Let's copy the document File.Copy(fromFileName.ToString(), destinationFileName.ToString(), true); // Let's open the DESTINATION document Word.Document vkMyDoc; try { vkMyDoc = vkWordApp.Documents.Open( ref destinationFileName, ref vkMissing, ref vkReadOnly, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkVisible); } catch (Exception ex) { ret.ReturnCode = -1; ret.ReasonCode = 1000; ret.Message = "Error copying file."; ret.Contents = ex; return(ret); } foreach (var t in tag) { if (t.TagType == Utils.InformationType.FIELD || t.TagType == Utils.InformationType.VARIABLE) { FindAndReplace(t.Tag, t.TagValue, 1, vkWordApp, vkMyDoc); } else { insertPicture(vkMyDoc, t.TagValue, t.Tag); } } // 24/10/2010 - Modificado quando troquei a referencia do Word // //vkMyDoc.Sections.Item( 1 ).Headers.Item( Word.WdHeaderFooterIndex.wdHeaderFooterPrimary ).Range.Fields.Update(); //vkMyDoc.Sections.Item( 1 ).Footers.Item( Word.WdHeaderFooterIndex.wdHeaderFooterPrimary ).Range.Fields.Update(); try { vkMyDoc.Save(); } catch (Exception ex) { uioutput.AddOutputMessage("(Word) ERROR in file: " + fromFileName + " --- Message: " + ex.ToString()); } // close the new document vkMyDoc.Close(); // Trying to release COM object System.Runtime.InteropServices.Marshal.ReleaseComObject(vkMyDoc); return(ret); }