From d327ab08afa73c0ddc0b6724a9c4d4dae01a7418 Mon Sep 17 00:00:00 2001 From: Jake Date: Tue, 26 Jul 2022 20:01:25 +0000 Subject: [PATCH] B2022-083: Support Conditional RO Values --- PROMS/LBWordLibrary/LBComObject.cs | 3 +- .../dlgApproveProcedure.cs | 40 +- PROMS/VEPROMS User Interface/frmVEPROMS.cs | 787 ++++++--- .../Config/DocVersionConfig.cs | 27 +- .../Config/ROFSTLookup.cs | 1263 +++++++------- .../Extension/DocVersionExt.cs | 72 +- .../Extension/DocumentExt.cs | 1462 +++++++++++------ .../VEPROMS.CSLA.Library/Extension/ItemExt.cs | 6 + .../VEPROMS.CSLA.Library/Extension/PdfExt.cs | 12 +- .../VEPROMS.CSLA.Library/Generated/PdfInfo.cs | 2 +- PROMS/Volian.Base.Library/TmpFile.cs | 4 +- PROMS/Volian.Controls.Library/DisplayRO.cs | 244 +-- PROMS/Volian.Controls.Library/StepRTB.cs | 26 +- .../Volian.Controls.Library/StepTabRibbon.cs | 28 +- PROMS/Volian.Print.Library/PDFReport.cs | 225 +-- .../Volian.Print.Library/VlnSvgPageHelper.cs | 212 +-- 16 files changed, 2670 insertions(+), 1743 deletions(-) diff --git a/PROMS/LBWordLibrary/LBComObject.cs b/PROMS/LBWordLibrary/LBComObject.cs index 989e45d7..dc51052f 100644 --- a/PROMS/LBWordLibrary/LBComObject.cs +++ b/PROMS/LBWordLibrary/LBComObject.cs @@ -198,7 +198,8 @@ namespace LBWordLibrary } public String Text { - get { return (GetProperty("Text").ToString()); } + //B2022-083: Support Conditional RO Values + get { return Convert.ToString(GetProperty("Text")); } set { SetProperty("Text", value); } } public LBWdSelectionType Type diff --git a/PROMS/VEPROMS User Interface/dlgApproveProcedure.cs b/PROMS/VEPROMS User Interface/dlgApproveProcedure.cs index a8415b9b..b7c026f7 100644 --- a/PROMS/VEPROMS User Interface/dlgApproveProcedure.cs +++ b/PROMS/VEPROMS User Interface/dlgApproveProcedure.cs @@ -197,11 +197,13 @@ namespace VEPROMS { OwnerInfo oi = OwnerInfo.GetByItemID(pi.ItemID, CheckOutType.Procedure); pi.MyDocVersion.DocVersionConfig.SelectedSlave = _MyDocVersion.DocVersionConfig.SelectedSlave; + if (clbMore.Items.Contains(pi.DisplayNumber)) { if (!dpl.Contains(pi.DisplayNumber)) dpl.Add(pi.DisplayNumber); //C2020-036 add to duplicate proc number list continue; } + // B2018-083: check for null MySessionInfo. if (oi != null && MySessionInfo != null && oi.SessionID != MySessionInfo.SessionID) { @@ -210,17 +212,22 @@ namespace VEPROMS } else clbMore.Items.Add(pi.DisplayNumber); + tmpProcedures.Add(pi.DisplayNumber, pi); } } } + if (dpl.Count > 0) return false; // C2018-025 cannot load list of procedure - duplicate proc numbers + for (int i = 0; i < clbMore.Items.Count; i++) { ProcedureInfo pi = GetProcedureInfoByKey(clbMore.Items[i].ToString()); clbMore.SetItemChecked(i, _MyApproval.ProcedureExists(pi)); } + lblMore.Text = string.Format("{0} Procedures, {1} Selected", clbMore.Items.Count, clbMore.CheckedItems.Count); + return true; } @@ -247,20 +254,23 @@ namespace VEPROMS setupLablesAndSwitches(); // C2018-008 redesign of user interface SetupMyApproval(); } + private Dictionary tmpProcedures = new Dictionary(); - private ProcedureInfo GetProcedureInfoByKey(string key) - { + private ProcedureInfo GetProcedureInfoByKey(string key) + { if (key.Contains(" Checked out to ")) key = key.Substring(0, key.IndexOf(" Checked out to ")); // B2019-048: after running consistency check - inconsistency text was added to string in dialog. Remove that text // if in key so that it can be used to find procedure in procedure list (was crashing): if (key.Contains(" - (")) key = key.Substring(0, key.LastIndexOf(" - (")); + if (tmpProcedures.ContainsKey(key)) - return tmpProcedures[key]; - else - return tmpProcedures[GetDisplayNumberOnly(key)]; - } + return tmpProcedures[key]; + else + return tmpProcedures[GetDisplayNumberOnly(key)]; + } + public dlgApproveProcedure(DocVersionInfo myDocVersion, bool selectSome, frmVEPROMS myFrmVEPROMS) // approve some procedures { MyFrmVEPROMS = myFrmVEPROMS;// Save frmVEPROMS for Import to shutoff SessionPing @@ -280,7 +290,8 @@ namespace VEPROMS InitializePanelSelect(); _initializing = false; } - public dlgApproveProcedure(ProcedureInfo myProcedure, frmVEPROMS myFrmVEPROMS) // approve sigle (selected from tree view) + + public dlgApproveProcedure(ProcedureInfo myProcedure, frmVEPROMS myFrmVEPROMS) // approve single (selected from tree view) { MyFrmVEPROMS = myFrmVEPROMS;// Save frmVEPROMS for Import to shutoff SessionPing _MyApproval = new ApprovalInfo(myFrmVEPROMS);// Save frmVEPROMS for Import to shutoff SessionPing @@ -332,6 +343,7 @@ namespace VEPROMS approvalProcedureBindingSource.ResetBindings(false); //this.ConsistencyPrintRequest -= new DisplayConsistencyReportEvent(dlgApproveProcedure_ConsistencyPrintRequest); } + private string GetMaxRevNumber() { string mrn = string.Empty; @@ -343,6 +355,7 @@ namespace VEPROMS } return mrn; } + void dlgApproveProcedure_ConsistencyPrintRequest(object sender, ConsistencyReportArgs args) { foreach (ProcedureInfo pi in args.MyItems) @@ -350,6 +363,7 @@ namespace VEPROMS PDFConsistencyCheckReport rpt = new PDFConsistencyCheckReport(args.ReportName, args.MyItems, args.MyDocVersion); //B2020-020 needed to pass in DocVersion to get paper size from format rpt.BuildReport(); } + private void SetupComboBoxes() { RevTypes rt = new RevTypes(); @@ -362,6 +376,7 @@ namespace VEPROMS revTypeBindingSource.DataSource = rt; stageInfoBindingSource.DataSource = StageInfoList.Get(); } + private void btnApprove_Click(object sender, EventArgs e) { this.Cursor = Cursors.WaitCursor; @@ -369,6 +384,7 @@ namespace VEPROMS this.DialogResult = DialogResult.None; this.Cursor = Cursors.Default; } + // C2018-008 redesign of user interface // -- Note that the Revison Type data source is still connected (revTypeBindingSource) - commented out for documentatin purposes //private void cmbRevisionType_SelectedIndexChanged(object sender, EventArgs e) @@ -376,11 +392,13 @@ namespace VEPROMS // RevType rt = cmbRevisionType2.SelectedItem as RevType; // _MyApproval.RevType = rt.TypeID; //} + private void cmbRevisionStage_SelectedIndexChanged(object sender, EventArgs e) { StageInfo si = cmbRevisionStage2.SelectedItem as StageInfo; _MyApproval.RevStage = si.StageID; } + private void clbMore_ItemCheck(object sender, ItemCheckEventArgs e) { ProcedureInfo pi = GetProcedureInfoByKey(clbMore.Items[e.Index].ToString()); @@ -397,6 +415,7 @@ namespace VEPROMS btnCheckMore.Enabled = true; } } + private void UpdateMyApproval() { SetupComboBoxes(); @@ -419,10 +438,12 @@ namespace VEPROMS SetupMyApproval(); RefreshCount(); // B2021-015: select/clear all not populating left panel & count not refreshed. } + private void btnCheck_Click(object sender, EventArgs e) { UpdateClbMore(); } + private ItemInfoList _MyItemInfoList; private void UpdateClbMore() { @@ -510,18 +531,21 @@ namespace VEPROMS } Application.DoEvents(); } + private void btnAll_Click(object sender, EventArgs e) { for (int i = 0; i < clbMore.Items.Count; i++) clbMore.SetItemChecked(i, true); UpdateMyApproval(); // B2021-015: select/clear all not populating left panel & count not refreshed. } + private void btnClear_Click(object sender, EventArgs e) { for (int i = 0; i < clbMore.Items.Count; i++) clbMore.SetItemChecked(i, false); UpdateMyApproval(); // B2021-015: select/clear all not populating left panel & count not refreshed. } + private int _LastIndex = -1; private void clbMore_MouseMove(object sender, MouseEventArgs e) { @@ -563,6 +587,7 @@ namespace VEPROMS s = s.Substring(0, d); //B2018-109 remvoed the call ".Trim()". had a procedure that began with a space and was being used as such everywhere else in the approveal logic return s; } + private bool _DoingConsistencyCheck = false; // C2018-008 redesign of user interface private void btnCheckMore_Click(object sender, EventArgs e) { @@ -574,6 +599,7 @@ namespace VEPROMS btnCheckMore.Enabled = false; } + private void btnReportMore_Click(object sender, EventArgs e) { OnConsistencyPrintRequest(new ConsistencyReportArgs(Volian.Base.Library.VlnSettings.TemporaryFolder + @"\MyConsistency.pdf", _MyItemInfoList, _MyDocVersion)); //B2020-020 needed to pass in DocVersion to get paper size from format diff --git a/PROMS/VEPROMS User Interface/frmVEPROMS.cs b/PROMS/VEPROMS User Interface/frmVEPROMS.cs index 123927ca..b733b6ae 100644 --- a/PROMS/VEPROMS User Interface/frmVEPROMS.cs +++ b/PROMS/VEPROMS User Interface/frmVEPROMS.cs @@ -32,7 +32,9 @@ namespace VEPROMS #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion + #region PropertiesVariables + private int securityRole; private bool _panelExpandedChanging = false; Color _CommentTitleBckColor; @@ -41,15 +43,18 @@ namespace VEPROMS public FindReplace dlgFindReplace = null; public VlnSpellCheck SpellChecker = null; private Int64 _LastContentChange; + public Int64 LastContentChange { get { return _LastContentChange; } set { _LastContentChange = value; } } + public void RefreshLastChange() { lblLastChange.Text = string.Format("Last Change: {0}", MySessionInfo.LastContentChange - this.LastContentChange); } + public StepTabPanel SelectedStepTabPanel { get @@ -61,7 +66,7 @@ namespace VEPROMS _SelectedStepTabPanel = value; if (value == null) // DSO Tab Panel { - dlgFindReplace.Visible = false; // Find/Replace dialog should not be visable for DSO tab panels + dlgFindReplace.Visible = false; // Find/Replace dialog should not be visible for DSO tab panels if (tc.SelectedDisplayTabItem != null && tc.SelectedDisplayTabItem.MyItemInfo != null) // 2nd part is for unassociated libdocs SelectedDVI = tc.SelectedDisplayTabItem.MyItemInfo.MyDocVersion; else @@ -69,7 +74,7 @@ namespace VEPROMS } else // Step Tab Panel { - // The following line was broken into separate lines because a NullReferenceError was occuring. + // The following line was broken into separate lines because a NullReferenceError was occurring. // Now we should be able to tell what is wrong by which line causes the Null Reference Error // RHM 20101217 //SelectedDVI = value.MyStepPanel.MyProcedureItemInfo.MyProcedure.ActiveParent as DocVersionInfo; @@ -93,29 +98,32 @@ namespace VEPROMS void MyStepTabRibbon_ContActionSummaryRequest(object sender, StepTabRibbonEventArgs args) { DialogResult dr = System.Windows.Forms.DialogResult.Yes; + ProcedureInfo piThis = null; if (_CurrentItem != null) piThis = _CurrentItem.MyProcedure; + ProcedureInfo pi = args.Proc as ProcedureInfo; if (piThis != null && pi.ItemID != piThis.ItemID) pi = piThis; - //added by jcb 20130718 to support create pdf button when multiunit and user selects a unit + //added by jcb 20130718 to support create pdf button when multi-unit and user selects a unit pi.MyDocVersion.DocVersionConfig.SelectedSlave = pi.ProcedureConfig.SelectedSlave; - //end added by jcb 20130718 + if (pi == null) return; + DlgPrintProcedure prnDlg = new DlgPrintProcedure(pi); - //added by jcb 20130718 to support create pdf button when multiunit and user selects a unit + + //added by jcb 20130718 to support create pdf button when multi-unit and user selects a unit prnDlg.SelectedSlave = pi.ProcedureConfig.SelectedSlave == 0 ? -1 : pi.ProcedureConfig.SelectedSlave; prnDlg.MySessionInfo = MySessionInfo; - //end added by jcb 20130718 prnDlg.Automatic = true; prnDlg.CreateContinuousActionSummary = true; prnDlg.OpenAfterCreate = (dr == System.Windows.Forms.DialogResult.Yes); prnDlg.Prefix = "CASTMP_"; // A temporary procedure PDF is created to grab page numbers prnDlg.SetupForProcedure(); prnDlg.CreatePDF(); - //added by jcb 20130718 to support create pdf button when multiunit and user selects a unit + + //added by jcb 20130718 to support create pdf button when multi-unit and user selects a unit pi.MyDocVersion.DocVersionConfig.SelectedSlave = 0; - //end added by jcb 20130718 } public DocVersionInfo SelectedDVI @@ -132,9 +140,7 @@ namespace VEPROMS InitiateDisplayReports(false); } } - // TODO: Should the following be an info - // For the initial release, we are assuming there will be only one rofst fro a docversion. Changes - // will be needed here if more than 1. + private ROFstInfo _SelectedROFst; public ROFstInfo SelectedROFst { @@ -153,57 +159,63 @@ namespace VEPROMS } set { _SelectedROFst = value; } } + #endregion + private frmVEPROMS _MyParent; public frmVEPROMS MyParent { get { return _MyParent; } set { _MyParent = value; } } - //private FolderInfo _MyFolder = null; - //public FolderInfo MyFolder - //{ - // get { return _MyFolder; } - // set { _MyFolder = value; } - //} - private DocVersionInfo _MyDocVersion = null; + private DocVersionInfo _MyDocVersion = null; public DocVersionInfo MyDocVersion { get { return _MyDocVersion; } set { _MyDocVersion = value; } } + // C2015-022 setup the child PROMS window public frmVEPROMS(frmVEPROMS myParent, DocVersionInfo myDocVersion) { MyParent = myParent; MyDocVersion = myDocVersion; InitializeComponent(); + // B2019-082 set the date format on the VEPROMS.exe thread to U.S. for i/o of a date string // this is to correct an issue for a UAE customer who could not open some procedures due to the desktop date setting using the "DD/MM/YYYY" instead of the "MM/DD/YYYY" format // NOTE: not doing the "Using System.Threading;" statement at beginning of file because it conflicts with the declaration of the "Timer" variable System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US"); displayRO.TabControl = tc; // B2019-043 this was being passed in as a parameter for DisplayRO which caused issues with the Visual Studio designer + SetupFolder(MyDocVersion.FolderID); tc.MySessionInfo = MyParent.MySessionInfo; displaySearch1.TopFolderID = myDocVersion.FolderID; SelectedDVI = myDocVersion; tc.VersionID = myDocVersion.VersionID; + tc.SeparateWindows = true; // need to set this in child window for goto Outside Transitions displayBookMarks.MyBookMarks = MyParent.displayBookMarks.MyBookMarks; displayBookMarks.SetupBookMarks(); // setup bookmarks in the child window + tc.MyCopyStep = myParent.tc.MyCopyStep; // copy the copystep info to the child window + (tv.Nodes[0] as VETreeNode).InChildWindow = true; // tells us this folder's tree nodes are in the child window } + public void OpenItem(ItemInfo myItemInfo) { tc.OpenItem(myItemInfo); } + public void RefreshItem(ItemInfo myItemInfo) { tc.RefreshItem(myItemInfo); } + private E_UCFImportOptions _UCFImportOptionsFromSettings; + public frmVEPROMS() { // The following Try/Catch was added to protect against a problem seen by Kathy and Michelle @@ -222,22 +234,31 @@ namespace VEPROMS catch (Exception ex) { _MyLog.Error(ex.GetType().Name + " - " + ex.InnerException, ex); + if (ex.Message.StartsWith("Configuration system failed to initialize")) { string filename = ex.InnerException.Message; filename = filename.Substring(filename.IndexOf("(") + 1); filename = filename.Substring(0, filename.IndexOf("user.config") + 11); + FileInfo myfile = new FileInfo(filename); myfile.Delete(); + MessageBox.Show("Config file was corrupt, it has been deleted.\r\nTry Again", "Corrupt config file", MessageBoxButtons.OK, MessageBoxIcon.Error); + System.Diagnostics.Process.GetCurrentProcess().Kill(); } } + // If first time close any remaining WinWords. These will sometimes get hung in memory and cause problems. if (System.Diagnostics.Process.GetProcessesByName(System.Diagnostics.Process.GetCurrentProcess().ProcessName).Length == 1) + { Volian.MSWord.WordDoc.KillWordApps(); + } + // cleanup from previous run: Volian.Base.Library.TmpFile.RemoveAllTmps(); + if (VlnSettings.DebugMode) { //use local data (for development/debug mode) @@ -263,16 +284,18 @@ namespace VEPROMS else VEPROMS.CSLA.Library.Database.ConnectionName = "VEPROMS_LOCAL"; } + InitializeComponent(); + // B2019-082 set the date format on the VEPROMS.exe thread to U.S. for i/o of a date string // this is to correct an issue for a UAE customer who could not open some procedures due to the desktop date setting using the "DD/MM/YYYY" instead of the "MM/DD/YYYY" format // NOTE: not doing the "Using System.Threading;" statement at beginning of file because it conflicts with the declaration of the "Timer" variable System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US"); + displayRO.TabControl = tc; // B2019-043 this was being passed in as a parameter for DisplayRO which caused issues with the Visual Studio designer bottomProgBar.ValueChanged += new EventHandler(bottomProgBar_ValueChanged); - // When creating an XY Plot, a System.Drawing.Graphics is needed and it requires a form. Use the main - // form. + // When creating an XY Plot, a System.Drawing.Graphics is needed and it requires a form. Use the main form. if (VlnSettings.DebugMode) { MSWordToPDF.DebugStatus = 1; @@ -283,101 +306,107 @@ namespace VEPROMS MSWordToPDF.DebugStatus = 0; MSWordToPDF.OverrideColor = Color.Transparent; } + MSWordToPDF.FormForPlotGraphics = this; // set the color of the ribbon RibbonPredefinedColorSchemes.ChangeOffice2007ColorTable((eOffice2007ColorScheme)Settings.Default.SystemColor); - - // LATER: get the user setting to control what is displayed for each tree node - // The logic is in the ToString() functions in FolderExt.cs and DocVersionExt.cs - //the GetFolder(1) function will read in the frist node (using ToString() to assign node text) - - // Get the saved Tree Node Diplay settings - //if (Settings.Default["UseNameOnTreeNode"]) - //{ - //} - //if (Settings.Default["UseTitleOnTreeNode"]) - //{ - //} cmbFont.DataSource = FontFamily.Families; cmbFont.DisplayMember = "Name"; cmbFont.SelectedIndex = -1; string[] parameters = System.Environment.CommandLine.Split(" ".ToCharArray()); string db = Volian.Base.Library.VlnSettings.GetDB(); + if (db != null) Database.SelectedDatabase = db; - if (Properties.Settings.Default["DefaultDB"] != string.Empty) //B2018-129 Most Recently Used list was being cleared. Needed to remove a (string) typecase in the IF statement + + //B2018-129 Most Recently Used list was being cleared. Needed to remove a (string) type case in the IF statement + if (!string.IsNullOrEmpty((string)Properties.Settings.Default["DefaultDB"])) Database.LastDatabase = Properties.Settings.Default.DefaultDB; + // Setup the Context menu for DisplaySearch including the symbols displaySearch1.SetupContextMenu(); displaySearch1.SearchComplete += displaySearch1_SearchComplete; + if (!FormatInfo.HasLatestChanges()) throw new Exception("Inconsistent Formats"); + if (!ItemAuditInfo.IsChangeManagerVersion()) throw new Exception("Inconsistent Data"); + // set a static variable to the PROMS Base format (BASEall.xml) // this is used to resolve Global Search bug B2014-057 so that we can get to the symbol list when no DocVersion is selected if (FormatInfo.PROMSBaseFormat == null) throw new Exception("Could not set PROMSBaseFormat"); + if ((Database.LastDatabase ?? "") != (Database.SelectedDatabase ?? "")) { if (Properties.Settings.Default.VersionWindows != null) Properties.Settings.Default.VersionWindows.Clear(); + Properties.Settings.Default.MRIList = null; Properties.Settings.Default.DefaultDB = Database.SelectedDatabase; Properties.Settings.Default.Save(); } + displayBookMarks.SetupBookMarks(); DateTime dtSunday = DateTime.Now.AddDays(-((int)DateTime.Now.DayOfWeek)); string c = Database.DBServer; + // D2017-260 - Use a prefix of the server name combined with the database name for temporary MSWord sections DSOFile.TempFilePrefix = System.Text.RegularExpressions.Regex.Replace(System.Text.RegularExpressions.Regex.Replace(c, @"([^[\]]*) \[.*\]", "$1"), @"[\#\~\%\@\[\]\(\)\{\}\-. \\*<>:;""/?|]+", "_"); ChangeLogFileName("LogFileAppender", Database.ActiveDatabase + " " + dtSunday.ToString("yyyyMMdd") + " ErrorLog.txt"); + // B2019-107 Error Log message for inconsistent PromsFixes _MyLog.InfoFormat("\r\nSession Beginning\r\n<===={0}[SQL:{1:yyMM.ddHH}]====== User: {2}/{3} Started {4} ===============>{5}" , Application.ProductVersion, Database.RevDate, Environment.UserDomainName, Environment.UserName, DateTime.Now.ToString("dddd MMMM d, yyyy h:mm:ss tt"), FormatInfo.Failed ?? ""); + foreach (string parameter in parameters) { if (parameter.ToUpper().StartsWith("/UF=")) UpdateFormats(parameter.Substring(4)); + else if (parameter.ToUpper().StartsWith("/UF")) UpdateFormats(null); } + SetupFolder(1); + tc.VersionID = 0; tc.SeparateWindows = Properties.Settings.Default.SeparateWindows; tv.PauseRefresh += tv_PauseRefresh; tv.UnPauseRefresh += tv_UnPauseRefresh; - } + + void displaySearch1_SearchComplete(object sender, DisplaySearchEventArgs args) { ProgBarText = string.Format("{0} Seconds", args.HowLong.TotalSeconds); } + private bool _PauseRefresh = false; public bool PauseRefresh { get { return _PauseRefresh; } - set - { - //_MyLog.WarnFormat(value ? "=== Pause" : "=== UnPause"); - _PauseRefresh = value; - } + set { _PauseRefresh = value; } } + void tv_UnPauseRefresh(object sender, vlnTreeSectionInfoEventArgs args) { - //_MyLog.WarnFormat("Unpause"); PauseRefresh = false; } + void tv_PauseRefresh(object sender, vlnTreeSectionInfoEventArgs args) { //_MyLog.WarnFormat("Pause"); //PauseRefresh = true; } + private void SetupFolder(int folderID) { VETreeNode tn = VETreeNode.GetFolder(folderID); + tv.Nodes.Add(tn); tv.NodePSI += new vlnTreeViewPSIEvent(tv_NodePSI); tv.NodeSI += new vlnTreeViewSIEvent(tv_NodeSI); @@ -395,30 +424,37 @@ namespace VEPROMS tv.GetChangeId += new vlnTreeViewGetChangeIdEvent(tv_GetChangeId); tv.NodeCopy += new vlnTreeViewEvent(tv_NodeCopy); tv.ClipboardStatus += new vlnTreeViewClipboardStatusEvent(tv_ClipboardStatus); + tv.ProgressBar = bottomProgBar; tc.ItemPaste += new StepPanelItemPastedEvent(tc_ItemPasted); + displayHistory.HistorySelectionChanged += new DisplayHistoryEvent(displayHistory_HistorySelectionChanged); _CommentTitleBckColor = epAnnotations.TitleStyle.BackColor1.Color; if (!btnAnnoDetailsPushPin.Checked) epAnnotations.Expanded = false; + infoPanel.Expanded = false; toolsPanel.Expanded = false; displayTags.Visible = false; ribbonControl1.ExpandedChanged += new EventHandler(ribbonControl1_ExpandedChanged); dlgFindReplace = new FindReplace(); SpellChecker = new VlnSpellCheck(); + displaySearch1.PrintRequest += new DisplaySearchEvent(displaySearch1_PrintRequest); displayHistory.ChronologyPrintRequest += new DisplayHistoryReportEvent(displayHistory_ChronologyPrintRequest); displayHistory.SummaryPrintRequest += new DisplayHistoryReportEvent(displayHistory_SummaryPrintRequest); displayHistory.AnnotationRestored += new AnnotationRestoredHandler(displayHistory_AnnotationRestored); displayReports.PrintRequest += new DisplayReportsEvent(displayReports_PrintRequest); + this.Activated += new EventHandler(frmVEPROMS_Activated); + VlnSettings.StepTypeToolType = Settings.Default.StepTypeToolTip; displayLibDocs.PrintRequest += new DisplayLibDocEvent(displayLibDocs_PrintRequest); ContentInfo.InfoChanged += new ContentInfoEvent(RefreshDisplayHistory); AnnotationInfo.InfoChanged += new AnnotationInfoEvent(RefreshDisplayHistory); ItemInfo.InfoRestored += new ItemInfoEvent(RefreshDisplayHistory); ItemInfo.ItemDeleted += new ItemInfoEvent(RefreshDisplayHistory); + tv.PrintProcedure += new vlnTreeViewEvent(tv_PrintProcedure); tv.PrintAllProcedures += new vlnTreeViewEvent(tv_PrintAllProcedures); tv.ApproveProcedure += new vlnTreeViewEvent(tv_ApproveProcedure); @@ -428,31 +464,35 @@ namespace VEPROMS tv.RefreshCheckedOutProcedures += new vlnTreeViewEvent(tv_RefreshCheckedOutProcedures); tv.ProcedureCheckedOutTo += new vlnTreeViewEvent(tv_ProcedureCheckedOutTo); tv.ViewPDF += new vlnTreeViewPdfEvent(tv_ViewPDF); + displayApplicability.ApplicabilityViewModeChanged += new DisplayApplicability.DisplayApplicabilityEvent(displayApplicability_ApplicabilityViewModeChanged); + tv.ExportImportProcedureSets += new vlnTreeViewEvent(tv_ExportImportProcedureSets); tv.PrintTransitionReport += new vlnTreeViewEvent(tv_PrintTransitionReport); tv.ProcessingComplete += tv_ProcessingComplete; tv.Processing += tv_Processing; tv.CreateContinuousActionSummary += new vlnTreeViewEvent(tv_CreateContinuousActionSummary); tv.SelectDateToStartChangeBars += tv_SelectDateToStartChangeBars; + displayBookMarks.ResetBookMarksInPROMSWindows += displayBookMarks_ResetBookMarksInPROMSWindows; } // Part of Separate Windows upgrade C2015-022 - // Extend changeds to BookMark information to all of the child windows + // Extend Changes to BookMark information to all of the child windows void displayBookMarks_ResetBookMarksInPROMSWindows(object sender, EventArgs args) { foreach (int k in PROMSWindowForms.Keys) { frmVEPROMS tmp = PROMSWindowForms[k]; + if (tmp.MyDocVersion.VersionID != this.SelectedDVI.VersionID) tmp.displayBookMarks.ResetBookMarkList(); + else if (tmp.MyParent != null) tmp.MyParent.displayBookMarks.ResetBookMarkList(); } } - void tv_SelectDateToStartChangeBars(object sender, vlnTreeEventArgs args) { ProcedureInfo pi = (args.Node as VETreeNode).VEObject as ProcedureInfo; @@ -480,36 +520,45 @@ namespace VEPROMS get { return _SkipRefresh; } set { _SkipRefresh = value; } } + void tv_Processing(object sender, vlnTreeStatusEventArgs args) { SkipRefresh = args.MyStatus; + if (args.MyStatus) bottomProgBar.ColorTable = eProgressBarItemColor.Paused; else bottomProgBar.ColorTable = eProgressBarItemColor.Normal; + bottomProgBar.Text = args.MyMessage; bottomProgBar.TextVisible = true; + Application.DoEvents(); } + void tv_ProcessingComplete(object sender, vlnTreeTimeEventArgs args) { bottomProgBar.Text = string.Format("{0} seconds - {1}", args.MyTimeSpan.TotalSeconds, args.MyMessage); Application.DoEvents(); } + void bottomProgBar_ValueChanged(object sender, EventArgs e) { if (bottomProgBar.Value < 10 && bottomProgBar.ColorTable != eProgressBarItemColor.Normal) bottomProgBar.ColorTable = eProgressBarItemColor.Normal; } + string tv_GetChangeId(object sender, vlnTreeItemInfoEventArgs args) { tc.HandleChangeId(args.MyItemInfo, null); return tc.ChgId; } + ItemInfo tv_ClipboardStatus(object sender, vlnTreeEventArgs args) { return tc.MyCopyStep; } + void tv_NodeCopy(object sender, vlnTreeEventArgs args) { VETreeNode tn = args.Node as VETreeNode; @@ -517,19 +566,24 @@ namespace VEPROMS tc.MyCopyStep = ii; tc_CopyStepSelected(sender, null); // C2015-022 set copy step info in the child windows } + void tv_PrintTransitionReport(object sender, vlnTreeEventArgs args) { FolderInfo fi = null; ProcedureInfo pi = null; + if ((args.Node as VETreeNode).VEObject is FolderInfo) fi = (args.Node as VETreeNode).VEObject as FolderInfo; + if ((args.Node as VETreeNode).VEObject is ProcedureInfo) pi = (args.Node as VETreeNode).VEObject as ProcedureInfo; + if (fi != null) //working with folder { dlgTransitionReport dlg = new dlgTransitionReport(fi); dlg.ShowDialog(this); } + if (pi != null) //working with procedure { this.Cursor = Cursors.WaitCursor; @@ -545,18 +599,24 @@ namespace VEPROMS FolderInfo fi = null; DocVersionInfo dvi = null; ProcedureInfo pi = null; + if ((args.Node as VETreeNode).VEObject is FolderInfo) fi = (args.Node as VETreeNode).VEObject as FolderInfo; + if ((args.Node as VETreeNode).VEObject is DocVersionInfo) dvi = (args.Node as VETreeNode).VEObject as DocVersionInfo; + if ((args.Node as VETreeNode).VEObject is ProcedureInfo) pi = (args.Node as VETreeNode).VEObject as ProcedureInfo; + if (fi != null) { string msg = string.Empty; + // B2018-023: If exporting a procedure set, and someone else is in the database (but not this folder) // don't stop the export (CheckOutType.Session was changed to CheckOutType.Folder). bool ok = MySessionInfo.CanCheckOutItem(fi.FolderID, CheckOutType.Folder, ref msg); + //bool ok = MySessionInfo.CanCheckOutItem(fi.FolderID, (args.Index == 0)? CheckOutType.Folder : CheckOutType.Session, ref msg); if (!ok) { @@ -571,15 +631,21 @@ namespace VEPROMS //int ownerid = MySessionInfo.CheckOutItem(fi.FolderID, (args.Index == 0) ? CheckOutType.Folder : CheckOutType.Session); dlgExportImport dlg = new dlgExportImport(args.Index == 0 ? "Export" : "Import", fi, this, (E_UCFImportOptions)Properties.Settings.Default.UCFImportOpt);//Added frmVEPROMS Parameter dlg.ShowDialog(this); + MySessionInfo.CheckInItem(ownerid); + if (args.Index == 1 && dlg.MyNewFolder != null) + { tv.AddNewNode(dlg.MyNewFolder); + } } } + if (dvi != null) { string msg = string.Empty; bool ok = MySessionInfo.CanCheckOutItem(dvi.VersionID, CheckOutType.DocVersion, ref msg); + if (!ok) { MessageBox.Show(this, msg, "Import Procedure Unavailable"); @@ -593,22 +659,28 @@ namespace VEPROMS MessageBox.Show("Prior to Importing Procedures you must set the Referenced Object Database", "No RO Database set", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } + int ownerid = MySessionInfo.CheckOutItem(dvi.VersionID, CheckOutType.DocVersion); dlgExportImport dlg = new dlgExportImport("Import", dvi, this, (E_UCFImportOptions)Properties.Settings.Default.UCFImportOpt);//Added frmVEPROMS Parameter dlg.MyNewProcedure = null; dlg.ExternalTransitionItem = null; dlg.ShowDialog(this); + MySessionInfo.CheckInItem(ownerid); + if (dlg.MyNewProcedure != null) tv.AddNewNode(dlg.MyNewProcedure); + if (dlg.ExternalTransitionItem != null) tc.OpenItem(dlg.ExternalTransitionItem); } } + if (pi != null) { string msg = string.Empty; bool ok = MySessionInfo.CanCheckOutItem(pi.ItemID, CheckOutType.Procedure, ref msg); + if (!ok) { MessageBox.Show(this, msg, "Export Procedure Unavailable"); @@ -618,6 +690,7 @@ namespace VEPROMS int ownerid = MySessionInfo.CheckOutItem(pi.ItemID, CheckOutType.Procedure); dlgExportImport dlg = new dlgExportImport("Export", pi, this, (E_UCFImportOptions)0);//Added frmVEPROMS Parameter dlg.ShowDialog(this); + MySessionInfo.CheckInItem(ownerid); } } @@ -640,14 +713,17 @@ namespace VEPROMS case ROImageCompressionEventType.Complete: ProgBarText = "Compressing Complete"; break; + case ROImageCompressionEventType.Initialize: ProgBarMax = args.Total; ProgBarText = "Compressing RO Images"; break; + case ROImageCompressionEventType.Update: ProgBarValue = args.Current; ProgBarText = args.FileName; break; + default: break; } @@ -660,24 +736,26 @@ namespace VEPROMS get { return frmVEPROMS._ErrorLogFileName; } set { frmVEPROMS._ErrorLogFileName = value; } } + static bool ChangeLogFileName(string AppenderName, string NewFilename) { log4net.Repository.ILoggerRepository RootRep; RootRep = log4net.LogManager.GetRepository(); + foreach (log4net.Appender.IAppender iApp in RootRep.GetAppenders()) { - if (iApp.Name.CompareTo(AppenderName) == 0 - && iApp is log4net.Appender.FileAppender) + if ((iApp.Name.CompareTo(AppenderName) == 0) && (iApp is log4net.Appender.FileAppender)) { log4net.Appender.FileAppender fApp = (log4net.Appender.FileAppender)iApp; string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); - //fApp.File = folderPath + @"\VEPROMS\" + (Volian.Base.Library.VlnSettings.GetCommand("U","") + "_").TrimStart("_".ToCharArray()) + NewFilename; fApp.File = folderPath + @"\VEPROMS\" + (Volian.Base.Library.VlnSettings.GetCommand("prefix", "") + "_").TrimStart("_".ToCharArray()) + NewFilename; ErrorLogFileName = fApp.File; fApp.ActivateOptions(); + return true; // Appender found and name changed to NewFilename } } + return false; } @@ -685,6 +763,7 @@ namespace VEPROMS { if (tc.SelectedDisplayTabItem == null) return; StepPanel pnl = tc.SelectedDisplayTabItem.MyStepTabPanel.MyStepPanel; + if (pnl != null) { pnl.ApplDisplayMode = displayApplicability.ViewMode; @@ -695,11 +774,14 @@ namespace VEPROMS void tv_ViewPDF(object sender, vlnTreeViewPdfArgs args) { byte[] buffer; + if (args.MyWatermark != string.Empty) buffer = PromsPrinter.WatermarkPDF(args.MyBuffer, args.MyWatermark); else buffer = args.MyBuffer; + string fileName = Volian.Base.Library.VlnSettings.TemporaryFolder + "\\" + args.MyFilename; + try { FileStream fs = new FileStream(fileName, FileMode.Create); @@ -710,13 +792,14 @@ namespace VEPROMS catch (Exception ex) { StringBuilder sb = new StringBuilder(); + sb.AppendLine("Could not create"); sb.AppendLine(); sb.AppendLine(fileName + "."); sb.AppendLine(); sb.AppendLine("If it is open, close and retry."); + MessageBox.Show(sb.ToString(), "Error on CreatePdf", MessageBoxButtons.OK, MessageBoxIcon.Warning); - // MessageBox.Show("Could not create " + fileName + ". If it is open, close and retry.", "Error on CreatePdf"); } } @@ -729,12 +812,16 @@ namespace VEPROMS { DocVersionInfo dvi = (args.Node as VETreeNode).VEObject as DocVersionInfo; if (dvi == null) return; + this.Cursor = Cursors.WaitCursor; + ItemInfoList iil = ItemInfoList.GetAllInconsistencies(dvi.VersionID); Volian.Print.Library.PDFConsistencyCheckReport rpt = new Volian.Print.Library.PDFConsistencyCheckReport(Volian.Base.Library.VlnSettings.TemporaryFolder + @"\AllInconsistencies.pdf", iil, dvi); //B2020-020 needed to pass in DocVersion to get paper size from format rpt.BuildAllReport(dvi); + this.Cursor = Cursors.Default; } + //C2020-036 returns a string of duplicate procedure numbers separated by newlines for use in FlexibleMessageBox private string dupProcList { @@ -750,6 +837,7 @@ namespace VEPROMS return rtn; } } + private List dpl = new List(); //C2020-036 used to create list duplicate procedure numbers // B2017-242 added check for duplicate procedure numbers in a procedure set @@ -761,10 +849,13 @@ namespace VEPROMS dpl.Clear(); dvi.ResetProcedures(); // B2021-035: Approve All – Pasted, modified number and deleted procedures not refreshed so missing from list List pnList = new List(); + foreach (ProcedureInfo pi in dvi.Procedures) { if (!pnList.Contains(pi.DisplayNumber)) + { pnList.Add(pi.DisplayNumber); + } else if (pinfo != null) { if (pinfo.DisplayNumber == pi.DisplayNumber) @@ -783,33 +874,40 @@ namespace VEPROMS if (!dpl.Contains(pi.DisplayNumber)) dpl.Add(pi.DisplayNumber); } } - return dpl.Count > 0; + + return (dpl.Count > 0); } + void tv_ApproveSomeProcedures(object sender, vlnTreeEventArgs args) { DocVersionInfo dvi = (args.Node as VETreeNode).VEObject as DocVersionInfo; if (dvi == null) return; + // B2017-242 added check for duplicate procedure numbers in a procedure set if (DuplicateProcedureNumbers(dvi, null)) { // C2020-036 display list of duplicate procedure numbers FlexibleMessageBox.Show("This procedure set has two or more procedures with the same procedure number.\n\n" + "Please make each procedure number unique before approving.\n\n" + - "Below is a list of the dupicate procedure numbers:\n\n" + dupProcList, "Approve Some Procedures", MessageBoxButtons.OK, MessageBoxIcon.Warning); + "Below is a list of the duplicate procedure numbers:\n\n" + dupProcList, "Approve Some Procedures", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } + tc.SaveCurrentEditItem(); string message = string.Empty; + if (!MySessionInfo.CanCheckOutItem(dvi.VersionID, CheckOutType.DocVersion, ref message)) { MessageBox.Show(this, message, "Working Draft Has Items Already Checked Out", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } + int ownerid = MySessionInfo.CheckOutItem(dvi.VersionID, CheckOutType.DocVersion); dvi.DocVersionConfig.SelectedSlave = args.UnitIndex; - dlgApproveProcedure dlg = new dlgApproveProcedure(dvi, true, this);//Added frmVEPROMS Parameter + dlgApproveProcedure dlg = new dlgApproveProcedure(dvi, true, this); dlg.MySessionInfo = MySessionInfo; dlg.ShowDialog(this); + displayHistory.RefreshList(); dvi.DocVersionConfig.SelectedSlave = 0; MySessionInfo.CheckInItem(ownerid); @@ -819,6 +917,7 @@ namespace VEPROMS { DocVersionInfo dvi = (args.Node as VETreeNode).VEObject as DocVersionInfo; if (dvi == null) return; + // B2017-242 added check for duplicate procedure numbers in a procedure set if (DuplicateProcedureNumbers(dvi, null)) { @@ -828,18 +927,22 @@ namespace VEPROMS "Below is a list of the dupicate procedure numbers:\n\n" + dupProcList, "Approve All Procedures", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } + tc.SaveCurrentEditItem(); string message = string.Empty; + if (!MySessionInfo.CanCheckOutItem(dvi.VersionID, CheckOutType.DocVersion, ref message)) { MessageBox.Show(this, message, "Working Draft Has Items Already Checked Out", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } + int ownerid = MySessionInfo.CheckOutItem(dvi.VersionID, CheckOutType.DocVersion); dvi.DocVersionConfig.SelectedSlave = args.UnitIndex; dlgApproveProcedure dlg = new dlgApproveProcedure(dvi, this);//Added frmVEPROMS Parameter dlg.MySessionInfo = MySessionInfo; dlg.ShowDialog(this); + displayHistory.RefreshList(); dvi.DocVersionConfig.SelectedSlave = 0; MySessionInfo.CheckInItem(ownerid); @@ -851,6 +954,7 @@ namespace VEPROMS OwnerInfoList oil = OwnerInfoList.Get(); Dictionary dicProcCheckedOut = new Dictionary(); Dictionary dicDocCheckedOut = new Dictionary(); + foreach (OwnerInfo oi in oil) { if (oi.SessionID != MySessionInfo.SessionID && oi.OwnerType == (byte)CheckOutType.Procedure) @@ -858,6 +962,7 @@ namespace VEPROMS else if (oi.SessionID != MySessionInfo.SessionID && oi.OwnerType == (byte)CheckOutType.Document) dicDocCheckedOut.Add(oi.OwnerItemID, oi.OwnerID); } + if (args.Node.IsExpanded) { foreach (TreeNode tn in args.Node.Nodes) @@ -866,16 +971,21 @@ namespace VEPROMS // The set the tree node to red text if the procedure or the section in the respected dictionary ProcedureInfo pi = (tn as VETreeNode).VEObject as ProcedureInfo; SectionInfo si = (tn as VETreeNode).VEObject as SectionInfo; + if ((pi != null && dicProcCheckedOut.ContainsKey(pi.ItemID)) || (si != null && !si.IsStepSection && dicDocCheckedOut.ContainsKey(si.MyContent.MyEntry.DocID))) tn.ForeColor = Color.Red; else tn.ForeColor = Color.Black; + bool expanded = tn.IsExpanded; + if (!expanded) tn.Expand(); + foreach (TreeNode tnn in tn.Nodes) { si = (tnn as VETreeNode).VEObject as SectionInfo; + if (si != null && si.MyContent.MyEntry != null) { if (dicDocCheckedOut.ContainsKey(si.MyContent.MyEntry.DocID)) @@ -884,6 +994,7 @@ namespace VEPROMS tnn.ForeColor = Color.Black; } } + if (!expanded) tn.Collapse(); } @@ -894,12 +1005,15 @@ namespace VEPROMS { ProcedureInfo pi = null; SectionInfo si = null; + pi = (args.Node as VETreeNode).VEObject as ProcedureInfo; - if (pi == null) - si = (args.Node as VETreeNode).VEObject as SectionInfo; + if (pi == null) si = (args.Node as VETreeNode).VEObject as SectionInfo; + UserInfo ui = UserInfo.GetByUserID(MySessionInfo.UserID); + dlgCheckedOutProcedure cop = new dlgCheckedOutProcedure(pi, si, ui); cop.ShowDialog(this); + tv_RefreshCheckedOutProcedures(sender, new vlnTreeEventArgs(args.Node.Parent, null, 0)); } @@ -908,6 +1022,7 @@ namespace VEPROMS ProcedureInfo pi = (args.Node as VETreeNode).VEObject as ProcedureInfo; pi.MyDocVersion.DocVersionConfig.SelectedSlave = args.UnitIndex; if (pi == null) return; + // B2017-242 added check for duplicate procedure numbers in a procedure set? if (DuplicateProcedureNumbers(pi.MyDocVersion, pi)) { @@ -916,17 +1031,21 @@ namespace VEPROMS "Please make each procedure number unique before approving.", "Approve Procedure", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } + tc.SaveCurrentEditItem(pi); string message = string.Empty; + if (!MySessionInfo.CanCheckOutItem(pi.ItemID, CheckOutType.Procedure, ref message)) { MessageBox.Show(this, message, "Procedure Already Checked Out", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } + int ownerid = MySessionInfo.CheckOutItem(pi.ItemID, 0); dlgApproveProcedure dlg = new dlgApproveProcedure(pi, this);//Added frmVEPROMS Parameter dlg.MySessionInfo = MySessionInfo; dlg.ShowDialog(this); + displayHistory.RefreshList(); pi.MyDocVersion.DocVersionConfig.SelectedSlave = 0; MySessionInfo.CheckInItem(ownerid); @@ -936,32 +1055,40 @@ namespace VEPROMS { DocVersionInfo dvi = (args.Node as VETreeNode).VEObject as DocVersionInfo; if (dvi == null) return; + tc.SaveCurrentEditItem(); + DlgPrintProcedure prnDlg = new DlgPrintProcedure(dvi); prnDlg.MySessionInfo = MySessionInfo; prnDlg.SelectedSlave = args.UnitIndex; prnDlg.ShowDialog(this); // RHM 20120925 - Center dialog over PROMS window } + void tv_PrintProcedure(object sender, vlnTreeEventArgs args) { ProcedureInfo pi = (args.Node as VETreeNode).VEObject as ProcedureInfo; pi.MyDocVersion.DocVersionConfig.SelectedSlave = args.UnitIndex; if (pi == null) return; + tc.SaveCurrentEditItem(pi); + DlgPrintProcedure prnDlg = new DlgPrintProcedure(pi); prnDlg.MySessionInfo = MySessionInfo; prnDlg.SelectedSlave = args.UnitIndex; - // prnDlg.Show(this); // RHM 20120925 - Center dialog over PROMS window prnDlg.ShowDialog(this); // RHM 20120925 - Center dialog over PROMS window + pi.MyDocVersion.DocVersionConfig.SelectedSlave = 0; } + void tv_CreateContinuousActionSummary(object sender, vlnTreeEventArgs args) { DialogResult dr = System.Windows.Forms.DialogResult.Yes; ProcedureInfo pi = (args.Node as VETreeNode).VEObject as ProcedureInfo; pi.MyDocVersion.DocVersionConfig.SelectedSlave = args.UnitIndex; if (pi == null) return; + tc.SaveCurrentEditItem(pi); + DlgPrintProcedure prnDlg = new DlgPrintProcedure(pi, true); prnDlg.MySessionInfo = MySessionInfo; prnDlg.SelectedSlave = args.UnitIndex; @@ -969,81 +1096,96 @@ namespace VEPROMS prnDlg.CreateContinuousActionSummary = true; prnDlg.OpenAfterCreate = (dr == System.Windows.Forms.DialogResult.Yes); prnDlg.Prefix = "CASTMP_"; // prefix the temporary procedure PDF file that is generated (to grab page numbers) + prnDlg.SetupForProcedure(); prnDlg.CreatePDF(); + pi.MyDocVersion.DocVersionConfig.SelectedSlave = 0; } + void RefreshDisplayHistory(object sender) { displayHistory.RefreshChangeList(); } + void displayHistory_HistorySelectionChanged(object sender, DisplayHistoryEventArgs args) { tc.OpenItem(ItemInfo.Get(args.ItemID)); } + void displayHistory_SummaryPrintRequest(object sender, DisplayHistoryReportEventArgs args) { Volian.Print.Library.PDFChronologyReport myChronoRpt = new Volian.Print.Library.PDFChronologyReport(args.ReportTitle, args.ProcedureInfo, args.AuditList, args.AnnotationList); myChronoRpt.BuildSummary(); } + void displayHistory_ChronologyPrintRequest(object sender, DisplayHistoryReportEventArgs args) { Volian.Print.Library.PDFChronologyReport myChronoRpt = new Volian.Print.Library.PDFChronologyReport(args.ReportTitle, args.ProcedureInfo, args.AuditList, args.AnnotationList); myChronoRpt.BuildChronology(); } + DialogResult tv_NodePSI(object sender, vlnTreeEventArgs args) { VETreeNode vNode = (VETreeNode)args.Node; IVEDrillDownReadOnly veObj = vNode.VEObject; ProcedureInfo myProc = veObj as ProcedureInfo; string message = string.Empty; + if (!MySessionInfo.CanCheckOutItem(myProc.ItemID, CheckOutType.Procedure, ref message)) { MessageBox.Show(this, message, "Item Already Checked Out", MessageBoxButtons.OK, MessageBoxIcon.Warning); return DialogResult.None; } + int ownerID = MySessionInfo.CheckOutItem(myProc.ItemID, 0); frmPSI fpsi = new frmPSI(myProc); DialogResult dr = fpsi.ShowDialog(this); MySessionInfo.CheckInItem(ownerID); + return dr; } + DialogResult tv_NodeSI(object sender, vlnTreeEventArgs args) { VETreeNode vNode = (VETreeNode)args.Node; IVEDrillDownReadOnly veObj = vNode.VEObject; - // see if working draft or folder & get associated 'SI' info from its config. - // For now, do folder. + + // see if working draft or folder & get associated 'SI' info from its config. For now, do folder. bool doFolder = true; FolderInfo myFolder = veObj as FolderInfo; - DocVersionInfo myDV = veObj as DocVersionInfo; ; + DocVersionInfo myDV = veObj as DocVersionInfo; + if (myFolder == null) doFolder = false; string message = string.Empty; + if (!MySessionInfo.CanCheckOutItem(doFolder ? myFolder.FolderID : myDV.VersionID, doFolder ? CheckOutType.Folder : CheckOutType.DocVersion, ref message)) { MessageBox.Show(this, message, "Item Already Checked Out", MessageBoxButtons.OK, MessageBoxIcon.Warning); return DialogResult.None; } - string strConfig = doFolder ? myFolder.Config : myDV.Config; - FormatInfo fi = doFolder ? myFolder.ActiveFormat : myDV.ActiveFormat; + + string strConfig = (doFolder) ? myFolder.Config : myDV.Config; + FormatInfo fi = (doFolder) ? myFolder.ActiveFormat : myDV.ActiveFormat; + if (fi == null) { MessageBox.Show("You must define a format at this level before access of Specific Information"); return DialogResult.Cancel; } + int ownerID = MySessionInfo.CheckOutItem(doFolder ? myFolder.FolderID : myDV.VersionID, doFolder ? CheckOutType.Folder : CheckOutType.DocVersion); frmSI fsi = new frmSI(fi.PlantFormat.FormatData.SI, strConfig, doFolder, myFolder, myDV); DialogResult dr = fsi.ShowDialog(this); MySessionInfo.CheckInItem(ownerID); + return dr; } - /// - /// Activate tmrTreeView so that the newly created Step recieves focus - /// - /// - /// + + void tv_NodeInsert(object sender, vlnTreeEventArgs args) { + // Activate tmrTreeView so that the newly created Step receives focus tmrTreeView.Enabled = true; } @@ -1051,6 +1193,8 @@ namespace VEPROMS void frmVEPROMS_Activated(object sender, EventArgs e) { + Volian.Base.Library.vlnStackTrace.ShowStack(); + if (ActiveControl == tc) tc.HideCaret(); // refresh anything that pertains to external files or programs: @@ -1083,8 +1227,11 @@ namespace VEPROMS // need this to update RO Tree after UpdateRofst (B2015-226) // B2022-026 RO Memory reduction coding (Jakes Merge) - displayRO.MyROFST = SelectedROFst; - displayRO.LoadTree(); + if (displayRO.MyROFST != SelectedROFst) + { + displayRO.MyROFST = SelectedROFst; + displayRO.LoadTree(); + } } if (SelectedStepTabPanel != null && SelectedStepTabPanel.MyStepTabRibbon != null) @@ -1113,22 +1260,28 @@ namespace VEPROMS // and if they are not the same, use the CurrentItem from the main frmVEPROMS. ProcedureInfo piThis = null; if (_CurrentItem != null) piThis = _CurrentItem.MyProcedure; + ProcedureInfo pi = args.Proc as ProcedureInfo; if (piThis != null && pi.ItemID != piThis.ItemID) pi = piThis; - //added by jcb 20130718 to support create pdf button when multiunit and user selects a unit + //added by jcb 20130718 to support create pdf button when multi-unit and user selects a unit pi.MyDocVersion.DocVersionConfig.SelectedSlave = pi.ProcedureConfig.SelectedSlave; - //end added by jcb 20130718 + + // Check if Procedure Info is null if (pi == null) return; + + DlgPrintProcedure prnDlg = new DlgPrintProcedure(pi); - //added by jcb 20130718 to support create pdf button when multiunit and user selects a unit + + //added by jcb 20130718 to support create pdf button when multi-unit and user selects a unit prnDlg.SelectedSlave = pi.ProcedureConfig.SelectedSlave == 0 ? -1 : pi.ProcedureConfig.SelectedSlave; prnDlg.MySessionInfo = MySessionInfo; - //end added by jcb 20130718 - prnDlg.ShowDialog(this); // RHM 20120925 - Center dialog over PROMS window - //added by jcb 20130718 to support create pdf button when multiunit and user selects a unit + + // RHM 20120925 - Center dialog over PROMS window + prnDlg.ShowDialog(this); + + //added by jcb 20130718 to support create pdf button when multi-unit and user selects a unit pi.MyDocVersion.DocVersionConfig.SelectedSlave = 0; - //end added by jcb 20130718 } void displaySearch1_PrintRequest(object sender, DisplaySearchEventArgs args) @@ -1137,16 +1290,21 @@ namespace VEPROMS //C2019-013 pass in sorted by information Volian.Print.Library.PDFReport myReport = new Volian.Print.Library.PDFReport(args.ReportTitle, args.TypesSelected, args.MyItemInfoList, Volian.Base.Library.VlnSettings.TemporaryFolder + @"\searchresults.pdf", args.PaperSize, args.SortedBy); + if (args.SearchString != null) myReport.SearchString = args.SearchString; + if (!args.ReportTitle.Contains("Annotation")) { int annotationCount = 0; + foreach (ItemInfo itm in args.MyItemInfoList) annotationCount += itm.ItemAnnotationCount; + if (annotationCount > 0) myReport.ShowAnnotations = (MessageBox.Show("Show Annotations", "Include Annotations", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes); } + myReport.Build(); } @@ -1212,13 +1370,13 @@ namespace VEPROMS return tc.PasteRTBItem(args.MyItemInfo, args.CopyStartID, args.PasteType, (int)args.Type); } - // C2020-033: Display the search panel with Incoming Transition info for the tree view - // and for the editor. private ItemInfo tv_SearchIncTrans(object sender, vlnTreeItemInfoEventArgs args) { + // C2020-033: Display the search panel with Incoming Transition info for the tree view and for the editor. displaySearch1.SearchIncTransII = args.MyItemInfo; toolsPanel.Expanded = true; displaySearch1.UpdateSearchIncTransResults(); + return args.MyItemInfo; } @@ -1227,6 +1385,7 @@ namespace VEPROMS displaySearch1.SearchIncTransII = args.MyItemInfo; toolsPanel.Expanded = true; displaySearch1.UpdateSearchIncTransResults(); + return args.MyItemInfo; } @@ -1243,9 +1402,13 @@ namespace VEPROMS // should be closed or if we should exit PROMS or just Cancel to continue working if (!_WeAreExitingPROMS && !ClosingWithError && tc.SelectedDisplayTabItem != null && tc._MyDisplayTabItems.Count > 0) { - DlgCloseTabsOrExit dctoe = new DlgCloseTabsOrExit(MyParent == null, PROMSWindowForms.Count > 0); // B2019-071 dialog to ask user if we are to close one tab or exit + // B2019-071 dialog to ask user if we are to close one tab or exit + DlgCloseTabsOrExit dctoe = new DlgCloseTabsOrExit(MyParent == null, PROMSWindowForms.Count > 0); dctoe.ShowDialog(); - _WeAreExitingPROMS = MyParent == null && dctoe.ExitPROMS; // B2019-101 flag that we are exiting from PROMS main window (separate windows) + + // B2019-101 flag that we are exiting from PROMS main window (separate windows) + _WeAreExitingPROMS = (MyParent == null && dctoe.ExitPROMS); + if (dctoe.Cancel) // B2019-071 user decided to not close any tab and not exit PROMS - so do nothing and continue working { e.Cancel = true; @@ -1254,15 +1417,19 @@ namespace VEPROMS } string stk = Volian.Base.Library.vlnStackTrace.StackToString(); + if (!stk.Contains("Exception")) { // B2018-091 Allow PROMS to close if only MSWord sections have been opened. // B2019-071 we will now close one or all of the tabs (even step editor ones) int n = tc._MyDisplayTabItems.Count; + while (n-- > 0 && tc._MyDisplayTabItems.Count > 0) { tc.CloseTabItem(tc.SelectedDisplayTabItem); - if (!dctoe.ExitPROMS) // B2019-071 close just the current tab and continue working + + // B2019-071 close just the current tab and continue working + if (!dctoe.ExitPROMS) { n = 0; e.Cancel = true; @@ -1270,18 +1437,21 @@ namespace VEPROMS return; } } + if (tc.SelectedDisplayTabItem != null && tc._MyDisplayTabItems.Count > 0 && dctoe.ExitPROMS) { _MyLog.WarnFormat(string.Format("Stack Does not contain an Exception\r\n" + "PROMS will Not Exit. Stack : \r\n{0}", stk)); e.Cancel = true; // If Display Items still exist don't close. } + dctoe.Close(); } } + //C2015-022 Separate Windows - if child windows are open and we are closing the main PROMS window, give user a chance to not close PROMS and that child windows // B2019-101 if we are exiting from PROMS main window no need to prompt user about child windows. - if (MyParent == null && PROMSWindowForms.Count > 0 && !_WeAreExitingPROMS) + if (MyParent == null && PROMSWindowForms != null && PROMSWindowForms.Count > 0 && !_WeAreExitingPROMS) { DialogResult dr = MessageBox.Show("Close all of the child windows and exit PROMS?", "Exit PROMS", MessageBoxButtons.YesNo); if (dr == System.Windows.Forms.DialogResult.No) @@ -1291,7 +1461,8 @@ namespace VEPROMS } } - tc.ShuttingDown = true; // This keeps PROMS from Hanging under certain circumstances + // This keeps PROMS from Hanging under certain circumstances + tc.ShuttingDown = true; // B2019-161 When shutting down output the timing information (to the error log) if (VolianTimer.TimingsOn) @@ -1305,7 +1476,7 @@ namespace VEPROMS MySessionInfo.CheckInItem(dti.OwnerID); //C2015-022 Separate Windows closing child form only left procedure ownership active } - //_MyLog.WarnFormat("frmVEPROMS_FormClosing"); + if (MyParent == null) { if (MyActivityTimer != null) @@ -1314,8 +1485,7 @@ namespace VEPROMS _MyLog.Debug("VEPROMS FormClosing - dispose timer"); } - // part of separate windows upgrade C2015-022 - // close all of the child windows before closing the main PROMS window + // C2015-022: part of separate windows upgrade close all of the child windows before closing the main PROMS window if (PROMSWindowForms != null && PROMSWindowForms.Count > 0) { foreach (int k in PROMSWindowForms.Keys) @@ -1331,7 +1501,7 @@ namespace VEPROMS if (MySessionInfo != null) MySessionInfo.EndSession(); - // Save the location and size of the VE-PROMS appication for this user + // Save the location and size of the VE-PROMS application for this user if (this.WindowState == FormWindowState.Normal) { Settings.Default.Location = this.Location; @@ -1339,10 +1509,13 @@ namespace VEPROMS } if (this.MyVersionWindowList != null) + { Settings.Default.VersionWindows = this.MyVersionWindowList.ToSettings(); + } Settings.Default.WindowState = this.WindowState; Settings.Default.QATItems = ribbonControl1.QatLayout; + SaveMRU(); //Settings.Default.Save(); @@ -1380,6 +1553,7 @@ namespace VEPROMS private string getProcedurePanelHeading() { VETreeNode jj_vetn = (VETreeNode)tv.Nodes[0]; // the VEPROMS tree node + if (!PROMSWindowForms.ContainsKey(tc.VersionID)) //C2018-029 check if we are in a child window return ((FolderConfig)jj_vetn.VEObject.MyConfig).Title; // get the panel heading else @@ -1412,28 +1586,29 @@ namespace VEPROMS return _RefreshTimer; } } + private bool _RefreshTimerActive = false; + // B2019-161 When tracking timing time this action private static VolianTimer _TimeActivity = new VolianTimer("frmVEPROMS.cs _RefreshTimer_Tick", 1346); + public bool RefreshTimerActive { get { return _RefreshTimerActive; } set { _RefreshTimerActive = value; } } + void _RefreshTimer_Tick(object sender, EventArgs e) { - //_MyLog.DebugFormat("_RefreshTimer_Tick {0}", RefreshTimerActive); - - if (RefreshTimerActive) { - _TimeActivity.Open(); RefreshTimerActive = false; + + _TimeActivity.Open(); if (PauseRefresh) return; RefreshChanged(this); _TimeActivity.Close(); } - } private void btnStepRTF_Click(object sender, System.EventArgs e) @@ -1489,44 +1664,59 @@ namespace VEPROMS private void PingSession(Object obj) { MySemaphore.WaitOne(); + if (!DisablePing)// If Ping is disabled don't do ping - This was causing a deadlock during import { List myList = MySessionInfo.PingSession(); + // B2017-247 Error Handler for Ping Session if (myList != null) { foreach (DisplayTabItem dti in tc.MyBar.Items) { if (!myList.Contains(dti.OwnerID)) + { MyCloseTabList.PushDTI(dti); + } } } } + MySemaphore.Release(); } WindowsFormsSynchronizationContext mUIContext = new WindowsFormsSynchronizationContext(); + public void MyFindNodeAndExpand(object obj) { if (tv == null || tv.SelectedNode == null) return; + IVEDrillDownReadOnly veObj1 = ((tv.SelectedNode as VETreeNode).VEObject as IVEDrillDownReadOnly); int id = (int)obj; ItemInfo ii = ItemInfo.Get(id); ii.ResetParts(); + using (Item i = Item.Get(id)) + { ItemInfo.Refresh(i); + } + tv.RefreshRelatedNode(ii); IVEDrillDownReadOnly veObj2 = ((tv.SelectedNode as VETreeNode).VEObject as IVEDrillDownReadOnly); + if (veObj1.ToString() != veObj2.ToString()) { VETreeNode tnNew = null; + foreach (VETreeNode tn in tv.SelectedNode.Nodes) { if (tn.VEObject.ToString() == veObj1.ToString()) tnNew = tn; } + if (tnNew != null) tv.SelectedNode = tnNew; } + MySemaphore.Release(); // ping session control } @@ -1544,6 +1734,7 @@ namespace VEPROMS //if (SkipRefresh) return; //MySemaphore.WaitOne(); Int64 lastChanged = 0; + //_MyLog.WarnFormat(">>> RefreshChanged"); try { @@ -1554,8 +1745,9 @@ namespace VEPROMS foreach (int id in MySessionInfo.ChangedItems.Keys) { if (ItemInfo.IsInCache(id)) - //mUIContext.Post(MyFindNodeAndExpand, id); + { MyFindNodeAndExpand(id); + } } } @@ -1567,7 +1759,7 @@ namespace VEPROMS if (ContentInfo.IsInCache(id)) { ContentInfo ci = ContentInfo.Get(id); - //if (ci.LastChangedInt64 > MySessionInfo.LastChangedInt64) + if (MySessionInfo.LastContentChange >= ci.LastChangedInt64) { using (Content c = Content.Get(id)) @@ -1576,6 +1768,7 @@ namespace VEPROMS } } } + lastChanged = MySessionInfo.ChangedContents[id]; } } @@ -1598,8 +1791,12 @@ namespace VEPROMS private int TotalCount(TreeNodeCollection tns) { int total = tns.Count; + foreach (TreeNode tn in tns) + { total += TotalCount(tn.Nodes); + } + return total; } @@ -1608,8 +1805,11 @@ namespace VEPROMS for (int i = 0; i < myArray.Length; i++) { if (myArray[i] != 0) + { return false; + } } + return true; } @@ -1631,6 +1831,7 @@ namespace VEPROMS Volian.Base.Library.VlnItextFont.RegisterPromsFonts(); InitializeSecurity(); UpdateUser(); + btnSecurity = new ButtonItem("btnSecurity", "Security"); // C2019-002: move security & format items into submenus btnFormats = new ButtonItem("btnFormats", "Formats"); btnAdmin.SubItems.Add(btnSecurity); @@ -1648,17 +1849,17 @@ namespace VEPROMS btnManageSecurity = new ButtonItem("btnManageSecurity", "Manage Security"); btnSecurity.SubItems.Add(btnManageSecurity); btnManageSecurity.Click += new EventHandler(btnManageSecurity_Click); - //added by jcb - //menu item to reset security - //requires password to implement + + //added by jcb: menu item to reset security requires password to implement btnResetSecurity = new ButtonItem("btnResetSecurity", "Reset Security"); btnSecurity.SubItems.Add(btnResetSecurity); btnResetSecurity.Click += new EventHandler(btnResetSecurity_Click); - //end added by jcb + //batch refresh transitions btnAdministrativeTools = new ButtonItem("btnAdministrativeTools", "Administrative Tools"); btnAdministrativeTools.Click += new EventHandler(btnAdministrativeTools_Click); btnAdmin.SubItems.Add(btnAdministrativeTools); + this.superTooltip1.SetSuperTooltip(btnPrint, new SuperTooltipInfo("Create PDF", null, null, null, null, eTooltipColor.Gray)); this.superTooltip1.SetSuperTooltip(btnExit, new SuperTooltipInfo("Exit", null, null, null, null, eTooltipColor.Gray)); this.superTooltip1.SetSuperTooltip(btnOptions, new SuperTooltipInfo("Options", null, null, null, null, eTooltipColor.Gray)); @@ -1667,7 +1868,7 @@ namespace VEPROMS this.superTooltip1.SetSuperTooltip(btnResetSecurity, new SuperTooltipInfo("Reset Security", null, null, null, null, eTooltipColor.Gray)); this.superTooltip1.SetSuperTooltip(btnAdministrativeTools, new SuperTooltipInfo("Administrative Tools", null, null, null, null, eTooltipColor.Gray)); this.superTooltip1.SetSuperTooltip(btnUpdateFormats, new SuperTooltipInfo("Update Formats", null, null, null, null, eTooltipColor.Gray)); - //end batch refresh transitions + try { MyUserInfo = UserInfo.GetByUserID(VlnSettings.UserID); @@ -1678,6 +1879,7 @@ namespace VEPROMS MessageBox.Show("This database is not compatible with this version of PROMS. The PROMS program will terminate. Please contact Volian to assist in resolution."); Application.Exit(); } + if (MyUserInfo == null) { User u = User.MakeUser(VlnSettings.UserID, "", "", "", "", "", "", "", "", "", "", DateTime.Now, VlnSettings.UserID); @@ -1686,6 +1888,7 @@ namespace VEPROMS MyUserInfo = UserInfo.Get(u.UID); SMyUserInfo = MyUserInfo; } + ctrlAnnotationDetails.MyUserInfo = MyUserInfo; DisplayRO.MyUserInfo = MyUserInfo; // set the user's security information in the properties RO panel StepTabRibbon.MyUserInfo = MyUserInfo; // set the user's security information in the ribbon @@ -1696,98 +1899,113 @@ namespace VEPROMS DisplayApplicability.MyUserInfo = MyUserInfo; // set the user's security information in the Applicability panel StepRTB.MyUserInfo = MyUserInfo; // set the user's security information in the StepRTB VlnFlexGrid.MyUserInfo = MyUserInfo; // set the user's security information in the VlnFlexGrid + bool isVisible = MyUserInfo.IsAdministrator(); + btnUserControlOfFormats.Visible = isVisible; btnUserControlOfFormatsExport.Visible = isVisible; btnUserControlOfFormatsImport.Visible = isVisible; btnManageSecurity.Visible = isVisible; btnUpdateFormats.Visible = isVisible; btnResetSecurity.Visible = isVisible; - btnAdministrativeTools.Visible = isVisible || HasSetAdministrator(MyUserInfo); + btnAdministrativeTools.Visible = (isVisible || HasSetAdministrator(MyUserInfo)); + // C2020-034 hide the Formats and Security buttons if user is a Set Administrator // if use is not an Administrator or Set Administrator then disable the Administrator button btnFormats.Visible = isVisible; btnSecurity.Visible = isVisible; - btnAdmin.Enabled = isVisible || HasSetAdministrator(MyUserInfo); + btnAdmin.Enabled = (isVisible || HasSetAdministrator(MyUserInfo)); + tmrCloseTabItems = new Timer(); tmrCloseTabItems.Interval = 100; tmrCloseTabItems.Tick += new EventHandler(tmrCloseTabItems_Tick); tmrCloseTabItems.Enabled = true; + CloseSessionsNoLongerActive(); MySessionInfo = SessionInfo.BeginSession(Environment.MachineName, System.Diagnostics.Process.GetCurrentProcess().Id); + if (MySessionInfo == null) { MessageBox.Show("This database is locked by the Administrator. Please try again later", "PROMS is Locked"); Application.Exit(); } + this.LastContentChange = MySessionInfo.LastContentChange; + //_MyLog.WarnFormat("Original last content change {0}", this.LastContentChange); RefreshLastChange(); tc.MySessionInfo = MySessionInfo; tv.MySessionInfo = MySessionInfo; tv.MyUserInfo = MyUserInfo; + // Initialize Caption with Server name and Database name. SetCaption(tv.TopNode as VETreeNode); System.Threading.AutoResetEvent autoEvent = new System.Threading.AutoResetEvent(false); + //System.Threading.TimerCallback timerDelegate = new System.Threading.TimerCallback(MySessionInfo.PingSession); //System.Diagnostics.Process xyzzy = System.Diagnostics.Process.GetCurrentProcess(); + if (!System.Diagnostics.Debugger.IsAttached)// running in Production Mode (Not in the debugger) { System.Threading.TimerCallback timerDelegate = new System.Threading.TimerCallback(this.PingSession); - if (this._MyParent == null) MyActivityTimer = new System.Threading.Timer(timerDelegate, autoEvent, 10000, 10000); - // System.Threading.Thread.Sleep(5000); - // System.Threading.TimerCallback timerRefresh = new System.Threading.TimerCallback(this.StartRefreshChanged); - // RefreshTimer.Enabled = true; - // MyRefreshTimer = new System.Threading.Timer(timerRefresh, autoEvent, 10000, 10000); + if (this._MyParent == null) + { + MyActivityTimer = new System.Threading.Timer(timerDelegate, autoEvent, 10000, 10000); + } } - //string debugMode = ConfigurationManager.AppSettings["Debug"]; - //VlnSettings.DebugMode = bool.Parse(debugMode); // set debug for the Volian.Controls.Library - // get the saved location and size of the VE-PROMS appication for this user + + // get the saved location and size of the VE-PROMS application for this user this.txtSearch.KeyPress += new KeyPressEventHandler(txtSearch_KeyPress); - this.txtSearch.KeyUp += txtSearch_KeyUp; // RHM20150506 Multiline ItemID TextBox - this.txtSearch.TextChanged += txtSearch_TextChanged; // RHM20150506 Multiline ItemID TextBox - this.btnNext.Click += btnNext_Click; // RHM20150506 Multiline ItemID TextBox - this.btnPrint1.Click += btnPrint1_Click; // RHM20150506 Multiline ItemID TextBox - this.btnPrevious.Click += btnPrevious_Click; // RHM20150506 Multiline ItemID TextBox + this.txtSearch.KeyUp += txtSearch_KeyUp; // RHM20150506 Multi-Line ItemID TextBox + this.txtSearch.TextChanged += txtSearch_TextChanged; // RHM20150506 Multi-Line ItemID TextBox + this.btnNext.Click += btnNext_Click; // RHM20150506 Multi-Line ItemID TextBox + this.btnPrint1.Click += btnPrint1_Click; // RHM20150506 Multi-Line ItemID TextBox + this.btnPrevious.Click += btnPrevious_Click; // RHM20150506 Multi-Line ItemID TextBox if (Settings.Default["Location"] != null) this.Location = Settings.Default.Location; if (Settings.Default["Size"] != null) this.Size = Settings.Default.Size; //if (Settings.Default["WindowState"] != null) this.WindowState = Settings.Default.WindowState; //if (Settings.Default.SaveTreeviewExpanded) epProcedures.Expanded = Settings.Default.TreeviewExpanded; + // if the Procedures panel was left open from the last session, then open it epProcedures.Expanded = Settings.Default.TreeviewExpanded; if (Settings.Default["QATItems"] != null) ribbonControl1.QatLayout = Settings.Default.QATItems; // See if any database 'changes' need done and do them: MakeDatabaseChanges(); - if (Volian.Base.Library.VlnSettings.GetCommandFlag("NOMRU")) // B2017-193 Error occured when a section in the MRU was being loaded as an iteminfo + + if (Volian.Base.Library.VlnSettings.GetCommandFlag("NOMRU")) // B2017-193 Error occurred when a section in the MRU was being loaded as an iteminfo _MyMRIList = new MostRecentItemList(); else _MyMRIList = MostRecentItemList.GetMRILst((System.Collections.Specialized.StringCollection)(Properties.Settings.Default["MRIList"])); + _MyMRIList.AfterRemove += new ItemInfoEvent(_MyMRIList_AfterRemove); SetupMRU(); - // if the user selected to "Remember Last" (was "Save Expanded") then use the MRU list to - // expand the tree to the last opened procedure - //if (epProcedures.Expanded && _MyMRIList.Count > 0) + + // if the user selected to "Remember Last" (was "Save Expanded") then use the MRU list to expand the tree to the last opened procedure if (MyParent == null) { if (Settings.Default.SaveTreeviewExpanded && _MyMRIList.Count > 0) { _frmVEPROMSloading = true; // C2015-022 so we don't try to create child windows when proms is first starting and position in the procedure tree + tv.AdjustTree(_MyMRIList[0].MyItemInfo.MyProcedure); tv.SelectedNode.Expand(); SetCaption(tv.SelectedNode as VETreeNode); + _frmVEPROMSloading = false; } } + //get version windows settings MyVersionWindowList = VersionWindowList.GetVersionWindowList(Properties.Settings.Default.VersionWindows); tc.SyncEnhancedDocuments = Properties.Settings.Default.SyncEnhancedDocuments; + // Assign the Procedure Panel's title (heading) - epProcedures.TitleText = getProcedurePanelHeading();// get the panel heading + epProcedures.TitleText = getProcedurePanelHeading(); // get the panel heading Database.DefaultTimeout = 20 * getTimeout(); - // if the procedure panel is expanded, make sure we enable the splitter so the user can resize the panel - // Bug fix: B2013-89 + + // Bug fix: B2013-89: if the procedure panel is expanded, make sure we enable the splitter so the user can resize the panel expandableSplitter1.Enabled = epProcedures.Expanded; displaySearch1.SetupAnnotationSearch(ctrlAnnotationDetails, tc); @@ -1795,9 +2013,11 @@ namespace VEPROMS ctrlAnnotationDetails.SetupAnnotations(displaySearch1); tc.MyAnnotationDetails = ctrlAnnotationDetails; SetupButtons(); - displayBookMarks.MyDisplayTabControl = tc; // allows bookmark selection to bring up steps/docs + + displayBookMarks.MyDisplayTabControl = tc; // allows bookmark selection to bring up steps/docs office2007StartButton1.MouseDown += new MouseEventHandler(office2007StartButton1_MouseDown); //displayRO.EnabledChanged += new EventHandler(displayRO_EnabledChanged); + tc.Enter += new EventHandler(tc_Enter); tc.Leave += new EventHandler(tc_Leave); tc.StatusChanged += new DisplayTabControlStatusEvent(tc_StatusChanged); @@ -1805,12 +2025,16 @@ namespace VEPROMS tc.OpenInSeparateWindow += tc_OpenInSeparateWindow; tc.RefreshEnhancedDocument += tc_RefreshEnhancedDocument; tc.CopyStepSelected += tc_CopyStepSelected; // will extend CopyStep info to all child windows (separate windows upgrade) + this.Deactivate += new EventHandler(frmVEPROMS_Deactivate); + if (VlnSettings.DemoMode) StepRTB.MyFontFamily = GetFamily("Bookman Old Style"); displaySearch1.Enter += new EventHandler(displaySearch1_Enter); displayHistory.Enter += new EventHandler(displayHistory_Enter); ctrlAnnotationDetails.Enter += new EventHandler(ctrlAnnotationDetails_Enter); + Application.DoEvents(); + if (RunningNewRevision && ShowEULA() != DialogResult.OK) { Timer tmrShutDown = new Timer(); @@ -1819,7 +2043,10 @@ namespace VEPROMS tmrShutDown.Enabled = true; } else + { tmrAutomatic.Enabled = true; + } + //// Shutoff UpdateFormats for Production Mode //if (Volian.Base.Library.VlnSettings.ProductionMode) // btnAdmin.Visible = false; @@ -1827,23 +2054,20 @@ namespace VEPROMS StepTabRibbon.PastePlainTextSetting = Properties.Settings.Default.PastePlainText; StepTabRibbon.SpecifiedVisioPath = Properties.Settings.Default.VisioPath; Activate(); - //FolderInfo fi = FolderInfo.Get(1); - //FormatInfo frmI = FormatInfo.Get(fi.FormatID ?? 1); - //if (frmI.PlantFormat.FormatData.ProcData.ChangeBarData.ChangeIds) - //{ - // dlgChgId dlgCI = new dlgChgId(tc); - // dlgCI.ShowDialog(this); - //} - // RHM20150506 Multiline ItemID TextBox + + // RHM20150506 Multi-line ItemID TextBox if (MyParent == null) { this.txtSearch.Text = Volian.Base.Library.VlnSettings.GetItemIDs().Replace(",", "\r\n"); - // Open First Item - if (this.txtSearch.Text.Length > 0 && !this.txtSearch.Text.Contains("\r\n")) - CurrentID = txtSearch.Text; - } + // Open First Item + if (!string.IsNullOrEmpty(this.txtSearch.Text) && this.txtSearch.Text.Length > 0 && !this.txtSearch.Text.Contains("\r\n")) + { + CurrentID = txtSearch.Text; + } + } } + void tc_RefreshEnhancedDocument(object sender, ItemSelectedChangedEventArgs args) { // if the procedure is opened then move to the select step @@ -1855,6 +2079,7 @@ namespace VEPROMS { int versionID = args.MyItemInfo.MyDocVersion.VersionID; frmVEPROMS child = null; + if (PROMSWindowForms.ContainsKey(versionID)) { child = PROMSWindowForms[versionID]; @@ -1870,6 +2095,7 @@ namespace VEPROMS foreach (int k in PROMSWindowForms.Keys) { frmVEPROMS tmp = PROMSWindowForms[k]; + if (tmp.MyDocVersion.VersionID != this.SelectedDVI.VersionID) tmp.tc.MyCopyStep = tc.MyCopyStep; else if (tmp.MyParent != null) @@ -1885,6 +2111,7 @@ namespace VEPROMS { SessionInfoList sil = SessionInfoList.Get(); int i = 0; + foreach (SessionInfo si in sil) { if (si.DTSEnd == null && si.MachineName == Environment.MachineName && si.UserID == Volian.Base.Library.VlnSettings.UserID) @@ -1895,14 +2122,21 @@ namespace VEPROMS } catch (Exception ex)// Process not found { - Session.Delete(si.SessionID);// Remove Session record associated with a closed process + // Remove Session record associated with a closed process + Session.Delete(si.SessionID); } } else if (si.DTSEnd == null) + { i = i + 1; + } } - if (i == 0)// Turn-on Change Manger if there are no active Sessions + + // Turn-on Change Manger if there are no active Sessions + if (i == 0) + { TurnChangeManagerOn.Execute(); + } } // C2015-022 Separate Windows. This is a dictionary of child PROMS windows forms (frmVEPROMS) @@ -1923,26 +2157,38 @@ namespace VEPROMS } set { _PROMSWindowForms = value; } } + // This gets called when user opens an enhanced document (ex Background) from the source (ex EOP) // C2015-022 - This also get called if opening a procedure in a child (separate) window void tc_OpenInSeparateWindow(object sender, ItemSelectedChangedEventArgs args) { int versionID = args.MyItemInfo.MyDocVersion.VersionID; + if (MyParent != null && args.MyItemInfo.MyDocVersion.DocVersionConfig.MyEnhancedDocuments.Count > 0 && !args.MyItemInfo.MyDocVersion.DocVersionConfig.MyEnhancedDocuments.HasSourcePointer) { MyParent.OpenItem(args.MyItemInfo); return; } + frmVEPROMS child = null; + if (PROMSWindowForms.ContainsKey(versionID)) + { child = PROMSWindowForms[versionID]; // use existing child window + } else { child = CreateChildPromsWindow(args.MyItemInfo.MyDocVersion); // create a new child window for the enhanced document procedure set tv.AdjustTree(args.MyItemInfo); // find the position in the tree VETreeNode _tn = tv.SelectedNode as VETreeNode; // get the tree node for args.MyItemInfo - while (!(_tn.VEObject is FolderInfo)) _tn = (VETreeNode)_tn.Parent; // back up to the first folder tree node + + while (!(_tn.VEObject is FolderInfo)) + { + // back up to the first folder tree node + _tn = (VETreeNode)_tn.Parent; + } + _tn.Nodes.Clear(); // remove the child nodes from main window - child window now has this part of the procedure tree _tn.ChildrenLoaded = false; _tn.MovedToSeparateWindow = true; // flag used to reload children nodes if the child window is closed and user clicks on the tree node in the main window @@ -1950,21 +2196,29 @@ namespace VEPROMS child.OpenItem(args.MyItemInfo); // this opens to the enhanced document step and expands the tree to the related node (in the child window) } + private frmVEPROMS CreateChildPromsWindow(DocVersionInfo dvi) // C2015-022 logic to create separate (child) windows for a procedure set { frmVEPROMS child; + // create a new window for this doc version (procedure set) child = new frmVEPROMS(this, dvi); PROMSWindowForms.Add(dvi.VersionID, child); // keep track of child windows child.Visible = false; child.Show(); + if (MyVersionWindowList != null && MyVersionWindowList.Count > 0) + { foreach (VersionWindow vw in MyVersionWindowList) + { if (vw.VersionID == dvi.VersionID) { child.SetDesktopBounds(vw.MyRectangle.Left, vw.MyRectangle.Top, vw.MyRectangle.Width, vw.MyRectangle.Height); break; } + } + } + child.office2007StartButton1.Visible = false; // hide V button child.qatCustomizeItem1.Visible = false; // hide quick access list child.btnExit.Visible = false; // hide the exit button (closes all of PROMS not just the child window) @@ -1972,10 +2226,12 @@ namespace VEPROMS child.Move += child_MoveOrSize; child.Resize += child_MoveOrSize; child.FormClosed += child_FormClosed; + // these next three lines of code will force the child window to display on top of all other windows on the screen child.TopMost = true; // force child window to the display on top of all others Application.DoEvents(); child.TopMost = false; // child window will remain on top but now other windows can be displayed on top of it + return child; } @@ -1990,44 +2246,55 @@ namespace VEPROMS RectangleConverter rc = new RectangleConverter(); string str = string.Format("{0}~{1}", frm.MyDocVersion.VersionID, rc.ConvertToString(frm.DesktopBounds)); MyVersionWindowList.Add(new VersionWindow(str)); - } + private bool HasSetAdministrator(UserInfo ui) { DocVersionInfoList dvil = DocVersionInfoList.Get(); + foreach (DocVersionInfo dvi in dvil) + { if (ui.IsSetAdministrator(dvi)) return true; - return false; + } + return false; } + // RHM20150507 Table Scrunch // B2018-033 VCS SAG-6 Steps 3 and 9 and SACRG1 Step 13 // Set default Scrunching flags private TableScrunching _DefaultScrunchingRules = TableScrunching.AllPhases; + void btnPrint1_Click(object sender, EventArgs e) { string[] ids = txtSearch.Text.Split("\r\n ".ToCharArray()); Dictionary dicProcs = new Dictionary(); + foreach (string id in ids) { - if (id != "") + if (!string.IsNullOrEmpty(id)) { ItemInfo ii = GetItemInfoFromString(id); + if (ii != null && !dicProcs.ContainsKey(ii.MyProcedure.ItemID))// B2018-087 - Don't fail if it doesn't exist dicProcs.Add(ii.MyProcedure.ItemID, ii.MyProcedure); } } + DialogResult dr = System.Windows.Forms.DialogResult.Yes; - //dr = MessageBox.Show("Do you want all of the PDFs to be opened?", "Open After Create", MessageBoxButtons.YesNo, MessageBoxIcon.Question); + // RHM20150507 Table Scrunch Rtf2Pdf.AllowTableScrunching = cbScrunch.Checked ? _DefaultScrunchingRules : TableScrunching.None; + foreach (int key in dicProcs.Keys) { ProcedureInfo proc = dicProcs[key]; + //Console.WriteLine("{0}", proc.ShortPath); - DlgPrintProcedure prnDlg = new DlgPrintProcedure(proc, true);//dvi.DocVersionConfig,pnum); + DlgPrintProcedure prnDlg = new DlgPrintProcedure(proc, true); prnDlg.MySessionInfo = MySessionInfo; + //prnDlg.ShowDialog(this); // RHM 20120925 - Center dialog over PROMS window prnDlg.Prefix = proc.MyDocVersion.VersionID.ToString() + "_"; prnDlg.Automatic = true; @@ -2036,30 +2303,43 @@ namespace VEPROMS prnDlg.CreatePDF(); } } + bool ProcessingPaste = false; + private void txtSearch_TextChanged(object sender, EventArgs e) { - if (!ProcessingPaste) // RHM20150507 Multiline ItemID TextBox + if (!ProcessingPaste) // RHM20150507 Multi-line ItemID TextBox { ProcessingPaste = true; + if (txtSearch.Text.Contains("\n")) { txtSearch.Text = txtSearch.Text.Trim("\r\n ".ToCharArray()); txtSearch.SelectionStart = 0; CurrentID = GetCurrentLine(); } - btnNext.Visible = btnPrint1.Visible = cbScrunch.Visible = btnPrevious.Visible = txtSearch.Text.Contains("\r\n"); + + bool isBtnVisible = txtSearch.Text.Contains("\r\n"); + + btnNext.Visible = isBtnVisible; + btnPrint1.Visible = isBtnVisible; + cbScrunch.Visible = isBtnVisible; + btnPrevious.Visible = isBtnVisible; + ProcessingPaste = false; } } + void btnPrevious_Click(object sender, EventArgs e) { CurrentID = FindPreviousLine(); } + void btnNext_Click(object sender, EventArgs e) { CurrentID = FindNextLine(); } + public string CurrentID { get @@ -2073,7 +2353,9 @@ namespace VEPROMS System.Media.SystemSounds.Beep.Play(); } else + { OpenMyItem(value); + } } } @@ -2081,13 +2363,16 @@ namespace VEPROMS { if (txtSearch.SelectionLength > 0) txtSearch.SelectionLength = 0; + string sub = txtSearch.Text.Substring(txtSearch.SelectionStart); + if (sub.Contains("\n")) { txtSearch.SelectionStart += sub.IndexOf("\n") + 1; txtSearch.ScrollToCaret(); return GetCurrentLine(); } + return null; } @@ -2095,17 +2380,23 @@ namespace VEPROMS { if (txtSearch.SelectionLength > 0) txtSearch.SelectionLength = 0; + string sub = txtSearch.Text; int selStart = 0; + if (txtSearch.SelectionStart == 0) return null; if (txtSearch.SelectionStart > 2) { sub = txtSearch.Text.Substring(0, txtSearch.SelectionStart - 2); if (sub.Contains("\n")) + { selStart = sub.LastIndexOf("\r\n") + 2; + } } + txtSearch.SelectionStart = selStart; txtSearch.ScrollToCaret(); + return GetCurrentLine(); } @@ -2123,6 +2414,7 @@ namespace VEPROMS CurrentID = GetCurrentLine(); e.Handled = true; } + if (e.Control && e.KeyCode == Keys.A) { txtSearch.SelectionStart = 0; @@ -2134,9 +2426,13 @@ namespace VEPROMS private string GetCurrentLine() { while (txtSearch.SelectionStart > 0 && txtSearch.Text[txtSearch.SelectionStart - 1] != '\n') + { txtSearch.SelectionStart--; + } + string sub = txtSearch.Text.Substring(txtSearch.SelectionStart).TrimStart("\r\n ".ToCharArray()); if (sub.Contains("\r\n")) return sub.Substring(0, sub.IndexOf("\r\n")); + return sub; } @@ -2145,23 +2441,26 @@ namespace VEPROMS if (e.KeyChar == '\r') { e.Handled = true; + if (txtSearch.Text.Length > 0) { - if (txtSearch.Text.Contains("\r\n")) // RHM20150506 Multiline ItemID TextBox + if (txtSearch.Text.Contains("\r\n")) // RHM20150506 Multi-Line ItemID TextBox CurrentID = GetCurrentLine(); else OpenMyItem(txtSearch.Text); } } + if (e.KeyChar == 1 || e.KeyChar == 22) { e.Handled = true; } } - private void OpenMyItem(string str) // RHM20150506 Multiline ItemID TextBox + private void OpenMyItem(string str) // RHM20150506 Multi-Line ItemID TextBox { - ItemInfo ii = GetItemInfoFromString(str); // RHM20150506 Multiline ItemID TextBox + ItemInfo ii = GetItemInfoFromString(str); // RHM20150506 Multi-Line ItemID TextBox + if (ii != null) { DisplayTabItem dti = tc.OpenItem(ii);// B2018-035 Allow procedure to be printed and property grid to be opened @@ -2175,18 +2474,22 @@ namespace VEPROMS lblItemID.Text = string.Format("ItemID = {0}", ii.ItemID); } else + { MessageBox.Show(string.Format("Looking for: {0}", str), "No item found"); + } } - private static ItemInfo GetItemInfoFromString(string str) // RHM20150506 Multiline ItemID TextBox + private static ItemInfo GetItemInfoFromString(string str) // RHM20150506 Multi-Line ItemID TextBox { ItemInfo ii = null; int id = 0; ContentInfo ci = null; + if (str.ToUpper().StartsWith("C=")) { if (int.TryParse(str.Substring(2), out id)) ci = ContentInfo.Get(id); + if (ci != null) ii = ci.ContentItems[0]; } @@ -2195,6 +2498,7 @@ namespace VEPROMS if (int.TryParse(str, out id)) ii = ItemInfo.Get(id); } + return ii; } @@ -2204,36 +2508,45 @@ namespace VEPROMS frm.ProgressBar = bottomProgBar; frm.ShowDialog(this); } + private static VolianTimer _TimeActivity1 = new VolianTimer("frmVEPROMS.cs tmrCloseTabItems_Tick", 2108); void tmrCloseTabItems_Tick(object sender, EventArgs e) { - _TimeActivity1.Open(); tmrCloseTabItems.Enabled = false; + + _TimeActivity1.Open(); + while (MyCloseTabList.CountDTI > 0) { DisplayTabItem dti = MyCloseTabList.PopDTI(); + if (dti.MyDSOTabPanel != null) { dti.MyDSOTabPanel.OverrideClose = true; // Add error log message for forced check-in _MyLog.WarnFormat("===============Override Close===================="); } + tc.CloseTabItem(dti); } - tmrCloseTabItems.Enabled = true; + _TimeActivity1.Close(); + + tmrCloseTabItems.Enabled = true; } private void InitializeSecurity() { Folder f = Folder.Get(1); GroupInfo gi = GroupInfo.Get(1); + if (f.FolderConfig.Security_Group == 0) { f.FolderConfig.Security_Group = gi.GID; f.Save(); } + securityRole = f.FolderConfig.Security_Group; } @@ -2241,17 +2554,22 @@ namespace VEPROMS private void UpdateUser() { string newUser = VlnSettings.GetCommand("U", null); + if (newUser != null) VlnSettings.UserID = newUser; + newUser = VlnSettings.GetCommand("V3Pr0m5" + GetSecurityKey(), null); + if (newUser != null) { VlnSettings.UserID = newUser; UserInfo ui = UserInfo.GetByUserID(VlnSettings.UserID); User u; + if (ui != null) { u = User.Get(ui.UID); + foreach (UserMembership um in u.UserMemberships) { if (um.EndDate == null || um.EndDate == string.Empty) @@ -2269,20 +2587,24 @@ namespace VEPROMS Membership.MakeMembership(u, g, null, ""); } } + if (MyParent == null) { if (VlnSettings.GetCommandFlag("VeauLeeAnn" + GetSecurityKey()) || VlnSettings.GetCommandFlag("VeauLeeAnnXYZZY")) { //pop up user list to select from ContextMenuStrip cms = BuildUserMenu(); + while (proxyUser == null) { cms.Show(new System.Drawing.Point((System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width - cms.Width) / 2, (System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height - cms.Height) / 2)); System.Windows.Forms.Application.DoEvents(); } + VlnSettings.UserID = proxyUser; } } + lblUser.Text = VlnSettings.UserID; lblUser.MouseDown += new MouseEventHandler(lblUser_MouseDown); } @@ -2303,6 +2625,7 @@ namespace VEPROMS - Jess- Volian0 - John- Volian0 - Kathy- Volian0 + - Jake- Volian0 - Jim- JCB2-HP - Rich- WINDOWS7-RHM - Rich - RICH-WINDOWS10 @@ -2312,11 +2635,12 @@ namespace VEPROMS - Harrys PC- Harry-7100 - Caitlin- Caitlin-PC */ - if ("|VLN|RICH-WINDOWS10|WINDOWS7-RHM|PAUL-PC|MICHELLE-PC|WIN-O4QLPEH7JKH|HARRY-7100|CAITLIN-PC|".Contains("|" + Environment.UserDomainName.ToUpper() /*Environment.GetEnvironmentVariable("USERDOMAIN").ToUpper()*/ + "|")) + if ("|VLN|RICH-WINDOWS10|WINDOWS7-RHM|PAUL-PC|MICHELLE-PC|WIN-O4QLPEH7JKH|HARRY-7100|CAITLIN-PC|".Contains("|" + Environment.UserDomainName.ToUpper() + "|")) { Random rnd = new Random(DateTime.Now.Year + DateTime.Now.DayOfYear * 1000); MessageBox.Show(this, GetSecurityKey(), "Today's Security Key"); } + _MyLog.WarnFormat("Environment.UserName = '{0}'", Environment.UserName); _MyLog.WarnFormat("Environment.UserDomainName = '{0}'", Environment.UserDomainName); _MyLog.WarnFormat("Environment.MachineName = '{0}'", Environment.MachineName); @@ -2327,12 +2651,14 @@ namespace VEPROMS private ContextMenuStrip BuildUserMenu() { System.Windows.Forms.ContextMenuStrip cms = new System.Windows.Forms.ContextMenuStrip(); + cms.Items.Add("Choose User"); System.Windows.Forms.ToolStripMenuItem tsmi = cms.Items[0] as System.Windows.Forms.ToolStripMenuItem; tsmi.BackColor = System.Drawing.Color.FromKnownColor(System.Drawing.KnownColor.ActiveCaption);// System.Drawing.Color.Pink; tsmi.ForeColor = System.Drawing.Color.FromKnownColor(System.Drawing.KnownColor.ActiveCaptionText); tsmi.Font = new System.Drawing.Font(tsmi.Font, System.Drawing.FontStyle.Bold); UserInfoList uil = UserInfoList.Get(); + foreach (UserInfo ui in uil) { if (ui.UserMembershipCount > 0) @@ -2349,23 +2675,27 @@ namespace VEPROMS } } } + return cms; } private void User_Click(object sender, EventArgs e) { ToolStripMenuItem tsmi = sender as ToolStripMenuItem; + if (tsmi != null) { UserInfo ui = tsmi.Tag as UserInfo; proxyUser = ui.UserID; } } + void btnUserControlOfFormats_Click(object sender, EventArgs e) { frmUCF frmucf = new frmUCF(); DialogResult dr = frmucf.ShowDialog(this); } + void btnUserControlOfFormatsExport_Click(object sender, EventArgs e) { DocVersionInfo dvi = null; @@ -2374,6 +2704,7 @@ namespace VEPROMS dlg.ExternalTransitionItem = null; dlg.ShowDialog(this); } + void btnUserControlOfFormatsImport_Click(object sender, EventArgs e) { DocVersionInfo dvi = null; @@ -2382,19 +2713,23 @@ namespace VEPROMS dlg.ExternalTransitionItem = null; dlg.ShowDialog(this); } + void btnManageSecurity_Click(object sender, EventArgs e) { dlgManageSecurity dlg = new dlgManageSecurity(); dlg.ShowDialog(this); } + void btnResetSecurity_Click(object sender, EventArgs e) { string password = string.Empty; + if (ShowInputDialog(ref password) == DialogResult.OK) { if (password == "V3Pr0m5") { StringBuilder sb = new StringBuilder(); + sb.AppendLine("***** WARNING *****"); sb.AppendLine(); sb.AppendLine("This action will delete all Groups, Users and Memberships from the database."); @@ -2402,6 +2737,7 @@ namespace VEPROMS sb.AppendLine("Following this action the application will terminate."); sb.AppendLine(); sb.AppendLine("Are you sure you want to continue?"); + if (MessageBox.Show(sb.ToString(), "Confirm Security Reset", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Stop) == DialogResult.Yes) { ResetSecurity.Execute(); @@ -2409,9 +2745,12 @@ namespace VEPROMS } } else + { MessageBox.Show("You have entered an incorrect password."); + } } } + private static DialogResult ShowInputDialog(ref string input) { System.Drawing.Size size = new System.Drawing.Size(200, 70); @@ -2448,6 +2787,7 @@ namespace VEPROMS DialogResult result = inputBox.ShowDialog(); input = textBox.Text; + return result; } @@ -2460,23 +2800,28 @@ namespace VEPROMS ProgBarText = args.Text; ProgBarValue = 0; break; + case VolianStatusType.Update: ProgBarText = args.Text; ProgBarValue = args.Count; break; + case VolianStatusType.Complete: ProgBarText = args.Text; ProgBarValue = 0; break; + default: break; } } + void tmrShutDown_Tick(object sender, EventArgs e) { (sender as Timer).Enabled = false; this.Close(); } + private DialogResult ShowEULA() { string eulaFile = string.Format(@"\{0}", VlnSettings.EULAfile); @@ -2485,6 +2830,7 @@ namespace VEPROMS frmViewTextFile ViewFile = new frmViewTextFile(strEULA, RichTextBoxStreamType.PlainText); ViewFile.Text = "End-User License Agreement"; ViewFile.ButtonText = "Agree"; + if (ViewFile.ShowDialog() == DialogResult.OK) { System.Version ver = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; @@ -2492,8 +2838,10 @@ namespace VEPROMS Properties.Settings.Default.LastVersion = thisVersion; return DialogResult.OK; } + return DialogResult.Cancel; } + private bool RunningNewRevision { get @@ -2504,19 +2852,23 @@ namespace VEPROMS return thisVersion != lastVersion; } } + void displayHistory_Enter(object sender, EventArgs e) { tc.HideCaret(); } + void AnnotationTypeInfoList_ListChanged() { displaySearch1.SetupAnnotationSearch(ctrlAnnotationDetails, tc); ctrlAnnotationDetails.SetupAnnotations(displaySearch1); } + private void RunAutomatic() { string[] parameters = System.Environment.CommandLine.Split(" ".ToCharArray()); bool ranAuto = false; + foreach (string parameter in parameters) { if (parameter.StartsWith("/P=")) @@ -2524,76 +2876,81 @@ namespace VEPROMS MSWordToPDF.Automatic = true; PromsPrinter.BaselineTesting = true;// Set Baseline Testing property for PROMsPrinter string[] dvstrs = parameter.Substring(3).Split(",".ToCharArray()); + foreach (string dvstr in dvstrs) { if (dvstr != "") { DocVersionInfo dvi = DocVersionInfo.Get(int.Parse(dvstr)); + if (dvi != null) { DlgPrintProcedure prnDlg = new DlgPrintProcedure(dvi, true); - if (dvi.MultiUnitCount == 0) - prnDlg.SelectedSlave = -1; + + if (dvi.MultiUnitCount == 0) prnDlg.SelectedSlave = -1; prnDlg.AllowDateTimePrefixSuffix = false; //C2018-033 don't append any selected date/time pdf file prefix or suffix (defined in working draft properties) prnDlg.ShowDialog(this); // RHM 20120925 - Center dialog over PROMS window //prnDlg.FormClosed += new FormClosedEventHandler(prnDlg_FormClosed); //while (!_RunNext) Application.DoEvents(); } } + ranAuto = true; } } } + if (ranAuto) { this.Close(); } } - //private bool _RunNext = false; - //void prnDlg_FormClosed(object sender, FormClosedEventArgs e) - //{ - // _RunNext = true; - //} + private FontFamily GetFamily(string name) { foreach (FontFamily ff in FontFamily.Families) if (ff.Name == name) return ff; + return null; } + void tc_ToggleRibbonExpanded(object sender, EventArgs args) { Volian.Base.Library.vlnStackTrace.ShowStackLocal("tc_ToggleRibbonExpanded {0}", ribbonControl1.Expanded); ribbonControl1.Expanded = !ribbonControl1.Expanded; } + void frmVEPROMS_Deactivate(object sender, EventArgs e) { tc.HideCaret(); // Hide the pseudo cursor (caret) } + void tc_Leave(object sender, EventArgs e) { if (tc.ShuttingDown) return; tc.ShowCaret();// Show the pseudo cursor (caret) } + void tc_Enter(object sender, EventArgs e) { tc.HideCaret();// Hide the pseudo cursor (caret) } + void displaySearch1_Enter(object sender, EventArgs e) { tc.HideCaret();// Hide the pseudo cursor (caret) } + void ctrlAnnotationDetails_Enter(object sender, EventArgs e) { tc.HideCaret();// Hide the pseudo cursor (caret) } - //void displayRO_EnabledChanged(object sender, EventArgs e) - //{ - // Console.WriteLine("here"); - //} + void _MyMRIList_AfterRemove(object sender) { SetupMRU(); } + private void SetupButtons() { if (!VlnSettings.DebugMode) @@ -2608,6 +2965,7 @@ namespace VEPROMS btnStepRTF.Visible = false; } } + #region MRU private MostRecentItemList _MyMRIList; private void SetupMRU() @@ -2651,6 +3009,7 @@ namespace VEPROMS Properties.Settings.Default.Save(); } #endregion + #region Tree View /// /// Get the selected tree node's properties @@ -2943,6 +3302,7 @@ namespace VEPROMS } #endregion #endregion + #region ColorStuff /// /// Get a System.Drawing.Color from an Argb or color name @@ -3002,6 +3362,7 @@ namespace VEPROMS // } //} #endregion + #region Table Insert Sample Code // TODO: for tables //private void btnInsTable_Click(object sender, EventArgs e) @@ -3033,6 +3394,7 @@ namespace VEPROMS // //} //} #endregion + #region Progress Bar /// @@ -3103,6 +3465,7 @@ namespace VEPROMS } #endregion + #region Find/Replace and Search /// @@ -3130,6 +3493,7 @@ namespace VEPROMS //} #endregion + #region Similar Steps /// @@ -3146,6 +3510,7 @@ namespace VEPROMS } #endregion + #region Help/About /// @@ -3175,6 +3540,7 @@ namespace VEPROMS } #endregion + #region Ribbon /// /// This Opens the treeView or opens the selected item in the TreeView @@ -3284,6 +3650,7 @@ namespace VEPROMS //displayTransition.CurTrans = null; } #endregion + #region InfoTabLibDocs private void tabItemLibDocs_Click(object sender, EventArgs e) { @@ -3315,6 +3682,7 @@ namespace VEPROMS } } #endregion + #region InfoTabTags private void infotabTags_Click(object sender, EventArgs e) { @@ -3324,6 +3692,7 @@ namespace VEPROMS displayTags.Mydvi = SelectedDVI; } #endregion + #region InfoTabBookMarks private void infotabBookMarks_Click(object sender, EventArgs e) { @@ -3332,6 +3701,7 @@ namespace VEPROMS displayTags.MyEditItem = (SelectedStepTabPanel == null) ? null : SelectedStepTabPanel.MyStepPanel.SelectedEditItem; } #endregion + #region PanelSupport private void tc_WordSectionClose(object sender, WordSectionEventArgs args) { @@ -3530,6 +3900,7 @@ namespace VEPROMS // _TmrRefreshItem.Enabled = false; // if (_RefreshRTB != null) _RefreshRTB.Focus(); //} + private void tc_ItemSelectedChanged(object sender, ItemSelectedChangedEventArgs args) { tc.HideTheCaret(); @@ -3622,8 +3993,8 @@ namespace VEPROMS { infotabRO.Visible = _LastStepRTB.MyItemInfo.MyDocVersion.DocVersionAssociationCount > 0; infotabTransition.Visible = !_CurrentItem.IsFigure && !_CurrentItem.IsRtfRaw; - // don't allow ro insert for a non-ro figure. First check that it is visible (from above line of code), - // and allow for non-figures or ro figures (for replace of existing ro figures) + // don't allow RO insert for a non-RO figure. First check that it is visible (from above line of code), + // and allow for non-figures or RO figures (for replace of existing RO figures) infotabRO.Visible = infotabRO.Visible && (!_CurrentItem.IsRtfRaw && (!_CurrentItem.IsFigure || (_CurrentItem.IsFigure && _CurrentItem.MyContent.MyImage == null))); displayRO.Enabled = _LastStepRTB.EditMode || _LastStepRTB.IsRoTable; displayTransition.Enabled = _LastStepRTB.EditMode; @@ -3657,9 +4028,9 @@ namespace VEPROMS // see if format has floating foldouts, and if so, display the panel. if (args.MyEditItem.MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.AlternateFloatingFoldout) { + infotabFoldoutMaint.Visible = true; displayFoldoutMaint.Visible = true; - infotabFoldoutMaint.Visible = true; displayFoldoutMaint.Enabled = true; displayFoldoutMaint.MyItemInfo = args.MyItemInfo; } @@ -3734,28 +4105,6 @@ namespace VEPROMS btnPrint.Enabled = (_CurrentItem != null); } - /*KBR:Timer _tmrSetTransROInVisible; - public Timer TmrSetTransROInVisible - { - get - { - if (_tmrSetTransROInVisible == null) - { - _tmrSetTransROInVisible = new Timer(); - _tmrSetTransROInVisible.Enabled = false; - _tmrSetTransROInVisible.Interval = 50; - _tmrSetTransROInVisible.Tick += _tmrSetTransROInVisible_Tick; - } - return _tmrSetTransROInVisible; - } - } - void _tmrSetTransROInVisible_Tick(object sender, EventArgs e) - { - TmrSetTransROInVisible.Enabled = false; - infotabTransition.Visible = false; - infotabRO.Visible = false; - } - */ void _LastStepRTB_EditModeChanged(object sender, EventArgs args) { if (_LastStepRTB.EditMode) // going into edit mode in a cell of the grid. @@ -4060,6 +4409,7 @@ namespace VEPROMS { } #endregion + #region PanelEvents private void infoPanel_Click(object sender, EventArgs e) { @@ -4246,15 +4596,7 @@ namespace VEPROMS private void btnPrint_Click(object sender, EventArgs e) { - //VETreeNode vtn = tv.SelectedNode as VETreeNode; - //DocVersionInfo dvi = vtn.VEObject as DocVersionInfo; - //while (dvi == null) - //{ - // vtn = vtn.Parent as VETreeNode; - // dvi = vtn.VEObject as DocVersionInfo; - //} - //string pnum = DisplayText.StaticStripRtfCommands(this._CurrentItem.MyProcedure.ProcedureConfig.Number).Replace("\\u8209?", "-"); - DlgPrintProcedure prnDlg = new DlgPrintProcedure(this._CurrentItem.MyProcedure);//dvi.DocVersionConfig,pnum); + DlgPrintProcedure prnDlg = new DlgPrintProcedure(this._CurrentItem.MyProcedure); prnDlg.MySessionInfo = MySessionInfo; prnDlg.ShowDialog(this); // RHM 20120925 - Center dialog over PROMS window } @@ -4279,6 +4621,7 @@ namespace VEPROMS { lblResolution.Text = string.Format("Resolution {0} x {1}", Size.Width, Size.Height); } + private void office2007StartButton1_MouseDown(object sender, MouseEventArgs e) { // Refresh the MostRecentlyUsedList @@ -4294,8 +4637,11 @@ namespace VEPROMS pg.Show(); } else + { MessageBox.Show("Select Item First", "Item not selected", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); + } } + private void btnUpdateFormat_Click(object sender, EventArgs e) { UpdateFormats(null); @@ -4307,6 +4653,7 @@ namespace VEPROMS { string fmtPath = Properties.Settings.Default.FormatPath ?? ""; DirectoryInfo di = null; + do { fbd.Description = "Select folder containing FmtAll and GenMacAll folders to update formats"; @@ -4320,15 +4667,20 @@ namespace VEPROMS di = new DirectoryInfo(fbd.SelectedPath); fmtPath = di.FullName; } while (((fmtPath ?? "") == "") || (!di.Exists || !Directory.Exists(di.FullName + @"\fmtall") || !Directory.Exists(di.FullName + @"\genmacall"))); + Properties.Settings.Default.FormatPath = fbd.SelectedPath; Properties.Settings.Default.Save(); + mypath = di.FullName; } + string fmtPathAll = mypath + @"\fmtall"; string genmacPathAll = mypath + @"\genmacall"; + Format.FormatLoaded += new FormatEvent(Format_FormatLoaded); Format.UpdateFormats(fmtPathAll, genmacPathAll); Format.FormatLoaded -= new FormatEvent(Format_FormatLoaded); + _MyLog.WarnFormat("Formats in {0} updated to {1}", Database.SelectedDatabase, fmtPathAll); } @@ -4342,11 +4694,18 @@ namespace VEPROMS else { if (args.Status.StartsWith("Error")) + { MessageBox.Show(args.Status, "Error Loading Format", MessageBoxButtons.OK, MessageBoxIcon.Error); - else if (!args.Status.Contains("SubFormat")) bottomProgBar.Value++; + } + else if (!args.Status.Contains("SubFormat")) + { + bottomProgBar.Value++; + } } + bottomProgBar.Text = args.Status; bottomProgBar.TextVisible = true; + Application.DoEvents(); Console.WriteLine(args.Status); } @@ -4356,12 +4715,14 @@ namespace VEPROMS try { frmSendErrorLog frm = new frmSendErrorLog(Properties.Settings.Default.OutlookEmail, Properties.Settings.Default["SMTPServer"].ToString(), Properties.Settings.Default["SMTPUser"].ToString(), ErrorLogFileName); + if (frm.ShowDialog(this) == DialogResult.OK) { Properties.Settings.Default.OutlookEmail = frm.OutlookEmail; Properties.Settings.Default.SMTPServer = frm.SMTPServer; Properties.Settings.Default.SMTPUser = frm.SMTPUser; Properties.Settings.Default.Save(); + MessageBox.Show("PROMS Error Log successfully sent to Volian support"); } } @@ -4372,12 +4733,13 @@ namespace VEPROMS } } - // C2019-024 Display the PROMS User Manual when user click on the option in the Help drop down menu - // PROMS looks for "PROMSmanual.pdf" in the executable folder. If not found, a message box - // will display. private void btnHelpManual_Click(object sender, EventArgs e) { + // C2019-024 Display the PROMS User Manual when user click on the option in the Help drop down menu + // PROMS looks for "PROMSmanual.pdf" in the executable folder. If not found, a message box will display. + string promsUserManual = System.Windows.Forms.Application.StartupPath + @"\PROMSManual.pdf"; + try { if (File.Exists(promsUserManual)) @@ -4399,7 +4761,9 @@ namespace VEPROMS } } } - #region Lock stuff / used for multi-user support + + #region (Lock stuff / used for multi-user support) + public class TabItemsToClose : Stack { public void PushDTI(DisplayTabItem dti) @@ -4410,6 +4774,7 @@ namespace VEPROMS this.Push(dti); } } + public DisplayTabItem PopDTI() { lock (this) @@ -4417,6 +4782,7 @@ namespace VEPROMS return this.Pop(); } } + public int CountDTI { get @@ -4428,7 +4794,9 @@ namespace VEPROMS } } } + #endregion + public class VersionWindow { private int _VersionID; @@ -4437,23 +4805,21 @@ namespace VEPROMS get { return _VersionID; } set { _VersionID = value; } } + private int _DBId; public int DBId { get { return _DBId; } set { _DBId = value; } } + private Rectangle _MyRectangle; public Rectangle MyRectangle { get { return _MyRectangle; } set { _MyRectangle = value; } } - public override string ToString() - { - RectangleConverter rc = new RectangleConverter(); - return string.Format("{0}~{1}", _VersionID, rc.ConvertToString(_MyRectangle)); - } + public VersionWindow(string str) { string[] parts = str.Split('~'); @@ -4461,27 +4827,45 @@ namespace VEPROMS RectangleConverter rc = new RectangleConverter(); _MyRectangle = (Rectangle)rc.ConvertFromString(parts[1]); } + + public override string ToString() + { + RectangleConverter rc = new RectangleConverter(); + return string.Format("{0}~{1}", _VersionID, rc.ConvertToString(_MyRectangle)); + } } + public class VersionWindowList : List { public static VersionWindowList GetVersionWindowList(System.Collections.Specialized.StringCollection list) { VersionWindowList vwl = new VersionWindowList(); + if (list != null) { foreach (string str in list) + { vwl.Add(new VersionWindow(str)); + } } + return vwl; } + public System.Collections.Specialized.StringCollection ToSettings() { if (Count == 0) return null; + System.Collections.Specialized.StringCollection retval = new System.Collections.Specialized.StringCollection(); + foreach (VersionWindow vw in this) + { retval.Add(vw.ToString()); + } + return retval; } + public new void Add(VersionWindow versionWindow) { foreach (VersionWindow vw in this) @@ -4492,6 +4876,7 @@ namespace VEPROMS break; } } + base.Add(versionWindow); } } diff --git a/PROMS/VEPROMS.CSLA.Library/Config/DocVersionConfig.cs b/PROMS/VEPROMS.CSLA.Library/Config/DocVersionConfig.cs index 0a01be7a..9a2f75b6 100644 --- a/PROMS/VEPROMS.CSLA.Library/Config/DocVersionConfig.cs +++ b/PROMS/VEPROMS.CSLA.Library/Config/DocVersionConfig.cs @@ -68,6 +68,7 @@ namespace VEPROMS.CSLA.Library } } } + public partial class DVEnhancedDocument { private string _Name; @@ -114,6 +115,7 @@ namespace VEPROMS.CSLA.Library return string.Format("{0}.ItemID={1}", Name,VersionID); } } + [Serializable] [TypeConverter(typeof(ExpandableObjectConverter))] public class DocVersionConfig : ConfigDynamicTypeDescriptor, INotifyPropertyChanged @@ -123,6 +125,7 @@ namespace VEPROMS.CSLA.Library { _MyEnhancedDocuments = null; } + public void RemoveEnhancedLink(int dvid) { // from this config, remove the link to the input dvid (DocVersionId: @@ -130,6 +133,7 @@ namespace VEPROMS.CSLA.Library if (xnx == null) return; // B2020-069: check for null reference before accessing xnx. xnx.ParentNode.RemoveChild(xnx); } + private DVEnhancedDocuments _MyEnhancedDocuments = null; public DVEnhancedDocuments MyEnhancedDocuments { @@ -143,15 +147,16 @@ namespace VEPROMS.CSLA.Library } set { _MyEnhancedDocuments = value; } } + public void SaveDVEnhancedDocuments() { - // get all of the current enhanced links from datastructure in code. This list may have been + // get all of the current enhanced links from data structure in code. This list may have been // modified by adding items during code execution by associating source <--> background etc. DVEnhancedDocuments edsToAdd = new DVEnhancedDocuments(); foreach (DVEnhancedDocument ed in MyEnhancedDocuments) edsToAdd.Add(ed); - // from the existing list in xml, remove any that are in the 'editted (edsToAdd) list + // from the existing list in xml, remove any that are in the 'edited (edsToAdd) list // so that what remains are those that need added to xml that will then be written to database foreach (XmlNode xn in _Xp.XmlContents.SelectNodes("//Enhanced")) { @@ -192,12 +197,14 @@ namespace VEPROMS.CSLA.Library xa.Value = edadd.PdfToken; } } + #region DynamicTypeDescriptor internal override bool IsReadOnly { get { return _DocVersion == null; } } #endregion + #region XML private XMLProperties _Xp; private XMLProperties Xp @@ -205,6 +212,7 @@ namespace VEPROMS.CSLA.Library get { return _Xp; } } #endregion + #region Constructors //PROPGRID: Hide ParentLookup [Browsable(false)] @@ -230,6 +238,7 @@ namespace VEPROMS.CSLA.Library _Xp = new XMLProperties(xml); if (docVersion.MyDocVersionInfo.MyFolder != null) _Xp.LookInAncestor += new XMLPropertiesEvent(Xp_LookInAncestorFolder); } + private string Xp_LookInAncestorFolder(object sender, XMLPropertiesArgs args) { if (args.AncestorLookup || ParentLookup) @@ -242,6 +251,7 @@ namespace VEPROMS.CSLA.Library } return string.Empty; } + //private string Xp_LookInAncestorFolderInfo(object sender, XMLPropertiesArgs args) //{ // if (args.AncestorLookup || ParentLookup) @@ -282,6 +292,7 @@ namespace VEPROMS.CSLA.Library _Xp[group, item] = newvalue; } #endregion + #region Local Properties [Category("General")] [DisplayName("Name")] @@ -360,6 +371,7 @@ namespace VEPROMS.CSLA.Library set { _SaveChangesToDocVersionConfig = value; } } #endregion + #region ToString public override string ToString() { @@ -368,6 +380,7 @@ namespace VEPROMS.CSLA.Library return s; } #endregion + // #region RODefaults // From proc.ini @@ -446,6 +459,7 @@ namespace VEPROMS.CSLA.Library } } #endregion + #region PrintSettingsCategory // From curset.dat [Category("Print Settings")] //PROPGRID: Hide Printer @@ -1466,6 +1480,7 @@ namespace VEPROMS.CSLA.Library } #endregion #endregion + #region Unit // From PROC.INI //MultiUnitCount [Category("Unit")] @@ -1479,6 +1494,8 @@ namespace VEPROMS.CSLA.Library return _Xp.XmlContents.SelectNodes("//Slave").Count; } } + + private int _SelectedSlave = 0; //[Browsable(false)] public int SelectedSlave @@ -1560,8 +1577,10 @@ namespace VEPROMS.CSLA.Library get { string s = GetCombinedSlaveValue("Name") ?? _Xp["Unit", "Name"];// get the saved value + if (SelectedSlave > 0) s = _Xp["Slave[@index='" + SelectedSlave.ToString() + "']", "Name"]; + return s; } set @@ -1570,9 +1589,11 @@ namespace VEPROMS.CSLA.Library _Xp["Slave[@index='" + SelectedSlave.ToString() + "']", "Name"] = value; // save selected value else _Xp["Unit", "Name"] = value; + OnPropertyChanged("Unit_Name"); } } + [Category("Unit")] [DisplayName("Other Unit Name")] [RefreshProperties(RefreshProperties.All)] @@ -2369,4 +2390,4 @@ OnPropertyChanged("Default_BkColor"); } #endregion } -} \ No newline at end of file +} diff --git a/PROMS/VEPROMS.CSLA.Library/Config/ROFSTLookup.cs b/PROMS/VEPROMS.CSLA.Library/Config/ROFSTLookup.cs index 37e2663d..35bb4bbe 100644 --- a/PROMS/VEPROMS.CSLA.Library/Config/ROFSTLookup.cs +++ b/PROMS/VEPROMS.CSLA.Library/Config/ROFSTLookup.cs @@ -113,31 +113,12 @@ namespace VEPROMS.CSLA.Library public rochild[] children; }; - - public class roChild + public class RoExtension { - //private static int _roChildUnique = 0; - //private static int roChildUnique - //{ get { return ++_roChildUnique; } } - //private int _MyRoChildUnique = roChildUnique; - //public int MyRoChildUnique // Absolutely Unique ID - Info - //{ get { return _MyRoChildUnique; } } - rochild _MyChild; - public rochild MyChild - { - get { return _MyChild; } - set { _MyChild = value; } - } - public roChild(rochild myChild) - { - _MyChild = myChild; - } - public override string ToString() - { - return _MyChild.title.Replace("\\u160?", " "); - } - }; - + public int Offset; + public string RoidExt; + public string AccPageExt; + } #endregion @@ -146,6 +127,10 @@ namespace VEPROMS.CSLA.Library public static Regex regRoKeyHigh = new Regex("( |-|_)(HIGH|HI)([0-9])"); public static Regex regRoKeyLow = new Regex("( |-|_)(LOW|LO)([0-9])"); + public const string RoMissingDefaultValue = "[TBD]"; + + private static List _extensions; + // RofstLookup/Conversion Variables private int _rofstID; private DocVersionInfo _myDocVersionInfo; @@ -197,6 +182,19 @@ namespace VEPROMS.CSLA.Library set { _itemInfo = value; } } + public List Extensions + { + get + { + if (_extensions == null) + { + _extensions = RofstDataGetExtensions(); + } + + return _extensions; + } + } + #endregion #region Constructors @@ -239,216 +237,14 @@ namespace VEPROMS.CSLA.Library #region Public Methods - #region (RO Info) + #region (RO Search / Collections) - public bool HasChildren(ref ROFSTLookup.rochild child) - { - LoadChildren(ref child); - return child.children.Any(); - } - - public bool HasChildren(ref ROFSTLookup.rodbi db) - { - LoadChildren(ref db); - return db.children.Any(); - } - - public void LoadChildren(ref ROFSTLookup.rochild child) - { - // If Children is null then it hasn't been loaded yet - if (child.children == null || child.children.Length <= 0) - { - if (!string.IsNullOrEmpty(child.appid)) - child = GetRoChild12(child.roid, true); - else - child.children = GetRoChildrenByRoid(child.roid, true); - } - } - - public void LoadChildren(ref ROFSTLookup.rodbi db) - { - // If Children is null then it hasn't been loaded yet - if (db.children == null || db.children.Length <= 0) - db.children = GetRoChildrenByID(db.ID, db.dbiID, true); - } - - - - public ROFSTLookup.rochild GetRoChild(string ROID, bool loadChildren = false, bool loadAllChildren = false) - { - ROFSTLookup.rochild rc = new ROFSTLookup.rochild() { ID = -1 }; - - if (ROID.StartsWith("FFFF")) - { - rc.ID = 0; - rc.ParentID = 0; - rc.roid = ROID; - rc.type = 1; - rc.value = GetRoValue(ROID); - - if (ROID == "FFFF00000001") rc.appid = "U-Number"; - else if (ROID == "FFFF00000002") rc.appid = "U-Other Number"; - else if (ROID == "FFFF00000003") rc.appid = "U-Text"; - else if (ROID == "FFFF00000004") rc.appid = "U-Other Text"; - else if (ROID == "FFFF00000005") rc.appid = "U-ID"; - else if (ROID == "FFFF00000006") rc.appid = "U-Other ID"; - else if (ROID == "FFFF00000007") rc.appid = "U-Name"; - else if (ROID == "FFFF00000008") rc.appid = "U-Other Name"; - else rc.appid = "U-Unknown"; - } - else - { - rc = GetRoChild12(ROID, loadChildren, loadAllChildren); - - if (rc.children != null && rc.children.Length > 0) - { - foreach (ROFSTLookup.rochild c in rc.children) - { - if (c.roid.ToUpper() == ROID.ToUpper()) - { - return c; - } - } - } - } - - return rc; - } - - public string GetRoValue(string ROID16) - { - // This only gets rochild values, not groups - string ROID = ROID16.Substring(0, 12); - - if (ROID.StartsWith("FFFF")) - { - DocVersionConfig dvc = _myDocVersionInfo.DocVersionConfig; - - if (ROID == "FFFF00000001") return dvc.Unit_Number; - if (ROID == "FFFF00000002") return dvc.Other_Unit_Number; - if (ROID == "FFFF00000003") return dvc.Unit_Text; - if (ROID == "FFFF00000004") return dvc.Other_Unit_Text; - if (ROID == "FFFF00000005") return dvc.Unit_ID; - if (ROID == "FFFF00000006") return dvc.Other_Unit_ID; - if (ROID == "FFFF00000007") return dvc.Unit_Name; - if (ROID == "FFFF00000008") return dvc.Other_Unit_Name; - - } - - ROFSTLookup.rochild rc = GetRoChild12(ROID); - - if (rc.ID > 0) - { - if (!string.IsNullOrEmpty(rc.value)) - { - return FixUnitROs(GetParentChildROValue(rc)); - } - - if (rc.children != null && rc.children.Length > 0) - { - foreach (ROFSTLookup.rochild c in rc.children) - { - if (c.roid.ToUpper() == ROID16.ToUpper() || (c.roid.EndsWith("0041") && ROID16.EndsWith("0000"))) - { - return FixUnitROs(GetParentChildROValue(c) ?? "?"); - } - } - - // if there isn't a specific match for multi-return values, default to the first child. - return FixUnitROs(GetParentChildROValue(rc.children[0]) ?? "?"); - } - } - - return "?"; - } - - public string GetParentChildROValue(ROFSTLookup.rochild roc) - { - // C2021-026 Get the child RO value if it exists, otherwise to the default (parent) RO value - // C2022-001 new logic to handle new format of Parent/Child RO.FST - // The RO.FST will not have a specific child value if that child value is the same as the default value - - string roval = roc.value; - - // B2021-093 Don't look for child RO values if "roval" is null - if (roval == null) return null; - - // B2022-020 remove a un-needed question mark that was in the search criteria "(" - // B2022-050 change the search string from "(" to "" to handle when RO values have less then sign - // B2022-077 Need to use the RegexOption of Singleline to handle cases of an RO Return value having ascii newline characters (\r\n) - MatchCollection mm = Regex.Matches(roval, "", RegexOptions.Singleline); - - // C2022-014 commented write to error log. Keep for debugging purposes. - //if (mm.Count == 0) // B2022-020 will now write in error log if there is a problem - // _MyLog.WarnFormat("Parent/Child Values not parsable for \r\nItemId={0}\r\nROValue={1} ",MyDocVersionInfo.ItemID,roval); - - StringBuilder sb = new StringBuilder(); - int lastIndex = 0; - - // Get selected child Idx - int selChldIdx = this.SelectedSlave; - - // Get Selected Child Value - foreach (Match m in mm) - { - sb.Append(roval.Substring(lastIndex, m.Index - lastIndex)); - - string aplString = m.Value; - string chldValStr = string.Format("UnitIdx={0} Value=", selChldIdx); - int offsetIdx = aplString.IndexOf(chldValStr); - int nextIDX = -1; - - if (offsetIdx == -1) - { - offsetIdx = aplString.IndexOf("DefaultVal=") + 11; - } - else - { - offsetIdx += chldValStr.Length; - } - - nextIDX = aplString.IndexOf(",UnitIdx", offsetIdx); - if (nextIDX == -1) nextIDX = aplString.IndexOf(" /APL>"); - sb.Append(aplString.Substring(offsetIdx, nextIDX - offsetIdx)); - - lastIndex = m.Index + m.Length; - } - - // B2022-018 append any remaining text - if (lastIndex < roval.Length) - { - sb.Append(roval.Substring(lastIndex)); - } - - return sb.ToString(); - } - - public string GetTranslatedRoValue(string ROID16, bool DoCaret, bool DoDOSSuperSubScript) - { - string retval = GetRoValue(ROID16); - retval = ReplaceUnicode(retval, DoCaret); - retval = ConvertFortranFormatToScienctificNotation(retval); - - // B2019-037 handle the super an sub scripts after getting the RO value from the FST - // the corrected RO text is added to the display text in the link info - if (DoDOSSuperSubScript) - { - retval = Regex.Replace(retval, "[#](.*?)[#]", "\\up2 $1\\up0 ");// Superscript - retval = Regex.Replace(retval, "[~](.*?)[~]", "\\dn2 $1\\up0 ");// Subscript - } - - return retval.Replace("\r\n", @"\par "); - } - - - - - public Dictionary Search(string value, int searchTypeID, int? maxNumRecords = null) + public Dictionary Search(string value, int searchTypeID, bool onlyRoid16, int? maxNumRecords = null) { if (string.IsNullOrEmpty(value)) return null; - return RofstDataSearch(_rofstID, value, searchTypeID, maxNumRecords); + return RofstDataSearch(_rofstID, value, searchTypeID, onlyRoid16, maxNumRecords); } public ROFSTLookup.rochild[] GetRoChildrenByID(int id, int dbiID, bool loadChildren = false, bool loadAllChildren = false) @@ -466,96 +262,6 @@ namespace VEPROMS.CSLA.Library return RofstDataGetRoChildrenByType(_rofstID, valueTypes, loadChildren, loadAllChildren); } - public List GetValueDifferences(int originalRofstID, ref List delList) - { - return RofstDataGetValueDifferences(originalRofstID, _rofstID, ref delList); - } - - public List GetROTitleAndGroupPath(string ROID, bool reportMissingROs, bool convertCaretToDelta) - { - // Return the RO Title in a list of strings. The last item in the list is the actual RO title, - // the items preceding it are the titles of the groups and sub-groups containing the RO - - List titlePath = new List(); - - ROFSTLookup.rochild roc = GetRoChild12(ROID); - - if (roc.appid != null) - { - string tmp = roc.title; - - if (roc.appid != string.Empty && roc.title.Contains(roc.appid)) - { - tmp = roc.title.Replace(roc.appid, "").Trim(); - } - - tmp = string.Format("[{0}] {1}", roc.appid, tmp); - tmp = tmp.Replace("`", "\u00B0"); //degree - tmp = tmp.Replace("\xF8", "\u00B0"); //degree - if (convertCaretToDelta) tmp = tmp.Replace("^", "\u0394"); // delta - - titlePath.Add(tmp); - - do - { - string parent = ROID.Substring(0, 4) + string.Format("{0:X8}", roc.ParentID); - roc = GetRoChild12(parent); - if (roc.ID > 0) titlePath.Add(roc.title.Trim()); - - } while (roc.ID > 0); - - titlePath.Reverse(); - } - else if (reportMissingROs) // Missing RO, put a message with the ROID on the report... - { - titlePath.Add(string.Format("Missing RO for ROID {0}", ROID)); - } - - return titlePath; - } - - public string GetROTitle(string ROID) - { - StringBuilder sb = new StringBuilder(); - - ROFSTLookup.rochild rc = GetRoChild12(ROID); - if (rc.value == null) rc = GetRoChild(ROID); - - // B2020-125: View of Consistency check report displaying error message and crashing. And also in 'else' check for null - if (rc.ID == -1) - { - sb.Append("Could not find RO data"); - } - else - { - string tmp = string.Empty; - if (!string.IsNullOrEmpty(rc.title)) tmp = rc.title; - if (!string.IsNullOrEmpty(rc.appid)) tmp = tmp.Replace(rc.appid, string.Empty); - if (!string.IsNullOrEmpty(rc.value)) tmp = tmp.Replace(rc.value, string.Empty); - sb.Append(tmp.Trim()); - } - - do - { - string parentROID = ROID.Substring(0, 4) + string.Format("{0:X8}", rc.ParentID); - rc = GetRoChild12(parentROID); - if (rc.ID > 0) sb.Insert(0, rc.title + " - "); - - } while (rc.ID > 0); - - return sb.ToString(); - } - - public DateTime GetRoFSTdts() - { - return GetRofstDtsByID(_rofstID); - } - - public static byte[] GetRofstLookupBytes(int rofstID) - { - return RofstDataGetRofstLookupBytes(rofstID); - } - #endregion #region (RO Database Info) @@ -587,67 +293,339 @@ namespace VEPROMS.CSLA.Library #region (RO Info By AccPageID) - public string GetROValueByAccPagID(string accPageID, string spDefault, string igDefault) + public static string FormatAccPageKey(string accPageID, string spDefault, string igDefault) { - ROFSTLookup.rochild? child = GetROChildByAccPageID(accPageID, spDefault, igDefault); - if (child == null) return null; - return GetParentChildROValue((ROFSTLookup.rochild)child); // C2021-026 get the P/C value if it exists, otherwise get the non-P/C value - } - - public int? GetROTypeByAccPagID(string accPageID, string spDefault, string igDefault) - { - ROFSTLookup.rochild? child = GetROChildByAccPageID(accPageID, spDefault, igDefault); - if (child == null) return null; - return ((ROFSTLookup.rochild)child).type; - } - - public string GetROIDByAccPagID(string accPageID, string spDefault, string igDefault) - { - ROFSTLookup.rochild? child = GetROChildByAccPageID(accPageID, spDefault, igDefault); - if (child == null) return null; - return ((ROFSTLookup.rochild)child).roid; - } - - public ROFSTLookup.rochild? GetROChildByAccPageID(string accPageID, string spDefault, string igDefault) - { - ROFSTLookup.rochild? child = GetRoChildByAccPagID(accPageID, spDefault, igDefault); - - if (child == null) + if (!string.IsNullOrEmpty(accPageID)) { - if (Regex.IsMatch(accPageID, @".*\.[A-Z]")) - { - string accpage = accPageID.Substring(0, accPageID.Length - 3); - int index = accPageID.Substring(accPageID.Length - 2, 1)[0] - 'A'; - child = GetRoChildByAccPagID(accpage.TrimStart("<".ToCharArray()), spDefault, igDefault); + accPageID = accPageID.ToUpper(); + + if (!accPageID.StartsWith("<")) + accPageID = string.Format("<{0}", accPageID); - if (child == null) return null; + if (!accPageID.EndsWith(">")) + accPageID = string.Format("{0}>", accPageID); - if (((ROFSTLookup.rochild)child).children != null && ((ROFSTLookup.rochild)child).children.Length > 0 && ((ROFSTLookup.rochild)child).children.Length > index) - { - return ((ROFSTLookup.rochild)child).children[index]; - } - } + accPageID = accPageID.Replace("", ""); + accPageID = accPageID.ToCleanString(); // Removes any spaces - return null; + // Clean up the AccPageID before using it to do a lookup + if (!string.IsNullOrEmpty(spDefault)) + accPageID = accPageID.Replace("".ToCharArray()); // String < and > + + accPageID = regRoKeyHigh.Replace(accPageID, "_HIGH$3"); + accPageID = regRoKeyLow.Replace(accPageID, "_LOW$3"); + accPageID = accPageID.ToUpper(); } - if (((ROFSTLookup.rochild)child).children != null && ((ROFSTLookup.rochild)child).children.Length > 0) - return ((ROFSTLookup.rochild)child).children[0]; - - return (ROFSTLookup.rochild)child; + return accPageID; } - public ROFSTLookup.rochild? GetRoChildByAccPagID(string accPageID, string spDefault, string igDefault) + public static string FormatAccPageKey(string accPageID, string spDefault, string igDefault, ref string accPageBase, ref string accPageExt, bool useDefaultExt = true) { - accPageID = accPageID.Replace("".ToCharArray()); // String < and > - string key = FormatKey(accPageID); + string accPageKey = FormatAccPageKey(accPageID, spDefault, igDefault); - ROFSTLookup.rochild rc = RofstDataGetChildByAccPageID(_rofstID, key); - if (rc.ID > 0) return rc; + if (Regex.IsMatch(accPageKey, @".*\.[A-Z]")) + { + accPageBase = accPageKey.Substring(0, accPageKey.Length - 2); + accPageExt = Convert.ToString(accPageKey.ToCharArray().LastOrDefault()); + } + else + { + accPageBase = accPageKey; + accPageExt = (!accPageKey.StartsWith(" 0) + { + // Check if AccPageID/Key has a return value specific extension. Try to find the RoChild record with the specific return value type, + // If not found then return the first/default return value type in the list of children + var accPageExt = Convert.ToString(accPageKey.ToCharArray().LastOrDefault()); + var roExt = Extensions.Where(x => x.AccPageExt.Equals(accPageExt)).SingleOrDefault(); + + return (rc.children.Where(x => x.roid.Substring(12, 4) == roExt.RoidExt).Any()) ? rc.children.Where(x => x.roid.Substring(12, 4) == roExt.RoidExt).Single() : rc.children.First(); + } + + return rc; // If RoChild is not found, then a default (ROFSTLookup.rochild) object will be returned, but its ID will be -1 + } + + #endregion + + #region (RO Info By Roid) + + public static string FormatRoidKey(string roid, bool check16Digits = false) + { + if (!string.IsNullOrEmpty(roid)) + { + roid = roid.ToUpper(); + roid = roid.Replace("", ""); + roid = roid.ToCleanString(); // Removes any spaces + + if ((!roid.StartsWith("") + roid = FormatRoidKey(roid); + + ROFSTLookup.rochild rc = GetRoChild12(roid, loadChildren, loadAllChildren); + + if (!roid.StartsWith("FFFF") && roid.Length == 16 && rc.children != null && rc.children.Length > 0) + { + // If specific match exists for multi-return values, then return specified value, otherwise default to the first child + if (rc.children.Where(x => x.roid.ToUpper() == roid.ToUpper()).Any()) + return rc.children.Where(x => x.roid.ToUpper() == roid.ToUpper()).Single(); + else + return rc.children.First(); + } + + return rc; + } + + + public string GetRoValue(string roid) + { + return GetRoChild(roid).value; + } + + public string GetTranslatedRoValue(string roid, bool DoCaret, bool DoDOSSuperSubScript) + { + roid = FormatRoidKey(roid); + + string retval = GetRoValue(roid); + retval = ReplaceUnicode(retval, DoCaret); + retval = ConvertFortranFormatToScienctificNotation(retval); + + // B2019-037 handle the super an sub scripts after getting the RO value from the FST + // the corrected RO text is added to the display text in the link info + if (DoDOSSuperSubScript) + { + retval = Regex.Replace(retval, "[#](.*?)[#]", "\\up2 $1\\up0 ");// Superscript + retval = Regex.Replace(retval, "[~](.*?)[~]", "\\dn2 $1\\up0 ");// Subscript + } + + return (!string.IsNullOrEmpty(retval)) ? retval.Replace("\r\n", @"\par ") : retval; + } + + public static string GetParentChildDefaultValue(string roval) + { + var test = GetParentChildROValue(roval, 0); + + // C2021-026 Get the Parent (Default) RO value if the return value include P/C information otherwise return the RO value as is. + // This is used for the insert RO interface on the Step Properties panel + if (string.IsNullOrEmpty(roval)) + return null; + + + string rntval = roval.Replace("\xFF", "\xa0").Replace(@"\u160?", " "); + + while (rntval.Contains("", startCVIdx); + string aplicValues = rntval.Substring(startCVIdx, EndCVidx + 6 - startCVIdx); + int endDefIdx = rntval.IndexOf(",", startCVIdx); + + // C2022-001 - handle if there is no child value in the RO FSt + // B2022-051 - was sometimes leaving "/APL>" when processing return value made up from multiple RO (editor) fields + // added check to make where next found comma was within the current + string defValue = rntval.Substring(startCVIdx + 16, ((endDefIdx > 0 && endDefIdx < EndCVidx) ? endDefIdx : EndCVidx) - (startCVIdx + 16)); + rntval = rntval.Replace(aplicValues, defValue); + } + + rntval = rntval.Trim(); + + // If Default Value is selected (selChldIdx = 0), and return value is empty then replace with Standard Missing Default Value + return (string.IsNullOrEmpty(rntval)) ? ROFSTLookup.RoMissingDefaultValue : rntval; + //return rntval; + } + + + + public List GetValueDifferences(int originalRofstID, ref List delList) + { + return RofstDataGetValueDifferences(originalRofstID, _rofstID, ref delList); + } + + public List GetROTitleAndGroupPath(string roid, bool reportMissingROs, bool convertCaretToDelta) + { + // Return the RO Title in a list of strings. The last item in the list is the actual RO title, + // the items preceding it are the titles of the groups and sub-groups containing the RO + + List titlePath = new List(); + + roid = FormatRoidKey(roid); + + ROFSTLookup.rochild roc = GetRoChild12(roid); + + if (!string.IsNullOrEmpty(roc.appid)) + { + string tmp = roc.title; + + if (!string.IsNullOrEmpty(roc.appid) && roc.title.Contains(roc.appid)) + { + tmp = roc.title.Replace(roc.appid, string.Empty).Trim(); + } + + tmp = string.Format("[{0}] {1}", roc.appid, tmp); + tmp = tmp.Replace("`", "\u00B0"); //degree + tmp = tmp.Replace("\xF8", "\u00B0"); //degree + if (convertCaretToDelta) tmp = tmp.Replace("^", "\u0394"); // delta + + titlePath.Add(tmp); + + if (roc.ParentID > 0) + { + do + { + string parent = roid.Substring(0, 4) + string.Format("{0:X8}", roc.ParentID); + roc = GetRoChild12(parent); + if (roc.ID >= 0) titlePath.Add(roc.title.Trim()); + + } while (roc.ID >= 0); + } + + titlePath.Reverse(); + } + else if (reportMissingROs) // Missing RO, put a message with the ROID on the report... + { + titlePath.Add(string.Format("Missing RO for ROID {0}", roid)); + } + + return titlePath; + } + + public string GetROTitle(string roid) + { + StringBuilder sb = new StringBuilder(); + + roid = FormatRoidKey(roid); + ROFSTLookup.rochild rc = GetRoChild(roid); + + // B2020-125: View of Consistency check report displaying error message and crashing. And also in 'else' check for null + if (rc.ID < 0) + { + sb.Append("Could not find RO data"); + } + else + { + string tmp = string.Empty; + if (!string.IsNullOrEmpty(rc.title)) tmp = rc.title; + if (!string.IsNullOrEmpty(rc.appid)) tmp = tmp.Replace(rc.appid, string.Empty); + if (!string.IsNullOrEmpty(rc.value)) tmp = tmp.Replace(rc.value, string.Empty); + sb.Append(tmp.Trim()); + } + + if (rc.ParentID > 0) + { + do + { + string parentROID = roid.Substring(0, 4) + string.Format("{0:X8}", rc.ParentID); + rc = GetRoChild12(parentROID); + if (rc.ID > 0) sb.Insert(0, rc.title + " - "); + + } while (rc.ID > 0); + + } + + return sb.ToString(); + } + + #endregion + + #region (RO Info Helper Methods) + + public static byte[] GetRofstLookupBytes(int rofstID) + { + return RofstDataGetRofstLookupBytes(rofstID); + } + + public static DateTime GetRoFSTdts(int rofstID) + { + return GetRofstDtsByID(rofstID); + } + + public DateTime GetRoFSTdts() + { + return GetRoFSTdts(_rofstID); + } + + public bool HasChildren(ref ROFSTLookup.rochild child) + { + LoadChildren(ref child); + return child.children.Any(); + } + + public bool HasChildren(ref ROFSTLookup.rodbi db) + { + LoadChildren(ref db); + return db.children.Any(); + } + + public void LoadChildren(ref ROFSTLookup.rochild child) + { + // If Children is null then it hasn't been loaded yet + //if (child.children == null || child.children.Length <= 0) + if (child.children == null) + { + if (!string.IsNullOrEmpty(child.appid)) + child = GetRoChild12(child.roid, true); + else + //child.children = GetRoChildrenByRoid(child.roid, true); + child.children = GetRoChildrenByRoid(child.roid, false); + } + } + + public void LoadChildren(ref ROFSTLookup.rodbi db) + { + // If Children is null then it hasn't been loaded yet + //if (child.children == null || child.children.Length <= 0) + if (db.children == null) + //db.children = GetRoChildrenByID(db.ID, db.dbiID, true); + db.children = GetRoChildrenByID(db.ID, db.dbiID, false); + } + + public static ROFSTLookup.rochild GetEmptyRoChild() + { + return new ROFSTLookup.rochild() { ID = -1, type = 0 }; } #endregion @@ -732,7 +710,7 @@ namespace VEPROMS.CSLA.Library } } - private DateTime GetRofstDtsByID(int rofstID) + private static DateTime GetRofstDtsByID(int rofstID) { try { @@ -793,7 +771,7 @@ namespace VEPROMS.CSLA.Library } catch (Exception ex) { - throw new DbCslaException("RofstData.vesp_RofstHeaderInsert", ex); + throw new DbCslaException("ROFSTLookup.RofstHeaderInsert.vesp_RofstHeaderInsert", ex); } } @@ -990,72 +968,6 @@ namespace VEPROMS.CSLA.Library } } - private ROFSTLookup.rochild RofstDataGetChildByRoid(int rofstID, string roid, bool loadChildren = false, bool loadAllChildren = false) - { - try - { - using (SqlConnection cn = Database.VEPROMS_SqlConnection) - { - using (SqlCommand cmd = cn.CreateCommand()) - { - cmd.CommandTimeout = Database.DefaultTimeout; - cmd.CommandType = CommandType.StoredProcedure; - cmd.CommandText = "vesp_RofstDataGetChildByRoid"; - - cmd.Parameters.Add(new SqlParameter("@RofstID", SqlDbType.Int)).Value = rofstID; - cmd.Parameters.Add(new SqlParameter("@Roid", SqlDbType.VarChar)).Value = roid; - - using (SafeDataReader dr = new SafeDataReader(cmd.ExecuteReader())) - { - if (dr.Read()) - { - return ConvertToRochildObject(dr, loadChildren, loadAllChildren); - } - } - } - } - - return new ROFSTLookup.rochild() { ID = -1 }; - } - catch (Exception ex) - { - throw new DbCslaException("RofstData.vesp_RofstDataGetChildByRoid", ex); - } - } - - private ROFSTLookup.rochild RofstDataGetChildByAccPageID(int rofstID, string accPageID, bool loadChildren = false, bool loadAllChildren = false) - { - try - { - using (SqlConnection cn = Database.VEPROMS_SqlConnection) - { - using (SqlCommand cmd = cn.CreateCommand()) - { - cmd.CommandTimeout = Database.DefaultTimeout; - cmd.CommandType = CommandType.StoredProcedure; - cmd.CommandText = "vesp_RofstDataGetChildByAccPageID"; - - cmd.Parameters.Add(new SqlParameter("@RofstID", SqlDbType.Int)).Value = rofstID; - cmd.Parameters.Add(new SqlParameter("@AccPageID", SqlDbType.VarChar)).Value = accPageID; - - using (SafeDataReader dr = new SafeDataReader(cmd.ExecuteReader())) - { - if (dr.Read()) - { - return ConvertToRochildObject(dr, loadChildren, loadAllChildren); - } - } - } - } - - return new ROFSTLookup.rochild() { ID = -1 }; - } - catch (Exception ex) - { - throw new DbCslaException("RofstData.vesp_RofstDataGetChildByAccPageID", ex); - } - } - private ROFSTLookup.rochild[] RofstDataGetChildrenByRoid(int rofstID, string roid, bool loadChildren = false, bool loadAllChildren = false) { try @@ -1176,7 +1088,7 @@ namespace VEPROMS.CSLA.Library } } - private Dictionary RofstDataSearch(int rofstID, string value, int searchTypeID, int? maxNumRecords) + private Dictionary RofstDataSearch(int rofstID, string value, int searchTypeID, bool onlyRoid16, int? maxNumRecords) { Dictionary dic = new Dictionary(); @@ -1196,6 +1108,7 @@ namespace VEPROMS.CSLA.Library cmd.Parameters.Add(new SqlParameter("@RofstID", SqlDbType.Int)).Value = rofstID; cmd.Parameters.Add(new SqlParameter("@Value", SqlDbType.VarChar)).Value = value; cmd.Parameters.Add(new SqlParameter("@SearchTypeID", SqlDbType.Int)).Value = searchTypeID; + cmd.Parameters.Add(new SqlParameter("@OnlyRoid16", SqlDbType.Bit)).Value = (onlyRoid16) ? 1 : 0; if (maxNumRecords != null) cmd.Parameters.Add(new SqlParameter("@MaxNumOfRecords", SqlDbType.Int)).Value = (int)maxNumRecords; @@ -1218,40 +1131,6 @@ namespace VEPROMS.CSLA.Library } } - private ROFSTLookup.rochild RofstDataGetChildByID(int rofstID, int dbiID, int id, bool loadChildren = false, bool loadAllChildren = false) - { - try - { - using (SqlConnection cn = Database.VEPROMS_SqlConnection) - { - using (SqlCommand cmd = cn.CreateCommand()) - { - cmd.CommandTimeout = Database.DefaultTimeout; - cmd.CommandType = CommandType.StoredProcedure; - cmd.CommandText = "vesp_RofstDataGetChildByID"; - - cmd.Parameters.Add(new SqlParameter("@RofstID", SqlDbType.Int)).Value = rofstID; - cmd.Parameters.Add(new SqlParameter("@DbiID", SqlDbType.Int)).Value = dbiID; - cmd.Parameters.Add(new SqlParameter("@ID", SqlDbType.Int)).Value = id; - - using (SafeDataReader dr = new SafeDataReader(cmd.ExecuteReader())) - { - if (dr.Read()) - { - return ConvertToRochildObject(dr, loadChildren, loadAllChildren); - } - } - } - } - - return new ROFSTLookup.rochild() { ID = -1 }; - } - catch (Exception ex) - { - throw new DbCslaException("RofstData.vesp_RofstDataGetChildByID", ex); - } - } - private ROFSTLookup.rochild[] RofstDataGetRoChildrenByType(int rofstID, E_ROValueType valueTypes, bool loadChildren = false, bool loadAllChildren = false) { try @@ -1287,6 +1166,128 @@ namespace VEPROMS.CSLA.Library } } + private List RofstDataGetExtensions() + { + try + { + List lst = new List(); + + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + using (SqlCommand cmd = cn.CreateCommand()) + { + cmd.CommandTimeout = Database.DefaultTimeout; + cmd.CommandType = CommandType.StoredProcedure; + cmd.CommandText = "vesp_RofstDataGetExtensions"; + + using (SafeDataReader dr = new SafeDataReader(cmd.ExecuteReader())) + { + while (dr.Read()) + { + lst.Add(ConvertToRoExtensionObject(dr)); + } + } + } + } + + return lst; + } + catch (Exception ex) + { + throw new DbCslaException("RofstData.vesp_RofstDataGetExtensions", ex); + } + } + + #endregion + + #region (Core/Base logic for RO Values & UnitInfo RO Values) + + private ROFSTLookup.rochild RofstDataGetChildByRoid(int rofstID, string roid, bool loadChildren = false, bool loadAllChildren = false) + { + try + { + // Cleanup Roid if necessary (Note* This method also handles the UnitInfo Ro Values. ex: "") + roid = FormatRoidKey(roid); + + // Check if roid is for a Unit Information RO Value Tag + if (!string.IsNullOrEmpty(roid) && roid.StartsWith("FFFF")) + { + return GetUnitInfoRoChild(roid); + } + + // Lookup RO Value in the database based on the roid + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + using (SqlCommand cmd = cn.CreateCommand()) + { + cmd.CommandTimeout = Database.DefaultTimeout; + cmd.CommandType = CommandType.StoredProcedure; + cmd.CommandText = "vesp_RofstDataGetChildByRoid"; + + cmd.Parameters.Add(new SqlParameter("@RofstID", SqlDbType.Int)).Value = rofstID; + cmd.Parameters.Add(new SqlParameter("@Roid", SqlDbType.VarChar)).Value = roid; + + using (SafeDataReader dr = new SafeDataReader(cmd.ExecuteReader())) + { + if (dr.Read()) + { + return ConvertToRochildObject(dr, loadChildren, loadAllChildren); + } + } + } + } + + return GetEmptyRoChild(); + } + catch (Exception ex) + { + throw new DbCslaException("RofstData.vesp_RofstDataGetChildByRoid", ex); + } + } + + private ROFSTLookup.rochild RofstDataGetChildByAccPageID(int rofstID, string accPageID, string spDefault, string igDefault, bool loadChildren = false, bool loadAllChildren = false) + { + try + { + // Cleanup / Reformat the AccPageID if necessary (Note* This method also handles the UnitInfo Ro Values. ex: "") + string accPageKey = FormatAccPageKey(accPageID, spDefault, igDefault); + + // Check if roid is for a Unit Information RO Value Tag + if (!string.IsNullOrEmpty(accPageKey) && accPageKey.StartsWith(" lstValues = GetROReturnValue(rawvalue); + + if (lstValues.Count > 0) // Single or Multiple Return Values + { + child.children = new ROFSTLookup.rochild[lstValues.Count]; + + for (int i = 0; i < lstValues.Count; i++) + { + var roExt = Extensions.Where(x => x.Offset.Equals(i + 1)).SingleOrDefault(); + + string roValue = GetParentChildROValue(lstValues[i], this.SelectedSlave); + + child.children[i].ParentID = child.ID; + child.children[i].type = child.type; // Multiple return value inherit type from parent + child.children[i].title = roValue; + child.children[i].value = roValue; + + child.children[i].appid = (roExt != null) ? string.Format("{0}.{1}", child.appid, roExt.AccPageExt) : child.appid; + child.children[i].roid = string.Format("{0}{1}{2}", tableID.ToString("X4"), child.ID.ToString("X8"), (roExt.RoidExt != null) ? roExt.RoidExt : string.Empty).ToUpper(); + child.children[i].children = new List().ToArray(); + } + + child.value = null; + } + + _lstRoValues.Clear(); + _multiRoValues.Clear(); + + return; + } + + private static string GetParentChildROValue(string roval, int selChldIdx) + { + // C2021-026 Get the child RO value if it exists, otherwise to the default (parent) RO value + // C2022-001 new logic to handle new format of Parent/Child RO.FST + // The RO.FST will not have a specific child value if that child value is the same as the default value + // B2021-093 Don't look for child RO values if "roval" is null + if (string.IsNullOrEmpty(roval)) + return null; + + // Clean Up RoValue + roval = roval.Replace("\xFF", "\xa0"); + roval = roval.Replace(@"\u160?", " "); + + // B2022-020 remove a un-needed question mark that was in the search criteria "(" + // B2022-050 change the search string from "(" to "" to handle when RO values have less then sign + // B2022-077 Need to use the RegexOption of Single Line to handle cases of an RO Return value having ascii newline characters (\r\n) + MatchCollection mm = Regex.Matches(roval, "", RegexOptions.Singleline); + + // C2022-014 commented write to error log. Keep for debugging purposes. + //if (mm.Count == 0) // B2022-020 will now write in error log if there is a problem + // _MyLog.WarnFormat("Parent/Child Values not parsable for \r\nItemId={0}\r\nROValue={1} ",MyDocVersionInfo.ItemID,roval); + + StringBuilder sb = new StringBuilder(); + int lastIndex = 0; + + // Get Selected Child Value + foreach (Match m in mm) + { + sb.Append(roval.Substring(lastIndex, m.Index - lastIndex)); + + string aplString = m.Value; + string chldValStr = string.Format("UnitIdx={0} Value=", selChldIdx); + int offsetIdx = aplString.IndexOf(chldValStr); + int nextIDX = -1; + + if (offsetIdx == -1) + { + offsetIdx = aplString.IndexOf("DefaultVal=") + 11; + } + else + { + offsetIdx += chldValStr.Length; + } + + nextIDX = aplString.IndexOf(",UnitIdx", offsetIdx); + if (nextIDX == -1) nextIDX = aplString.IndexOf(" /APL>"); + sb.Append(aplString.Substring(offsetIdx, nextIDX - offsetIdx)); + + lastIndex = m.Index + m.Length; + } + + // B2022-018 append any remaining text + if (lastIndex < roval.Length) + { + sb.Append(roval.Substring(lastIndex)); + } + + // If Default Value is selected (selChldIdx = 0), and return value is empty then replace with Standard Missing Default Value + return (selChldIdx == 0 && sb.ToString().Trim().Length <= 0) ? ROFSTLookup.RoMissingDefaultValue : sb.ToString().Trim(); + //return sb.ToString(); + } + private List GetROReturnValue(string roval) { _lstRoValues = new List(); @@ -1550,7 +1658,7 @@ namespace VEPROMS.CSLA.Library _dicRoVars = new Dictionary(); string tmp = ProcessRO(_myDocVersionInfo == null ? roval : _myDocVersionInfo.ProcessDocVersionSpecificInfo(roval), false); - + if (!string.IsNullOrEmpty(tmp) && _lstRoValues.Count == 0) // was not a multiple return value { _lstRoValues.Add(tmp); @@ -1559,39 +1667,6 @@ namespace VEPROMS.CSLA.Library return _lstRoValues; } - private void ProcessROReturnValue(ref ROFSTLookup.rochild child, string rawvalue, int tableID) - { - // This function will take the raw RO return value and resolve any macros, conditionals, - // and generate the return value or a list of multiple return values. - List lstValues = GetROReturnValue(rawvalue); - - if (lstValues.Count > 1) // Multiple Return Values - { - child.children = new ROFSTLookup.rochild[lstValues.Count]; - - for (int i = 0; i < lstValues.Count; i++) - { - string tsts = Convert.ToInt32(_multiRoValues[i][0]).ToString("X4"); - child.children[i].value = lstValues[i].Replace("\xFF", "\xa0"); - child.children[i].roid = tableID.ToString("X4") + child.ID.ToString("X8") + tsts; - child.children[i].type = child.type; // Multiple return value inherit type from parent - child.children[i].title = lstValues[i].Replace("\xFF", "\xa0"); - child.children[i].appid = child.appid; - } - - child.value = null; - } - else - { - child.value = lstValues[0]; - } - - _lstRoValues.Clear(); - _multiRoValues.Clear(); - - return; - } - private string ProcessRO(string roval, bool multiRtnVal) { string str = roval; @@ -1670,6 +1745,7 @@ namespace VEPROMS.CSLA.Library { // 'l' is the length up to the matching brace of the variable definition string tmpval = ProcessRO(str.Substring(nxt + 1, l - nxt - 1), multiRtnVal); + if (string.IsNullOrEmpty(tmpval)) tmpval = " "; // nothing assigned to variable if (!_dicRoVars.ContainsKey(str.Substring(0, nxt))) @@ -1813,65 +1889,53 @@ namespace VEPROMS.CSLA.Library return (level != 0) ? -1 : idx; //return -1 if didn't find matching brace otherwise length including end brace } - private string FormatKey(string keyStr) - { - if (!string.IsNullOrEmpty(keyStr)) - { - keyStr = keyStr.ToUpper(); - keyStr = regRoKeyHigh.Replace(keyStr, "_HIGH$3"); - keyStr = regRoKeyLow.Replace(keyStr, "_LOW$3"); - } - - return keyStr; - } - private string ReplaceUnicode(string s2, bool DoCaret) { string orig = s2; - s2 = s2.Replace(@"\u160?", ""); // convert hard spaces bug fix: B2016-206 + s2 = s2.Replace(@"\u160?", ""); // convert hard spaces bug fix: B2016-206 s2 = s2.Replace(@"\", @"\u9586?"); // convert backslashes to a backslash symbol - s2 = s2.Replace("", @"\u160?"); // convert hard spaces bug fix: B2016-206 + s2 = s2.Replace("", @"\u160?"); // convert hard spaces bug fix: B2016-206 s2 = s2.Replace("`", @"\'b0"); // convert backquote to degree - left over from DOS days. - s2 = s2.Replace("\xf8", @"\'b0"); // convert \xf8 to degree. + s2 = s2.Replace("\xf8", @"\'b0"); // convert \xf8 to degree. s2 = s2.Replace("\xa0", @"\u160?"); // hardspace s2 = s2.Replace("\xb0", @"\'b0"); // degree s2 = s2.Replace("\x7f", @"\u916?"); // delta - s2 = s2.Replace("\x2265", @"\u8805?"); // greater than or equal - s2 = s2.Replace("\x2264", @"\u8804?"); // less than or equal + s2 = s2.Replace("\x2265", @"\u8805?"); // greater than or equal + s2 = s2.Replace("\x2264", @"\u8804?"); // less than or equal s2 = s2.Replace("\xB1", @"\'b1"); // plus minus s2 = s2.Replace("\x3A3", @"\u931?"); // sigma s2 = s2.Replace("\x3C4", @"\u947?"); // gamma s2 = s2.Replace("\xBD", @"\'bd"); // half s2 = s2.Replace("\x25A0", @"\u9604?"); // accum 2584 s2 = s2.Replace("\x7", @"\u9679?"); // bullet 25CF - s2 = s2.Replace("\x2248", @"\u8776?"); // approx eq - s2 = s2.Replace("\x2261", @"\u8773?"); // similar eq 2245 + s2 = s2.Replace("\x2248", @"\u8776?"); // approx eq + s2 = s2.Replace("\x2261", @"\u8773?"); // similar eq 2245 s2 = s2.Replace("\xF7", @"\'f7"); // division s2 = s2.Replace("\x221A", @"\u8730?"); // square root s2 = s2.Replace("\x393", @"\u961?"); // rho 3C1 s2 = s2.Replace("\x3C0", @"\u960?"); // pi s2 = s2.Replace("\xb5", @"\u956?"); // micro 3BC (try e6, if not work try 109) - s2 = s2.Replace("\x3B4", @"\u948?"); // lower case delta - s2 = s2.Replace("\x3C3", @"\u963?"); // lower case sigma + s2 = s2.Replace("\x3B4", @"\u948?"); // lower case delta + s2 = s2.Replace("\x3C3", @"\u963?"); // lower case sigma s2 = s2.Replace("\xBC", @"\'bc"); // quarter s2 = s2.Replace("\x3C6", @"\'d8"); // dist zero, D8 s2 = s2.Replace("\xC9", @"\u274?"); // energy, 112 s2 = s2.Replace("\xEC", @"\'ec"); // grave - s2 = s2.Replace("\x2502", @"\u9474?"); // bar - s2 = s2.Replace("\x3B5", @"\u949?"); // epsilon - s2 = s2.Replace("\x398", @"\u952?"); // theta, 3B8 - s2 = s2.Replace("\x221E", @"\u8857?"); // dot in oval, 2299 + s2 = s2.Replace("\x2502", @"\u9474?"); // bar + s2 = s2.Replace("\x3B5", @"\u949?"); // epsilon + s2 = s2.Replace("\x398", @"\u952?"); // theta, 3B8 + s2 = s2.Replace("\x221E", @"\u8857?"); // dot in oval, 2299 s2 = s2.Replace("\xBF", @"\u964?"); // tau, 3C4 - s2 = s2.Replace("\x2310", @"\u9830?"); // diamond, 2666 + s2 = s2.Replace("\x2310", @"\u9830?"); // diamond, 2666 s2 = s2.Replace("\x2192", @"\u8594?"); // Rightwards Arrow s2 = s2.Replace("\x2190", @"\u8592?"); // Leftwards Arrow - s2 = s2.Replace("\x2191", @"\u8593?"); // Upwards Arrow - s2 = s2.Replace("\x2193", @"\u8595?"); // Downwards Arrow + s2 = s2.Replace("\x2191", @"\u8593?"); // Upwards Arrow + s2 = s2.Replace("\x2193", @"\u8595?"); // Downwards Arrow s2 = s2.Replace("\x2207", @"\u8711?"); // Nabla - s2 = s2.Replace("\x2591", @"\'b0"); // Degree Symbol - s2 = s2.Replace("\xFF", @"\u8593?"); // Up Arrow - s2 = s2.Replace("\xD6", @"\u8595?"); // Down Arrow + s2 = s2.Replace("\x2591", @"\'b0"); // Degree Symbol + s2 = s2.Replace("\xFF", @"\u8593?"); // Up Arrow + s2 = s2.Replace("\xD6", @"\u8595?"); // Down Arrow if (DoCaret) s2 = s2.Replace("^", @"\u916?"); // Convert dash to a non-breaking dash. This is a unicode character. @@ -1883,25 +1947,108 @@ namespace VEPROMS.CSLA.Library return s2; } - private string FixUnitROs(string val) - { - DocVersionInfo dvi = _myDocVersionInfo; + #endregion - if (dvi != null && !string.IsNullOrEmpty(val) && val.StartsWith("") val = dvi.DocVersionConfig.Unit_Text; - else if (val.ToUpper() == "") val = dvi.DocVersionConfig.Unit_Number; - else if (val.ToUpper() == "") val = dvi.DocVersionConfig.Unit_Name; - else if (val.ToUpper() == "") val = dvi.DocVersionConfig.Unit_ID; - // B2021-145: For applicability, the tree view & pdf file name are not getting resolved when using any of the ‘OTHER’ tokens - // B2022-023 also check for other followed by a space - else if (val.ToUpper() == "" || val.ToUpper() == "") val = dvi.DocVersionConfig.Other_Unit_Text; - else if (val.ToUpper() == "" || val.ToUpper() == "") val = dvi.DocVersionConfig.Other_Unit_Number; - else if (val.ToUpper() == "" || val.ToUpper() == "") val = dvi.DocVersionConfig.Other_Unit_Name; - else if (val.ToUpper() == "" || val.ToUpper() == "") val = dvi.DocVersionConfig.Other_Unit_ID; + DocVersionConfig dvc = (_myDocVersionInfo != null) ? _myDocVersionInfo.DocVersionConfig : null; + + rc.roid = FormatRoidKey(roid).Substring(0, 12); + + switch (rc.roid) + { + case "FFFF00000001": + rc.title = "Number"; + rc.appid = "U-NUMBER"; + rc.value = (dvc != null) ? dvc.Unit_Number : null; + break; + + case "FFFF00000002": + rc.title = "Other Number"; + rc.appid = "U-OTHERNUMBER"; + rc.value = (dvc != null) ? dvc.Other_Unit_Number : null; + break; + + case "FFFF00000003": + rc.title = "Text"; + rc.appid = "U-TEXT"; + rc.value = (dvc != null) ? dvc.Unit_Text : null; + break; + + case "FFFF00000004": + rc.title = "Other Text"; + rc.appid = "U-OTHERTEXT"; + rc.value = (dvc != null) ? dvc.Other_Unit_Text : null; + break; + + case "FFFF00000005": + rc.title = "ID"; + rc.appid = "U-ID"; + rc.value = (dvc != null) ? dvc.Unit_ID : null; + break; + + case "FFFF00000006": + rc.title = "Other ID"; + rc.appid = "U-OTHERID"; + rc.value = (dvc != null) ? dvc.Other_Unit_ID : null; + break; + + case "FFFF00000007": + rc.title = "Name"; + rc.appid = "U-NAME"; + rc.value = (dvc != null) ? dvc.Unit_Name : null; + break; + + case "FFFF00000008": + rc.title = "Other Name"; + rc.appid = "U-OTHERNAME"; + rc.value = (dvc != null) ? dvc.Other_Unit_Name : null; + break; + } + + if (!string.IsNullOrEmpty(rc.appid)) + { + rc.ID = 0; + rc.ParentID = 0; + rc.type = 1; // Single Text + rc.roid = string.Format("{0}0041", rc.roid); + rc.children = new List().ToArray(); + } } - return val; + return rc; + } + + private string GetUnitInfoRoidByAccPageID(string accPageID) + { + string roid = string.Empty; + + if (!string.IsNullOrEmpty(accPageID)) + { + string accPageKey = accPageID; + + // Try to cleanup / standardize the Unit Info Tag before attempting to lookup the associated value + if (!accPageKey.StartsWith("<")) accPageKey = string.Format("<{0}", accPageKey); + if (!accPageKey.EndsWith(">")) accPageKey = string.Format("{0}>", accPageKey); + accPageKey = FormatAccPageKey(accPageKey, null, null); + + if (accPageKey == "") roid = "FFFF00000001"; + if (accPageKey == "") roid = "FFFF00000002"; + if (accPageKey == "") roid = "FFFF00000003"; + if (accPageKey == "") roid = "FFFF00000004"; + if (accPageKey == "") roid = "FFFF00000005"; + if (accPageKey == "") roid = "FFFF00000006"; + if (accPageKey == "") roid = "FFFF00000007"; + if (accPageKey == "") roid = "FFFF00000008"; + } + + return roid; } #endregion diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/DocVersionExt.cs b/PROMS/VEPROMS.CSLA.Library/Extension/DocVersionExt.cs index 8730a8cd..84343893 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/DocVersionExt.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/DocVersionExt.cs @@ -317,6 +317,7 @@ namespace VEPROMS.CSLA.Library AssociationConfig ac = new AssociationConfig(associationInfo); return ac.ROUpdate_LoadingFigures; } + #region SearchPaths public string _SearchDVPath; public string SearchDVPath @@ -330,6 +331,7 @@ namespace VEPROMS.CSLA.Library } public string SearchPath { get { return ""; } } #endregion + #region UnlinkEnhancedDocVersion // Unlink (clear) enhanced from source for this docversion. Refresh all related cache items. public void DoUnlinkEnhancedDocVersion() @@ -371,6 +373,7 @@ namespace VEPROMS.CSLA.Library } } #endregion UnlinkEnhanced + #region DocVersion Config [NonSerialized] private DocVersionConfig _DocVersionConfig; @@ -381,7 +384,9 @@ namespace VEPROMS.CSLA.Library _DocVersionConfig = null; } #endregion + #region MOVE TO DOCVERSION CONFIG + private string GetProfile(string grp, string nam) { return GetProfile(grp, nam, false); @@ -409,20 +414,25 @@ namespace VEPROMS.CSLA.Library public string UnitSpecific(string str, int len, ItemInfo ii) { ProcedureInfo pi = ii as ProcedureInfo; + if (pi == null) // B2022-004: Don't crash if Proc PC/PC (ii is from a list, so wasn't an ItemInfo) { pi = ProcedureInfo.Get(ii.ItemID); } + if (pi == null) return ""; + string unitdes = "ID"; string prefix = null; string fromunitdes = null; str = ItemInfo.ConvertToDisplayText(pi.MyContent.Number); bool hastoken = false; + // Determine if there is a token in the procedure number data, default is ID if (str.ToUpper().Contains(@" -1) { try @@ -438,6 +448,7 @@ namespace VEPROMS.CSLA.Library } } } + if (unitdes == "NUMBER") fromunitdes = DocVersionConfig.Unit_Number; else if (unitdes == "ID") @@ -468,8 +479,7 @@ namespace VEPROMS.CSLA.Library string[] units = mstr.Split(",".ToCharArray()); string[] fromdata = fromunitdes.Split(",".ToCharArray()); - // SelectedSlave is > 0 if a unit has been selected, for example from print or approve. It represents that index into - // the list of units. + // SelectedSlave is > 0 if a unit has been selected, for example from print or approve. It represents that index into the list of units. if (DocVersionConfig.SelectedSlave > 0) { prefix = units[0].Replace("#", ""); @@ -482,12 +492,13 @@ namespace VEPROMS.CSLA.Library // 1) [] (square brackets) are placed around any prefixes determined from the token or the Procedure Number data on // the working draft properties. If None, i.e. no units, are applicable, as selected from the Step Properties/Applicability tab. // there will be no text between the brackets to represent no applicability - // 2) , (commas) are used as a delimeter. Only have 1 comma separating the prefix, there may be no text if some units are + // 2) , (commas) are used as a delimiter. Only have 1 comma separating the prefix, there may be no text if some units are // not applicable, but code exists here so that ',,,' does not appear in the treenode // 3) don't duplicate resolved text, for example if NUMBER is used, and prefix text would be '[A,A,B,C,C]', only show '[A,B,C]' bool sometext = false; // flag to use since don't want ',,,,,' before number List prefs = new List(); + for (int i = 1; i <= UnitNames.Length; i++) { bool procAppl = pi.ApplInclude(i); @@ -502,10 +513,13 @@ namespace VEPROMS.CSLA.Library } if (procAppl && tokRepAndPrefix != "") prefix = prefix + (prefix == null ? tokRepAndPrefix : (prefix != null && prefix.Length > 0 && prefix[prefix.Length - 1] != ',' ? "," : "") + tokRepAndPrefix); } + str = Regex.Replace(str, @"\<[uU]-[a-zA-Z]+\>", ""); str = Regex.Replace(str, @"\<[uU]\>", ""); + return (!sometext) ? str: "[" + prefix + "]" + str; } + public string UnitSpecific(string str, int len) { @@ -536,11 +550,6 @@ namespace VEPROMS.CSLA.Library retvalu = str; else if (pnum[0] == '!') { - // look for mstr in SET.INI - // GetPrivateProfileString("replace", mstr, mstr, tonum, 24, "set.ini"); - - // TODO: NOT SURE IF SET.INI AND PROC.INI HAVE UNIQUE GROUP NAMES!!!!!!! - //mstr = GetProfile("Replace", mstr); mstr = GetProfile("Replace", mstr, true); // true allow it to return a null if not found if (mstr == null) retvalu = str; // no replacement, use procedure number as is } @@ -580,20 +589,19 @@ namespace VEPROMS.CSLA.Library public string Evaluate(string str, int len) { string retval = null; - string swhir = "PSU"; /* order inwhich to check */ + string swhir = "PSU"; /* order in which to check */ string pn; + if (str.Length > 1 && str[1] == '-') { int swptr = swhir.IndexOf((str.ToUpper())[0]); - //char swchar = ''; - //if (swptr != -1) - // swchar = swhir[swptr]; string sav = str.Substring(len); str = str.Substring(0, len); string substr = str.Substring(2); substr = substr.Replace(" ", ""); - while (swptr >= 0 && swptr < swhir.Length && retval == null) //retval.Equals(string.Empty)) + + while (swptr >= 0 && swptr < swhir.Length && retval == null) { switch (swhir[swptr]) { @@ -607,10 +615,6 @@ namespace VEPROMS.CSLA.Library retval = this.DocVersionConfig.Unit_Number; if (substr.ToLower() == "text") retval = this.DocVersionConfig.Unit_Text; - //retval = this.DocVersionConfig.Other_Unit_ID; - //retval = this.DocVersionConfig.Other_Unit_Name; - //retval = this.DocVersionConfig.Other_Unit_Number; - //retval = this.DocVersionConfig.Other_Unit_Text; break; case 'S': //retval = GetProfile("Procedure_Set", substr, true); @@ -639,60 +643,54 @@ namespace VEPROMS.CSLA.Library { retval = this.DocVersionConfig.Unit_ID; } - // if the return value is empty, then the resulting - // evaluation should repeat the token string including - // the braces. - the beginning brace is not passed in. - //if (retval.Equals(string.Empty)) - //{ - // retval = (char*)mallocq(len + 3); - // strncpy(retval, str - 1, len + 2); - //} + if (retval == null) retval = string.Format("<{0}>", str.Substring(0, len)); return retval; } - public string ProcessDocVersionSpecificInfo(string rawvalue) { string str = rawvalue; - string rtnstr = ""; + string rtnstr = string.Empty; int l = rawvalue.Length; + while (l > 0) { - int ptr = str.IndexOf('<'); //nextDelimiter("<", str, l); - int cptr = (ptr == -1) ? -1 : str.IndexOf('>'); //nextDelimiter(">", ptr, strlen(ptr)); + int ptr = str.IndexOf('<'); + int cptr = (ptr == -1) ? -1 : str.IndexOf('>'); + // jsj 2/5/10 added "|| (ptr > cptr)" to fix bug where rawvalue = "Insert token for ->Step<- to transition back to." if (ptr == -1 || (ptr > -1 && ((cptr == -1) || (ptr > cptr)))) { - //add(new seText(str, l)); - //str += l; rtnstr += str; l = 0; // jump out of while loop } else { int cnt = ptr; + if (cnt > 0) { - //add(new seText(str, cnt)); rtnstr += str.Substring(0, cnt); l -= cnt; str = str.Substring(ptr); } - ptr = str.IndexOf('>') + 1; //nextDelimiter(">", str, l) + 1; - cnt = ptr; //(int)(ptr - str); - //add(new seUser(str + 1, cnt - 2)); + + ptr = str.IndexOf('>') + 1; + cnt = ptr; + rtnstr += Evaluate(str.Substring(1, cnt - 2), cnt - 2); l -= cnt; - str = str.Substring(ptr); //ptr; + + str = str.Substring(ptr); } } + return rtnstr; } - #endregion ItemInfoList _Procedures = null; diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/DocumentExt.cs b/PROMS/VEPROMS.CSLA.Library/Extension/DocumentExt.cs index 6ce347a0..13e3bb19 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/DocumentExt.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/DocumentExt.cs @@ -14,7 +14,8 @@ using System.Drawing.Imaging; using Volian.Base.Library; using System.Diagnostics; using System.Runtime.InteropServices; - +using System.Runtime; +using System.Linq; namespace VEPROMS.CSLA.Library { @@ -31,7 +32,7 @@ namespace VEPROMS.CSLA.Library { get { - if (_LibTitle == "") return string.Format("Document {0}", _DocID); + if (_LibTitle == string.Empty) return string.Format("Document {0}", _DocID); return _LibTitle; } } @@ -64,21 +65,23 @@ namespace VEPROMS.CSLA.Library } foreach (string roidkey in roids) { - string [] parts = roidkey.Split(":".ToCharArray()); + string[] parts = roidkey.Split(":".ToCharArray()); DocumentDROUsages.Add(parts[1], RODb.GetJustRoDb(int.Parse(parts[0]))); } } + private int _Unique = 0; private string Unique { get { - string retval = ""; + string retval = string.Empty; if (_Unique != 0) retval = "_" + _Unique.ToString(); _Unique++; return retval; } } + public void StatusChanged(VolianStatusType type, int count, string text) { //if (Parent != null && Parent.Parent != null && Parent.Parent.Parent is DisplayTabControl) @@ -87,6 +90,7 @@ namespace VEPROMS.CSLA.Library // tc.ONStatusChanged(this, new DisplayTabControlStatusEventArgs(type, count, text)); //} } + public void RestoreWordDoc(ItemInfo myItemInfo) { DocumentAuditInfo savDocAuditInfo = null; @@ -144,12 +148,12 @@ namespace VEPROMS.CSLA.Library SectionConfig sc = myItemInfo.ActiveSection.MyConfig as SectionConfig; if (sc != null && sc.Section_WordMargin == "Y") { - using (Pdf myPdf = Pdf.MakePdf(this, MSWordToPDF.DebugStatus, 0, 0, 0, 0, (double)myItemInfo.MSWordPageCount, buf)) { ;} + using (Pdf myPdf = Pdf.MakePdf(this, MSWordToPDF.DebugStatus, 0, 0, 0, 0, (double)myItemInfo.MSWordPageCount, buf)) {; } } else { using (Pdf myPdf = Pdf.MakePdf(this, MSWordToPDF.DebugStatus, (int)myDocStyle.Layout.TopMargin, (int)myDocStyle.Layout.PageLength, - (int)myDocStyle.Layout.LeftMargin, (int)myDocStyle.Layout.PageWidth, (double)myItemInfo.MSWordPageCount, buf)) { ;} + (int)myDocStyle.Layout.LeftMargin, (int)myDocStyle.Layout.PageWidth, (double)myItemInfo.MSWordPageCount, buf)) {; } } UpdateDRoUsages(roids); Save(); @@ -187,7 +191,7 @@ namespace VEPROMS.CSLA.Library { get { - if (_LibTitle == "") return string.Format("Document {0}", _DocID); + if (_LibTitle == string.Empty) return string.Format("Document {0}", _DocID); return _LibTitle; } } @@ -439,7 +443,7 @@ namespace VEPROMS.CSLA.Library { if (_MyDocument == null) return; if (_MyFile == null) return; - // B2017-249 Recover Temporary File And AutoSave support for MSWord + // B2017-249 Recover Temporary File And AutoSave support for MSWord _MyFile.Refresh(); if (_MyFile.Exists && (TimeSpan.FromTicks(_MyDocument.DTS.Ticks - _MyFile.LastWriteTimeUtc.Ticks).TotalSeconds > 1.0)) { @@ -464,7 +468,7 @@ namespace VEPROMS.CSLA.Library { get { - string retval = ""; + string retval = string.Empty; if (_Unique != 0) retval = "_" + _Unique.ToString(); _Unique++; return retval; @@ -491,12 +495,13 @@ namespace VEPROMS.CSLA.Library set { _StartDTS = value; } } //B2017-260 Prefix the Temporary document file with server name and database name - private static string _TempFilePrefix = ""; + private static string _TempFilePrefix = string.Empty; public static string TempFilePrefix { get { return DSOFile._TempFilePrefix; } set { DSOFile._TempFilePrefix = value; } } + private void CreateTemporaryFile() { _Unique = 0; @@ -505,7 +510,7 @@ namespace VEPROMS.CSLA.Library if (_MyDocument != null) { //B2017-260 Prefix the Temporary document file with server name and database name - _MyFile = new FileInfo(string.Format(@"{0}\{1}_tmp_{2}{3}{4}", VlnSettings.TemporaryFolder,TempFilePrefix, MyDocument.DocID, Unique, MyDocument.FileExtension)); + _MyFile = new FileInfo(string.Format(@"{0}\{1}_tmp_{2}{3}{4}", VlnSettings.TemporaryFolder, TempFilePrefix, MyDocument.DocID, Unique, MyDocument.FileExtension)); FileInfo matchingFile = null; while (_MyFile.Exists) { @@ -563,6 +568,7 @@ namespace VEPROMS.CSLA.Library Console.WriteLine(ex.Message); } } + public string FullName { get { return _MyFile.FullName; } @@ -572,18 +578,21 @@ namespace VEPROMS.CSLA.Library _MyFile = new FileInfo(value); } } + public void SaveFile(float length, string ascii, ItemInfo myItemInfo, bool cvtLibDoc, VolianStatusChange statusChange) { // TODO: Add Try & Catch logic if (_MyDocument == null) return; + Document doc = _MyDocument.Get(); MyFile.Refresh(); // B2017-255 Get the latest file length before reading and saving + FileStream fs = _MyFile.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite); // B2017-262 Verify that the file length is correct. long savLen2 = fs.Length; long savLen = _MyFile.Length; - if(savLen2!=savLen)_MyLog.WarnFormat("FileInfoLength = {0}, FileStreamLength= {1}", savLen, savLen2); - Byte[] buf = new byte[Math.Max(savLen,savLen2)]; + if (savLen2 != savLen) _MyLog.WarnFormat("FileInfoLength = {0}, FileStreamLength= {1}", savLen, savLen2); + Byte[] buf = new byte[Math.Max(savLen, savLen2)]; fs.Read(buf, 0, buf.Length); fs.Close(); @@ -593,7 +602,7 @@ namespace VEPROMS.CSLA.Library // if just one usage (this one), then just convert this to a non-library document. If there is more // than one usage, make a copy so that the rest of the usages still point to the library document. if (doc.DocumentEntryCount == 1) - doc.LibTitle = null; + doc.LibTitle = null; else { // make new document with 'no' libtitle. Then link this to the item/content via the entry. @@ -608,10 +617,12 @@ namespace VEPROMS.CSLA.Library } } } + doc.FileExtension = MyFile.Extension; doc.DocContent = buf; doc.DocAscii = ascii; //doc.UpdateDocAscii(_MyFile.FullName); + DocumentConfig cfg = new DocumentConfig(doc); cfg.Edit_Initialized = true; doc.Config = cfg.ToString(); @@ -620,10 +631,13 @@ namespace VEPROMS.CSLA.Library doc.DTS = _MyFile.LastWriteTimeUtc; //doc.DTS = DateTime.Now.ToUniversalTime(); doc = doc.Save(); + if (myItemInfo != null) // B2016-131 if myItemInfo is null, the lib doc is not referenced from any procedure. Just save changes, but don't generate a PDF { List roids = new List(); + string pdfTmp = MSWordToPDF.ToPDFReplaceROs(_MyDocument, roids, myItemInfo, statusChange); + FileInfo pdfFile = new FileInfo(pdfTmp); fs = pdfFile.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite); buf = new byte[pdfFile.Length]; @@ -631,28 +645,31 @@ namespace VEPROMS.CSLA.Library fs.Close(); pdfFile.Delete(); Pdf.DeleteAll(doc.DocID); // clear the PDF table for DocID first + DocStyle myDocStyle = myItemInfo.ActiveSection.MyDocStyle; SectionConfig sc = myItemInfo.ActiveSection.MyConfig as SectionConfig; + if (sc != null && sc.Section_WordMargin == "Y") { - using (Pdf myPdf = Pdf.MakePdf(doc, MSWordToPDF.DebugStatus, 0, 0, 0, 0, (double)myItemInfo.MSWordPageCount, buf)) { ;} + using (Pdf myPdf = Pdf.MakePdf(doc, MSWordToPDF.DebugStatus, 0, 0, 0, 0, (double)myItemInfo.MSWordPageCount, buf)) {; } } else { using (Pdf myPdf = Pdf.MakePdf(doc, MSWordToPDF.DebugStatus, (int)myDocStyle.Layout.TopMargin, (int)myDocStyle.Layout.PageLength, - (int)myDocStyle.Layout.LeftMargin, (int)myDocStyle.Layout.PageWidth, (double)myItemInfo.MSWordPageCount, buf)) { ;} + (int)myDocStyle.Layout.LeftMargin, (int)myDocStyle.Layout.PageWidth, (double)myItemInfo.MSWordPageCount, buf)) {; } } + doc.UpdateDRoUsages(roids); doc.Save(); + if (savLen != _MyFile.Length) _MyLog.ErrorFormat("DSO FRAMER: File size changed during Save for Word Document, beginSize = {0}, endSize = {1}", savLen, _MyFile.Length); } } + #endregion - #region Constructors - public DSOFile(DocumentInfo myDocument) - { - MyDocument = myDocument; - } + + #region Properties + // B2017-249 Recover Temporary File And AutoSave support for MSWord private bool _Temporary = false; public bool Temporary @@ -660,17 +677,31 @@ namespace VEPROMS.CSLA.Library get { return _Temporary; } set { _Temporary = value; } } + + #endregion + + #region Constructors + + public DSOFile(DocumentInfo myDocument) + { + MyDocument = myDocument; + } + public DSOFile(DocumentInfo myDocument, bool temporary) { Temporary = temporary; MyDocument = myDocument; } + #endregion + #region Destructor + ~DSOFile() { Dispose(false); } + public void Dispose() { Dispose(false); @@ -686,63 +717,141 @@ namespace VEPROMS.CSLA.Library //TryDelete(); } } + #endregion } + public static class MSWordToPDF { + #region Log4Net + + private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); + + #endregion + + #region Enums + + public enum DeviceCap + { + VERTRES = 10, + DESKTOPVERTRES = 117 + } + + #endregion + + #region Fields + + // B2019-123 Verify that the RO token is the correct format + private static Regex _ROAccPageTokenPattern = new Regex("[<][^<>-]+-[^<>]+[>]"); + // used to save Word sections with resolved ROs (for export generated from Approve) + private static LBApplicationClass _MyApp = null; + private static SectionInfo _MySection; private static Dictionary _DocReplace; + private static bool _CloseWordWhenDone = true; + private static System.Drawing.Color _OverrideColor = System.Drawing.Color.Transparent; + private static System.Windows.Forms.Form _FormForPlotGraphics = null; + private static int _DebugStatus = 0; + + // B2018-071 Save list of DocIDs for invalid document so that error log messages are not repeated + private static List _MissingDocs = new List(); + private static bool _Automatic = false; + + // [JAKE CODE]: Added an internal rochild dictionary cache specifically for printing + // + // As you loop through all of the specific RO AccPageKeys for the current MsWord Document Section, the code will first + // check the internal rochild cache for the base (12) digit roid Key/Value, if it doesn't already exist, then load the + // RoChild from the database, add it to the rochild print cache, and then based on the length of the roid, either (12) or (16), + // return either the base RoChild Object with its collection of children return values or the specific return value RoChild object. + // + // Notes** + // 1) Every base RoChild object must have one to many specific return values. + // 2) The first RoChild return value in the "children" collection will always have a roid Ext of "0041" or and a accPage Ext of "A" + // 3) The first RoChild return value in the "children" collection "0041/A" will also be used as the Default RoChild return value if a + // specific RoChild return value (by (4) digit Extension) doesn't exist in the base RoChild Objects "children" collection of return values. + // Ex: The specific RoChild return value for the roidExt "0044" doesn't exist now for some reason, then always return + // the first RoChild return value "0041" as the Default RO return value for that RO Object + // 4) Any (16) digit roids with an invalid/padded roid Ext (last (4) digits of roid = "0000") are automatically converted to use the "0041" + // roid Ext so the RO's with the older roidExt formats will be backwards compatible with the new logic/code and they will now be more consistent like + // the newer roidExt formats. The actual data in the database records with the roids that have the older "0000" extension (ROUsages & DROUsages Tables) + // are not physically modified or updated in the source tables. The RofstLookup method "FormatRoidKey" is always called first in the code before attempting + // to do any lookups or comparisons with any other roids. By standardizing the roid / accPageID formats and values first before running any other rules/logic, + // dramatically simplifies the down stream code for how to process/convert the Ro values + // 5) If a specific RoChild return value does not exist (maybe it was removed in the ROEditor / latest RO.FST file), then just return + // the first RoChild return value in the "children" collection (0041) instead + + private static Dictionary _roPrintCache = new Dictionary(); + + #endregion + + #region Properties + public static Dictionary DocReplace { get { return MSWordToPDF._DocReplace; } set { MSWordToPDF._DocReplace = value; } } - private static bool _CloseWordWhenDone = true; + public static bool CloseWordWhenDone { get { return MSWordToPDF._CloseWordWhenDone; } set { MSWordToPDF._CloseWordWhenDone = value; } } - private static LBApplicationClass _MyApp = null; + public static LBApplicationClass MyApp { get { - if (_MyApp == null) - _MyApp = new LBApplicationClass(); + if (_MyApp == null) _MyApp = new LBApplicationClass(); return _MyApp; } } - private static int _DebugStatus = 0; + public static int DebugStatus { get { return MSWordToPDF._DebugStatus; } set { MSWordToPDF._DebugStatus = value; } } - private static System.Drawing.Color _OverrideColor = System.Drawing.Color.Transparent; + public static System.Drawing.Color OverrideColor { get { return MSWordToPDF._OverrideColor; } set { MSWordToPDF._OverrideColor = value; } } - private static System.Windows.Forms.Form _FormForPlotGraphics=null; + public static System.Windows.Forms.Form FormForPlotGraphics { get { return MSWordToPDF._FormForPlotGraphics; } set { MSWordToPDF._FormForPlotGraphics = value; } } - private static SectionInfo _MySection; + + /// + /// C2018-035 Don't use a MessageBox if in automatic (Baseline) testing mode. + /// + public static bool Automatic + { + get { return MSWordToPDF._Automatic; } + set { MSWordToPDF._Automatic = value; } + } + + #endregion + + #region Public Methods + public static string GetDocPdf(SectionInfo sect, Color overrideColor) { _MySection = sect; + DocumentInfo mydoc = sect.MyContent.MyEntry.MyDocument; - UpdateDocPdf(mydoc, overrideColor,sect); + UpdateDocPdf(mydoc, overrideColor, sect); + string fileName = GetFileName(sect); FileInfo fi = new FileInfo(fileName); FileStream fs = fi.Create(); - PdfInfo myPdf = PdfInfo.Get(sect,false); + PdfInfo myPdf = PdfInfo.Get(sect, false); if (myPdf != null && myPdf.DocPdf != null) fs.Write(myPdf.DocPdf, 0, myPdf.DocPdf.Length); fs.Close(); + return fileName; } @@ -750,22 +859,24 @@ namespace VEPROMS.CSLA.Library { //B2019-144 Set the document text color to Red (overlay) or Black (normal) Color lastColor = MSWordToPDF.OverrideColor;// Remember last override color - if(MSWordToPDF.OverrideColor != overrideColor) MSWordToPDF.OverrideColor = overrideColor; + if (MSWordToPDF.OverrideColor != overrideColor) MSWordToPDF.OverrideColor = overrideColor; + PdfInfo myPdf = PdfInfo.Get(sect, DocReplace != null); + //B2019-144 Set the document text color to Red (overlay) or Black (normal) if (MSWordToPDF.OverrideColor != lastColor) MSWordToPDF.OverrideColor = lastColor; // Restore last override color - //MSWordToPDF.OverrideColor = Color.Black; // B2019-090 reset to black text (when a Complete RO Report was created after printing procedure, X/Y Plot was in red text) + //MSWordToPDF.OverrideColor = Color.Black; // B2019-090 reset to black text (when a Complete RO Report was created after printing procedure, X/Y Plot was in red text) return true; } - // B2018-071 Save list of DocIDs for invalid document so that error log messages are not repeated - private static List _MissingDocs = new List(); + public static bool SetDocPdf(DocumentInfo docInfo, ItemInfo sect) { string pdfTmp = null; List roids = new List(); + try { - pdfTmp = MSWordToPDF.ToPDFReplaceROs(docInfo,roids,sect,null); + pdfTmp = MSWordToPDF.ToPDFReplaceROs(docInfo, roids, sect, null); } catch (Exception ex) { @@ -776,50 +887,57 @@ namespace VEPROMS.CSLA.Library } return false; } + if (pdfTmp == null) return false; + FileInfo pdfFile = new FileInfo(pdfTmp); FileStream fs = pdfFile.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite); Byte[] buf = new byte[pdfFile.Length]; fs.Read(buf, 0, buf.Length); fs.Close(); - pdfFile.Delete(); + + try + { + pdfFile.Delete(); + } + catch { } + using (Document doc = docInfo.Get()) { DocStyle myDocStyle = sect.ActiveSection.MyDocStyle; SectionConfig sc = sect.ActiveSection.MyConfig as SectionConfig; int ss = sect.MyDocVersion.DocVersionConfig.SelectedSlave; + if (sc != null && sc.Section_WordMargin == "Y") { - using (Pdf myPdf = Pdf.MakePdf(doc, ss*10 + MSWordToPDF.DebugStatus, 0, 0, 0, 0, (double)sect.MSWordPageCount, buf)) { ;} + using (Pdf myPdf = Pdf.MakePdf(doc, ss * 10 + MSWordToPDF.DebugStatus, 0, 0, 0, 0, (double)sect.MSWordPageCount, buf)) {; } } else { using (Pdf myPdf1 = Pdf.MakePdf(doc, ss * 10 + MSWordToPDF.DebugStatus, (int)myDocStyle.Layout.TopMargin, (int)myDocStyle.Layout.PageLength, - (int)myDocStyle.Layout.LeftMargin, (int)myDocStyle.Layout.PageWidth, (double)sect.MSWordPageCount, buf)) { ;} + (int)myDocStyle.Layout.LeftMargin, (int)myDocStyle.Layout.PageWidth, (double)sect.MSWordPageCount, buf)) {; } } + doc.UpdateDRoUsages(roids); doc.Save(); } + docInfo.RefreshConfig(); + return true; } + public static string ToPDFReplaceROs(DocumentInfo doc, List roids, ItemInfo sect, VolianStatusChange statusChange) { - //ItemInfo sect = doc.DocumentEntries[0].MyContent.ContentItems[0]; if (Volian.Base.Library.BaselineMetaFile.IsOpen && Volian.Base.Library.BaselineMetaFile.IncludeWordSecText) Volian.Base.Library.BaselineMetaFile.WriteLine("WrdSec SecNum=\"{0}\" SecTitle=\"{1}\" Itemid={2}", sect.ActiveSection.DisplayNumber, sect.ActiveSection.DisplayText, sect.ItemID); // C2018-003 fixed use of getting the active section return ToPDFReplaceROs(sect, false, roids, statusChange); } - private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - public static string ToPDFReplaceROs(ItemInfo sect, bool openPdf, List roids, VolianStatusChange statusChange) //, System.Drawing.Color overrideColor, System.Windows.Forms.Form myForm) + + public static string ToPDFReplaceROs(ItemInfo sect, bool openPdf, List roids, VolianStatusChange statusChange) { string fileName = GetFileName(sect); - // TODO: do we want to cache the word pdfs - //if (System.IO.File.Exists(@"C:\Temp\" + fileName + ".pdf")) - // return @"C:\Temp\" + fileName + ".pdf"; - //int docStyleIndex = ((int)sect.MyContent.Type) % 10000; - //DocStyle myDocStyle = sect.ActiveFormat.PlantFormat.DocStyles.DocStyleList[docStyleIndex]; + DocStyle myDocStyle = sect.MyDocStyle; - //PageStyle myPageStyle = myDocStyle.pagestyle; ProcedureInfo proc = sect.MyProcedure; DocVersionInfo dvi = proc.ActiveParent as DocVersionInfo; bool hasRos = false; @@ -828,25 +946,30 @@ namespace VEPROMS.CSLA.Library string igPrefix = null; string spPrefix = null; bool convertCaretToDeltaSymbol = (sect.ActiveSection != null) ? sect.ActiveSection.ActiveFormat.PlantFormat.FormatData.SectData.ConvertCaretToDelta : false; // C2018-003 fixed use of getting the active section + if (dvi.DocVersionAssociationCount > 0) { hasRos = true; rofst = dvi.DocVersionAssociations[0].MyROFst; - lookup = rofst.GetROFSTLookup(dvi); igPrefix = dvi.DocVersionConfig.RODefaults_graphicsprefix; spPrefix = dvi.DocVersionConfig.RODefaults_setpointprefix; + + // The following code sets the DocVersionInfo and the OtherChild properties for the current RofstLookup instance (lookup), and also enables Caching + // When printing or converting word sections to pdf, any RoChild "value" is the Unit Specific Value for the SelectedSlave + lookup = rofst.GetROFSTLookup(dvi, Convert.ToString(sect.MyDocVersion.DocVersionConfig.SelectedSlave)); } - // string AccPageID = string.Format("<{0}-{1}>", accPrefix, roch.appid); - // B2017-249 Recover Temporary File And AutoSave support for MSWord + + // B2017-249 Recover Temporary File And AutoSave support for MSWord using (DSOFile myFile = new DSOFile(sect.MyContent.MyEntry.MyDocument, true)) { // Increase the priority of the Word Process so that the pdf creation happens quickly Process[] myProcessess = Process.GetProcessesByName("winword"); + foreach (Process myProcess in myProcessess) { try { - if (myProcess.PriorityClass != ProcessPriorityClass.High && myProcess.MainWindowTitle == "") + if (myProcess.PriorityClass != ProcessPriorityClass.High && myProcess.MainWindowTitle == string.Empty) myProcess.PriorityClass = ProcessPriorityClass.High; } catch (Exception ex) @@ -858,78 +981,105 @@ namespace VEPROMS.CSLA.Library } } } + + // Use positions relative to margins + bool adjustMargins = true; + + // Set Application Level Properties + //MyApp.Visible = false; + + // Open new Document LBDocumentClass myDoc = MyApp.Documents.Open(myFile.FullName, false); - //MyApp.Visible = true; - bool adjustMargins = true; // Use positions relative to margins + try { SectionConfig sc = sect.ActiveSection.MyConfig as SectionConfig; + if (sc == null || sc.Section_WordMargin == "N") { AdjustMargins(myDocStyle, myDoc, true); + // B2020-122 Reset RightIndent to zero if it is set AP Enhanced Background Documents/AP-RHR.2 // B2020-136 for Ginna (RGE) only. Causes problems for WCN Training/APs/AP30E-002 myDoc.Application.Selection.WholeStory(); - if(myDoc.Application.Selection.ParagraphFormat.RightIndent != 0 - && (sect.ActiveFormat.Name.StartsWith("RGE") - || sect.ActiveFormat.Name.StartsWith("Ginna"))) + + if (myDoc.Application.Selection.ParagraphFormat.RightIndent != 0 && (sect.ActiveFormat.Name.StartsWith("RGE") || sect.ActiveFormat.Name.StartsWith("Ginna"))) + { myDoc.Application.Selection.ParagraphFormat.RightIndent = 0; + } } else + { adjustMargins = false; // Use absolute positions + } } catch (Exception ex) { - AddErrorLogInfoMarginNotFixed(sect,"Word section could not adjust margins"); // B2018-089 - Made error log output more useful - //_MyLog.Error("Could not Adjust Margins", ex); + // B2018-089 - Made error log output more useful + AddErrorLogInfoMarginNotFixed(sect, "Word section could not adjust margins"); } - string txtForBaseline = ""; // C2018-018 save the contents of Word sections - after resolving RO values + + string txtForBaseline = string.Empty; // C2018-018 save the contents of Word sections - after resolving RO values if (Volian.Base.Library.BaselineMetaFile.IsOpen && Volian.Base.Library.BaselineMetaFile.IncludeWordSecText) Volian.Base.Library.BaselineMetaFile.WriteLine("++BgnTxt++"); LBSelection sel = MyApp.Selection; sel.WholeStory(); + if (Volian.Base.Library.BaselineMetaFile.IsOpen && Volian.Base.Library.BaselineMetaFile.IncludeWordSecText) txtForBaseline = sel.Text; LBSelection selxy = hasRos ? FindXyPlot() : null; // look for XY Plot language typed into word section (not an RO) string pngFile = VlnSettings.TemporaryFolder + @"\XYPlot1.png"; //@"C:\Temp\XYPlot1.png"; - if (File.Exists(pngFile)) File.Delete(pngFile); + + try + { + File.Delete(pngFile); + } + catch { } + int filecount = 1; + while (selxy != null) { // B2017-007 Fixed logic to properly position an XY Plot string xyplot = selxy.Text; xyplot = xyplot.Replace("`", "\xB0"); xyplot = xyplot.Replace("\xF8", "\xB0"); + if (Volian.Base.Library.BaselineMetaFile.IsOpen && Volian.Base.Library.BaselineMetaFile.IncludeWordSecText) { txtForBaseline = txtForBaseline.Replace("`", "\xB0"); txtForBaseline = txtForBaseline.Replace("\xF8", "\xB0"); } + if (convertCaretToDeltaSymbol) { xyplot = xyplot.Replace("^", "\x394"); // delta xyplot = xyplot.Replace("\x7F", "\x394"); //delta + if (Volian.Base.Library.BaselineMetaFile.IsOpen && Volian.Base.Library.BaselineMetaFile.IncludeWordSecText) { txtForBaseline = txtForBaseline.Replace("^", "\x394"); txtForBaseline = txtForBaseline.Replace("\x7F", "\x394"); } } + // The 16bit code must have kept the carriage returns in the word doc, if there // are carriage returns in the plot language. Count number of carriage return/newlines // so that they can be added back. int cnt = 0; int indxCr = xyplot.IndexOf("\r"); + while (indxCr > 0) { cnt++; indxCr = xyplot.IndexOf("\r", indxCr + 1); } - // Setting the selected text to "" actually sets it to "\r", thus cnt-- (subtract one - // from cnt since there's already a return in the string. + + // Setting the selected text to "" actually sets it to "\r", thus cnt-- (subtract one from cnt since there's already a return in the string. cnt--; - PointF pt = GetLocation(selxy,adjustMargins); + PointF pt = GetLocation(selxy, adjustMargins); float y = pt.Y; string resXyPlot = xyplot; string txt = FindEmbeddedText(selxy.Text, ref resXyPlot); + if (txt != null) { selxy.Text = txt; @@ -937,12 +1087,13 @@ namespace VEPROMS.CSLA.Library } else { - selxy.Text = ""; + selxy.Text = string.Empty; if (cnt > 0) for (int icnt = 0; icnt < cnt; icnt++) selxy.Text = selxy.Text + "\r"; } pngFile = VlnSettings.TemporaryFolder + @"\XYPlot" + filecount.ToString() + @".png"; //@"C:\Temp\XYPlot1.png"; filecount++; + try // C2018-035 if an error occurs make the error message more specific { RectangleF plotRect = CreatePlot(pngFile, xyplot, 600F, FormForPlotGraphics); @@ -950,9 +1101,16 @@ namespace VEPROMS.CSLA.Library float xxx = pt.X + plotRect.X; if (xxx < 0 && xxx > -.5) xxx = 0; + float yyy = yAdjust + y + plotRect.Y; LBShape shape = myDoc.Shapes.AddPicture(pngFile, xxx, yyy, selxy.Range); - File.Delete(pngFile); + + try + { + File.Delete(pngFile); + } + catch { } + if (adjustMargins) { shape.RelativeVerticalPosition = LBWdRelativeVerticalPosition.wdRelativeVerticalPositionMargin; @@ -963,372 +1121,433 @@ namespace VEPROMS.CSLA.Library shape.RelativeVerticalPosition = LBWdRelativeVerticalPosition.wdRelativeVerticalPositionPage; shape.RelativeHorizontalPosition = LBWdRelativeHorizontalPosition.wdRelativeHorizontalPositionPage;// .wdRelativeHorizontalPositionMargin; } + shape.LockAspectRatio = LBMsoTriState.msoTrue; shape.Width = plotRect.Width; shape.Left = xxx; shape.Top = pt.Y; + } catch (Exception ex)// C2018-035 if an error occurs make the error message more specific { - // C2018-035 Don't use a messagebox if in automatic(Baseline) testing mode. + // C2018-035 Don't use a MessageBox if in automatic(Baseline) testing mode. if (!Automatic) System.Windows.Forms.MessageBox.Show(ex.Message, "X/Y Plot Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation); _MyLog.WarnFormat("Problem with XYPlot {0} - {1}", ex.GetType().Name, ex.Message); } + selxy.WholeStory(); selxy = FindXyPlot(); } - //LBSelection sel = MyApp.Selection; + sel.WholeStory(); - string roTokenForBaseline = ""; + string roTokenForBaseline = string.Empty; if (statusChange != null) statusChange(VolianStatusType.Initialize, sel.End, "Refreshing ROs"); sel = hasRos ? FindRO() : null; int roCount = 0; + // force Print of MS Word Attachment to Final without revisions and comments myDoc.ActiveWindow.View.ShowRevisionsAndComments = false; myDoc.ActiveWindow.View.RevisionsView = LBWdRevisionsView.wdRevisionsViewFinal; + int lastStart = sel == null ? 0 : sel.Start; + // Cache RO Values while printing for performance increase + _roPrintCache = new Dictionary(); + while (sel != null) { - if (Volian.Base.Library.BaselineMetaFile.IsOpen && Volian.Base.Library.BaselineMetaFile.IncludeWordSecText) roTokenForBaseline = sel.Text; - if (statusChange != null) statusChange(VolianStatusType.Update, sel.Start, string.Format("{0} ROs Refreshed", ++roCount)); - string val = lookup.GetROValueByAccPagID(sel.Text, spPrefix, igPrefix); - int? type = lookup.GetROTypeByAccPagID(sel.Text, spPrefix, igPrefix); - // if type is null, then set type to zero so that InsertROValue will put in "RO Not Found" for the value - if (type == null) - type = 0; - // If multiple return values includes X-Y Plot, check to see if it is an X-Y Plot - if (val == null) + if (!string.IsNullOrEmpty(sel.Text)) { - if(sel.Text.ToUpper() == "") val =lookup.MyDocVersionInfo.DocVersionConfig.Unit_Text; - else if (sel.Text.ToUpper() == "") val = lookup.MyDocVersionInfo.DocVersionConfig.Unit_Number; - else if (sel.Text.ToUpper() == "") val = lookup.MyDocVersionInfo.DocVersionConfig.Unit_Name; - else if (sel.Text.ToUpper() == "") val = lookup.MyDocVersionInfo.DocVersionConfig.Unit_ID; - // B2021-145: For applicability, the tree view & pdf file name are not getting resolved when using any of the ‘OTHER’ tokens - // B2022-023 also check for other followed by a space - else if (sel.Text.ToUpper() == "" || sel.Text.ToUpper() == "") val = lookup.MyDocVersionInfo.DocVersionConfig.Other_Unit_Text; - else if (sel.Text.ToUpper() == "" || sel.Text.ToUpper() == "") val = lookup.MyDocVersionInfo.DocVersionConfig.Other_Unit_Number; - else if (sel.Text.ToUpper() == "" || sel.Text.ToUpper() == "") val = lookup.MyDocVersionInfo.DocVersionConfig.Other_Unit_Name; - else if (sel.Text.ToUpper() == "" || sel.Text.ToUpper() == "") val = lookup.MyDocVersionInfo.DocVersionConfig.Other_Unit_ID; - //val = "",MyDocVersion.DocVersionConfig.Unit_ID); - //text = text.Replace(@"", _MyItemInfo.MyDocVersion.DocVersionConfig.Unit_ProcedureSetID); - //text = text.Replace("", _MyItemInfo.MyDocVersion.DocVersionConfig.Unit_Number); - } - if ((type & 4) == 4 && val.StartsWith("< -.5) - xxx = 0; - float yyy = pt.Y; - //_MyLog.WarnFormat("xxx={0},yyy={1}", xxx, yyy); - sel.Text = ""; - LBShape shape = myDoc.Shapes.AddPicture(roImageFile.MyFile.FullName, xxx, yyy, sel.Range); - File.Delete(pngFile); - if (adjustMargins) - { - shape.RelativeVerticalPosition = LBWdRelativeVerticalPosition.wdRelativeVerticalPositionMargin; - shape.RelativeHorizontalPosition = LBWdRelativeHorizontalPosition.wdRelativeHorizontalPositionMargin;// .wdRelativeHorizontalPositionMargin; - } - else - { - shape.RelativeVerticalPosition = LBWdRelativeVerticalPosition.wdRelativeVerticalPositionPage; - shape.RelativeHorizontalPosition = LBWdRelativeHorizontalPosition.wdRelativeHorizontalPositionPage;// .wdRelativeHorizontalPositionMargin; - } - shape.LockAspectRatio = LBMsoTriState.msoTrue; - shape.Width = width; - shape.Height = height; - shape.Left = xxx; - shape.Top = pt.Y; - //_MyLog.WarnFormat("Shape.Left={0}, Shape.Top={1}", shape.Left, shape.Top); - if (Volian.Base.Library.BaselineMetaFile.IsOpen && Volian.Base.Library.BaselineMetaFile.IncludeWordSecText) txtForBaseline = txtForBaseline.Replace(roTokenForBaseline, string.Format("[{0}]", vals[0])); - imageROTokenReplaced = true; + string roidkey = string.Format("{0}:{1}", rofst.RODbID, roc.roid); + if (!roids.Contains(roidkey)) roids.Add(roidkey); } - if (!imageROTokenReplaced) + + if (roType == 8) // Image { - sel.Text = string.Format("Bad Image Link (Missing Image File:{0})", vals[0]); - if (Volian.Base.Library.BaselineMetaFile.IsOpen && Volian.Base.Library.BaselineMetaFile.IncludeWordSecText) txtForBaseline = txtForBaseline.Replace(roTokenForBaseline, sel.Text); + //Console.WriteLine("Image: {0} - {1}", sect.MyContent.Number, sect.MyContent.Text); + bool imageROTokenReplaced = false; + string[] vals = roValue.Split("\n".ToCharArray()); + + ROImageInfo roImage = ROImageInfo.GetByROFstID_FileName(rofst.ROFstID, vals[0]); + + if (roImage == null) + { + // need code to go and get an ROImaage if it exists + roImage = rofst.GetROImageByFilename(vals[0], sect); + } + + if (roImage != null) + { + ROImageFile roImageFile = new ROImageFile(roImage); + float width = 72 * Int32.Parse(vals[3], System.Globalization.NumberStyles.AllowHexSpecifier) / 12.0F; + int lines = Int32.Parse(vals[2], System.Globalization.NumberStyles.AllowHexSpecifier); + float height = 72 * lines / 6.0F; + PointF pt = GetLocation(sel, adjustMargins); + + //_MyLog.WarnFormat("pt.x={0},pt.y={1}", pt.X,pt.Y); + float xxx = pt.X; + if (xxx < 0 && xxx > -.5) xxx = 0; + float yyy = pt.Y; + + //_MyLog.WarnFormat("xxx={0},yyy={1}", xxx, yyy); + sel.Text = string.Empty; + LBShape shape = myDoc.Shapes.AddPicture(roImageFile.MyFile.FullName, xxx, yyy, sel.Range); + + try + { + File.Delete(pngFile); + } + catch { } + + if (adjustMargins) + { + shape.RelativeVerticalPosition = LBWdRelativeVerticalPosition.wdRelativeVerticalPositionMargin; + shape.RelativeHorizontalPosition = LBWdRelativeHorizontalPosition.wdRelativeHorizontalPositionMargin;// .wdRelativeHorizontalPositionMargin; + } + else + { + shape.RelativeVerticalPosition = LBWdRelativeVerticalPosition.wdRelativeVerticalPositionPage; + shape.RelativeHorizontalPosition = LBWdRelativeHorizontalPosition.wdRelativeHorizontalPositionPage;// .wdRelativeHorizontalPositionMargin; + } + + shape.LockAspectRatio = LBMsoTriState.msoTrue; + shape.Width = width; + shape.Height = height; + shape.Left = xxx; + shape.Top = pt.Y; + + //_MyLog.WarnFormat("Shape.Left={0}, Shape.Top={1}", shape.Left, shape.Top); + if (Volian.Base.Library.BaselineMetaFile.IsOpen && Volian.Base.Library.BaselineMetaFile.IncludeWordSecText) txtForBaseline = txtForBaseline.Replace(roTokenForBaseline, string.Format("[{0}]", vals[0])); + + imageROTokenReplaced = true; + } + + if (!imageROTokenReplaced) + { + sel.Text = string.Format("Bad Image Link (Missing Image File:{0})", vals[0]); + if (Volian.Base.Library.BaselineMetaFile.IsOpen && Volian.Base.Library.BaselineMetaFile.IncludeWordSecText) txtForBaseline = txtForBaseline.Replace(roTokenForBaseline, sel.Text); + } + } - } - else if ((int)type == 4) // X-Y Plot - { - // B2017-007 Fixed logic to properly position an XY Plot - try + else if (roType == 4) // X-Y Plot { - val = val.Replace("`", "\xB0"); - val = val.Replace("\xF8", "\xB0"); - if (convertCaretToDeltaSymbol) - val = val.Replace("^", "\x394"); // delta - val = val.Replace("\x7F", "\x394"); //delta - if (Volian.Base.Library.BaselineMetaFile.IsOpen && Volian.Base.Library.BaselineMetaFile.IncludeWordSecText) txtForBaseline = txtForBaseline.Replace(sel.Text, val); - // An X/Y Plot RO type might have text preceding the Plot Commands - int pstart = val.IndexOf("< -.5) xxx = 0; + + float y = pt.Y; + int idx = sel.Text.IndexOf("\r"); + + while ((idx > 0) && (idx < sel.Text.Length + 1)) + { + idx = sel.Text.IndexOf("\r", idx + 1); + y += (float)sel.ParagraphFormat.LineSpacing; // get_Information(LBWdLineSpacing.wdLineSpaceSingle); + } + + float yAdjust = sel.Font.Size; + float yyy = yAdjust + y + plotRect.Y; + LBShape shape = myDoc.Shapes.AddPicture(pngFile, xxx, yyy, sel.Range); + + try + { + File.Delete(pngFile); + } + catch { } + + if (adjustMargins) + { + shape.RelativeVerticalPosition = LBWdRelativeVerticalPosition.wdRelativeVerticalPositionMargin; + shape.RelativeHorizontalPosition = LBWdRelativeHorizontalPosition.wdRelativeHorizontalPositionMargin;// .wdRelativeHorizontalPositionMargin; + } + else + { + shape.RelativeVerticalPosition = LBWdRelativeVerticalPosition.wdRelativeVerticalPositionPage; + shape.RelativeHorizontalPosition = LBWdRelativeHorizontalPosition.wdRelativeHorizontalPositionPage;// .wdRelativeHorizontalPositionMargin; + } + + shape.LockAspectRatio = LBMsoTriState.msoTrue; + shape.Width = plotRect.Width; + shape.Left = xxx; + shape.Top = pt.Y; + sel.WholeStory(); + + if (Volian.Base.Library.BaselineMetaFile.IsOpen && Volian.Base.Library.BaselineMetaFile.IncludeWordSecText) Volian.Base.Library.BaselineMetaFile.WriteLine("{0}", TextForBaseline.FixText(txtForBaseline, true)); + } + catch (Exception ex) + { + // something is wrong with the X/Y plot RO. Just print out the un-processed X/Y plot RO value + if (Volian.Base.Library.BaselineMetaFile.IsOpen && Volian.Base.Library.BaselineMetaFile.IncludeWordSecText) txtForBaseline = txtForBaseline.Replace(roTokenForBaseline, string.Format("BAD XYPLOT: {0}", roValue)); + sel.Text = roValue; + } + } + else + { + // if roValue is null, then InsertROValue will put in "RO Not Found" for the value + float indent = (float)sel.get_Information(LBWdInformation.wdHorizontalPositionRelativeToTextBoundary); + if (Volian.Base.Library.BaselineMetaFile.IsOpen && Volian.Base.Library.BaselineMetaFile.IncludeWordSecText) txtForBaseline = txtForBaseline.Replace(roTokenForBaseline, roValue); + // B2017-217 Added logic so that underscores are not converted to underline // C2018-003 fixed use of getting the active section - AddPrecedingText(sel, val.Substring(0, pstart), 0.0F, (sect.ActiveSection != null)? sect.ActiveSection.ActiveFormat.PlantFormat.FormatData.SectData.ConvertUnderscoreToUnderline : false);// replace the RO token with what's in front of the X/Y Plot - val = val.Substring(pstart); // set val to the start of the plot commands - pngFile = VlnSettings.TemporaryFolder + @"\XYPlot1.png"; //@"C:\Temp\XYPlot1.png"; - RectangleF plotRect = CreatePlot(pngFile, val, 600F, FormForPlotGraphics); - PointF pt = GetLocation(sel, adjustMargins); - float xxx = pt.X + plotRect.X; - if (xxx < 0 && xxx > -.5) - xxx = 0; - float y = pt.Y; - int idx = sel.Text.IndexOf("\r"); - while ((idx > 0) && (idx < sel.Text.Length + 1)) - { - idx = sel.Text.IndexOf("\r", idx + 1); - y += (float)sel.ParagraphFormat.LineSpacing; // get_Information(LBWdLineSpacing.wdLineSpaceSingle); - } - float yAdjust = sel.Font.Size; - float yyy = yAdjust + y + plotRect.Y; - LBShape shape = myDoc.Shapes.AddPicture(pngFile, xxx, yyy, sel.Range); - File.Delete(pngFile); - if (adjustMargins) - { - shape.RelativeVerticalPosition = LBWdRelativeVerticalPosition.wdRelativeVerticalPositionMargin; - shape.RelativeHorizontalPosition = LBWdRelativeHorizontalPosition.wdRelativeHorizontalPositionMargin;// .wdRelativeHorizontalPositionMargin; - } - else - { - shape.RelativeVerticalPosition = LBWdRelativeVerticalPosition.wdRelativeVerticalPositionPage; - shape.RelativeHorizontalPosition = LBWdRelativeHorizontalPosition.wdRelativeHorizontalPositionPage;// .wdRelativeHorizontalPositionMargin; - } - shape.LockAspectRatio = LBMsoTriState.msoTrue; - shape.Width = plotRect.Width; - shape.Left = xxx; - shape.Top = pt.Y; - sel.WholeStory(); - if (Volian.Base.Library.BaselineMetaFile.IsOpen && Volian.Base.Library.BaselineMetaFile.IncludeWordSecText) Volian.Base.Library.BaselineMetaFile.WriteLine("{0}", TextForBaseline.FixText(txtForBaseline, true)); - } - catch (Exception ex) - { - // something is wrong with the X/Y plot RO. - // print out the un-processed X/Y plot RO value - if (Volian.Base.Library.BaselineMetaFile.IsOpen && Volian.Base.Library.BaselineMetaFile.IncludeWordSecText) txtForBaseline = txtForBaseline.Replace(roTokenForBaseline, string.Format("BAD XYPLOT: {0}", val)); - sel.Text = val; - //return null; + InsertROValue(sel, roValue, sect.ActiveFormat.PlantFormat.FormatData.ROData.UpRoIfPrevUpper, indent, (sect.ActiveSection != null) ? sect.ActiveSection.ActiveFormat.PlantFormat.FormatData.SectData.ConvertUnderscoreToUnderline : false); } + } - else - { - if (val != null) - { - val = val.Replace("`", "\xB0"); - val = val.Replace("\xF8", "\xB0"); - } - //AddInfo("\tRO Found {0} = '{1}'", sel.Text, val); - // if val is null, then InsertROValue will put in "RO Not Found" for the value - float indent = (float)sel.get_Information(LBWdInformation.wdHorizontalPositionRelativeToTextBoundary); - if (Volian.Base.Library.BaselineMetaFile.IsOpen && Volian.Base.Library.BaselineMetaFile.IncludeWordSecText) txtForBaseline = txtForBaseline.Replace(roTokenForBaseline, val); - // B2017-217 Added logic so that underscores are not converted to underline - // C2018-003 fixed use of getting the active section - InsertROValue(sel, val, sect.ActiveFormat.PlantFormat.FormatData.ROData.UpRoIfPrevUpper, indent, (sect.ActiveSection != null)?sect.ActiveSection.ActiveFormat.PlantFormat.FormatData.SectData.ConvertUnderscoreToUnderline:false); - } + sel = FindRO(); - if (sel != null && sel.Start == lastStart) + + if (sel != null && !string.IsNullOrEmpty(sel.Text) && sel.Start == lastStart) { Console.WriteLine("Seems to be repeating find of ro that is not an ro: " + sel.Text); sel = null; } } + + // Disable/Clear RO Cache When done looking up RO Values during printing + _roPrintCache.Clear(); + _roPrintCache = null; + if (statusChange != null) statusChange(VolianStatusType.Update, 0, "Creating PDF"); sel = MyApp.Selection; sel.WholeStory(); + if (Volian.Base.Library.BaselineMetaFile.IsOpen && Volian.Base.Library.BaselineMetaFile.IncludeWordSecText) Volian.Base.Library.BaselineMetaFile.WriteLine("{0}", TextForBaseline.FixText(txtForBaseline, true)); - //sel.Range.Font.Color = (LBWdColor)WordColor(PrintOverride.OverrideTextColor(System.Drawing.Color.Black)); - //Console.WriteLine("'{0}' Colors Sel '{1}' Override '{2}' Transparent '{3}' Black '{4}' Red '{5}'", sect.DisplayNumber, sel.Range.Font.Color, OverrideColor, System.Drawing.Color.Transparent, System.Drawing.Color.Black, System.Drawing.Color.Red); + if (sel.Range.Font.Color != (LBWdColor)9999999 || OverrideColor == System.Drawing.Color.Red)// B2017-144 If the font color is 9999999 then the color is mixed, and if the override color isn't red, don't change the color. sel.Range.Font.Color = (LBWdColor)WordColor(OverrideColor == System.Drawing.Color.Transparent ? System.Drawing.Color.Black : OverrideColor); + sect.MSWordPageCount = myDoc.Length; - fileName = CreatePDF(fileName, openPdf,MSWordToPDF.DebugStatus); + fileName = CreatePDF(fileName, openPdf, MSWordToPDF.DebugStatus); + if (DocReplace != null) { MyApp.ActiveDocument.SaveAs2000(); - DocReplace.Add(sect.MyContent.MyEntry.DocID, GetBytes(MyApp.ActiveDocument.FullName)); // save the word document containing resolved ROs + + // save the word document containing resolved ROs + DocReplace.Add(sect.MyContent.MyEntry.DocID, GetBytes(MyApp.ActiveDocument.FullName)); } + CloseDocument(); - // B2017-249 Delete Temporary file - myFile.MyFile.Delete(); + + // B2017-249 Try to Delete Temporary file + try + { + myFile.MyFile.Delete(); + } + catch { } + if (CloseWordWhenDone) { CloseAppAfterWait(); } - if (statusChange != null) statusChange(VolianStatusType.Complete, 0, ""); + + if (statusChange != null) statusChange(VolianStatusType.Complete, 0, string.Empty); if (Volian.Base.Library.BaselineMetaFile.IsOpen && Volian.Base.Library.BaselineMetaFile.IncludeWordSecText) Volian.Base.Library.BaselineMetaFile.WriteLine("++EndTxt++"); - GC.Collect(); //jsj 2-15-2016 - for memeory garbage collection + + //GC.Collect(); //jsj 2-15-2016 - for memory garbage collection + + //GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce; + //GC.Collect(); + return fileName; } } - private static bool _Automatic = false; - /// - /// C2018-035 Don't use a messagebox if in automatic(Baseline) testing mode. - /// - public static bool Automatic - { - get { return MSWordToPDF._Automatic; } - set { MSWordToPDF._Automatic = value; } - } - private static void AddErrorLogInfoMarginNotFixed(ItemInfo sect,string msg)// B2018-089 - Made error log output more useful - { - _MyLog.WarnFormat("\r\n==> {0}\r\n" + - " [{1}] {2}\r\n" + - " in {3}\r\n" + - " Document: {4}\r\n" + - " ACTION REQUIRED: Should use Word Margins", - msg, sect.ItemID, sect.ShortPath, - sect.SearchDVPath.Replace("\a", "/"), sect.MyContent.MyEntry.MyDocument.LibTitle ?? sect.MyContent.MyEntry.DocID.ToString()); - } - private static PointF GetLocation(LBSelection sel, bool adjustMargins) - { - LBRange rng0 = MyApp.ActiveDocument.Range(0, 0); - LBRange rng1 = MyApp.ActiveDocument.Range(sel.Start, sel.Start); - float fx0 = adjustMargins ? (float)rng0.get_Information(LBWdInformation.wdHorizontalPositionRelativeToPage) : 0; - for (int ix = sel.Start; ix > 0; ix--) // Find left most location - this was added since the first line may be centered or right justified - { - LBRange rngx = MyApp.ActiveDocument.Range(ix, ix); - float fxx = adjustMargins ? (float)rngx.get_Information(LBWdInformation.wdHorizontalPositionRelativeToPage) : 0; - //Console.WriteLine("fx0={0},fxx={1}", fx0, fxx); - if (fxx < fx0) fx0 = fxx; - else break; - } - float fy0 = adjustMargins ? (float)rng0.get_Information(LBWdInformation.wdVerticalPositionRelativeToPage) : 0; - float fx1 = (float)rng1.get_Information(LBWdInformation.wdHorizontalPositionRelativeToPage); - float fy1 = (float)rng1.get_Information(LBWdInformation.wdVerticalPositionRelativeToPage); - //_MyLog.WarnFormat("X {0}-{1}={2}",fx1, fx0, fx1-fx0); - //_MyLog.WarnFormat("Y {0}-{1}={2}",fy1, fy0, fy1-fy0); - return new PointF(fx1-fx0,fy1-fy0); - } - // Reads the Word file containing the resolved ROs - // used when adding to DocReplace - private static byte[] GetBytes(string filename) - { - FileInfo fi = new FileInfo(filename); - FileStream fs = fi.Open(FileMode.Open,FileAccess.Read,FileShare.ReadWrite); - byte[] buf = new byte[fi.Length]; - fs.Read(buf, 0, buf.Length); - fs.Close(); - return buf; - } - private static void CloseDocument() - { - int attempts = 0; - while (++attempts < 11) - { - if (TryToClose(attempts)) return; - WaitMS(1000); - } - } - private static bool TryToClose(int attempts) + + + private static ROFSTLookup.rochild GetCachedRoByAccPageID(ROFSTLookup lookup, string selText, string spPrefix, string igPrefix, bool convertCaretToDeltaSymbol) { + string accPageBase = string.Empty; + string accPageExt = string.Empty; + try { - MyApp.ActiveDocument.Close(false); - return true; - } - catch (Exception ex) - { - _MyLog.WarnFormat("{0} - {1}, Attempt {2}", ex.GetType().Name, ex.Message, attempts); - if (attempts >= 10) - _MyLog.Error("Failed to close 10 times.", ex); - return false; - } - } - private static string FindEmbeddedText(string p, ref string resXyPlot) - { - StringBuilder sb = new StringBuilder(); // contains embedded text - StringBuilder xy = new StringBuilder(); // contains xyplot without embedded text. - string origXy = p; - bool findEmbeddedText = false; - // get past opening command: - int indxCmd = p.IndexOf("<"); - indxCmd = p.IndexOf("<", indxCmd + 1); - xy.Append(p.Substring(0, indxCmd)); - // While there are xyplot commands, check for beginning/ending. - // Any text not in a command, save. - while (indxCmd > 0) - { - // find end of command. Look for another beginning of command, newline, - // regular text, or end of graph and handle each of these cases. - int indxClose = GetNonStringCmdClose(p, indxCmd + 1); // p.IndexOf(">", indxCmd + 1); - int nxtIndxCmd = p.IndexOf("<", indxCmd + 1); - xy.Append(p.Substring(indxCmd, indxClose - indxCmd+1)); - xy.Append("\r"); // the xyplot code assumes a return exists. - // get substrings between end index & start of next and if any - // non white space text, add it to return string and flag that we have - // embedded text. If there's a newline and just other white space put a - // newline in return string. - if (nxtIndxCmd > 0) + ROFSTLookup.rochild roc = ROFSTLookup.GetEmptyRoChild(); + + string accPageKey = ROFSTLookup.FormatAccPageKey(selText, spPrefix, igPrefix, ref accPageBase, ref accPageExt, true); + + // Check if the Rochild is in the PrintCache (use base accPageID without specific extension) + if (!_roPrintCache.ContainsKey(accPageBase)) { - string mydebug = p.Substring(indxClose + 1); - for (int i = indxClose + 1; i < nxtIndxCmd; i++) - { - if (!System.Char.IsWhiteSpace(p[i])) - { - sb.Append(p[i]); - findEmbeddedText = true; - } - if (p[i] == '\r' || p[i] == ' ') sb.Append(p[i]); - } + // Lookup RoChild Info from database + roc = lookup.GetROChildByAccPageID(accPageBase, spPrefix, igPrefix); + + // Check if RO is valid + if (roc.ID < 0 || string.IsNullOrEmpty(roc.roid)) + return ROFSTLookup.GetEmptyRoChild(); + + // If Valid Rochild, then add Rochild to Print Cache + _roPrintCache.Add(accPageBase, roc); } - indxCmd = nxtIndxCmd; + else // Get Base Rochild from Print Cache + { + roc = (ROFSTLookup.rochild)_roPrintCache[accPageBase]; + } + + // Check if RO is a "Unit Information" value (Ex: , etc..) + if (roc.roid.StartsWith("FFFF")) + return roc; + + + // All ROs should have a specific accPageExt or the default (A/0041), except for the "Unit Information" ("FFFF") + roc = (roc.children.Where(x => x.appid.EndsWith(accPageExt)).Any()) ? roc.children.Where(x => x.appid.EndsWith(accPageExt)).Single() : roc.children.First(); + + // Check the RoType + roc.type = ((roc.type & 4) == 4 && roc.value.StartsWith("<"); - if (findEmbeddedText) + catch { - resXyPlot = xy.ToString(); - return sb.ToString(); + return ROFSTLookup.GetEmptyRoChild(); } - resXyPlot = origXy; - return null; + + + + + //if (roc.children != null && roc.children.Count() > 0) + //{ + // roc = (roc.children.Where(x => x.appid.EndsWith(accPageExt)).Any()) ? roc.children.Where(x => x.appid.EndsWith(accPageExt)).Single() : roc.children.First(); + + // //roc = (roc.children.Where(x => x.roid.Substring(12, 4) == roExt.RoidExt).Any()) ? rc.children.Where(x => x.roid.Substring(12, 4) == roExt.RoidExt).Single() : rc.children.First(); + // // Convert.ToString(accPageKey.ToCharArray().LastOrDefault()) + //} + + //// All ROs should have a specific accPageExt, except for the "Unit Information" ("FFFF") + //// if (!string.IsNullOrEmpty(rc.roid) && Regex.IsMatch(accPageKey, @".*\.[A-Z]") && rc.children != null && rc.children.Count() > 0) + //if (!string.IsNullOrEmpty(accPageExt)) + //{ + // if (roc.children != null && roc.children.Count() > 0) + // { + // roc = (roc.children.Where(x => x.appid.EndsWith(accPageExt)).Any()) ? roc.children.Where(x => x.appid.EndsWith(accPageExt)).Single() : roc.children.First(); + // //roc = (roc.children.Where(x => x.roid.Substring(12, 4) == roExt.RoidExt).Any()) ? rc.children.Where(x => x.roid.Substring(12, 4) == roExt.RoidExt).Single() : rc.children.First(); + // // Convert.ToString(accPageKey.ToCharArray().LastOrDefault()) + // } + + // // Get specific RO return value by Extension, if not exists then return default ("0041") + // // var roExt = lookup.Extensions.Where(x => x.AccPageExt.Equals(accPageExt)).SingleOrDefault(); + //} + + + + // var accPageExt = Convert.ToString(accPageKey.ToCharArray().LastOrDefault()); + + // Regex.IsMatch(accPageKey, @".*\.[A-Z]") + + // Get the RoChild object once and cache it for any future calls to the same Ro while printing + //ROFSTLookup.rochild roc = lookup.GetROChildByAccPageID(sel.Text, spPrefix, igPrefix); + + //if (!_roPrintCache.ContainsKey(accPageKey)) + // _roPrintCache.Add(accPageKey, roc); + + //// Check the RoType + //int roType = roType = ((roc.type & 4) == 4 && roc.value.StartsWith("<", indxCmd); - if (indxClose >= 0) + RectangleF retval = new RectangleF(0, 0, 0, 0); + + System.Windows.Forms.Form frm = myForm; + Graphics grfx = frm.CreateGraphics(); + string emfFile = pngFile.Replace(".png", ".emf"); + + using (Metafile mf = new Metafile(emfFile, grfx.GetHdc())) { - // if there are any quotes between the open of command and close, - // need to see if the close command is quoted. - if (p.IndexOf('"', indxCmd, indxClose - indxCmd) > -1) - { - // see how many quotes between open/close command, if - // an odd number, the close command char '>' is in quotes. - int countQuotes = 0; - for (int i = indxCmd; i < indxClose; i++) if (p[i] == '"') countQuotes++; - if ((countQuotes % 2) != 0) - { - // find quote after close, and then get next close. - int closeQuote = p.IndexOf('"', indxClose); - if (closeQuote < 0) return -1; // this is error, so return end not found. - return p.IndexOf(">", closeQuote + 1); - } - } + grfx.Dispose(); + grfx = Graphics.FromImage(mf); + float dpi = grfx.DpiX; + float sf = ScalingFactor(); // B2019-069 get monitor scaling factor + + grfx.ScaleTransform(sf * resolution / grfx.DpiX, sf * resolution / grfx.DpiY); // B2019-069 multiply the monitor's scaling factor + grfx.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor; + grfx.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; + grfx.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; + grfx.Clear(MSWordToPDF.DebugStatus == 1 ? System.Drawing.Color.Transparent : System.Drawing.Color.White); + + XYPlots.XYPlot.BlackColor = MSWordToPDF.OverrideColor == Color.Red ? Color.Red : Color.Black; + XYPlots.XYPlot myPlot = new XYPlots.XYPlot(xyPlot); + myPlot.SetMargins(0, 0, 0, 0); + + VG.IVGOutput vgOut = new VG.VGOut_Graphics(grfx); + vgOut.DebugStatus = MSWordToPDF.DebugStatus; + myPlot.Process(vgOut); + grfx.Dispose(); + + //GC.Collect(); // memory garbage collection (Regex bug) + + GraphicsUnit gu = new GraphicsUnit(); + retval = mf.GetBounds(ref gu); + retval.Width *= dpi / resolution; + retval.Height *= dpi / resolution; + retval.X *= dpi / resolution; + retval.Y *= dpi / resolution; } - return indxClose; + + using (Metafile mf2 = new Metafile(emfFile)) + { + mf2.Save(pngFile, ImageFormat.Png); + } + + FileInfo myFile = new System.IO.FileInfo(emfFile); + + try + { + myFile.Delete(); + } + catch { } + + return retval; } + public static void AddPrecedingText(LBSelection sel, string val, float indent, bool convertUnderline) { // B2017-217 Added logic so that underscores are not converted to underline @@ -1345,19 +1564,23 @@ namespace VEPROMS.CSLA.Library { sel.Text = val; // nothing is underlined, use text as is } + return; } - // Back in the DOS days, an underbar was used to toggle underlining on/off - // Spit the val text on the underbar characters + + // Back in the DOS days, an under bar was used to toggle underlining on/off + // Spit the val text on the under bar characters string[] parts = val.Split("_".ToCharArray()); bool firstLine = true; + foreach (string partq in parts) { string part = partq; - // if we have a row of underbar "_" chars then we will parts of empty strings. - // in this case, we want to output the underbar char and turn off underlining. - // Ex Commanche Peak RO table in ECA-1.1A Attachment 5 - if (part.Equals("")) + + // if we have a row of under bar "_" chars then we will parts of empty strings. + // in this case, we want to output the under bar char and turn off underlining. + // Ex Comanche Peak RO table in ECA-1.1A Attachment 5 + if (part.Equals(string.Empty)) { if (sel.Font.Underline != LBWdUnderline.wdUnderlineNone) { @@ -1366,9 +1589,9 @@ namespace VEPROMS.CSLA.Library } sel.TypeText("_"); } - // If there is a carrage return, and underline is turned on, then turn off the underline else if (sel.Font.Underline != LBWdUnderline.wdUnderlineNone && part.Contains("\r")) { + // If there is a carriage return, and underline is turned on, then turn off the underline int idx = part.IndexOf("\r"); string part1 = part.Substring(0, idx); string part2 = part.Substring(idx); @@ -1383,6 +1606,7 @@ namespace VEPROMS.CSLA.Library // was spaced over. The remaining lines were up against the left margin. // this code will space over (indent) the remaining lines the same amount as the first line. if (!firstLine) sel.ParagraphFormat.FirstLineIndent = indent; + if (firstLine && part.Contains("\r\n")) { int idx = part.IndexOf("\r\n"); @@ -1391,9 +1615,10 @@ namespace VEPROMS.CSLA.Library sel.TypeText(beforeCR); sel.ParagraphFormat.FirstLineIndent = indent; } + // Farley had a case where the underlining of text with spaces at end of line was // not underlining the spaces. To fix this, test for spaces at the end of text - // and ireplace last space with a hard space. Note that the underlying issue + // and replace last space with a hard space. Note that the underlying issue // existed in MS Word, so this is a work around from our code to make MS Word work. // The problem was in Farley's FNP-1-ECP-3.1, Table 1 - 'ro': W.4T. if (part.EndsWith(" ")) @@ -1402,17 +1627,26 @@ namespace VEPROMS.CSLA.Library sel.InsertSymbol(160); } else + { sel.TypeText(part); + } if (sel.Font.Underline == LBWdUnderline.wdUnderlineNone) + { sel.Font.Underline = LBWdUnderline.wdUnderlineSingle; + } else + { sel.Font.Underline = LBWdUnderline.wdUnderlineNone; + } } } + // We are done processing the text in val, if underline is on, turn it off if (sel.Font.Underline != LBWdUnderline.wdUnderlineNone) + { sel.Font.Underline = LBWdUnderline.wdUnderlineNone; + } } public static void AdjustMargins(DocStyle myDocStyle, LBDocumentClass myDoc, bool printingMode) @@ -1427,28 +1661,38 @@ namespace VEPROMS.CSLA.Library float oldRight = myDoc.PageSetup.RightMargin; float oldHeight = myDoc.PageSetup.PageHeight; float oldWidth = myDoc.PageSetup.PageWidth; - // in the following line, the 2 accounts for a difference between how word treats margin versus - // ours, we are not exactly sure why. + + // in the following line, the 2 accounts for a difference between how word treats margin versus ours, we are not exactly sure why. float newRight = Math.Max(0, oldWidth - (newWidth + 2)); float newBottom = Math.Max(0, oldHeight - (newLength + newTop + 1)); + //Console.WriteLine("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9}", newTop, newLeft, newLength, newWidth, oldTop, oldLeft, oldBottom, oldRight,oldHeight,oldWidth); + if (printingMode) { if (myDoc.PageSetup.BottomMargin != 9999999) { // the + 1 in the next line allows for rounding. if ((newWidth > (8.5f * 72)) && newWidth > newLength) + { if (myDoc.PageSetup.Orientation != LBWdOrientation.wdOrientLandscape) { myDoc.PageSetup.Orientation = LBWdOrientation.wdOrientLandscape; myDoc.PageSetup.RightMargin = 11 * 72 - newWidth; } else + { myDoc.PageSetup.RightMargin = newRight; - else - myDoc.PageSetup.RightMargin = newRight; // bug fix B2017-140, B2017-142 right margin was too short - try // B2017-138 Add error handling for setting Bottom Margin + } + } + else { + myDoc.PageSetup.RightMargin = newRight; // bug fix B2017-140, B2017-142 right margin was too short + } + + try + { + // B2017-138 Add error handling for setting Bottom Margin myDoc.PageSetup.BottomMargin = newBottom; myDoc.PageSetup.LeftMargin = newLeft; myDoc.PageSetup.TopMargin = newTop; @@ -1457,13 +1701,14 @@ namespace VEPROMS.CSLA.Library { if (_MySection != null) { - AddErrorLogInfoMarginNotFixed(_MySection, "MSWord could not set Section margins");// B2018-089 - Made error log output more useful - //_MyLog.ErrorFormat("<<< ERROR >>> MSWord could not set margins\r\n==>'MSWord could not set margins',{0},'{1}','{2}'" - // , _MySection.ItemID, _MySection.MyDocVersion.MyFolder.Name, _MySection.ShortPath); + // B2018-089 - Made error log output more useful + AddErrorLogInfoMarginNotFixed(_MySection, "MSWord could not set Section margins"); } else - AddErrorLogInfoMarginNotFixed(myDoc, "MSWord could not set Document margins");// B2018-089 - Made error log output more useful - //_MyLog.ErrorFormat("Could not set margins {0}", myDoc.FullName); + { + // B2018-089 - Made error log output more useful + AddErrorLogInfoMarginNotFixed(myDoc, "MSWord could not set Document margins"); + } } } else @@ -1480,13 +1725,14 @@ namespace VEPROMS.CSLA.Library { if (_MySection != null) { - AddErrorLogInfoMarginNotFixed(_MySection, "MSWord could not set Section margins");// B2018-089 - Made error log output more useful - //_MyLog.ErrorFormat("<<< ERROR >>> MSWord could not set margins\r\n==>'MSWord could not set margins',{0},'{1}','{2}'" - // , _MySection.ItemID, _MySection.MyDocVersion.MyFolder.Name, _MySection.ShortPath); + // B2018-089 - Made error log output more useful + AddErrorLogInfoMarginNotFixed(_MySection, "MSWord could not set Section margins"); } else - AddErrorLogInfoMarginNotFixed(myDoc, "MSWord could not set Document margins");// B2018-089 - Made error log output more useful - //_MyLog.Error("Could not set margins", ex); + { + // B2018-089 - Made error log output more useful + AddErrorLogInfoMarginNotFixed(myDoc, "MSWord could not set Document margins"); + } } } } @@ -1494,36 +1740,31 @@ namespace VEPROMS.CSLA.Library { myDoc.PageSetup.TopMargin = 0; myDoc.PageSetup.LeftMargin = 0;// B2017-264 Limit the value for right margin so that it cannot be negative. - float rm = (8.5F * 72) - newWidth + newLeft; - myDoc.PageSetup.RightMargin = Math.Max(0,rm); + float rm = (8.5F * 72) - newWidth + newLeft; + myDoc.PageSetup.RightMargin = Math.Max(0, rm); + // For OHLP, docstyle (ohlpdoc.in) in 16-bit for "Cover Page", pagelen seems to be incorrect. It would // put out text on a second page. The following code is to catch this condition and reset the bottom margin. // 11 * 72 -> 11 inches converted to points. newLength is printable part so BottomMargin is unprintable part float bm; - if (newTop + 36 > ((11 * 72) - newLength)) // 36 is 1/2 inch - bm = newTop + 36; // makes an 1/2 inch bottom margin + if (newTop + 36 > ((11 * 72) - newLength)) // 36 is 1/2 inch + bm = newTop + 36; // makes an 1/2 inch bottom margin else bm = (11 * 72) - newLength; + // B2017-264 Limit the value for bottom margin so that it cannot be negative myDoc.PageSetup.BottomMargin = Math.Max(0, bm); } } - private static void AddErrorLogInfoMarginNotFixed(LBDocumentClass myDoc, string msg)// B2018-089 - Made error log output more useful - { - _MyLog.WarnFormat("\r\n==> {0}\r\n" + - " Document: {1}\r\n" + - " ACTION REQUIRED: Should use Word Margins", - msg, myDoc.FullName); - } - public static void CloseApp() - { - //WaitMS(900);// This was added because MSWord will sometimes get the error below - // Microsoft Office Word has stopped working - // It appears that this is caused by quiting the MS Word application - // to soon after closing the document or doing an export. - MyApp.Quit(false); - _MyApp = null; - } + + //public static void CloseApp() + //{ + // // WaitMS(900);// This was added because MSWord will sometimes get the following error: [Microsoft Office Word has stopped working] + // // It appears that this is caused by quitting the MS Word application to soon after closing the document or doing an export. + // MyApp.Quit(false); + // _MyApp = null; + //} + /// /// This closes the MS Word Application, but, delays for about 1 second. /// It appears that closing MSWord to quickly causes a: @@ -1535,165 +1776,103 @@ namespace VEPROMS.CSLA.Library new CloseWordApp(_MyApp, 1000); _MyApp = null; } - private class CloseWordApp:System.Windows.Forms.Timer - { - LBApplicationClass _MyApp; - public LBApplicationClass MyApp - { - get { return _MyApp; } - set { _MyApp = value; } - } - public CloseWordApp(LBApplicationClass myApp, int interval) - { - MyApp = myApp; - Interval = interval; - Tick += new EventHandler(CloseWordApp_Tick); - Enabled = true; - } - // B2019-161 When tracking timing time this action - private static VolianTimer _TimeActivity = new VolianTimer("DocumentExt.cs CloseWordApp_Tick", 1548); - void CloseWordApp_Tick(object sender, EventArgs e) - { - _TimeActivity.Open(); - Enabled = false; - try // B2018-071 Keep code from crashing on close of MS Word - { - MyApp.Quit(false); - } - catch (Exception ex) - { - _MyLog.WarnFormat("MyApp Quit {0} {1}", ex.GetType().FullName, ex.Message); - } - Dispose(); - _TimeActivity.Close(); - } - } - private static void WaitMS(int n) + #endregion + + #region Private Methods + + //private static void WaitMS(int n) + //{ + // DateTime dtw = DateTime.Now.AddMilliseconds(n); + + // while (DateTime.Now < dtw) + // { + // System.Windows.Forms.Application.DoEvents(); + // } + //} + + private static void CloseDocument() { - DateTime dtw = DateTime.Now.AddMilliseconds(n); - while (DateTime.Now < dtw) + int attempts = 0; + + while (++attempts < 11) { System.Windows.Forms.Application.DoEvents(); + + if (TryToClose(attempts)) return; + System.Threading.Thread.Sleep(1000); + //WaitMS(1000); } } - private static int WordColor(System.Drawing.Color color) + + private static bool TryToClose(int attempts) { - System.Drawing.Color c1 = System.Drawing.Color.FromArgb(0, color.B, color.G, color.R); - return c1.ToArgb(); - } - private static string GetFileName(ItemInfo sect) - { - string fileName = VlnSettings.TemporaryFolder + @"\Doc_" + sect.MyContent.MyEntry.DocID.ToString()+".Pdf"; // +" " + (sect.DisplayNumber == "" ? sect.DisplayText : sect.DisplayNumber); - return fileName; - } - [DllImport("User32.dll")] - static extern IntPtr GetDC(IntPtr hwnd); - [DllImport("User32.dll")] - static extern int ReleaseDC(IntPtr hwnd, IntPtr dc); - [DllImport("gdi32.dll")] - static extern int GetDeviceCaps(IntPtr hdc, int nIndex); - public enum DeviceCap - { - VERTRES = 10, - DESKTOPVERTRES = 117 - } - // B2019-069 needed to get the monitor's scaling factor - used in generating RO X/Y plot - private static float ScalingFactor() - { - IntPtr desktop = GetDC(IntPtr.Zero); - int LogicalScreenHeight = GetDeviceCaps(desktop, (int)DeviceCap.VERTRES); - int PhysicalScreenHeight = GetDeviceCaps(desktop, (int)DeviceCap.DESKTOPVERTRES); - ReleaseDC(IntPtr.Zero, desktop); - return (float)PhysicalScreenHeight / (float)LogicalScreenHeight; // a value of 1.50 represents monitor scaling set to 150% - } - public static RectangleF CreatePlot(string pngFile, string xyPlot, float resolution, System.Windows.Forms.Form myForm) - { - RectangleF retval = new RectangleF(0, 0, 0, 0); - //Form frm = Application.OpenForms[0]; - System.Windows.Forms.Form frm = myForm; - Graphics grfx = frm.CreateGraphics(); - string emfFile = pngFile.Replace(".png", ".emf"); - using (Metafile mf = new Metafile(emfFile, grfx.GetHdc())) + try { - grfx.Dispose(); - grfx = Graphics.FromImage(mf); - float dpi = grfx.DpiX; - float sf = ScalingFactor(); // B2019-069 get monitor scaling factor - //grfx.ScaleTransform(resolution / grfx.DpiX, (resolution +1F) / grfx.DpiY); - grfx.ScaleTransform(sf * resolution / grfx.DpiX, sf * resolution / grfx.DpiY); // B2019-069 multiply the monitor's scaling factor - grfx.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor; - grfx.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; - grfx.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; - grfx.Clear(MSWordToPDF.DebugStatus == 1 ? System.Drawing.Color.Transparent : System.Drawing.Color.White); - //grfx.Clear(System.Drawing.Color.SlateGray); - XYPlots.XYPlot.BlackColor = MSWordToPDF.OverrideColor == Color.Red ? Color.Red : Color.Black; - XYPlots.XYPlot myPlot = new XYPlots.XYPlot(xyPlot); - myPlot.SetMargins(0, 0, 0, 0); - VG.IVGOutput vgOut = new VG.VGOut_Graphics(grfx); - vgOut.DebugStatus = MSWordToPDF.DebugStatus; - myPlot.Process(vgOut); - GC.Collect(); // memory garbage collection (Regex bug) - grfx.Dispose(); - GraphicsUnit gu = new GraphicsUnit(); - retval = mf.GetBounds(ref gu); - retval.Width *= dpi / resolution; - retval.Height *= dpi / resolution; - retval.X *= dpi / resolution; - retval.Y *= dpi / resolution; - //retval.X = myPlot.Width-retval.Width; - //AddInfo("{0},{1},{2},{3},{4},{5}", myPlot.Width, myPlot.Height, retval.Width, retval.Height,retval.X,retval.Y); - //Console.Write("{0},{1},{2},{3}", myPlot.Width, myPlot.Height, retval.Width, retval.Height); - //mf.Save(pngFile, ImageFormat.Png); - //Console.WriteLine("'pngfile','{0}'", pngFile); + MyApp.ActiveDocument.Close(false); + return true; + } + catch (Exception ex) + { + _MyLog.WarnFormat("{0} - {1}, Attempt {2}", ex.GetType().Name, ex.Message, attempts); + if (attempts >= 10) _MyLog.Error("Failed to close 10 times.", ex); + return false; } - using(Metafile mf2 = new Metafile(emfFile)) - mf2.Save(pngFile, ImageFormat.Png); - FileInfo myFile = new System.IO.FileInfo(emfFile); - myFile.Delete(); - return retval; } + + private static string CreatePDF(string fileName, bool openPdf, int DebugStatus) + { + // C2018-019 only allow one .pdf extension + if (!fileName.ToUpper().EndsWith(".PDF")) fileName += ".pdf"; + return MyApp.CreatePDF(fileName, openPdf, DebugStatus); + } + private static void InsertROValue(LBSelection sel, string roValue, bool upRoIfPrevUpper, float indent, bool convertUnderline) { if (roValue == null) { string orgtext = sel.Text; - sel.Text = string.Format("RO ({0}) Not Found",orgtext.Replace("<","").Replace(">","")); + sel.Text = string.Format("RO ({0}) Not Found", orgtext.Replace("<", string.Empty).Replace(">", string.Empty)); sel.Font.Color = LBWdColor.wdColorRed; } - else + else if (roValue != string.Empty) { if (upRoIfPrevUpper && sel.LastWasUpper) roValue = roValue.ToUpper(); - // Convert fortran formatted numbers to scientific notation. - //string tmp = DisplayRO.ConvertFortranFormatToScienctificNotation(roValue); + // Convert Fortran formatted numbers to scientific notation. string tmp = ROFSTLookup.ConvertFortranFormatToScienctificNotation(roValue); - // Only in Word sections, convert the # to superscripts and ~ to subscrtipts + + // Only in Word sections, convert the # to superscripts and ~ to subscripts tmp = Regex.Replace(tmp, "[#](.*?)[#]", "\\up2 $1\\up0 ");// DOS Superscript tmp = Regex.Replace(tmp, "[~](.*?)[~]", "\\dn2 $1\\up0 ");// DOS Subscript tmp = tmp.Replace(@"\u160?", "\xA0"); tmp = tmp.Replace(@"\U160?", "\xA0"); tmp = tmp.Replace(@"[xB3]", "\xB3"); - tmp = tmp.Replace(@"\U8209?", "-"); // fixes negative value in scienctific notation + tmp = tmp.Replace(@"\U8209?", "-"); // fixes negative value in scientific notation tmp = tmp.Replace(@"\u8209?", "-"); + // Look for superscript or subscript and insert the appropriate commands Match roMatch = Regex.Match(tmp, @"(.*?)\\(up2|dn2) (.*?)\\(up0|dn0) "); + if (roMatch.Groups.Count == 5)// Superscript or subscript found { - // B2017-177 Don't print text RO in red - //sel.Font.Color = LBWdColor.wdColorRed; + //sel.Font.Color = LBWdColor.wdColorRed; // B2017-177 Don't print text RO in red while (roMatch.Groups.Count == 5) { - sel.TypeText(roMatch.Groups[1].Value); // output the text preceeding the super or sub command + sel.TypeText(roMatch.Groups[1].Value); // output the text preceding the super or sub command sel.Font.Position = roMatch.Groups[2].Value == "up2" ? 2 : -2; // Shift the vertical position for super or sub sel.TypeText(roMatch.Groups[3].Value); // output the superscript or subscript sel.Font.Position = 0; // restore the vertical position tmp = tmp.Substring(roMatch.Length); // remove the processed text roMatch = Regex.Match(tmp, @"(.*?)\\(up2|dn2) (.*?)\\(up0|dn0) "); // check to see if the text contain another super or sub } - if (tmp != "")// Add any remaining text + + // Add any remaining text + if (!string.IsNullOrEmpty(tmp)) sel.TypeText(tmp); + sel.Font.Color = LBWdColor.wdColorAutomatic; + } else // if no superscripts or subscripts just output the text { @@ -1702,18 +1881,161 @@ namespace VEPROMS.CSLA.Library roValue = roValue.Replace(@"[xB3]", "\xB3"); roValue = roValue.Replace(@"[XB3]", "\xB3"); sel.Text = roValue; + // look for toggling of '_' to turn underlining on/off: - AddPrecedingText(sel, roValue, indent,convertUnderline); // parse underlining - // B2017-177 Don't print text RO in red - //sel.Font.Color = LBWdColor.wdColorRed; + AddPrecedingText(sel, roValue, indent, convertUnderline); // parse underlining } } } + + private static byte[] GetBytes(string filename) + { + // Reads the Word file containing the resolved ROs used when adding to DocReplace + FileInfo fi = new FileInfo(filename); + + FileStream fs = fi.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + byte[] buf = new byte[fi.Length]; + fs.Read(buf, 0, buf.Length); + fs.Close(); + + return buf; + } + + private static string GetFileName(ItemInfo sect) + { + return VlnSettings.TemporaryFolder + @"\Doc_" + sect.MyContent.MyEntry.DocID.ToString() + ".Pdf"; + } + + private static float ScalingFactor() + { + // B2019-069 needed to get the monitor's scaling factor - used in generating RO X/Y plot + IntPtr desktop = GetDC(IntPtr.Zero); + + int LogicalScreenHeight = GetDeviceCaps(desktop, (int)DeviceCap.VERTRES); + int PhysicalScreenHeight = GetDeviceCaps(desktop, (int)DeviceCap.DESKTOPVERTRES); + ReleaseDC(IntPtr.Zero, desktop); + + return (float)PhysicalScreenHeight / (float)LogicalScreenHeight; // a value of 1.50 represents monitor scaling set to 150% + } + + private static PointF GetLocation(LBSelection sel, bool adjustMargins) + { + LBRange rng0 = MyApp.ActiveDocument.Range(0, 0); + LBRange rng1 = MyApp.ActiveDocument.Range(sel.Start, sel.Start); + + float fx0 = adjustMargins ? (float)rng0.get_Information(LBWdInformation.wdHorizontalPositionRelativeToPage) : 0; + + for (int ix = sel.Start; ix > 0; ix--) // Find left most location - this was added since the first line may be centered or right justified + { + LBRange rngx = MyApp.ActiveDocument.Range(ix, ix); + float fxx = adjustMargins ? (float)rngx.get_Information(LBWdInformation.wdHorizontalPositionRelativeToPage) : 0; + if (fxx < fx0) fx0 = fxx; else break; + } + + float fy0 = adjustMargins ? (float)rng0.get_Information(LBWdInformation.wdVerticalPositionRelativeToPage) : 0; + float fx1 = (float)rng1.get_Information(LBWdInformation.wdHorizontalPositionRelativeToPage); + float fy1 = (float)rng1.get_Information(LBWdInformation.wdVerticalPositionRelativeToPage); + + return new PointF(fx1 - fx0, fy1 - fy0); + } + + private static string FindEmbeddedText(string p, ref string resXyPlot) + { + StringBuilder sb = new StringBuilder(); // contains embedded text + StringBuilder xy = new StringBuilder(); // contains xyplot without embedded text. + string origXy = p; + bool findEmbeddedText = false; + + // get past opening command: + int indxCmd = p.IndexOf("<"); + indxCmd = p.IndexOf("<", indxCmd + 1); + xy.Append(p.Substring(0, indxCmd)); + + // While there are xyplot commands, check for beginning/ending. Any text not in a command, save. + while (indxCmd > 0) + { + // find end of command. Look for another beginning of command, newline, + // regular text, or end of graph and handle each of these cases. + int indxClose = GetNonStringCmdClose(p, indxCmd + 1); // p.IndexOf(">", indxCmd + 1); + int nxtIndxCmd = p.IndexOf("<", indxCmd + 1); + xy.Append(p.Substring(indxCmd, indxClose - indxCmd + 1)); + xy.Append("\r"); // the xyplot code assumes a return exists. + + // get substrings between end index & start of next and if any + // non white space text, add it to return string and flag that we have + // embedded text. If there's a newline and just other white space put a + // newline in return string. + if (nxtIndxCmd > 0) + { + string mydebug = p.Substring(indxClose + 1); + + for (int i = indxClose + 1; i < nxtIndxCmd; i++) + { + if (!System.Char.IsWhiteSpace(p[i])) + { + sb.Append(p[i]); + findEmbeddedText = true; + } + + if (p[i] == '\r' || p[i] == ' ') sb.Append(p[i]); + } + } + + indxCmd = nxtIndxCmd; + } + + xy.Append(">"); + + if (findEmbeddedText) + { + resXyPlot = xy.ToString(); + return sb.ToString(); + } + + resXyPlot = origXy; + return null; + } + + private static int GetNonStringCmdClose(string p, int indxCmd) + { + int indxClose = p.IndexOf(">", indxCmd); + + if (indxClose >= 0) + { + // if there are any quotes between the open of command and close, + // need to see if the close command is quoted. + if (p.IndexOf('"', indxCmd, indxClose - indxCmd) > -1) + { + // see how many quotes between open/close command, if + // an odd number, the close command char '>' is in quotes. + int countQuotes = 0; + for (int i = indxCmd; i < indxClose; i++) if (p[i] == '"') countQuotes++; + + if ((countQuotes % 2) != 0) + { + // find quote after close, and then get next close. + int closeQuote = p.IndexOf('"', indxClose); + if (closeQuote < 0) return -1; // this is error, so return end not found. + return p.IndexOf(">", closeQuote + 1); + } + } + } + + return indxClose; + } + + private static int WordColor(System.Drawing.Color color) + { + System.Drawing.Color c1 = System.Drawing.Color.FromArgb(0, color.B, color.G, color.R); + return c1.ToArgb(); + } + private static LBSelection FindXyPlot() { LBSelection sel = MyApp.Selection; LBFind find = sel.Find; find.ClearFormatting(); + // Search string format - this is MSWord wildcard format // If you do a search in MSWord, make sure wildcard box is checked and then press the // Special button to see the definitions of the various wildcards @@ -1730,21 +2052,24 @@ namespace VEPROMS.CSLA.Library find.MatchWildcards = true; find.MatchSoundsLike = false; find.MatchAllWordForms = false; + if (find.Execute()) return sel; + return null; } - // B2019-123 Verify that the RO token is the correct format - private static Regex _ROAccPageTokenPattern = new Regex("[<][^<>-]+-[^<>]+[>]"); + private static LBSelection FindRO() { int firstStart = 0; bool executeResult = false; LBSelection sel = null; + while (!executeResult) { sel = MyApp.Selection; LBFind find = sel.Find; find.ClearFormatting(); + // Search string format - this is MSWord wildcard format // If you do a search in MSWord, make sure wildcard box is checked and then press the // Special button to see the definitions of the various wildcards @@ -1761,6 +2086,7 @@ namespace VEPROMS.CSLA.Library find.MatchWildcards = true; find.MatchSoundsLike = false; find.MatchAllWordForms = false; + // B2022-053 in a Barakah word attachment (ST procedure set procedure DG-5204) the RO tokens are not resolved after a certain // point in a table. // Turns out this happens when a table cell had text that begins with a "<" and it does not end with a ">" and there is no @@ -1768,6 +2094,7 @@ namespace VEPROMS.CSLA.Library // was "<90" cause the Word Find command to return an entire table row which cause PROMS to stop processing // the rest of the Word attachment section. bool tryagain = false; + do { tryagain = false; @@ -1776,18 +2103,21 @@ namespace VEPROMS.CSLA.Library // move past that text and try the Word Find function again. if (executeResult && !sel.Text.StartsWith("<") && !sel.Text.EndsWith(">")) { - sel.MoveStart(LBWdUnits.wdCharacter, sel.Text.Length-1); + sel.MoveStart(LBWdUnits.wdCharacter, sel.Text.Length - 1); tryagain = true; } } while (tryagain); + if (!executeResult) return null; + // B2019-123 Word 2019 returns true when find string was not found // This line checks to make sure an RO was found. // B2019-138 Word section fails during RO Replacement // Calvert Cliffs/Working Draft Procedures/OI Procedures - Unit 1 - OI-43C.SATTACHMENT 1 if (sel.End != 0 && !_ROAccPageTokenPattern.IsMatch(sel.Text)) return null; + // MS Word found 'invalid' ro when text had "[335.0 {0}\r\n" + " [{1}] {2}\r\n" + " in {3}\r\n" + " Document: {4}\r\n" + " ACTION REQUIRED: Should use Word Margins", + msg, sect.ItemID, sect.ShortPath, sect.SearchDVPath.Replace("\a", "/"), sect.MyContent.MyEntry.MyDocument.LibTitle ?? sect.MyContent.MyEntry.DocID.ToString()); } + + private static void AddErrorLogInfoMarginNotFixed(LBDocumentClass myDoc, string msg) + { + // B2018-089 - Made error log output more useful + _MyLog.WarnFormat("\r\n==> {0}\r\n" + " Document: {1}\r\n" + " ACTION REQUIRED: Should use Word Margins", msg, myDoc.FullName); + } + + #endregion + + #region Kernel Level Methods + + [DllImport("User32.dll")] + static extern IntPtr GetDC(IntPtr hwnd); + + [DllImport("User32.dll")] + static extern int ReleaseDC(IntPtr hwnd, IntPtr dc); + + [DllImport("gdi32.dll")] + static extern int GetDeviceCaps(IntPtr hdc, int nIndex); + + #endregion + + #region Private Class + + private class CloseWordApp : System.Windows.Forms.Timer + { + // B2019-161 When tracking timing time this action + private static VolianTimer _TimeActivity = new VolianTimer("DocumentExt.cs CloseWordApp_Tick", 1548); + + LBApplicationClass _MyApp; + + + public LBApplicationClass MyApp + { + get { return _MyApp; } + set { _MyApp = value; } + } + + + public CloseWordApp(LBApplicationClass myApp, int interval) + { + MyApp = myApp; + Interval = interval; + Tick += new EventHandler(CloseWordApp_Tick); + Enabled = true; + } + + private void CloseWordApp_Tick(object sender, EventArgs e) + { + _TimeActivity.Open(); + Enabled = false; + + try // B2018-071 Keep code from crashing on close of MS Word + { + MyApp.Quit(false); + } + catch (Exception ex) + { + _MyLog.WarnFormat("MyApp Quit {0} {1}", ex.GetType().FullName, ex.Message); + } + + Dispose(); + _TimeActivity.Close(); + } + } + + #endregion } } diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/ItemExt.cs b/PROMS/VEPROMS.CSLA.Library/Extension/ItemExt.cs index e4bd4ab6..1d8c9384 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/ItemExt.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/ItemExt.cs @@ -1232,6 +1232,10 @@ namespace VEPROMS.CSLA.Library return (MyPrevious == null); } } + + + + public bool IsAutoTOCSection { get @@ -2615,6 +2619,7 @@ namespace VEPROMS.CSLA.Library } } } + RefreshFields(enhii); // B2021-042: Crash on link/unlink/link - refresh cache } catch (Exception ex) @@ -2672,6 +2677,7 @@ namespace VEPROMS.CSLA.Library return dtext; } } + internal int _SearchAnnotationID; public int SearchAnnotationID { diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/PdfExt.cs b/PROMS/VEPROMS.CSLA.Library/Extension/PdfExt.cs index 99ca0a52..7a971ec4 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/PdfExt.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/PdfExt.cs @@ -6,6 +6,7 @@ using System.Data.SqlClient; using Csla; using Csla.Data; using Csla.Validation; +using System.Diagnostics; namespace VEPROMS.CSLA.Library { @@ -117,12 +118,15 @@ namespace VEPROMS.CSLA.Library public static PdfInfo Get(ItemInfo sect, bool ovrride) { int count = 0; + while (count < 2) { DocStyle myDocStyle = sect.ActiveSection.MyDocStyle; SectionConfig sc = sect.ActiveSection.MyConfig as SectionConfig; PdfInfo myPdf = null; + int ss = sect.MyDocVersion.DocVersionConfig.SelectedSlave; + if (sc != null && sc.Section_WordMargin == "Y") { myPdf = Get(sect.MyContent.MyEntry.DocID, ss*10 + MSWordToPDF.DebugStatus, 0, 0, 0, 0); @@ -132,15 +136,19 @@ namespace VEPROMS.CSLA.Library myPdf = Get(sect.MyContent.MyEntry.DocID, ss*10 + MSWordToPDF.DebugStatus, (int)myDocStyle.Layout.TopMargin, (int)myDocStyle.Layout.PageLength, (int)myDocStyle.Layout.LeftMargin, (int)myDocStyle.Layout.PageWidth); } - // ovrride forces the the printing of the word seciton, which creates a word file with resolved ROs, which is saved for an approved export - if (!ovrride || (ovrride && count ==1)) + + // override forces the printing of the word section, which creates a word file with resolved ROs, which is saved for an approved export + if (!ovrride || (ovrride && count == 1)) { if (myPdf != null) return myPdf; if (count > 0) return null; // Could not find or create a pdf } + MSWordToPDF.SetDocPdf(sect.MyContent.MyEntry.MyDocument, sect); + count++; } + return null; } } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/PdfInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/PdfInfo.cs index 68b388c4..81a795e2 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/PdfInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/PdfInfo.cs @@ -321,7 +321,7 @@ namespace VEPROMS.CSLA.Library if (tmp == null) { tmp = DataPortal.Fetch(new PKCriteria(docID, debugStatus, topRow, pageLength, leftMargin, pageWidth)); - AddToCache(tmp); + if (tmp.DocID > 0) AddToCache(tmp); } if (tmp.ErrorMessage == "No Record Found") { diff --git a/PROMS/Volian.Base.Library/TmpFile.cs b/PROMS/Volian.Base.Library/TmpFile.cs index 7e842d79..821d75ce 100644 --- a/PROMS/Volian.Base.Library/TmpFile.cs +++ b/PROMS/Volian.Base.Library/TmpFile.cs @@ -65,7 +65,7 @@ namespace Volian.Base.Library { try { - // delete any docs. If it fails, just go on to the next one becase + // delete any docs. If it fails, just go on to the next one because // it may be open from another process. if(fi.LastWriteTimeUtc < DateTime.Now.AddDays(-2.0)) fi.Delete(); @@ -86,7 +86,7 @@ namespace Volian.Base.Library { try { - // delete any docs. If it fails, just go on to the next one becase + // delete any docs. If it fails, just go on to the next one because // it may be open from another process. fi.Delete(); } diff --git a/PROMS/Volian.Controls.Library/DisplayRO.cs b/PROMS/Volian.Controls.Library/DisplayRO.cs index 4a28b064..2a4ee017 100644 --- a/PROMS/Volian.Controls.Library/DisplayRO.cs +++ b/PROMS/Volian.Controls.Library/DisplayRO.cs @@ -81,7 +81,7 @@ namespace Volian.Controls.Library public bool RoTreeNeedsReloaded { - get { return (MyROFST != null && _currRofstID != null && MyROFST.ROFstID != (int)_currRofstID) || (MyDvi != null && _currDocVersionID != null && MyDvi.VersionID != (int)_currDocVersionID) ; } + get { return (MyROFST != null && _currRofstID != null && MyROFST.ROFstID != (int)_currRofstID) || (MyDvi != null && _currDocVersionID != null && MyDvi.VersionID != (int)_currDocVersionID); } } public ROFstInfo MyROFST @@ -110,7 +110,7 @@ namespace Volian.Controls.Library if (!_isInitializedRofstID && IsRofstValid) { - _currRofstID = (IsRofstValid) ? (int?)_myROFST.RODbID : null; + _currRofstID = (IsRofstValid) ? (int?)_myROFST.ROFstID : null; } } } @@ -142,15 +142,7 @@ namespace Volian.Controls.Library public E_ROValueType ROTypeFilter { get { return _roTypeFilter; } - set - { - _roTypeFilter = value; - - //if (!Visible) return; // don't reset anything if the form is invisible. - //_roTypeFilter = value; - - // LoadTree(); - } + set {_roTypeFilter = value; } } public RoUsageInfo CurROLink @@ -188,13 +180,6 @@ namespace Volian.Controls.Library get { return _myRTB; } set { - //if (_myRTB != null) - //{ - // MyRTB.LinkChanged -= new StepRTBLinkEvent(MyRTB_LinkChanged); - // MyRTB.SelectionChanged -= new EventHandler(MyRTB_SelectionChanged); - //} - - if (value == null) { _myRTB = value; @@ -318,11 +303,6 @@ namespace Volian.Controls.Library _searchTimer.Stop(); _searchTimer.Start(); - //if (!string.IsNullOrEmpty(MyRTB.SelectedText)) - //{ - // _searchTimer.Start(); - //} - _timeActivity.Close(); } @@ -373,25 +353,24 @@ namespace Volian.Controls.Library if (chld.value != null) { RoUsageInfo SavROLink = null; + if (_savCurROLink != null) SavROLink = _savCurROLink; lbROId.Text = chld.appid; // Allow the user to select a different return value. - string childroid = string.Format("{0}{1}", chld.roid.ToLower(), "0000").Substring(0, 16); + string childroid = ROFSTLookup.FormatRoidKey(chld.roid, true); //B2017-245 Disable SaveRO button for Procedures and Sections //B2020-049: Save button not enabled on Word docs, only if a procedure was opened first and immediately after the word document // section is opened (added 'IsInWorDoc') - btnSaveRO.Enabled = (IsInWordDoc || (!IsNotStep && !IsEnhancedStep)) && UserInfo.CanEdit(MyUserInfo, MyDvi) && ((_savCurROLink == null) || !(childroid.Equals(SavROLink.ROID.ToLower()))); //added security check (UserInfo.CanEdit) - btnCancelRO.Enabled = (_savCurROLink != null && childroid != SavROLink.ROID.ToLower()); + btnSaveRO.Enabled = (IsInWordDoc || (!IsNotStep && !IsEnhancedStep)) && UserInfo.CanEdit(MyUserInfo, MyDvi) && ((SavROLink == null) || !(childroid.Equals(SavROLink.ROID.ToUpper()))); //added security check (UserInfo.CanEdit) + btnCancelRO.Enabled = (_savCurROLink != null && (SavROLink != null && childroid != SavROLink.ROID.ToUpper())); btnGoToRO.Enabled = UserInfo.CanEditROs(MyUserInfo, MyDvi); // Writers and Reviewers cannot edit ROs (run the RO Editor) switch (chld.type) { case 1: // standard (regular) text RO type - string roval = chld.value.Replace(@"\u160?", " "); - roval = GetPCDefaultValue(roval); // C2021-026 get the default RO value from P/C RO value information - tbROValue.Text = roval; + tbROValue.Text = chld.value; btnPreviewRO.Enabled = false; if (chld.roid.StartsWith("FFFF")) btnGoToRO.Enabled = false; break; @@ -530,7 +509,7 @@ namespace Volian.Controls.Library ROFSTLookup.rochild roch = (ROFSTLookup.rochild)obj; _selectedRoidBeforeRoEditor = roch.roid; - string args = "\"" + MyROFST.MyRODb.FolderPath + "\" " + roch.roid.ToLower(); + string args = "\"" + MyROFST.MyRODb.FolderPath + "\" " + roch.roid.Substring(0,12).ToLower(); // C2017-003: ro data in sql server, check for sql connection string if (MyROFST.MyRODb.DBConnectionString != "cstring") args = args + " \"" + MyROFST.MyRODb.DBConnectionString + "\""; @@ -574,8 +553,6 @@ namespace Volian.Controls.Library { if (MyROFST == null) { - //_curROFST = null; - //_curROFSTLookup = null; tvROFST.Nodes.Clear(); lbFound.Visible = false; return; @@ -599,6 +576,7 @@ namespace Volian.Controls.Library _currRofstID = (int?)MyROFST.ROFstID; _currDocVersionID = null; + if(_docVersionInfo != null) _currDocVersionID = (int?)_docVersionInfo.VersionID; } @@ -610,30 +588,39 @@ namespace Volian.Controls.Library if (unitInfoNode == null) { TreeNode tnn = tvROFST.Nodes.Add("Unit Information"); + TreeNode cn = null; + + ROFSTLookup.rochild roc = MyROFSTLookup.GetRoChild("FFFF00000001"); + cn = tnn.Nodes.Add(roc.title); + cn.Tag = roc; - TreeNode cn = tnn.Nodes.Add("Number"); - cn.Tag = MyROFSTLookup.GetRoChild("FFFF00000001"); + roc = MyROFSTLookup.GetRoChild("FFFF00000002"); + cn = tnn.Nodes.Add(roc.title); + cn.Tag = roc; - cn = tnn.Nodes.Add("Other Number"); - cn.Tag = MyROFSTLookup.GetRoChild("FFFF00000002"); + roc = MyROFSTLookup.GetRoChild("FFFF00000003"); + cn = tnn.Nodes.Add(roc.title); + cn.Tag = roc; - cn = tnn.Nodes.Add("Text"); - cn.Tag = MyROFSTLookup.GetRoChild("FFFF00000003"); + roc = MyROFSTLookup.GetRoChild("FFFF00000004"); + cn = tnn.Nodes.Add(roc.title); + cn.Tag = roc; - cn = tnn.Nodes.Add("Other Text"); - cn.Tag = MyROFSTLookup.GetRoChild("FFFF00000004"); + roc = MyROFSTLookup.GetRoChild("FFFF00000005"); + cn = tnn.Nodes.Add(roc.title); + cn.Tag = roc; - cn = tnn.Nodes.Add("ID"); - cn.Tag = MyROFSTLookup.GetRoChild("FFFF00000005"); + roc = MyROFSTLookup.GetRoChild("FFFF00000006"); + cn = tnn.Nodes.Add(roc.title); + cn.Tag = roc; - cn = tnn.Nodes.Add("Other ID"); - cn.Tag = MyROFSTLookup.GetRoChild("FFFF00000006"); + roc = MyROFSTLookup.GetRoChild("FFFF00000007"); + cn = tnn.Nodes.Add(roc.title); + cn.Tag = roc; - cn = tnn.Nodes.Add("Name"); - cn.Tag = MyROFSTLookup.GetRoChild("FFFF00000007"); - - cn = tnn.Nodes.Add("Other Name"); - cn.Tag = MyROFSTLookup.GetRoChild("FFFF00000008"); + roc = MyROFSTLookup.GetRoChild("FFFF00000008"); + cn = tnn.Nodes.Add(roc.title); + cn.Tag = roc; } } else if (unitInfoNode != null) // Add Unit Information Database if it doesn't exist [Not Multi-Unit DocVersion] @@ -644,61 +631,6 @@ namespace Volian.Controls.Library _curROTypeFilter = _roTypeFilter; - //if (MyROFST != _curROFST || MyROFSTLookup != _curROFSTLookup || tvROFST.Nodes == null || tvROFST.Nodes.Count <= 0) - //{ - // ROFSTLookup.rodbi[] dbs = MyROFSTLookup.GetRODatabaseList(true); - - // for (int i = 0; i < dbs.Length; i++) - // { - // ROFSTLookup.rodbi db = dbs[i]; - - // TreeNode tn = new TreeNode(db.dbiTitle); - // tn.Tag = db; - // tvROFST.Nodes.Add(tn); - - // AddDummyGroup(db, tn); - // } - //} - - //var unitInfoNode = tvROFST.Nodes.Cast().Where(x => x.Text == "Unit Information").FirstOrDefault(); - - //if ((ROTypeFilter == E_ROValueType.Text || ROTypeFilter == E_ROValueType.All) && this.MyDvi != null && this.MyDvi.MultiUnitCount > 1) - //{ - // // Add Unit Information Database if it doesn't exist - // if (unitInfoNode == null) - // { - // TreeNode tnn = tvROFST.Nodes.Add("Unit Information"); - - // TreeNode cn = tnn.Nodes.Add("Number"); - // cn.Tag = MyROFSTLookup.GetRoChild("FFFF00000001"); - - // cn = tnn.Nodes.Add("Other Number"); - // cn.Tag = MyROFSTLookup.GetRoChild("FFFF00000002"); - - // cn = tnn.Nodes.Add("Text"); - // cn.Tag = MyROFSTLookup.GetRoChild("FFFF00000003"); - - // cn = tnn.Nodes.Add("Other Text"); - // cn.Tag = MyROFSTLookup.GetRoChild("FFFF00000004"); - - // cn = tnn.Nodes.Add("ID"); - // cn.Tag = MyROFSTLookup.GetRoChild("FFFF00000005"); - - // cn = tnn.Nodes.Add("Other ID"); - // cn.Tag = MyROFSTLookup.GetRoChild("FFFF00000006"); - - // cn = tnn.Nodes.Add("Name"); - // cn.Tag = MyROFSTLookup.GetRoChild("FFFF00000007"); - - // cn = tnn.Nodes.Add("Other Name"); - // cn.Tag = MyROFSTLookup.GetRoChild("FFFF00000008"); - // } - //} - //else if (unitInfoNode != null) // Add Unit Information Database if it doesn't exist [Not Multi-Unit DocVersion] - //{ - // tvROFST.Nodes.Remove(unitInfoNode); - //} - //_curROFST = _myROFST; //_curROFSTLookup = _myROFSTLookup; //_curROTypeFilter = _roTypeFilter; @@ -732,7 +664,7 @@ namespace Volian.Controls.Library #endregion - #region Private Methods? + #region Private Methods private void LoadChildren(TreeNode tn) { @@ -760,15 +692,11 @@ namespace Volian.Controls.Library // if children, add dummy node if (children != null && children.Length > 0) { - //ProgressBar_Initialize(children.Length, tn.Text); - for (int i = 0; i < children.Length; i++) { - //ProgressBar_SetValue(i); - TreeNode tmp = null; ROFSTLookup.rochild roc = children[i]; - + // if this is a group, i.e. type 0, add a dummy node if (roc.type == 0 && !MyROFSTLookup.HasChildren(ref roc)) { @@ -778,10 +706,20 @@ namespace Volian.Controls.Library { continue; // Ignore: Filter Doesn't Match } - else if (roc.value == null) + else if (!string.IsNullOrEmpty(roc.appid)) { MyROFSTLookup.LoadChildren(ref roc); + if (roc.children.Length == 1 && roc.children.First().roid.Length == 16) + { + roc.appid = roc.children.First().appid; + roc.roid = roc.children.First().roid; + roc.value = roc.children.First().value; + } + } + + if (roc.value == null) + { tmp = new TreeNode(roc.title); tmp.Tag = roc; @@ -793,9 +731,7 @@ namespace Volian.Controls.Library } else { - string ntitle = roc.title.Replace(@"\u160?", " "); - ntitle = GetPCDefaultValue(ntitle); // C2021-026 get the default RO value from P/C RO value information - tmp = new TreeNode(ntitle); + tmp = new TreeNode(roc.title); tmp.Tag = roc; if (roc.roid.Length == 16) @@ -810,8 +746,6 @@ namespace Volian.Controls.Library } } } - - //ProgressBar_Clear(); } private void AddDummyGroup(ROFSTLookup.rodbi rodbi, TreeNode tn) @@ -825,17 +759,20 @@ namespace Volian.Controls.Library private void ExpandNode(string roid) { + // Clean-up Roid if necessary + roid = ROFSTLookup.FormatRoidKey(roid); + + bool multValSel = (roid.Length == 16) ? true : false; string db = roid.Substring(0, 4); int dbiID = MyROFSTLookup.GetRODatabaseTitleIndex(roid); - bool multValSel = (roid.Length == 16) ? true : false; - + ROFSTLookup.rochild rochld = MyROFSTLookup.GetRoChild(roid.Substring(0, 12).ToUpper()); // use this to walk up tree until database - this is used to expand tree. List path = new List(); int myid = rochld.ID; - while (myid > 0) + while (myid >= 0) { path.Insert(0, myid); myid = rochld.ParentID; @@ -849,7 +786,13 @@ namespace Volian.Controls.Library //Find Database Node First - TreeNode dbNode = tvROFST.Nodes.Cast().Where(x => (x.Tag is ROFSTLookup.rodbi) && ((ROFSTLookup.rodbi)x.Tag).dbiID == dbiID).FirstOrDefault(); + TreeNode dbNode = null; + + if (roid.StartsWith("FFFF")) + dbNode = tvROFST.Nodes.Cast().Where(x => (x.Tag.Equals(null)) && (x.Text.Equals("Unit Information"))).FirstOrDefault(); + else + dbNode = tvROFST.Nodes.Cast().Where(x => (x.Tag is ROFSTLookup.rodbi) && ((ROFSTLookup.rodbi)x.Tag).dbiID == dbiID).FirstOrDefault(); + if (dbNode != null) { LoadChildren(dbNode); @@ -891,30 +834,6 @@ namespace Volian.Controls.Library tvROFST.SelectedNode = tnExpand; } - private string GetPCDefaultValue(string roval) - { - // C2021-026 Get the Parent (Default) RO value if the return value include P/C information - // otherwise return the RO value as is. - // This is used for the insert RO interface on the Step Properties panel - string rntval = roval; - - while (rntval.Contains("", startCVIdx); - string aplicValues = rntval.Substring(startCVIdx, EndCVidx + 6 - startCVIdx); - int endDefIdx = rntval.IndexOf(",", startCVIdx); - - // C2022-001 - handle if there is no child value in the RO FSt - // B2022-051 - was sometimes leaving "/APL>" when processing return value made up from multiple RO (editor) fields - // added check to make where next found comma was within the current - string defValue = rntval.Substring(startCVIdx + 16, ((endDefIdx > 0 && endDefIdx < EndCVidx) ? endDefIdx : EndCVidx) - (startCVIdx + 16)); - rntval = rntval.Replace(aplicValues, defValue); - } - - return rntval; - } - private int FindIndex(TreeNodeCollection nodes, string value) { int index = 0; @@ -947,47 +866,22 @@ namespace Volian.Controls.Library if (dti.MyDSOTabPanel != null) // A Word Document tab is the active tab { - string AccPageID = string.Empty; - - if (roc.roid.StartsWith("FFFF")) - { - AccPageID = "<" + roc.appid + ">"; - } - else - { - int dbiID = MyROFSTLookup.GetRODatabaseTitleIndex(roc.roid); - ROFSTLookup.rodbi db = MyROFSTLookup.GetRODatabase(roc.roid, true, false); - - if (db.dbiID == dbiID) - { - string accPrefix = db.dbiAP.Replace(MyDvi.DocVersionConfig.RODefaults_graphicsprefix, "IG"); - accPrefix = accPrefix.Replace(MyDvi.DocVersionConfig.RODefaults_setpointprefix, "SP"); - - string suffix = (roc.roid.Length == 12 || roc.roid.Substring(12, 4) == "0041") ? string.Empty : "." + ((char)Convert.ToInt32(roc.roid.Substring(12, 4), 16)).ToString(); - AccPageID = string.Format("<{0}-{1}{2}>", accPrefix, roc.appid, suffix);// makes for example - } - else - { - FlexibleMessageBox.Show("Error occurred finding RO. Contact Volian"); - return; - } - } + string accPageID = string.Format("<{0}>", roc.appid); // Insert the RO text at the current cursor position in the word document // NOTE: assuming any type of RO can be put in an Accessory (MSWord) Document if (dti.MyDSOTabPanel != null) { - dti.MyDSOTabPanel.InsertText(AccPageID); + dti.MyDSOTabPanel.InsertText(accPageID); } - } else if (MyRTB != null) // a Procedure Steps section tab is active { if (CheckROSelection(roc)) // check for RO type is valid for this type of step/substep { - // the roid may be 12 or 16 chars long, with the last 4 set if there is unit specific - // menuing. Pad to 12 to store in the rousage table. - string padroid = (roc.roid.Length <= 12) ? roc.roid + "0000" : roc.roid; + // the roid may be 12 or 16 chars long, with the last 4 set if there is unit specific value + // Pad to 16 to store in the RoUsage table. + string padroid = ROFSTLookup.FormatRoidKey(roc.roid, true); string linktxt = string.Format(@"#Link:ReferencedObject: {0} {1}", padroid, MyROFST.RODbID); // Resolve symbols and scientific notation in the RO return value @@ -1133,7 +1027,7 @@ namespace Volian.Controls.Library { if (MyROFST != null && searchValue.Length >= 2) { - dicRoVals = MyROFSTLookup.Search(searchValue, searchTypeID, MaxNumSearchRecords); + dicRoVals = MyROFSTLookup.Search(searchValue, searchTypeID, false, MaxNumSearchRecords); } if (dicRoVals != null && dicRoVals.Count > 0) diff --git a/PROMS/Volian.Controls.Library/StepRTB.cs b/PROMS/Volian.Controls.Library/StepRTB.cs index 41d1591e..0cbf310a 100644 --- a/PROMS/Volian.Controls.Library/StepRTB.cs +++ b/PROMS/Volian.Controls.Library/StepRTB.cs @@ -715,13 +715,16 @@ namespace Volian.Controls.Library get { return _MyLinkText; } set { - //if (value != _MyLinkText) - //{ - // updates to the info panel were not always occurring when the previous two - // lines were active + if (value != _MyLinkText) + { + //updates to the info panel were not always occurring when the previous two lines were active _MyLinkText = value; OnLinkChanged(this, new StepPanelLinkEventArgs(_MyLinkText)); - //} + } + else + { + _MyLinkText = value; + } } } #endregion @@ -1768,11 +1771,20 @@ namespace Volian.Controls.Library DebugPrint("RS------ SelectionChange > {0}", FindRangeStatus()); if (SelectionLength > 0 && IsSelectionLinked(SelectionStart, SelectionLength)) { - if (SelectedText.IndexOf(@"[END>") > 0) MyLinkText = SelectedText.Substring(0, SelectedText.IndexOf(@"[END>")); - else MyLinkText = SelectedText; + if (SelectedText.IndexOf(@"[END>") > 0) + { + MyLinkText = SelectedText.Substring(0, SelectedText.IndexOf(@"[END>")); + } + else + { + MyLinkText = SelectedText; + } } else + { MyLinkText = null; + } + OnRTBSelectionChanged(this, new EventArgs()); _LastWasLeftArrow = false; } diff --git a/PROMS/Volian.Controls.Library/StepTabRibbon.cs b/PROMS/Volian.Controls.Library/StepTabRibbon.cs index c006532a..794574b1 100644 --- a/PROMS/Volian.Controls.Library/StepTabRibbon.cs +++ b/PROMS/Volian.Controls.Library/StepTabRibbon.cs @@ -423,7 +423,8 @@ namespace Volian.Controls.Library //} #endregion string accPageID = GetAccPageID(data); - ROFSTLookup.rochild? roc = MyLookup.GetRoChildByAccPagID(accPageID, Mydvi.DocVersionConfig.RODefaults_setpointprefix, Mydvi.DocVersionConfig.RODefaults_graphicsprefix); + ROFSTLookup.rochild? roc = MyLookup.GetROChildByAccPageID(accPageID, Mydvi.DocVersionConfig.RODefaults_setpointprefix, Mydvi.DocVersionConfig.RODefaults_graphicsprefix); + if (roc != null) { int index = GetROValueIndex(data); @@ -449,7 +450,7 @@ namespace Volian.Controls.Library for (int i = 1; i < 4; i++) { tmpAccPageID = accPageID + suffix + i.ToString(); - roc = MyLookup.GetRoChildByAccPagID(tmpAccPageID, Mydvi.DocVersionConfig.RODefaults_setpointprefix, Mydvi.DocVersionConfig.RODefaults_graphicsprefix); + roc = MyLookup.GetROChildByAccPageID(tmpAccPageID, Mydvi.DocVersionConfig.RODefaults_setpointprefix, Mydvi.DocVersionConfig.RODefaults_graphicsprefix); if (roc != null) { int index = GetROValueIndex(data); @@ -460,12 +461,13 @@ namespace Volian.Controls.Library } } } + //try LO1,2,3 suffix = "-LO"; for (int i = 1; i < 4; i++) { tmpAccPageID = accPageID + suffix + i.ToString(); - roc = MyLookup.GetRoChildByAccPagID(tmpAccPageID, Mydvi.DocVersionConfig.RODefaults_setpointprefix, Mydvi.DocVersionConfig.RODefaults_graphicsprefix); + roc = MyLookup.GetROChildByAccPageID(tmpAccPageID, Mydvi.DocVersionConfig.RODefaults_setpointprefix, Mydvi.DocVersionConfig.RODefaults_graphicsprefix); if (roc != null) { int index = GetROValueIndex(data); @@ -481,6 +483,7 @@ namespace Volian.Controls.Library } return rv; } + private string GetAccPageID(string txt) { // @@ -491,11 +494,14 @@ namespace Volian.Controls.Library txt = txt.Replace(" 0) @@ -522,7 +528,7 @@ namespace Volian.Controls.Library else rv = -1; } - if (data.StartsWith(" 0) @@ -534,8 +540,10 @@ namespace Volian.Controls.Library else rv = -1; } + return rv; } + private void SaveRO_Click(object sender, EventArgs e) { DevComponents.DotNetBar.BaseItem btn = sender as DevComponents.DotNetBar.BaseItem; @@ -1252,10 +1260,12 @@ namespace Volian.Controls.Library _MyLog.WarnFormat("Equation Editor executable could not be found."); return retval; } + private static string GetVisio() // Added support for Visio { string retval = _SpecifiedVisioPath; // use the Visio path specified by the user - if (retval != null && retval != "") + + if (!string.IsNullOrEmpty(retval)) { if (!retval.ToUpper().EndsWith(".EXE")) retval += (retval.EndsWith("\\")) ? "visio.exe" : "\\visio.exe"; @@ -1265,7 +1275,8 @@ namespace Volian.Controls.Library retval = null; // look in the registry } } - if (retval == null || retval == "") + + if (!string.IsNullOrEmpty(retval)) { try { @@ -1279,7 +1290,8 @@ namespace Volian.Controls.Library _MyLog.WarnFormat("Visio was not found in the registry."); } } - return retval; + + return retval; } private static string _EqnEdtPath = null; public static string EqnEdtPath diff --git a/PROMS/Volian.Print.Library/PDFReport.cs b/PROMS/Volian.Print.Library/PDFReport.cs index d1c29a04..81e42447 100644 --- a/PROMS/Volian.Print.Library/PDFReport.cs +++ b/PROMS/Volian.Print.Library/PDFReport.cs @@ -14,7 +14,7 @@ namespace Volian.Print.Library public class PDFReport { #region Enums - + public enum ReportType { SearchResults = 0, @@ -28,7 +28,7 @@ namespace Volian.Print.Library #endregion #region Fields - + private PdfWriter _MyPdfWriter; private ICollection _ResultList; @@ -57,31 +57,31 @@ namespace Volian.Print.Library #endregion #region Properties - + public ICollection ResultList { get { return _ResultList; } set { _ResultList = value; } } - + public string FileName { get { return _FileName; } set { _FileName = value; } } - + public string ReportTitle { get { return _ReportTitle; } set { _ReportTitle = value; } } - + public string TypesSelected { get { return _TypesSelected; } set { _TypesSelected = value; } } - + public bool ShowAnnotations { get { return _ShowAnnotations; } @@ -249,7 +249,7 @@ namespace Volian.Print.Library #endregion #region Public Methods - + public void AddMainRODatabaseTitle(PdfPTable datatable, int dbTitleIndex, Font f2, Color bgColor) { string dbTitle = _ROFSTLookup.GetRODatabaseTitle(dbTitleIndex); @@ -403,7 +403,7 @@ namespace Volian.Print.Library bool foundMisMatch = false; // n-1 Exclude the "Working Draft" entry from the list - int n = NewPath.Length-1; + int n = NewPath.Length - 1; int jstart = (skipFirst) ? 1 : 0; if (StripLast) @@ -427,7 +427,7 @@ namespace Volian.Print.Library if (!string.IsNullOrEmpty(NewPath[j]) && (foundMisMatch || OldPath.Length < j + 1 || NewPath[j] != OldPath[j])) { // B2020-006: Add hard space '\u160?' - sb.Append(sep + "".PadLeft(2 * level) + NewPath[j].Replace("\x11", " ")).Replace(@"\u8209?", "-").Replace(@"\u160?", " ").Replace(@"\u9586?",@"\"); + sb.Append(sep + "".PadLeft(2 * level) + NewPath[j].Replace("\x11", " ")).Replace(@"\u8209?", "-").Replace(@"\u160?", " ").Replace(@"\u9586?", @"\"); sep = "\r\n"; foundMisMatch = true; } @@ -592,7 +592,7 @@ namespace Volian.Print.Library level = NewPath.Length - 1; } } - + return level; } @@ -603,7 +603,7 @@ namespace Volian.Print.Library /// /// /// - private bool CreateResultsPDF(iTextSharp.text.Document document,int typ) + private bool CreateResultsPDF(iTextSharp.text.Document document, int typ) { int topMargin = 36; @@ -670,18 +670,18 @@ namespace Volian.Print.Library datatable.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin; datatable.LockedWidth = true; - // C2017-036 get best available proportional font for symbols that looks close to Arial - // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 - iTextSharp.text.Font f1 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 14, 1, Color.BLACK); - iTextSharp.text.Font f2 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 0, Color.BLACK); - iTextSharp.text.Font f3 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 12, 0, Color.BLACK); + // C2017-036 get best available proportional font for symbols that looks close to Arial + // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 + iTextSharp.text.Font f1 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 14, 1, Color.BLACK); + iTextSharp.text.Font f2 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 0, Color.BLACK); + iTextSharp.text.Font f3 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 12, 0, Color.BLACK); PdfPCell cell = new PdfPCell(new Phrase(ReportTitle, f1)); cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.BackgroundColor = new Color(0xD0, 0xF0, 0xF0); // light cyan datatable.AddCell(cell); // C2019-013 add sorted by information if sorting is used - cell = new PdfPCell(new Phrase(TypesSelected + ((SortedBy.Length >0)?string.Format("\n{0}",SortedBy):string.Empty), f3)); + cell = new PdfPCell(new Phrase(TypesSelected + ((SortedBy.Length > 0) ? string.Format("\n{0}", SortedBy) : string.Empty), f3)); cell.HorizontalAlignment = Element.ALIGN_LEFT; cell.BackgroundColor = new Color(0xD0, 0xF0, 0xF0); // light cyan datatable.AddCell(cell); @@ -737,15 +737,15 @@ namespace Volian.Print.Library { lastSectNumAndTitle = string.Empty; // C2020-019 reset we are processing a different procedure } - + lastProcNum = curProcNum; // B2020-006: When doing a section, don't remove the last item or the procedure title won't print (if section is only item found w/ search string) string stepPath = AddGroup(subTable, item.SearchPath ?? item.ShortPath, lastPath, f2, item.IsSection ? false : true, new Color(0xC0, 0xFF, 0xC0), true); // light green for procedure number and title - + // C2020-019 add section number and title if is different from last item and it is not a Word Section (item will be a section if search item was found in a Word section) string curSectNumTitle = GetCurSectionNumTitle(item); - + if (curSectNumTitle != string.Empty && curSectNumTitle != lastSectNumAndTitle && !item.IsSection) { AddColSpanCell(subTable, curSectNumTitle, f2, StepSectColor, 2, 0); @@ -820,7 +820,7 @@ namespace Volian.Print.Library } } - if (str.Length > 0) + if (str.Length > 0) p.Add(new Phrase(str, fnt)); return p; @@ -857,18 +857,18 @@ namespace Volian.Print.Library { // Adjusted from 20,80 to 25,75 to account for long Procedure Numbers float[] headerwidths = { 25, 75 }; - // C2017-036 get best available proportional font for symbols that looks close to Arial - // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 - iTextSharp.text.Font f2 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 0, Color.BLACK); + // C2017-036 get best available proportional font for symbols that looks close to Arial + // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 + iTextSharp.text.Font f2 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 0, Color.BLACK); BuildLibDocProcSetList(); - int splitAt = FindSpitLevel()-1; // find the split level of the common path - for all procedure sets that use these library documents + int splitAt = FindSpitLevel() - 1; // find the split level of the common path - for all procedure sets that use these library documents string lastDvPath = string.Empty; Color AnnoBackgroundColor = new Color(0xFF, 0xFF, 0xC0); Color TextBackgroundColor = Color.WHITE; Color NotUsedBackgroundColor = Color.WHITE; MyPageHelper pghlp = _MyPdfWriter.PageEvent as MyPageHelper; - pghlp.HeaderTable = LibDocTable(document, headerwidths, f2,null); + pghlp.HeaderTable = LibDocTable(document, headerwidths, f2, null); foreach (DocumentInfo di in _LibDocList) { @@ -926,16 +926,16 @@ namespace Volian.Print.Library private PdfPTable LibDocTable(iTextSharp.text.Document document, float[] headerwidths, iTextSharp.text.Font f2, DocumentInfo di) { PdfPTable datatable = new PdfPTable(1);// (headerwidths); - PdfPTable colheader = new PdfPTable(headerwidths); + PdfPTable colheader = new PdfPTable(headerwidths); datatable.HeaderRows = 2; datatable.KeepTogether = false; datatable.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin; datatable.LockedWidth = true; - // C2017-036 get best available proportional font for symbols that looks close to Arial - // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 - iTextSharp.text.Font f1 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 14, 1, Color.BLACK); - iTextSharp.text.Font f3 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 12, 0, Color.BLACK); + // C2017-036 get best available proportional font for symbols that looks close to Arial + // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 + iTextSharp.text.Font f1 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 14, 1, Color.BLACK); + iTextSharp.text.Font f3 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 12, 0, Color.BLACK); PdfPCell cell = new PdfPCell(new Phrase(ReportTitle, f1)); cell.HorizontalAlignment = Element.ALIGN_CENTER; //cell.Colspan = 2; @@ -977,9 +977,9 @@ namespace Volian.Print.Library private void PutROusageForProcedure(PdfPTable curTable, Dictionary> rosused, float[] headerwidths) { //if (rosused.Count == 0) return; // nothing to process - // C2017-036 get best available proportional font for symbols that looks close to Arial - // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 - iTextSharp.text.Font f2 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 0, Color.BLACK); + // C2017-036 get best available proportional font for symbols that looks close to Arial + // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 + iTextSharp.text.Font f2 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 0, Color.BLACK); foreach (string roKey in rosused.Keys) { @@ -1006,7 +1006,7 @@ namespace Volian.Print.Library { ROTitleCell.BackgroundColor = new Color(0xDC, 0xE7, 0xC9); //new Color(0xD0, 0xF0, 0xD0);//ligt green //new Color(0xC8, 0xC8, 0x91);//(0xAF, 0xD8, 0xD8);//(0xF5, 0xE4, 0xA0); } - + rotable.AddCell(ROTitleCell); // put RO value and description } } @@ -1042,11 +1042,11 @@ namespace Volian.Print.Library datatable.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin; datatable.LockedWidth = true; - // C2017-036 get best available proportional font for symbols that looks close to Arial - // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 - iTextSharp.text.Font f1 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 14, 1, Color.BLACK); - iTextSharp.text.Font f2 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 0, Color.BLACK); - iTextSharp.text.Font f3 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 12, 0, Color.BLACK); + // C2017-036 get best available proportional font for symbols that looks close to Arial + // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 + iTextSharp.text.Font f1 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 14, 1, Color.BLACK); + iTextSharp.text.Font f2 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 0, Color.BLACK); + iTextSharp.text.Font f3 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 12, 0, Color.BLACK); PdfPCell cell = new PdfPCell(new Phrase(ReportTitle, f1)); cell.HorizontalAlignment = Element.ALIGN_CENTER; //cell.Colspan = 2; @@ -1134,7 +1134,7 @@ namespace Volian.Print.Library { string dictKey = GetCurProcNum(item.SearchPath) + " " + GetCurSectionNumTitle(item); - if (dictKey != null && dictKey != string.Empty) + if (!string.IsNullOrEmpty(dictKey)) { if (procRoUse.ContainsKey(dictKey)) { @@ -1151,9 +1151,9 @@ namespace Volian.Print.Library private void PutStepListForProcedure(PdfPTable rotable, SortedDictionary sortedStepList) { - // C2017-036 get best available proportional font for symbols that looks close to Arial - // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 - iTextSharp.text.Font f2 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 0, Color.BLACK); + // C2017-036 get best available proportional font for symbols that looks close to Arial + // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 + iTextSharp.text.Font f2 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 0, Color.BLACK); foreach (ItemInfo itm in sortedStepList.Values) { @@ -1165,11 +1165,11 @@ namespace Volian.Print.Library sortedStepList.Clear(); } - private void PutROusageForROID(PdfPTable curTable, SortedDictionary> procRoUse, float[] headerwidths, int splitAt , bool moreThanOneProcSet) + private void PutROusageForROID(PdfPTable curTable, SortedDictionary> procRoUse, float[] headerwidths, int splitAt, bool moreThanOneProcSet) { - // C2017-036 get best available proportional font for symbols that looks close to Arial - // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 - iTextSharp.text.Font f2 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 0, Color.BLACK); + // C2017-036 get best available proportional font for symbols that looks close to Arial + // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 + iTextSharp.text.Font f2 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 0, Color.BLACK); SortedDictionary sortedStepList = new SortedDictionary(); string lastProcKey = string.Empty; @@ -1249,14 +1249,15 @@ namespace Volian.Print.Library { string rotitle = string.Empty; - ROFSTLookup myrofstlookup = (itm == null)? _ROFSTLookup : itm.MyDocVersion.DocVersionAssociations[0].MyROFst.GetROFSTLookup(itm.MyDocVersion); - List roTitleList = myrofstlookup.GetROTitleAndGroupPath(roid,_IncludeMissingROs,_ConvertCaretToDelta); + ROFSTLookup myrofstlookup = (itm == null) ? _ROFSTLookup : itm.MyDocVersion.DocVersionAssociations[0].MyROFst.GetROFSTLookup(itm.MyDocVersion); + + List roTitleList = myrofstlookup.GetROTitleAndGroupPath(roid, _IncludeMissingROs, _ConvertCaretToDelta); if (roTitleList != null && roTitleList.Count > 0) { for (int cnt = 0; cnt < roTitleList.Count; cnt++) { - if (cnt == roTitleList.Count - 1) + if (cnt == roTitleList.Count - 1) // Last roTitle in list, don't add a NewLine character after the value rotitle += roTitleList[cnt]; else rotitle += roTitleList[cnt] + "\n "; @@ -1269,15 +1270,15 @@ namespace Volian.Print.Library private void AddROHeaderGroup(PdfPTable datatable, string curROID, ItemInfo itm, Font f2, Color bgColor) { string headerText = GetROTitleAndGroup(curROID, itm); - if (headerText != null && headerText.Length > 0) + + if (!string.IsNullOrEmpty(headerText) && headerText.Length > 0) { PdfPCell cell = new PdfPCell(new Phrase(headerText, f2)); + cell.Colspan = 2; - if (headerText.StartsWith("Missing RO")) - cell.BackgroundColor = Color.PINK; - else - cell.BackgroundColor = bgColor; + cell.BackgroundColor = (headerText.StartsWith("Missing RO")) ? Color.PINK : bgColor; cell.BorderWidthTop = 1; + datatable.AddCell(cell); } } @@ -1285,6 +1286,7 @@ namespace Volian.Print.Library private void BuildROUsageTableByRO(iTextSharp.text.Document document) { SortedDictionary> procRoUse = new SortedDictionary>(); + float[] headerwidths = { 20, 80 }; PdfPTable datatable = new PdfPTable(1); PdfPTable colHeader = new PdfPTable(headerwidths); @@ -1292,11 +1294,11 @@ namespace Volian.Print.Library datatable.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin; datatable.LockedWidth = true; - // C2017-036 get best available proportional font for symbols that looks close to Arial - // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 - iTextSharp.text.Font f1 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 14, 1, Color.BLACK); - iTextSharp.text.Font f2 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 0, Color.BLACK); - iTextSharp.text.Font f3 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 12, 0, Color.BLACK); + // C2017-036 get best available proportional font for symbols that looks close to Arial + // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 + iTextSharp.text.Font f1 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 14, 1, Color.BLACK); + iTextSharp.text.Font f2 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 0, Color.BLACK); + iTextSharp.text.Font f3 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 12, 0, Color.BLACK); PdfPCell cell = new PdfPCell(new Phrase(ReportTitle, f1)); cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.BackgroundColor = new Color(0xD0, 0xF0, 0xF0); // light blue @@ -1360,9 +1362,9 @@ namespace Volian.Print.Library // Check for different ROID string curROID = item.FoundROID; - differentRO = lastROID != string.Empty && curROID.Substring(0, 12) != lastROID.Substring(0, 12); + differentRO = (!string.IsNullOrEmpty(lastROID) && !string.IsNullOrEmpty(curROID) && curROID.Substring(0, 12) != lastROID.Substring(0, 12)); - if (procRoUse.Count > 0 && (differentProcSet || differentRO)) + if (procRoUse.Count > 0 && (differentProcSet || differentRO)) { if (!moreThanOneProcSet && !printedSetTitle) { @@ -1450,55 +1452,68 @@ namespace Volian.Print.Library private void BuildCompleteROReport(iTextSharp.text.Document document) { - CompleteROReport compRORpt = new CompleteROReport(_MyPdfWriter, document,_RODataFile, _ConvertCaretToDelta, _IncludeEmptyROFields); + CompleteROReport compRORpt = new CompleteROReport(_MyPdfWriter, document, _RODataFile, _ConvertCaretToDelta, _IncludeEmptyROFields); + compRORpt.F10 = pdf.GetFont("Courier New", 10, 0, Color.BLACK); compRORpt.F10Bold = pdf.GetFont("Courier New", 10, 1, Color.BLACK); compRORpt.F12 = pdf.GetFont("Courier New", 12, 0, Color.BLACK); compRORpt.F12Bold = pdf.GetFont("Courier New", 12, 1, Color.BLACK); - // C2017-036 get best available proportional font for symbols that looks close to Arial - // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 - compRORpt.F14 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 14, 1, Color.BLACK); - compRORpt.ROFstID = _ROFSTLookup.MyDocVersionInfo.DocVersionAssociations[0].MyROFst.ROFstID; + // C2017-036 Get best available proportional font for symbols that looks close to Arial + // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 + compRORpt.F14 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 14, 1, Color.BLACK); + + //B2022 - 083: Support Conditional RO Values + compRORpt.ROFstID = _ROFSTLookup.RofstID; + compRORpt.Run(); } - private string GetROTitleAndGroupsForSummary(ListroTitleList, List prevROTitleList) + private string GetROTitleAndGroupsForSummary(List roTitleList, List prevROTitleList) { string rotitle = string.Empty; string indent = string.Empty; - for (int icnt = 0; icnt < roTitleList.Count; icnt++) + + for (int icnt = 0; icnt < roTitleList.Count; icnt++) + { + indent += " "; + + if (icnt == roTitleList.Count - 1) { - indent += " "; - if (icnt == roTitleList.Count - 1) - { - rotitle += indent + roTitleList[icnt]; // this should be the ro description - break; //break out of for loop - } - if (prevROTitleList == null || (icnt < roTitleList.Count && icnt < prevROTitleList.Count && prevROTitleList[icnt] != roTitleList[icnt])) - { - if (rotitle == string.Empty && prevROTitleList != null) - rotitle = "\n"; - rotitle += indent + roTitleList[icnt] + "\n"; - } + rotitle += indent + roTitleList[icnt]; // this should be the ro description + break; //break out of for loop } + + if (prevROTitleList == null || (icnt < roTitleList.Count && icnt < prevROTitleList.Count && prevROTitleList[icnt] != roTitleList[icnt])) + { + if (rotitle == string.Empty && prevROTitleList != null) + rotitle = "\n"; + + rotitle += indent + roTitleList[icnt] + "\n"; + } + } + return rotitle; } - private List AddROHeaderGroupForSummary(PdfPTable datatable, string curROID,List prevROTitleList, Font f2, Color bgColor) + private List AddROHeaderGroupForSummary(PdfPTable datatable, string curROID, List prevROTitleList, Font f2, Color bgColor) { - List roTitleList = _ROFSTLookup.GetROTitleAndGroupPath(curROID,_IncludeMissingROs,_ConvertCaretToDelta); + List roTitleList = _ROFSTLookup.GetROTitleAndGroupPath(curROID, _IncludeMissingROs, _ConvertCaretToDelta); string headerText = GetROTitleAndGroupsForSummary(roTitleList, prevROTitleList); + if (headerText.Length > 0) { Paragraph pgh = new Paragraph(headerText, f2); PdfPCell cell = new PdfPCell(pgh); + cell.FollowingIndent = 72; cell.Colspan = 2; cell.BorderColor = Color.WHITE; cell.BackgroundColor = Color.WHITE; cell.BorderWidthTop = 1; + datatable.AddCell(cell); } + return roTitleList; } @@ -1509,11 +1524,11 @@ namespace Volian.Print.Library datatable.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin; datatable.LockedWidth = true; - // C2017-036 get best available proportional font for symbols that looks close to Arial - // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 - iTextSharp.text.Font f1 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 14, 1, Color.BLACK); - iTextSharp.text.Font f2 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 0, Color.BLACK); - iTextSharp.text.Font f3 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 12, 1, Color.BLACK); + // C2017-036 get best available proportional font for symbols that looks close to Arial + // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 + iTextSharp.text.Font f1 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 14, 1, Color.BLACK); + iTextSharp.text.Font f2 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 0, Color.BLACK); + iTextSharp.text.Font f3 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 12, 1, Color.BLACK); PdfPCell cell = new PdfPCell(new Phrase(ReportTitle, f1)); @@ -1527,22 +1542,22 @@ namespace Volian.Print.Library cell = new PdfPCell(new Phrase(roFSTDateTime, f2)); cell.BorderColor = Color.WHITE; datatable.AddCell(cell); - + datatable.HeaderRows = 2;//3 + (ProcSetList.Count == 1 ? 1 : 0); datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT; string lastROID = string.Empty; - List prevROTitleList = null; + List prevROTitleList = null; int lastDBindex = -1; foreach (string curROID in _ROList) { string[] tmp = curROID.TrimEnd(',').Split(':'); //curROID.Split(':');// this is the RO FST id number (for plants with multiple RO FSTs) - string rolst = (tmp.Length == 2)? tmp[1] : tmp[0]; + string rolst = (tmp.Length == 2) ? tmp[1] : tmp[0]; string[] roIdslst = rolst.Split(','); foreach (string cROID in roIdslst) { - if (string.IsNullOrEmpty(cROID)) + if (string.IsNullOrEmpty(cROID)) break; if (cROID.Length == 4) @@ -1579,7 +1594,7 @@ namespace Volian.Print.Library } } - private void ProcessROChild(PdfPTable datatable, iTextSharp.text.Font f2, iTextSharp.text.Font f3, ref PdfPCell cell, ref string lastROID, ref List prevROTitleList, ref int lastDBindex,ROFSTLookup.rochild cld) + private void ProcessROChild(PdfPTable datatable, iTextSharp.text.Font f2, iTextSharp.text.Font f3, ref PdfPCell cell, ref string lastROID, ref List prevROTitleList, ref int lastDBindex, ROFSTLookup.rochild cld) { if (cld.children == null || cld.children.Length <= 0) // leaf node { @@ -1625,7 +1640,7 @@ namespace Volian.Print.Library #endregion #region Private Static Methods - + private static PdfPTable BuildSubTable(iTextSharp.text.Document document, float[] headerwidths) { PdfPTable subtable = new PdfPTable(headerwidths); @@ -1874,7 +1889,7 @@ namespace Volian.Print.Library public class MyPageHelper : PdfPageEventHelper { #region Fields - + private PdfPTable _HeaderTable = null; protected PdfTemplate total; protected BaseFont helv; @@ -1884,7 +1899,7 @@ namespace Volian.Print.Library #endregion #region Properties - + public PdfPTable HeaderTable { get { return _HeaderTable; } @@ -1894,7 +1909,7 @@ namespace Volian.Print.Library #endregion #region Constructors - + public MyPageHelper(string byLine) { _ByLine = byLine; @@ -1903,7 +1918,7 @@ namespace Volian.Print.Library #endregion #region Public Methods - + public override void OnOpenDocument(PdfWriter writer, iTextSharp.text.Document document) { total = writer.DirectContent.CreateTemplate(100, 100); @@ -1918,20 +1933,20 @@ namespace Volian.Print.Library cb.SaveState(); if (HeaderTable != null) - HeaderTable.WriteSelectedRows(0, 2, 36, document.Top+44, cb); + HeaderTable.WriteSelectedRows(0, 2, 36, document.Top + 44, cb); String text = "Page " + writer.PageNumber + " of "; float textBase = document.Bottom - 19;//20; cb.BeginText(); cb.SetFontAndSize(helv, ptSize); - - float posCenter = document.Left + ((document.Right - document.Left) / 2) - (helv.GetWidthPoint(text+"XX", ptSize) / 2); + + float posCenter = document.Left + ((document.Right - document.Left) / 2) - (helv.GetWidthPoint(text + "XX", ptSize) / 2); cb.SetTextMatrix(posCenter, textBase); cb.ShowText(text); cb.EndText(); cb.AddTemplate(total, posCenter + helv.GetWidthPoint(text, ptSize), textBase); cb.RestoreState(); - AddVolianFooter(writer,document); + AddVolianFooter(writer, document); AddDateFooter(writer, document); } @@ -1949,7 +1964,7 @@ namespace Volian.Print.Library #endregion #region Private Methods - + private void AddVolianFooter(PdfWriter writer, iTextSharp.text.Document document) { PdfContentByte cb = writer.DirectContent; diff --git a/PROMS/Volian.Print.Library/VlnSvgPageHelper.cs b/PROMS/Volian.Print.Library/VlnSvgPageHelper.cs index 11f986ac..bfd87994 100644 --- a/PROMS/Volian.Print.Library/VlnSvgPageHelper.cs +++ b/PROMS/Volian.Print.Library/VlnSvgPageHelper.cs @@ -436,7 +436,7 @@ i = 0; // a tabbing line - BGE wasn't using this in data at time of development. The following code may // need expanded to support the tabbing/column definitions if this is found in data. float lyoff = yOff - 4; - plist = plist.Replace("\r", ""); + plist = plist.Replace("\r", string.Empty); string[] lines = plist.Split("\n".ToCharArray()); DocStyle docstyle = MySection.MyDocStyle; try @@ -444,7 +444,7 @@ i = 0; foreach (string clinex in lines) { string cline = clinex.TrimEnd(); - if (cline != "") + if (cline != string.Empty) { // xoff handles the columns. The separator between phone items is a double space. A phone // item may have a single space within it (this comes from 16bit implementation) @@ -721,7 +721,7 @@ i = 0; { PdfDestination dest =pb.PdfDestination; if(dest==null) dest = new PdfDestination(PdfDestination.FIT); - PdfOutline pdo = new PdfOutline(MyPdfOutlines[lev-1], dest,Regex.Replace(pb.Title, @"\\{Prerequisite Step: .*?\\}", ""), false); + PdfOutline pdo = new PdfOutline(MyPdfOutlines[lev-1], dest,Regex.Replace(pb.Title, @"\\{Prerequisite Step: .*?\\}", string.Empty), false); if (MyPdfOutlines.Count == lev) MyPdfOutlines.Add(pdo); else @@ -861,7 +861,7 @@ i = 0; set { _MySection = value; - MySectionTitle = ((_MySection.DisplayNumber ?? "")=="" ? "" : _MySection.DisplayNumber + " - ") + _MySection.DisplayText; + MySectionTitle = ((_MySection.DisplayNumber ?? string.Empty)==string.Empty ? string.Empty : _MySection.DisplayNumber + " - ") + _MySection.DisplayText; bool forceLoadSvg = false; if (value.SectionConfig.Section_Pagination == SectionConfig.SectionPagination.Separate && value.MyDocStyle.ResetFirstPageOnSection) DidFirstPageDocStyle = false; @@ -1185,7 +1185,7 @@ i = 0; key = key + "." + MySection.ItemID; break; case E_NumberingSequence.WithinEachSectionNumber: - key = key + "." + ( MySection.DisplayNumber == "" ? (MySection.ActiveParent as ItemInfo).DisplayNumber : MySection.DisplayNumber); + key = key + "." + ( MySection.DisplayNumber == string.Empty ? (MySection.ActiveParent as ItemInfo).DisplayNumber : MySection.DisplayNumber); break; case E_NumberingSequence.GroupedByLevel: case E_NumberingSequence.Like6_ButDoesntNeedSubsection: @@ -1245,7 +1245,7 @@ i = 0; { while (fibase.FormatID != fibase.ParentID) fibase = fibase.MyParent; sGenMacBase = fibase.GenMac; - if (sGenMacBase != null && sGenMacBase != "") + if (sGenMacBase != null && sGenMacBase != string.Empty) { XmlDocument xDocGenMacBase = new XmlDocument(); xDocGenMacBase.LoadXml(sGenMacBase); @@ -1260,19 +1260,19 @@ i = 0; } } } - if (sGenMac == null || sGenMac == "") + if (sGenMac == null || sGenMac == string.Empty) { // If subformat and does not have its own genmac, find an inherited genmac. FormatInfo tmpf = FormatInfo.Get(activeFormat.ParentID); - while (tmpf.FormatID!=1 && (sGenMac==null||sGenMac=="")) + while (tmpf.FormatID!=1 && (sGenMac==null||sGenMac==string.Empty)) { sGenMac = tmpf.GenMac; tmpf = FormatInfo.Get(tmpf.ParentID); } - if (sGenMac == null || sGenMac == "") + if (sGenMac == null || sGenMac == string.Empty) sGenMac = ""; } - if (sGenMacBase != null && sGenMacBase != "") + if (sGenMacBase != null && sGenMacBase != string.Empty) { sGenMac = sGenMac.Replace("", sGenMacBase + ""); } @@ -1338,7 +1338,7 @@ i = 0; //float rowAdj = 0; // = 18; bool usePSIvalue = false; // C2021-065 used with ROLkUpMatch pagelist flag (Barakah Alarms) - string otherChildUnit = ""; // C2021-065 used when OTHER applicability information is used for the ROLookUp + string otherChildUnit = string.Empty; // C2021-065 used when OTHER applicability information is used for the ROLookUp foreach (VEPROMS.CSLA.Library.PageItem pageItem in pageStyle.PageItems) { if (pageItem.Token == null) continue; // can be null if token is dependent on PSI lookup! @@ -1401,7 +1401,7 @@ i = 0; parts[1] = parts[n + 1];// Get the last 2 parts parts[2] = parts[n + 2]; } - string ROLookupVal = ""; + string ROLookupVal = string.Empty; // parts[0] - the RO to look up - for Alarms, is usually the EOP number thus uses the "{EOPNUM}" token // parts[1] - Which of the multiple return value from the RO to return // parts[2] - the value to use if not found in ROs - usually defined in a PSI field for that Alarm procedure @@ -1420,7 +1420,7 @@ i = 0; int idx = procnum.IndexOf('-'); otherChildUnit = procnum.Substring(0, idx); // we need to get RO info for the Other child applicability - this gets child's number } - ROLookupVal = ROLookup(parts[0], parts[1], "",otherChildUnit); // will return empty string if alarm point is not found in RO database + ROLookupVal = ROLookup(parts[0], parts[1], string.Empty,otherChildUnit); // will return empty string if alarm point is not found in RO database usePSIvalue = (ROLookupVal != section.MyProcedure.DisplayNumber); // use PSI value if child alarm ID not found or does not match resolved procedure number (alarm point) } // C2021-065 if usePSIvalue is true, then we know alarm point info is not in the RO database, so just use the default (PSI) value @@ -1437,7 +1437,7 @@ i = 0; ROLookupVal = dt1.StartText; } // replace the pagelist token with ROLookupVal - pltok = pltok.Substring(0, idxstart) + ROLookupVal + ((idxstart + idxend < pltok.Length) ? pltok.Substring(idxstart + idxend + 1) : ""); + pltok = pltok.Substring(0, idxstart) + ROLookupVal + ((idxstart + idxend < pltok.Length) ? pltok.Substring(idxstart + idxend + 1) : string.Empty); } // C2021-065 (BNPP Alarms format) we are processing a paglist flag (ROLkUpMatch) to determine how to get Alarm Point information // Nothing else is on this page list item, so use "continue" to jump to the next pagelist item as nothing gets printed for this item @@ -1447,13 +1447,13 @@ i = 0; MatchCollection matches = regexFindToken.Matches(pltok);//(pageItem.Token); if (matches.Count > 0) { - string plstr = ""; + string plstr = string.Empty; // When a pagelist line (row) has more than one token that is resolved to text, each resolved token text was place on top // of each other. Use a temporary string (plstr) to process the pagelist tokens for each pagelist line (row) before adding // it to the svgGroup. plstr = pltok;//pageItem.Token; // F2017-046: Remove the '@@' characters that were getting printed on SAMG Sup Info facing pages for Calvert (BGESAM1 format). - if (MyPromsPrinter.DoingFacingPage && plstr.Contains("@@")) plstr = plstr.Replace("@@", ""); + if (MyPromsPrinter.DoingFacingPage && plstr.Contains("@@")) plstr = plstr.Replace("@@", string.Empty); foreach (Match match in matches) { string token = match.Value; @@ -1485,7 +1485,7 @@ i = 0; { //svgGroup.Add(PageItemToSvgText(pageItem.Token, (float)pageItem.RelatedItem.Row, (float)pageItem.RelatedItem.Col, pageItem.RelatedItem.Justify ?? VEPROMS.CSLA.Library.E_Justify.PSLeft, pageItem.Font, val, MySection)); svgGroup.Add(PageItemToSvgText(pltok, (float)pageItem.RelatedItem.Row, (float)pageItem.RelatedItem.Col, pageItem.RelatedItem.Justify ?? VEPROMS.CSLA.Library.E_Justify.PSLeft, pageItem.Font, val, MySection)); - plstr = ""; // Clear it so it isn't put out twice (used below) + plstr = string.Empty; // Clear it so it isn't put out twice (used below) } } } @@ -1494,11 +1494,11 @@ i = 0; int eindx = token.IndexOf("}", bindx); val = token.Substring(bindx + 1, eindx - bindx - 1); } - if (val != null && val != "" && !PgLogicals.ContainsKey(pstok)) PgLogicals.Add(pstok, val != null); - //if (val == null || val == "") + if (val != null && val != string.Empty && !PgLogicals.ContainsKey(pstok)) PgLogicals.Add(pstok, val != null); + //if (val == null || val == string.Empty) //val = " "; if (val == null) - val = ""; + val = string.Empty; plstr = plstr.Replace(token, val); // Get a list of Pagelist token that are inside the PS= conditional result // Paglist tokens inside a PS= conditional are surrounded by square brackets instead of curley @@ -1540,7 +1540,7 @@ i = 0; if (relval == "Y") { svgGroup.Add(PageItemToSvgText(pltok, (float)pageItem.RelatedItem.Row, (float)pageItem.RelatedItem.Col, pageItem.RelatedItem.Justify ?? VEPROMS.CSLA.Library.E_Justify.PSLeft, pageItem.Font, val, MySection)); - plstr = ""; // Clear it so it isn't put out twice (used below) + plstr = string.Empty; // Clear it so it isn't put out twice (used below) } } } @@ -1549,11 +1549,11 @@ i = 0; int eindx = token.IndexOf("}", bindx); val = token.Substring(bindx + 1, eindx - bindx - 1); } - if (val != null && val != "" && !PgLogicals.ContainsKey(pstok)) PgLogicals.Add(pstok, val != null); - //if (val == null || val == "") + if (val != null && val != string.Empty && !PgLogicals.ContainsKey(pstok)) PgLogicals.Add(pstok, val != null); + //if (val == null || val == string.Empty) //val = " "; if (val == null) - val = ""; + val = string.Empty; plstr = plstr.Replace(token, val); // Get a list of Pagelist token that are inside the SI= conditional result // Paglist tokens inside a PS= conditional are surrounded by square brackets instead of curley @@ -1575,7 +1575,7 @@ i = 0; if (!ProcessPaglistToken(section, svgGroup, pageItem, ref useFontForCheckOffHeader, ref plstr, token)) break; } } // end foreach matches - if (plstr != "") + if (plstr != string.Empty) { if (useFontForCheckOffHeader != null) svgGroup.Add(PageItemToSvgText(pageItem, plstr, useFontForCheckOffHeader, MySection)); @@ -1604,30 +1604,36 @@ i = 0; else Volian.Base.Library.BaselineMetaFile.WriteLine("No Pagelist Information"); } + private string ROLookup(string accpageid, string multiid, string deflt) { - return ROLookup(accpageid, multiid, deflt, ""); + return ROLookup(accpageid, multiid, deflt, string.Empty); } + // C2021-065 pass in a override for the child unit - in this case the token is being used (Barakah Alarms) private string ROLookup(string accpageid, string multiid, string deflt, string overrideChild) { ROFSTLookup myLookup = MySection.MyDocVersion.DocVersionAssociations[0].MyROFst.GetROFSTLookup(MySection.MyDocVersion, overrideChild); + string accpgid = accpageid; - //accpgid = accpgid.Replace("-HIGH", "-HI").Replace("-LOW", "-LO").Replace("_HIGH", "-HI").Replace("_LOW", "-LO").Replace(@"\u8209?", "-"); - string val = myLookup.GetROValueByAccPagID("<" + accpgid + "." + multiid + ">", MySection.MyDocVersion.DocVersionConfig.RODefaults_setpointprefix, MySection.MyDocVersion.DocVersionConfig.RODefaults_graphicsprefix); - if (val == null) + ROFSTLookup.rochild roc = myLookup.GetROChildByAccPageID("<" + accpgid + "." + multiid + ">", MySection.MyDocVersion.DocVersionConfig.RODefaults_setpointprefix, MySection.MyDocVersion.DocVersionConfig.RODefaults_graphicsprefix); + + if (roc.value == null) { accpgid = accpgid.Replace(@"\u8209?", "-"); - val = myLookup.GetROValueByAccPagID("<" + accpgid + "." + multiid + ">", MySection.MyDocVersion.DocVersionConfig.RODefaults_setpointprefix, MySection.MyDocVersion.DocVersionConfig.RODefaults_graphicsprefix); + roc = myLookup.GetROChildByAccPageID("<" + accpgid + "." + multiid + ">", MySection.MyDocVersion.DocVersionConfig.RODefaults_setpointprefix, MySection.MyDocVersion.DocVersionConfig.RODefaults_graphicsprefix); } - if (!deflt.StartsWith("[") && val != null && val.Trim().Length > 0) // don't return val if it's an empty or blank string - jsj 01-28-2019 + + if (!deflt.StartsWith("[") && !string.IsNullOrEmpty(roc.value) && roc.value.Trim().Length > 0) // don't return val if it's an empty or blank string - jsj 01-28-2019 { - val = val.Replace("[xB3]", "\xB3"); - val = val.Replace("[xB2]", "\xB2"); - return val; + roc.value = roc.value.Replace("[xB3]", "\xB3"); + roc.value = roc.value.Replace("[xB2]", "\xB2"); + return roc.value; } + return deflt; } + private bool _DidHLSText = false; public bool DidHLSText { @@ -1640,23 +1646,23 @@ i = 0; get { return _HasHLSTextId; } set { _HasHLSTextId = value; } } - private string _HLSText = ""; + private string _HLSText = string.Empty; public string HLSText { get { return _HLSText; } set { - if (_HLSText == "") + if (_HLSText == string.Empty) _HLSText = value; } } - private string _HLSTAB = ""; + private string _HLSTAB = string.Empty; public string HLSTAB { get { return _HLSTAB; } set { _HLSTAB = value; } } - private string _HLRNO = ""; + private string _HLRNO = string.Empty; public string HLRNO { get { return _HLRNO; } @@ -1697,11 +1703,11 @@ i = 0; { case "{!atom}": // Add an Atom Figure to the SVG - plstr = plstr.Replace(token, ""); + plstr = plstr.Replace(token, string.Empty); AddImage(svgGroup, 160.5f, 170.5f, 288f, 323f, "atom.bmp"); break; case "{!cpllogo}": - plstr = plstr.Replace(token, ""); + plstr = plstr.Replace(token, string.Empty); AddImage(svgGroup, 10f, 10f, 78.7f, 29.8f, "cpllogo.bmp"); break; //case "{!domlogo}": @@ -1738,7 +1744,7 @@ i = 0; case "[BOX8]": case "{BOX9}": case "[BOX9]": - plstr = plstr.Replace(token, ""); + plstr = plstr.Replace(token, string.Empty); svgGroup.Add(PageItemToSvgUse(pageItem, FirstAndLast(token))); break; case "{PMODEBOX}": // need to set either 1 or 2 depending on number of columns @@ -1751,24 +1757,24 @@ i = 0; else if (_MySection.SectionConfig.Section_ColumnMode == SectionConfig.SectionColumnMode.Two) box = "2"; box = "{BOX" + box + "}"; - plstr = plstr.Replace(token, ""); + plstr = plstr.Replace(token, string.Empty); svgGroup.Add(PageItemToSvgUse(pageItem, FirstAndLast(box))); break; case "{DRAFTPAGE}": //if (!AllowedWatermarks.Contains("Draft")) AllowedWatermarks.Add("Draft"); -- B2018-124 not needed anymore - plstr = plstr.Replace(token, "");// Remove token since it is handled now + plstr = plstr.Replace(token, string.Empty);// Remove token since it is handled now break; case "{REFERENCEPAGE}": //if (!AllowedWatermarks.Contains("Reference")) AllowedWatermarks.Add("Reference"); -- B2018-124 not needed anymore - plstr = plstr.Replace(token, "");// Remove token since it is handled now + plstr = plstr.Replace(token, string.Empty);// Remove token since it is handled now break; case "{MASTERPAGE}": //if (!AllowedWatermarks.Contains("Master")) AllowedWatermarks.Add("Master"); -- B2018-124 not needed anymore - plstr = plstr.Replace(token, "");// Remove token since it is handled now + plstr = plstr.Replace(token, string.Empty);// Remove token since it is handled now break; case "{SAMPLEPAGE}": //if (!AllowedWatermarks.Contains("Sample")) AllowedWatermarks.Add("Sample"); -- B2018-124 not needed anymore - plstr = plstr.Replace(token, "");// Remove token since it is handled now + plstr = plstr.Replace(token, string.Empty);// Remove token since it is handled now break; //case "{INFORMATIONPAGE}": // if (!AllowedWatermarks.Contains("Information Only")) AllowedWatermarks.Add("Information Only"); -- B2018-124 not needed anymore @@ -1788,7 +1794,7 @@ i = 0; float linelen = tlen * (float)pageItem.Font.CPI / 12; string title = section.MyProcedure.MyContent.Text; if (title.Contains("") && !section.ActiveFormat.PlantFormat.FormatData.ProcData.PrintNoTitle) - plstr = ""; + plstr = string.Empty; else { if (section.ActiveFormat.PlantFormat.FormatData.ProcData.CapitalizeTitle) title = title.ToUpper(); @@ -1833,7 +1839,7 @@ i = 0; if (OldTemplateContMsg) plstr = plstr.Replace("{CM:(Cont)}", "(Cont)"); else - plstr = plstr.Replace("{CM:(Cont)}", ""); + plstr = plstr.Replace("{CM:(Cont)}", string.Empty); break; case "{RF:REFERENCE}": // This token is used by IP2. In 16bit it is processed when the PO_DISTRIBUTEAPPROVED @@ -1842,13 +1848,13 @@ i = 0; // unless/until it is determined that it is used (no data that Volian currently has // contains this file). To implement it requires a config item off of the procedure level, // user interface support on the Procedure Properties dialog and print support. - plstr = plstr.Replace("{RF:REFERENCE}", ""); + plstr = plstr.Replace("{RF:REFERENCE}", string.Empty); break; case "{NULLDOCCURPAGE}": // This token is used by IP2. There was no support for it in 16bit and the 16bit to 32bit // output compared so it is just removed here so that a pagelist token error is not output // in error log. - plstr = plstr.Replace("{NULLDOCCURPAGE}", ""); + plstr = plstr.Replace("{NULLDOCCURPAGE}", string.Empty); break; case "{PDFDate}": plstr = plstr.Replace("{PDFDate}", DateTime.Now.ToString("MM/dd/yyyy")); @@ -1882,16 +1888,16 @@ i = 0; { // copied Rgex from DisplayText and modifed to remove the Parent/Child Unit information // i.e. , , , , , , , , - eopnum = Regex.Replace(eopnum, @"\", "", RegexOptions.IgnoreCase); - eopnum = Regex.Replace(eopnum, @"\<(U(-|\\u8209\?)ID)\>(-|\\u8209\?)", "", RegexOptions.IgnoreCase); - eopnum = Regex.Replace(eopnum, @"\<(U(-|\\u8209\?)NAME)\>(-|\\u8209\?)", "", RegexOptions.IgnoreCase); - eopnum = Regex.Replace(eopnum, @"\<(U(-|\\u8209\?)TEXT)\>(-|\\u8209\?)", "", RegexOptions.IgnoreCase); - eopnum = Regex.Replace(eopnum, @"\<(U(-|\\u8209\?)NUMBER)\>(-|\\u8209\?)", "", RegexOptions.IgnoreCase); + eopnum = Regex.Replace(eopnum, @"\", string.Empty, RegexOptions.IgnoreCase); + eopnum = Regex.Replace(eopnum, @"\<(U(-|\\u8209\?)ID)\>(-|\\u8209\?)", string.Empty, RegexOptions.IgnoreCase); + eopnum = Regex.Replace(eopnum, @"\<(U(-|\\u8209\?)NAME)\>(-|\\u8209\?)", string.Empty, RegexOptions.IgnoreCase); + eopnum = Regex.Replace(eopnum, @"\<(U(-|\\u8209\?)TEXT)\>(-|\\u8209\?)", string.Empty, RegexOptions.IgnoreCase); + eopnum = Regex.Replace(eopnum, @"\<(U(-|\\u8209\?)NUMBER)\>(-|\\u8209\?)", string.Empty, RegexOptions.IgnoreCase); // B2021-148 remove space character after "OTHER" - eopnum = Regex.Replace(eopnum, @"\<(U(-|\\u8209\?)OTHERID)\>(-|\\u8209\?)", "", RegexOptions.IgnoreCase); - eopnum = Regex.Replace(eopnum, @"\<(U(-|\\u8209\?)OTHERNAME)\>(-|\\u8209\?)", "", RegexOptions.IgnoreCase); - eopnum = Regex.Replace(eopnum, @"\<(U(-|\\u8209\?)OTHERTEXT)\>(-|\\u8209\?)", "", RegexOptions.IgnoreCase); - eopnum = Regex.Replace(eopnum, @"\<(U(-|\\u8209\?)OTHERNUMBER)\>(-|\\u8209\?)", "", RegexOptions.IgnoreCase); + eopnum = Regex.Replace(eopnum, @"\<(U(-|\\u8209\?)OTHERID)\>(-|\\u8209\?)", string.Empty, RegexOptions.IgnoreCase); + eopnum = Regex.Replace(eopnum, @"\<(U(-|\\u8209\?)OTHERNAME)\>(-|\\u8209\?)", string.Empty, RegexOptions.IgnoreCase); + eopnum = Regex.Replace(eopnum, @"\<(U(-|\\u8209\?)OTHERTEXT)\>(-|\\u8209\?)", string.Empty, RegexOptions.IgnoreCase); + eopnum = Regex.Replace(eopnum, @"\<(U(-|\\u8209\?)OTHERNUMBER)\>(-|\\u8209\?)", string.Empty, RegexOptions.IgnoreCase); } else eopnum = section.MyProcedure.DisplayNumber;// B2021-066: found and fixed during proc pc/pc work @@ -1933,7 +1939,7 @@ i = 0; && token.Contains("ATTACHTITLECONT") && DidFirstPageDocStyle) { string myMsg = section.MyDocStyle.Continue.Top.Message; - if (myMsg != null && myMsg != "")stitle = stitle + myMsg; + if (myMsg != null && myMsg != string.Empty)stitle = stitle + myMsg; } // B2021-119: large titles on Landscape Word Attachments are printing on 2 lines. int? stl = (int)section.ActiveFormat.PlantFormat.FormatData.SectData.SectionNumberAndTitleLength; @@ -1945,7 +1951,7 @@ i = 0; PrintedSectionPage = (int)pageItem.Row - _sectLevelNumTtlDiff; } else - plstr = plstr.Replace(token, ""); + plstr = plstr.Replace(token, string.Empty); //svgGroup.Add(PageItemToSvgText(pageItem, section.DisplayText)); break; case "{METASECTIONTITLE}": // This will print the top level section title (versus level above current) @@ -1961,7 +1967,7 @@ i = 0; plstr = SplitTitle(svgGroup, pageItem, top.DisplayText, section.ActiveFormat.PlantFormat.FormatData.SectData.SectionTitleLength, token, plstr, section.ActiveFormat.PlantFormat.FormatData.SectData.SectionNumberAndTitleLength); } else - plstr = plstr.Replace(token, ""); + plstr = plstr.Replace(token, string.Empty); break; case "{SECTIONLEVELNUMBER}": case "[SECTIONLEVELNUMBER]": @@ -1972,7 +1978,7 @@ i = 0; _sectLevelNumTtlDiff = (int)pageItem.Row; } else - plstr = plstr.Replace(token, ""); + plstr = plstr.Replace(token, string.Empty); // B2020-040: pagelist was {SECTIONLEVELNUMBER}, {SECTIONLEVELTITLE} and if no SECTIONLEVELNUMBER exists, printed // text starts with a ', ' - remove it. if (plstr.StartsWith(", ") && plstr.IndexOf("{SECTIONLEVELTITLE}") == 2) @@ -1996,7 +2002,7 @@ i = 0; plstr = plstr.Replace(token, top.DisplayNumber); } else - plstr = plstr.Replace(token, ""); + plstr = plstr.Replace(token, string.Empty); break; case "{UNITTEXT}": case "[UNITTEXT]": @@ -2069,12 +2075,12 @@ i = 0; plstr = plstr.Replace(token, "BREAKER"); break; default: - plstr = plstr.Replace(token, ""); + plstr = plstr.Replace(token, string.Empty); break; } } else - plstr = plstr.Replace(token, ""); + plstr = plstr.Replace(token, string.Empty); break; case "{STARTUP}": ItemInfo firstHighs = ValveGetFirstStep(section); @@ -2092,12 +2098,12 @@ i = 0; plstr = plstr.Replace(token, "STARTUP/"); break; default: - plstr = plstr.Replace(token, ""); + plstr = plstr.Replace(token, string.Empty); break; } } else - plstr = plstr.Replace(token, ""); + plstr = plstr.Replace(token, string.Empty); break; case "{PROCDES}": ProcDescrList pdl = section.ActiveFormat.PlantFormat.FormatData.PrintData.ProcDescrList; @@ -2112,7 +2118,7 @@ i = 0; if (procnum.Contains(matchStr)) { if (pd.ProcDescr1 == "{null}") // used to override fmt file inheritance & set null/empty string - plstr = ""; + plstr = string.Empty; else plstr = pd.ProcDescr1; break; @@ -2127,13 +2133,13 @@ i = 0; if (Regex.IsMatch(procnum.Substring(0,1),"[A-Za-z]")) plstr = pd.ProcDescr1; else - plstr = ""; + plstr = string.Empty; break; } if (Regex.IsMatch(procnum, "^[A-Za-z]+$")) plstr = pd.ProcDescr1; else - plstr = ""; + plstr = string.Empty; break; } } @@ -2162,7 +2168,7 @@ i = 0; if (Regex.IsMatch(procnum, "^[A-Za-z]+$")) plstr = pd.ProcDescr2; else - plstr = ""; + plstr = string.Empty; break; } } @@ -2180,7 +2186,7 @@ i = 0; plstr = plstr.Replace(token, thisDate2.ToString("H:mm")); break; case "{HLRNO}": - plstr = HLRNO==null?"":plstr.Replace(token, HLRNO); + plstr = HLRNO==null?string.Empty:plstr.Replace(token, HLRNO); break; case "{HLSTAB}": plstr = plstr.Replace(token, HLSTAB); @@ -2204,14 +2210,14 @@ i = 0; //int sc = sectCfg.Section_CheckoffListSelection; if (!MySection.HasInitials) { - plstr = plstr.Replace(token, ""); + plstr = plstr.Replace(token, string.Empty); //PIInitials = pageItem; } else { if (pageItem.Row == -MySection.MyDocStyle.Layout.TopMargin) { - plstr = plstr.Replace(token, ""); + plstr = plstr.Replace(token, string.Empty); PIInitials = pageItem; } else @@ -2222,7 +2228,7 @@ i = 0; // copied from 16bit's pagelist.cs for BGE: string revUnit = null; string unitNum = MySection.MyDocVersion.DocVersionConfig.Print_UnitNumberForPageList; - if (Rev != null && Rev != "") + if (Rev != null && Rev != string.Empty) { revUnit = Rev; int indxs = Rev.IndexOf(MySection.ActiveFormat.PlantFormat.FormatData.PrintData.RevDateWithForwardSlash ? '\\' : '/'); @@ -2262,7 +2268,7 @@ i = 0; if (val.ToUpper().Contains("") || val.ToUpper().Contains("") || val.ToUpper().Contains("") || val.ToUpper().Contains(" 14) ? pageItem.Font.Size : 12); } @@ -2489,7 +2495,7 @@ i = 0; private string SplitTitle(SvgGroup svgGroup, VEPROMS.CSLA.Library.PageItem pageItem, string title, int? len, string match, string plstr,int? numAndTitleLen) { bool includePrecedingText = false; - if (match == "{PROCTITLE2}" || match == "[PROCTITLE2]") return plstr.Replace(match, ""); + if (match == "{PROCTITLE2}" || match == "[PROCTITLE2]") return plstr.Replace(match, string.Empty); // F2017-013 - Ginna (RGESAM1) this handles when you have {SECTIONLEVELNUMBER} and {SECTIONLEVELTITLE} on the same line. // The section number was already replaced in plstr so when determining where to split the title, // include the section number (and anything before the title) in the calculation of where to split. @@ -2508,9 +2514,9 @@ i = 0; if ((len == null || len == 0 || ItemInfo.StripRtfFormatting(title).Length < len) && (!includePrecedingText || ItemInfo.StripRtfFormatting(title).Length < numAndTitleLen)) { // B2022-061: don't print '\line' as part of procedure title in pagelist items. - if (match == "{PROCTITLE}") title = title.Replace("\\line ", ""); - if (match == "{PROCTITLE2}" || match == "[PROCTITLE2]") return plstr.Replace(match, ""); // this would have been done in proctitle1 - plstr = plstr.Replace(match, title).Replace("@@",""); + if (match == "{PROCTITLE}") title = title.Replace("\\line ", string.Empty); + if (match == "{PROCTITLE2}" || match == "[PROCTITLE2]") return plstr.Replace(match, string.Empty); // this would have been done in proctitle1 + plstr = plstr.Replace(match, title).Replace("@@",string.Empty); //svgGroup.Add(PageItemToSvgText(pageItem, title)); return plstr; } @@ -2520,7 +2526,7 @@ i = 0; if (plstr.Contains("@@")) { DoSpecialSectNumTitle(svgGroup, pageItem, title, len, match, plstr); - return ""; // all resolved pagelist items were already added to svgGroup for printing. + return string.Empty; // all resolved pagelist items were already added to svgGroup for printing. } // Otherwise determine how many line to split the text into ListtitleLines = Volian.Base.Library.RtfTools.SplitText(title,(includePrecedingText)?(int)numAndTitleLen: (int)len); @@ -2555,11 +2561,11 @@ i = 0; { plstr = plstr.Replace(match, line); // include preceeding text with the first line v.c. summer svgGroup.Add(PageItemToSvgText(pageItem, plstr, yOffset)); - plstr = ""; + plstr = string.Empty; } else svgGroup.Add(PageItemToSvgText(pageItem, line, yOffset)); - plstr = plstr.Replace(match, ""); + plstr = plstr.Replace(match, string.Empty); } yOffset += (float)((pageItem.Font.Size > 14) ? pageItem.Font.Size : 12); } @@ -2632,7 +2638,7 @@ i = 0; svgGroup.Add(PageItemToSvgText(pageItem, line, yOffset)); yOffset += (float)((pageItem.Font.Size > 14) ? pageItem.Font.Size : 12); } - return plstr.Replace(token, ""); + return plstr.Replace(token, string.Empty); } private string SplitEOPNumber(SvgGroup svgGroup, PageItem pageItem, string eopnum, string token, string plstr) { @@ -2643,7 +2649,7 @@ i = 0; svgGroup.Add(PageItemToSvgText(pageItem, line, yOffset)); yOffset += (float)((pageItem.Font.Size > 14) ? pageItem.Font.Size : 12); } - return plstr.Replace(token, ""); + return plstr.Replace(token, string.Empty); } //private string symblsStr = "\u25CF\u0394"; // string of possible symbol character in a tab //// add symbol characters as needed @@ -2697,7 +2703,7 @@ i = 0; if (lnCnt == 1) continue; plstr = plstr.Replace(match, line); svgGroup.Add(PageItemToSvgText(pageItem, plstr, yOffset)); - plstr = ""; // clear it because it was added into the list in the line above this, i.e. don't duplicate + plstr = string.Empty; // clear it because it was added into the list in the line above this, i.e. don't duplicate yOffset += 12; } return plstr; @@ -2815,7 +2821,7 @@ i = 0; // there is a message in format file to use instead of text, then use it. if (tmpi == 8 && mySize.Width > fontShrinkAftLen) { - if (reptext != null && reptext != "") + if (reptext != null && reptext != string.Empty) text = reptext; else // As per PAL (11/15/21) have default message and highlight by italics (text was already bolded) { @@ -2939,7 +2945,7 @@ i = 0; // that are used. // 16-bit had code to string preceeding blanks. - if (Rev != null && Rev != "") Rev = Rev.TrimStart(" ".ToCharArray()); + if (Rev != null && Rev != string.Empty) Rev = Rev.TrimStart(" ".ToCharArray()); // Now check the format flags to determine if/how the Rev string should be parsed. if ((MySection.ActiveFormat.PlantFormat.FormatData.PrintData.DoRevDate && Rev.Contains("/")) @@ -2958,14 +2964,14 @@ i = 0; case "{SETREV}": return MySection.MyDocVersion.DocVersionConfig.ProcedureSetRev; case "{NULLDOCCURPAGE}": - return ""; + return string.Empty; } if (!_MissingTokens.Contains(match.Value)) { _MissingTokens.Add(match.Value); _MyLog.InfoFormat("Unhandled token {0}", match.Value); } - return ""; + return string.Empty; } } public class ChkListBoxesHelper : List