diff --git a/PROMS/VEPROMS User Interface/dlgExportImport.cs b/PROMS/VEPROMS User Interface/dlgExportImport.cs index 6c0dad02..ab66cb4a 100644 --- a/PROMS/VEPROMS User Interface/dlgExportImport.cs +++ b/PROMS/VEPROMS User Interface/dlgExportImport.cs @@ -2108,6 +2108,28 @@ namespace VEPROMS ExportROFst(xe, ai.MyROFst, "rofst"); } private void ExportAssociation(AssociationInfo ai, string nodename) + { + /* + AssociationID + VersionID + ROFstID + Config + DTS + UserID + */ + lblExportStatus.Text = "Exporting Association..."; + Application.DoEvents(); + XmlElement xe = xn.OwnerDocument.CreateElement(nodename); + xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "associationid", ai.AssociationID.ToString())); + xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "versionid", ai.VersionID.ToString())); + xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "rofstid", ai.ROFstID.ToString())); + xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "config", ai.Config)); + xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "dts", ai.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff"))); + xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "userid", ai.UserID.ToString())); + xn.AppendChild(xe); + ExportROFst(xe, ai.MyROFst, "rofst"); + } + private void ExportAssociation(AssociationInfo ai, string nodename) { /* AssociationID @@ -2127,6 +2149,7 @@ namespace VEPROMS ExportROFst(ai.MyROFst, "rofst"); MyWriter.WriteEndElement(); } + private void ExportROFst(XmlElement xn, ROFstInfo fst, string nodename) { /* @@ -2139,17 +2162,20 @@ namespace VEPROMS */ lblExportStatus.Text = "Exporting ROFst..."; Application.DoEvents(); + XmlElement xe = xn.OwnerDocument.CreateElement(nodename); xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "rofstid", fst.ROFstID.ToString())); xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "rodbid", fst.RODbID.ToString())); - xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "rolookup", Convert.ToBase64String(fst.ROLookup))); + xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "rolookup", Convert.ToBase64String(ROFSTLookup.GetRofstLookupBytes(fst.ROFstID)))); // B2022-026 RO Memory reduction - new calls xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "config", fst.Config)); xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "dts", fst.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff"))); xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "userid", fst.UserID.ToString())); xn.AppendChild(xe); + ExportFigures(xe, fst); ExportRODb(xe, fst.MyRODb, "rodb"); } + private void ExportROFst(ROFstInfo fst, string nodename) { /* @@ -2163,22 +2189,26 @@ namespace VEPROMS MyWriter.WriteStartElement(nodename); MyWriter.WriteAttributeString("rofstid", fst.ROFstID.ToString()); MyWriter.WriteAttributeString("rodbid", fst.RODbID.ToString()); - MyWriter.WriteAttributeString("rolookup", Convert.ToBase64String(fst.ROLookup)); + MyWriter.WriteAttributeString("rolookup", Convert.ToBase64String(ROFSTLookup.GetRofstLookupBytes(fst.ROFstID))); // B2022-026 RO Memory reduction - new calls MyWriter.WriteAttributeString("config", fst.Config); MyWriter.WriteAttributeString("dts", fst.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff")); MyWriter.WriteAttributeString("userid", fst.UserID.ToString()); + ExportRODb(fst.MyRODb, "rodb"); MyWriter.WriteEndElement(); } + private void ExportFigures(XmlElement xn, ROFstInfo fst) { if (fst.ROFstFigureCount > 0) { XmlElement xe = xn.OwnerDocument.CreateElement("figures"); xn.AppendChild(xe); + foreach (FigureInfo figure in fst.ROFstFigures) { XmlElement xee = xn.OwnerDocument.CreateElement("figure"); + xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "figureid", figure.FigureID.ToString())); xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "rofstid", figure.ROFstID.ToString())); xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "imageid", figure.ImageID.ToString())); @@ -2186,13 +2216,16 @@ namespace VEPROMS xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "dts", figure.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff"))); xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "userid", figure.UserID)); xe.AppendChild(xee); + // B2018-031 Output figure names as they are exported to provide more constant feedback lblExportStatus.Text = string.Format("Exporting Figure...{0}", figure.MyROImage.FileName); Application.DoEvents(); + ExportROImage(xee, figure.MyROImage); } } } + private void ExportROImage(XmlElement xn, ROImageInfo image) { XmlElement xe = xn.OwnerDocument.CreateElement("image"); @@ -2205,6 +2238,7 @@ namespace VEPROMS xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "userid", image.UserID)); xn.AppendChild(xe); } + private void ExportRODb(XmlElement xn, RODbInfo db, string nodename) { /* @@ -2218,6 +2252,7 @@ namespace VEPROMS */ lblExportStatus.Text = "Exporting RODb..."; Application.DoEvents(); + XmlElement xe = xn.OwnerDocument.CreateElement(nodename); xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "rodbid", db.RODbID.ToString())); xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "roname", db.ROName)); @@ -2228,6 +2263,7 @@ namespace VEPROMS xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "userid", db.UserID.ToString())); xn.AppendChild(xe); } + private void ExportRODb(RODbInfo db, string nodename) { /* @@ -2263,6 +2299,7 @@ namespace VEPROMS xd.AppendChild(xe); ExportItem(xe, ii, nodename); } + private void ExportItem(XmlElement xn, ItemInfo ii, string nodename) { /* @@ -2279,6 +2316,7 @@ namespace VEPROMS xe = xn.OwnerDocument.CreateElement(nodename); xn.AppendChild(xe); } + if (ii.IsProcedure) { pbExportProcedure.PerformStep(); @@ -2286,10 +2324,12 @@ namespace VEPROMS TimeSpan elapsed = DateTime.Now.Subtract(MyStart); lblExportTime.Text = "Elapsed Time: " + elapsed.ToString(); Application.DoEvents(); + pbExportSection.Value = 0; pbExportSection.Maximum = pbExportSection.Value; pbExportStep.Value = 0; pbExportStep.Maximum = pbExportStep.Value; + if (ii.Sections != null) pbExportSection.Maximum = ii.Sections.Count; else @@ -2303,6 +2343,7 @@ namespace VEPROMS Application.DoEvents(); } } + if (ii.IsSection && ii.ActiveParent.IsProcedure) { pbExportSection.PerformStep(); @@ -2310,6 +2351,7 @@ namespace VEPROMS Application.DoEvents(); pbExportStep.Value = 0; pbExportStep.Maximum = pbExportStep.Value; + if (ii.Steps != null) pbExportStep.Maximum = ii.Steps.Count; else @@ -2320,36 +2362,44 @@ namespace VEPROMS Application.DoEvents(); } } + if (ii.IsStep && ii.ActiveParent.IsSection && ii.ActiveParent.ActiveParent.IsProcedure) { pbExportStep.PerformStep(); lblExportStep.Text = string.Format("{0} of {1} Steps", pbExportStep.Value.ToString(), pbExportStep.Maximum.ToString()); Application.DoEvents(); } + xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "itemid", ii.ItemID.ToString())); xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "previousid", ii.PreviousID.ToString())); xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "contentid", ii.ContentID.ToString())); xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "dts", ii.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff"))); + //item audits ExportItemAudits(xe, ii); ExportContent(xe, ii.MyContent, "content"); + if (ii.ItemAnnotationCount > 0) foreach (AnnotationInfo ai in ii.ItemAnnotations) ExportAnnotation(xe, ai, "annotation"); } + private void ExportItemAudits(XmlElement xn, ItemInfo ii) { if (cbxExportAudits.Checked) { ItemAuditInfoList audits = ItemAuditInfoList.Get(ii.ItemID); + if (audits.Count > 0) { XmlElement xe = xn.OwnerDocument.CreateElement("audits"); + foreach (ItemAuditInfo audit in audits) { if (audit.DeleteStatus == 0) { XmlElement xee = xn.OwnerDocument.CreateElement("audit"); + xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "auditid", audit.AuditID.ToString())); xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "contentid", audit.ContentID.ToString())); xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "deletestatus", audit.DeleteStatus.ToString())); @@ -2357,13 +2407,16 @@ namespace VEPROMS xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "itemid", audit.ItemID.ToString())); xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "previousid", audit.PreviousID.ToString())); xee.Attributes.SetNamedItem(AddAttribute(xee.OwnerDocument, "userid", audit.UserID)); + xe.AppendChild(xee); } } + xn.AppendChild(xe); } } } + // used to save word sections with resolved ROs (export generated from Approve) private Dictionary _DocReplace; public Dictionary DocReplace @@ -2375,6 +2428,7 @@ namespace VEPROMS _ConvertROsAndTransitionsToText = (value != null); } } + private void ExportItem(ItemInfo ii, string nodename) { /* @@ -2388,9 +2442,11 @@ namespace VEPROMS pbExportProcedure.PerformStep(); lblExportProcedure.Text = string.Format("{0} of {1} Procedures", pbExportProcedure.Value.ToString(), pbExportProcedure.Maximum.ToString()); Application.DoEvents(); + pbExportSection.Value = 0; pbExportStep.Value = 0; pbExportSection.Maximum = ii.Sections.Count; + if (ii.Sections != null) pbExportSection.Maximum = ii.Sections.Count; else @@ -2404,6 +2460,7 @@ namespace VEPROMS Application.DoEvents(); } } + if (ii.IsSection) { pbExportSection.PerformStep(); @@ -2420,23 +2477,28 @@ namespace VEPROMS Application.DoEvents(); } } + if (ii.IsStep) { pbExportStep.PerformStep(); lblExportStep.Text = string.Format("{0} of {1} Steps", pbExportStep.Value.ToString(), pbExportStep.Maximum.ToString()); Application.DoEvents(); } + MyWriter.WriteStartElement(nodename); MyWriter.WriteAttributeString("itemid", ii.ItemID.ToString()); MyWriter.WriteAttributeString("previousid", ii.PreviousID.ToString()); MyWriter.WriteAttributeString("contentid", ii.ContentID.ToString()); MyWriter.WriteAttributeString("dts", ii.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff")); + ExportContent(ii.MyContent, "content"); if (ii.ItemAnnotationCount > 0) foreach (AnnotationInfo ai in ii.ItemAnnotations) ExportAnnotation(ai, "annotation"); + MyWriter.WriteEndElement(); } + private void ExportContent(XmlElement xn, ContentInfo ci, string nodename) { /* @@ -2453,6 +2515,7 @@ namespace VEPROMS // strip the link information if we are convertingthe RO and Transitions to text string ciText = (_ConvertROsAndTransitionsToText) ? ItemInfo.StripLinks(ci.Text) : ci.Text; string formatFileName = (ci.MyFormat != null) ? ci.MyFormat.Name : ""; + xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "contentid", ci.ContentID.ToString())); xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "number", ci.Number)); xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "text", ciText)); @@ -2462,33 +2525,43 @@ namespace VEPROMS xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "dts", ci.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff"))); xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "userid", ci.UserID.ToString())); xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "formatfilename", formatFileName)); + //content audits ExportContentAudits(xe, ci); xn.AppendChild(xe); + if (ci.ContentTransitionCount > 0) foreach (TransitionInfo ti in ci.ContentTransitions) ExportTransition(xe, ti, "transition"); + if (ci.ContentRoUsageCount > 0) foreach (RoUsageInfo ri in ci.ContentRoUsages) ExportROUsage(xe, ri, "rousage"); + if (ci.ContentEntryCount > 0) ExportEntry(xe, ci.MyEntry, "entry"); + if (ci.ContentGridCount > 0) ExportGrid(xe, ci.MyGrid, "grid"); + if (ci.ContentImageCount > 0) ExportImage(xe, ci.MyImage, "image"); + if (ci.ContentPartCount > 0) foreach (PartInfo pi in ci.ContentParts) ExportPart(xe, pi, ((E_FromTypes)pi.FromType).ToString().ToLower()); } + private void ExportContentAudits(XmlElement xn, ContentInfo ci) { if (cbxExportAudits.Checked) { ContentAuditInfoList audits = ContentAuditInfoList.Get(ci.ContentID); + if (audits.Count > 0) { XmlElement xe = xn.OwnerDocument.CreateElement("audits"); + foreach (ContentAuditInfo audit in audits) { if (audit.DeleteStatus == 0) @@ -2511,6 +2584,7 @@ namespace VEPROMS } } } + private void ExportContent(ContentInfo ci, string nodename) { /* @@ -2526,6 +2600,7 @@ namespace VEPROMS // strip the link information if we are convertinga the ROs and Transitions to text string ciText = (_ConvertROsAndTransitionsToText) ? ItemInfo.StripLinks(ci.Text) : ci.Text; string formatFileName = (ci.MyFormat != null) ? ci.MyFormat.Name : ""; + MyWriter.WriteStartElement(nodename); MyWriter.WriteAttributeString("contentid", ci.ContentID.ToString()); MyWriter.WriteAttributeString("number", ci.Number); @@ -2536,23 +2611,31 @@ namespace VEPROMS MyWriter.WriteAttributeString("dts", ci.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff")); MyWriter.WriteAttributeString("userid", ci.UserID.ToString()); MyWriter.WriteAttributeString("formatfilename", formatFileName); + if (ci.ContentTransitionCount > 0) foreach (TransitionInfo ti in ci.ContentTransitions) ExportTransition(ti, "transition"); + if (ci.ContentRoUsageCount > 0) foreach (RoUsageInfo ri in ci.ContentRoUsages) ExportROUsage(ri, "rousage"); + if (ci.ContentEntryCount > 0) ExportEntry(ci.MyEntry, "entry"); + if (ci.ContentGridCount > 0) ExportGrid(ci.MyGrid, "grid"); + if (ci.ContentImageCount > 0) ExportImage(ci.MyImage, "image"); + if (ci.ContentPartCount > 0) foreach (PartInfo pi in ci.ContentParts) ExportPart(pi, ((E_FromTypes)pi.FromType).ToString().ToLower()); + MyWriter.WriteEndElement(); } + private void ExportGrid(XmlElement xn, GridInfo gi, string nodename) { /* @@ -2568,24 +2651,29 @@ namespace VEPROMS giData = giData.Replace("True", "False"); // converts a RO table to a unlinked regular table giData = ItemInfo.StripLinks(giData); // this converts ROs and transitions to text } + XmlElement xe = xn.OwnerDocument.CreateElement(nodename); xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "contentid", gi.ContentID.ToString())); xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "data", giData)); xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "config", gi.Config)); xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "dts", gi.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff"))); xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "userid", gi.UserID.ToString())); + //grid audits ExportGridAudits(xe, gi); xn.AppendChild(xe); } + private void ExportGridAudits(XmlElement xn, GridInfo gi) { if (cbxExportAudits.Checked) { GridAuditInfoList audits = GridAuditInfoList.Get(gi.ContentID); + if (audits.Count > 0) { XmlElement xe = xn.OwnerDocument.CreateElement("audits"); + foreach (GridAuditInfo audit in audits) { if (audit.DeleteStatus == 0) @@ -2606,6 +2694,7 @@ namespace VEPROMS } } } + private void ExportGrid(GridInfo gi, string nodename) { /* @@ -2621,6 +2710,7 @@ namespace VEPROMS giData = giData.Replace("IsRoTable>True", "IsRoTable>False"); // converts a RO table to regular table giData = ItemInfo.StripLinks(giData); // converts ROs and Transitions to text } + MyWriter.WriteStartElement(nodename); MyWriter.WriteAttributeString("contentid", gi.ContentID.ToString()); MyWriter.WriteAttributeString("data", giData); @@ -2629,6 +2719,7 @@ namespace VEPROMS MyWriter.WriteAttributeString("userid", gi.UserID.ToString()); MyWriter.WriteEndElement(); } + private void ExportEntry(XmlElement xn, EntryInfo ei, string nodename) { /* @@ -2642,19 +2733,23 @@ namespace VEPROMS xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "docid", ei.DocID.ToString())); xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "dts", ei.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff"))); xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "userid", ei.UserID.ToString())); + //entry audits ExportEntryAudits(xe, ei); xn.AppendChild(xe); ExportDocument(xe, ei.MyDocument, "document"); } + private void ExportEntryAudits(XmlElement xn, EntryInfo ei) { if (cbxExportAudits.Checked) { EntryAuditInfoList audits = EntryAuditInfoList.Get(ei.ContentID); + if (audits.Count > 0) { XmlElement xe = xn.OwnerDocument.CreateElement("audits"); + foreach (EntryAuditInfo audit in audits) { if (audit.DeleteStatus == 0) @@ -2672,6 +2767,7 @@ namespace VEPROMS } } } + private void ExportEntry(EntryInfo ei, string nodename) { /* @@ -2688,6 +2784,7 @@ namespace VEPROMS ExportDocument(ei.MyDocument, "document"); MyWriter.WriteEndElement(); } + private void ExportImage(XmlElement xn, ImageInfo ii, string nodename) { /* @@ -2711,14 +2808,17 @@ namespace VEPROMS ExportImageAudits(xe, ii); xn.AppendChild(xe); } + private void ExportImageAudits(XmlElement xn, ImageInfo ii) { if (cbxExportAudits.Checked) { ImageAuditInfoList audits = ImageAuditInfoList.Get(ii.ContentID); + if (audits.Count > 0) { XmlElement xe = xn.OwnerDocument.CreateElement("audits"); + foreach (ImageAuditInfo audit in audits) { if (audit.DeleteStatus == 0) @@ -2739,6 +2839,7 @@ namespace VEPROMS } } } + private void ExportImage(ImageInfo ii, string nodename) { /* @@ -2760,6 +2861,7 @@ namespace VEPROMS MyWriter.WriteAttributeString("userid", ii.UserID.ToString()); MyWriter.WriteEndElement(); } + private void ExportDocument(XmlElement xn, DocumentInfo di, string nodename) { /* @@ -2779,6 +2881,7 @@ namespace VEPROMS buf = DocReplace[di.DocID]; libDocTitle = null; // unlink the word section from the library document } + XmlElement xe = xn.OwnerDocument.CreateElement(nodename); xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "docid", di.DocID.ToString())); xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "libtitle", libDocTitle)); // di.LibTitle)); @@ -2788,18 +2891,22 @@ namespace VEPROMS xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "dts", di.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff"))); xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "userid", di.UserID.ToString())); xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "fileextension", di.FileExtension)); + //document audits ExportDocumentAudits(xe, di); xn.AppendChild(xe); } + private void ExportDocumentAudits(XmlElement xn, DocumentInfo di) { if (cbxExportAudits.Checked) { DocumentAuditInfoList audits = DocumentAuditInfoList.Get(di.DocID); + if (audits.Count > 0) { XmlElement xe = xn.OwnerDocument.CreateElement("audits"); + foreach (DocumentAuditInfo audit in audits) { if (audit.DeleteStatus == 0) @@ -2840,6 +2947,7 @@ namespace VEPROMS buf = DocReplace[di.DocID]; libDocTitle = null; // unlink the word section from the library document } + MyWriter.WriteStartElement(nodename); MyWriter.WriteAttributeString("docid", di.DocID.ToString()); MyWriter.WriteAttributeString("libtitle", libDocTitle);// di.LibTitle); @@ -2851,6 +2959,7 @@ namespace VEPROMS MyWriter.WriteAttributeString("fileextension", di.FileExtension); MyWriter.WriteEndElement(); } + private void ExportROUsage(XmlElement xn, RoUsageInfo ri, string nodename) { /* @@ -2870,16 +2979,17 @@ namespace VEPROMS xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "dts", ri.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff"))); xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "userid", ri.UserID.ToString())); xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "rodbid", ri.RODbID.ToString())); + //rousage audits ExportROUsageAudits(xe, ri); xn.AppendChild(xe); } + private void ExportROUsageAudits(XmlElement xe, RoUsageInfo ri) { - if (cbxExportAudits.Checked) - { - } + if (cbxExportAudits.Checked) { }; } + private void ExportROUsage(RoUsageInfo ri, string nodename) { /* @@ -2901,6 +3011,7 @@ namespace VEPROMS MyWriter.WriteAttributeString("rodbid", ri.RODbID.ToString()); MyWriter.WriteEndElement(); } + private void ExportPart(XmlElement xn, PartInfo pi, string nodename) { /* @@ -2916,20 +3027,24 @@ namespace VEPROMS xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "itemid", pi.ItemID.ToString())); xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "dts", pi.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff"))); xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "userid", pi.UserID.ToString())); + //part audits ExportPartAudits(xe, pi); xn.AppendChild(xe); foreach (ItemInfo ii in pi.MyItems) ExportItem(xe, ii, pi.PartType.ToString().ToLower()); } + private void ExportPartAudits(XmlElement xn, PartInfo pi) { if (cbxExportAudits.Checked) { PartAuditInfoList audits = PartAuditInfoList.Get(pi.ContentID); + if (audits.Count > 0) { XmlElement xe = xn.OwnerDocument.CreateElement("audits"); + foreach (PartAuditInfo audit in audits) { if (audit.DeleteStatus == 0) @@ -2948,6 +3063,7 @@ namespace VEPROMS } } } + private void ExportPart(PartInfo pi, string nodename) { /* @@ -2967,6 +3083,7 @@ namespace VEPROMS ExportItem(ii, pi.PartType.ToString().ToLower()); MyWriter.WriteEndElement(); } + private void ExportTransition(XmlElement xn, TransitionInfo ti, string nodename) { /* @@ -2990,16 +3107,17 @@ namespace VEPROMS xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "config", ti.Config)); xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "dts", ti.DTS.ToString("MM/dd/yyyy HH:mm:ss.fff"))); xe.Attributes.SetNamedItem(AddAttribute(xe.OwnerDocument, "userid", ti.UserID.ToString())); + //transition audits ExportTransitionAudits(xe, ti); xn.AppendChild(xe); } + private void ExportTransitionAudits(XmlElement xe, TransitionInfo ti) { - if (cbxExportAudits.Checked) - { - } + if (cbxExportAudits.Checked) { }; } + private void ExportTransition(TransitionInfo ti, string nodename) { /* @@ -3024,9 +3142,12 @@ namespace VEPROMS nodename = "external" + nodename; folder = "UNKNOWN"; } + MyWriter.WriteStartElement(nodename); + if (folder != string.Empty) MyWriter.WriteAttributeString("folder", folder); + MyWriter.WriteAttributeString("transitionid", ti.TransitionID.ToString()); MyWriter.WriteAttributeString("fromid", ti.FromID.ToString()); MyWriter.WriteAttributeString("toid", ti.ToID.ToString()); @@ -3038,6 +3159,7 @@ namespace VEPROMS MyWriter.WriteAttributeString("userid", ti.UserID.ToString()); MyWriter.WriteEndElement(); } + private void ExportAnnotation(XmlElement xn, AnnotationInfo ai, string nodename) { /* @@ -3065,14 +3187,17 @@ namespace VEPROMS ExportAnnotationAudits(xe, ai); xn.AppendChild(xe); } + private void ExportAnnotationAudits(XmlElement xn, AnnotationInfo ai) { if (cbxExportAudits.Checked) { AnnotationAuditInfoList audits = AnnotationAuditInfoList.GetByAnnotationID(ai.AnnotationID); + if (audits.Count > 0) { XmlElement xe = xn.OwnerDocument.CreateElement("audits"); + foreach (AnnotationAuditInfo audit in audits) { if (audit.DeleteStatus == 0) @@ -3096,6 +3221,7 @@ namespace VEPROMS } } } + private void ExportAnnotation(AnnotationInfo ai, string nodename) { /* @@ -3119,7 +3245,9 @@ namespace VEPROMS MyWriter.WriteAttributeString("userid", ai.UserID.ToString()); MyWriter.WriteEndElement(); } + #endregion + #region Import for Merge // jsj 4-29-2016 appears to not be used @@ -3203,10 +3331,12 @@ namespace VEPROMS type,id,toid,rangeid */ XmlNodeList nl = xn.SelectNodes("./transition"); + foreach (XmlNode nd in nl) { int toid = int.Parse(nd.Attributes.GetNamedItem("toid").InnerText); int rangeid = int.Parse(nd.Attributes.GetNamedItem("rangeid").InnerText); + if (Old2NewItem.ContainsKey(toid) && Old2NewItem.ContainsKey(rangeid)) { int transitionid = int.Parse(nd.Attributes.GetNamedItem("transitionid").InnerText); @@ -3216,28 +3346,37 @@ namespace VEPROMS string userid = nd.Attributes.GetNamedItem("userid").InnerText; DateTime dts = DateTime.Parse(nd.Attributes.GetNamedItem("dts").InnerText); string lookfor; + if (isrange == 0) lookfor = string.Format("#Link:Transition:{0} {1} {2}", trantype, transitionid, toid); else lookfor = string.Format("#Link:TransitionRange:{0} {1} {2} {3}", trantype, transitionid, toid, rangeid); + //fromid = content.ContentID; toid = Old2NewItem[toid]; rangeid = Old2NewItem[rangeid]; Transition tt = Transition.MakeTransition(content, Item.Get(toid), Item.Get(rangeid), isrange, trantype, config, dts, userid); transitionid = tt.TransitionID; string replacewith; + if (isrange == 0) replacewith = string.Format("#Link:Transition:{0} {1} {2}", trantype, transitionid, toid); else replacewith = string.Format("#Link:TransitionRange:{0} {1} {2} {3}", trantype, transitionid, toid, rangeid); + content.Text = content.Text.Replace(lookfor, replacewith); + if (content.MyGrid != null && content.MyGrid.Data != "") + { content.MyGrid.Data = content.MyGrid.Data.Replace(lookfor, replacewith); + } + _DidProcessTransitions |= content.FixTransitionText(TransitionInfo.Get(tt.TransitionID)); // B2017-076 FixTransitionText will tell us if transitions were processed/changed // B2017=003 make sure any grid changes are saved. // done here because FixTransitionText() could update the transitions in the grid if (content.MyGrid != null && content.MyGrid.Data != "") content.MyGrid.Save(); + content.Save(); } else @@ -3247,6 +3386,7 @@ namespace VEPROMS } } } + private void AddTransitions() { AddTransitions(PendingTransitions); @@ -3273,6 +3413,7 @@ namespace VEPROMS */ XmlNodeList nl = xd.SelectNodes("//transition"); lblImportStatus.Text = string.Format("Updating {0} Tranistions", nl.Count.ToString()); + foreach (XmlNode nd in nl) { int fromid = int.Parse(nd.Attributes.GetNamedItem("fromid").InnerText); @@ -3289,10 +3430,12 @@ namespace VEPROMS string userid = nd.Attributes.GetNamedItem("userid").InnerText; DateTime dts = DateTime.Parse(nd.Attributes.GetNamedItem("dts").InnerText); string lookfor; + if (isrange == 0) lookfor = string.Format("#Link:Transition:{0} {1} {2}", trantype, transitionid, toid); else lookfor = string.Format("#Link:TransitionRange:{0} {1} {2} {3}", trantype, transitionid, toid, rangeid); + fromid = Old2NewContent[fromid]; toid = Old2NewItem[toid]; rangeid = Old2NewItem[rangeid]; @@ -3300,13 +3443,19 @@ namespace VEPROMS Transition tt = Transition.MakeTransition(cc, Item.Get(toid), Item.Get(rangeid), isrange, trantype, config, dts, userid); transitionid = tt.TransitionID; string replacewith; + if (isrange == 0) replacewith = string.Format("#Link:Transition:{0} {1} {2}", trantype, transitionid, toid); else replacewith = string.Format("#Link:TransitionRange:{0} {1} {2} {3}", trantype, transitionid, toid, rangeid); + cc.Text = cc.Text.Replace(lookfor, replacewith); - if (cc.MyGrid != null && cc.MyGrid.Data != "") + + if (cc.MyGrid != null && !string.IsNullOrEmpty(cc.MyGrid.Data)) + { cc.MyGrid.Data = cc.MyGrid.Data.Replace(lookfor, replacewith); + } + bool forceConvertToText = false; if (TransitionInfo.Get(tt.TransitionID).MyItemToID.ActiveSection != null) { @@ -3315,6 +3464,7 @@ namespace VEPROMS // This was found when fixing B2018-002 but it actually applies to B2016-081 forceConvertToText = (sc.SubSection_Edit == "N" && TransitionInfo.Get(tt.TransitionID).MyItemToID.IsStep); } + _DidProcessTransitions |= cc.FixTransitionText(TransitionInfo.Get(tt.TransitionID), forceConvertToText); // B2017-076 FixTransitionText will tell us if transitions were processed/changed // B2017=003 make sure any grid changes are saved. // done here because FixTransitionText() could update the transitions in the grid @@ -3332,13 +3482,16 @@ namespace VEPROMS string userid = nd.Attributes.GetNamedItem("userid").InnerText; DateTime dts = DateTime.Parse(nd.Attributes.GetNamedItem("dts").InnerText); string lookfor; + if (isrange == 0) lookfor = string.Format("#Link:Transition:{0} {1} {2}", trantype, transitionid, toid); else lookfor = string.Format("#Link:TransitionRange:{0} {1} {2} {3}", trantype, transitionid, toid, rangeid); + fromid = Old2NewContent[fromid]; Content cc = Content.Get(fromid); Transition tt = Transition.MakeTransition(cc, Item.Get(toid), Item.Get(rangeid), isrange, trantype, config, dts, userid); + if (tt.TransitionID < 0) { forceConvertToText = true; @@ -3350,13 +3503,19 @@ namespace VEPROMS { transitionid = tt.TransitionID; string replacewith; + if (isrange == 0) replacewith = string.Format("#Link:Transition:{0} {1} {2}", trantype, transitionid, toid); else replacewith = string.Format("#Link:TransitionRange:{0} {1} {2} {3}", trantype, transitionid, toid, rangeid); + cc.Text = cc.Text.Replace(lookfor, replacewith); - if (cc.MyGrid != null && cc.MyGrid.Data != "") + + if (cc.MyGrid != null && !string.IsNullOrEmpty(cc.MyGrid.Data)) + { cc.MyGrid.Data = cc.MyGrid.Data.Replace(lookfor, replacewith); + } + // B2016-176, B2016-197 - external transitions should be converted to text forceConvertToText = true; //if (TransitionInfo.Get(tt.TransitionID).MyItemToID.ActiveSection != null) @@ -3421,6 +3580,7 @@ namespace VEPROMS { lblImportStatus.Text = "Creating Folder..."; Application.DoEvents(); + string title = xd.DocumentElement.Attributes.GetNamedItem("title").InnerText; //string name = xd.DocumentElement.Attributes.GetNamedItem("name").InnerText; string shortname = xd.DocumentElement.Attributes.GetNamedItem("shortname").InnerText; @@ -3430,13 +3590,17 @@ namespace VEPROMS XmlNode fnNode = xd.DocumentElement.Attributes.GetNamedItem("formatfilename"); //Bug fix B2016-103 the formatid in an Export file may not match the formatid where you are importing to string formatfilename = (fnNode != null) ? fnNode.InnerText : ""; Format format = formatid == string.Empty ? null : OldToNewFormat(int.Parse(formatid), formatfilename); + if (Folder.GetByParentID_Name(p.FolderID, name) != null) return null; + // B2020-053: procedure set (folder) specific info was not imported: string config = xd.DocumentElement.Attributes.GetNamedItem("config").InnerText; Folder f = Folder.MakeFolder(p, p.MyConnection, name, title, shortname, format, config, dts, usrid); + return f; } + private Format OldToNewFormat(int formatID, string formatFileName) { try @@ -3456,6 +3620,7 @@ namespace VEPROMS return null; // format not found return null to use default format } } + private DocVersion AddDocVersion(Folder f, XmlReader xr) { int versiontype = int.Parse(xr.GetAttribute("versiontype")); @@ -3466,9 +3631,12 @@ namespace VEPROMS string formatid = xr.GetAttribute("formatid"); string formatfilename = xr.GetAttribute("formatfilename"); //Bug fix B2016-103 the formatid in an Export file may not match the formatid where you are importing to Format format = formatid == string.Empty ? null : OldToNewFormat(int.Parse(formatid), formatfilename); + DocVersion dv = DocVersion.MakeDocVersion(f, versiontype, name, null, null, format, config, dts, userid); + return dv; } + private void AddAnnotationTypes(XmlDocument xd) { XmlNodeList nl = xd.SelectNodes("folder/annotationtypes/annotationtype"); @@ -3479,10 +3647,12 @@ namespace VEPROMS AnnotationType.MakeAnnotationType(nd.Attributes.GetNamedItem("name").InnerText, nd.Attributes.GetNamedItem("config").InnerText, DateTime.Parse(nd.Attributes.GetNamedItem("dts").InnerText), nd.Attributes.GetNamedItem("userid").InnerText); } } + private DocVersionInfo AddDocVersion(Folder f, XmlDocument xd) { lblImportStatus.Text = "Creating DocVersion..."; Application.DoEvents(); + XmlElement xe = (XmlElement)xd.SelectSingleNode("folder/docversion"); int versiontype = int.Parse(xe.Attributes.GetNamedItem("versiontype").InnerText); string name = xe.Attributes.GetNamedItem("name").InnerText; @@ -3494,17 +3664,22 @@ namespace VEPROMS XmlNode fnNode = xe.Attributes.GetNamedItem("formatfilename"); //Bug fix B2016-103 the formatid in an Export file may not match the formatid where you are importing to string formatfilename = (fnNode != null) ? fnNode.InnerText : ""; Format format = formatid == string.Empty ? null : OldToNewFormat(int.Parse(formatid), formatfilename); + DocVersion dv = DocVersion.MakeDocVersion(f, versiontype, name, null, null, format, config, dts, userid); XmlNode xassoc = xe.SelectSingleNode("association"); + if (xassoc != null) { XmlNode xrofst = xassoc.SelectSingleNode("rofst"); XmlNode xrodb = xrofst.SelectSingleNode("rodb"); MyRODb = AddRODb(xrodb); ROFst rofst = AddROFst(xrofst); + DocVersionAssociation dva = dv.DocVersionAssociations.Add(rofst); + dv.Save(); } + return DocVersionInfo.Get(dv.VersionID); } @@ -3537,28 +3712,37 @@ namespace VEPROMS { lblImportStatus.Text = "Creating ROFst..."; Application.DoEvents(); + byte[] rolookup = Convert.FromBase64String(xrofst.Attributes.GetNamedItem("rolookup").InnerText); string config = xrofst.Attributes.GetNamedItem("config").InnerText; string userid = xrofst.Attributes.GetNamedItem("userid").InnerText; DateTime dts = DateTime.Parse(xrofst.Attributes.GetNamedItem("dts").InnerText); - ROFst rv = null; - rv = ROFst.GetByRODbID_DTS(MyRODb.RODbID, dts); + + ROFst rv = ROFst.GetByRODbID_DTS(MyRODb.RODbID, dts); + // if the RO database is not found in the current data (does not have the same RODBid nor date/time stamp // then spin through the list of RO databases and compare the FST information. // If the RO FST information is the same, then use that current RO database when importing if (rv == null) { RODbInfoList rodblst = RODbInfoList.Get(); + foreach (RODbInfo roinfo in rodblst) { rv = ROFst.GetByRODbID_DTS(roinfo.RODbID, dts); - if (rv != null && Same(rv.ROLookup, rolookup)) return rv; + if (rv != null && Same(ROFSTLookup.GetRofstLookupBytes(rv.ROFstID), rolookup)) // B2022-026 RO Memory reduction - new calls + { + return rv; + } } + rv = ROFst.MakeROFst(MyRODb, rolookup, config, dts, userid); + XmlNode xfigures = xrofst.SelectSingleNode("figures"); if (xfigures != null) AddFigures(xfigures, rv); } + return rv; } @@ -3576,11 +3760,13 @@ namespace VEPROMS { XmlNode image = nd.SelectSingleNode("image"); int imageid = int.Parse(image.Attributes.GetNamedItem("imageid").InnerText); + using (ROImage roimage = ROImage.GetJustROImage(imageid))//Dispose when done { string config; DateTime dts; string userid; + if (roimage == null) { string filename = image.Attributes.GetNamedItem("filename").InnerText; @@ -3588,12 +3774,14 @@ namespace VEPROMS config = image.Attributes.GetNamedItem("config").InnerText; dts = DateTime.Parse(image.Attributes.GetNamedItem("dts").InnerText); userid = image.Attributes.GetNamedItem("userid").InnerText; + // Dispose when done using (ROImage roimage1 = ROImage.MakeROImage(MyRODb, filename, content, config, dts, userid)) { config = nd.Attributes.GetNamedItem("config").InnerText; dts = DateTime.Parse(nd.Attributes.GetNamedItem("dts").InnerText); userid = nd.Attributes.GetNamedItem("userid").InnerText; + // Dispose when done using (Figure fig = Figure.MakeFigure(rofst, roimage, config, dts, userid)) { ;} } @@ -3606,6 +3794,7 @@ namespace VEPROMS // Dispose when done using (Figure fig = Figure.MakeFigure(rofst, roimage, config, dts, userid)) { ;} } + } } } @@ -3632,6 +3821,7 @@ namespace VEPROMS { lblImportStatus.Text = "Creating RODb..."; Application.DoEvents(); + oldRODbID = int.Parse(xrodb.Attributes.GetNamedItem("rodbid").InnerText); string roname = xrodb.Attributes.GetNamedItem("roname").InnerText; string folderpath = xrodb.Attributes.GetNamedItem("folderpath").InnerText; @@ -3639,27 +3829,35 @@ namespace VEPROMS string config = xrodb.Attributes.GetNamedItem("config").InnerText; string userid = xrodb.Attributes.GetNamedItem("userid").InnerText; DateTime dts = DateTime.Parse(xrodb.Attributes.GetNamedItem("dts").InnerText); - RODb rv = null; - rv = RODb.GetByFolderPath(folderpath); + + RODb rv = RODb.GetByFolderPath(folderpath); + if (rv == null) { // create a list of the RO databases currently in the database List roDbNameList = new List(); RODbInfoList rolist = RODbInfoList.Get(); + foreach (RODbInfo rodbinfo in rolist) { if (!roDbNameList.Contains(rodbinfo.ROName)) roDbNameList.Add(rodbinfo.ROName); } + rolist.Dispose(); int cnt = 0; string roNameNew = roname; + // if the ROname we are importing is the same as one already in the database // and the ROpaths are different, then rename the one we are importing while (roDbNameList.Contains(roNameNew)) + { roNameNew = string.Format("{0}_{1}", roname, (++cnt).ToString()); + } + rv = RODb.MakeRODb(roNameNew, folderpath, dbconnectionstring, config, dts, userid); } + newRODbID = rv.RODbID; return rv; } @@ -3703,6 +3901,7 @@ namespace VEPROMS TimeSpan elapsed = DateTime.Now.Subtract(MyStart); lblImportTime.Text = "Elapsed Time: " + elapsed.ToString(); Application.DoEvents(); + XmlNode xc = xn.SelectSingleNode("content"); string number = xc.Attributes.GetNamedItem("number").InnerText; string text = xc.Attributes.GetNamedItem("text").InnerText; @@ -3712,6 +3911,7 @@ namespace VEPROMS config = StripEnhanced(config); string userid = xc.Attributes.GetNamedItem("userid").InnerText; DateTime dts = DateTime.Parse(xc.Attributes.GetNamedItem("dts").InnerText); + using (Procedure p = Procedure.MakeProcedure(dvInfo, procInfo, number, text, proctype)) { p.DTS = dts; @@ -3719,33 +3919,46 @@ namespace VEPROMS // check for a null in case an older export file is being imported (the older files will not have the fromatfilename attribute) XmlNode fnNode = xc.Attributes.GetNamedItem("formatfilename"); //Bug fix B2016-103 the formatid in an Export file may not match the formatid where you are importing to string formatfilename = (fnNode != null) ? fnNode.InnerText : ""; - if (formatid != string.Empty) - p.MyContent.MyFormat = OldToNewFormat(int.Parse(formatid), formatfilename); + + if (formatid != string.Empty) p.MyContent.MyFormat = OldToNewFormat(int.Parse(formatid), formatfilename); p.MyContent.Config = config; p.MyContent.DTS = dts; p.MyContent.UserID = userid; + p.Save(); + if (!Old2NewItem.ContainsKey(int.Parse(xn.Attributes.GetNamedItem("itemid").InnerText))) Old2NewItem.Add(int.Parse(xn.Attributes.GetNamedItem("itemid").InnerText), p.ItemID); else Old2NewItem[int.Parse(xn.Attributes.GetNamedItem("itemid").InnerText)] = p.ItemID; // B2016-176, B2016-197 refresh saved ItemId with current ItemID + if (!Old2NewContent.ContainsKey(int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText))) Old2NewContent.Add(int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText), p.MyContent.ContentID); else Old2NewContent[int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText)] = p.MyContent.ContentID; // B2016-176, B2016-197 refresh saved ContentID with current ContentID + if (xn.SelectNodes("annotation").Count > 0) AddAnnotations(p.ItemID, xn); + if (xc.SelectNodes("rousage").Count > 0) AddROUsages(p.MyContent, xc); + if (xc.SelectNodes("transition").Count > 0) AddTransitions(p.MyContent, xc); + procInfo = ProcedureInfo.Get(p.ItemID); } + if (xc.HasChildNodes) + { AddParts(xc, procInfo); + } + FixSectionStart(procInfo); + return procInfo; } + // jsj 2016Feb16 - This appears to not be used //private void AddROUsage(XmlReader xr) //{ @@ -3795,6 +4008,14 @@ namespace VEPROMS return text.Substring(start, firstSlashVeeZero + 3); //everything upto \v0" } private void ConvertImportProcedureROsToText(Content content, XmlNode xn) + { + string txt = text.Substring(start); + int firstSlashVeeZero = txt.IndexOf(@"\v0"); + if (firstSlashVeeZero == 0 && txt.Length > 3 && txt[3] == ' ') //"\v0 " + return text.Substring(start, 4); + return text.Substring(start, firstSlashVeeZero + 3); //everything upto \v0" + } + private void ConvertImportProcedureROsToText(Content content, XmlNode xn) { foreach (XmlNode nd in xn.SelectNodes("rousage")) { @@ -3916,10 +4137,14 @@ namespace VEPROMS string config = nd.Attributes.GetNamedItem("config").InnerText; string userid = nd.Attributes.GetNamedItem("userid").InnerText; DateTime dts = DateTime.Parse(nd.Attributes.GetNamedItem("dts").InnerText); + if (MyDocVersion.DocVersionAssociations == null) MyDocVersion.RefreshDocVersionAssociations(); + ROFSTLookup lookup = MyDocVersion.DocVersionAssociations[0].MyROFst.GetROFSTLookup(MyDocVersion); + string roval = lookup.GetRoValue(roid); + if (roval == "?") { RoUsageInfo roui = RoUsageInfo.Get(int.Parse(rousageid)); @@ -3931,27 +4156,34 @@ namespace VEPROMS { RoUsage rou = RoUsage.MakeRoUsage(content, roid, config, dts, userid, MyRODb); rou.Save(); + RoUsageInfo roui = RoUsageInfo.Get(rou.ROUsageID); string lookFor = string.Format("#Link:ReferencedObject:{0} {1} {2}[END>", rousageid, roid, oldRODbID.ToString()); string replaceWith = string.Format("#Link:ReferencedObject:{0} {1} {2}[END>", rou.ROUsageID.ToString(), roid, newRODbID.ToString()); _DidProcessROs = content.Text.Contains(lookFor); // B2017-076 RO link in the text so we will be processing it + if (lookFor != replaceWith) { content.Text = content.Text.Replace(lookFor, replaceWith); content.FixContentText(roui, roval, 0, MyDocVersion.DocVersionAssociations[0].MyROFst); } + if (isGrid) // B2017-060 when importing a grid, also update the grid's xml defination { string glookFor = string.Format("#Link:ReferencedObject:{0} {1} {2}[END>", rousageid, roid, oldRODbID.ToString()); string greplaceWith = string.Format("#Link:ReferencedObject:{0} {1} {2}[END>", rou.ROUsageID.ToString(), roid, newRODbID.ToString()); + if (glookFor != greplaceWith) { content.MyGrid.Data = content.MyGrid.Data.Replace(glookFor, greplaceWith); } } } + } + content.Save(); + if (isGrid) GridInfo.Refresh(content.MyGrid); // force the updated grid (table) to refresh } @@ -4044,6 +4276,7 @@ namespace VEPROMS } } } + private void AddTables(XmlNode xn, ItemInfo parentInfo) { if (parentInfo.IsProcedure) @@ -4061,6 +4294,7 @@ namespace VEPROMS foreach (XmlNode nd in xn.ChildNodes) prevInfo = AddTable(nd, parentInfo, prevInfo); } + // jsj 2016Feb16 - This appears to not be used //private ItemInfo AddTable(XmlReader xr, ItemInfo parentInfo, ItemInfo prevInfo, int oldid) //{ @@ -4090,6 +4324,7 @@ namespace VEPROMS pbImportStep.PerformStep(); lblImportStep.Text = string.Format("{0} of {1} Steps", pbImportStep.Value.ToString(), pbImportStep.Maximum.ToString()); Application.DoEvents(); + XmlNode xc = xn.SelectSingleNode("content"); Step step; string number = xc.Attributes.GetNamedItem("number").InnerText; @@ -4102,6 +4337,7 @@ namespace VEPROMS CheckForFloatingFoldout(contentid, config); string userid = xc.Attributes.GetNamedItem("userid").InnerText; DateTime dts = DateTime.Parse(xc.Attributes.GetNamedItem("dts").InnerText); + using (step = Step.MakeStep(parentInfo, prevInfo, number, text, steptype, E_FromType.Table)) { step.DTS = dts; @@ -4109,36 +4345,50 @@ namespace VEPROMS // check for a null in case an older export file is being imported (the older files will not have the fromatfilename attribute) XmlNode fnNode = xc.Attributes.GetNamedItem("formatfilename"); //Bug fix B2016-103 the formatid in an Export file may not match the formatid where you are importing to string formatfilename = (fnNode != null) ? fnNode.InnerText : ""; + if (formatid != string.Empty) step.MyContent.MyFormat = OldToNewFormat(int.Parse(formatid), formatfilename); + step.MyContent.Config = config; step.MyContent.DTS = dts; step.MyContent.UserID = userid; + step.Save(); + if (!Old2NewItem.ContainsKey(int.Parse(xn.Attributes.GetNamedItem("itemid").InnerText))) Old2NewItem.Add(int.Parse(xn.Attributes.GetNamedItem("itemid").InnerText), step.ItemID); else Old2NewItem[int.Parse(xn.Attributes.GetNamedItem("itemid").InnerText)] = step.ItemID; // B2016-176, B2016-197 refresh saved ItemId with current ItemID + if (!Old2NewContent.ContainsKey(int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText))) Old2NewContent.Add(int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText), step.MyContent.ContentID); else Old2NewContent[int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText)] = step.MyContent.ContentID; // B2016-176, B2016-197 refresh saved ContentID with current ContentID + if (xc.SelectNodes("grid").Count > 0) AddGrid(step.MyContent, xc); + if (xc.SelectNodes("image").Count > 0) AddImage(step.MyContent, xc); + if (xn.SelectNodes("annotation").Count > 0) AddAnnotations(step.ItemID, xn); + if (xc.SelectNodes("rousage").Count > 0) AddROUsages(step.MyContent, xc, true); // part of bug fix: B2017060 to properly convert invalid RO to text + if (xc.SelectNodes("transition").Count > 0) AddTransitions(step.MyContent, xc); + prevInfo = StepInfo.Get(step.ItemID); + if (xc.HasChildNodes) AddParts(xc, prevInfo); } + return prevInfo; } + private void AddSteps(XmlNode xn, ItemInfo parentInfo) { if (parentInfo.IsProcedure) @@ -4187,6 +4437,7 @@ namespace VEPROMS pbImportStep.PerformStep(); lblImportStep.Text = string.Format("{0} of {1} Steps", pbImportStep.Value.ToString(), pbImportStep.Maximum.ToString()); Application.DoEvents(); + XmlNode xc = xn.SelectSingleNode("content"); Step step; string number = xc.Attributes.GetNamedItem("number").InnerText; @@ -4199,6 +4450,7 @@ namespace VEPROMS CheckForFloatingFoldout(contentid, config); string userid = xc.Attributes.GetNamedItem("userid").InnerText; DateTime dts = DateTime.Parse(xc.Attributes.GetNamedItem("dts").InnerText); + using (step = Step.MakeStep(parentInfo, prevInfo, number, text, steptype, E_FromType.Step)) { step.DTS = dts; @@ -4206,32 +4458,44 @@ namespace VEPROMS // check for a null in case an older export file is being imported (the older files will not have the fromatfilename attribute) XmlNode fnNode = xc.Attributes.GetNamedItem("formatfilename"); //Bug fix B2016-103 the formatid in an Export file may not match the formatid where you are importing to string formatfilename = (fnNode != null) ? fnNode.InnerText : ""; + if (formatid != string.Empty) step.MyContent.MyFormat = OldToNewFormat(int.Parse(formatid), formatfilename); + step.MyContent.Config = config; step.MyContent.DTS = dts; step.MyContent.UserID = userid; + step.Save(); + if (!Old2NewItem.ContainsKey(int.Parse(xn.Attributes.GetNamedItem("itemid").InnerText))) Old2NewItem.Add(int.Parse(xn.Attributes.GetNamedItem("itemid").InnerText), step.ItemID); else Old2NewItem[int.Parse(xn.Attributes.GetNamedItem("itemid").InnerText)] = step.ItemID; // B2016-176, B2016-197 refresh saved ItemId with current ItemID + if (!Old2NewContent.ContainsKey(int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText))) Old2NewContent.Add(int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText), step.MyContent.ContentID); else Old2NewContent[int.Parse(xc.Attributes.GetNamedItem("contentid").InnerText)] = step.MyContent.ContentID; // B2016-176, B2016-197 refresh saved ContentID with current ContentID + if (xn.SelectNodes("annotation").Count > 0) AddAnnotations(step.ItemID, xn); + if (xc.SelectNodes("rousage").Count > 0) AddROUsages(step.MyContent, xc); + if (xc.SelectNodes("transition").Count > 0) AddTransitions(step.MyContent, xc); + prevInfo = StepInfo.Get(step.ItemID); + if (xc.HasChildNodes) AddParts(xc, prevInfo); } + return prevInfo; } + private void AddRNOs(XmlNode xn, ItemInfo parentInfo) { if (parentInfo.IsProcedure) @@ -4249,6 +4513,7 @@ namespace VEPROMS foreach (XmlNode nd in xn.ChildNodes) prevInfo = AddRNO(nd, parentInfo, prevInfo); } + private void AddSupInfos(XmlNode xn, ItemInfo parentInfo) { if (parentInfo.IsProcedure) @@ -4266,6 +4531,7 @@ namespace VEPROMS foreach (XmlNode nd in xn.ChildNodes) prevInfo = AddSupInfo(nd, parentInfo, prevInfo); } + // jsj 4-29-2016 appears to not be used //private ItemInfo AddRNO(XmlReader xr, ItemInfo parentInfo, ItemInfo prevInfo, int oldid) //{ @@ -4593,6 +4859,7 @@ namespace VEPROMS foreach (XmlNode nd in xn.ChildNodes) prevInfo = AddSection(nd, parentInfo, prevInfo); } + private Dictionary GetSectionData(XmlReader xr) { Dictionary rv = new Dictionary(); @@ -4682,6 +4949,7 @@ namespace VEPROMS } return prevInfo; } + private string StripEnhanced(string config) { if (config.Length > 0) @@ -4695,6 +4963,7 @@ namespace VEPROMS } return config; } + private void CheckForFloatingFoldout(int contentid, string config) { if (config != string.Empty) @@ -4727,6 +4996,7 @@ namespace VEPROMS XmlDocument xd = new XmlDocument(); xd.LoadXml(data); XmlNode gn = xd.SelectSingleNode("C1FlexGrid/Control/IsRoTable"); + if (gn.InnerText.ToLower() == "true") { if (_ConvertROsToTextDuringImport) @@ -4791,11 +5061,14 @@ namespace VEPROMS data = xd.OuterXml; } } + string config = nd.Attributes.GetNamedItem("config").InnerText; string userid = nd.Attributes.GetNamedItem("userid").InnerText; DateTime dts = DateTime.Parse(nd.Attributes.GetNamedItem("dts").InnerText); Grid gg = Grid.MakeGrid(content, data, config, dts, userid); + gg.Save(); + content.MyGrid = gg; } @@ -4856,8 +5129,8 @@ namespace VEPROMS di.Dispose(); } } - } + private Document AddDocument(XmlNode xn) { Document d=null; @@ -4876,12 +5149,14 @@ namespace VEPROMS // C2019-026 if the lib doc title exists in the current database, compare it with the contents of what we // are importing. If the same, use it, else enter a new lib doc appending the date/time byte[] doccontent = Convert.FromBase64String(xn.Attributes.GetNamedItem("doccontent").InnerText); + if (ExistingLibDocs.ContainsKey(libtitle)) { d = Document.Get(ExistingLibDocs[libtitle]); if (!ByteArrayCompare.DoCompare(d.DocContent,doccontent)) d = null; } + if (d == null) { // B2019-035 better memory management. Prior logic would eat up memory (and not free it). @@ -4890,6 +5165,7 @@ namespace VEPROMS d = Document.Get(ExistingLibDocs[libkey]); // found library document in existing database } } + if (d == null) // not found in existing database, create it { byte[] doccontent = Convert.FromBase64String(xn.Attributes.GetNamedItem("doccontent").InnerText); @@ -4902,7 +5178,9 @@ namespace VEPROMS d.Save(); Old2NewLibDoc.Add(docid, d.DocID); } + } + return d; } #endregion diff --git a/PROMS/VEPROMS User Interface/frmBatchRefresh.cs b/PROMS/VEPROMS User Interface/frmBatchRefresh.cs index 7d110e21..396b2ba3 100644 --- a/PROMS/VEPROMS User Interface/frmBatchRefresh.cs +++ b/PROMS/VEPROMS User Interface/frmBatchRefresh.cs @@ -31,6 +31,7 @@ namespace VEPROMS setupProgessSteps1(); // C2017-030 - new Admin Tools user interface UserInfo ui = UserInfo.GetByUserID(MySessionInfo.UserID); IsAdministratorUser = ui.IsAdministrator(); + if (!IsAdministratorUser) { //C2020-035 if not full Admin disable repair tools @@ -176,6 +177,15 @@ namespace VEPROMS tnc = tmp; } } + else + { + if (tnc != null && tnc.Text != "VEPROMS") // B2020-114 - mad if statement removed: && !IsUsedPath(tnc.FullPath)) + { + TreeNode tmp = tnc.Parent; + tnc.Remove(); + tnc = tmp; + } + } } return rtnval; } @@ -253,7 +263,7 @@ namespace VEPROMS if (dvil.Count > 0) { StringBuilder sb = new StringBuilder(); - sb.AppendLine("The batch update process was not usccessful for all working drafts selected."); + sb.AppendLine("The batch update process was not successful for all working drafts selected."); sb.AppendLine("The following working drafts were not able to be refreshed..."); sb.AppendLine(); sb.AppendLine(sbDocVersions.ToString()); @@ -536,8 +546,7 @@ namespace VEPROMS this.Cursor = Cursors.Default; } - // C2017-030 - new Admin Tools user interface - // is one of two tools run from Remove Obsolete RO Data + // C2017-030 - new Admin Tools user interface is one of two tools run from Remove Obsolete RO Data private void RemoveUnusedRoFstsAndFigures() { this.Cursor = Cursors.WaitCursor; @@ -621,6 +630,21 @@ namespace VEPROMS DateTime pEnd = DateTime.Now; txtProcess.AppendText(string.Format("Completed: {0}",pEnd.ToString("MM/dd/yyyy @ HH:mm"))); txtProcess.AppendText(Environment.NewLine); + if (rowCount > 0) + { + txtResults.AppendText(string.Format("The database contains {0} unused RO Associations.", rowCount)); + txtResults.AppendText(Environment.NewLine); + txtResults.AppendText(Environment.NewLine); + } + else + { + txtResults.AppendText("No unused RO Associations Found");// B2017-108 Always output results even if there isn't any + txtResults.AppendText(Environment.NewLine); + txtResults.AppendText(Environment.NewLine); + } + DateTime pEnd = DateTime.Now; + txtProcess.AppendText(string.Format("Completed: {0}",pEnd.ToString("MM/dd/yyyy @ HH:mm"))); + txtProcess.AppendText(Environment.NewLine); txtProcess.AppendText(Environment.NewLine); Application.DoEvents(); this.Cursor = Cursors.Default; @@ -744,6 +768,7 @@ namespace VEPROMS txtResults.AppendText(statmsg); txtResults.AppendText(Environment.NewLine); Application.DoEvents(); + if (dq.DocVersionAssociationCount < 1) { ProgressBar.ColorTable = eProgressBarItemColor.Error; @@ -758,8 +783,11 @@ namespace VEPROMS txtResults.AppendText(Environment.NewLine); return; } + ROFstInfo roFstInfo = dq.DocVersionAssociations[0].MyROFst; string rofstPath = roFstInfo.MyRODb.FolderPath + @"\ro.fst"; + + //if (!pathExists(rofstPath)) if (!File.Exists(rofstPath)) { ProgressBar.ColorTable = eProgressBarItemColor.Error; @@ -774,14 +802,24 @@ namespace VEPROMS txtResults.AppendText(Environment.NewLine); return; } - FileInfo fiRofst = new FileInfo(rofstPath); + + //FileInfo fiRofst = new FileInfo(rofstPath); Cursor = Cursors.WaitCursor; + using (DocVersion dv = DocVersion.Get(dq.VersionID)) { + // B2022-026 RO Memory Reduction code - first load the new ro.fst so that we can assign the ROTableUpdate event to the correct roFstInfo + if (dv.ROfstLoadingFigures || dv.NewerRoFst) // B2017-125 see if loading figures was completed + { + // only load the RO.fst + ROFstInfo.UpdateRoFst(roFstInfo.MyRODb, dv, roFstInfo, DoProgressBarRefresh); + roFstInfo = dq.DocVersionAssociations[0].MyROFst; + } roFstInfo.ROTableUpdate += new ROFstInfoROTableUpdateEvent(roFstInfo_ROTableUpdate); - ROFst newrofst = ROFstInfo.RefreshROFst(roFstInfo.MyRODb, dv.DocVersionAssociations[0], dv, roFstInfo, DoProgressBarRefresh, txtProcess); + ROFst newrofst = ROFstInfo.RefreshROFst(dv, roFstInfo, DoProgressBarRefresh, txtProcess); roFstInfo.ROTableUpdate -= new ROFstInfoROTableUpdateEvent(roFstInfo_ROTableUpdate); } + Cursor = Cursors.Default; ProgressBar.ColorTable = eProgressBarItemColor.Normal; FinalProgressBarMessage = "ROs values updated"; @@ -790,6 +828,7 @@ namespace VEPROMS txtResults.AppendText("ROs values updated"); txtResults.AppendText(Environment.NewLine); txtResults.AppendText(Environment.NewLine); + return; } @@ -890,6 +929,7 @@ namespace VEPROMS sfd.FileName = string.Format("BatchRefreshResults_{0}", DateTime.Now.ToString("yyyyMMdd_HHmm")); sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\VEPROMS"; DialogResult dr = sfd.ShowDialog(); + if (dr == DialogResult.OK) { System.IO.StreamWriter sw = new System.IO.StreamWriter(sfd.FileName); @@ -901,8 +941,13 @@ namespace VEPROMS private void myTV_AfterCheck(object sender, TreeViewEventArgs e) { if (e.Action != TreeViewAction.Unknown) - if(e.Node.Nodes.Count > 0) + { + if (e.Node.Nodes.Count > 0) + { CheckChildNodes(e.Node, e.Node.Checked); + } + } + btnFixLinks.Enabled = AtLeastOneNodeChecked(); // C2017-030 support for Refresh Transitions/Update RO Values } @@ -911,12 +956,16 @@ namespace VEPROMS foreach (TreeNode tn in treeNode.Nodes) { tn.Checked = ischecked; + if (tn.Nodes.Count > 0) + { CheckChildNodes(tn, ischecked); + } } } private ProgressBarItem _ProgressBar = null; + public ProgressBarItem ProgressBar { get { return _ProgressBar; } @@ -930,9 +979,11 @@ namespace VEPROMS private void DoProgressBarRefresh(int value, int max, string text) { if (ProgressBar == null) return; + ProgressBar.Maximum = max; ProgressBar.Value = value; ProgressBar.Text = text; + Application.DoEvents(); } @@ -941,12 +992,14 @@ namespace VEPROMS set { if (ProgressBar == null) return; + ProgressBar.Maximum = 100; ProgressBar.Value = 0; ProgressBar.Text = value; txtProcess.AppendText(value); txtProcess.AppendText(Environment.NewLine); txtProcess.AppendText(Environment.NewLine); + Application.DoEvents(); } } @@ -956,12 +1009,14 @@ namespace VEPROMS set { if (ProgressBar == null) return; + ProgressBar.Value = 100; ProgressBar.Maximum = 100; ProgressBar.Text = value; txtProcess.AppendText(value); txtProcess.AppendText(Environment.NewLine); txtProcess.AppendText(Environment.NewLine); + Application.DoEvents(); } } @@ -985,8 +1040,11 @@ namespace VEPROMS AdminToolType = E_AdminToolType.Repair; lblAdmToolProgressType.Text = "Repairing:"; setupProgessSteps1(); + if (!IsAdministratorUser) // C2020-035 notify Set Amin user that only Full Admins can run repair tools - MessageBox.Show("Only Full PROMS Administrator Users can run these data repair tools","Data Repair Tools",MessageBoxButtons.OK,MessageBoxIcon.Exclamation); + { + MessageBox.Show("Only Full PROMS Administrator Users can run these data repair tools", "Data Repair Tools", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); + } } // C2017-030 new Admin Tools user interface @@ -994,6 +1052,7 @@ namespace VEPROMS { AdminToolType = E_AdminToolType.Links; setupProgessSteps1(); + if (swUpdateROVals.Value) ResetTV(true); else @@ -1014,6 +1073,7 @@ namespace VEPROMS } #region On/Off Swiches + // C2017-030 new Admin Tools user interface private enum E_AdminToolType : int { @@ -1035,6 +1095,7 @@ namespace VEPROMS { progressSteps1.Visible = false; progressSteps1.Items.Clear(); + switch (AdminToolType) { case E_AdminToolType.Check: @@ -1048,6 +1109,7 @@ namespace VEPROMS progressSteps1.Visible = true; progressSteps1.Refresh(); break; + case E_AdminToolType.Repair: if (swRmOrphanDataRecs.Value) progressSteps1.Items.Add(siOrphDatRecs); @@ -1061,6 +1123,7 @@ namespace VEPROMS progressSteps1.Visible = true; progressSteps1.Refresh(); break; + case E_AdminToolType.Links: case E_AdminToolType.Users: splitContainer3.Panel2Collapsed = true; @@ -1068,6 +1131,7 @@ namespace VEPROMS break; } } + // used for all of the Switch buttons (ON/OFF buttons) private void swCk_ValueChanged(object sender, EventArgs e) { @@ -1091,6 +1155,7 @@ namespace VEPROMS ResetTV(false); } } + #endregion // C2017-030 New Admin Tools user interface @@ -1100,15 +1165,17 @@ namespace VEPROMS ((DevComponents.DotNetBar.StepItem)progressSteps1.Items[prgStpIdx]).Value = val; return; } + private void ClearStepProgress() { for (int i = 0; i < progressSteps1.Items.Count; i++) + { ((DevComponents.DotNetBar.StepItem)progressSteps1.Items[i]).Value = 0; + } } // C2017-030 New Admin Tools user interface // button clicks for processing selected tools - //B2017-221 Allow the batch dialog to close when waiting to process. private bool CheckProcessLater() // see if we should delay processing until later { @@ -1116,6 +1183,7 @@ namespace VEPROMS { long later = long.Parse(dtpDate.Value.ToString("yyyyMMdd") + dtpTime.Value.ToString("HHmm")); long now = long.Parse(DateTime.Now.ToString("yyyyMMddHHmm")); + while (now < later) { txtProcess.Clear(); @@ -1126,6 +1194,7 @@ namespace VEPROMS now = long.Parse(DateTime.Now.ToString("yyyyMMddHHmm")); } } + return true;// Close after complete } @@ -1133,18 +1202,23 @@ namespace VEPROMS private void btn_ShowUsers_Click(object sender, EventArgs e) { if (!CheckProcessLater()) return; // delay processing if set//B2017-221 Allow the batch dialog to close when waiting to process. + txtProcess.Clear(); txtResults.Clear(); + GetDatabaseSessions(); } private void btnFixLinks_Click(object sender, EventArgs e) { if (!CheckProcessLater()) return; // delay processing if set//B2017-221 Allow the batch dialog to close when waiting to process. + txtProcess.Clear(); txtResults.Clear(); + if (swRefreshTrans.Value) RefreshTransitions(); + if (swUpdateROVals.Value) UpdateROValues(); } @@ -1152,21 +1226,25 @@ namespace VEPROMS private void btnRunCheck_Click(object sender, EventArgs e) { if (!CheckProcessLater()) return; // delay processing if set//B2017-221 Allow the batch dialog to close when waiting to process. + int prgStpIdx = -1; txtResults.Clear(); txtProcess.Clear(); + if (swCkOrphanDataRecs.Value) { StepProgress(++prgStpIdx, 50); IdentifyDisconnectedItems(); // orphan items StepProgress(prgStpIdx, 100); } + if (swHiddenDataLocs.Value) { StepProgress(++prgStpIdx, 50); IdentifyNonEditableItems(); // hidden items StepProgress(prgStpIdx, 100); } + if (swCkObsoleteROData.Value) { StepProgress(++prgStpIdx, 25); @@ -1175,22 +1253,27 @@ namespace VEPROMS IdentifyUnusedRoFstsAndFigures(); StepProgress(prgStpIdx, 100); } + MessageBox.Show("Check Functions Completed", "Check"); + ClearStepProgress(); } private void btnRunRepair_Click(object sender, EventArgs e) { if (!CheckProcessLater()) return; // delay processing if set//B2017-221 Allow the batch dialog to close when waiting to process. + int prgStpIdx = -1; txtResults.Clear(); txtProcess.Clear(); + if (swRmOrphanDataRecs.Value) { StepProgress(++prgStpIdx, 50); PurgeDisconnectedItems(); // Orphan Items StepProgress(prgStpIdx, 100); } + if (swRmObsoleteROData.Value) { StepProgress(++prgStpIdx, 25); @@ -1199,12 +1282,14 @@ namespace VEPROMS RemoveUnusedRoFstsAndFigures(); StepProgress(prgStpIdx, 100); } + if (swStandardHypenChars.Value) { StepProgress(++prgStpIdx, 50); FixHyphens(); StepProgress(prgStpIdx, 100); } + if (swRefreshWordAttmts.Value) { StepProgress(++prgStpIdx, 50); @@ -1213,6 +1298,7 @@ namespace VEPROMS } MessageBox.Show("Repair Functions Completed", "Repair"); + ClearStepProgress(); } diff --git a/PROMS/VEPROMS User Interface/frmPDFStatusForm.cs b/PROMS/VEPROMS User Interface/frmPDFStatusForm.cs index 5e69d58f..6b43b126 100644 --- a/PROMS/VEPROMS User Interface/frmPDFStatusForm.cs +++ b/PROMS/VEPROMS User Interface/frmPDFStatusForm.cs @@ -86,28 +86,37 @@ namespace VEPROMS { // B2021-088 moved this if/else from CreatePDF() so that the Approval logic will have access to this logic ProcedureInfo MyProcedure = myItem as ProcedureInfo; + if (MyProcedure.MyDocVersion.DocVersionConfig.SelectedSlave > 0 || MyProcedure.ActiveFormat.PlantFormat.FormatData.TransData.UseTransitionModifier || MyProcedure.ActiveFormat.PlantFormat.FormatData.TransData.UseSpecificTransitionModifier) MyProcedure = ProcedureInfo.GetItemAndChildrenByUnit(MyProcedure.ItemID, 0, MyProcedure.MyDocVersion.DocVersionConfig.SelectedSlave); else MyProcedure = ProcedureInfo.GetItemAndChildren(MyProcedure.ItemID); + // B2021-102 moved the baseline meta file write here too - should have been done with B2021-088 fix // C2018-015 add the procedure tree path and the procedure number and title to the meta file if (BaselineMetaFile.IsOpen) BaselineMetaFile.WriteLine("!! {0}", MyProcedure.SearchDVPath.Replace("\a", " | ")); if (BaselineMetaFile.IsOpen) BaselineMetaFile.WriteLine("!! {0} | {1}", MyProcedure.DisplayNumber, MyProcedure.DisplayText); + myItem = MyProcedure; Prefix = prefix; OpenPDF = openPDF; DidAll = didAll; + InitializeComponent(); + // if the version number of PROMS is 1.0, then we are running a Demo version. // When running a Demo version, force a "Sample" watermark when printing. // B2020-022 append a ".pdf" extension if the file name does on have one. MyPromsPrinter = new PromsPrinter(myItem, rev, (VlnSettings.ReleaseMode.Equals("DEMO")) ? "Sample" : watermark, debugOutput, origPgBrk, pdfPath + @"\Compare", false, overWrite, cbd, (pdfFile.ToUpper().EndsWith(".PDF"))?pdfFile:pdfFile+".pdf", insertBlankPages, allOrAuto,Prefix,saveLinks,removeTrailingHardReturnsAndManualPageBreaks, blankPageText, DidAll, mergedPdf, watermarkColor); + MyPromsPrinter.PromsVersion = (showPROMSVer) ? AboutVEPROMS.PROMSVersion : ""; //C2018-009 print PROMS version + + PDFPath = pdfPath; this.Text = "Creating PDF of " + myItem.DisplayNumber; _NewLocation = newLocation; + DialogResult = DialogResult.OK; } public static void SetUnitWatermark(ProcedureInfo procInfo, ref string waterMarkText, ref string watermarkColor) @@ -156,6 +165,7 @@ namespace VEPROMS } void pp_StatusChanged(object sender, PromsPrintStatusArgs args) { + if (args.Type == PromsPrinterStatusType.ProgressSetup) pb.Maximum = args.Progress; else if (args.Type == PromsPrinterStatusType.Progress) @@ -168,6 +178,7 @@ namespace VEPROMS } MyStatus = args.MyStatus; Application.DoEvents(); + } public string MyStatus { @@ -210,13 +221,17 @@ namespace VEPROMS tmrRun.Enabled = false; if (CancelStop) btnCancel.Visible = true; Application.DoEvents(); + MyPromsPrinter.StatusChanged += new PromsPrinterStatusEvent(pp_StatusChanged); MyPromsPrinter.DocReplace = DocReplace; // used when approve generates an export with unlinked ROs and Transitions + DateTime tStart = DateTime.Now; if (!CancelStop) PromsPrinter.ClearTransPageNumProblems(); + // B2018-029: delete any pdf files related to printing supplemental information facing pages: - // B2018-039 Delete only pdf files that begin with "SupInof" - string[] filePaths = System.IO.Directory.GetFiles(Volian.Base.Library.VlnSettings.TemporaryFolder, "SupInfo*.pdf"); + // B2018-039 Delete only pdf files that begin with "SupInof" + string[] filePaths = System.IO.Directory.GetFiles(Volian.Base.Library.VlnSettings.TemporaryFolder, "SupInfo*.pdf"); + foreach (string filePath in filePaths) System.IO.File.Delete(filePath); do @@ -224,46 +239,59 @@ namespace VEPROMS int profileDepth = ProfileTimer.Push(">>>> MyPromsPrinter.Print"); // B2018-099: remove cache items for contents, items and parts to prevent out of memory errors when // doing print all or automated print testing or approval of some or all procedures, i.e. HashSet and use of them below. + HashSet cacheContentInfo = null; HashSet cacheItemInfo = null; HashSet cachePartInfo = null; + if (DidAll) { cacheContentInfo = ContentInfo.CacheList; cacheItemInfo = ItemInfo.CacheList; cachePartInfo = PartInfo.CacheList; } + _PdfFile = MyPromsPrinter.Print(PDFPath, MakePlaceKeeper, MakeContinuousActionSummary); + ProfileTimer.Pop(profileDepth); + if (DidAll) { ContentInfo.RestoreCacheList(cacheContentInfo); ItemInfo.RestoreCacheList(cacheItemInfo); PartInfo.RestoreCacheList(cachePartInfo); } + } while (!MyPromsPrinter.MergeNotIncluded && _PdfFile == null && MessageBox.Show("Try Again?", "PDF Creation Failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes); + + if (_PdfFile == null) { this.Close(); return; } + if (!CancelStop) { if (PromsPrinter.ReportTransPageNumProblems() == DialogResult.Yes && MyPromsPrinter.BeforePageNumberPdf != null) { System.Diagnostics.Process.Start(MyPromsPrinter.BeforePageNumberPdf); + // C2017-018 - Open Pass 2 output if it exists if (MyPromsPrinter.BeforePageNumber2Pdf != null) System.Diagnostics.Process.Start(MyPromsPrinter.BeforePageNumber2Pdf); } } + DateTime tEnd = DateTime.Now; MyStatus = _PdfFile + " created."; MyStatus = string.Format("{0} created in {1:0.} milliseconds", _PdfFile, (TimeSpan.FromTicks(tEnd.Ticks - tStart.Ticks).TotalMilliseconds)); + if (OpenPDF) { OpenPDFandPlacekeeper(_PdfFile); this.Close(); + // C2021-010: Remove trailing returns/spaces & manual page breaks & allow save. Ask if user wants to save chanages // if they were found. if ((MyPromsPrinter.RemoveManualPageBreaks != null && MyPromsPrinter.RemoveManualPageBreaks.Count > 0) @@ -281,6 +309,7 @@ namespace VEPROMS } return; } + btnOpenFolder.Visible = btnOpenPDF.Visible = true; if (CloseWhenDone) @@ -290,11 +319,13 @@ namespace VEPROMS return; } } + private void btnOpenPDF_Click(object sender, EventArgs e) { OpenPDFandPlacekeeper(_PdfFile); this.Close(); } + // set a delay so that the word document containing the newly generated placekeeper will appear on top of everything else. // - requested by Calvert Cliffs private void OpenPDFandPlacekeeper(string pdffile) @@ -304,32 +335,41 @@ namespace VEPROMS if ((pdffile ?? "") != "" && !OnlyShowContinuousActionSummary) { System.Diagnostics.Process sdp = System.Diagnostics.Process.Start(pdffile); + if (sdp != null) sdp.WaitForInputIdle(); } + if (OnlyShowContinuousActionSummary) System.IO.File.Delete(pdffile); // remove the temporary PDF file used to create the Continuous Action Summary + if (MyPromsPrinter.MyPlacekeeper != null) { // The PlacekeeperDelay is a switch that can be added to the PROMS.exe shortcut // ex: VEPROMS.EXE /PlacekeeperDelay=2.5 will delay it 2 1/2 seconds float delay = Volian.Base.Library.VlnSettings.GetCommandFloat("PlacekeeperDelay", 3.0f); + int mydelay = (int)(1000 * delay); System.Threading.Thread.Sleep(mydelay); + MyPromsPrinter.MyPlacekeeper.Visible(); } + // this will display the generated Continuous Action Summary in MS Word (starting a new instance of MS Word outside of PROMS) if (MyPromsPrinter.MyContActSummary != null) { string instructions = "The Continuous Action Summary will be opened in MS Word.\n\nYou can make modifications and copy it into a PROMS Word section."; MessageBox.Show(instructions, "Continuous Action Summary"); + // The ContActSummaryDelay is a switch that can be added to the PROMS.exe shortcut // ex: VEPROMS.EXE /ContActSummaryDelay=2.5 will delay it 2 1/2 seconds float delay = Volian.Base.Library.VlnSettings.GetCommandFloat("ContActSummaryDelay", 1.0f); int mydelay = (int)(1000 * delay); System.Threading.Thread.Sleep(mydelay); + MyPromsPrinter.MyContActSummary.Visible(); } + } catch (Exception ex) { @@ -337,12 +377,14 @@ namespace VEPROMS MessageBox.Show(str, "Error Opening PDFFile", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } + private void btnOpenFolder_Click(object sender, EventArgs e) { System.Diagnostics.Process.Start("Explorer", "/select," + _PdfFile); OpenPDFandPlacekeeper(null); this.Close(); } + private void btnCancel_Click(object sender, EventArgs e) { CancelPrinting = true; diff --git a/PROMS/VEPROMS User Interface/frmVEPROMS.cs b/PROMS/VEPROMS User Interface/frmVEPROMS.cs index fc9d1861..5b0b2620 100644 --- a/PROMS/VEPROMS User Interface/frmVEPROMS.cs +++ b/PROMS/VEPROMS User Interface/frmVEPROMS.cs @@ -189,9 +189,9 @@ namespace VEPROMS 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.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 } @@ -324,8 +324,8 @@ namespace VEPROMS 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(); + Properties.Settings.Default.DefaultDB = Database.SelectedDatabase; + Properties.Settings.Default.Save(); } displayBookMarks.SetupBookMarks(); DateTime dtSunday = DateTime.Now.AddDays(-((int)DateTime.Now.DayOfWeek)); @@ -348,6 +348,8 @@ namespace VEPROMS tc.SeparateWindows = Properties.Settings.Default.SeparateWindows; tv.PauseRefresh += tv_PauseRefresh; tv.UnPauseRefresh += tv_UnPauseRefresh; + + } void displaySearch1_SearchComplete(object sender, DisplaySearchEventArgs args) { @@ -432,7 +434,7 @@ namespace VEPROMS tv.Processing += tv_Processing; tv.CreateContinuousActionSummary += new vlnTreeViewEvent(tv_CreateContinuousActionSummary); tv.SelectDateToStartChangeBars += tv_SelectDateToStartChangeBars; - displayBookMarks.ResetBookMarksInPROMSWindows += displayBookMarks_ResetBookMarksInPROMSWindows; + displayBookMarks.ResetBookMarksInPROMSWindows += displayBookMarks_ResetBookMarksInPROMSWindows; } // Part of Separate Windows upgrade C2015-022 @@ -1284,10 +1286,10 @@ namespace VEPROMS VolianTimer.ShowTimers(); foreach (DisplayTabItem dti in tc.MyBar.Items) { - if (dti.MyDSOTabPanel != null) - dti.MyDSOTabPanel.CloseDSO(); - else - MySessionInfo.CheckInItem(dti.OwnerID); //C2015-022 Separate Windows closing child form only left procedure ownership active + if (dti.MyDSOTabPanel != null) + dti.MyDSOTabPanel.CloseDSO(); + else + MySessionInfo.CheckInItem(dti.OwnerID); //C2015-022 Separate Windows closing child form only left procedure ownership active } //_MyLog.WarnFormat("frmVEPROMS_FormClosing"); if (MyParent == null) @@ -2767,6 +2769,7 @@ namespace VEPROMS /// private void tmrTreeView_Tick(object sender, EventArgs e) { + _TimeActivity2.Open(); bool giveTvFocus = true; @@ -3231,6 +3234,7 @@ namespace VEPROMS displayRO.MyRTB = (SelectedStepTabPanel == null) ? null : SelectedStepTabPanel.MyStepPanel.SelectedEditItem == null ? null : SelectedStepTabPanel.MyStepPanel.SelectedEditItem.MyStepRTB; displayRO.ProgressBar = bottomProgBar; + displayRO.LoadTree(); // B2022-026 RO Memory Reduction code } #endregion #region InfoTabTransition @@ -3385,6 +3389,8 @@ namespace VEPROMS } private void tc_SelectedDisplayTabItemChanged(object sender, EventArgs args) { + if (tc.ShuttingDown) return; // B2022-026 RO Memory Reduction code - to prevent refreshing the RO tree again + // If the current procedure or section in the treeview doesn't match then change the treeview selection. //jcb added for error B2012-117 ItemInfo tvii; @@ -3413,7 +3419,10 @@ namespace VEPROMS SetCaption(tv.SelectedNode as VETreeNode); displayApplicability.MyDisplayTabItem = tc.SelectedDisplayTabItem; if (tc.SelectedDisplayTabItem.MyItemInfo.MyDocVersion.DocVersionAssociationCount > 0) + { displayRO.MyROFSTLookup = tc.SelectedDisplayTabItem.MyItemInfo.MyDocVersion.DocVersionAssociations[0].MyROFst.GetROFSTLookup(tc.SelectedDisplayTabItem.MyItemInfo.MyDocVersion); + displayRO.LoadTree(); // B2022-026 RO Memory Reduction code + } lblUser.Text = tc.SelectedDisplayTabItem.MyUserRole; if (tc.SelectedDisplayTabItem.MyItemInfo.MyDocVersion.MultiUnitCount > 1) btnPrint.Visible = false; @@ -3471,21 +3480,19 @@ namespace VEPROMS private void tc_ItemSelectedChanged(object sender, ItemSelectedChangedEventArgs args) { tc.HideTheCaret(); - //if (args.MyEditItem != null) - //Volian.Base.Library.vlnStackTrace.ShowStackLocal(2,10,"Edit item {0}, Step Panel {1}",args.MyEditItem.MyStepRTB.ContainsFocus, args.MyEditItem.MyStepPanel.ContainsFocus); - if (args != null && args.MyEditItem != null && !args.MyEditItem.MyStepPanel.ContainsFocus) return; - //if (args != null && args.MyEditItem != null && !args.MyEditItem.MyStepPanel.ContainsFocus) - //{ - // _RefreshRTB = args.MyEditItem.MyStepRTB; - // TmrRefreshItem.Enabled = true; - // return; - //} + + if (args != null && args.MyEditItem != null && !args.MyEditItem.MyStepPanel.ContainsFocus) + return; + btnFixMSWord.Visible = (args != null && ( args.MyItemInfo != null && args.MyEditItem == null)); + if (_LastStepRTB != null && !_LastStepRTB.Disposing && !_LastStepRTB.Closed) _LastStepRTB.EditModeChanged -= new StepRTBEvent(_LastStepRTB_EditModeChanged); + _LastStepRTB = args != null && args.MyEditItem != null ? args.MyEditItem.MyStepRTB : null; if (_LastStepRTB != null) _LastStepRTB.EditModeChanged += new StepRTBEvent(_LastStepRTB_EditModeChanged); lblEditView.Text = " "; + if (args == null) { _CurrentItem = null; @@ -3507,12 +3514,13 @@ namespace VEPROMS { lblItemID.Text = string.Format("ItemID = {0}", args.MyItemInfo.ItemID); lblItemID.ForeColor = Color.DarkBlue; + if (_CurrentItem != args.MyItemInfo) { if (_CurrentItem != null) _CurrentItem.Deleted -= new ItemInfoEvent(_CurrentItem_Deleted); _CurrentItem = args.MyItemInfo; } - //vlnStackTrace.ShowStack("enter tc_ItemSelectedChanged {0}", _CurrentItem); + if (args.MyEditItem == null) { ctrlAnnotationDetails.Enabled = false; @@ -3520,12 +3528,15 @@ namespace VEPROMS infotabFoldoutMaint.Visible = false; infotabTransition.Visible = false; infotabRO.Visible = false; + if (args.MyItemInfo.MyDocVersion.DocVersionAssociations != null) { displayRO.MyROFST = args.MyItemInfo.MyDocVersion.DocVersionAssociations[0].MyROFst; displayRO.MyRTB = null; infotabRO.Visible = true; + displayRO.LoadTree(); // B2022-026 RO Memory Reduction code } + infotabTags.Visible = false; infotabApplicability.Visible = false; // Not sure why but the following line was causing a hang if @@ -3613,10 +3624,14 @@ namespace VEPROMS displayTags.MyEditItem = args.MyEditItem; displayRO.ROTypeFilter = SelectedStepTabPanel.MyStepPanel.SelectedEditItem is Volian.Controls.Library.GridItem && (SelectedStepTabPanel.MyStepPanel.SelectedEditItem as Volian.Controls.Library.GridItem).MyFlexGrid.IsRoTable ? E_ROValueType.Table : (SelectedStepTabPanel.MyStepPanel.SelectedEditItem.MyItemInfo.IsFigure) ? E_ROValueType.Image : E_ROValueType.Text; + displayRO.LoadTree(); // B2022-026 RO Memory Reduction code + if (_LastStepRTB.IsRoTable && _LastStepRTB.MyItemInfo.MyContent.ContentRoUsageCount > 0) displayRO.CurROLink = _LastStepRTB.MyItemInfo.MyContent.ContentRoUsages[0]; + if (_LastStepRTB.IsRoFigure && _LastStepRTB.MyItemInfo.MyContent.ContentRoUsageCount > 0) displayRO.CurROLink = _LastStepRTB.MyItemInfo.MyContent.ContentRoUsages[0]; + // if this is an enhanced step (linked from a source document), don't bring up the ro or transition panel, // and don't allow replace on the find/replace dialog. if (args.MyItemInfo.IsEnhancedStep) @@ -3642,6 +3657,7 @@ namespace VEPROMS displayRO.MyROFST = args.MyItemInfo.MyDocVersion.DocVersionAssociations[0].MyROFst; } displayRO.ROTypeFilter = E_ROValueType.All; // allow all RO types for Word attachments (but fix) + displayRO.LoadTree(); // B2022-026 RO Memory Reduction code displayRO.SetFindDocROButton(true); } } @@ -3654,8 +3670,10 @@ namespace VEPROMS { ctrlAnnotationDetails.UpdateAnnotationGrid(_CurrentItem); // set the CurrentItem (send Message) when the MSWord section is opened. } + btnPrint.Enabled = (_CurrentItem != null); } + /*KBR:Timer _tmrSetTransROInVisible; public Timer TmrSetTransROInVisible { @@ -3750,6 +3768,7 @@ namespace VEPROMS E_ROValueType.Table : (SelectedStepTabPanel.MyStepPanel.SelectedEditItem.MyItemInfo.IsFigure) ? E_ROValueType.Image: E_ROValueType.Text; //displayRO.Mydvi = SelectedDVI; displayRO.ProgressBar = bottomProgBar; + displayRO.LoadTree(); // B2022-026 RO Memory Reduction code } #endregion #region VButton diff --git a/PROMS/VEPROMS User Interface/frmVersionsProperties.cs b/PROMS/VEPROMS User Interface/frmVersionsProperties.cs index 294408e9..9c54446b 100644 --- a/PROMS/VEPROMS User Interface/frmVersionsProperties.cs +++ b/PROMS/VEPROMS User Interface/frmVersionsProperties.cs @@ -20,17 +20,20 @@ namespace VEPROMS { public partial class frmVersionsProperties : DevComponents.DotNetBar.Office2007Form { + #region Fields + + public bool _showApplicSearchResults = false; + public bool _refreshProcedureList = false; + private List _Apples; private List _DeletedApples; private List _Enhanced; - private bool _Initializing = false; private DocVersionConfig _DocVersionConfig; - + // Default values private string _DefaultFormatName = null; private string _DefaultROPrefix = null; private string _DefaultImagePrefix = null; - //private string _DefaultPagination = null; private string _DefaultWatermark = null; private string _DefaultChgBarType = null; private string _DefaultChgBarLoc = null; @@ -40,16 +43,28 @@ namespace VEPROMS private bool _DefaultDisableDuplex = false; private DisplaySearch _DisplaySearch1 = null; + private bool _Initializing = false; + private System.IO.StreamWriter swROUpdate; + private ProgressBarItem _ProgressBar = null; + private RODbInfo _CurRoDbInfo = null; + private ROFstInfo _SelectedROFst; + private List NewEnhVersions = new List(); + private bool doingNew = false; + private bool _EnhNeedToUnlink = false; + private int _InitialIndex = -2; // added as part of code change C2017-004. this also makes it consistent with section properties + private int? _cmbxformatOriginal = null; + + #endregion + + #region Properties + public DisplaySearch DisplaySearch1 { get { return _DisplaySearch1; } set { _DisplaySearch1 = value; } } - - // For the initial release, we are assuming there will be only one rofst for a docversion. Changes - // will be needed here if more than 1. - private ROFstInfo _SelectedROFst; + // For the initial release, we are assuming there will be only one rofst for a docversion. Changes will be needed here if more than 1. public ROFstInfo SelectedROFst { get @@ -59,313 +74,92 @@ namespace VEPROMS if (_DocVersionConfig.MyDocVersion.DocVersionAssociationCount < 1) return null; _SelectedROFst = ROFstInfo.GetJustROFst(_DocVersionConfig.MyDocVersion.DocVersionAssociations[0].ROFstID); } + return _SelectedROFst; } set { _SelectedROFst = value; } } - // + + public ProgressBarItem ProgressBar + { + get { return _ProgressBar; } + set { _ProgressBar = value; } + } + + #endregion + + #region Constructors public frmVersionsProperties(DocVersionConfig docVersionConfig) { _DocVersionConfig = docVersionConfig; docVersionConfig.RefreshMyEnhancedDocuments(); + _Initializing = true; InitializeComponent(); btnGeneral.PerformClick(); // always start with General tab or button _Initializing = false; + //build the caption this.Text = string.Format("{0} Properties", _DocVersionConfig.Name); } - private string AddSlaveNode(MiniConfig mc) - { - System.Xml.XmlDocument xd = new System.Xml.XmlDocument(); - xd.LoadXml(_DocVersionConfig.ToString()); - System.Xml.XmlNodeList nl = xd.SelectNodes("//Slave"); - int max = 0; - foreach (System.Xml.XmlNode n in nl) - { - max = int.Parse(n.Attributes.GetNamedItem("index").InnerText); - } - max++; - System.Xml.XmlNode nn = xd.CreateElement("Slave"); - AddSlaveAttribute(nn, "index", max.ToString()); - AddSlaveAttribute(nn, "ID", mc.ID); - AddSlaveAttribute(nn, "Name", mc.Name); - AddSlaveAttribute(nn, "Number", mc.Number); - AddSlaveAttribute(nn, "Text", mc.Text); - AddSlaveAttribute(nn, "ProcedureNumber", mc.ProcedureNumber); - AddSlaveAttribute(nn, "SetID", mc.SetID); - AddSlaveAttribute(nn, "SetName", mc.SetName); - AddSlaveAttribute(nn, "OtherID", mc.OtherID); - AddSlaveAttribute(nn, "OtherName", mc.OtherName); - AddSlaveAttribute(nn, "OtherNumber", mc.OtherNumber); - AddSlaveAttribute(nn, "OtherText", mc.OtherText); - System.Xml.XmlNode sn = xd.SelectSingleNode("//Slaves"); - sn.AppendChild(nn); - return xd.OuterXml; - } - private void AddSlaveAttribute(System.Xml.XmlNode nn, string name, string value) - { - System.Xml.XmlAttribute xa = nn.OwnerDocument.CreateAttribute(name); - xa.InnerText = value; - nn.Attributes.SetNamedItem(xa); - } - private void btnVersionsPropOK_Click(object sender, EventArgs e) - { - docVersionConfigBindingSource.EndEdit(); // need to end the edit session first or any format selection chanage will not stick B2015-157 - // if there is a change to the format, clean up any overridden formats that point to the selected item before saving the format change: - if (_DocVersionConfig.MyDocVersion.FormatID != _cmbxformatOriginal) - { - // clean up & then refresh the configs - string strdv = _DocVersionConfig.MyDocVersion.VersionID.ToString(); - using (ContentInfoList cil = ContentInfoList.ClearOverrideFormatsByDocVersion(strdv, _cmbxformatOriginal, _DocVersionConfig.MyDocVersion.FormatID)) - { - foreach (ContentInfo ci in cil) - { - using (Content c = ci.Get()) - { - // first refresh configs because the ContentInfo.Refresh causes events to occur that refresh screen - // and if configs aren't done first, the screen refresh, if based on config data, will not be correct. - foreach (ItemInfo ii in ci.ContentItems) ii.RefreshConfig(); - ContentInfo.Refresh(c); - } - } - } - } - if (_DocVersionConfig.Unit_Count > 0 || (_Apples != null && _Apples.Count > 0)) + #endregion + + #region Public Methods + + public List roFstInfo_ROTableUpdate(object sender, ROFstInfoROTableUpdateEventArgs args) + { + string xml = null; + string srchtxt = null; + + using (VlnFlexGrid myGrid = new VlnFlexGrid()) { - if (_DeletedApples != null && _DeletedApples.Count > 0) + using (StringReader sr = new StringReader(args.OldGridXml)) { - foreach (MiniConfig mc in _DeletedApples) - _DocVersionConfig.RemoveSlave(mc.Index); + myGrid.ReadXml(sr); + myGrid.KeyActionTab = C1.Win.C1FlexGrid.KeyActionEnum.MoveAcross; + sr.Close(); } - foreach (MiniConfig mc in _Apples) + + string roid = myGrid.ROID; + int rodbid = myGrid.RODbId; + Font GridFont = myGrid.Font; + + myGrid.Clear(); + myGrid.ParseTableFromText(args.ROText, GridLinePattern.Single); + myGrid.AutoSizeCols(); + myGrid.AutoSizeRows(); + myGrid.MakeRTFcells(); + myGrid.RODbId = rodbid; + myGrid.ROID = roid; + myGrid.IsRoTable = true; + + using (StringWriter sw = new StringWriter()) { - if (mc.IsDirty) - { - if (mc.Index < 0) - { - mc.Index = _DocVersionConfig.MaxSlaveIndex + 1; - _DocVersionConfig.AddSlave(mc.MyXml); - } - else - { - int k = _DocVersionConfig.SelectedSlave; - _DocVersionConfig.SelectedSlave = mc.Index; - _DocVersionConfig.Unit_ID = mc.ID; - _DocVersionConfig.Unit_Name = mc.Name; - _DocVersionConfig.Unit_Number = mc.Number; - _DocVersionConfig.Unit_Text = mc.Text; - _DocVersionConfig.Unit_ProcedureNumber = mc.ProcedureNumber; - _DocVersionConfig.Unit_ProcedureSetID = mc.SetID; - _DocVersionConfig.Unit_ProcedureSetName = mc.SetName; - _DocVersionConfig.Other_Unit_ID = mc.OtherID; - _DocVersionConfig.Other_Unit_Name = mc.OtherName; - _DocVersionConfig.Other_Unit_Number = mc.OtherNumber; - _DocVersionConfig.Other_Unit_Text = mc.OtherText; - _DocVersionConfig.SelectedSlave = k; - } - } + myGrid.WriteXml(sw); + xml = sw.GetStringBuilder().ToString(); + sw.Close(); } - } - if (_Enhanced != null) - { - foreach (EnhancedMiniConfig emc in _Enhanced) - { - if (emc.IsDirty) - { - bool isnew = true; - foreach (DVEnhancedDocument dved in _DocVersionConfig.MyEnhancedDocuments) - { - if (dved.Type == Convert.ToInt32(emc.Type)) - { - isnew = false; - dved.Name = emc.Name; - dved.PdfToken = emc.PdfToken; - try - { - dved.PdfX = Convert.ToInt32(emc.PdfXOffset); - } - catch (Exception ex) - { - dved.PdfX = 10; - } - } - } - if (isnew) // make new link for this and the enhanced it points to. - { - int ipdfx = 0; - try - { - ipdfx = Convert.ToInt32(emc.PdfXOffset); - } - catch (Exception ex) - { - ipdfx = (emc.PdfToken==null||emc.PdfToken=="")?0:10; - } - int itype = 0; - try - { - itype = Convert.ToInt32(emc.Type); - } - catch (Exception ex) - { - itype = 1; - } - // get index into combo box for doc version selected. - int selindx = cbxEnhVersions.SelectedIndex; - DocVersionInfo dvisel = NewEnhVersions[selindx]; - _DocVersionConfig.MyEnhancedDocuments.Add(new DVEnhancedDocument(emc.Name, itype, dvisel.VersionID, ipdfx, emc.PdfToken)); - using (DocVersion dv = DocVersion.Get(dvisel.VersionID)) - { - DocVersionConfig dvc = dv.MyConfig as DocVersionConfig; - dvc.MyEnhancedDocuments.Add(new DVEnhancedDocument("Source", 0, (int)_DocVersionConfig.MyDocVersion.VersionID, 10, "S")); - dvc.SaveDVEnhancedDocuments(); - dv.Config = dvc.ToString(); - dv.Save(); - DocVersionInfo.Refresh(dv); - } - } - } - } - // B2020-004: only set allowmods if this is an enhanced: - bool isEnhanced = (_DocVersionConfig.MyEnhancedDocuments != null && _DocVersionConfig.MyEnhancedDocuments.Count == 1 && _DocVersionConfig.MyEnhancedDocuments[0].Type == 0); - if (isEnhanced) _DocVersionConfig.Enhanced_AllowMods = ppChbxEnhancedAllowMods.Checked; - _DocVersionConfig.SaveDVEnhancedDocuments(); + + srchtxt = myGrid.GetSearchableText(); } - _DocVersionConfig.Print_UnitNumberForPageList = ppTxbxUnitNum.Text; + List retlist = new List(); + retlist.Add(srchtxt); + retlist.Add(xml); - // save the merge pdf settings: - _DocVersionConfig.Print_MergedPdfsPageOf = (MergedPdfsPageOf)ppCmbxMOSformat.SelectedIndex; - _DocVersionConfig.Print_MergedPdfsPageNumFormatOther = tbxMOSother.Text; - _DocVersionConfig.Print_MergedPdfsPageNumFont = (string)ppCmbxMOSfontName.SelectedValue; - _DocVersionConfig.Print_MergedPdfsPageNumFontSize = tbxMOSfontSz.Text; - _DocVersionConfig.Print_MergedPdfsPageNumLocX = float.Parse(tbxMOSxloc.Text); - _DocVersionConfig.Print_MergedPdfsPageNumLocY = float.Parse(tbxMOSyloc.Text); - _DocVersionConfig.Print_MergedPdfsPageNumCorner = (MergedPdfsPageNumCorner)ppCmbxMOScornerLoc.SelectedIndex; - // C2021-047: Allow for setting of Merged Pdf Landscape Page Number Location - _DocVersionConfig.Print_MergedPdfsLandPageNumLocX = float.Parse(tbxMOSLandxloc.Text); - _DocVersionConfig.Print_MergedPdfsLandPageNumLocY = float.Parse(tbxMOSLandyloc.Text); - _DocVersionConfig.Print_MergedPdfsLandPageNumCorner = (MergedPdfsPageNumCorner)ppCmbxMOSLandcornerLoc.SelectedIndex; - _DocVersionConfig.Print_MergedPdfsViewAfter = ppChbxMOSview.Checked; - - //docVersionConfigBindingSource.EndEdit(); - // Save Default settings for User - // - // Save whether we should display the default values on this property page - Settings.Default.ShowDefaultVersionProp = ppCbShwDefSettings.Checked; - Settings.Default.Save(); - DialogResult = DialogResult.OK; - _DocVersionConfig.MyDocVersion.Config = _DocVersionConfig.ToString(); - _refreshProcedureList = true; - _DocVersionConfig.MyDocVersion.Save().Dispose(); - if (_EnhNeedToUnlink) - { - this.Cursor = Cursors.WaitCursor; - _DocVersionConfig.MyDocVersion.MyDocVersionInfo.DoUnlinkEnhancedDocVersion(); - this.Cursor = Cursors.Default; - } - // B2019-132 update the association count for this working draft - _DocVersionConfig.MyDocVersion.MyDocVersionInfo.RefreshDocVersionAssociations(); - this.Close(); + return retlist; } - private void btnFldrPropCancel_Click(object sender, EventArgs e) - { - docVersionConfigBindingSource.CancelEdit(); - this.Close(); - } + #endregion - /// - /// Use the ParentLookup to grab the default values - /// - set the watermark property (where applicable) of the control with that value - /// - set the default setting labels with that value - /// ** the default setting labels appear when the Show Default Values checkbox is checked by the user. - /// - private void FindDefaultValues() - { - _DocVersionConfig.ParentLookup = true; + #region Private Methods - // get default format - _DefaultFormatName = _DocVersionConfig.DefaultFormatSelection; - SetupDefault(_DefaultFormatName, ppLblFormatDefault, ppCmbxFormat); - - // Get the default Change Bar Type - _DefaultChgBarType = _DocVersionConfig.Print_ChangeBar.ToString(); - SetupDefault(EnumDescConverter.GetEnumDescription(_DocVersionConfig.Print_ChangeBar), ppLblChangeBarTypeDefault, ppCmbxChangeBarType); - - // Get the default Change Bar Location - _DefaultChgBarLoc = _DocVersionConfig.Print_ChangeBarLoc.ToString(); - SetupDefault(EnumDescConverter.GetEnumDescription(_DocVersionConfig.Print_ChangeBarLoc), ppLblChgBarPosDefault, ppCmbxChgBarPos); - - // Get the default Change Bar text - _DefaultChgBarText = _DocVersionConfig.Print_ChangeBarText.ToString(); - SetupDefault(EnumDescConverter.GetEnumDescription(_DocVersionConfig.Print_ChangeBarText), ppLblChgBarTxtTypeDefault, ppCmbxChgBarTxtType); - - // Get the default User Change Bar Message 1 - _DefaultChgBarUsrMsg1 = _DocVersionConfig.Print_UserCBMess1; - if (!(_DefaultChgBarUsrMsg1.Equals(""))) - { - ppLblChgBarUserMsgOneDefault.Text = string.Format("({0})", _DefaultChgBarUsrMsg1); - } - - // Get the default User Change Bar Message 2 - _DefaultChgBarUsrMsg2 = _DocVersionConfig.Print_UserCBMess2; - if (!(_DefaultChgBarUsrMsg2.Equals(""))) - { - ppLblChgBarUserMsgTwoDefault.Text = string.Format("{0}", _DefaultChgBarUsrMsg2); - } - - // Get the ro path - there is no 'default' - if (_DocVersionConfig.MyDocVersion.DocVersionAssociationCount < 0 && _DocVersionConfig.MyDocVersion.DocVersionAssociations.Count == 0) - ;// The line above refreshes the data - if (_DocVersionConfig.MyDocVersion.DocVersionAssociationCount > 0) - { - RODbInfo rdi = RODbInfo.GetJustRODB(SelectedROFst.RODbID); - tbRoDb.Text = string.Format("{0} ({1})", rdi.ROName, rdi.FolderPath); - ppBtnRoToSql.Visible = ppBtnRoToSql.Enabled = CanMigrateRoAccessToSql(rdi); // C2017-003: make button visible if ro migration is doable - _CurRoDbInfo = rdi; - } - else - { - int selindx = -1; - cmbRoDb.Items.Clear(); - int myrodbid = -1; - if (_DocVersionConfig.MyDocVersion.DocVersionAssociationCount >= 1) myrodbid = SelectedROFst.RODbID; - foreach (RODbInfo rdi in RODbInfoList.Get()) - { - int i = cmbRoDb.Items.Add(string.Format("{0} ({1})", rdi.ROName, rdi.FolderPath)); - if (rdi.RODbID == myrodbid) - { - selindx = i; - ppBtnRoToSql.Visible = ppBtnRoToSql.Enabled = CanMigrateRoAccessToSql(rdi); // C2017-003: make button visible if ro migration is doable - _CurRoDbInfo = rdi; - } - } - if (cmbRoDb.Items.Count > 0) cmbRoDb.SelectedIndex = selindx; - } - - // Get the default Print Pagination - //_DefaultPagination = _DocVersionConfig.Print_Pagination.ToString(); - //SetupDefault(EnumDescConverter.GetEnumDescription(_DocVersionConfig.Print_Pagination), ppLblPaginationDefault, ppCmbxPagination); - - // Get the default Watermark - _DefaultWatermark = _DocVersionConfig.Print_Watermark.ToString(); - SetupDefault(EnumDescConverter.GetEnumDescription(_DocVersionConfig.Print_Watermark), ppLblWatermarkDefault, ppCmbxWatermark); - - // Get the default Disable Duplex - _DefaultDisableDuplex = _DocVersionConfig.Print_DisableDuplex; - ppLblAutoDuplexDefault.Text = string.Format("(Duplex {0})", (_DefaultDisableDuplex) ? "OFF" : "ON"); - - _DocVersionConfig.ParentLookup = false; - } - - private int? _cmbxformatOriginal = null; private void frmVersionsProperties_Load(object sender, EventArgs e) { _Initializing = true; + docVersionConfigBindingSource.DataSource = _DocVersionConfig; //formatInfoListBindingSource.DataSource = FormatInfoList.Get(); @@ -375,17 +169,19 @@ namespace VEPROMS ppCmbxFormat.DisplayMember = "FullName"; ppCmbxFormat.ValueMember = "FullName"; ppCmbxFormat.DataSource = FormatInfoList.SortedFormatInfoList; - _cmbxformatOriginal = _DocVersionConfig.MyDocVersion.FormatID; + _cmbxformatOriginal = _DocVersionConfig.MyDocVersion.FormatID; + if (_DocVersionConfig.FormatSelection != null) { ppCmbxFormat.SelectedValue = _DocVersionConfig.FormatSelection; ppBtnDefaultFmt.Visible = true; //bug fix B2016-102 make the default button visable if other the the default format is being used } else + { ppCmbxFormat.SelectedIndex = -1; // default format + } // Get the saved settings for this user - // // Get setting telling us whether to display the default values on this property page ppCbShwDefSettings.Checked = (Settings.Default["ShowDefaultVersionProp"] != null) ? Settings.Default.ShowDefaultVersionProp : false; @@ -428,15 +224,9 @@ namespace VEPROMS ppCmbxPDFdtPrefix.SelectedIndex = -1; ppCmbxPDFdtSuffix.DataSource = EnumDetail.Details(); // C2018-033 dropdown for PDF Suffix date/time format - //ppCmbxPDFdtSuffix.DisplayMember = "Description"; ppCmbxPDFdtSuffix.ValueMember = "EValue"; ppCmbxPDFdtSuffix.SelectedIndex = -1; - //ppCmbxPagination.DataSource = EnumDetail.Details(); - //ppCmbxPagination.DisplayMember = "Description"; - //ppCmbxPagination.ValueMember = "EValue"; - //ppCmbxPagination.SelectedIndex = -1; - ppCmbxProcSetType.DataSource = EnumDetail.Details(); ppCmbxProcSetType.DisplayMember = "Description"; ppCmbxProcSetType.ValueMember = "EValue"; @@ -479,6 +269,7 @@ namespace VEPROMS ppBtnRoDbBrowse.Visible = cmbRoDb.Visible = _DocVersionConfig.MyDocVersion.DocVersionAssociationCount == 0; btnRoDbProperties.Visible = tbRoDb.Visible = !(_DocVersionConfig.MyDocVersion.DocVersionAssociationCount == 0); + // only allow update if association, and the RO update was not done and/or not completed ppBtnUpRoVals.Enabled = !_DocVersionConfig.MyDocVersion.ROfstLastCompleted || _DocVersionConfig.MyDocVersion.NewerRoFst; @@ -499,11 +290,13 @@ namespace VEPROMS ppLblAutoDuplexDefault.Visible = false; ppBtnDeftDisAutoDuplx.Visible = false; } + //add new applicability stuff if (_DocVersionConfig.Unit_Count > 0) { int k = _DocVersionConfig.SelectedSlave; _Apples = new List(); + for (int i = 1; i <= _DocVersionConfig.MaxSlaveIndex; i++) { _DocVersionConfig.SelectedSlave = i; @@ -512,10 +305,9 @@ namespace VEPROMS MiniConfig cfg = new MiniConfig(i, _DocVersionConfig.Unit_ID, _DocVersionConfig.Unit_Name, _DocVersionConfig.Unit_Number, _DocVersionConfig.Unit_Text, _DocVersionConfig.Unit_ProcedureNumber, _DocVersionConfig.Unit_ProcedureSetID, _DocVersionConfig.Unit_ProcedureSetName, _DocVersionConfig.Other_Unit_ID, _DocVersionConfig.Other_Unit_Name, _DocVersionConfig.Other_Unit_Number, _DocVersionConfig.Other_Unit_Text); _Apples.Add(cfg); } - catch - { - } + catch { } } + _DocVersionConfig.SelectedSlave = k; bsApples.DataSource = _Apples; } @@ -530,7 +322,9 @@ namespace VEPROMS btnApplicability.Visible = false; tiApplicability.Visible = false; } + ppTxtBxPDFLoc.TextChanged += new EventHandler(ppTxtBxPDFLoc_TextChanged); + //end add new applicability stuff lblProcSetRev.Visible = ppRTxtProcSetRev.Visible = _DocVersionConfig.MyDocVersion.MyDocVersionInfo.ActiveFormat.MyStepSectionPrintData.UseXtraRevNumber; @@ -549,21 +343,31 @@ namespace VEPROMS { // Page Settings ppCmbxMOSformat.SelectedIndex = (int)_DocVersionConfig.Print_MergedPdfsPageOf; + if (_DocVersionConfig.Print_MergedPdfsPageOf == MergedPdfsPageOf.Other) { tbxMOSother.Text = _DocVersionConfig.Print_MergedPdfsPageNumFormatOther; tbxMOSother.Enabled = true; } else + { tbxMOSother.Enabled = false; + } + tbxMOSother.Text = _DocVersionConfig.Print_MergedPdfsPageNumFormatOther; tbxMOSfontSz.Text = _DocVersionConfig.Print_MergedPdfsPageNumFontSize; ppCmbxMOSfontName.DataSource = FontFamily.Families; ppCmbxMOSfontName.DisplayMember = "Name"; - if (_DocVersionConfig.Print_MergedPdfsPageNumFont == null || _DocVersionConfig.Print_MergedPdfsPageNumFont == "") + + if (_DocVersionConfig.Print_MergedPdfsPageNumFont == null || _DocVersionConfig.Print_MergedPdfsPageNumFont == string.Empty) + { ppCmbxMOSfontName.SelectedIndex = -1; + } else + { ppCmbxMOSfontName.SelectedValue = _DocVersionConfig.Print_MergedPdfsPageNumFont; + } + ppChbxMOSview.Checked = _DocVersionConfig.Print_MergedPdfsViewAfter; // Portrait Specific Settings @@ -576,6 +380,7 @@ namespace VEPROMS tbxMOSLandyloc.Text = _DocVersionConfig.Print_MergedPdfsLandPageNumLocY.ToString(); ppCmbxMOSLandcornerLoc.SelectedIndex = (int)_DocVersionConfig.Print_MergedPdfsLandPageNumCorner; } + private void InitEnhanced() { // if this working draft has no enhanced documents, then put display a button for creating the enhanced links - @@ -590,7 +395,7 @@ namespace VEPROMS { bool validEmptyEnhancedExists = false; // See if there are available (enhanced) DocVersions that can be linked to from this (source) DocVersion - DocVersionInfoList nonenhdvs = DocVersionInfoList.GetNonEnhancedDocVersions(); // this is a list of docversions that have no 'Enhanced' in config data + DocVersionInfoList nonenhdvs = DocVersionInfoList.GetNonEnhancedDocVersions(); // this is a list of docversions that have no 'Enhanced' in config data foreach (DocVersionInfo nonenhdv in nonenhdvs) { if (nonenhdv.VersionID != _DocVersionConfig.MyDocVersion.VersionID) @@ -623,7 +428,7 @@ namespace VEPROMS // get enhanced tab's data if: // 1) hasEnhancedPO: this is source and format file has the purchase options for enhanced deviation or enhanced background // 2) isEnhanced: this docversion has a config/enhanced node that defines it as an enhanced document. - bool hasEnhancedPO = true; // for now all can be enhanced + bool hasEnhancedPO = true; // for now all can be enhanced bool isEnhanced = (_DocVersionConfig.MyEnhancedDocuments != null && _DocVersionConfig.MyEnhancedDocuments.Count == 1 && _DocVersionConfig.MyEnhancedDocuments[0].Type == 0); ppChbxEnhancedAllowMods.Visible = isEnhanced; // isEnhanced is an already existing enhanced document. Only allow the user to change the Pdf settings: @@ -673,7 +478,7 @@ namespace VEPROMS _Enhanced = new List(); lbEnhanced.Visible = true; lblEnhSet.Visible = true; - btnUnlinkDocVersion.Visible = false; // no unlink button when on a Source Document + btnUnlinkDocVersion.Visible = false; // no unlink button when on a Source Document foreach (DVEnhancedDocument dved in _DocVersionConfig.MyEnhancedDocuments) { DocVersionInfo dvi = DocVersionInfo.Get(dved.VersionID); @@ -686,10 +491,10 @@ namespace VEPROMS tbEnhType.Enabled = false; cbxEnhVersions.Enabled = false; bsEnhanced.DataSource = _Enhanced; - if (cbxEnhVersions.Items.Count>0) cbxEnhVersions.SelectedIndex = 0; + if (cbxEnhVersions.Items.Count > 0) cbxEnhVersions.SelectedIndex = 0; if (lbEnhanced.Items.Count > 0) lbEnhanced.SelectedIndex = 0; bsMiniEnhanced.DataSource = bsEnhanced.Current as EnhancedMiniConfig; - + // only allow new if there are available non-linked 'enhanced format' docversions. int cntAvailForLinkEnh = 0; DocVersionInfoList nonenhdvs = DocVersionInfoList.GetNonEnhancedDocVersions(); @@ -704,11 +509,12 @@ namespace VEPROMS } } } - btnNewEnh.Visible = (cntAvailForLinkEnh > 0); + + btnNewEnh.Visible = (cntAvailForLinkEnh > 0); } } - void btnEnh_Click(object sender, EventArgs e) + private void btnEnh_Click(object sender, EventArgs e) { if (MessageBox.Show(this, "Are you sure you want to Link Enhanced Document(s) to this Working Draft?", "Add Enhanced Link", MessageBoxButtons.YesNoCancel) == DialogResult.Yes) { @@ -719,7 +525,8 @@ namespace VEPROMS btnEnhanced_Click(sender, e); } } - void btnPC_Click(object sender, EventArgs e) + + private void btnPC_Click(object sender, EventArgs e) { if (MessageBox.Show(this, "Are you sure you want to add Applicability to this Working Draft?", "Add Applicability", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Stop) == DialogResult.Yes) { @@ -730,13 +537,899 @@ namespace VEPROMS btnApplicability_Click(sender, e); } } + // The following code was added to fix Bug B2013-117 - void ppTxtBxPDFLoc_TextChanged(object sender, EventArgs e) + private void ppTxtBxPDFLoc_TextChanged(object sender, EventArgs e) { if (_Initializing == false) _DocVersionConfig.Print_PDFLocation = ppTxtBxPDFLoc.Text; } - #region General tab + + private string AddSlaveNode(MiniConfig mc) + { + System.Xml.XmlDocument xd = new System.Xml.XmlDocument(); + xd.LoadXml(_DocVersionConfig.ToString()); + System.Xml.XmlNodeList nl = xd.SelectNodes("//Slave"); + int max = 0; + + foreach (System.Xml.XmlNode n in nl) + { + max = int.Parse(n.Attributes.GetNamedItem("index").InnerText); + } + + max++; + + System.Xml.XmlNode nn = xd.CreateElement("Slave"); + AddSlaveAttribute(nn, "index", max.ToString()); + AddSlaveAttribute(nn, "ID", mc.ID); + AddSlaveAttribute(nn, "Name", mc.Name); + AddSlaveAttribute(nn, "Number", mc.Number); + AddSlaveAttribute(nn, "Text", mc.Text); + AddSlaveAttribute(nn, "ProcedureNumber", mc.ProcedureNumber); + AddSlaveAttribute(nn, "SetID", mc.SetID); + AddSlaveAttribute(nn, "SetName", mc.SetName); + AddSlaveAttribute(nn, "OtherID", mc.OtherID); + AddSlaveAttribute(nn, "OtherName", mc.OtherName); + AddSlaveAttribute(nn, "OtherNumber", mc.OtherNumber); + AddSlaveAttribute(nn, "OtherText", mc.OtherText); + + System.Xml.XmlNode sn = xd.SelectSingleNode("//Slaves"); + sn.AppendChild(nn); + + return xd.OuterXml; + } + + private void AddSlaveAttribute(System.Xml.XmlNode nn, string name, string value) + { + System.Xml.XmlAttribute xa = nn.OwnerDocument.CreateAttribute(name); + xa.InnerText = value; + nn.Attributes.SetNamedItem(xa); + } + + private void btnVersionsPropOK_Click(object sender, EventArgs e) + { + docVersionConfigBindingSource.EndEdit(); // need to end the edit session first or any format selection chanage will not stick B2015-157 + + // if there is a change to the format, clean up any overridden formats that point to the selected item before saving the format change: + if (_DocVersionConfig.MyDocVersion.FormatID != _cmbxformatOriginal) + { + // clean up & then refresh the configs + string strdv = _DocVersionConfig.MyDocVersion.VersionID.ToString(); + + using (ContentInfoList cil = ContentInfoList.ClearOverrideFormatsByDocVersion(strdv, _cmbxformatOriginal, _DocVersionConfig.MyDocVersion.FormatID)) + { + foreach (ContentInfo ci in cil) + { + using (Content c = ci.Get()) + { + // first refresh configs because the ContentInfo.Refresh causes events to occur that refresh screen + // and if configs aren't done first, the screen refresh, if based on config data, will not be correct. + foreach (ItemInfo ii in ci.ContentItems) + { + ii.RefreshConfig(); + } + + ContentInfo.Refresh(c); + } + } + } + } + + if (_DocVersionConfig.Unit_Count > 0 || (_Apples != null && _Apples.Count > 0)) + { + if (_DeletedApples != null && _DeletedApples.Count > 0) + { + foreach (MiniConfig mc in _DeletedApples) + { + _DocVersionConfig.RemoveSlave(mc.Index); + } + } + + foreach (MiniConfig mc in _Apples) + { + if (mc.IsDirty) + { + if (mc.Index < 0) + { + mc.Index = _DocVersionConfig.MaxSlaveIndex + 1; + _DocVersionConfig.AddSlave(mc.MyXml); + } + else + { + int k = _DocVersionConfig.SelectedSlave; + + _DocVersionConfig.SelectedSlave = mc.Index; + _DocVersionConfig.Unit_ID = mc.ID; + _DocVersionConfig.Unit_Name = mc.Name; + _DocVersionConfig.Unit_Number = mc.Number; + _DocVersionConfig.Unit_Text = mc.Text; + _DocVersionConfig.Unit_ProcedureNumber = mc.ProcedureNumber; + _DocVersionConfig.Unit_ProcedureSetID = mc.SetID; + _DocVersionConfig.Unit_ProcedureSetName = mc.SetName; + _DocVersionConfig.Other_Unit_ID = mc.OtherID; + _DocVersionConfig.Other_Unit_Name = mc.OtherName; + _DocVersionConfig.Other_Unit_Number = mc.OtherNumber; + _DocVersionConfig.Other_Unit_Text = mc.OtherText; + _DocVersionConfig.SelectedSlave = k; + } + } + } + } + + if (_Enhanced != null) + { + foreach (EnhancedMiniConfig emc in _Enhanced) + { + if (emc.IsDirty) + { + bool isnew = true; + + foreach (DVEnhancedDocument dved in _DocVersionConfig.MyEnhancedDocuments) + { + if (dved.Type == Convert.ToInt32(emc.Type)) + { + isnew = false; + dved.Name = emc.Name; + dved.PdfToken = emc.PdfToken; + + try + { + dved.PdfX = Convert.ToInt32(emc.PdfXOffset); + } + catch (Exception ex) + { + dved.PdfX = 10; + } + } + } + + if (isnew) // make new link for this and the enhanced it points to. + { + int ipdfx = 0; + + try + { + ipdfx = Convert.ToInt32(emc.PdfXOffset); + } + catch (Exception ex) + { + ipdfx = (emc.PdfToken == null || emc.PdfToken == "") ? 0 : 10; + } + + int itype = 0; + + try + { + itype = Convert.ToInt32(emc.Type); + } + catch (Exception ex) + { + itype = 1; + } + + // get index into combo box for doc version selected. + int selindx = cbxEnhVersions.SelectedIndex; + DocVersionInfo dvisel = NewEnhVersions[selindx]; + _DocVersionConfig.MyEnhancedDocuments.Add(new DVEnhancedDocument(emc.Name, itype, dvisel.VersionID, ipdfx, emc.PdfToken)); + + using (DocVersion dv = DocVersion.Get(dvisel.VersionID)) + { + DocVersionConfig dvc = dv.MyConfig as DocVersionConfig; + + dvc.MyEnhancedDocuments.Add(new DVEnhancedDocument("Source", 0, (int)_DocVersionConfig.MyDocVersion.VersionID, 10, "S")); + dvc.SaveDVEnhancedDocuments(); + dv.Config = dvc.ToString(); + dv.Save(); + + DocVersionInfo.Refresh(dv); + } + } + } + } + + // B2020-004: only set allow mods if this is an enhanced: + bool isEnhanced = (_DocVersionConfig.MyEnhancedDocuments != null && _DocVersionConfig.MyEnhancedDocuments.Count == 1 && _DocVersionConfig.MyEnhancedDocuments[0].Type == 0); + + if (isEnhanced) + { + _DocVersionConfig.Enhanced_AllowMods = ppChbxEnhancedAllowMods.Checked; + } + + _DocVersionConfig.SaveDVEnhancedDocuments(); + } + + _DocVersionConfig.Print_UnitNumberForPageList = ppTxbxUnitNum.Text; + + // save the merge pdf settings: + _DocVersionConfig.Print_MergedPdfsPageOf = (MergedPdfsPageOf)ppCmbxMOSformat.SelectedIndex; + _DocVersionConfig.Print_MergedPdfsPageNumFormatOther = tbxMOSother.Text; + _DocVersionConfig.Print_MergedPdfsPageNumFont = (string)ppCmbxMOSfontName.SelectedValue; + _DocVersionConfig.Print_MergedPdfsPageNumFontSize = tbxMOSfontSz.Text; + _DocVersionConfig.Print_MergedPdfsPageNumLocX = float.Parse(tbxMOSxloc.Text); + _DocVersionConfig.Print_MergedPdfsPageNumLocY = float.Parse(tbxMOSyloc.Text); + _DocVersionConfig.Print_MergedPdfsPageNumCorner = (MergedPdfsPageNumCorner)ppCmbxMOScornerLoc.SelectedIndex; + + // C2021-047: Allow for setting of Merged Pdf Landscape Page Number Location + _DocVersionConfig.Print_MergedPdfsLandPageNumLocX = float.Parse(tbxMOSLandxloc.Text); + _DocVersionConfig.Print_MergedPdfsLandPageNumLocY = float.Parse(tbxMOSLandyloc.Text); + _DocVersionConfig.Print_MergedPdfsLandPageNumCorner = (MergedPdfsPageNumCorner)ppCmbxMOSLandcornerLoc.SelectedIndex; + _DocVersionConfig.Print_MergedPdfsViewAfter = ppChbxMOSview.Checked; + + // Save whether we should display the default values on this property page + Settings.Default.ShowDefaultVersionProp = ppCbShwDefSettings.Checked; + Settings.Default.Save(); + DialogResult = DialogResult.OK; + + _DocVersionConfig.MyDocVersion.Config = _DocVersionConfig.ToString(); + _refreshProcedureList = true; + _DocVersionConfig.MyDocVersion.Save().Dispose(); + + if (_EnhNeedToUnlink) + { + this.Cursor = Cursors.WaitCursor; + _DocVersionConfig.MyDocVersion.MyDocVersionInfo.DoUnlinkEnhancedDocVersion(); + this.Cursor = Cursors.Default; + } + + // B2019-132 update the association count for this working draft + _DocVersionConfig.MyDocVersion.MyDocVersionInfo.RefreshDocVersionAssociations(); + + this.Close(); + } + + private void btnFldrPropCancel_Click(object sender, EventArgs e) + { + docVersionConfigBindingSource.CancelEdit(); + this.Close(); + } + + /// + /// Use the ParentLookup to grab the default values + /// - set the watermark property (where applicable) of the control with that value + /// - set the default setting labels with that value + /// ** the default setting labels appear when the Show Default Values checkbox is checked by the user. + /// + private void FindDefaultValues() + { + _DocVersionConfig.ParentLookup = true; + + // get default format + _DefaultFormatName = _DocVersionConfig.DefaultFormatSelection; + SetupDefault(_DefaultFormatName, ppLblFormatDefault, ppCmbxFormat); + + // Get the default Change Bar Type + _DefaultChgBarType = _DocVersionConfig.Print_ChangeBar.ToString(); + SetupDefault(EnumDescConverter.GetEnumDescription(_DocVersionConfig.Print_ChangeBar), ppLblChangeBarTypeDefault, ppCmbxChangeBarType); + + // Get the default Change Bar Location + _DefaultChgBarLoc = _DocVersionConfig.Print_ChangeBarLoc.ToString(); + SetupDefault(EnumDescConverter.GetEnumDescription(_DocVersionConfig.Print_ChangeBarLoc), ppLblChgBarPosDefault, ppCmbxChgBarPos); + + // Get the default Change Bar text + _DefaultChgBarText = _DocVersionConfig.Print_ChangeBarText.ToString(); + SetupDefault(EnumDescConverter.GetEnumDescription(_DocVersionConfig.Print_ChangeBarText), ppLblChgBarTxtTypeDefault, ppCmbxChgBarTxtType); + + // Get the default User Change Bar Message 1 + _DefaultChgBarUsrMsg1 = _DocVersionConfig.Print_UserCBMess1; + + if (!(_DefaultChgBarUsrMsg1.Equals(string.Empty))) + { + ppLblChgBarUserMsgOneDefault.Text = string.Format("({0})", _DefaultChgBarUsrMsg1); + } + + // Get the default User Change Bar Message 2 + _DefaultChgBarUsrMsg2 = _DocVersionConfig.Print_UserCBMess2; + if (!(_DefaultChgBarUsrMsg2.Equals(string.Empty))) + { + ppLblChgBarUserMsgTwoDefault.Text = string.Format("{0}", _DefaultChgBarUsrMsg2); + } + + // Get the ro path - there is no 'default' + if (_DocVersionConfig.MyDocVersion.DocVersionAssociationCount < 0 && _DocVersionConfig.MyDocVersion.DocVersionAssociations.Count == 0) + ;// The line above refreshes the data + + if (_DocVersionConfig.MyDocVersion.DocVersionAssociationCount > 0) + { + RODbInfo rdi = RODbInfo.GetJustRODB(SelectedROFst.RODbID); + + tbRoDb.Text = string.Format("{0} ({1})", rdi.ROName, rdi.FolderPath); + ppBtnRoToSql.Visible = ppBtnRoToSql.Enabled = CanMigrateRoAccessToSql(rdi); // C2017-003: make button visible if ro migration is doable + _CurRoDbInfo = rdi; + } + else + { + int selindx = -1; + cmbRoDb.Items.Clear(); + int myrodbid = -1; + if (_DocVersionConfig.MyDocVersion.DocVersionAssociationCount >= 1) myrodbid = SelectedROFst.RODbID; + + foreach (RODbInfo rdi in RODbInfoList.Get()) + { + int i = cmbRoDb.Items.Add(string.Format("{0} ({1})", rdi.ROName, rdi.FolderPath)); + + if (rdi.RODbID == myrodbid) + { + selindx = i; + ppBtnRoToSql.Visible = ppBtnRoToSql.Enabled = CanMigrateRoAccessToSql(rdi); // C2017-003: make button visible if ro migration is doable + _CurRoDbInfo = rdi; + } + } + + if (cmbRoDb.Items.Count > 0) + cmbRoDb.SelectedIndex = selindx; + } + + // Get the default Watermark + _DefaultWatermark = _DocVersionConfig.Print_Watermark.ToString(); + SetupDefault(EnumDescConverter.GetEnumDescription(_DocVersionConfig.Print_Watermark), ppLblWatermarkDefault, ppCmbxWatermark); + + // Get the default Disable Duplex + _DefaultDisableDuplex = _DocVersionConfig.Print_DisableDuplex; + ppLblAutoDuplexDefault.Text = string.Format("(Duplex {0})", (_DefaultDisableDuplex) ? "OFF" : "ON"); + + _DocVersionConfig.ParentLookup = false; + } + + private void DoProgressBarRefresh(int value, int max, string text) + { + if (ProgressBar == null) return; + ProgressBar.Maximum = max; + ProgressBar.Value = value; + ProgressBar.Text = text; + Application.DoEvents(); + } + + private string InitialProgressBarMessage + { + set + { + if (ProgressBar == null) return; + ProgressBar.Value = 0; + ProgressBar.Maximum = 100; + ProgressBar.Text = value; + Application.DoEvents(); + } + } + + private string FinalProgressBarMessage + { + set + { + if (ProgressBar == null) return; + ProgressBar.Maximum = 100; + ProgressBar.Value = 100; + ProgressBar.Text = value; + Application.DoEvents(); + } + } + + private void ppBtnResetRoVals_Click(object sender, EventArgs e) + { + // This will not be supported in the first release. A discussion was held on 1/6/09 with MRC, JSJ, RHM & + // KBR & it was decided that we'd wait to see if users end up needing this. It can be done by going + // into the sql database and modify/delete records if needed. + } + + private void cmbRoDb_SelectedIndexChanged(object sender, EventArgs e) + { + if (_Initializing) + return; + + // The only way that a selected index can change on the rodb combo box is if there was no rofst + // to docversion association. If a selection is made, make that association and then change the + // combo box to a non-editable text box with button becoming a properties rather than browse. + + // add the rofst for the selected rodb (note that it may already exist, and will use the current one. + // get the rodb from the selection - and then do an 'update rofst'... + RODbInfoList rdil = RODbInfoList.Get(); + RODbInfo rdi = rdil[cmbRoDb.SelectedIndex]; + ROFstInfo fst = null; + + foreach (ROFstInfo inf in rdi.RODbROFsts) + { + if (fst == null || inf.ROFstID > fst.ROFstID) + { + fst = inf; + } + } + + if (fst != null) + { + using (ROFst fst1 = fst.Get()) + { + _DocVersionConfig.MyDocVersion.DocVersionAssociations.Add(fst1); + } + + cmbRoDb.Visible = ppBtnRoDbBrowse.Visible = false; + tbRoDb.Visible = btnRoDbProperties.Visible = true; + tbRoDb.Text = string.Format("{0} ({1})", fst.MyRODb.ROName, fst.MyRODb.FolderPath); + + // C2017-003: See if the selected ro databasew has been converted to sql and if not, make visible a button to convert the data. + ppBtnRoToSql.Visible = ppBtnRoToSql.Enabled = CanMigrateRoAccessToSql(fst.MyRODb); + _CurRoDbInfo = fst.MyRODb; + } + else + { + ROFst tmp = ROFstInfo.AddRoFst(rdi, _DocVersionConfig.MyDocVersion, DoProgressBarRefresh); // RHM Needs To Include Delegate + + if (tmp == null) + { + MessageBox.Show("Invalid ro fst directory, use the Property dialog to fix directory path to ro.fst."); + frmRODbProperties dlgROProperties = new frmRODbProperties(_DocVersionConfig.MyDocVersion, rdi); + dlgROProperties.ProgressBar = ProgressBar; + + if (dlgROProperties.ShowDialog() == DialogResult.OK) + { + tbRoDb.Text = string.Format("{0} ({1})", SelectedROFst.MyRODb.ROName, SelectedROFst.MyRODb.FolderPath); + // only allow update if association, and the RO update was not done and/or not completed + ppBtnUpRoVals.Enabled = !_DocVersionConfig.MyDocVersion.ROfstLastCompleted || _DocVersionConfig.MyDocVersion.NewerRoFst; + } + else + { + return; + } + } + + cmbRoDb.Visible = ppBtnRoDbBrowse.Visible = false; + tbRoDb.Visible = btnRoDbProperties.Visible = true; + tbRoDb.Text = string.Format("{0} ({1})", tmp.MyRODb.ROName, tmp.MyRODb.FolderPath); + + // C2017-003: See if the selected ro database has been converted to sql and if not, make visible a button to convert the data. + RODbInfo rodbi = RODbInfo.GetJustRODB(tmp.MyRODb.RODbID); + ppBtnRoToSql.Visible = ppBtnRoToSql.Enabled = CanMigrateRoAccessToSql(rodbi); + _CurRoDbInfo = rodbi; + } + + } + + private bool CanMigrateRoAccessToSql(RODbInfo rODbi) + { + // C2017-003: This method is used to determine whether RO data can be migrated from MS Access to sql server + // A command line argument 'RoInSql'. For now, this argument must be used to allow code to run for ro->sql. Later + // this will be changed so that if arugment is used, the program does NOT include button. + if (!Volian.Base.Library.VlnSettings.GetCommandFlag("RoInSql")) return false; + + // The following conditions must be true in order to migrate the ro data to sql. Only the first condition can be + // tested in this executable since the roall database is interfaced to by the roeditor & the program that migrates the data. + // The migration program will make the 2-4 tests, put up a message box if it cannot migrate & will send a failure back + // to this program, PROMS. + // 1) the user must be an admin and the rodb record's connection string must be 'cstring' (it is the connection string if data was migrated) + // 2) the roall database must exist when using the rodb record's connection string and this database must have the stored procedures + // 3) roall must be empty + // 4) the database must be the correct version + UserInfo ui = UserInfo.GetByUserID(VlnSettings.UserID); + if (!ui.IsAdministrator()) return false; + return (rODbi.DBConnectionString == "cstring"); + } + + private void ppBtnRoDbBrowse_Click(object sender, EventArgs e) + { + frmRODbProperties dlgROProperties = new frmRODbProperties(_DocVersionConfig.MyDocVersion, SelectedROFst == null ? null : SelectedROFst.MyRODb); + dlgROProperties.ParentLocation = Location; + + // if a user has entered a valid rodb, then this docversion will be conntected to it - change + // to a non-editable text box and the button becomes a properties button rather than browse. + if (dlgROProperties.ShowDialog() == DialogResult.OK) + { + cmbRoDb.Items.Clear(); + _DocVersionConfig.MyDocVersion.Reset_DocVersionAssociations(); + + if (_DocVersionConfig.MyDocVersion.DocVersionAssociations != null && _DocVersionConfig.MyDocVersion.DocVersionAssociationCount > 0) + { + cmbRoDb.Visible = ppBtnRoDbBrowse.Visible = false; + tbRoDb.Visible = btnRoDbProperties.Visible = true; + tbRoDb.Text = string.Format("{0} ({1})", SelectedROFst.MyRODb.ROName, SelectedROFst.MyRODb.FolderPath); + return; + } + + RODbInfoList.Reset(); + int selindx = -1; + int myrodbid = (SelectedROFst == null) ? -1 : SelectedROFst.RODbID; + + foreach (RODbInfo rdi in RODbInfoList.Get()) + { + int i = cmbRoDb.Items.Add(rdi.ROName + " (" + rdi.FolderPath + ")"); + if (rdi.RODbID == myrodbid) + { + selindx = i; + } + } + + if (cmbRoDb.Items.Count > 0) + cmbRoDb.SelectedIndex = selindx; + } + } + + private void ppBtnPDFLoc_Click(object sender, EventArgs e) + { + PDFLocationBrowserDialog.SelectedPath = ppTxtBxPDFLoc.Text; + DialogResult dr = PDFLocationBrowserDialog.ShowDialog(); + if (dr == DialogResult.OK) ppTxtBxPDFLoc.Text = PDFLocationBrowserDialog.SelectedPath; + } + + private void ppBtnDefCbTxt1_Click(object sender, EventArgs e) + { + // Compare default setting with current setting + // Reset with the default and hide the default button and label + if (_DefaultChgBarUsrMsg1 != _DocVersionConfig.Print_UserCBMess1) + { + _DocVersionConfig.Print_UserCBMess1 = _DefaultChgBarUsrMsg1; + ppLblChgBarUserMsgOneDefault.Visible = false; + ppBtnDefCbTxt1.Visible = false; + } + } + + private void ppBtnDefCbTxt2_Click(object sender, EventArgs e) + { + // Compare default setting with current setting + // Reset with the default and hide the default button and label + if (_DefaultChgBarUsrMsg2 != _DocVersionConfig.Print_UserCBMess2) + { + _DocVersionConfig.Print_UserCBMess2 = _DefaultChgBarUsrMsg2; + ppLblChgBarUserMsgTwoDefault.Visible = false; + ppBtnDefCbTxt2.Visible = false; + } + } + + private void ppBtnDeftDisAutoDuplx_Click(object sender, EventArgs e) + { + ppChbxDisAutoDuplex.Checked = _DefaultDisableDuplex; + _DocVersionConfig.Print_DisableDuplex = ppChbxDisAutoDuplex.Checked; + ppBtnDeftDisAutoDuplx.Visible = false; + ppLblAutoDuplexDefault.Visible = false; + } + + private void frmVersionsProperties_Shown(object sender, EventArgs e) + { + ppRTxtName.Focus(); + } + + private void ppRTxtName_Leave(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(ppRTxtName.Text)) + { + MessageBox.Show("Cannot have a blank Name."); + return; + } + } + + private void btnApplicability_Click(object sender, EventArgs e) + { + ProcessButtonClick(tiApplicability, btnApplicability); + } + + private void lbApplicabilities_SelectedIndexChanged(object sender, EventArgs e) + { + if (lbApplicabilities.SelectedIndex > -1) + { + bsMiniApple.DataSource = bsApples.Current as MiniConfig; + btnDelApple.Enabled = true; + } + + } + + private void btnNewApple_Click(object sender, EventArgs e) + { + MiniConfig cfg = new MiniConfig(); + + cfg.Name = "New Applicability"; + + if (_Apples == null) + { + _Apples = new List(); + } + _Apples.Add(cfg); + + bsApples.DataSource = null; + bsApples.DataSource = _Apples; + lbApplicabilities.SelectedItem = cfg; + } + + private bool ApplicIsUsed(MiniConfig cfg) // B2017-230 - don't allow user to remove an applicability that is being used (specified) + { + if (_showApplicSearchResults) + { + _showApplicSearchResults = false; + _DisplaySearch1.SearchResults = null; + } + + Cursor.Current = Cursors.WaitCursor; + ItemInfoList placesUsed = ItemInfoList.GetListFromApplicabilitySearch(_DocVersionConfig.MyDocVersion.VersionID.ToString(), "", "", 0, ItemSearchIncludeLinks.Nothing, false, false, "", cfg.Index.ToString()); + Cursor.Current = Cursors.Default; + + if (placesUsed != null && placesUsed.Count > 0) + { // B2017-230 give user option to save the locations in Global Search results + if (MessageBox.Show(string.Format("Cannot remove an Applicability that is being use in {0} places.\n\nDo you want to view locations via Search Results?\n\nThe Search panel will open when you exit the property page.", placesUsed.Count), "Applicability In Use", MessageBoxButtons.YesNo) == DialogResult.Yes) + { + _showApplicSearchResults = true; + _DisplaySearch1.SearchResults = placesUsed; + _DisplaySearch1.ReportTitle = string.Format("{0} Applicability", cfg.Name); + _DisplaySearch1.TypesSelected = string.Format("These Locations Specify The \"{0}\" Applicability", cfg.Name); + } + + return true; + } + + return false; + } + + private void btnDelApple_Click(object sender, EventArgs e) + { + MiniConfig cfg = bsApples.Current as MiniConfig; + + if (!ApplicIsUsed(cfg) && MessageBox.Show(string.Format("Are you sure you want to delete {0}", cfg.Name), "Confirm Delete", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) == DialogResult.Yes) + { + if (_DeletedApples == null) + { + _DeletedApples = new List(); + } + + _DeletedApples.Add(cfg); + _Apples.Remove(cfg); + + bsApples.DataSource = null; + bsApples.DataSource = _Apples; + // C2018-010: When removing an applicability, info on right side still contains old content. Do refreshes and reset datasource to fix this. + this.lbApplicabilities.Refresh(); + + if (_Apples != null && _Apples.Count > 0) + { + lbApplicabilities.SelectedIndex = 0; + bsMiniApple.DataSource = bsApples.Current as MiniConfig; + btnDelApple.Enabled = true; + } + } + } + + private void btnPhoneList_Click(object sender, EventArgs e) + { + dlgPhoneList dlgPL = new dlgPhoneList(_DocVersionConfig); + dlgPL.ShowDialog(); + } + + private void btnEnhanced_Click(object sender, EventArgs e) + { + ProcessButtonClick(tiEnhanced, btnEnhanced); + } + + private void lbEnhanced_SelectedIndexChanged(object sender, EventArgs e) + { + if (!_Initializing && lbEnhanced.SelectedIndex > -1 && !doingNew) + { + bsMiniEnhanced.DataSource = bsEnhanced.Current as EnhancedMiniConfig; + + if (cbxEnhVersions.Items.Count >= lbEnhanced.Items.Count) + cbxEnhVersions.SelectedIndex = lbEnhanced.SelectedIndex; + } + } + + private void btnNewEnh_Click(object sender, EventArgs e) + { + _Initializing = true; + doingNew = true; + + // the 'New' button is only enabled for Source documents. + EnhancedMiniConfig cfg = new EnhancedMiniConfig(); + cfg.Name = "New Enhanced"; + + // need to have a unique number for this enhanced link, find largest and then increment by 1. + int maxtype = -1; + + if (_DocVersionConfig.MyEnhancedDocuments != null && _DocVersionConfig.MyEnhancedDocuments.Count > 0) + { + foreach (DVEnhancedDocument dve in _DocVersionConfig.MyEnhancedDocuments) + { + maxtype = Math.Max(maxtype, dve.Type); + } + } + + maxtype = (maxtype < 0) ? 1 : maxtype + 1; + cfg.Type = maxtype.ToString(); + if (_Enhanced == null) _Enhanced = new List(); + _Enhanced.Add(cfg); + + bsEnhanced.DataSource = null; + bsEnhanced.DataSource = _Enhanced; + cbxEnhVersions.Items.Clear(); + NewEnhVersions.Clear(); + + DocVersionInfoList nonenhdvs = DocVersionInfoList.GetNonEnhancedDocVersions(); // this is a list of docversions that have no 'Enhanced' in config data + + foreach (DocVersionInfo nonenhdv in nonenhdvs) + { + if (nonenhdv.VersionID != _DocVersionConfig.MyDocVersion.VersionID) + { + if (((nonenhdv.ActiveFormat.PlantFormat.FormatData.PurchaseOptions.Value & E_PurchaseOptions.EnhancedBackgrounds) == E_PurchaseOptions.EnhancedBackgrounds) || + ((nonenhdv.ActiveFormat.PlantFormat.FormatData.PurchaseOptions.Value & E_PurchaseOptions.EnhancedDeviations) == E_PurchaseOptions.EnhancedDeviations)) + { + NewEnhVersions.Add(nonenhdv); + cbxEnhVersions.Items.Add(nonenhdv.SearchDVPath); + } + } + } + + if (cbxEnhVersions.Items.Count > 0) + { + cbxEnhVersions.Enabled = true; + cbxEnhVersions.SelectedIndex = 0; + } + else + { + cbxEnhVersions.Enabled = false; + } + + bsMiniEnhanced.DataSource = cfg; + lbEnhanced.SelectedItem = cfg; + tbEnhType.Enabled = false; + btnNewEnh.Enabled = false; // for now, only do 1 at a time. + + _Initializing = false; + } + + private void btnUnlinkDocVersion_Click(object sender, EventArgs e) + { + if (MessageBox.Show(this, "Are you sure you want to Unlink? Your documents will no longer link to Enhanced. NOTE that this processing occurs when 'OK' button is selected!", "Unlink", MessageBoxButtons.YesNo) == DialogResult.Yes) + { + _EnhNeedToUnlink = true; // do the unlink when 'OK' button is selected + } + } + + private void ppCmbxFormat_DropDown(object sender, EventArgs e) + { + _Initializing = true; + + // C2017-004 - if using the default format, position the dropdown to the default format + if (ppCmbxFormat.SelectedIndex == -1) + ppCmbxFormat.SelectedValue = _DefaultFormatName; + + _Initializing = false; + } + + private void ppCmbxFormat_DropDownClosed(object sender, EventArgs e) + { + // upon exit of the dropdown if the default format is selected - click the Default button + if ((string)(ppCmbxFormat.SelectedValue) == _DefaultFormatName) + { + ppBtnDefaultFmt.PerformClick(); + ppCmbxChangeBarType.Focus(); + } + } + + private void ppCmbxFormat_SelectedIndexChanged(object sender, EventArgs e) + { + if (_Initializing) + { + // determine if the default button and the default description text should visable + ppBtnDefaultFmt.Visible = !(ppCmbxFormat.SelectedValue == null || ppCmbxFormat.SelectedIndex == -1); + ppLblFormatDefault.Visible = ppCbShwDefSettings.Checked && ppBtnDefaultFmt.Visible; + return; + } + + if (_InitialIndex < -1) + _InitialIndex = ppCmbxFormat.SelectedIndex; // save the current format selection (happens here when current section format is not the default section) + + if ((ppCmbxFormat.SelectedIndex != -1) && _DefaultFormatName != null && _DefaultFormatName.Equals(ppCmbxFormat.SelectedValue)) + { + ppBtnDefaultFmt.Focus(); + ppBtnDefaultFmt.PerformClick(); + } + + // determine if the default button and the default description text should visable + ppBtnDefaultFmt.Visible = !(ppCmbxFormat.SelectedValue == null || ppCmbxFormat.SelectedIndex == -1); + ppLblFormatDefault.Visible = ppCbShwDefSettings.Checked && ppBtnDefaultFmt.Visible; + } + + // C2018-033 save the Prefix date/time format selection to config + private void ppCmbxPDFdtPrefix_SelectedValueChanged(object sender, EventArgs e) + { + if (!_Initializing) + { + if (ppCmbxPDFdtPrefix.SelectedIndex > 0) + { + ppTxtBxPdfPre.Enabled = false; // cannot have both entered text and a date/time format + } + else + { + _Initializing = true; + ppTxtBxPdfPre.Enabled = true; // not using the date/time format so allow for text entry + ppCmbxPDFdtPrefix.SelectedIndex = -1; + _DocVersionConfig.Print_PDFdtFilePrefix = 0; // this will force a database update (write) + _Initializing = false; + } + } + } + + // C2018-033 save the Suffix date/time format selection to config + private void ppCmbxPDFdtSuffix_SelectedValueChanged(object sender, EventArgs e) + { + if (!_Initializing) + { + if (ppCmbxPDFdtSuffix.SelectedIndex > 0) + { + ppTxtBxPDFSuf.Enabled = false; // cannot have both entered text and a date/time format + } + else + { + _Initializing = true; + ppTxtBxPDFSuf.Enabled = true; // not using the date/time format so allow for text entry + ppCmbxPDFdtSuffix.SelectedIndex = -1; + _DocVersionConfig.Print_PDFdtFileSuffix = 0; // this will force a database update (write) + _Initializing = false; + } + } + } + + private void ppCmbxMOSformat_SelectedIndexChanged(object sender, EventArgs e) + { + if (!_Initializing) + { + // The Other textbox for defining the merged pdf file page of format is only enabled if the user + // has selected 'Other' as the format type. + if ((MergedPdfsPageOf)ppCmbxMOSformat.SelectedValue == MergedPdfsPageOf.Other) + { + tbxMOSother.Text = _DocVersionConfig.Print_MergedPdfsPageNumFormatOther; + tbxMOSother.Enabled = true; + } + else + { + tbxMOSother.Enabled = false; + } + } + } + + // C2017-003: The button to migrate ro data from MS Access to sql server was clicked: + private void ppBtnRoToSql_Click(object sender, EventArgs e) + { + try + { + Application.DoEvents(); + + string exelocation = Application.ExecutablePath; + + exelocation = exelocation.Substring(0, exelocation.LastIndexOf("\\")) + @"\RoAccessToSql.exe"; + int indx = tbRoDb.Text.IndexOf(" (") + 2; + string accesspath = tbRoDb.Text.Substring(indx, tbRoDb.Text.Length - indx - 1); + string sqldb = Database.ActiveDatabase; + indx = Database.DBServer.IndexOf(" "); + string server = Database.DBServer.Substring(0, indx); + string args = @"/acc=" + accesspath + @" /sqldb=" + sqldb + @" /server=" + server; + + System.Diagnostics.Process p = System.Diagnostics.Process.Start(exelocation, args); + p.WaitForExit(); // without arguments, this will wait indefinitely + Application.DoEvents(); + + string _TmpFileForConnectStr = Path.GetTempPath() + @"\PromsConnect.txt"; + + if (File.Exists(_TmpFileForConnectStr)) // if conversion was done, the connection string will be added to the promsconnect.txt file + { + string constring = File.ReadAllText(_TmpFileForConnectStr); + + if (constring != null && constring != "" && constring.ToUpper().Contains("DATA SOURCE")) + { + // read in the connection string & set for this rodbinfo + using (RODb rodbtmp = RODb.GetJustRoDb(_CurRoDbInfo.RODbID)) + { + rodbtmp.DBConnectionString = File.ReadAllText(_TmpFileForConnectStr); + rodbtmp.Save(); + } + + // to be sure all aspects of program are using the converted database, tell user to restart: + MessageBox.Show(this, "Restart PROMS to have referenced object database migration take effect.", "", MessageBoxButtons.OK); + } + + ppBtnRoToSql.Visible = false; + } + } + catch (Exception ex) + { + while (ex.InnerException != null) + ex = ex.InnerException; + + MessageBox.Show(ex.Message, "Migration Error: " + ex.GetType().Name); + } + } + + #region (General Tab) /// /// This is the General button used on the button interface design @@ -750,7 +1443,7 @@ namespace VEPROMS #endregion - #region Referenced Objects + #region (Referenced Objects) /// /// This is the Referenced Objects button used on the button interface design @@ -762,9 +1455,85 @@ namespace VEPROMS ProcessButtonClick(tiRefObjs, btnRefObjs); } + private void btnRoDbProperties_Click(object sender, EventArgs e) + { + frmRODbProperties dlgROProperties = new frmRODbProperties(_DocVersionConfig.MyDocVersion, SelectedROFst == null ? null : SelectedROFst.MyRODb); + dlgROProperties.ParentLocation = Location; + + if (dlgROProperties.ShowDialog() == DialogResult.OK) + { + tbRoDb.Text = string.Format("{0} ({1})", SelectedROFst.MyRODb.ROName, SelectedROFst.MyRODb.FolderPath); + // only allow update if association, and the RO update was not done and/or not completed + ppBtnUpRoVals.Enabled = !_DocVersionConfig.MyDocVersion.ROfstLastCompleted || _DocVersionConfig.MyDocVersion.NewerRoFst; + } + } + + private void ppBtnUpRoVals_Click(object sender, EventArgs e) + { + InitialProgressBarMessage = "Updating ROs"; + + // use rodb directory path of the first rofst for the this document version. Bring up a file + // selection dialog starting with this path. The user can select another path. + // RHM question - we talked about just using the current path, but what is the current path when + // a docversion can have more than one rofst (for now, just use first?) - should I bring up a dialog? + if (_DocVersionConfig.MyDocVersion.DocVersionAssociations.Count < 1) + { + MessageBox.Show("Error Updating ro.fst.", "No associated ro.fst"); //B2017-125 added title to messagebox + return; + } + + foreach (DocVersionAssociation dva in _DocVersionConfig.MyDocVersion.DocVersionAssociations) + { + RODbInfo rdi = RODbInfo.Get(dva.ROFst_RODbID); + string rofstPath = rdi.FolderPath + @"\ro.fst"; + + if (!File.Exists(rofstPath)) + { + FinalProgressBarMessage = "No existing RO.FST"; + MessageBox.Show("No existing ro.fst in path " + rdi.FolderPath + ". Check for invalid path", "No existing RO.FST"); //B2017-125 added title to messagebox + break; + } + + Cursor = Cursors.WaitCursor; + + // RO changes placed in file in the Documents\VEPROMS folder + swROUpdate = new System.IO.StreamWriter(ROFstInfo.ROUpdateResultsPath(_DocVersionConfig.MyDocVersion.MyDocVersionInfo)); + DocVersion dv = _DocVersionConfig.MyDocVersion; + // B2022-026 RO Memory Reduction code - first load the new ro.fst so that we can assign the ROTableUpdate event to the correct roFstInfo + if (dv.ROfstLoadingFigures || dv.NewerRoFst) // B2017-125 see if loading figures was completed + { + ROFstInfo.UpdateRoFst(SelectedROFst.MyRODb, dv, SelectedROFst, DoProgressBarRefresh); + SelectedROFst = null; // set to null to force getting the updated ROfst + } + + ContentInfo.StaticContentInfoChange += ContentInfo_StaticContentInfoChange; // write changes to a text file + SelectedROFst.ROTableUpdate += new ROFstInfoROTableUpdateEvent(roFstInfo_ROTableUpdate); + + ROFst newrofst = ROFstInfo.RefreshROFst(_DocVersionConfig.MyDocVersion, SelectedROFst, DoProgressBarRefresh, null); + + ContentInfo.StaticContentInfoChange -= ContentInfo_StaticContentInfoChange; + SelectedROFst.ROTableUpdate -= new ROFstInfoROTableUpdateEvent(roFstInfo_ROTableUpdate); + + swROUpdate.Close(); + + ppBtnUpRoVals.Enabled = (!_DocVersionConfig.MyDocVersion.ROfstLastCompleted || _DocVersionConfig.MyDocVersion.NewerRoFst); + + Cursor = Cursors.Default; + } + + FinalProgressBarMessage = "ROs values updated"; + } + + // write the RO reference changes to a text file, include the old/new text, location, and the itemid of the step element + private void ContentInfo_StaticContentInfoChange(object sender, StaticContentInfoEventArgs args) + { + if (args.Type == "RO") + swROUpdate.Write(string.Format("Fixed Referenced Object for {1}({4}){0}Old Text: {2}{0}New Text: {3}{0}{0}", Environment.NewLine, (sender as ItemInfo).ShortPath, args.OldValue, args.NewValue, (sender as ItemInfo).ItemID)); + } + #endregion - #region Output Settings + #region (Output Settings) /// /// This is the Output Settings button used on the button interface design @@ -776,38 +1545,6 @@ namespace VEPROMS ProcessButtonClick(tiOutputSettings, btnOutputSettings); } - /// - /// Selection in Pagination combo box changed. - /// - /// object - /// EventArgs - //private void ppCmbxPagination_SelectedValueChanged(object sender, EventArgs e) - //{ - // if (!_Initializing) - // { - // PrintPagination pgtn = (PrintPagination)Enum.Parse(typeof(PrintPagination), _DefaultPagination); - // ProcessCmbxSelectionEnumChanged(ppCmbxPagination, pgtn, ppBtnDefPagination, ppLblPaginationDefault); - // } - //} - - /// - /// Reset to the parent setting. - /// Find the parent setting and assign it to _DocVersionConfig.Print_Pagination. - /// This will force the database to be updated. - /// - /// - /// - //private void ppBtnDefPagination_Click(object sender, EventArgs e) - //{ - // // Get the parent setting - // PrintPagination pgtn = (PrintPagination)Enum.Parse(typeof(PrintPagination), _DefaultPagination); - // // Compare parent setting with current setting - // if (pgtn != _DocVersionConfig.Print_Pagination) - // _DocVersionConfig.Print_Pagination = pgtn; // this will force a database update (write) - // ppCmbxPagination.SelectedIndex = -1; - // //tcpOutputSettings.Focus(); - //} - /// /// Selection in Watermark combo box changed. /// @@ -833,16 +1570,17 @@ namespace VEPROMS { // Get the parent setting PrintWatermark wtr = (PrintWatermark)Enum.Parse(typeof(PrintWatermark), _DefaultWatermark); + // Compare parent setting with current setting if (wtr != _DocVersionConfig.Print_Watermark) _DocVersionConfig.Print_Watermark = wtr; // this will force a database update (write) + ppCmbxWatermark.SelectedIndex = -1; - //tcpOutputSettings.Focus(); } #endregion - #region Format Settings + #region (Format Settings) /// /// This is the Format Settings button used on the button interface design @@ -859,7 +1597,6 @@ namespace VEPROMS private void ppBtnDefaultFmt_Click(object sender, EventArgs e) { ppCmbxFormat.SelectedIndex = -1; - //tcpFormatSettings.Focus(); } /// @@ -878,36 +1615,15 @@ namespace VEPROMS } - // commented out as part of code change C2017-004. this also makes it consistent with section properties - ///// - ///// Selection in Format combo box changed. - ///// - ///// object - ///// EventArgs - //private void ppCmbxFormat_SelectedValueChanged(object sender, EventArgs e) - //{ - // if (!_Initializing) - // ProcessCmbxSelectedValueChange(ppCmbxFormat, _DefaultFormatName, ppBtnDefaultFmt, ppLblFormatDefault); - //} - /// /// Enable or disable the user specified change bar options base on the type /// of change bar selected. /// private void setEnabledUserSpecifiedChgBarCombos(PrintChangeBar pcb) { - //ppGpbxUserSpecCB.Enabled = - //ppCmbxChgBarPos.Enabled = - //ppCmbxChgBarTxtType.Enabled = - //ppBtnDefaultCbPos.Enabled = - //ppBtnDefCbTxtTyp.Enabled = (ppCmbxChangeBarType.SelectedValue != null && - //ppCmbxChangeBarType.SelectedValue.Equals(DocVersionConfig.PrintChangeBar.WithUserSpecified)) || - //(ppCmbxChangeBarType.SelectedValue == null && pcb.Equals(DocVersionConfig.PrintChangeBar.WithUserSpecified)); - ppGpbxUserSpecCB.Enabled = (ppCmbxChangeBarType.SelectedValue != null && ppCmbxChangeBarType.SelectedValue.Equals(PrintChangeBar.WithUserSpecified)) || (ppCmbxChangeBarType.SelectedValue == null && pcb.Equals(PrintChangeBar.WithUserSpecified)); - } /// @@ -936,11 +1652,12 @@ namespace VEPROMS { // Get the parent setting PrintChangeBar pcb = (PrintChangeBar)Enum.Parse(typeof(PrintChangeBar), _DefaultChgBarType); + // Compare parent setting with current setting if (pcb != _DocVersionConfig.Print_ChangeBar) _DocVersionConfig.Print_ChangeBar = pcb; // this will force a database update (write) + ppCmbxChangeBarType.SelectedIndex = -1; //reset combo box to the default Change Bar setting - //tcpFormatSettings.Focus(); } /// @@ -968,11 +1685,12 @@ namespace VEPROMS { // Get the parent setting PrintChangeBarLoc cbl = (PrintChangeBarLoc)Enum.Parse(typeof(PrintChangeBarLoc), _DefaultChgBarLoc); + // Compare parent setting with current setting if (cbl != _DocVersionConfig.Print_ChangeBarLoc) _DocVersionConfig.Print_ChangeBarLoc = cbl; // this will force a database update (write) + ppCmbxChgBarPos.SelectedIndex = -1; - //tcpFormatSettings.Focus(); } /// @@ -981,15 +1699,6 @@ namespace VEPROMS /// private void setEnabledUserSpecifiedChgBarText() { - //ppGpbxUserSpecTxt.Enabled = - //ppTxbxChangeBarUserMsgOne.Enabled = - //ppTxbxChangeBarUserMsgTwo.Enabled = - //ppBtnDefCbTxt1.Enabled = - //ppBtnDefCbTxt2.Enabled = (ppCmbxChgBarTxtType.SelectedValue != null && - //ppCmbxChgBarTxtType.SelectedValue.Equals(DocVersionConfig.PrintChangeBarText.UserDef)); - - //string decUserDef = EnumDescConverter.GetEnumDescription(DocVersionConfig.PrintChangeBarText.UserDef); - // This string is used to check against our default setting to see if User Defined Changebar Text is active string decUserDef = PrintChangeBarText.UserDef.ToString(); @@ -1025,11 +1734,12 @@ namespace VEPROMS { // Get the parent setting PrintChangeBarText cbt = (PrintChangeBarText)Enum.Parse(typeof(PrintChangeBarText), _DefaultChgBarText); + // Compare parent setting with current setting if (cbt != _DocVersionConfig.Print_ChangeBarText) _DocVersionConfig.Print_ChangeBarText = cbt; // this will force a database update (write) + ppCmbxChgBarTxtType.SelectedIndex = -1; - //tcpFormatSettings.Focus(); } /// @@ -1056,26 +1766,7 @@ namespace VEPROMS #endregion - #region Library Documents - - /// - /// This is the Library Documents button used on the button interface design - /// - /// object - /// EventArgs - private void btnLibDocs_Click(object sender, EventArgs e) - { - ProcessButtonClick(tiLibDocs, btnLibDocs); - } - - #endregion - #region MergedOutputSettings - private void btnMergedOutputSettngs_Click(object sender, EventArgs e) - { - ProcessButtonClick(tiMergedOutputSettings, btnMergedOutputSettngs); - } - #endregion - #region Generic functions used on this property page + #region (Generic Methods for the Form) /// /// This is a generic Enter Event function for use with all of the property page tabs. @@ -1087,7 +1778,6 @@ namespace VEPROMS private void tabpage_Enter(object sender, EventArgs e) { // Show or hide the labels containing the default values - //if (!_Initializing) defaultSettingsVisiblity(); } @@ -1124,7 +1814,7 @@ namespace VEPROMS btnFmtSettings.Checked = false; btnLibDocs.Checked = false; btnApplicability.Checked = false; - btnMergedOutputSettngs.Checked = false; //B2019-074: turn off button when another is selected + btnMergedOutputSettngs.Checked = false; //B2019-074: turn off button when another is selected } /// @@ -1148,8 +1838,7 @@ namespace VEPROMS /// label containing the default private void ProcessCmbxSelectionEnumChanged(ComboBoxEx cmbx, object enumval, ButtonX button, Label deflabel) { - if ((cmbx.SelectedIndex != -1) && - cmbx.SelectedValue.Equals(enumval)) + if (cmbx.SelectedIndex > -1 && cmbx.SelectedValue.Equals(enumval)) { _Initializing = true; button.Visible = true; @@ -1158,6 +1847,7 @@ namespace VEPROMS cmbx.SelectedIndex = -1; // This will hide the Default button _Initializing = false; } + button.Visible = (cmbx.SelectedValue != null); deflabel.Visible = ppCbShwDefSettings.Checked && button.Visible; } @@ -1171,15 +1861,17 @@ namespace VEPROMS /// label containing the default private void ProcessCmbxSelectedValueChange(ComboBoxEx cmbx, string defstr, ButtonX button, Label deflabel) { - if ((cmbx.SelectedIndex != -1) && defstr != null && defstr.Equals(cmbx.SelectedValue)) + if (cmbx.SelectedIndex > -1 && !string.IsNullOrEmpty(defstr) && defstr.Equals(cmbx.SelectedValue)) { button.Visible = true; button.Focus(); button.PerformClick(); } + button.Visible = cmbx.SelectedValue != null; deflabel.Visible = ppCbShwDefSettings.Checked && button.Visible; } + /// /// Set the watermark and default label /// @@ -1188,7 +1880,7 @@ namespace VEPROMS /// Combo box with a watermark property private static void SetupDefault(string defaultText, Label lbl, ComboBoxEx cmbo) { - if (defaultText != null && !(defaultText.Equals(""))) + if (!string.IsNullOrEmpty(defaultText)) { string deftext = string.Format("{0}", defaultText); lbl.Text = deftext; @@ -1198,681 +1890,123 @@ namespace VEPROMS #endregion - private void btnRoDbProperties_Click(object sender, EventArgs e) + #region (MergedOutputSettings) + + private void btnMergedOutputSettngs_Click(object sender, EventArgs e) { - frmRODbProperties dlgROProperties = new frmRODbProperties(_DocVersionConfig.MyDocVersion, SelectedROFst == null ? null : SelectedROFst.MyRODb); - dlgROProperties.ParentLocation = Location; - if (dlgROProperties.ShowDialog() == DialogResult.OK) - { - tbRoDb.Text = string.Format("{0} ({1})", SelectedROFst.MyRODb.ROName, SelectedROFst.MyRODb.FolderPath); - // only allow update if association, and the RO update was not done and/or not completed - ppBtnUpRoVals.Enabled = !_DocVersionConfig.MyDocVersion.ROfstLastCompleted || _DocVersionConfig.MyDocVersion.NewerRoFst; - } + ProcessButtonClick(tiMergedOutputSettings, btnMergedOutputSettngs); } - private void ppBtnUpRoVals_Click(object sender, EventArgs e) - { - InitialProgressBarMessage = "Updating ROs"; - // use rodb directory path of the first rofst for the this document version. Bring up a file - // selection dialog starting with this path. The user can select another path. - // RHM question - we talked about just using the current path, but what is the current path when - // a docversion can have more than one rofst (for now, just use first?) - should I bring up a dialog? - if (_DocVersionConfig.MyDocVersion.DocVersionAssociations.Count < 1) - { - MessageBox.Show("Error Updating ro.fst.", "No associated ro.fst"); //B2017-125 added title to messagebox - return; - } - foreach (DocVersionAssociation dva in _DocVersionConfig.MyDocVersion.DocVersionAssociations) - { - RODbInfo rdi = RODbInfo.Get(dva.ROFst_RODbID); + #endregion - string rofstPath = rdi.FolderPath + @"\ro.fst"; - if (!File.Exists(rofstPath)) - { - FinalProgressBarMessage = "No existing RO.FST"; - MessageBox.Show("No existing ro.fst in path " + rdi.FolderPath + ". Check for invalid path", "No existing RO.FST"); //B2017-125 added title to messagebox - break; - } - // B2017-130 code no longer needed. Was checking the DTS but always was different by miliseconds - //FileInfo fiRofst = new FileInfo(rofstPath); - //if (SelectedROFst.DTS == fiRofst.LastWriteTimeUtc) - //{ - // FinalProgressBarMessage = "RO.FST up to date"; - // MessageBox.Show("ro.fst files are same for path " + rdi.FolderPath + ", import of that ro.fst will not be done", "RO.FST up to date"); //B2017-125 added title to messagebox - // break; - //} - //if (SelectedROFst.DTS > fiRofst.LastWriteTimeUtc) - //{ - // FinalProgressBarMessage = "RO.FST is older"; - // MessageBox.Show("Cannot copy older ro.fst from " + rdi.FolderPath + ", import of that ro.fst will not be done", "RO.FST is older"); //B2017-125 added title to messagebox - // break; - //} - Cursor = Cursors.WaitCursor; - swROUpdate = new System.IO.StreamWriter(ROFstInfo.ROUpdateResultsPath(_DocVersionConfig.MyDocVersion.MyDocVersionInfo)); // RO changes placed in file in the Documents\VEPROMS folder - ContentInfo.StaticContentInfoChange += ContentInfo_StaticContentInfoChange; // write changes to a text file - SelectedROFst.ROTableUpdate += new ROFstInfoROTableUpdateEvent(roFstInfo_ROTableUpdate); - ROFst newrofst = ROFstInfo.RefreshROFst(rdi, dva, _DocVersionConfig.MyDocVersion, SelectedROFst, DoProgressBarRefresh, null); - swROUpdate.Close(); - ContentInfo.StaticContentInfoChange -= ContentInfo_StaticContentInfoChange; - SelectedROFst.ROTableUpdate -= new ROFstInfoROTableUpdateEvent(roFstInfo_ROTableUpdate); - ppBtnUpRoVals.Enabled = !_DocVersionConfig.MyDocVersion.ROfstLastCompleted || _DocVersionConfig.MyDocVersion.NewerRoFst; - Cursor = Cursors.Default; - } - FinalProgressBarMessage = "ROs values updated"; + #region Library Documents + + /// + /// This is the Library Documents button used on the button interface design + /// + /// object + /// EventArgs + private void btnLibDocs_Click(object sender, EventArgs e) + { + ProcessButtonClick(tiLibDocs, btnLibDocs); } - private System.IO.StreamWriter swROUpdate; - // write the RO reference changes to a text file, include the old/new text, location, and the itemid of the step element - void ContentInfo_StaticContentInfoChange(object sender, StaticContentInfoEventArgs args) - { - if (args.Type == "RO") - swROUpdate.Write(string.Format("Fixed Referenced Object for {1}({4}){0}Old Text: {2}{0}New Text: {3}{0}{0}", Environment.NewLine, (sender as ItemInfo).ShortPath, args.OldValue, args.NewValue, (sender as ItemInfo).ItemID)); - } + #endregion - private ProgressBarItem _ProgressBar = null; - public ProgressBarItem ProgressBar - { - get { return _ProgressBar; } - set { _ProgressBar = value; } - } - private void DoProgressBarRefresh(int value, int max, string text) - { - if (ProgressBar == null) return; - ProgressBar.Maximum = max; - ProgressBar.Value = value; - ProgressBar.Text = text; - Application.DoEvents(); - } - private string InitialProgressBarMessage - { - set - { - if (ProgressBar == null) return; - ProgressBar.Value = 0; - ProgressBar.Maximum = 100; - ProgressBar.Text = value; - Application.DoEvents(); - } - } - private string FinalProgressBarMessage - { - set - { - if (ProgressBar == null) return; - ProgressBar.Maximum = 100; - ProgressBar.Value = 100; - ProgressBar.Text = value; - Application.DoEvents(); - } - } - public List roFstInfo_ROTableUpdate(object sender, ROFstInfoROTableUpdateEventArgs args) - { - string xml = null; - string srchtxt = null; - using (VlnFlexGrid myGrid = new VlnFlexGrid()) - { - using (StringReader sr = new StringReader(args.OldGridXml)) - { - myGrid.ReadXml(sr); - myGrid.KeyActionTab = C1.Win.C1FlexGrid.KeyActionEnum.MoveAcross; - sr.Close(); - } - string roid = myGrid.ROID; - int rodbid = myGrid.RODbId; - Font GridFont = myGrid.Font; - myGrid.Clear(); - myGrid.ParseTableFromText(args.ROText, GridLinePattern.Single); - myGrid.AutoSizeCols(); - myGrid.AutoSizeRows(); - myGrid.MakeRTFcells(); - myGrid.RODbId = rodbid; - myGrid.ROID = roid; - myGrid.IsRoTable = true; - using (StringWriter sw = new StringWriter()) - { - myGrid.WriteXml(sw); - xml = sw.GetStringBuilder().ToString(); - sw.Close(); - } - srchtxt = myGrid.GetSearchableText(); - } - List retlist = new List(); - retlist.Add(srchtxt); - retlist.Add(xml); - return retlist; - } - private void ppBtnResetRoVals_Click(object sender, EventArgs e) - { - // This will not be supported in the first release. A discussion was held on 1/6/09 with MRC, JSJ, RHM & - // KBR & it was decided that we'd wait to see if users end up needing this. It can be done by going - // into the sql database and modify/delete records if needed. - } - private RODbInfo _CurRoDbInfo = null; - private void cmbRoDb_SelectedIndexChanged(object sender, EventArgs e) - { - // The only way that a selected index can change on the rodb combo box is if there was no rofst - // to docversion association. If a selection is made, make that association and then change the - // combo box to a non-editable text box with button becoming a properties rather than browse. - if (_Initializing) return; - // add the rofst for the selected rodb (note that it may already exist, and will use the current - // one. - // get the rodb from the selection - and then do an 'update rofst'... - RODbInfoList rdil = RODbInfoList.Get(); - RODbInfo rdi = rdil[cmbRoDb.SelectedIndex]; - ROFstInfo fst=null; - foreach(ROFstInfo inf in rdi.RODbROFsts) - if(fst == null || inf.ROFstID > fst.ROFstID) - fst = inf; - if (fst != null) - { - using(ROFst fst1 = fst.Get()) - _DocVersionConfig.MyDocVersion.DocVersionAssociations.Add(fst1); - cmbRoDb.Visible = ppBtnRoDbBrowse.Visible = false; - tbRoDb.Visible = btnRoDbProperties.Visible = true; - tbRoDb.Text = string.Format("{0} ({1})", fst.MyRODb.ROName, fst.MyRODb.FolderPath); - // C2017-003: See if the selected ro databasew has been converted to sql and if not, make visible a button to convert the data. - ppBtnRoToSql.Visible = ppBtnRoToSql.Enabled = CanMigrateRoAccessToSql(fst.MyRODb); - _CurRoDbInfo = fst.MyRODb; - } - else - { - ROFst tmp = ROFstInfo.AddRoFst(rdi, _DocVersionConfig.MyDocVersion, DoProgressBarRefresh); // RHM Needs To Include Delegate - if (tmp == null) - { - MessageBox.Show("Invalid ro fst directory, use the Property dialog to fix directory path to ro.fst."); - frmRODbProperties dlgROProperties = new frmRODbProperties(_DocVersionConfig.MyDocVersion, rdi); - dlgROProperties.ProgressBar = ProgressBar; - if (dlgROProperties.ShowDialog() == DialogResult.OK) - { - tbRoDb.Text = string.Format("{0} ({1})", SelectedROFst.MyRODb.ROName, SelectedROFst.MyRODb.FolderPath); - // only allow update if association, and the RO update was not done and/or not completed - ppBtnUpRoVals.Enabled = !_DocVersionConfig.MyDocVersion.ROfstLastCompleted || _DocVersionConfig.MyDocVersion.NewerRoFst; - } - else - return; - } - cmbRoDb.Visible = ppBtnRoDbBrowse.Visible = false; - tbRoDb.Visible = btnRoDbProperties.Visible = true; - tbRoDb.Text = string.Format("{0} ({1})", tmp.MyRODb.ROName, tmp.MyRODb.FolderPath); - // C2017-003: See if the selected ro database has been converted to sql and if not, make visible a button to convert the data. - RODbInfo rodbi = RODbInfo.GetJustRODB(tmp.MyRODb.RODbID); - ppBtnRoToSql.Visible = ppBtnRoToSql.Enabled = CanMigrateRoAccessToSql(rodbi); - _CurRoDbInfo = rodbi; - } - } - - private bool CanMigrateRoAccessToSql(RODbInfo rODbi) - { - // C2017-003: This method is used to determine whether RO data can be migrated from MS Access to sql server - // A command line argument 'RoInSql'. For now, this argument must be used to allow code to run for ro->sql. Later - // this will be changed so that if arugment is used, the program does NOT include button. - if (!Volian.Base.Library.VlnSettings.GetCommandFlag("RoInSql")) return false; - - // The following conditions must be true in order to migrate the ro data to sql. Only the first condition can be - // tested in this executable since the roall database is interfaced to by the roeditor & the program that migrates the data. - // The migration program will make the 2-4 tests, put up a message box if it cannot migrate & will send a failure back - // to this program, PROMS. - // 1) the user must be an admin and the rodb record's connection string must be 'cstring' (it is the connection string if data was migrated) - // 2) the roall database must exist when using the rodb record's connection string and this database must have the stored procedures - // 3) roall must be empty - // 4) the database must be the correct version - UserInfo ui = UserInfo.GetByUserID(VlnSettings.UserID); - if (!ui.IsAdministrator()) return false; - return (rODbi.DBConnectionString == "cstring"); - } - - private void ppBtnRoDbBrowse_Click(object sender, EventArgs e) - { - frmRODbProperties dlgROProperties = new frmRODbProperties(_DocVersionConfig.MyDocVersion, SelectedROFst == null ? null : SelectedROFst.MyRODb); - dlgROProperties.ParentLocation = Location; - // if a user has entered a valid rodb, then this docversion will be conntected to it - change - // to a non-editable text box and the button becomes a properties button rather than browse. - if (dlgROProperties.ShowDialog() == DialogResult.OK) - { - cmbRoDb.Items.Clear(); - _DocVersionConfig.MyDocVersion.Reset_DocVersionAssociations(); - if (_DocVersionConfig.MyDocVersion.DocVersionAssociations != null && _DocVersionConfig.MyDocVersion.DocVersionAssociationCount > 0) - { - cmbRoDb.Visible = ppBtnRoDbBrowse.Visible = false; - tbRoDb.Visible = btnRoDbProperties.Visible = true; - tbRoDb.Text = string.Format("{0} ({1})", SelectedROFst.MyRODb.ROName, SelectedROFst.MyRODb.FolderPath); - return; - } - RODbInfoList.Reset(); - int selindx = -1; - int myrodbid = (SelectedROFst == null) ? -1 : SelectedROFst.RODbID; - foreach (RODbInfo rdi in RODbInfoList.Get()) - { - int i = cmbRoDb.Items.Add(rdi.ROName + " (" + rdi.FolderPath + ")"); - if (rdi.RODbID == myrodbid) selindx = i; - } - if (cmbRoDb.Items.Count > 0) cmbRoDb.SelectedIndex = selindx; - } - } - - private void ppBtnPDFLoc_Click(object sender, EventArgs e) - { - PDFLocationBrowserDialog.SelectedPath = ppTxtBxPDFLoc.Text; - DialogResult dr = PDFLocationBrowserDialog.ShowDialog(); - if (dr == DialogResult.OK) - ppTxtBxPDFLoc.Text = PDFLocationBrowserDialog.SelectedPath; - } - - private void ppBtnDefCbTxt1_Click(object sender, EventArgs e) - { - // Compare default setting with current setting - // Reset with the default and hide the default button and label - if (_DefaultChgBarUsrMsg1 != _DocVersionConfig.Print_UserCBMess1) - { - _DocVersionConfig.Print_UserCBMess1 = _DefaultChgBarUsrMsg1; - ppLblChgBarUserMsgOneDefault.Visible = false; - ppBtnDefCbTxt1.Visible = false; - //tcpFormatSettings.Focus(); - } - } - - private void ppBtnDefCbTxt2_Click(object sender, EventArgs e) - { - // Compare default setting with current setting - // Reset with the default and hide the default button and label - if (_DefaultChgBarUsrMsg2 != _DocVersionConfig.Print_UserCBMess2) - { - _DocVersionConfig.Print_UserCBMess2 = _DefaultChgBarUsrMsg2; - ppLblChgBarUserMsgTwoDefault.Visible = false; - ppBtnDefCbTxt2.Visible = false; - //tcpFormatSettings.Focus(); - } - } - - private void ppBtnDeftDisAutoDuplx_Click(object sender, EventArgs e) - { - ppChbxDisAutoDuplex.Checked = _DefaultDisableDuplex; - _DocVersionConfig.Print_DisableDuplex = ppChbxDisAutoDuplex.Checked; - ppBtnDeftDisAutoDuplx.Visible = false; - ppLblAutoDuplexDefault.Visible = false; - //tcpOutputSettings.Focus(); - } - - private void frmVersionsProperties_Shown(object sender, EventArgs e) - { - ppRTxtName.Focus(); - } - - private void ppRTxtName_Leave(object sender, EventArgs e) - { - if (ppRTxtName.Text == null || ppRTxtName.Text == "") - { - MessageBox.Show("Cannot have a blank Name."); - return; - } - } - - private void btnApplicability_Click(object sender, EventArgs e) - { - ProcessButtonClick(tiApplicability, btnApplicability); - } - - private void lbApplicabilities_SelectedIndexChanged(object sender, EventArgs e) - { - if (lbApplicabilities.SelectedIndex > -1) - { - bsMiniApple.DataSource = bsApples.Current as MiniConfig; - btnDelApple.Enabled = true; - } - - } - private void btnNewApple_Click(object sender, EventArgs e) - { - MiniConfig cfg = new MiniConfig(); - cfg.Name = "New Applicability"; - if (_Apples == null) - _Apples = new List(); - _Apples.Add(cfg); - bsApples.DataSource = null; - bsApples.DataSource = _Apples; - lbApplicabilities.SelectedItem = cfg; - } - public bool _showApplicSearchResults = false; - public bool _refreshProcedureList = false; - private bool ApplicIsUsed(MiniConfig cfg) // B2017-230 - don't allow user to remove an applicability that is being used (specified) - { - if (_showApplicSearchResults) - { - _showApplicSearchResults = false; - _DisplaySearch1.SearchResults = null; - } - Cursor.Current = Cursors.WaitCursor; - ItemInfoList placesUsed = ItemInfoList.GetListFromApplicabilitySearch(_DocVersionConfig.MyDocVersion.VersionID.ToString(), "", "", 0, ItemSearchIncludeLinks.Nothing, false, false, "", cfg.Index.ToString()); - Cursor.Current = Cursors.Default; - if (placesUsed != null && placesUsed.Count > 0) - { // B2017-230 give user option to save the locations in Global Search results - if (MessageBox.Show(string.Format("Cannot remove an Applicability that is being use in {0} places.\n\nDo you want to view locations via Search Results?\n\nThe Search panel will open when you exit the property page.",placesUsed.Count), "Applicability In Use", MessageBoxButtons.YesNo) == DialogResult.Yes) - { - _showApplicSearchResults = true; - _DisplaySearch1.SearchResults = placesUsed; - _DisplaySearch1.ReportTitle = string.Format("{0} Applicability", cfg.Name); - _DisplaySearch1.TypesSelected = string.Format("These Locations Specify The \"{0}\" Applicability", cfg.Name); - } - return true; - } - return false; - } - private void btnDelApple_Click(object sender, EventArgs e) - { - MiniConfig cfg = bsApples.Current as MiniConfig; - if (!ApplicIsUsed(cfg) && MessageBox.Show(string.Format("Are you sure you want to delete {0}", cfg.Name), "Confirm Delete", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) == DialogResult.Yes) - { - if (_DeletedApples == null) - _DeletedApples = new List(); - _DeletedApples.Add(cfg); - _Apples.Remove(cfg); - bsApples.DataSource = null; - bsApples.DataSource = _Apples; - // C2018-010: When removing an applicability, info on right side still contains old content. Do refreshes and reset datasource to fix this. - this.lbApplicabilities.Refresh(); - if (_Apples != null && _Apples.Count > 0) - { - lbApplicabilities.SelectedIndex = 0; - bsMiniApple.DataSource = bsApples.Current as MiniConfig; - btnDelApple.Enabled = true; - } - } - } - - private void btnPhoneList_Click(object sender, EventArgs e) - { - dlgPhoneList dlgPL = new dlgPhoneList(_DocVersionConfig); - dlgPL.ShowDialog(); - } - - private void btnEnhanced_Click(object sender, EventArgs e) - { - ProcessButtonClick(tiEnhanced, btnEnhanced); - } - - private void lbEnhanced_SelectedIndexChanged(object sender, EventArgs e) - { - if (!_Initializing && lbEnhanced.SelectedIndex > -1 && !doingNew) - { - bsMiniEnhanced.DataSource = bsEnhanced.Current as EnhancedMiniConfig; - if (cbxEnhVersions.Items.Count >= lbEnhanced.Items.Count) - cbxEnhVersions.SelectedIndex = lbEnhanced.SelectedIndex; - } - } - private List NewEnhVersions = new List(); - private bool doingNew = false; - private void btnNewEnh_Click(object sender, EventArgs e) - { - _Initializing = true; - doingNew = true; - // the 'New' button is only enabled for Source documents. - EnhancedMiniConfig cfg = new EnhancedMiniConfig(); - cfg.Name = "New Enhanced"; - // need to have a unique number for this enhanced link, find largest and then increment by 1. - int maxtype = -1; - if (_DocVersionConfig.MyEnhancedDocuments != null && _DocVersionConfig.MyEnhancedDocuments.Count > 0) - { - foreach (DVEnhancedDocument dve in _DocVersionConfig.MyEnhancedDocuments) - { - maxtype = Math.Max(maxtype, dve.Type); - } - } - if (maxtype < 0) maxtype = 1; - else maxtype++; - cfg.Type = maxtype.ToString(); - - if (_Enhanced == null) - _Enhanced = new List(); - _Enhanced.Add(cfg); - bsEnhanced.DataSource = null; - bsEnhanced.DataSource = _Enhanced; - cbxEnhVersions.Items.Clear(); - NewEnhVersions.Clear(); - DocVersionInfoList nonenhdvs = DocVersionInfoList.GetNonEnhancedDocVersions(); // this is a list of docversions that have no 'Enhanced' in config data - foreach (DocVersionInfo nonenhdv in nonenhdvs) - { - if (nonenhdv.VersionID != _DocVersionConfig.MyDocVersion.VersionID) - { - if (((nonenhdv.ActiveFormat.PlantFormat.FormatData.PurchaseOptions.Value & E_PurchaseOptions.EnhancedBackgrounds) == E_PurchaseOptions.EnhancedBackgrounds) || - ((nonenhdv.ActiveFormat.PlantFormat.FormatData.PurchaseOptions.Value & E_PurchaseOptions.EnhancedDeviations) == E_PurchaseOptions.EnhancedDeviations)) - { - NewEnhVersions.Add(nonenhdv); - cbxEnhVersions.Items.Add(nonenhdv.SearchDVPath); - } - } - } - if (cbxEnhVersions.Items.Count > 0) - { - cbxEnhVersions.Enabled = true; - cbxEnhVersions.SelectedIndex = 0; - } - else - cbxEnhVersions.Enabled = false; - bsMiniEnhanced.DataSource = cfg; - lbEnhanced.SelectedItem = cfg; - tbEnhType.Enabled = false; - btnNewEnh.Enabled = false; // for now, only do 1 at a time. - _Initializing = false; - } - private bool _EnhNeedToUnlink = false; - private void btnUnlinkDocVersion_Click(object sender, EventArgs e) - { - if (MessageBox.Show(this, "Are you sure you want to Unlink? Your documents will no longer link to Enhanced. NOTE that this processing occurs when 'OK' button is selected!", "Unlink", MessageBoxButtons.YesNo) == DialogResult.Yes) - { - _EnhNeedToUnlink = true; // do the unlink when 'OK' button is selected - } - } - - private void ppCmbxFormat_DropDown(object sender, EventArgs e) - { - _Initializing = true; - // C2017-004 - if using the default format, position the dropdown to the default format - if (ppCmbxFormat.SelectedIndex == -1) - ppCmbxFormat.SelectedValue = _DefaultFormatName; - _Initializing = false; - } - - private void ppCmbxFormat_DropDownClosed(object sender, EventArgs e) - { - // upon exit of the dropdown if the default format is selected - click the Default button - if ((string)(ppCmbxFormat.SelectedValue) == _DefaultFormatName) - { - ppBtnDefaultFmt.PerformClick(); - ppCmbxChangeBarType.Focus(); - } - } - - // added as part of code change C2017-004. this also makes it consistent with section properties - int _InitialIndex = -2; - private void ppCmbxFormat_SelectedIndexChanged(object sender, EventArgs e) - { - if (_Initializing) - { - // determine if the default button and the default description text should visable - ppBtnDefaultFmt.Visible = !(ppCmbxFormat.SelectedValue == null || ppCmbxFormat.SelectedIndex == -1); - ppLblFormatDefault.Visible = ppCbShwDefSettings.Checked && ppBtnDefaultFmt.Visible; - return; - } - if (_InitialIndex < -1) _InitialIndex = ppCmbxFormat.SelectedIndex; // save the current format selection (happens here when current section format is not the default section) - if ((ppCmbxFormat.SelectedIndex != -1) && _DefaultFormatName != null && _DefaultFormatName.Equals(ppCmbxFormat.SelectedValue)) - { - ppBtnDefaultFmt.Focus(); - ppBtnDefaultFmt.PerformClick(); - } - // determine if the default button and the default description text should visable - ppBtnDefaultFmt.Visible = !(ppCmbxFormat.SelectedValue == null || ppCmbxFormat.SelectedIndex == -1); - ppLblFormatDefault.Visible = ppCbShwDefSettings.Checked && ppBtnDefaultFmt.Visible; - } - - // C2018-033 save the Prefix date/time format selection to config - private void ppCmbxPDFdtPrefix_SelectedValueChanged(object sender, EventArgs e) - { - if (!_Initializing) - { - if (ppCmbxPDFdtPrefix.SelectedIndex > 0) - { - ppTxtBxPdfPre.Enabled = false; // cannot have both entered text and a date/time format - } - else - { - ppTxtBxPdfPre.Enabled = true; // not using the date/time format so allow for text entry - _Initializing = true; - ppCmbxPDFdtPrefix.SelectedIndex = -1; - _DocVersionConfig.Print_PDFdtFilePrefix = 0; // this will force a database update (write) - _Initializing = false; - } - } - } - - // C2018-033 save the Suffix date/time format selection to config - private void ppCmbxPDFdtSuffix_SelectedValueChanged(object sender, EventArgs e) - { - if (!_Initializing) - { - if (ppCmbxPDFdtSuffix.SelectedIndex > 0) - { - ppTxtBxPDFSuf.Enabled = false; // cannot have both entered text and a date/time format - } - else - { - ppTxtBxPDFSuf.Enabled = true; // not using the date/time format so allow for text entry - _Initializing = true; - ppCmbxPDFdtSuffix.SelectedIndex = -1; - _DocVersionConfig.Print_PDFdtFileSuffix = 0; // this will force a database update (write) - _Initializing = false; - } - } - } - - private void ppCmbxMOSformat_SelectedIndexChanged(object sender, EventArgs e) - { - if (!_Initializing) - { - // The Other textbox for defining the merged pdf file page of format is only enabled if the user - // has selected 'Other' as the format type. - if ((MergedPdfsPageOf)ppCmbxMOSformat.SelectedValue == MergedPdfsPageOf.Other) - { - tbxMOSother.Text = _DocVersionConfig.Print_MergedPdfsPageNumFormatOther; - tbxMOSother.Enabled = true; - } - else - tbxMOSother.Enabled = false; - } - } - - // C2017-003: The button to migrate ro data from MS Access to sql server was clicked: - private void ppBtnRoToSql_Click(object sender, EventArgs e) - { - string exelocation = Application.ExecutablePath; - try - { - Application.DoEvents(); - exelocation = exelocation.Substring(0, exelocation.LastIndexOf("\\")) + @"\RoAccessToSql.exe"; - int indx = tbRoDb.Text.IndexOf(" (")+2; - string accesspath = tbRoDb.Text.Substring(indx, tbRoDb.Text.Length - indx - 1); - string sqldb = Database.ActiveDatabase; - indx = Database.DBServer.IndexOf(" "); - string server = Database.DBServer.Substring(0, indx); - string args = @"/acc=" + accesspath + @" /sqldb=" + sqldb + @" /server=" + server; - System.Diagnostics.Process p = System.Diagnostics.Process.Start(exelocation, args); - p.WaitForExit(); // without arguments, this will wait indefinitely - Application.DoEvents(); - string _TmpFileForConnectStr = Path.GetTempPath(); - _TmpFileForConnectStr = _TmpFileForConnectStr + @"\PromsConnect.txt"; - if (File.Exists(_TmpFileForConnectStr)) // if conversion was done, the connection string will be added to the promsconnect.txt file - { - string constring = File.ReadAllText(_TmpFileForConnectStr); - if (constring != null && constring != "" && constring.ToUpper().Contains("DATA SOURCE")) - { - // read in the connection string & set for this rodbinfo - using (RODb rodbtmp = RODb.GetJustRoDb(_CurRoDbInfo.RODbID)) - { - rodbtmp.DBConnectionString = File.ReadAllText(_TmpFileForConnectStr); - rodbtmp.Save(); - } - // to be sure all aspects of program are using the converted database, tell user to restart: - MessageBox.Show(this, "Restart PROMS to have referenced object database migration take effect.", "", MessageBoxButtons.OK); - } - ppBtnRoToSql.Visible = false; - } - } - catch (Exception ex) - { - while (ex.InnerException != null) - ex = ex.InnerException; - string tmpmsg = ex.Message; - MessageBox.Show(tmpmsg, "Migration Error: " + ex.GetType().Name); - } - } - + #endregion } + + + #region EnhancedMiniConfig Class + [XmlRoot("Enhanced")] public class EnhancedMiniConfig { + #region Fields + private static int lastindex = 0; + private bool _isDeleted; + private bool _isDirty; + private int _index; + private int _versionID; + private string _versionPathName; + private string _name; + private string _type; + private string _pdfToken; + private string _pdfXOffset; + + #endregion + + #region Properties + [XmlIgnore] public bool IsDeleted { get { return _isDeleted; } set { _isDeleted = value; } } - private bool _isDirty; + [XmlIgnore] public bool IsDirty { get { return _isDirty; } set { _isDirty = value; } } - private int _index; + [XmlAttribute("index")] public int Index { get { return _index; } set { _index = value; IsDirty = true; } } - private int _versionID; + [XmlAttribute("VersionID")] public int VersionID { get { return _versionID; } set { _versionID = value; IsDirty = true; } } - private string _versionPathName; + [XmlAttribute("VersionPathName")] public string VersionPathName { get { return _versionPathName; } set { _versionPathName = value; IsDirty = true; } } - private string _name; + [XmlAttribute("Name")] public string Name { get { return _name; } set { _name = value; IsDirty = true; } } - private string _type; + [XmlAttribute("Type")] public string Type { get { return _type; } set { _type = value; IsDirty = true; } } - private string _pdfToken; + [XmlAttribute("PdfToken")] public string PdfToken { get { return _pdfToken; } set { _pdfToken = value; IsDirty = true; } } - private string _pdfXOffset; + [XmlAttribute("PdfXOffset")] public string PdfXOffset { get { return _pdfXOffset; } set { _pdfXOffset = value; IsDirty = true; } } + + #endregion + + #region Constructors + public EnhancedMiniConfig() { _index = --lastindex; @@ -1884,6 +2018,7 @@ namespace VEPROMS _pdfXOffset = string.Empty; _isDirty = false; } + public EnhancedMiniConfig(int index, int versionid, string id, string versionPathName, string name, string type, string pdftoken, string pdfxoffset) { _index = index; @@ -1895,113 +2030,152 @@ namespace VEPROMS _pdfXOffset = pdfxoffset; _isDirty = false; } + + #endregion + + #region Public Methods + public override string ToString() { return Name; } + + #endregion } + + #endregion + + + #region MiniConfig Class + [XmlRoot("Slave")] public class MiniConfig { + #region Fields + private static int lastindex = 0; + private bool _isDeleted; + private bool _isDirty; + private int _index; + private string _iD; + private string _name; + private string _number; + private string _text; + private string _procedureNumber; + private string _setID; + private string _setName; + private string _otherID; + private string _otherName; + private string _otherNumber; + private string _otherText; + + #endregion + + #region Properties + [XmlIgnore] public bool IsDeleted { get { return _isDeleted; } set { _isDeleted = value; } } - private bool _isDirty; + [XmlIgnore] public bool IsDirty { get { return _isDirty; } set { _isDirty = value; } } - private int _index; + [XmlAttribute("index")] public int Index { get { return _index; } set { _index = value; IsDirty = true; } } - private string _iD; + [XmlAttribute("ID")] public string ID { get { return _iD; } set { _iD = value; IsDirty = true; } } - private string _name; + [XmlAttribute("Name")] public string Name { get { return _name; } set { _name = value; IsDirty = true; } } - private string _number; + [XmlAttribute("Number")] public string Number { get { return _number; } set { _number = value; IsDirty = true; } } - private string _text; + [XmlAttribute("Text")] public string Text { get { return _text; } set { _text = value; IsDirty = true; } } - private string _procedureNumber; + [XmlAttribute("ProcedureNumber")] public string ProcedureNumber { get { return _procedureNumber; } set { _procedureNumber = value; IsDirty = true; } } - private string _setID; + [XmlAttribute("SetID")] public string SetID { get { return _setID; } set { _setID = value; IsDirty = true; } } - private string _setName; + [XmlAttribute("SetName")] public string SetName { get { return _setName; } set { _setName = value; IsDirty = true; } } - private string _otherID; + [XmlAttribute("OtherID")] public string OtherID { get { return _otherID; } set { _otherID = value; IsDirty = true; } } - private string _otherName; + [XmlAttribute("OtherName")] public string OtherName { get { return _otherName; } set { _otherName = value; IsDirty = true; } } - private string _otherNumber; + [XmlAttribute("OtherNumber")] public string OtherNumber { get { return _otherNumber; } set { _otherNumber = value; IsDirty = true; } } - private string _otherText; - [XmlAttribute("OyherText")] // 11/3/21: Typo that is in data. Don't fix unless writing code to fix data + + [XmlAttribute("OyherText")] // 11/3/21: Typo that is in data. Don't fix unless writing code to fix data public string OtherText { get { return _otherText; } set { _otherText = value; IsDirty = true; } } + + #endregion + + #region Constructors + public MiniConfig() { _index = --lastindex; @@ -2018,6 +2192,7 @@ namespace VEPROMS _otherText = string.Empty; _isDirty = false; } + public MiniConfig(int index, string id, string name, string number, string text, string procedurenumber, string setid, string setname, string otherid, string othername, string othernumber, string othertext) { _index = index; @@ -2034,29 +2209,24 @@ namespace VEPROMS _otherText = othertext; _isDirty = false; } + + #endregion + + #region Public Methods + public override string ToString() { return Name; } + public string MyXml { get { return GenericSerializer.StringSerialize(this); } } - //#region XML Serializer Namespaces - //private XmlSerializerNamespaces _Namespaces = null; - //[XmlNamespaceDeclarations] - //public XmlSerializerNamespaces Namespaces - //{ - // get - // { - // if (_Namespaces == null) - // { - // _Namespaces = new XmlSerializerNamespaces(); - // } - // return _Namespaces; - // } - // set { _Namespaces = value; } - //} - //#endregion + + #endregion } + + #endregion + } diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/ContentExt.cs b/PROMS/VEPROMS.CSLA.Library/Extension/ContentExt.cs index 14319e1f..bceb68ad 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/ContentExt.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/ContentExt.cs @@ -40,42 +40,42 @@ namespace VEPROMS.CSLA.Library string newvalue = tran != null ? tran.ResolvePathTo() : string.Empty; if (forceConvertToText) newvalue = "?"; - string findLink = @""; - // B2019-084: Procedure number change not updated in pasted transition - there were 2 '", rousg.ROUsageID); + string findLink = @""; + // B2019-084: Procedure number change not updated in pasted transition - there were 2 '", rousg.ROUsageID); string lookFor; if (tran == null) { // B2018-002 - Invalid Transitions - Handle Range Transitions int loc1 = Text.IndexOf("#Link:Transition:", 0); - if(loc1 > 0) loc1+=("#Link:Transition:").Length; - else - loc1 = Text.IndexOf("#Link:TransitionRange:", 0)+ ("#Link:TransitionRange:").Length;; + if (loc1 > 0) loc1 += ("#Link:Transition:").Length; + else + loc1 = Text.IndexOf("#Link:TransitionRange:", 0) + ("#Link:TransitionRange:").Length; ; int loc2 = Text.IndexOf(" ", loc1); string trantype = Text.Substring(loc1, loc2 - loc1); loc1 = loc2 + 1; loc2 = Text.IndexOf(" ", loc1); string tranid = Text.Substring(loc1, loc2 - loc1); - lookFor = string.Format(@"^", trantype, tranid); + lookFor = string.Format(@"^", trantype, tranid); } else lookFor = string.Format(@"^", tran.TranType, tran.TransitionID); - foreach (Match mm in ms) - { - Match m = Regex.Match(mm.Value, lookFor, RegexOptions.Singleline); - if (m != null && m.Groups.Count > 1) - { + foreach (Match mm in ms) + { + Match m = Regex.Match(mm.Value, lookFor, RegexOptions.Singleline); + if (m != null && m.Groups.Count > 1) + { int myIndex = m.Groups[4].Index + mm.Index; - int myLength = m.Groups[4].Length; - if (m.Groups[3].Value != " ") - { - myIndex = m.Groups[3].Index + mm.Index; - myLength += m.Groups[3].Length; - } - string gg = Text.Substring(myIndex, myLength); - newvalue = newvalue.Replace("{", @"\{").Replace("}", @"\}"); + int myLength = m.Groups[4].Length; + if (m.Groups[3].Value != " ") + { + myIndex = m.Groups[3].Index + mm.Index; + myLength += m.Groups[3].Length; + } + string gg = Text.Substring(myIndex, myLength); + newvalue = newvalue.Replace("{", @"\{").Replace("}", @"\}"); if (newvalue == "?") // B2017-165 used to also check if gg and newvalue were different AND newvalue = '?'. Had case where gg also was = '?' (from 16-bit conversion) { string rv = ConvertTransitionToText(tran, newvalue); @@ -90,54 +90,54 @@ namespace VEPROMS.CSLA.Library if (tran == null) prefix = "Invalid "; Annotation.MakeAnnotation(myitem, AnnotationType.GetByNameOrCreate("Link Converted To Text"), "", prefix + string.Format("Transition ({0}) converted to text", ItemInfo.ConvertToDisplayText(gg)), null); } - if(tran != null) + if (tran != null) Transition.Delete(tran.TransitionID); didFixATransition = true; // B2017-076 return Transitions were processed (used when importing a procedure) break; } //else if ((gg.Contains("\\u8209?") ? gg.Replace("\\u8209?", "-") : gg) != (newvalue.Contains("\\u8209?") ? newvalue.Replace("\\u8209?", "-") : newvalue)) else if ((gg.Replace(@"\u8209?", "-").Replace(@"\u9568?", @"\\")) != (newvalue.Replace(@"\u8209?", "-").Replace(@"\u9568?", @"\\"))) - { + { Text = Text.Substring(0, myIndex) + newvalue + Text.Substring(myIndex + myLength); didFixATransition = true; // B2017-076 return Transitions were processed (used when importing a procedure) break; // Text has been processed - } - } - } + } + } + } // see if there is a grid to update too. if (tran != null && tran.MyContent.MyGrid != null) { - //string lookForXml = string.Format(@"<START\](\\[^v \\]+)*\\v0(\\[^v \\]+)* ([^#]*?)(\\[^v'? \\]+)*\\v(\\[^v \\]+)* #Link:Transition[^:]*?:{0} {1}( [0-9]*){{1,2}}\[END>", tran.TranType, tran.TransitionID); - //Match mg = Regex.Match(MyGrid.Data, lookForXml); - //if (mg != null && mg.Groups.Count > 1) - //{ - // System.Text.RegularExpressions.Group g = mg.Groups[3]; - // if (g.ToString() != transText) - // MyGrid.Data = MyGrid.Data.Substring(0, g.Index) + transText + MyGrid.Data.Substring(g.Index + g.Length); - //} - string findLinkXml = @"<START\].*?\[END>"; - //string lookForXml = string.Format(@"<START\](\\[^v \\]+)*\\v0(\\[^v \\]+)* (.*?)(\\[^v '?\\]+)*\\v(\\[^v \\]+)* #Link:ReferencedObject:{0} .*?\[END>", rousg.ROUsageID); - string lookForXml = string.Format(@"^<START\](\\[^v \\]+)*\\v0(\\[^v '?{{}}\\]+)*( |\\u[0-9]{{1,4}}?|\\'[0-9a-fA-F]{{2}}|\\[{{}}~])(.*?)(\\[^v'?{{}} \\]+)*\\v(\\[^v \\]+)* #Link:Transition[^:]*?:{0} {1}( [0-9]*){{1,2}}\[END>", tran.TranType, tran.TransitionID); - MatchCollection msg = Regex.Matches(MyGrid.Data, findLinkXml); - foreach (Match mmg in msg) - { - Match mg = Regex.Match(mmg.Value, lookForXml);// Regex.Match(MyGrid.Data, lookForXml); - if (mg != null && mg.Groups.Count > 1) - { - int myIndex = mg.Groups[4].Index + mmg.Index; - int myLength = mg.Groups[4].Length; - if (mg.Groups[3].Value != " ") - { - myIndex = mg.Groups[3].Index + mmg.Index; - myLength += mg.Groups[3].Length; - } - string gg = MyGrid.Data.Substring(myIndex, myLength); + //string lookForXml = string.Format(@"<START\](\\[^v \\]+)*\\v0(\\[^v \\]+)* ([^#]*?)(\\[^v'? \\]+)*\\v(\\[^v \\]+)* #Link:Transition[^:]*?:{0} {1}( [0-9]*){{1,2}}\[END>", tran.TranType, tran.TransitionID); + //Match mg = Regex.Match(MyGrid.Data, lookForXml); + //if (mg != null && mg.Groups.Count > 1) + //{ + // System.Text.RegularExpressions.Group g = mg.Groups[3]; + // if (g.ToString() != transText) + // MyGrid.Data = MyGrid.Data.Substring(0, g.Index) + transText + MyGrid.Data.Substring(g.Index + g.Length); + //} + string findLinkXml = @"<START\].*?\[END>"; + //string lookForXml = string.Format(@"<START\](\\[^v \\]+)*\\v0(\\[^v \\]+)* (.*?)(\\[^v '?\\]+)*\\v(\\[^v \\]+)* #Link:ReferencedObject:{0} .*?\[END>", rousg.ROUsageID); + string lookForXml = string.Format(@"^<START\](\\[^v \\]+)*\\v0(\\[^v '?{{}}\\]+)*( |\\u[0-9]{{1,4}}?|\\'[0-9a-fA-F]{{2}}|\\[{{}}~])(.*?)(\\[^v'?{{}} \\]+)*\\v(\\[^v \\]+)* #Link:Transition[^:]*?:{0} {1}( [0-9]*){{1,2}}\[END>", tran.TranType, tran.TransitionID); + MatchCollection msg = Regex.Matches(MyGrid.Data, findLinkXml); + foreach (Match mmg in msg) + { + Match mg = Regex.Match(mmg.Value, lookForXml);// Regex.Match(MyGrid.Data, lookForXml); + if (mg != null && mg.Groups.Count > 1) + { + int myIndex = mg.Groups[4].Index + mmg.Index; + int myLength = mg.Groups[4].Length; + if (mg.Groups[3].Value != " ") + { + myIndex = mg.Groups[3].Index + mmg.Index; + myLength += mg.Groups[3].Length; + } + string gg = MyGrid.Data.Substring(myIndex, myLength); if (newvalue.Contains(@"\u8209?")) // process dash - newvalue = ProcessSpecChar(gg, newvalue, @"\u8209?","-"); + newvalue = ProcessSpecChar(gg, newvalue, @"\u8209?", "-"); if (newvalue.Contains(@"\u8593?")) // process carrot/delta - newvalue = ProcessSpecChar(gg, newvalue, @"\u8593?","^"); + newvalue = ProcessSpecChar(gg, newvalue, @"\u8593?", "^"); if (newvalue.Contains(@"\u9586?")) // process backslash - newvalue = ProcessSpecChar(gg, newvalue, @"\u9586?",@"\\"); + newvalue = ProcessSpecChar(gg, newvalue, @"\u9586?", @"\\"); if (gg != newvalue) { if (newvalue == "?") @@ -146,11 +146,11 @@ namespace VEPROMS.CSLA.Library MyGrid.Data = MyGrid.Data.Substring(0, myIndex) + newvalue + MyGrid.Data.Substring(myIndex + myLength); didFixATransition = true; // B2017-076 return Transitions were processed (used when importing a procedure) } - } - } - } + } + } + } return didFixATransition; - } + } private string ProcessSpecChar(string orgText, string newValue, string specChar, string kbChar) { @@ -207,25 +207,25 @@ namespace VEPROMS.CSLA.Library Match m = Regex.Match(mm.Value, lookFor, RegexOptions.Singleline); if (m != null && m.Groups.Count > 1) { - int myIndex = m.Groups[4].Index + mm.Index; - int myLength = m.Groups[4].Length; - if (m.Groups[3].Value != " ") - { - myIndex = m.Groups[3].Index + mm.Index; - myLength += m.Groups[3].Length; - } - string ss = MyGrid.Data.Substring(myIndex, myLength); - if (ss != newvalue) - { - int ii = MyGrid.Data.Substring(0, mm.Index).LastIndexOf(@"\v"); - int iil = MyGrid.Data.Substring(mm.Index + m.Value.Length).IndexOf(@"\v0"); - string part1 = MyGrid.Data.Substring(0, ii); // length up to \v - string part2 = MyGrid.Data.Substring(ii + 2, mm.Index - (ii + 2)); - string part3 = ss; - string part4 = MyGrid.Data.Substring(mm.Index + m.Value.Length, iil); - string part5 = MyGrid.Data.Substring(mm.Index + (m.Value.Length + iil + 3)); - MyGrid.Data = part1 + part2 + part3 + part4 + part5; - } + int myIndex = m.Groups[4].Index + mm.Index; + int myLength = m.Groups[4].Length; + if (m.Groups[3].Value != " ") + { + myIndex = m.Groups[3].Index + mm.Index; + myLength += m.Groups[3].Length; + } + string ss = MyGrid.Data.Substring(myIndex, myLength); + if (ss != newvalue) + { + int ii = MyGrid.Data.Substring(0, mm.Index).LastIndexOf(@"\v"); + int iil = MyGrid.Data.Substring(mm.Index + m.Value.Length).IndexOf(@"\v0"); + string part1 = MyGrid.Data.Substring(0, ii); // length up to \v + string part2 = MyGrid.Data.Substring(ii + 2, mm.Index - (ii + 2)); + string part3 = ss; + string part4 = MyGrid.Data.Substring(mm.Index + m.Value.Length, iil); + string part5 = MyGrid.Data.Substring(mm.Index + (m.Value.Length + iil + 3)); + MyGrid.Data = part1 + part2 + part3 + part4 + part5; + } break; // Text has been processed } lastIndex = mm.Index + mm.Length; @@ -253,7 +253,7 @@ namespace VEPROMS.CSLA.Library loc1 = loc2 + 1; loc2 = Text.IndexOf(" ", loc1); string tranid = Text.Substring(loc1, loc2 - loc1); - lookFor = string.Format(@"^", trantype, tranid); + lookFor = string.Format(@"^", trantype, tranid); } else lookFor = string.Format(@"^", tran.TranType, tran.TransitionID); @@ -382,9 +382,9 @@ namespace VEPROMS.CSLA.Library { string txt = Text.Substring(start); int firstSlashVeeZero = txt.IndexOf(@"\v0"); - if (firstSlashVeeZero == 0 && txt.Length > 3 && txt[3] == ' ') //"\v0 " + if (firstSlashVeeZero == 0 && txt.Length > 3 && txt[3] == ' ') //"\v0 " return Text.Substring(start, 4); - return Text.Substring(start, firstSlashVeeZero + 3); //everything upto \v0" + return Text.Substring(start, firstSlashVeeZero + 3); //everything upto \v0" } private string GetMyPrefix(int start, int lastIndex) { @@ -393,7 +393,7 @@ namespace VEPROMS.CSLA.Library if (tText.Contains(@"\fs")) { tText = Regex.Replace(tText, @"\\v\\fs[0-9]+ ", "\\v "); - start = tText.IndexOf(""; MatchCollection ms = Regex.Matches(Text, findLink); - //string lookFor = string.Format(@"", rousg.ROUsageID); + //string lookFor = string.Format(@"", rousg.ROUsageID); //string lookFor = string.Format(@"^$", rousg.ROUsageID); string strROUID = (rousg != null) ? rousg.ROUsageID.ToString() : roidFrmImportStep; string lookFor = string.Format(@"^$", strROUID); - int lastIndex = 0; + int lastIndex = 0; string newText = Text; foreach (Match mm in ms) { @@ -437,16 +437,16 @@ namespace VEPROMS.CSLA.Library { string prefix = GetMyPrefix(mm.Index, lastIndex); string suffix = GetMySuffix(mm.Index + mm.Length); - int myIndex = m.Groups[4].Index + mm.Index; - int myLength = m.Groups[4].Length; - if (m.Groups[3].Value != " ") - { - myIndex = m.Groups[3].Index + mm.Index; - myLength += m.Groups[3].Length; - } - string gg = newText.Substring(myIndex, myLength); + int myIndex = m.Groups[4].Index + mm.Index; + int myLength = m.Groups[4].Length; + if (m.Groups[3].Value != " ") + { + myIndex = m.Groups[3].Index + mm.Index; + myLength += m.Groups[3].Length; + } + string gg = newText.Substring(myIndex, myLength); retval = gg; - gg = gg.Replace("{", @"\{").Replace("}", @"\}"); + gg = gg.Replace("{", @"\{").Replace("}", @"\}"); string part1 = newText.Substring(0, mm.Index); string part2 = gg; string part3 = newText.Substring(mm.Index + mm.Length); @@ -459,36 +459,36 @@ namespace VEPROMS.CSLA.Library if (suffix == @"\v0 ") part3 = part3.Substring(4); else - part3 = suffix.Replace(@"\v0","") + part3.Substring(suffix.Length); - if (gg.Contains(@"\u8209?")) - { - Match mmm = Regex.Match(gg, @"(\\f[0-9]+)(\\u[0-9]{1,4}\?)(\\f[0-9]+ ?)"); - if (mmm == null) - newvalue = newvalue.Replace(@"\u8209?", "-"); - else - newvalue = newvalue.Replace(@"\u8209?", m.Groups[1].Value + @"\u8209?" + m.Groups[3].Value); - } - if (gg.Contains(@"\u9586?")) - { - Match mmm = Regex.Match(gg, @"(\\f[0-9]+)(\\u[0-9]{1,4}\?)(\\f[0-9]+ ?)"); - if (mmm == null) + part3 = suffix.Replace(@"\v0", "") + part3.Substring(suffix.Length); + if (gg.Contains(@"\u8209?")) + { + Match mmm = Regex.Match(gg, @"(\\f[0-9]+)(\\u[0-9]{1,4}\?)(\\f[0-9]+ ?)"); + if (mmm == null) + newvalue = newvalue.Replace(@"\u8209?", "-"); + else + newvalue = newvalue.Replace(@"\u8209?", m.Groups[1].Value + @"\u8209?" + m.Groups[3].Value); + } + if (gg.Contains(@"\u9586?")) + { + Match mmm = Regex.Match(gg, @"(\\f[0-9]+)(\\u[0-9]{1,4}\?)(\\f[0-9]+ ?)"); + if (mmm == null) newvalue = newvalue.Replace(@"\u9586?", @"\\"); - else + else newvalue = newvalue.Replace(@"\u9586?", m.Groups[1].Value + @"\u9586?" + m.Groups[3].Value); - } - //System.Text.RegularExpressions.Group g2 = m.Groups[2]; - //if (g2.Value.StartsWith(@"\u8209?")) - //{ - // string gg = g2.Value + " " + g.Value; - // retval = gg; - // part2 = retval; - //} - //else - ////else if (g.ToString() != newvalue) - //{ - // retval = g.Value; - // part2 = retval; - //} + } + //System.Text.RegularExpressions.Group g2 = m.Groups[2]; + //if (g2.Value.StartsWith(@"\u8209?")) + //{ + // string gg = g2.Value + " " + g.Value; + // retval = gg; + // part2 = retval; + //} + //else + ////else if (g.ToString() != newvalue) + //{ + // retval = g.Value; + // part2 = retval; + //} Text = part1 + part2 + part3; break; // Text has been processed } @@ -516,9 +516,9 @@ namespace VEPROMS.CSLA.Library { // if it's an ro within a table, need to process into an flex grid to save the grid data: string findLinkXml = @"<START\].*?\[END>"; - //string lookForXml = string.Format(@"<START\](\\[^v \\]+)*\\v0(\\[^v \\]+)* (.*?)(\\[^v '?\\]+)*\\v(\\[^v \\]+)* #Link:ReferencedObject:{0} .*?\[END>", rousg.ROUsageID); + //string lookForXml = string.Format(@"<START\](\\[^v \\]+)*\\v0(\\[^v \\]+)* (.*?)(\\[^v '?\\]+)*\\v(\\[^v \\]+)* #Link:ReferencedObject:{0} .*?\[END>", rousg.ROUsageID); string lookForXml = string.Format(@"^<START\](\\[^v \\]+)*\\v0(\\[^v '?{{}}\\]+)*( |\\u[0-9]{{1,4}}?|\\'[0-9a-fA-F]{{2}}|\\[{{}}~])(.*?)(\\[^v'?{{}} \\]+)*\\v(\\[^v \\]+)* #Link:ReferencedObject:{0} .*?\[END>$", strROUID); - MatchCollection msg = Regex.Matches(MyGrid.Data, findLinkXml); + MatchCollection msg = Regex.Matches(MyGrid.Data, findLinkXml); int nmsg = msg.Count; for (int i = nmsg - 1; i >= 0; i--) { @@ -526,36 +526,36 @@ namespace VEPROMS.CSLA.Library Match mg = Regex.Match(mmg.Value, lookForXml);// Regex.Match(MyGrid.Data, lookForXml); if (mg != null && mg.Groups.Count > 1) { - int myIndex = mg.Groups[4].Index + mmg.Index; - int myLength = mg.Groups[4].Length; - if (mg.Groups[3].Value != " ") - { - myIndex = mg.Groups[3].Index + mmg.Index; - myLength += mg.Groups[3].Length; - } - string gg = MyGrid.Data.Substring(myIndex, myLength); + int myIndex = mg.Groups[4].Index + mmg.Index; + int myLength = mg.Groups[4].Length; + if (mg.Groups[3].Value != " ") + { + myIndex = mg.Groups[3].Index + mmg.Index; + myLength += mg.Groups[3].Length; + } + string gg = MyGrid.Data.Substring(myIndex, myLength); if (value == "?") newvalue = gg; // B2017-060 the text part of the RO link - if (newvalue.Contains(@"\u8209?")) - { - Match m = Regex.Match(newvalue, @"(\\f[0-9]+)(\\u[0-9]{1,4}\?)(\\f[0-9]+ ?)"); - if (m == null) - newvalue = newvalue.Replace(@"\u8209?", "-"); - else - newvalue = newvalue.Replace(@"\u8209?", m.Groups[1].Value + @"\u8209?" + m.Groups[3].Value); - } - if (newvalue.Contains(@"\u9586?")) - { - Match m = Regex.Match(newvalue, @"(\\f[0-9]+)(\\u[0-9]{1,4}\?)(\\f[0-9]+ ?)"); - if (m == null) + if (newvalue.Contains(@"\u8209?")) + { + Match m = Regex.Match(newvalue, @"(\\f[0-9]+)(\\u[0-9]{1,4}\?)(\\f[0-9]+ ?)"); + if (m == null) + newvalue = newvalue.Replace(@"\u8209?", "-"); + else + newvalue = newvalue.Replace(@"\u8209?", m.Groups[1].Value + @"\u8209?" + m.Groups[3].Value); + } + if (newvalue.Contains(@"\u9586?")) + { + Match m = Regex.Match(newvalue, @"(\\f[0-9]+)(\\u[0-9]{1,4}\?)(\\f[0-9]+ ?)"); + if (m == null) newvalue = newvalue.Replace(@"\u9586?", @"\\"); - else + else newvalue = newvalue.Replace(@"\u9586?", m.Groups[1].Value + @"\u9586?" + m.Groups[3].Value); - } - if (value == "?" || gg != newvalue) - { + } + if (value == "?" || gg != newvalue) + { MyGrid.Data = Content.ConvertGridROsToText(MyGrid.Data, mmg, mg, newvalue); // B2017-060 convert the RO in the grid (table) to text - } + } } } } @@ -613,26 +613,26 @@ namespace VEPROMS.CSLA.Library return retval; } string newvalue = value; - newvalue = newvalue.Replace("{", @"\{").Replace("}", @"\}"); + newvalue = newvalue.Replace("{", @"\{").Replace("}", @"\}"); string findLink = @""; MatchCollection ms = Regex.Matches(Text, findLink); - //string lookFor = string.Format(@"", rousg.ROUsageID); - string lookFor = string.Format(@"^$", rousg.ROUsageID); - foreach (Match mm in ms) + //string lookFor = string.Format(@"", rousg.ROUsageID); + string lookFor = string.Format(@"^$", rousg.ROUsageID); + foreach (Match mm in ms) { Match m = Regex.Match(mm.Value, lookFor, RegexOptions.Singleline); if (m != null && m.Groups.Count > 1) { - int myIndex = m.Groups[4].Index + mm.Index; - int myLength = m.Groups[4].Length; - if(m.Groups[3].Value != " ") - { - myIndex = m.Groups[3].Index + mm.Index; - myLength += m.Groups[3].Length; - } - string gg = Text.Substring(myIndex,myLength); - if (((fileNameOnly == null) && (MakeConsistentFormat(gg) != MakeConsistentFormat(newvalue))) || ((fileNameOnly != null) && !(gg.Replace(@"\u8209?", "-").StartsWith(fileNameOnly) && newvalue.Replace(@"\u8209?", "-").StartsWith(fileNameOnly)))) - { + int myIndex = m.Groups[4].Index + mm.Index; + int myLength = m.Groups[4].Length; + if (m.Groups[3].Value != " ") + { + myIndex = m.Groups[3].Index + mm.Index; + myLength += m.Groups[3].Length; + } + string gg = Text.Substring(myIndex, myLength); + if (((fileNameOnly == null) && (MakeConsistentFormat(gg) != MakeConsistentFormat(newvalue))) || ((fileNameOnly != null) && !(gg.Replace(@"\u8209?", "-").StartsWith(fileNameOnly) && newvalue.Replace(@"\u8209?", "-").StartsWith(fileNameOnly)))) + { retval = gg; Text = Text.Substring(0, myIndex) + newvalue + Text.Substring(myIndex + myLength); if (!saveAnnotation) @@ -670,7 +670,7 @@ namespace VEPROMS.CSLA.Library { // if it's an ro within a table, need to process into an flex grid to save the grid data: string findLinkXml = @"<START\].*?\[END>"; - //string lookForXml = string.Format(@"<START\](\\[^v \\]+)*\\v0(\\[^v \\]+)* (.*?)(\\[^v '?\\]+)*\\v(\\[^v \\]+)* #Link:ReferencedObject:{0} .*?\[END>", rousg.ROUsageID); + //string lookForXml = string.Format(@"<START\](\\[^v \\]+)*\\v0(\\[^v \\]+)* (.*?)(\\[^v '?\\]+)*\\v(\\[^v \\]+)* #Link:ReferencedObject:{0} .*?\[END>", rousg.ROUsageID); string lookForXml = string.Format(@"^<START\](\\[^v \\]+)*\\v0(\\[^v '?{{}}\\]+)*( |\\u[0-9]{{1,4}}?|\\'[0-9a-fA-F]{{2}}|\\[{{}}~])(.*?)(\\[^v'?{{}} \\]+)*\\v(\\[^v \\]+)* #Link:ReferencedObject:{0} .*?\[END>$", rousg.ROUsageID); MatchCollection msg = Regex.Matches(MyGrid.Data, findLinkXml); foreach (Match mmg in msg) @@ -678,39 +678,39 @@ namespace VEPROMS.CSLA.Library Match mg = Regex.Match(mmg.Value, lookForXml);// Regex.Match(MyGrid.Data, lookForXml); if (mg != null && mg.Groups.Count > 1) { - int myIndex = mg.Groups[4].Index + mmg.Index; - int myLength = mg.Groups[4].Length; - if (mg.Groups[3].Value != " ") - { - myIndex = mg.Groups[3].Index + mmg.Index; - myLength += mg.Groups[3].Length; - } - string gg = MyGrid.Data.Substring(myIndex, myLength); - if (newvalue.Contains(@"\u8209?")) - { - Match m = Regex.Match(newvalue, @"(\\f[0-9]+)(\\u[0-9]{1,4}\?)(\\f[0-9]+ ?)"); - if (m == null) - newvalue = newvalue.Replace(@"\u8209?", "-"); - else - newvalue = newvalue.Replace(@"\u8209?", m.Groups[1].Value + @"\u8209?" + m.Groups[3].Value); - } - if (newvalue.Contains(@"\u8593?")) - { - Match m = Regex.Match(newvalue, @"(\\f[0-9]+)(\\u[0-9]{1,4}\?)(\\f[0-9]+ ?)"); - if (m == null) - newvalue = newvalue.Replace(@"\u8593?", "^"); - else - newvalue = newvalue.Replace(@"\u8593?", m.Groups[1].Value + @"\u8593?" + m.Groups[3].Value); - } - if (newvalue.Contains(@"\u9586?")) - { - Match m = Regex.Match(newvalue, @"(\\f[0-9]+)(\\u[0-9]{1,4}\?)(\\f[0-9]+ ?)"); - if (m == null) - newvalue = newvalue.Replace(@"\u9586?", @"\\"); - else - newvalue = newvalue.Replace(@"\u9586?", m.Groups[1].Value + @"\u9586?" + m.Groups[3].Value); - } - if (gg != newvalue) + int myIndex = mg.Groups[4].Index + mmg.Index; + int myLength = mg.Groups[4].Length; + if (mg.Groups[3].Value != " ") + { + myIndex = mg.Groups[3].Index + mmg.Index; + myLength += mg.Groups[3].Length; + } + string gg = MyGrid.Data.Substring(myIndex, myLength); + if (newvalue.Contains(@"\u8209?")) + { + Match m = Regex.Match(newvalue, @"(\\f[0-9]+)(\\u[0-9]{1,4}\?)(\\f[0-9]+ ?)"); + if (m == null) + newvalue = newvalue.Replace(@"\u8209?", "-"); + else + newvalue = newvalue.Replace(@"\u8209?", m.Groups[1].Value + @"\u8209?" + m.Groups[3].Value); + } + if (newvalue.Contains(@"\u8593?")) + { + Match m = Regex.Match(newvalue, @"(\\f[0-9]+)(\\u[0-9]{1,4}\?)(\\f[0-9]+ ?)"); + if (m == null) + newvalue = newvalue.Replace(@"\u8593?", "^"); + else + newvalue = newvalue.Replace(@"\u8593?", m.Groups[1].Value + @"\u8593?" + m.Groups[3].Value); + } + if (newvalue.Contains(@"\u9586?")) + { + Match m = Regex.Match(newvalue, @"(\\f[0-9]+)(\\u[0-9]{1,4}\?)(\\f[0-9]+ ?)"); + if (m == null) + newvalue = newvalue.Replace(@"\u9586?", @"\\"); + else + newvalue = newvalue.Replace(@"\u9586?", m.Groups[1].Value + @"\u9586?" + m.Groups[3].Value); + } + if (gg != newvalue) { retval = gg; MyGrid.Data = MyGrid.Data.Substring(0, myIndex) + newvalue + MyGrid.Data.Substring(myIndex + myLength); @@ -728,11 +728,13 @@ namespace VEPROMS.CSLA.Library // replace degree, bullet dash, hardspace return ROFSTLookup.ConvertFortranFormatToScienctificNotation(gg).Replace("`", @"\'B0").Replace(@"\'b0", @"\'B0").Replace(@"\u8209?", "-").Replace(@"\u160?", " ").Replace("\xA0", " ").Replace(@"\'a0", " ").Replace(@"\'A0", " "); } + private string FixValue(string str) { return str.Replace(@"\u8209?", "-").Replace(@"\u160?", " "); //dash and hard space } } + public delegate void StaticContentInfoEvent(object sender, StaticContentInfoEventArgs args); public class StaticContentInfoEventArgs { @@ -761,22 +763,26 @@ namespace VEPROMS.CSLA.Library _Type = type; } } + public partial class ContentInfo { public static string FormatByteArray(byte[] myArray) { StringBuilder sb = new StringBuilder(); + for (int i = 0; i < myArray.Length; i++) { sb.Append(string.Format("{0:x2}", myArray[i])); } + return sb.ToString(); } + public string LastChangedString { get { return ContentInfo.FormatByteArray(_LastChanged); } } - //Convert.ToInt64( ByteArrayToHexString(_ts), 16 ) ) + public Int64 LastChangedInt64 { get { return Convert.ToInt64(LastChangedString, 16); } @@ -792,62 +798,71 @@ namespace VEPROMS.CSLA.Library if (StaticContentInfoChange != null) StaticContentInfoChange(sender, args); } - public string MyContentMessage = string.Empty; - public string MyGridMessage = string.Empty; + public string MyContentMessage = string.Empty; + public string MyGridMessage = string.Empty; public bool InList(params int[] IDs) { foreach (int id in IDs) + { if (id == ContentID) return true; + } + return false; } public void FixTransitionText(TransitionInfo tran, TransitionLookup tranLookup, ItemInfo ii) { FixTransitionText(tran, tranLookup, ii, ""); } - public void FixTransitionText(TransitionInfo tran, TransitionLookup tranLookup, ItemInfo ii, string forceConvertToText) + + public void FixTransitionText(TransitionInfo tran, ItemInfo ii) { - //string transText = tran.ResolvePathTo(); - //string lookFor = string.Format(@"", tran.TranType, tran.TransitionID); - ////string lookFor = string.Format(@"", tran.TranType, tran.TransitionID); - //Match m = Regex.Match(Text, lookFor); - //if (m != null && m.Groups.Count > 1) - //{ - // System.Text.RegularExpressions.Group g = m.Groups[3]; - // if (g.ToString() != transText) - // _Text = Text.Substring(0, g.Index) + transText + Text.Substring(g.Index + g.Length); - //} - string newvalue; - MyContentMessage = string.Empty; - if (tranLookup == null) - newvalue = tran.ResolvePathTo(); - else - newvalue = tran.ResolvePathTo(tranLookup); + FixTransitionText(tran, ii, ""); + } + + public void FixTransitionText(TransitionInfo tran, ItemInfo ii, string forceConvertToText) + { + FixTransitionText(tran, null, ii, forceConvertToText); + } + + public void FixTransitionText(TransitionInfo tran, TransitionLookup tranLookup, ItemInfo ii, string forceConvertToText) + { + string newvalue; + MyContentMessage = string.Empty; + + if (tranLookup == null) + newvalue = tran.ResolvePathTo(); + else + newvalue = tran.ResolvePathTo(tranLookup); + if (forceConvertToText != string.Empty) newvalue = "?"; - string findLink = @""; - // B2019-084: There were 2 '", rousg.ROUsageID); + + string findLink = @""; + + // B2019-084: There were 2 '", tran.TranType, tran.TransitionID); - foreach (Match mm in ms) - { - Match m = Regex.Match(mm.Value, lookFor, RegexOptions.Singleline); - if (m != null && m.Groups.Count > 1) - { - int myIndex = m.Groups[4].Index + mm.Index; - int myLength = m.Groups[4].Length; - if (m.Groups[3].Value != " ") - { - myIndex = m.Groups[3].Index + mm.Index; - myLength += m.Groups[3].Length; - } - string gg = Text.Substring(myIndex, myLength); - MyContentMessage = string.Format("ContentExt.ContentInfo:Content:{0}, {1}, {2}", this.ContentID, tran.TransitionID, gg); - newvalue = newvalue.Replace("{", @"\{").Replace("}", @"\}"); - if ((gg.Replace(@"\u8209?", "-").Replace(@"\u9586?",@"\\")) != (newvalue.Replace("\\u8209?", "-").Replace(@"\u9586?",@"\\")) || newvalue == "?") // B2017-165 added check of newvalue - { - _Text = Text.Substring(0, myIndex) + newvalue + Text.Substring(myIndex + myLength); + + foreach (Match mm in ms) + { + Match m = Regex.Match(mm.Value, lookFor, RegexOptions.Singleline); + if (m != null && m.Groups.Count > 1) + { + int myIndex = m.Groups[4].Index + mm.Index; + int myLength = m.Groups[4].Length; + if (m.Groups[3].Value != " ") + { + myIndex = m.Groups[3].Index + mm.Index; + myLength += m.Groups[3].Length; + } + string gg = Text.Substring(myIndex, myLength); + MyContentMessage = string.Format("ContentExt.ContentInfo:Content:{0}, {1}, {2}", this.ContentID, tran.TransitionID, gg); + newvalue = newvalue.Replace("{", @"\{").Replace("}", @"\}"); + if ((gg.Replace(@"\u8209?", "-").Replace(@"\u9586?", @"\\")) != (newvalue.Replace("\\u8209?", "-").Replace(@"\u9586?", @"\\")) || newvalue == "?") // B2017-165 added check of newvalue + { + _Text = Text.Substring(0, myIndex) + newvalue + Text.Substring(myIndex + myLength); if (newvalue == "?") { gg = ItemInfo.ConvertToDisplayText(gg); @@ -868,10 +883,10 @@ namespace VEPROMS.CSLA.Library OnStaticContentInfoChange(ii, new StaticContentInfoEventArgs(gg, newvalue, "TX")); break; // Text has been processed } - } - } - } - // see if there is a grid to update too. + } + } + } + // see if there is a grid to update too. if (tran.MyContent.MyGrid != null) { //string lookForXml = string.Format(@"<START\](\\[^v \\]+)*\\v0(\\[^v \\]+)* ([^#]*?)(\\[^v'? \\]+)*\\v(\\[^v \\]+)* #Link:Transition[^:]*?:{0} {1}( [0-9]*){{1,2}}\[END>", tran.TranType, tran.TransitionID); @@ -910,13 +925,13 @@ namespace VEPROMS.CSLA.Library else newvalue = newvalue.Replace(@"\u8209?", m.Groups[1].Value + @"\u8209?" + m.Groups[3].Value); } - if (newvalue.Contains(@"\u8593?")) + if (newvalue.Contains(@"\u9586?")) { Match m = Regex.Match(newvalue, @"(\\f[0-9]+)(\\u[0-9]{1,4}\?)(\\f[0-9]+ ?)"); if (m == null) - newvalue = newvalue.Replace(@"\u8593?", "^"); + newvalue = newvalue.Replace(@"\u9586?", @"\\"); else - newvalue = newvalue.Replace(@"\u8593?", m.Groups[1].Value + @"\u8593?" + m.Groups[3].Value); + newvalue = newvalue.Replace(@"\u9586?", m.Groups[1].Value + @"\u9586?" + m.Groups[3].Value); } if (newvalue.Contains(@"\u9586?")) { @@ -935,70 +950,47 @@ namespace VEPROMS.CSLA.Library } } } - public void FixTransitionText(TransitionInfo tran, ItemInfo ii) - { - FixTransitionText(tran, ii, ""); - } - public void FixTransitionText(TransitionInfo tran, ItemInfo ii, string forceConvertToText) - { - FixTransitionText(tran, null, ii, forceConvertToText); - //string transText = tran.ResolvePathTo(tranLookup); - //string lookFor = string.Format(@"", tran.TranType, tran.TransitionID); - ////string lookFor = string.Format(@"", tran.TranType, tran.TransitionID); - //Match m = Regex.Match(Text, lookFor); - //if (m != null && m.Groups.Count > 1) - //{ - // System.Text.RegularExpressions.Group g = m.Groups[3]; - // if (g.ToString() != transText) - // _Text = Text.Substring(0, g.Index) + transText + Text.Substring(g.Index + g.Length); - //} - //// see if there is a grid to update too. - //if (MyGrid != null) - //{ - // string lookForXml = string.Format(@"<START\](\\[^v \\]+)*\\v0(\\[^v \\]+)* ([^#]*?)(\\[^v'? \\]+)*\\v(\\[^v \\]+)* #Link:Transition[^:]*?:{0} {1}( [0-9]*){{1,2}}\[END>", tran.TranType, tran.TransitionID); - // Match mg = Regex.Match(MyGrid.Data, lookForXml); - // if (mg != null && mg.Groups.Count > 1) - // { - // System.Text.RegularExpressions.Group g = mg.Groups[3]; - // if (g.ToString() != transText) - // MyGrid.SetData(MyGrid.Data.Substring(0, g.Index) + transText + MyGrid.Data.Substring(g.Index + g.Length)); - // } - //} - } - public void FixContentText(RoUsageInfo rousg, string value, int rotype, ROFstInfo origROFstInfo, ItemInfo ii) // string newvalue) + + public void FixContentText(RoUsageInfo rousg, string value, int rotype, ROFstInfo origROFstInfo, ItemInfo ii) { string fileNameOnly = null; + //B2020-127 don't try to parse out a file name from "?" (happens with the RO figure no longer exists) // - this allows it to drop through and put an annotation on the step if (ii.IsFigure && Text != null && Text.Length > 0 && value != "?") - fileNameOnly = value.Substring(0,value.IndexOf("\n")).Replace(@"\u8209?","-"); // check only the file name of the RO figure + { + fileNameOnly = value.Substring(0, value.IndexOf("\n")).Replace(@"\u8209?", "-"); // check only the file name of the RO figure + } + string newvalue = value; - newvalue = newvalue.Replace("{", @"\{").Replace("}", @"\}"); + newvalue = newvalue.Replace("{", @"\{").Replace("}", @"\}"); newvalue = newvalue.Replace(@"\up2 \u8209?", @"\up2\u8209?");// B2017-167 Remove spurious space in RO Value between two RTF Commands - string findLink = @""; + string findLink = @""; MatchCollection ms = Regex.Matches(Text, findLink); - //string lookFor = string.Format(@"", rousg.ROUsageID); - string lookFor = string.Format(@"^$", rousg.ROUsageID); - foreach (Match mm in ms) + string lookFor = string.Format(@"^$", rousg.ROUsageID); + + foreach (Match mm in ms) { int offset = mm.Index; Match m = Regex.Match(mm.Value, lookFor, RegexOptions.Singleline); + if (m != null && m.Groups.Count > 1) { - int myIndex = m.Groups[4].Index + mm.Index; - int myLength = m.Groups[4].Length; - if (m.Groups[3].Value != " ") - { - myIndex = m.Groups[3].Index + mm.Index; - myLength += m.Groups[3].Length; - } - string gg = Text.Substring(myIndex, myLength); + int myIndex = m.Groups[4].Index + mm.Index; + int myLength = m.Groups[4].Length; + + if (m.Groups[3].Value != " ") + { + myIndex = m.Groups[3].Index + mm.Index; + myLength += m.Groups[3].Length; + } + + string gg = Text.Substring(myIndex, myLength); + if (((fileNameOnly == null) && (Content.MakeConsistentFormat(gg) != Content.MakeConsistentFormat(newvalue))) || ((fileNameOnly != null) && !(gg.Replace(@"\u8209?", "-").StartsWith(fileNameOnly) && newvalue.Replace(@"\u8209?", "-").StartsWith(fileNameOnly)))) { - // Debug - jsj 5-19-2017 - left in for initial check-in - //string gg_org = gg; - //string newval_org = newvalue; _Text = Text.Substring(0, myIndex) + newvalue + _Text.Substring(myIndex + myLength); + if (newvalue == "?") { gg = ItemInfo.ConvertToDisplayText(gg); @@ -1006,6 +998,7 @@ namespace VEPROMS.CSLA.Library OnStaticContentInfoChange(ii, new StaticContentInfoEventArgs(gg, newvalue, "RO")); break; } + if (newvalue.StartsWith(gg) && (newvalue.ToUpper().Contains("BMP") || newvalue.ToUpper().Contains("GIF") || newvalue.ToUpper().Contains("TIF"))) { break; // Text has been processed @@ -1021,67 +1014,74 @@ namespace VEPROMS.CSLA.Library OnStaticContentInfoChange(ii, new StaticContentInfoEventArgs(gg, newvalue, "RO")); break; // Text has been processed } - } - } + } + } } + // see if there is a grid to update too. if (MyGrid != null) { if (rotype == (int)E_ROValueType.Table) // if change in rotable data... { - List retlist = origROFstInfo.OnROTableUpdate(this, new ROFstInfoROTableUpdateEventArgs(newvalue, MyGrid.Data)); + List retlist = origROFstInfo.OnROTableUpdate(this.Get(), new ROFstInfoROTableUpdateEventArgs(newvalue, MyGrid.Data)); if (Text != retlist[0]) _Text = retlist[0]; - //if (MyGrid.Data != retlist[1]) MyGrid.Data = retlist[1]; } else { // if it's an ro within a table, need to process into an flex grid to save the grid data: string findLinkXml = @"<START\].*?\[END>"; - //string lookForXml = string.Format(@"<START\](\\[^v \\]+)*\\v0(\\[^v \\]+)* (.*?)(\\[^v '?\\]+)*\\v(\\[^v \\]+)* #Link:ReferencedObject:{0} .*?\[END>", rousg.ROUsageID); - string lookForXml = string.Format(@"^<START\](\\[^v \\]+)*\\v0(\\[^v '?{{}}\\]+)*( |\\u[0-9]{{1,4}}?|\\'[0-9a-fA-F]{{2}}|\\[{{}}~])(.*?)(\\[^v'?{{}} \\]+)*\\v(\\[^v \\]+)* #Link:ReferencedObject:{0} .*?\[END>$", rousg.ROUsageID); - MatchCollection msg = Regex.Matches(MyGrid.Data, findLinkXml); + string lookForXml = string.Format(@"^<START\](\\[^v \\]+)*\\v0(\\[^v '?{{}}\\]+)*( |\\u[0-9]{{1,4}}?|\\'[0-9a-fA-F]{{2}}|\\[{{}}~])(.*?)(\\[^v'?{{}} \\]+)*\\v(\\[^v \\]+)* #Link:ReferencedObject:{0} .*?\[END>$", rousg.ROUsageID); + MatchCollection msg = Regex.Matches(MyGrid.Data, findLinkXml); + foreach (Match mmg in msg) { //int offset = 0; // crashed in substring line below if using mmg.Index; Set to 0 and it worked - KBR. Match mg = Regex.Match(mmg.Value, lookForXml); + if (mg != null && mg.Groups.Count > 1) { - int myIndex = mg.Groups[4].Index; - int myLength = mg.Groups[4].Length; - if (mg.Groups[3].Value != " ") - { - myIndex = mg.Groups[3].Index ; - myLength += mg.Groups[3].Length; - } - string gg = MyGrid.Data.Substring(myIndex+ mmg.Index, myLength); - if (newvalue.Contains(@"\u8209?")) - { - Match m = Regex.Match(gg, @"(\\f[0-9]+)(\\u[0-9]{1,4}\?)(\\f[0-9]+ ?)"); - if (m.Groups.Count < 3) - newvalue = newvalue.Replace(@"\u8209?", "-"); - else - newvalue = newvalue.Replace(@"\u8209?", m.Groups[1].Value + @"\u8209?" + m.Groups[3].Value); - } - if (newvalue.Contains(@"\u8593?")) - { - Match m = Regex.Match(newvalue, @"(\\f[0-9]+)(\\u[0-9]{1,4}\?)(\\f[0-9]+ ?)"); - if (m.Groups.Count < 3) - newvalue = newvalue.Replace(@"\u8593?", "^"); - else - newvalue = newvalue.Replace(@"\u8593?", m.Groups[1].Value + @"\u8593?" + m.Groups[3].Value); - } - if (newvalue.Contains(@"\u9586?")) - { - Match m = Regex.Match(newvalue, @"(\\f[0-9]+)(\\u[0-9]{1,4}\?)(\\f[0-9]+ ?)"); - if (m.Groups.Count < 3) - newvalue = newvalue.Replace(@"\u9586?", @"\\"); - else - newvalue = newvalue.Replace(@"\u9586?", m.Groups[1].Value + @"\u9586?" + m.Groups[3].Value); - } - if (gg != newvalue) + int myIndex = mg.Groups[4].Index; + int myLength = mg.Groups[4].Length; + + if (mg.Groups[3].Value != " ") { - string prefix1 = MyGrid.Data.Substring(0,mmg.Index); - string prefix2 = mmg.Value.Substring(0,myIndex); + myIndex = mg.Groups[3].Index; + myLength += mg.Groups[3].Length; + } + + string gg = MyGrid.Data.Substring(myIndex + mmg.Index, myLength); + + if (newvalue.Contains(@"\u8209?")) + { + Match m = Regex.Match(gg, @"(\\f[0-9]+)(\\u[0-9]{1,4}\?)(\\f[0-9]+ ?)"); + if (m.Groups.Count < 3) + newvalue = newvalue.Replace(@"\u8209?", "-"); + else + newvalue = newvalue.Replace(@"\u8209?", m.Groups[1].Value + @"\u8209?" + m.Groups[3].Value); + } + + if (newvalue.Contains(@"\u8593?")) + { + Match m = Regex.Match(newvalue, @"(\\f[0-9]+)(\\u[0-9]{1,4}\?)(\\f[0-9]+ ?)"); + if (m.Groups.Count < 3) + newvalue = newvalue.Replace(@"\u8593?", "^"); + else + newvalue = newvalue.Replace(@"\u8593?", m.Groups[1].Value + @"\u8593?" + m.Groups[3].Value); + } + + if (newvalue.Contains(@"\u9586?")) + { + Match m = Regex.Match(newvalue, @"(\\f[0-9]+)(\\u[0-9]{1,4}\?)(\\f[0-9]+ ?)"); + if (m.Groups.Count < 3) + newvalue = newvalue.Replace(@"\u9586?", @"\\"); + else + newvalue = newvalue.Replace(@"\u9586?", m.Groups[1].Value + @"\u9586?" + m.Groups[3].Value); + } + + if (gg != newvalue) + { + string prefix1 = MyGrid.Data.Substring(0, mmg.Index); + string prefix2 = mmg.Value.Substring(0, myIndex); string suffix1 = MyGrid.Data.Substring(mmg.Index + mmg.Length); string suffix2 = mmg.Value.Substring(myIndex + myLength); MyGrid.SetData(prefix1 + prefix2 + newvalue + suffix2 + suffix1); @@ -1091,23 +1091,28 @@ namespace VEPROMS.CSLA.Library } } } + if (_Text == string.Empty) _Text = "?"; } + // C2021-018 used to update the content record when displaying Alarm Pont Table information in the step Editor (BNPP alarms) public void UpdateAlarmTableInfoView(string updateText) { _Text = updateText; } + public void LoadNonCachedGrid() { _MyGrid = GridInfo.GetNonCached(ContentID); //Console.WriteLine("LoadNonCachedGrid {0},{1},{2}",ContentID,_MyGrid==null,_MyContentInfoUnique); } + public PartInfoList LocalContentParts { get { return _ContentParts; } } + public void AddPart(SafeDataReader dr, ItemInfo itemInfo) { if (_ContentParts == null) @@ -1115,36 +1120,21 @@ namespace VEPROMS.CSLA.Library else _ContentParts.AddPartInfo(dr, itemInfo); } + public override string ToString() { return string.Format("{0} {1}", Number, Text); } + public void ShowChange() { OnChange(); } - //public XmlNode ToXml(XmlNode xn) - //{ - // XmlNode nd = xn.OwnerDocument.CreateElement("Content"); - // xn.AppendChild(nd); - // AddAttribute(nd, "Number", _Number); - // AddAttribute(nd, "Text", _Text); - // AddAttribute(nd, "FormatID", _FormatID); - // AddAttribute(nd, "Config", _Config); - // return nd; - //} - //public void AddAttribute(XmlNode xn, string name, object o) - //{ - // if (o != null && o.ToString() != "") - // { - // XmlAttribute xa = xn.OwnerDocument.CreateAttribute(name); - // xa.Value = o.ToString(); - // xn.Attributes.Append(xa); - // } - //} - internal ContentInfo(SafeDataReader dr,bool ForItem) + + internal ContentInfo(SafeDataReader dr, bool ForItem) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ContentInfo.Constructor", GetHashCode()); + try { ReadDataItemList(dr); @@ -1156,9 +1146,11 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ContentInfo.Constructor", ex); } } + private void ReadDataItemList(SafeDataReader dr) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ContentInfo.ReadDataItemList", GetHashCode()); + try { _ContentID = dr.GetInt32("ContentID"); @@ -1186,8 +1178,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ContentInfo.ReadData", ex); } } - } + public partial class ContentInfoList { public static ContentInfoList GetList(int? itemID) @@ -1204,6 +1196,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on ItemInfoList.GetChildren", ex); } } + [Serializable()] private class ContentListCriteria { @@ -1218,6 +1211,7 @@ namespace VEPROMS.CSLA.Library set { _ItemID = value; } } } + private void DataPortal_Fetch(ContentListCriteria criteria) { this.RaiseListChangedEvents = false; @@ -1251,12 +1245,13 @@ namespace VEPROMS.CSLA.Library } this.RaiseListChangedEvents = true; } + public static ContentInfoList GetChangedList(byte[] lastChanged) { try { ContentInfoList tmp = DataPortal.Fetch(new ChangeListCriteria(lastChanged)); -// ContentInfo.AddList(tmp); + // ContentInfo.AddList(tmp); tmp.AddEvents(); return tmp; } @@ -1265,6 +1260,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on ContentInfoList.GetChangedList", ex); } } + [Serializable()] private class ChangeListCriteria { @@ -1279,6 +1275,7 @@ namespace VEPROMS.CSLA.Library _LastChanged = lastChanged; } } + private void DataPortal_Fetch(ChangeListCriteria criteria) { this.RaiseListChangedEvents = false; @@ -1312,7 +1309,9 @@ namespace VEPROMS.CSLA.Library } this.RaiseListChangedEvents = true; } + #region ClearCBOverride + // B2015-039 fix: // the following code clears the change bar override attribute from the step config, using the // sql stored procedure 'ClearCBOverrideForProcedure'. The stored procedure returns @@ -1321,7 +1320,7 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ClearCBOverrideCriteria { - public ClearCBOverrideCriteria(int? itemID) + public ClearCBOverrideCriteria(int? itemID) { _ItemID = itemID; } @@ -1332,6 +1331,7 @@ namespace VEPROMS.CSLA.Library set { _ItemID = value; } } } + private void DataPortal_Fetch(ClearCBOverrideCriteria criteria) { try @@ -1366,6 +1366,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ClearCBOverrideCriteria.DataPortal_Fetch", ex); } } + public static ContentInfoList GetClearedCBOverrides(int itemID) { try @@ -1378,7 +1379,9 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on ContentInfoList.GetClearedCBOverrides", ex); } } + #endregion + #region UCF Fix FormatId After Import private class FixFormatIDAfterImportCriteria { @@ -1407,6 +1410,7 @@ namespace VEPROMS.CSLA.Library _NewFormatID = newfid; } } + private void DataPortal_Fetch(FixFormatIDAfterImportCriteria criteria) { try @@ -1440,6 +1444,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("FixFormatIDAfterImport.DataPortal_Fetch", ex); } } + public static ContentInfoList FixFormatIDAfterImport(string dvlst, int oldfid, int newfid) { try @@ -1452,249 +1457,259 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on ContentInfoList.FixFormatIDAfterImport", ex); } } + #endregion + #region UCF Clear Overwridden Formats private class ClearOverrideFormatsByFolderCriteria - { - public ClearOverrideFormatsByFolderCriteria(int folderID, int? formatID, int? newformatID) - { - _FormatID = formatID; - _FolderID = folderID; - _NewFormatID = newformatID; - } - private int? _FormatID; - public int? FormatID - { - get { return _FormatID; } - set { _FormatID = value; } - } - private int? _NewFormatID; - public int? NewFormatID - { - get { return _NewFormatID; } - set { _NewFormatID = value; } - } - private int _FolderID; - public int FolderID - { - get { return _FolderID; } - set { _FolderID = value; } - } - } - private void DataPortal_Fetch(ClearOverrideFormatsByFolderCriteria criteria) - { - try - { - using (SqlConnection cn = Database.VEPROMS_SqlConnection) - { - using (SqlCommand cm = cn.CreateCommand()) - { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandText = "vesp_ClearOverrideFormatsByFolder"; - cm.Parameters.AddWithValue("@FolderID", criteria.FolderID); - if (criteria.FormatID == null) - cm.Parameters.AddWithValue("@FormatID", DBNull.Value); - else - cm.Parameters.AddWithValue("@FormatID", criteria.FormatID); - if (criteria.NewFormatID == null) - cm.Parameters.AddWithValue("@NewFormatID", DBNull.Value); - else - cm.Parameters.AddWithValue("@NewFormatID", criteria.NewFormatID); - cm.CommandTimeout = Database.DefaultTimeout; - using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) - { - IsReadOnly = false; - while (dr.Read()) - { - ContentInfo contentInfo = new ContentInfo(dr); - this.Add(contentInfo); - } - IsReadOnly = true; - } - } - } - } - catch (Exception ex) - { - Database.LogException("ClearOverrideFormatsByFolderCriteria.DataPortal_Fetch", ex); - throw new DbCslaException("ClearOverrideFormatsByFolderCriteria.DataPortal_Fetch", ex); - } - } + { + public ClearOverrideFormatsByFolderCriteria(int folderID, int? formatID, int? newformatID) + { + _FormatID = formatID; + _FolderID = folderID; + _NewFormatID = newformatID; + } + private int? _FormatID; + public int? FormatID + { + get { return _FormatID; } + set { _FormatID = value; } + } + private int? _NewFormatID; + public int? NewFormatID + { + get { return _NewFormatID; } + set { _NewFormatID = value; } + } + private int _FolderID; + public int FolderID + { + get { return _FolderID; } + set { _FolderID = value; } + } + } + + private void DataPortal_Fetch(ClearOverrideFormatsByFolderCriteria criteria) + { + try + { + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandText = "vesp_ClearOverrideFormatsByFolder"; + cm.Parameters.AddWithValue("@FolderID", criteria.FolderID); + if (criteria.FormatID == null) + cm.Parameters.AddWithValue("@FormatID", DBNull.Value); + else + cm.Parameters.AddWithValue("@FormatID", criteria.FormatID); + if (criteria.NewFormatID == null) + cm.Parameters.AddWithValue("@NewFormatID", DBNull.Value); + else + cm.Parameters.AddWithValue("@NewFormatID", criteria.NewFormatID); + cm.CommandTimeout = Database.DefaultTimeout; + using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) + { + IsReadOnly = false; + while (dr.Read()) + { + ContentInfo contentInfo = new ContentInfo(dr); + this.Add(contentInfo); + } + IsReadOnly = true; + } + } + } + } + catch (Exception ex) + { + Database.LogException("ClearOverrideFormatsByFolderCriteria.DataPortal_Fetch", ex); + throw new DbCslaException("ClearOverrideFormatsByFolderCriteria.DataPortal_Fetch", ex); + } + } + public static ContentInfoList ClearOverrideFormatsByFolder(int folderID, int? formatID, int? newformatID) - { - try - { - ContentInfoList tmp = DataPortal.Fetch(new ClearOverrideFormatsByFolderCriteria(folderID, formatID, newformatID)); - return tmp; - } - catch (Exception ex) - { - throw new DbCslaException("Error on ContentInfoList.ClearOverrideFormatsByFolder", ex); - } - } - private class ClearOverrideFormatsByDocVersionCriteria - { - public ClearOverrideFormatsByDocVersionCriteria(string dvlist, int? formatID, int?newformatID) - { - _FormatID = formatID; - _DVList = dvlist; - _NewFormatID = newformatID; - } - private int? _FormatID; - public int? FormatID - { - get { return _FormatID; } - set { _FormatID = value; } - } - private int? _NewFormatID; - public int? NewFormatID - { - get { return _NewFormatID; } - set { _NewFormatID = value; } - } - private string _DVList; - public string DVList - { - get { return _DVList; } - set { _DVList = value; } - } - } - private void DataPortal_Fetch(ClearOverrideFormatsByDocVersionCriteria criteria) - { - try - { - using (SqlConnection cn = Database.VEPROMS_SqlConnection) - { - using (SqlCommand cm = cn.CreateCommand()) - { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandText = "vesp_ClearOverrideFormatsByDocVersion"; - cm.Parameters.AddWithValue("@DocVersionList", criteria.DVList); - if (criteria.FormatID == null) - cm.Parameters.AddWithValue("@FormatID", DBNull.Value); - else - cm.Parameters.AddWithValue("@FormatID", criteria.FormatID); - if (criteria.NewFormatID == null) - cm.Parameters.AddWithValue("@NewFormatID", DBNull.Value); - else - cm.Parameters.AddWithValue("@NewFormatID", criteria.NewFormatID); - cm.CommandTimeout = Database.DefaultTimeout; - using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) - { - IsReadOnly = false; - while (dr.Read()) - { - ContentInfo contentInfo = new ContentInfo(dr); - this.Add(contentInfo); - } - IsReadOnly = true; - } - } - } - } - catch (Exception ex) - { - Database.LogException("ClearOverrideFormatsByDocVersion.DataPortal_Fetch", ex); - throw new DbCslaException("ClearOverrideFormatsByDocVersion.DataPortal_Fetch", ex); - } - } - public static ContentInfoList ClearOverrideFormatsByDocVersion(string dvlist, int? formatID, int? newformatID) - { - try - { - ContentInfoList tmp = DataPortal.Fetch(new ClearOverrideFormatsByDocVersionCriteria(dvlist, formatID, newformatID)); - return tmp; - } - catch (Exception ex) - { - throw new DbCslaException("Error on ContentInfoList.ClearOverrideFormatsByDocVersion", ex); - } - } - private class ClearOverrideFormatsByItemCriteria - { - public ClearOverrideFormatsByItemCriteria(int itemID, int? formatID, int? newformatID) - { - _FormatID = formatID; - _NewFormatID = newformatID; - _ItemID = itemID; - } - private int? _FormatID; - public int? FormatID - { - get { return _FormatID; } - set { _FormatID = value; } - } - private int? _NewFormatID; - public int? NewFormatID - { - get { return _NewFormatID; } - set { _NewFormatID = value; } - } - private int _ItemID; - public int ItemID - { - get { return _ItemID; } - set { _ItemID = value; } - } - } - private void DataPortal_Fetch(ClearOverrideFormatsByItemCriteria criteria) - { - try - { - using (SqlConnection cn = Database.VEPROMS_SqlConnection) - { - using (SqlCommand cm = cn.CreateCommand()) - { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandText = "vesp_ClearOverrideFormatsByItem"; - cm.Parameters.AddWithValue("@ItemID", criteria.ItemID); - if (criteria.FormatID == null) - cm.Parameters.AddWithValue("@FormatID", DBNull.Value); - else - cm.Parameters.AddWithValue("@FormatID", criteria.FormatID); - if (criteria.NewFormatID == null) - cm.Parameters.AddWithValue("@NewFormatID", DBNull.Value); - else - cm.Parameters.AddWithValue("@NewFormatID", criteria.NewFormatID); - cm.CommandTimeout = Database.DefaultTimeout; - using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) - { - IsReadOnly = false; - while (dr.Read()) - { - ContentInfo contentInfo = new ContentInfo(dr); - this.Add(contentInfo); - } - IsReadOnly = true; - } - } - } - } - catch (Exception ex) - { - Database.LogException("ClearOverrideFormatsByItem.DataPortal_Fetch", ex); - throw new DbCslaException("ClearOverrideFormatsByItem.DataPortal_Fetch", ex); - } - } - public static ContentInfoList ClearOverrideFormatsByItem(int itemID, int? formatID, int? newformatID) - { - try - { - ContentInfoList tmp = DataPortal.Fetch(new ClearOverrideFormatsByItemCriteria(itemID, formatID, newformatID)); - return tmp; - } - catch (Exception ex) - { - throw new DbCslaException("Error on ContentInfoList.ClearOverrideFormatsByItem", ex); - } - } + { + try + { + ContentInfoList tmp = DataPortal.Fetch(new ClearOverrideFormatsByFolderCriteria(folderID, formatID, newformatID)); + return tmp; + } + catch (Exception ex) + { + throw new DbCslaException("Error on ContentInfoList.ClearOverrideFormatsByFolder", ex); + } + } + private class ClearOverrideFormatsByDocVersionCriteria + { + public ClearOverrideFormatsByDocVersionCriteria(string dvlist, int? formatID, int? newformatID) + { + _FormatID = formatID; + _DVList = dvlist; + _NewFormatID = newformatID; + } + private int? _FormatID; + public int? FormatID + { + get { return _FormatID; } + set { _FormatID = value; } + } + private int? _NewFormatID; + public int? NewFormatID + { + get { return _NewFormatID; } + set { _NewFormatID = value; } + } + private string _DVList; + public string DVList + { + get { return _DVList; } + set { _DVList = value; } + } + } + private void DataPortal_Fetch(ClearOverrideFormatsByDocVersionCriteria criteria) + { + try + { + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandText = "vesp_ClearOverrideFormatsByDocVersion"; + cm.Parameters.AddWithValue("@DocVersionList", criteria.DVList); + if (criteria.FormatID == null) + cm.Parameters.AddWithValue("@FormatID", DBNull.Value); + else + cm.Parameters.AddWithValue("@FormatID", criteria.FormatID); + if (criteria.NewFormatID == null) + cm.Parameters.AddWithValue("@NewFormatID", DBNull.Value); + else + cm.Parameters.AddWithValue("@NewFormatID", criteria.NewFormatID); + cm.CommandTimeout = Database.DefaultTimeout; + using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) + { + IsReadOnly = false; + while (dr.Read()) + { + ContentInfo contentInfo = new ContentInfo(dr); + this.Add(contentInfo); + } + IsReadOnly = true; + } + } + } + } + catch (Exception ex) + { + Database.LogException("ClearOverrideFormatsByDocVersion.DataPortal_Fetch", ex); + throw new DbCslaException("ClearOverrideFormatsByDocVersion.DataPortal_Fetch", ex); + } + } - #endregion - #region Enhanced - #region Enhanced_UnlinkItems - [Serializable()] + public static ContentInfoList ClearOverrideFormatsByDocVersion(string dvlist, int? formatID, int? newformatID) + { + try + { + ContentInfoList tmp = DataPortal.Fetch(new ClearOverrideFormatsByDocVersionCriteria(dvlist, formatID, newformatID)); + return tmp; + } + catch (Exception ex) + { + throw new DbCslaException("Error on ContentInfoList.ClearOverrideFormatsByDocVersion", ex); + } + } + + private class ClearOverrideFormatsByItemCriteria + { + public ClearOverrideFormatsByItemCriteria(int itemID, int? formatID, int? newformatID) + { + _FormatID = formatID; + _NewFormatID = newformatID; + _ItemID = itemID; + } + private int? _FormatID; + public int? FormatID + { + get { return _FormatID; } + set { _FormatID = value; } + } + private int? _NewFormatID; + public int? NewFormatID + { + get { return _NewFormatID; } + set { _NewFormatID = value; } + } + private int _ItemID; + public int ItemID + { + get { return _ItemID; } + set { _ItemID = value; } + } + } + + private void DataPortal_Fetch(ClearOverrideFormatsByItemCriteria criteria) + { + try + { + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandText = "vesp_ClearOverrideFormatsByItem"; + cm.Parameters.AddWithValue("@ItemID", criteria.ItemID); + if (criteria.FormatID == null) + cm.Parameters.AddWithValue("@FormatID", DBNull.Value); + else + cm.Parameters.AddWithValue("@FormatID", criteria.FormatID); + if (criteria.NewFormatID == null) + cm.Parameters.AddWithValue("@NewFormatID", DBNull.Value); + else + cm.Parameters.AddWithValue("@NewFormatID", criteria.NewFormatID); + cm.CommandTimeout = Database.DefaultTimeout; + using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) + { + IsReadOnly = false; + while (dr.Read()) + { + ContentInfo contentInfo = new ContentInfo(dr); + this.Add(contentInfo); + } + IsReadOnly = true; + } + } + } + } + catch (Exception ex) + { + Database.LogException("ClearOverrideFormatsByItem.DataPortal_Fetch", ex); + throw new DbCslaException("ClearOverrideFormatsByItem.DataPortal_Fetch", ex); + } + } + + public static ContentInfoList ClearOverrideFormatsByItem(int itemID, int? formatID, int? newformatID) + { + try + { + ContentInfoList tmp = DataPortal.Fetch(new ClearOverrideFormatsByItemCriteria(itemID, formatID, newformatID)); + return tmp; + } + catch (Exception ex) + { + throw new DbCslaException("Error on ContentInfoList.ClearOverrideFormatsByItem", ex); + } + } + + #endregion + + #region Enhanced + + #region Enhanced_UnlinkItems + [Serializable()] private class EnhancedUnlinkCriteria { public EnhancedUnlinkCriteria(int? enhancedID) @@ -1708,6 +1723,7 @@ namespace VEPROMS.CSLA.Library set { _EnhancedID = value; } } } + private void DataPortal_Fetch(EnhancedUnlinkCriteria criteria) { try @@ -1718,7 +1734,7 @@ namespace VEPROMS.CSLA.Library { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "vesp_PurgeEnhancedItemsAndChildren"; - cm.Parameters.AddWithValue("@EnhanceID", criteria.EnhancedID); // note query had 'EnhanceID', not 'EnhancedID' + cm.Parameters.AddWithValue("@EnhanceID", criteria.EnhancedID); // note query had 'EnhanceID', not 'EnhancedID' cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { @@ -1739,6 +1755,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("EnhancedUnlinkCriteria.DataPortal_Fetch", ex); } } + public static ContentInfoList DoEnhancedUnlink(int enhancedID) { try @@ -1751,9 +1768,11 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on ContentInfoList.DoEnhancedUnlink", ex); } } + #endregion Enhanced_UnlinkItems + #region Enhanced_UnlinkDocVersionAndItems - ////// + [Serializable()] private class EnhancedDocVersionUnlinkCriteria { @@ -1768,6 +1787,7 @@ namespace VEPROMS.CSLA.Library set { _EnhancedDocVersionID = value; } } } + private void DataPortal_Fetch(EnhancedDocVersionUnlinkCriteria criteria) { try @@ -1812,6 +1832,7 @@ namespace VEPROMS.CSLA.Library } } #endregion Enhanced_UnlinkDocVersionAndItems + #region Enhanced_Convert16To32 ////// [Serializable()] @@ -1964,6 +1985,7 @@ namespace VEPROMS.CSLA.Library } } #endregion Enhanced_Convert16To32 + #endregion Enhanced } } diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/DocVersionExt.cs b/PROMS/VEPROMS.CSLA.Library/Extension/DocVersionExt.cs index 8df369d9..8730a8cd 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/DocVersionExt.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/DocVersionExt.cs @@ -48,10 +48,13 @@ namespace VEPROMS.CSLA.Library get { if (DocVersionAssociations == null || DocVersionAssociations.Count == 0) return false; + ROFstInfo roFstInfo = ROFstInfo.GetJustROFst(DocVersionAssociations[0].ROFstID); + RODbInfo rdi = RODbInfo.GetJustRODB(roFstInfo.RODbID); string rofstPath = rdi.FolderPath + @"\ro.fst"; if (!File.Exists(rofstPath)) return false; + FileInfo fiRofst = new FileInfo(rofstPath); // if the database Ro.Fst is newer or if the files have identical DTS, @@ -60,7 +63,11 @@ namespace VEPROMS.CSLA.Library // next see if the data is the same size, i.e. byte count of record and byte count // of file. If different sizes, the date/time stamp check will hold. - if (fiRofst.Length != roFstInfo.ROLookup.Length) return fiRofst.LastWriteTimeUtc > roFstInfo.DTS; + // B2022-026 RO Memory reduction - new logic + var bytes = ROFSTLookup.GetRofstLookupBytes(roFstInfo.ROFstID); + + if (bytes != null && fiRofst.Length != bytes.Length) + return fiRofst.LastWriteTimeUtc > roFstInfo.DTS; // if we can't tell by the DTS or size, compare the contents. Get all of the rodb's // rofsts of the size of the file & compare bytes. @@ -249,15 +256,18 @@ namespace VEPROMS.CSLA.Library get { if (DocVersionAssociations == null || DocVersionAssociationCount==0) return false; + ROFstInfo roFstInfo = ROFstInfo.GetJustROFst(DocVersionAssociations[0].ROFstID); RODbInfo rdi = RODbInfo.GetJustRODB(roFstInfo.RODbID); string rofstPath = rdi.FolderPath + @"\ro.fst"; + //if (!File.Exists(rofstPath)) return false; if (!pathExists(rofstPath)) { _MyLog.WarnFormat("RO Path '{0}' could not be found", rofstPath); return false; } + FileInfo fiRofst = new FileInfo(rofstPath); // if the database Ro.Fst is newer or if the files have identical DTS, @@ -265,14 +275,21 @@ namespace VEPROMS.CSLA.Library // put this in a dictionary so we don't have to keep testing to see if the file version of ro.fst is newer than database version string key = string.Format("{0}-{1}", DocVersionAssociations[0].ROFstID, fiRofst.LastWriteTimeUtc); + if (NewerRoFstLookup.ContainsKey(key)) return NewerRoFstLookup[key]; if (roFstInfo.DTS >= fiRofst.LastWriteTimeUtc) return AddToRoFstLookup(key, false); + TimeSpan ts = roFstInfo.DTS - fiRofst.LastWriteTimeUtc; + if (ts.TotalSeconds > -1F) return AddToRoFstLookup(key, false); // next see if the data is the same size, i.e. byte count of record and byte count // of file. If different sizes, the date/time stamp check will hold. - if (fiRofst.Length != roFstInfo.ROLookup.Length) return AddToRoFstLookup(key,fiRofst.LastWriteTimeUtc > roFstInfo.DTS); + // B2022-026 RO Memory reduction - new logic + var bytes = ROFSTLookup.GetRofstLookupBytes(roFstInfo.ROFstID); + + if (bytes != null && fiRofst.Length != bytes.Length) + return AddToRoFstLookup(key, fiRofst.LastWriteTimeUtc > roFstInfo.DTS); // if we can't tell by the DTS or size, compare the contents. Get all of the rodb's // rofsts of the size of the file & compare bytes. diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/ItemExt.cs b/PROMS/VEPROMS.CSLA.Library/Extension/ItemExt.cs index 9a5ea637..ddacf524 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/ItemExt.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/ItemExt.cs @@ -326,26 +326,31 @@ namespace VEPROMS.CSLA.Library public partial class ItemInfo : IVEDrillDownReadOnly { private bool _PrintAllAtOnce = false; + public bool PrintAllAtOnce { get { return _PrintAllAtOnce; } set { _PrintAllAtOnce = value; } } + public SectionInfo GetSectionInfo() { if (this is SectionInfo) return this as SectionInfo; return SectionInfo.Get(ItemID); } + public StepInfo GetStepInfo() { if (this is StepInfo) return this as StepInfo; return StepInfo.Get(ItemID); } + public ProcedureInfo GetProcedureInfo() { if (this is ProcedureInfo) return this as ProcedureInfo; return ProcedureInfo.Get(ItemID); } + private string _EnhType = null; public string EnhType { @@ -379,10 +384,12 @@ namespace VEPROMS.CSLA.Library if (id == ItemID) return true; return false; } + public static bool IsInCache(int itemID) { return _CacheByPrimaryKey.ContainsKey(itemID.ToString()); } + public static string ReplaceLinkWithNewID(string tmpForLink) { tmpForLink = Regex.Replace(tmpForLink, @"#Link:ReferencedObject:[0-9]+ ", @"#Link:ReferencedObject: "); @@ -394,6 +401,7 @@ namespace VEPROMS.CSLA.Library tmpForLink = tmpForLink.Replace(@"\u8211 ", @"-"); // Replace EN Dash with hyphen return tmpForLink; } + public void SetHeader(VE_Font myFont, string myText) { _MyHeader = new MetaTag(myFont); @@ -402,6 +410,7 @@ namespace VEPROMS.CSLA.Library _MyHeader.Text = myText; _MyHeader.Justify = ContentAlignment.MiddleCenter; } + public void MoveItem(IVEDrillDownReadOnly pInfo, int index) { using (ItemInfoList movedItems = ItemInfoList.GetMoveItem(ItemID, index)) @@ -416,6 +425,7 @@ namespace VEPROMS.CSLA.Library if (parentInfo != null) ItemInfo.ResetParts(parentInfo.ItemID); } + public static void Refresh(ItemInfo tmp) { string key = tmp.ItemID.ToString(); @@ -424,6 +434,7 @@ namespace VEPROMS.CSLA.Library foreach (ItemInfo tmpInfo in _CacheByPrimaryKey[key]) tmpInfo.RefreshFields(tmp); } + protected virtual void RefreshFields(ItemInfo tmp) { if (_PreviousID != tmp.PreviousID) @@ -574,6 +585,7 @@ namespace VEPROMS.CSLA.Library } } } + /// /// The following method is used only in print because the 'printed' data is loaded into /// memory before printing. Find the next item from memory (do not go out to database). @@ -596,43 +608,35 @@ namespace VEPROMS.CSLA.Library } return null; } + public static void ResetTranCounters() { TranCheckCount = 0; TranFixCount = 0; TranConvertCount = 0;// B2018-002 - Invalid Transitions - Initialize Transition Conversion Count } + public static int TranCheckCount = 0; public static int TranFixCount = 0; public static int TranConvertCount = 0;// B2018-002 - Invalid Transitions - Declare Transition Conversion Count internal static TransitionInfoList TransitionsToDisconnected; internal static TransitionInfoList TransitionsToNonEditable; + internal static void MyRefreshTransitions(ItemInfo itemInfo, IVEDrillDownReadOnly itemParent, SectionInfo sectionInfo, ProcedureInfo procInfo, DocVersionInfo docVersionInfo, TransitionLookup tranLookup) { - //TransitionInfoList til = TransitionInfoList.GetByFromID(itemInfo.ItemID); - //Console.WriteLine("Procedure: {0}, transitions: {1}", (itemInfo as ProcedureInfo).DisplayNumber, til.Count); - //foreach (TransitionInfo traninfo in til) - //{ - // string oldText = itemInfo.MyContent.Text; - // itemInfo.MyContent.FixTransitionText(traninfo, tranLookup); - // string newText = itemInfo.MyContent.Text; - // if (newText != oldText) - // { - // Content content = Content.Get(itemInfo.MyContent.ContentID); - // content.FixTransitionText(traninfo); - // content.Save(); - // } - //} if (itemInfo == null) return; + if (itemInfo.MyContent.ContentPartCount > 0) + { foreach (PartInfo pi in itemInfo.MyContent.ContentParts) { - //List myItems = new List(); foreach (ItemInfo ii in pi.MyItems) - // myItems.Add(ii); - //foreach (ItemInfo ii in myItems) + { MyRefreshTransitions(ii, itemInfo, (itemInfo as SectionInfo) ?? sectionInfo, procInfo, docVersionInfo, tranLookup); + } } + } + // B2018-002 - Invalid Transitions - Convert Invalid Transitions to Text // An invalid transition is a transition embedded in the content text that does not match the transition table record. if(ConvertInvalidTransitionsToText(itemInfo)) @@ -642,18 +646,7 @@ namespace VEPROMS.CSLA.Library { bool forceConvertToText = false; TranCheckCount++; - //if (TransitionsToNonEditable != null) - //{ - // if (IsTransitionToNonEditable(traninfo)) - // { - // forceConvertToText = true; - // TranFixCount++; - // itemInfo.MyContent.FixTransitionText(traninfo, itemInfo, "Reason for Change: Transition to Non-Editable Step"); - // Content content = Content.Get(itemInfo.MyContent.ContentID); - // content.FixTransitionText(traninfo, true); - // content.Save(); - // } - //} + if (!forceConvertToText) { if (traninfo.MyItemToID.ActiveSection != null) @@ -661,6 +654,7 @@ namespace VEPROMS.CSLA.Library SectionConfig sc = traninfo.MyItemToID.ActiveSection.MyConfig as SectionConfig; forceConvertToText = (sc.SubSection_Edit == "N" && traninfo.MyItemToID.IsStep); // Bug fix B2016-081 also check if transition is to a step element } + if (forceConvertToText) { TranFixCount++; @@ -670,11 +664,14 @@ namespace VEPROMS.CSLA.Library content.Save(); } } + if (!forceConvertToText) { - if (itemInfo.MyProcedure.ItemID != traninfo.MyItemToID.MyProcedure.ItemID) //different proc - if (!itemInfo.ActiveFormat.PlantFormat.FormatData.TransData.TransTypeList[traninfo.TranType].TransMenu.Contains("Proc")) //internal format - if (!itemInfo.ActiveFormat.PlantFormat.FormatData.TransData.TransTypeList[traninfo.TranType].TransMenu.Contains("other proc")) //B2017-068 paste with transition fix + if (itemInfo.MyProcedure.ItemID != traninfo.MyItemToID.MyProcedure.ItemID) //different proc + { + if (!itemInfo.ActiveFormat.PlantFormat.FormatData.TransData.TransTypeList[traninfo.TranType].TransMenu.Contains("Proc")) //internal format + { + if (!itemInfo.ActiveFormat.PlantFormat.FormatData.TransData.TransTypeList[traninfo.TranType].TransMenu.Contains("other proc")) //B2017-068 paste with transition fix { forceConvertToText = true; TranFixCount++; @@ -683,13 +680,17 @@ namespace VEPROMS.CSLA.Library content.FixTransitionText(traninfo, true); content.Save(); } + } + } } + if (!forceConvertToText) { if (itemInfo.MyDocVersion != null && traninfo.MyItemToID.MyDocVersion != null && itemInfo.MyDocVersion.VersionID != traninfo.MyItemToID.MyDocVersion.VersionID) //different doc version { - if (!itemInfo.ActiveFormat.PlantFormat.FormatData.TransData.TransTypeList[traninfo.TranType].TransMenu.Contains("Proc")) //internal format - if (!itemInfo.ActiveFormat.PlantFormat.FormatData.TransData.TransTypeList[traninfo.TranType].TransMenu.Contains("other proc")) //B2017-068 paste with transition fix + if (!itemInfo.ActiveFormat.PlantFormat.FormatData.TransData.TransTypeList[traninfo.TranType].TransMenu.Contains("Proc")) //internal format + { + if (!itemInfo.ActiveFormat.PlantFormat.FormatData.TransData.TransTypeList[traninfo.TranType].TransMenu.Contains("other proc")) //B2017-068 paste with transition fix { forceConvertToText = true; TranFixCount++; @@ -698,8 +699,10 @@ namespace VEPROMS.CSLA.Library content.FixTransitionText(traninfo, true); content.Save(); } + } } } + if (!forceConvertToText) { string oldText = itemInfo.MyContent.Text; @@ -718,6 +721,7 @@ namespace VEPROMS.CSLA.Library } } } + // // B2018-002 - Invalid Transitions - Method to check for invalid transitions and convert them to text public static bool ConvertInvalidTransitionsToText(ItemInfo itemInfo) { @@ -729,25 +733,30 @@ namespace VEPROMS.CSLA.Library retval = false; if (itemInfo.MyContent.Text.Contains("Link:Transition")) { - //Console.WriteLine("\"TranCount\"\t\"{0}\"\t{1}\t{2}\t{3}", itemInfo.ShortPath, itemInfo.ItemID, mc.Count, itemInfo.MyContent.ContentTransitionCount); Content content = Content.Get(itemInfo.MyContent.ContentID); - //if (itemInfo.InList(616031, 615898, 5516866)) - // Console.WriteLine("here"); + if (itemInfo.MyContent.ContentTransitions != null) + { foreach (TransitionInfo ct in itemInfo.MyContent.ContentTransitions) + { Transition.Delete(ct.TransitionID); + } + } + itemInfo.MyContent.RefreshContentTransitions(); - //if (content.Text.Contains("Link:TransitionRange")) - // Console.WriteLine("Here"); + while (content.Text.Contains("Link:Transition")) { TranCheckCount++; TranConvertCount++; + if (content.FixTransitionText(null, true)) { ContentInfo.OnStaticContentInfoChange(itemInfo, new StaticContentInfoEventArgs("", "", "")); if (itemInfo.MyContent.MyGrid != null) + { content.ConvertTransitionToTextInGrid(null, null); + } content.Save(); } else // B2018-043 Eliminate infinite loop for invalid transition structure @@ -759,14 +768,21 @@ namespace VEPROMS.CSLA.Library } } } + // B2021-008: Delete the transition record if there is no link in the text if (mc.Count == 0 && itemInfo.MyContent.ContentTransitionCount > 0) { TranCheckCount++; TranFixCount++; + if (itemInfo.MyContent.ContentTransitions != null) + { foreach (TransitionInfo ct in itemInfo.MyContent.ContentTransitions) + { Transition.Delete(ct.TransitionID); + } + } + itemInfo.MyContent.RefreshContentTransitions(); } @@ -800,10 +816,12 @@ namespace VEPROMS.CSLA.Library string txt = myContent.Text; string regDelete = @"(\\v |)\(\\v0 |)"; string txt2=txt; + do{ txt = txt2; txt2 = Regex.Replace(txt, regDelete, ""); } while(txt2 != txt); + if(txt2 != myContent.Text) { using(Content tmp = myContent.Get()) @@ -814,15 +832,7 @@ namespace VEPROMS.CSLA.Library AddInvalidTransitionAnnotation(itemInfo, "Removed Empty Transition Text"); } } - //private static bool IsTransitionToDisconnected(TransitionInfo ti) - //{ - // foreach (TransitionInfo til in TransitionsToDisconnected) - // { - // if (ti.TransitionID == til.TransitionID) - // return true; - // } - // return false; - //} + private static bool IsTransitionToNonEditable(TransitionInfo ti) { foreach (TransitionInfo til in TransitionsToNonEditable) @@ -832,32 +842,39 @@ namespace VEPROMS.CSLA.Library } return false; } + public static void ResetROCounters() { ROCheckCount = 0; ROFixCount = 0; } + public static int ROCheckCount = 0; public static int ROFixCount = 0; private static AnnotationType _VolianCommentType = null; // Using this to flag ro value issues with byron to braidwood + public static AnnotationType VolianCommentType { get { if (_VolianCommentType == null) _VolianCommentType = AnnotationType.GetByName("Volian Comment"); + if (_VolianCommentType == null) _VolianCommentType = AnnotationType.MakeAnnotationType("Volian Comment", null); + return _VolianCommentType; } } + public void UpdateROText() { if (this.MyDocVersion.DocVersionAssociationCount == 0) return; + ROFstInfo rofstinfo = this.MyDocVersion.DocVersionAssociations[0].MyROFst; ROFSTLookup lookup = rofstinfo.GetROFSTLookup(this.MyDocVersion); - lookup.MyDocVersionInfo = this.MyDocVersion; lookup.MyItemInfo = this; // B2022-020 to pass information into error log if needed + if (this.MyContent.ContentRoUsageCount > 0) { foreach (RoUsageInfo rousage in this.MyContent.ContentRoUsages) @@ -878,33 +895,39 @@ namespace VEPROMS.CSLA.Library using (Item myitem = content.ContentItems[0].MyItem) // so that myitem does not stay in cache B2016-153 { myitem.DisposeOfContent = false; // don't dispose of the contents may be needed if more than one RO needs processed - part of B2017-060 - // B2016-225 (follow through) added more descriptive Annotation Type when RO is converted to text + // B2016-225 (follow through) added more descriptive Annotation Type when RO is converted to text Annotation.MakeAnnotation(myitem, AnnotationType.GetByNameOrCreate("Link Converted To Text"), "", string.Format("RO value ({0}) converted to text", ItemInfo.ConvertToDisplayText(oldText)), null); } } else + { content.FixContentText(rousage, roval, roch.type, rofstinfo); + } + content.Save(); } } } } } - internal static void MyRefreshReferenceObjects(ItemInfo itemInfo, IVEDrillDownReadOnly itemParent, SectionInfo sectionInfo, DocVersionInfo docVersionInfo) + // B2022-026 RO Memory Reduction code - pass in ROFstInfo + internal static void MyRefreshReferenceObjects(ItemInfo itemInfo, IVEDrillDownReadOnly itemParent, SectionInfo sectionInfo, DocVersionInfo docVersionInfo, ROFstInfo origROFst) { if (itemInfo.MyContent.ContentPartCount > 0) + { foreach (PartInfo pi in itemInfo.MyContent.ContentParts) { - //List myItems = new List(); foreach (ItemInfo ii in pi.MyItems) - // myItems.Add(ii); - //foreach (ItemInfo ii in myItems) - MyRefreshReferenceObjects(ii, itemInfo, (itemInfo as SectionInfo) ?? sectionInfo, docVersionInfo); + { + MyRefreshReferenceObjects(ii, itemInfo, (itemInfo as SectionInfo) ?? sectionInfo, docVersionInfo, origROFst); + } } - ROFstInfo rofstinfo = docVersionInfo.DocVersionAssociations[0].MyROFst; - ROFSTLookup lookup = rofstinfo.GetROFSTLookup(docVersionInfo); - lookup.MyDocVersionInfo = docVersionInfo; + } + + // B2022-026 RO Memory Reduction code - get ROLookup from passed in ROFstInfo + ROFSTLookup lookup = origROFst.GetROFSTLookup(docVersionInfo); lookup.MyItemInfo = itemInfo; // B2022-020 to pass information into error log if needed + if (itemInfo.MyContent.ContentRoUsageCount > 0) { foreach (RoUsageInfo rousage in itemInfo.MyContent.ContentRoUsages) @@ -915,8 +938,9 @@ namespace VEPROMS.CSLA.Library string oldText = itemInfo.MyContent.Text; string roval = lookup.GetTranslatedRoValue(rousage.ROID, sectionInfo.ActiveFormat.PlantFormat.FormatData.SectData.ConvertCaretToDelta, sectionInfo.ActiveFormat.PlantFormat.FormatData.SectData.UseTildaPoundCharsForSuperSubScriptInROValues); ROFSTLookup.rochild roch = lookup.GetRoChild(rousage.ROID); - itemInfo.MyContent.FixContentText(rousage, roval, roch.type, rofstinfo, itemInfo); + itemInfo.MyContent.FixContentText(rousage, roval, roch.type, origROFst, itemInfo); string newText = itemInfo.MyContent.Text; + if (DifferentROtext(newText,oldText)) { //ShowDifference(oldText, newText); // debug - display in Visual Studio Output window @@ -924,7 +948,7 @@ namespace VEPROMS.CSLA.Library Content content = Content.Get(itemInfo.MyContent.ContentID); if (roval == "?") { - oldText = content.ConvertROToText(rousage, roval, roch.type, rofstinfo); + oldText = content.ConvertROToText(rousage, roval, roch.type, origROFst); using (Item myitem = content.ContentItems[0].MyItem) // so that myitem does not stay in cache B2016-153 { myitem.DisposeOfContent = false; // don't dispose of the contents may be needed if more than one RO needs processed - part of B2017-060 @@ -934,7 +958,7 @@ namespace VEPROMS.CSLA.Library } else { - content.FixContentText(rousage, roval, roch.type, rofstinfo); + content.FixContentText(rousage, roval, roch.type, origROFst); } content.UserID = Volian.Base.Library.VlnSettings.UserID; content.DTS = DateTime.Now; @@ -949,12 +973,17 @@ namespace VEPROMS.CSLA.Library { string nt = newText.Replace(@"\u8209?", "-").Replace(@"\u160?", " ").Replace("\xA0", " "); string ot = oldText.Replace(@"\u8209?", "-").Replace(@"\u160?", " ").Replace("\xA0", " "); + if (nt.Equals(ot)) + { return false; + } return true; } - #region debug + + #region Debug Code + //private static void ShowDifference(string oldText, string newText) //{ // string nt = newText.Replace(@"\u8209?", "-").Replace(@"\u160?", " ").Replace("\xA0", " "); @@ -974,7 +1003,9 @@ namespace VEPROMS.CSLA.Library // } // Console.WriteLine("{0}='{1}'",title,sb.ToString()); //} + #endregion // debug + internal static void SetParentSectionAndDocVersionPageNum(ItemInfo itemInfo, IVEDrillDownReadOnly itemParent, SectionInfo sectionInfo, ProcedureInfo procInfo, DocVersionInfo docVersionInfo, TransitionLookup tranLookup) { if (itemInfo.MyContent.ContentPartCount > 0) @@ -995,21 +1026,7 @@ namespace VEPROMS.CSLA.Library } } } - //internal static long ticksROUsage; - //internal static long ticksItems; - //internal static long ticksTrans; - //internal static void ResetTicks() - //{ - // ticksROUsage = 0; - // ticksItems = 0; - // ticksTrans = 0; - //} - //internal static void ShowTicks() - //{ - // Console.WriteLine("ROUsage: {0}", TimeSpan.FromTicks(ticksROUsage).TotalSeconds); - // Console.WriteLine("Items: {0}", TimeSpan.FromTicks(ticksItems).TotalSeconds); - // Console.WriteLine("Transitions: {0}", TimeSpan.FromTicks(ticksTrans).TotalSeconds); - //} + public static string GetCombinedTab(ItemInfo itemInfo, string parTab) { string pTab = parTab == null ? "" : parTab; @@ -1034,6 +1051,7 @@ namespace VEPROMS.CSLA.Library if (itemInfo.HasParentTab) return thisTab.Trim(); // F2020-023: if tab includes parent tab already, don't concatenate it return pTab + thisTab.Trim(); } + internal static void SetParentSectionAndDocVersion(ItemInfo itemInfo, IVEDrillDownReadOnly itemParent, SectionInfo sectionInfo, DocVersionInfo docVersionInfo, TransitionLookup tranLookup) { if (itemInfo == null) return; @@ -1044,17 +1062,20 @@ namespace VEPROMS.CSLA.Library itemInfo.ActiveSection = sectionInfo; itemInfo.ActiveFormat = itemInfo.MyContent.MyFormat != null ? itemInfo.MyContent.MyFormat : sectionInfo == null ? itemParent.ActiveFormat : sectionInfo.ActiveFormat; itemInfo.MyDocVersion = docVersionInfo; + if (itemInfo.IsStep) { ItemInfo ip = itemParent as ItemInfo; itemInfo.CombinedTab = (ip == null) ? itemInfo.MyTab.CleanText.Trim() : GetCombinedTab(itemInfo, ip.CombinedTab); } + if (docVersionInfo.DocVersionAssociationCount == 1) { string otherChildUnit = null; ROFstInfo rofstinfo = docVersionInfo.DocVersionAssociations[0].MyROFst; //rofstinfo.docVer = docVersionInfo; string rawPrcNum = itemInfo.MyProcedure.MyContent.Number; + // C2022-001 see if we need to get the Other child info from ROLookUp if (rawPrcNum.ToUpper().StartsWith(" in its definiation (procedure property page) { @@ -1064,11 +1085,11 @@ namespace VEPROMS.CSLA.Library } ROFSTLookup lookup = rofstinfo.GetROFSTLookup(docVersionInfo, otherChildUnit); - lookup.MyDocVersionInfo = docVersionInfo; lookup.MyItemInfo = itemInfo; // B2022-020 to pass information into error log if needed - //DateTime dts = DateTime.Now; + if (itemInfo.MyContent.ContentGridCount > 0) itemInfo.MyContent.LoadNonCachedGrid(); + if (itemInfo.MyContent.ContentRoUsageCount > 0) { foreach (RoUsageInfo rousage in itemInfo.MyContent.ContentRoUsages) @@ -1087,39 +1108,27 @@ namespace VEPROMS.CSLA.Library // Force Error Message docVersionInfo.GetROFst(0); } - //TimeSpan ts = DateTime.Now.Subtract(dts); - //ticksROUsage += ts.Ticks; - //dts = DateTime.Now; + if (itemInfo.MyContent.ContentPartCount > 0) { foreach (PartInfo pi in itemInfo.MyContent.ContentParts) { - //ItemInfo il = null; foreach (ItemInfo ii in pi.MyItems) { SetParentSectionAndDocVersion(ii, itemInfo, (itemInfo as SectionInfo) ?? sectionInfo, docVersionInfo, tranLookup); - //if(ii._MyPrevious == null) - // ii.MyPrevious = il; - //if (il != null) il.NextItem = ii; - //il = ii; } } } - //ts = DateTime.Now.Subtract(dts); - //ticksItems += ts.Ticks; - //dts = DateTime.Now; + if (itemInfo.MyContent.ContentTransitionCount > 0) { - //itemInfo.UpdateTransitionText(); foreach (TransitionInfo traninfo in itemInfo.MyContent.ContentTransitions) { - //itemInfo.UpdateTransitionText(); itemInfo.MyContent.FixTransitionText(traninfo, tranLookup, itemInfo); } } - //ts = DateTime.Now.Subtract(dts); - //ticksTrans += ts.Ticks; } + private int _PrintBias = 0; public int PrintBias { @@ -7127,10 +7136,11 @@ namespace VEPROMS.CSLA.Library if (tmp.MyDocVersion.DocVersionConfig.SelectedSlave <= 0) MyRefreshTransitions(tmp, tmp.MyDocVersion, null, tmp, tmp.MyDocVersion, tranLookup); } - public static void RefreshReferenceObjects(ProcedureInfo tmp) + // B2022-026 RO Memory Reduction code - added ROFstInfo parameter + public static void RefreshReferenceObjects(ProcedureInfo tmp, ROFstInfo origROFst) { if (tmp.MyDocVersion.DocVersionConfig.SelectedSlave <= 0) - MyRefreshReferenceObjects(tmp, tmp.MyDocVersion, null, tmp.MyDocVersion); + MyRefreshReferenceObjects(tmp, tmp.MyDocVersion, null, tmp.MyDocVersion, origROFst); } public static void RefreshPageNumTransitions(ProcedureInfo tmp) { diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/MultiUserExt.cs b/PROMS/VEPROMS.CSLA.Library/Extension/MultiUserExt.cs index 3b8beae9..c1f64bc3 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/MultiUserExt.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/MultiUserExt.cs @@ -16,6 +16,7 @@ namespace VEPROMS.CSLA.Library Procedure = 0, Document = 1, DocVersion = 2, Folder = 3, Session = 4 } #endregion + #region SessionInfoList stuff public partial class SessionInfoList { @@ -67,6 +68,7 @@ namespace VEPROMS.CSLA.Library } } #endregion + #region SessionInfo stuff public partial class SessionInfo { @@ -750,6 +752,7 @@ namespace VEPROMS.CSLA.Library #endregion } #endregion + #region OwnerInfo stuff public partial class OwnerInfoList { @@ -1072,29 +1075,36 @@ namespace VEPROMS.CSLA.Library } } #endregion + #region UserInfo stuff + public partial class UserInfo { public static bool CanEdit(UserInfo myUserInfo, DocVersionInfo myDVI) { return myUserInfo!=null && myDVI!=null && (myUserInfo.IsAdministrator() || myUserInfo.IsSetAdministrator(myDVI) || myUserInfo.IsWriter(myDVI)); } + public static bool CanEditROs(UserInfo myUserInfo, DocVersionInfo myDVI) { return myUserInfo != null && myDVI != null && myUserInfo.IsAdministrator() || myUserInfo.IsSetAdministrator(myDVI) || myUserInfo.IsROEditor(myDVI); } + public static bool CanCreateFolders(UserInfo myUserInfo, DocVersionInfo myDVI) { return myUserInfo != null && myDVI != null && myUserInfo.IsAdministrator() || myUserInfo.IsSetAdministrator(myDVI); } + public static bool CanCreateFolders(UserInfo myUserInfo, FolderInfo fi) { return myUserInfo != null && fi != null && myUserInfo.IsAdministrator() || myUserInfo.IsSetAdministrator(fi.MyParent); //B2020-111 allow if set amin controls parent } + public bool IsAdministrator() { if (this.UserMembershipCount == 0) return false; + foreach (MembershipInfo mi in this.UserMemberships) { if (mi.EndDate == string.Empty) @@ -1108,6 +1118,7 @@ namespace VEPROMS.CSLA.Library } return false; } + //B2020-111, B2020-114, C2020-035 this was setting the passed in parameter, such that the first time this // was called, the passed in parameter was set to the top node (VEPROMS). The check of other folders // would then be skipped (from where is called) @@ -1115,6 +1126,7 @@ namespace VEPROMS.CSLA.Library { if (this.UserMembershipCount == 0 || fldinf == null) return false; + foreach (MembershipInfo mi in this.UserMemberships) { if (mi.EndDate == string.Empty) @@ -1137,10 +1149,12 @@ namespace VEPROMS.CSLA.Library } return false; } + public bool IsSetAdministrator(DocVersionInfo dv) { - if (this.UserMembershipCount == 0) + if (this.UserMembershipCount == 0 || dv == null) // B2022-026 RO Memory reduction - check for null DocVersionInfo return false; + foreach (MembershipInfo mi in this.UserMemberships) { if (mi.EndDate == string.Empty) @@ -1162,10 +1176,12 @@ namespace VEPROMS.CSLA.Library } return false; } + public bool IsWriter(DocVersionInfo dv) { - if (this.UserMembershipCount == 0) + if (this.UserMembershipCount == 0 || dv == null) // B2022-026 RO Memory reduction - check for null DocVersionInfo return false; + foreach (MembershipInfo mi in this.UserMemberships) { if (mi.EndDate == string.Empty) @@ -1187,10 +1203,12 @@ namespace VEPROMS.CSLA.Library } return false; } + public bool IsReviewer(DocVersionInfo dv) { - if (this.UserMembershipCount == 0) + if (this.UserMembershipCount == 0 || dv == null) // B2022-026 RO Memory reduction - check for null DocVersionInfo return false; + foreach (MembershipInfo mi in this.UserMemberships) { if (mi.EndDate == string.Empty) @@ -1212,10 +1230,12 @@ namespace VEPROMS.CSLA.Library } return false; } + public bool IsROEditor(DocVersionInfo dv) { - if (this.UserMembershipCount == 0) + if (this.UserMembershipCount == 0 || dv == null) // B2022-026 RO Memory reduction - check for null DocVersionInfo return false; + foreach (MembershipInfo mi in this.UserMemberships) { if (mi.EndDate == string.Empty) @@ -1237,6 +1257,7 @@ namespace VEPROMS.CSLA.Library } return false; } + // B2018-112 added for easy check if user's PROMS Security allows making edits - used in StepTabRibbon - SetButtonAndMenuEnabling() public bool IsAllowedToEdit(DocVersionInfo dvi) { @@ -1259,6 +1280,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on UserInfo.GetByUserID", ex); } } + [Serializable()] protected class GetByUserIDCriteria { @@ -1270,6 +1292,7 @@ namespace VEPROMS.CSLA.Library _UserID = userID; } } + private void DataPortal_Fetch(GetByUserIDCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] UserInfo.DataPortal_Fetch", GetHashCode()); @@ -1307,5 +1330,6 @@ namespace VEPROMS.CSLA.Library } } } + #endregion } diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/ROFSTExt.cs b/PROMS/VEPROMS.CSLA.Library/Extension/ROFSTExt.cs index 10f5e52a..4f00bf44 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/ROFSTExt.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/ROFSTExt.cs @@ -28,34 +28,15 @@ namespace VEPROMS.CSLA.Library { public partial class ROFst { - // put in for debug - //public static int CacheCountPrimaryKey - //{ get { return _CacheByPrimaryKey.Count; } } - //public static int CacheCountByRODbID_DTS - //{ get { return _CacheByRODbID_DTS.Count; } } - //public static int CacheCountList - //{ get { return _CacheList.Count; } } - - //[NonSerialized] - //private ROFSTLookup _ROFSTLookup; - //public ROFSTLookup ROFSTLookup - //{ - // get - // { - // if (_ROFSTLookup == null) - // { - // _ROFSTLookup = new ROFSTLookup(this); - // } - // return _ROFSTLookup; - // } - //} public static ROFst GetJustROFst(int rOFstID) { if (!CanGetObject()) throw new System.Security.SecurityException("User not authorized to view a ROFst"); + try { ROFst tmp = GetCachedByPrimaryKey(rOFstID); + if (tmp == null) { tmp = DataPortal.Fetch(new PKCriteriaJustROFst(rOFstID)); @@ -66,6 +47,7 @@ namespace VEPROMS.CSLA.Library tmp.Dispose(); // Clean-up ROFst tmp = null; } + return tmp; } catch (Exception ex) @@ -73,6 +55,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on ROFst.Get", ex); } } + [Serializable()] protected class PKCriteriaJustROFst { @@ -84,6 +67,7 @@ namespace VEPROMS.CSLA.Library _ROFstID = rOFstID; } } + private void DataPortal_Fetch(PKCriteriaJustROFst criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ROFst.DataPortal_Fetch", GetHashCode()); @@ -106,12 +90,6 @@ namespace VEPROMS.CSLA.Library return; } ReadData(dr); - // load child objects - //dr.NextResult(); - //_ROFstAssociations = ROFstAssociations.Get(dr); - // load child objects - //dr.NextResult(); - //_ROFstFigures = ROFstFigures.Get(dr); } } // removing of item only needed for local data portal @@ -126,120 +104,70 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ROFst.DataPortal_Fetch", ex); } } - } + public delegate List ROFstInfoROTableUpdateEvent(object sender, ROFstInfoROTableUpdateEventArgs args); public delegate void ROFstInfoProgressBarRefresh(int value, int max, string text); + public partial class ROFstInfo { - // put in for debug - //public static int CacheCountPrimaryKey - //{ get { return _CacheByPrimaryKey.Count; } } - //public static int CacheCountList - //{ get { return _CacheList.Count; } } #region Log4Net - private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region PropertiesAndData -// private DocVersionInfo _docVer; -// public DocVersionInfo docVer -// { -// get -// { -// if (_docVer == null) -// { -// if (ROFstAssociations.Count == 0) return null; -//// _docVer = DocVersion.Get(this.ROFstAssociations[0].MyDocVersion.VersionID); -// _docVer = this.ROFstAssociations[0].MyDocVersion; -// } -// return _docVer; -// } -// set -// { -// _docVer = value; - -// } -// } - //[NonSerialized] - //private ROFSTLookup _ROFSTLookup; - //public ROFSTLookup ROFSTLookup - //{ - // get - // { - // if (_ROFSTLookup == null) - // { - // _ROFSTLookup = new ROFSTLookup(this); - // } - // return _ROFSTLookup; - // } - //} - private Dictionary dicLookups = new Dictionary(); - public ROFSTLookup GetROFSTLookup(DocVersionInfo dvi) - { - return GetROFSTLookup(dvi, ""); - } - public ROFSTLookup GetROFSTLookup(DocVersionInfo dvi, string ovrrideChild) - { - string key = ""; - if (ovrrideChild == null || ovrrideChild == "") - key = string.Format("{0}.{1}.{2}", ROFstID, dvi.DocVersionConfig.MaxSlaveIndex, dvi.DocVersionConfig.SelectedSlave); - else - key = string.Format("{0}.{1}.{2}", ROFstID, dvi.DocVersionConfig.MaxSlaveIndex, ovrrideChild); // C2021-065 use OTHER child information - if (!dicLookups.ContainsKey(key)) - { - dicLookups.Clear(); //B2022-001 clear the dictionary each time to free up memory - out of memory fix - dicLookups.Add(key, new ROFSTLookup(this, dvi)); - } - if (ovrrideChild != null && ovrrideChild != "") - dicLookups[key].OtherChild = ovrrideChild; // C2021-065 use the OTHER applicabiltiy info to get RO Values - return dicLookups[key]; - } + private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); + #endregion - #region AppSupport - //public static ROImageInfo Get(RODbInfo rodbinfo, string filename) - //{ - // if (rodbinfo.RODbROImageCount != 0) - // { - // foreach (ROImageInfo ri in rodbinfo.RODbROImages) - // { - // if (ri.FileName == filename) return ri; - // } - // } - // return null; - //} - //public string GetDefaultROPrefix() - //{ - // if (docVer != null) - // return docVer.DocVersionConfig.RODefaults_setpointprefix; - // else - // return "SP1"; // Not Sure about this... - //} - //public string GetDefaultGraphicsPrefix() - //{ - // if (docVer != null) - // return docVer.DocVersionConfig.RODefaults_graphicsprefix; - // else - // return "IG1"; // Not Sure about this... - //} - #region Add New Ro Fst + + [Serializable()] + protected class PKCriteriaJustROFst + { + private int _ROFstID; + public int ROFstID + { get { return _ROFstID; } } + public PKCriteriaJustROFst(int rOFstID) + { + _ROFstID = rOFstID; + } + } + + #region Fields + + // this is used by the frmBatchRefresh which is the Adim Tools so that one message is display for a group of procedure sets processed + public static StringBuilder MessageList = null; + + private static List DocVersionsNeedingROUpdate = new List(); + + #endregion + + #region Events + + public event ROFstInfoROTableUpdateEvent ROTableUpdate; + + #endregion + + #region Public Methods + + public ROFSTLookup GetROFSTLookup(DocVersionInfo dvi, string ovrrideChild = null) + { + return new ROFSTLookup(this.ROFstID, dvi, ovrrideChild); + } + /// /// Adds an ro.fst into a sql database. /// - /// /// ROFst: Returns the created rofst object public static ROFst AddRoFst(RODbInfo rdi, DocVersion docver, ROFstInfoProgressBarRefresh myProgressBarRefresh) { string rofstfilepath = rdi.FolderPath + @"\ro.fst"; DirectoryInfo di = new DirectoryInfo(rdi.FolderPath); + if (!di.Exists) return null; if (!File.Exists(rofstfilepath)) return null; - // check if this rofst has been loaded, i.e. dts on file versus dts in db... - // if so, just make association with docversion. + // check if this rofst has been loaded, i.e. dts on file versus dts in db... if so, just make association with docversion. ROFst rofst = ROFst.GetByRODbID_DTS(rdi.RODbID, di.LastWriteTimeUtc); + if (rofst != null) { docver.DocVersionAssociations.Add(rofst); @@ -247,95 +175,110 @@ namespace VEPROMS.CSLA.Library return rofst; } - // Next read in the rofst & make the rofst record. - FileStream fsIn = new FileStream(rofstfilepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); - // Create an instance of StreamReader that can read characters from the FileStream. - BinaryReader r = new BinaryReader(fsIn); - byte[] ab = r.ReadBytes((int)fsIn.Length); - fsIn.Close(); + byte[] rofstBytes = null; // B2022-026 RO Memory Reduction code - more descriptive name + using (FileStream fsIn = new FileStream(rofstfilepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) + { + using (BinaryReader r = new BinaryReader(fsIn)) + { + rofstBytes = r.ReadBytes((int)fsIn.Length); + fsIn.Close(); + } + } using (RODb rodb = RODb.GetJustRoDb(rdi.RODbID)) { using (ROImageInfoList myROImages = ROImageInfoList.GetByRODbID(rdi.RODbID)) { Dictionary myExistingROImages = BuildROImagesList(myROImages); + List myUnChangedROImages = new List(); List myAddedROImages = new List(); List MyChangedFigureROIDs = new List(); - rofst = ROFst.MakeROFst(rodb, ab, null, di.LastWriteTimeUtc, rdi.UserID); - // Hook this into the current docversion by replacing the rofstid field in the doc version - // association object: + + rofst = ROFst.MakeROFst(rodb, rofstBytes, null, di.LastWriteTimeUtc, rdi.UserID); + + // Hook this into the current docversion by replacing the rofstid field in the doc version association object: docver.DocVersionAssociations.Add(rofst); docver.Save(); - ROFSTLookup myLookup = ROFstInfo.GetJustROFst(rofst.ROFstID).GetROFSTLookup(DocVersionInfo.Get(docver.VersionID)); + // Now load any images in... type 8 - integrated graphics ro type - for (int i = 0; i < myLookup.myHdr.myDbs.Length; i++) + // B2022-026 RO Memory Reduction code now load the children with a separate call which will get only the Image ROs + ROFSTLookup myLookup = new ROFSTLookup(rofst.ROFstID, DocVersionInfo.Get(docver.VersionID)); + ROFSTLookup.rochild[] children = myLookup.GetRoChildrenByType(E_ROValueType.Image); + + if (children != null && children.Length > 0) { - // walk through the rofst 'database' searching for all nodes that are integrated graphics, type 8: - if (myLookup.myHdr.myDbs[i].children != null) + using (ROFstInfo rfi = ROFstInfo.Get(rofst.ROFstID)) { - using (ROFstInfo rfi = ROFstInfo.Get(rofst.ROFstID)) - { - int cnt = rfi.CountRoFstGraphics(myLookup.myHdr.myDbs[i].children); // get the total number of RO figures - int curCnt = 0; - rfi.MigrateRoFstGraphics(rdi, myLookup.myHdr.myDbs[i].children, rodb, rofst, myExistingROImages, myUnChangedROImages, myAddedROImages, MyChangedFigureROIDs, myProgressBarRefresh, cnt, ref curCnt);// TODO: Need to add MyImages - } + int cnt = children.Length; // get the total number of RO figures + int curCnt = 0; + rfi.MigrateRoFstGraphics(rdi, children, rodb, rofst, myExistingROImages, myUnChangedROImages, myAddedROImages, MyChangedFigureROIDs, myProgressBarRefresh, cnt, ref curCnt);// TODO: Need to add MyImages } } + if (myUnChangedROImages.Count > 0) using (FigureInfoList fil = FigureInfoList.AddByROFstIDImageIDs(rofst.ROFstID, buildImageIDString(myUnChangedROImages))) ; + return rofst; } } } - #endregion - #region Update Ro Values - public static int RefreshROFst(DocVersionInfo dvi, ROFstInfoProgressBarRefresh myProgressBarRefresh, System.Windows.Forms.TextBox tbStatus) + + // B2022-026 RO Memory Reduction code - pass in the ROFstInfo + public static int RefreshROFst(DocVersionInfo dvi, ROFstInfoProgressBarRefresh myProgressBarRefresh, System.Windows.Forms.TextBox tbStatus, ROFstInfo origROFst) { int fixedROs = 0; + if (dvi.DocVersionConfig.SelectedSlave <= 0) { myProgressBarRefresh(1, 100, "Update MS Word ROs"); - Pdf.DeleteAllDocVersion(dvi.VersionID); // remove word section PDFs to force upate of RO values when printed + + Pdf.DeleteAllDocVersion(dvi.VersionID); // remove word section PDFs to force update of RO values when printed int i = 0; + foreach (ProcedureInfo proc in dvi.Procedures) { DateTime start = DateTime.Now; + ProcedureInfo.ResetROCounters(); - myProgressBarRefresh(++i, dvi.Procedures.Count, string.Format("{0} ({1}/{2} ROs {3})",proc.DisplayNumber,i,dvi.Procedures.Count,fixedROs)); - ProcedureInfo.RefreshReferenceObjects(proc); + myProgressBarRefresh(++i, dvi.Procedures.Count, string.Format("{0} ({1}/{2} ROs {3})", proc.DisplayNumber, i, dvi.Procedures.Count, fixedROs)); + ProcedureInfo.RefreshReferenceObjects(proc, origROFst); fixedROs += ProcedureInfo.ROFixCount; + TimeSpan ts = DateTime.Now - start; + if (tbStatus != null) tbStatus.AppendText(string.Format("Procedure: {1}{0}, Checked {2} Referenced Objects{0}, Fixed {3} Referenced Objects{0}, Elapsed Seconds:{4}{0}{0}", Environment.NewLine, proc.DisplayNumber, ProcedureInfo.ROCheckCount, ProcedureInfo.ROFixCount, ts.TotalSeconds)); + } } - } + return fixedROs; } + // returns the path and file name with Proc Set Name and the completed date/time (used for all update RO calls except for Amin Tool from the V button) - public static string ROUpdateResultsPath (DocVersionInfo dvi) - { - // B2019-032 - call ValidFileName.FixFileName() to clean up the file name. - return Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\VEPROMS\ROUpdateReport_" + ValidFileName.FixFileName(dvi.MyFolder.Name.Replace(" ", "_") + "_" + DateTime.Now.ToString("MM-dd-yyyy_HH-mm-ss") + ".txt"); - } - public static ROFst RefreshROFst(RODbInfo rdi, DocVersionAssociation dva, DocVersion docver, ROFstInfo origROFst, ROFstInfoProgressBarRefresh myProgressBarRefresh, System.Windows.Forms.TextBox tbStatus) + public static string ROUpdateResultsPath(DocVersionInfo dvi) + { + // B2019-032 - call ValidFileName.FixFileName() to clean up the file name. + return Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\VEPROMS\ROUpdateReport_" + ValidFileName.FixFileName(dvi.MyFolder.Name.Replace(" ", "_") + "_" + DateTime.Now.ToString("MM-dd-yyyy_HH-mm-ss") + ".txt"); + } + + // B2022-026 RO Memory Reduction code - moved the call to UpdateROFst() to before we call RefreshROFst + // so that we used the correct ROFstInfo which as the needed event methods set when updated RO Table types + public static ROFst RefreshROFst(DocVersion docver, ROFstInfo origROFst, ROFstInfoProgressBarRefresh myProgressBarRefresh, System.Windows.Forms.TextBox tbStatus) { ROFst rofst = null; - if (docver.ROfstLoadingFigures || docver.NewerRoFst) // B2017-125 see if loading figures was completed - { - // only load the RO.fst - Volian.Base.Library.VlnSettings.DoUpdateRO = false; - rofst = ROFstInfo.UpdateRoFst(rdi, dva, docver, origROFst, myProgressBarRefresh); - Volian.Base.Library.VlnSettings.DoUpdateRO = true; - } - else - rofst = docver.DocVersionAssociations[0].MyROFst; - DocVersionInfo dvi = DocVersionInfo.Get(docver.VersionID); - SetAssociationLastCompleted(docver,string.Empty); - int fixedROs = RefreshROFst(dvi, myProgressBarRefresh, tbStatus); + + rofst = docver.DocVersionAssociations[0].MyROFst; + + DocVersionInfo dvi = DocVersionInfo.Get(docver.VersionID); + + SetAssociationLastCompleted(docver, string.Empty); + int fixedROs = RefreshROFst(dvi, myProgressBarRefresh, tbStatus, origROFst); SetAssociationLastCompleted(docver, DateTime.Now.ToString()); // RO Update completed successfully and un-interrupted, save the date/time to the Doc Version Association config + myProgressBarRefresh(100, 100, "RO Update Complete"); // update the progress bar System.Windows.Forms.Application.DoEvents(); + // pop up a message window telling the user the RO Update has completed and how many ROs were updated // If we are updating RO from the Admin Tools (from the V button) and we are updating more than on procedure set, then just append the "RO Update Complete" text // To the MessageList. Once completed will all procedure sets, Admin Tools will display one message box with all the results in it. @@ -343,32 +286,10 @@ namespace VEPROMS.CSLA.Library FlexibleMessageBox.Show(fixedROs == 0 ? "No ROs Required Updating" : string.Format("{0} ROs Updated for {1}", fixedROs, dvi.MyFolder.Name), "RO Update Complete"); else MessageList.AppendLine((fixedROs == 0 ? "No ROs Required Updating for " : string.Format("{0} ROs Updated for ", fixedROs)) + dvi.MyFolder.Name); - + return rofst; } - // this is used by the frmBatchRefresh which is the Adim Tools so that one message is display for a group of procedure sets processed - public static StringBuilder MessageList = null; - - // Place the date/time of the completed RO Update in the DocVersion association config - // this witll tell us if the RO Update was completed, interrupted, or just needs done and whether to make the Update ROs button available - private static void SetAssociationLastCompleted(DocVersion docver, string value) - { - string cfg = docver.DocVersionAssociations[0].Config; - AssociationConfig ac = new AssociationConfig((cfg== null || cfg.Length == 0) ? "" : cfg); - ac.ROUpdate_LastCompleted = value; - docver.DocVersionAssociations[0].Config = ac.ToString(); - docver.Save(); - } - // Place the status of loading the RO Figures when updating RO Values - private static void SetAssociationROFiguresLoading(DocVersion docver, string value) - { - string cfg = docver.DocVersionAssociations[0].Config; - AssociationConfig ac = new AssociationConfig((cfg== null || cfg.Length == 0) ? "" : cfg); - ac.ROUpdate_LoadingFigures = value; - docver.DocVersionAssociations[0].Config = ac.ToString(); - docver.Save(); - } /// /// Updates an ro.fst into a sql database. /// @@ -378,87 +299,208 @@ namespace VEPROMS.CSLA.Library /// the current one. /// /// ROFst: Returns the created rofst object - public static ROFst UpdateRoFst(RODbInfo rdi, DocVersionAssociation dva, DocVersion docver, ROFstInfo origROFst, ROFstInfoProgressBarRefresh myProgressBarRefresh) + + // B2022-026 RO Memory Reduction code - removed checks and calls to update the RO values in the text. + // all of the calls aways set the flags to not update the RO values + public static ROFst UpdateRoFst(RODbInfo rdi, DocVersion docver, ROFstInfo origROFst, ROFstInfoProgressBarRefresh myProgressBarRefresh) { if (myProgressBarRefresh != null) myProgressBarRefresh(0, 100, "Starting Update"); + DirectoryInfo di = new DirectoryInfo(rdi.FolderPath); string rofstfilepath = rdi.FolderPath + @"\ro.fst"; FileStream fsIn = new FileStream(rofstfilepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); FileInfo rofstFI = new FileInfo(rofstfilepath); + // check if this rofst has been loaded, i.e. dts on file versus dts in db... // if so, just make association to existing with docversion. ROFst rofst = ROFst.GetByRODbID_DTS(rdi.RODbID, rofstFI.LastWriteTimeUtc); + if (rofst != null) { // Get a list of figures which have changed content (DTS) List MyChangedFigureROIDs = null; + if (docver.ROfstLoadingFigures) // B2017-125 see if loading figures was completed { - ROFSTLookup myLookup = ROFstInfo.GetJustROFst(rofst.ROFstID).GetROFSTLookup(DocVersionInfo.Get(docver.VersionID)); + ROFSTLookup myLookup = new ROFSTLookup(rofst.ROFstID, DocVersionInfo.Get(docver.VersionID)); MyChangedFigureROIDs = UpdateROFigures(rdi, myProgressBarRefresh, rofst, RODb.GetJustRoDb(rdi.RODbID), myLookup, docver); } else + { MyChangedFigureROIDs = GetChangedFigureROIDs(origROFst, ROFstInfo.GetJustROFst(rofst.ROFstID), DocVersionInfo.Get(docver.VersionID), myProgressBarRefresh); + } + docver.DocVersionAssociations[0].MyROFst = rofst; SetAssociationLastCompleted(docver, string.Empty); - if (!Volian.Base.Library.VlnSettings.GetCommandFlag("NOUPDATERO") && Volian.Base.Library.VlnSettings.DoUpdateRO) - UpdateROValuesText(origROFst, rofst, DocVersionInfo.Get(docver.VersionID), myProgressBarRefresh, MyChangedFigureROIDs); + return rofst; } - + // Read in the rofst & make the rofst record. // Create an instance of StreamReader that can read characters from the FileStream. BinaryReader r = new BinaryReader(fsIn); byte[] ab = r.ReadBytes((int)fsIn.Length); fsIn.Close(); + using (RODb rodb = RODb.GetJustRoDb(rdi.RODbID)) { rofst = ROFst.MakeROFst(rodb, ab, null, rofstFI.LastWriteTimeUtc, rdi.UserID); - // Hook this into the current docversion by replacing the rofstid field in the doc version - // association object: - dva.MyROFst = rofst; + + // Hook this into the current docversion by replacing the rofstid field in the doc version association object: + docver.DocVersionAssociations[0].MyROFst = rofst; SetAssociationROFiguresLoading(docver, "Started"); // B2017-125 flag was we are loading the RO figures - //docver.Save(); - ROFSTLookup myLookup = ROFstInfo.GetJustROFst(rofst.ROFstID).GetROFSTLookup(DocVersionInfo.Get(docver.VersionID)); + + ROFSTLookup myLookup = new ROFSTLookup(rofst.ROFstID, DocVersionInfo.Get(docver.VersionID)); + // Keep a list of ROIDs for Images that have changed. - List MyChangedFigureROIDs = UpdateROFigures(rdi, myProgressBarRefresh, rofst, rodb, myLookup,docver); - // Now update the usages: compare old to new rofsts and update usages accordingly, i.e. modified - // values, deleted ros, etc. - if (!Volian.Base.Library.VlnSettings.GetCommandFlag("NOUPDATERO") && Volian.Base.Library.VlnSettings.DoUpdateRO) - UpdateROValuesText(origROFst, rofst, DocVersionInfo.Get(docver.VersionID),myProgressBarRefresh, MyChangedFigureROIDs); + List MyChangedFigureROIDs = UpdateROFigures(rdi, myProgressBarRefresh, rofst, rodb, myLookup, docver); + return rofst; } } + public bool IsSetpointDB(int id, DocVersionInfo dvi) + { + ROFSTLookup.rodbi[] dbs = GetROFSTLookup(dvi).GetRODatabaseList(false); + + foreach (ROFSTLookup.rodbi rodbi in dbs) + { + if (id == rodbi.dbiID) + return (rodbi.dbiAP.StartsWith("SP")); + } + + return false; + } + + public ROFst GetJustROFst() + { + return ROFst.GetJustROFst(ROFstID); + } + + public List OnROTableUpdate(object sender, ROFstInfoROTableUpdateEventArgs args) + { + if (ROTableUpdate != null) return ROTableUpdate(sender, args); + return null; + } + + public static ROFstInfo GetJustROFst(int rOFstID) + { + try + { + ROFstInfo tmp = GetCachedByPrimaryKey(rOFstID); + + if (tmp == null) + { + tmp = DataPortal.Fetch(new PKCriteriaJustROFst(rOFstID)); + AddToCache(tmp); + } + + if (tmp.ErrorMessage == "No Record Found") + { + tmp.Dispose(); // Clean-up ROFstInfo + tmp = null; + } + + if (tmp != null) + { + tmp.ClearROLookupBytes(); + } + + return tmp; + } + catch (Exception ex) + { + throw new DbCslaException("Error on ROFstInfo.Get", ex); + } + } + + public ROImageInfo GetROImageByFilename(string filename, ItemInfo myItemInfo) + { + ROImageInfoList images = ROImageInfoList.GetByRODbIDFilename(RODbID, filename); + + if (images == null || images.Count == 0) + { + ROWarning(myItemInfo, "Referenced Object Image {0} Missing", filename); + return null; + } + + ROImageInfo retval = null; + foreach (ROImageInfo image in images) + { + if (image.DTS > DTS && retval != null) break; + retval = image; + } + + if (retval.DTS > DTS) + ROWarning(myItemInfo, "Referenced Object Image {0} newer {1} than RO.FST {2}", filename, retval.DTS.ToShortDateString(), DTS.ToShortDateString()); + else + ROWarning(myItemInfo, "Referenced Object Image {0} older {1} then RO.FST {2}", filename, retval.DTS.ToShortDateString(), DTS.ToShortDateString()); + + return retval; + } + + #endregion + + #region Private Methods + + // Place the date/time of the completed RO Update in the DocVersion association config + // this will tell us if the RO Update was completed, interrupted, or just needs done and whether to make the Update ROs button available + private static void SetAssociationLastCompleted(DocVersion docver, string value) + { + string cfg = docver.DocVersionAssociations[0].Config; + + AssociationConfig ac = new AssociationConfig((cfg== null || cfg.Length == 0) ? "" : cfg); + ac.ROUpdate_LastCompleted = value; + docver.DocVersionAssociations[0].Config = ac.ToString(); + docver.Save(); + } + + // Place the status of loading the RO Figures when updating RO Values + private static void SetAssociationROFiguresLoading(DocVersion docver, string value) + { + string cfg = docver.DocVersionAssociations[0].Config; + + AssociationConfig ac = new AssociationConfig((cfg== null || cfg.Length == 0) ? "" : cfg); + ac.ROUpdate_LoadingFigures = value; + docver.DocVersionAssociations[0].Config = ac.ToString(); + docver.Save(); + } + private static List UpdateROFigures(RODbInfo rdi, ROFstInfoProgressBarRefresh myProgressBarRefresh, ROFst rofst, RODb rodb, ROFSTLookup myLookup, DocVersion docVer) { List MyChangedFigureROIDs = new List(); + // Now load any images in... type 8 - integrated graphics ro type using (ROImageInfoList myROImages = ROImageInfoList.GetByRODbIDNoData(rdi.RODbID)) { Dictionary myExistingROImages = BuildROImagesList(myROImages); + List myUnChangedROImages = new List(); List myAddedROImages = new List(); - using (ROFstInfo rfi = ROFstInfo.Get(rofst.ROFstID)) + + // B2022-026 RO Memory Reduction code - get only the Image ROs + ROFSTLookup.rochild[] children = myLookup.GetRoChildrenByType(E_ROValueType.Image); + + if (children != null && children.Length > 0) { - for (int i = 0; i < myLookup.myHdr.myDbs.Length; i++) + using (ROFstInfo rfi = ROFstInfo.Get(rofst.ROFstID)) { - // walk through the rofst 'database' searching for all nodes that are integrated graphics, type 8: - if (myLookup.myHdr.myDbs[i].children != null) - { - int cnt = rfi.CountRoFstGraphics(myLookup.myHdr.myDbs[i].children); // get the total number of RO figures - int curCnt = 0; - rfi.MigrateRoFstGraphics(rdi, myLookup.myHdr.myDbs[i].children, rodb, rofst, myExistingROImages, myUnChangedROImages, myAddedROImages, MyChangedFigureROIDs, myProgressBarRefresh, cnt, ref curCnt); - } + int cnt = children.Length; // get the total number of RO figures + int curCnt = 0; + rfi.MigrateRoFstGraphics(rdi, children, rodb, rofst, myExistingROImages, myUnChangedROImages, myAddedROImages, MyChangedFigureROIDs, myProgressBarRefresh, cnt, ref curCnt);// TODO: Need to add MyImages } } + // Add references for existing RO Images to the Figure table (Figure table relates ro.fst with its images) if (myUnChangedROImages.Count > 0) using (FigureInfoList fil = FigureInfoList.AddByROFstIDImageIDs(rofst.ROFstID, buildImageIDString(myUnChangedROImages))) ; } + SetAssociationROFiguresLoading(docVer, string.Empty); // B2017-125 loading RO Figures is completed + return MyChangedFigureROIDs; } + /// /// Get a list of ROIDs for figures that have changed content. This is only used when the contents of a figure /// is changed without changing the filename. @@ -471,10 +513,13 @@ namespace VEPROMS.CSLA.Library { // Need to create a list of ROIDs for figures which have changed List ChangedFiles = GetChangedFigures(origROFst, rofst, myProgressBarRefresh); + // Get ROID associated with FileNames List ROIDs = GetROIDsFromLookup(rofst,ChangedFiles,docver); + return ROIDs; } + /// /// Find all of the ROIDs associated with files that have changed /// @@ -485,39 +530,28 @@ namespace VEPROMS.CSLA.Library private static List GetROIDsFromLookup(ROFstInfo rofst, List ChangedFiles, DocVersionInfo docver) { List roids = new List(); - ROFSTLookup myLookup = rofst.GetROFSTLookup(docver); - for (int i = 0; i < myLookup.myHdr.myDbs.Length; i++) + + ROFSTLookup myLookup = new ROFSTLookup(rofst.ROFstID, docver); + // B2022-026 RO Memory Reduction code - get only the Image type of ROs + ROFSTLookup.rochild[] children = myLookup.GetRoChildrenByType(E_ROValueType.Image); + + if (children != null && children.Length > 0) { - if (myLookup.myHdr.myDbs[i].children != null) + for (int i = 0; i < children.Length; i++) { - FindChangedFiles(myLookup.myHdr.myDbs[i].children,ChangedFiles,roids); + string filename = children[i].value; + filename = filename.Substring(0, filename.IndexOf('\n')); + + if (ChangedFiles.Contains(filename)) + { + roids.Add(children[i].roid); + } } } + return roids; } - /// - /// Find the ROIDs in the ROLookup - /// - /// an RO or RO Group - /// List of Files that have changed - /// List of ROIDs with changed figures - private static void FindChangedFiles(ROFSTLookup.rochild[] rochild,List ChangedFiles, List roids) - { - if (ChangedFiles != null) - { - for (int i = 0; i < rochild.Length; i++) - { - if (rochild[i].type == 8 && rochild[i].value != null) - { - string filename = rochild[i].value; - filename = filename.Substring(0, filename.IndexOf('\n')); - if (ChangedFiles.Contains(filename)) - roids.Add(rochild[i].roid); - } - if (rochild[i].children != null) FindChangedFiles(rochild[i].children, ChangedFiles, roids); - } - } - } + /// /// Get a List of figures which have changed /// @@ -527,7 +561,9 @@ namespace VEPROMS.CSLA.Library private static List GetChangedFigures(ROFstInfo origROFst, ROFstInfo rofst, ROFstInfoProgressBarRefresh myProgressBarRefresh) { if (origROFst.ROFstFigures == null) return null; + Dictionary orig = new Dictionary(); + int i = 0; foreach (FigureInfo fi in origROFst.ROFstFigures) { @@ -535,71 +571,91 @@ namespace VEPROMS.CSLA.Library myProgressBarRefresh(++i, origROFst.ROFstFigures.Count, "Original " + key); if (!orig.ContainsKey(key)) orig.Add(key, fi.ImageID); } + + // B2018-032 Don't crash if there are no figures + if (rofst.ROFstFigures == null) + return null; + i = 0; - if (rofst.ROFstFigures == null) return null;// B2018-032 Don't crash if there are no figures foreach (FigureInfo fi in rofst.ROFstFigures) { string key = fi.ROImage_FileName ?? fi.MyROImage.FileName; myProgressBarRefresh(++i, rofst.ROFstFigures.Count, "Current " + key); - if (orig.ContainsKey(key) && orig[key] == fi.ImageID) - orig.Remove(key); + if (orig.ContainsKey(key) && orig[key] == fi.ImageID) orig.Remove(key); } + List changedFigures = new List(); + i = 0; foreach (string key in orig.Keys) { myProgressBarRefresh(++i, orig.Count, "Compare " + key); changedFigures.Add(key); } + return changedFigures; } + private static Dictionary BuildROImagesList(ROImageInfoList myROImages) { Dictionary myRoImagesList = new Dictionary(); + foreach (ROImageInfo myROImage in myROImages) - myRoImagesList.Add(ROImageKey(myROImage.FileName, myROImage.DTS),myROImage.ImageID); + { + myRoImagesList.Add(ROImageKey(myROImage.FileName, myROImage.DTS), myROImage.ImageID); + } + return myRoImagesList; } + private static string ROImageKey(string fileName, DateTime dts) { return string.Format("{0}:{1}", fileName, dts); } + private static string buildImageIDString(List myROImageIDs) { StringBuilder sb = new StringBuilder(); string sep = ""; + foreach (int imageID in myROImageIDs) { sb.Append(sep + imageID.ToString()); sep = ","; } + return sb.ToString(); } + private static void UpdateROValuesText(ROFstInfo origROFstInfo, ROFst newROFst, DocVersionInfo dvi, ROFstInfoProgressBarRefresh myProgressBarRefresh, List MyChangedFigureROIDs) { if (myProgressBarRefresh != null) myProgressBarRefresh(0, 100, "Update Ro Values"); + string versionList = dvi.VersionID.ToString(); - //DateTime dtStart = DateTime.Now; - //DateTime dtLast = DateTime.Now; - ROFSTLookup origLU = new ROFSTLookup(origROFstInfo, dvi); - //dtLast = ShowDuration(dtLast, "origLU"); - ROFSTLookup newLU = new ROFSTLookup(newROFst, dvi); - //dtLast = ShowDuration(dtLast, "newLU"); + + ROFSTLookup origLookup = new ROFSTLookup(origROFstInfo.ROFstID, dvi); + ROFSTLookup newLookup = new ROFSTLookup(newROFst.ROFstID, dvi); + List delList = new List(); - List chgList = newLU.GetValueDifferences(origLU, ref delList); + List chgList = newLookup.GetValueDifferences(origROFstInfo.ROFstID, ref delList); + // Any figures which have been changed will be included in the list of values that have changed. if (MyChangedFigureROIDs != null) - foreach (string roid in MyChangedFigureROIDs) - if (!chgList.Contains(roid)) - chgList.Add(roid); - //dtLast = ShowDuration(dtLast, "chgList"); + { + foreach (string roid in MyChangedFigureROIDs) + { + if (!chgList.Contains(roid)) chgList.Add(roid); + } + } + string RoidList = GetRoidList(newROFst.RODbID, chgList); - //dtLast = ShowDuration(dtLast, "RoidList"); + if (myProgressBarRefresh != null) myProgressBarRefresh(0, chgList.Count, "Getting List of ROs Used"); List activeRoids = BuildActiveROIDsForRoUsages12(RoidList, versionList); - //dtLast = ShowDuration(dtLast, "activeRoids"); + if (myProgressBarRefresh != null) myProgressBarRefresh(0, chgList.Count, "Updating RO Values"); int iCount = 0; + if (activeRoids.Count > 0) { foreach (string chg in chgList) @@ -607,11 +663,12 @@ namespace VEPROMS.CSLA.Library if (myProgressBarRefresh != null) myProgressBarRefresh(++iCount, chgList.Count, "Updating RO Values"); if (activeRoids.Contains(chg.Substring(0, 12))) { - ROFSTLookup.rochild roch = newLU.GetRoChild(chg); - string desc = string.Format("Change in RO Values: Old value = {0}, New value = {1}", origLU.GetRoValue(chg), roch.value); - // roid's are stored in database as 16 characters long in the rousages table. They may be stored - // as 12 characters in the ro.fst. + ROFSTLookup.rochild roch = newLookup.GetRoChild(chg); + string desc = string.Format("Change in RO Values: Old value = {0}, New value = {1}", origLookup.GetRoValue(chg), roch.value); + + // roid's are stored in database as 16 characters long in the RoUsages table. They may be stored as 12 characters in the ro.fst. string padroid = chg.Length <= 12 ? chg + "0000" : chg; + using (RoUsageInfoList affected = RoUsageInfoList.GetAffected(origROFstInfo.MyRODb.RODbID, padroid, desc, "Changed", versionList)) { foreach (RoUsageInfo roUsg in affected) @@ -620,16 +677,20 @@ namespace VEPROMS.CSLA.Library { foreach (ItemInfo ii in roUsg.MyContent.ContentItems) { - string val = newLU.GetTranslatedRoValue(padroid, ii.ActiveFormat.PlantFormat.FormatData.SectData.ConvertCaretToDelta, ii.ActiveFormat.PlantFormat.FormatData.SectData.UseTildaPoundCharsForSuperSubScriptInROValues); + string val = newLookup.GetTranslatedRoValue(padroid, ii.ActiveFormat.PlantFormat.FormatData.SectData.ConvertCaretToDelta, ii.ActiveFormat.PlantFormat.FormatData.SectData.UseTildaPoundCharsForSuperSubScriptInROValues); content.FixContentText(roUsg, val, roch.type, origROFstInfo, true); + if (content.IsDirty) { // Update UserID and DTS when RO Value is updated. content.UserID = Volian.Base.Library.VlnSettings.UserID; content.DTS = DateTime.Now; content.Save(); + if (content.MyGrid != null) + { GridInfo.Refresh(content.MyGrid); + } } } } @@ -638,23 +699,25 @@ namespace VEPROMS.CSLA.Library } } } - //dtLast = ShowDuration(dtLast, "chg loop"); + if (myProgressBarRefresh != null) myProgressBarRefresh(0, chgList.Count, "Getting List of ROs Used"); List activeDRoids = BuildActiveROIDsForDRoUsages12(RoidList, versionList); - //dtLast = ShowDuration(dtLast, "activeRoids Doc"); iCount = 0; + if (activeDRoids.Count > 0) { foreach (string chg in chgList) { string padroid = chg.Length <= 12 ? chg + "0000" : chg; if (myProgressBarRefresh != null) myProgressBarRefresh(++iCount, chgList.Count, "Updating RO Values"); + if (activeDRoids.Contains(chg.Substring(0, 12))) { - ROFSTLookup.rochild roch = newLU.GetRoChild(chg); - string desc = string.Format("Change in RO Values: Old value = {0}, New value = {1}", origLU.GetRoValue(chg), roch.value); - // roid's are stored in database as 16 characters long in the rousages table. They may be stored - // as 12 characters in the ro.fst. + ROFSTLookup.rochild roch = newLookup.GetRoChild(chg); + + string desc = string.Format("Change in RO Values: Old value = {0}, New value = {1}", origLookup.GetRoValue(chg), roch.value); + + // roid's are stored in database as 16 characters long in the rousages table. They may be stored as 12 characters in the ro.fst. using (DROUsageInfoList affected = DROUsageInfoList.GetAffected(origROFstInfo.MyRODb.RODbID, padroid, desc, "Changed", versionList)) { foreach (DROUsageInfo droUsg in affected) @@ -665,17 +728,20 @@ namespace VEPROMS.CSLA.Library } } } + iCount = 0; string RoidDelList = GetRoidList(newROFst.RODbID, delList); if (myProgressBarRefresh != null) myProgressBarRefresh(0, chgList.Count, "Getting List of ROs Used"); activeRoids = BuildActiveROIDsForRoUsages12(RoidDelList, versionList); + if (activeRoids.Count > 0) { foreach (string del in delList) { string padroiddel = del.Length <= 12 ? del + "0000" : del; if (myProgressBarRefresh != null) myProgressBarRefresh(++iCount, chgList.Count, "Removing Old RO Values"); - string desc = string.Format("Deleted RO: Value = {0}", origLU.GetRoValue(del)); + string desc = string.Format("Deleted RO: Value = {0}", origLookup.GetRoValue(del)); + if (activeRoids.Contains(del.Substring(0, 12).ToUpper())) { using (RoUsageInfoList affected = RoUsageInfoList.GetAffected(origROFstInfo.MyRODb.RODbID, padroiddel, desc, "Deleted", versionList)) @@ -698,15 +764,18 @@ namespace VEPROMS.CSLA.Library } } } + if (myProgressBarRefresh != null) myProgressBarRefresh(0, chgList.Count, "Getting List of ROs Used"); activeDRoids = BuildActiveROIDsForDRoUsages12(RoidDelList, versionList); iCount = 0; + if (activeDRoids.Count > 0) { foreach (string del in delList) { string padroiddel = del.Length <= 12 ? del + "0000" : del; - string desc = string.Format("Deleted RO: Value = {0}", origLU.GetRoValue(del)); + string desc = string.Format("Deleted RO: Value = {0}", origLookup.GetRoValue(del)); + if (activeDRoids.Contains(del.Substring(0, 12).ToUpper())) { using (DROUsageInfoList Daffected = DROUsageInfoList.GetAffected(origROFstInfo.MyRODb.RODbID, padroiddel, desc, "Deleted", versionList)) @@ -720,6 +789,7 @@ namespace VEPROMS.CSLA.Library } } } + if (myProgressBarRefresh != null) myProgressBarRefresh(100,100, "RO Values Updated"); } @@ -729,53 +799,11 @@ namespace VEPROMS.CSLA.Library Console.WriteLine("{0,10:#####0.00},'{1}'", TimeSpan.FromTicks(dtNext.Ticks - dtLast.Ticks).TotalSeconds, message); return dtNext; } - private static List BuildActiveROIDsForRoUsages(string RoidList) - { - List activeRoids = new List(); - using (RoUsageInfoList activeList = RoUsageInfoList.GetROUSagesByROIDs(RoidList)) - { - foreach (RoUsageInfo roui in activeList) - { - string roid = roui.ROID.ToUpper(); - if (roid.EndsWith("0000")) roid = roid.Substring(0, 12); - if (!activeRoids.Contains(roid)) - activeRoids.Add(roid); - } - } - return activeRoids; - } - private static List BuildActiveROIDsForRoUsages(string RoidList,string versions) - { - List activeRoids = new List(); - using (RoUsageInfoList activeList = RoUsageInfoList.GetROUSagesByROIDsAndVersions(RoidList,versions)) - { - foreach (RoUsageInfo roui in activeList) - { - string roid = roui.ROID.ToUpper(); - if (roid.EndsWith("0000")) roid = roid.Substring(0, 12); - if (!activeRoids.Contains(roid)) - activeRoids.Add(roid); - } - } - return activeRoids; - } - private static List BuildActiveROIDsForRoUsages12(string RoidList) - { - List activeRoids = new List(); - using (RoUsageInfoList activeList = RoUsageInfoList.GetROUSagesByROIDs(RoidList)) - { - foreach (RoUsageInfo roui in activeList) - { - string roid = roui.ROID.ToUpper().Substring(0, 12); - if (!activeRoids.Contains(roid)) - activeRoids.Add(roid); - } - } - return activeRoids; - } + private static List BuildActiveROIDsForRoUsages12(string RoidList, string versions) { List activeRoids = new List(); + using (RoUsageInfoList activeList = RoUsageInfoList.GetROUSagesByROIDsAndVersions(RoidList, versions)) { foreach (RoUsageInfo roui in activeList) @@ -785,55 +813,14 @@ namespace VEPROMS.CSLA.Library activeRoids.Add(roid); } } + return activeRoids; } - private static List BuildActiveROIDsForDRoUsages(string RoidList) - { - List activeRoids = new List(); - using (DROUsageInfoList activeList = DROUsageInfoList.GetDROUsagesByROIDs(RoidList)) - { - foreach (DROUsageInfo roui in activeList) - { - string roid = roui.ROID; - if (roid.EndsWith("0000")) roid = roid.Substring(0, 12); - if (!activeRoids.Contains(roid)) - activeRoids.Add(roid); - } - } - return activeRoids; - } - private static List BuildActiveROIDsForDRoUsages(string RoidList,string versions) - { - List activeRoids = new List(); - using (DROUsageInfoList activeList = DROUsageInfoList.GetDROUsagesByROIDsAndVersions(RoidList,versions)) - { - foreach (DROUsageInfo roui in activeList) - { - string roid = roui.ROID; - if (roid.EndsWith("0000")) roid = roid.Substring(0, 12); - if (!activeRoids.Contains(roid)) - activeRoids.Add(roid); - } - } - return activeRoids; - } - private static List BuildActiveROIDsForDRoUsages12(string RoidList) - { - List activeRoids = new List(); - using (DROUsageInfoList activeList = DROUsageInfoList.GetDROUsagesByROIDs(RoidList)) - { - foreach (DROUsageInfo roui in activeList) - { - string roid = roui.ROID.Substring(0, 12); - if (!activeRoids.Contains(roid)) - activeRoids.Add(roid); - } - } - return activeRoids; - } + private static List BuildActiveROIDsForDRoUsages12(string RoidList, string versions) { List activeRoids = new List(); + using (DROUsageInfoList activeList = DROUsageInfoList.GetDROUsagesByROIDsAndVersions(RoidList, versions)) { foreach (DROUsageInfo roui in activeList) @@ -843,72 +830,46 @@ namespace VEPROMS.CSLA.Library activeRoids.Add(roid); } } + return activeRoids; } + private static string GetRoidList(int dbid, List chgList) { StringBuilder sb = new StringBuilder(string.Format("{0}", dbid)); string sep=":"; + foreach (string roid in chgList) { sb.Append(sep + roid); sep = ","; } + return sb.ToString(); } - private static string NewROName(string roName) - { - string retval = roName; - int iSuffix = -1; - RODbInfoList rodblist = RODbInfoList.Get(); - - foreach (RODbInfo rdi in rodblist) - { - if (rdi.ROName.StartsWith(roName)) - { - if (rdi.ROName == roName) - iSuffix = 0; - else if (Regex.IsMatch(rdi.ROName, roName + "[_][0-9]+")) - { - int ii = int.Parse(rdi.ROName.Substring(1 + roName.Length)); - if (ii > iSuffix) iSuffix = ii; - } - } - } - if (iSuffix >= 0) - retval = string.Format("{0}_{1}", roName, iSuffix + 1); - return retval; - } + // B2022-026 RO Memory Reduction code - all rochild types passed in are of type image (graphics) private void MigrateRoFstGraphics(RODbInfo rdi, ROFSTLookup.rochild[] rochild, RODb rodb, ROFst rofst, Dictionary myExistingROImages, List myUnChangedROImages, List myAddedROImages, List MyChangedFigureROIDs, ROFstInfoProgressBarRefresh myProgressBarRefresh, int cnt, ref int curCnt) { - for (int i = 0; i < rochild.Length; i++) + if (rochild != null) { - if (rochild[i].type == 8) + for (int i = 0; i < rochild.Length; i++) { this.AddGraphic(rdi, rochild[i], rodb, rofst, myExistingROImages, myUnChangedROImages, myAddedROImages, MyChangedFigureROIDs, myProgressBarRefresh, cnt, curCnt); curCnt++; } - if (rochild[i].children != null) this.MigrateRoFstGraphics(rdi, rochild[i].children, rodb, rofst, myExistingROImages, myUnChangedROImages, myAddedROImages, MyChangedFigureROIDs, myProgressBarRefresh, cnt, ref curCnt); } } - private int CountRoFstGraphics(ROFSTLookup.rochild[] rochild) - { - int cnt = 0; - for (int i = 0; i < rochild.Length; i++) - { - if (rochild[i].type == 8) cnt++; - if (rochild[i].children != null) cnt += this.CountRoFstGraphics(rochild[i].children); - } - return cnt; - } + private void AddGraphic(RODbInfo rdi, ROFSTLookup.rochild myRO, RODb rodb, ROFst rofst, Dictionary myExistingROImages, List myUnChangedROImages, List myAddedROImages, List MyChangedFigureROIDs, ROFstInfoProgressBarRefresh myProgressBarRefresh, int cnt, int curCnt) { + if (string.IsNullOrEmpty(myRO.value)) return; + string p = myRO.value; - if (p == null) return; string imgname = p.Substring(0, p.IndexOf('\n')); int thedot = imgname.LastIndexOf('.'); string fname = imgname; + if (thedot == -1 || (thedot != (imgname.Length - 4))) { RODbConfig roDbCfg = new RODbConfig(rdi.Config); @@ -918,11 +879,14 @@ namespace VEPROMS.CSLA.Library string imgfile = rdi.FolderPath + @"\" + fname; ROImage roImg = null; + if (File.Exists(imgfile)) { FileInfo fi = new FileInfo(imgfile); + // if the roimage record exists, don't create a new one... string key = ROImageKey(imgname, fi.LastWriteTimeUtc); + if (myExistingROImages.ContainsKey(key)) { int imageID = myExistingROImages[key]; @@ -934,35 +898,43 @@ namespace VEPROMS.CSLA.Library if (!myAddedROImages.Contains(key)) { myProgressBarRefresh(curCnt, cnt, "Loading " + imgname); // show progress of loading images + FileStream fsIn = new FileStream(imgfile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); BinaryReader r = new BinaryReader(fsIn); byte[] ab = r.ReadBytes((int)fsIn.Length); r.Close(); fsIn.Close(); + byte[] cmp = ROImageInfo.Compress(ab); int existingImageID = FindExisting(myExistingROImages, imgname, imgfile, cmp, ab); + if (existingImageID != 0) { if (!myUnChangedROImages.Contains(existingImageID)) + { myUnChangedROImages.Add(existingImageID); + } + return; } + ROImageConfig rc = new ROImageConfig(); rc.Image_Size = ab.Length.ToString(); + using (roImg = ROImage.MakeROImage(rodb, imgname, ROImageInfo.Compress(ab), rc.ToString(), fi.LastWriteTimeUtc, "Migration")) { using (Figure figure = Figure.GetByROFstID_ImageID(this.ROFstID, roImg.ImageID)) { - if (figure != null) return; + if (figure != null) return; Figure.MakeFigure(rofst, roImg, null).Dispose(); - myAddedROImages.Add(key); - MyChangedFigureROIDs.Add(myRO.roid); // Save the roid so that the related documents will be refeshed. (PDF will be deleted) + myAddedROImages.Add(key); + MyChangedFigureROIDs.Add(myRO.roid); // Save the roid so that the related documents will be refeshed. (PDF will be deleted) + } + } } } } } - } - } private int FindExisting(Dictionary myExistingROImages, string imgname, string imgfile, byte[] cmpFileContents, byte[] fileContents) { @@ -978,6 +950,7 @@ namespace VEPROMS.CSLA.Library // if found, compare the date/time stamp string part1 = Regex.Replace(key, ":.*$", ""); string part2 = Regex.Replace(key, "^.*?:", ""); + if (part1.ToUpper() == imgname.ToUpper()) { // if date/time stamps matches date, minutes & seconds, compare contents @@ -985,10 +958,12 @@ namespace VEPROMS.CSLA.Library cmp1 = Regex.Replace(cmp1, " [AP]", " x"); string cmp2 = Regex.Replace(part2, " [0-9]*:", " x:"); cmp2 = Regex.Replace(cmp2, " [AP]", " x"); - if (cmp1==cmp2) + + if (cmp1 == cmp2) { // compare contents int imgId = myExistingROImages[key]; + using (ROImageInfo roii = ROImageInfo.Get(imgId)) { ROImageConfig roicfg = new ROImageConfig(roii); @@ -1003,74 +978,32 @@ namespace VEPROMS.CSLA.Library } } } + return 0; } + private static void ROWarning(ItemInfo myItemInfo, string format, params object[] args) + { + int key = 0; + if (myItemInfo != null && myItemInfo.MyDocVersion != null) key = myItemInfo.MyDocVersion.VersionID; - private ROImageInfo GetMyImage(Dictionary myImages, string imgname, DateTime dts) - { - string key = string.Format("{0}:{1}", imgname, dts); - if(myImages.ContainsKey(key)) - return myImages[key]; - return null; - } - #endregion - #endregion - public bool IsSetpointDB(int id, DocVersionInfo dvi) - { - ROFSTLookup.rodbi[] dbs = GetROFSTLookup(dvi).GetRODatabaseList(); - foreach (ROFSTLookup.rodbi rodbi in dbs) + if (!DocVersionsNeedingROUpdate.Contains(key)) { - if (id == rodbi.dbiID) - return (rodbi.dbiAP.StartsWith("SP")); - } - return false; - } - public ROFst GetJustROFst() - { - return ROFst.GetJustROFst(ROFstID); - } - public event ROFstInfoROTableUpdateEvent ROTableUpdate; - public List OnROTableUpdate(object sender, ROFstInfoROTableUpdateEventArgs args) - { - if (ROTableUpdate != null) return ROTableUpdate(sender, args); - return null; - } - public static ROFstInfo GetJustROFst(int rOFstID) - { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a ROFst"); - try - { - ROFstInfo tmp = GetCachedByPrimaryKey(rOFstID); - if (tmp == null) + if (myItemInfo == null) { - tmp = DataPortal.Fetch(new PKCriteriaJustROFst(rOFstID)); - AddToCache(tmp); + string prefix = string.Format("\r\nNeed to Update RO Values\r\n"); + _MyLog.WarnFormat(prefix + format, args); + DocVersionsNeedingROUpdate.Add(key); } - if (tmp.ErrorMessage == "No Record Found") + else { - tmp.Dispose(); // Clean-up ROFstInfo - tmp = null; + string prefix = string.Format("\r\nNeed to Update RO Values for {0}\r\nProcedure {1}\r\n", myItemInfo.SearchDVPath, myItemInfo.MyProcedure.DisplayNumber); + _MyLog.WarnFormat(prefix + format, args); + DocVersionsNeedingROUpdate.Add(key); } - return tmp; - } - catch (Exception ex) - { - throw new DbCslaException("Error on ROFstInfo.Get", ex); - } - } - [Serializable()] - protected class PKCriteriaJustROFst - { - private int _ROFstID; - public int ROFstID - { get { return _ROFstID; } } - public PKCriteriaJustROFst(int rOFstID) - { - _ROFstID = rOFstID; } } + private void DataPortal_Fetch(PKCriteriaJustROFst criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ROFstInfo.DataPortal_Fetch", GetHashCode()); @@ -1107,48 +1040,10 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ROFstInfo.DataPortal_Fetch", ex); } } - public ROImageInfo GetROImageByFilename(string filename, ItemInfo myItemInfo) - { - ROImageInfoList images = ROImageInfoList.GetByRODbIDFilename(RODbID, filename); - if (images == null || images.Count == 0) - { - ROWarning(myItemInfo,"Referenced Object Image {0} Missing", filename); - return null; - } - ROImageInfo retval = null; - foreach (ROImageInfo image in images) - { - if (image.DTS > DTS && retval != null) break; - retval = image; - } - if(retval.DTS > DTS) - ROWarning(myItemInfo, "Referenced Object Image {0} newer {1} than RO.FST {2}", filename, retval.DTS.ToShortDateString(), DTS.ToShortDateString()); - else - ROWarning(myItemInfo, "Referenced Object Image {0} older {1} then RO.FST {2}", filename, retval.DTS.ToShortDateString(), DTS.ToShortDateString()); - return retval; - } - private static List DocVersionsNeedingROUpdate = new List(); - private static void ROWarning(ItemInfo myItemInfo, string format, params object[] args) - { - int key = 0; - if(myItemInfo != null && myItemInfo.MyDocVersion != null) key = myItemInfo.MyDocVersion.VersionID; - if (!DocVersionsNeedingROUpdate.Contains(key)) - { - if (myItemInfo == null) - { - string prefix = string.Format("\r\nNeed to Update RO Values\r\n"); - _MyLog.WarnFormat(prefix + format, args); - DocVersionsNeedingROUpdate.Add(key); - } - else - { - string prefix = string.Format("\r\nNeed to Update RO Values for {0}\r\nProcedure {1}\r\n", myItemInfo.SearchDVPath, myItemInfo.MyProcedure.DisplayNumber); - _MyLog.WarnFormat(prefix + format, args); - DocVersionsNeedingROUpdate.Add(key); - } - } - } + + #endregion } + public class ROFstInfoROTableUpdateEventArgs { private string _ROText; @@ -1169,6 +1064,7 @@ namespace VEPROMS.CSLA.Library _OldGridXml = oldgridxml; } } + public partial class ROFstInfoList { [Serializable()] @@ -1192,6 +1088,7 @@ namespace VEPROMS.CSLA.Library set { _Len = value; } } } + public static ROFstInfoList GetBySize(int roDbID, int len) { try @@ -1206,11 +1103,13 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on RoFstInfoList.GetBySize", ex); } } + public static bool ROFstDiffBySize(string rofstPath, int roDbID, int len) { try { bool isDifferent = false; + using (ROFstInfoList tmp = GetBySize(roDbID, len)) { if (tmp.Count > 0) @@ -1223,17 +1122,36 @@ namespace VEPROMS.CSLA.Library byte[] ab = r.ReadBytes((int)fsIn.Length); r.Close(); fsIn.Close(); + + Dictionary rofstBytes = new Dictionary(); + foreach (ROFstInfo irofst in tmp) { + if (!rofstBytes.ContainsKey(irofst.ROFstID)) + { + rofstBytes.Add(irofst.ROFstID, ROFSTLookup.GetRofstLookupBytes(irofst.ROFstID)); + } + + var bytes = rofstBytes[irofst.ROFstID]; + irofst.Dispose(); + // compare contents by comparing each byte. for (int i = 20; i < len; i++) // this skips past RO.FST header which has the FST creation date/time - if (ab[i] != irofst.ROLookup[i]) isDifferent = true; - irofst.Dispose(); - if (isDifferent) break; + { + if (ab[i] != bytes[i]) + { + isDifferent = true; + break; + } + } + + if (isDifferent) + break; } } } - GC.Collect(); + + //GC.Collect(); return isDifferent; } catch (Exception ex) @@ -1241,6 +1159,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on RoFstInfoList.ROFstDiffBySize", ex); } } + private void DataPortal_Fetch(RoFstSizeCriteria criteria) { this.RaiseListChangedEvents = false; @@ -1274,5 +1193,6 @@ namespace VEPROMS.CSLA.Library } this.RaiseListChangedEvents = true; } + } } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/DocVersionAssociation.cs b/PROMS/VEPROMS.CSLA.Library/Generated/DocVersionAssociation.cs index 327ca885..2257d29b 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/DocVersionAssociation.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/DocVersionAssociation.cs @@ -435,7 +435,8 @@ namespace VEPROMS.CSLA.Library _UserID = dr.GetString("UserID"); dr.GetBytes("LastChanged", 0, _LastChanged, 0, 8); _ROFst_RODbID = dr.GetInt32("ROFst_RODbID"); - _ROFst_ROLookup = (byte[])dr.GetValue("ROFst_ROLookup"); + //_ROFst_ROLookup = (byte[])dr.GetValue("ROFst_ROLookup"); + _ROFst_ROLookup = null; // B2022-026 RO Memory reduction - use ROlookup of null to know if we loaded the RO.FST file _ROFst_Config = dr.GetString("ROFst_Config"); _ROFst_DTS = dr.GetDateTime("ROFst_DTS"); _ROFst_UserID = dr.GetString("ROFst_UserID"); diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ROFst.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ROFst.cs index c76d2b72..6387278f 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ROFst.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ROFst.cs @@ -81,12 +81,20 @@ namespace VEPROMS.CSLA.Library } ClearRefreshList(); } + #endregion + #region Collection + private static List _CacheList = new List(); protected static void AddToCache(ROFst rOFst) { - if (!_CacheList.Contains(rOFst)) _CacheList.Add(rOFst); // In AddToCache + if (!_CacheList.Contains(rOFst)) + { + rOFst.ROLookup = null; // B2022-026 RO Memory reduction + _CacheList.Add(rOFst); // In AddToCache + } + } protected static void RemoveFromCache(ROFst rOFst) { @@ -105,6 +113,7 @@ namespace VEPROMS.CSLA.Library _CacheByPrimaryKey[pKey] = new List(); // Add new list for PrimaryKey _CacheByRODbID_DTS[tmp.RODbID.ToString() + "_" + tmp.DTS.ToString()] = new List(); // Add new list for RODbID_DTS } + tmp.ROLookup = null; // B2022-026 RO Memory reduction _CacheByPrimaryKey[pKey].Add(tmp); // Add to Primary Key list _CacheByRODbID_DTS[tmp.RODbID.ToString() + "_" + tmp.DTS.ToString()].Add(tmp); // Unique Index _CacheList.RemoveAt(0); // Remove the first ROFst @@ -124,8 +133,11 @@ namespace VEPROMS.CSLA.Library if (_CacheByRODbID_DTS.ContainsKey(key)) return _CacheByRODbID_DTS[key][0]; return null; } + #endregion + #region Business Methods + private string _ErrorMessage = string.Empty; public string ErrorMessage { @@ -180,14 +192,21 @@ namespace VEPROMS.CSLA.Library } } } + private byte[] _ROLookup; + public byte[] ROLookup { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty("ROLookup", true); - return _ROLookup; + return null; // B2022-026 RO Memory reduction + //if (_ROLookup == null) + //{ + // _ROLookup = ROFSTLookup.GetRofstLookupBytes(_ROFstID); + //} + //return _ROLookup; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set @@ -200,6 +219,7 @@ namespace VEPROMS.CSLA.Library } } } + private string _Config = string.Empty; public string Config { @@ -557,6 +577,7 @@ namespace VEPROMS.CSLA.Library _Disposed = true; RemoveFromDictionaries(); } + private void RemoveFromDictionaries() { RemoveFromCache(this); @@ -580,6 +601,7 @@ namespace VEPROMS.CSLA.Library _CacheByRODbID_DTS.Remove(myKey); // remove the list } } + public static ROFst New() { if (!CanAddObject()) @@ -593,6 +615,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on ROFst.New", ex); } } + public static ROFst New(RODb myRODb, byte[] rOLookup) { ROFst tmp = ROFst.New(); @@ -600,6 +623,7 @@ namespace VEPROMS.CSLA.Library tmp.ROLookup = rOLookup; return tmp; } + public static ROFst New(RODb myRODb, byte[] rOLookup, string config, DateTime dts, string userID) { ROFst tmp = ROFst.New(); @@ -610,22 +634,7 @@ namespace VEPROMS.CSLA.Library tmp.UserID = userID; return tmp; } - public static ROFst MakeROFst(RODb myRODb, byte[] rOLookup, string config, DateTime dts, string userID) - { - ROFst tmp = ROFst.New(myRODb, rOLookup, config, dts, userID); - if (tmp.IsSavable) - tmp = tmp.Save(); - else - { - Csla.Validation.BrokenRulesCollection brc = tmp.ValidationRules.GetBrokenRules(); - tmp._ErrorMessage = "Failed Validation:"; - foreach (Csla.Validation.BrokenRule br in brc) - { - tmp._ErrorMessage += "\r\n\tFailure: " + br.RuleName; - } - } - return tmp; - } + public static ROFst New(RODb myRODb, byte[] rOLookup, string config) { ROFst tmp = ROFst.New(); @@ -634,11 +643,23 @@ namespace VEPROMS.CSLA.Library tmp.Config = config; return tmp; } - public static ROFst MakeROFst(RODb myRODb, byte[] rOLookup, string config) + + public static ROFst MakeROFst(RODb myRODb, byte[] rOLookup, string config, DateTime dts, string userID) { - ROFst tmp = ROFst.New(myRODb, rOLookup, config); + ROFst tmp = ROFst.New(myRODb, rOLookup, config, dts, userID); + if (tmp.IsSavable) + { tmp = tmp.Save(); + + // B2022-026 RO Memory reduction + if (tmp.ROLookup != null && tmp.ROFstID > 0) + { + //Force Load the new Lookup Data + var RofstLookup = new ROFSTLookup(tmp.ROFstID); + tmp.ROLookup = null; + } + } else { Csla.Validation.BrokenRulesCollection brc = tmp.ValidationRules.GetBrokenRules(); @@ -648,8 +669,36 @@ namespace VEPROMS.CSLA.Library tmp._ErrorMessage += "\r\n\tFailure: " + br.RuleName; } } + return tmp; } + + public static ROFst MakeROFst(RODb myRODb, byte[] rOLookup, string config) + { + ROFst tmp = ROFst.New(myRODb, rOLookup, config); + + if (tmp.IsSavable) + { + tmp = tmp.Save(); + + // B2022-026 RO Memory reduction + //Force Load the new Lookup Data + var RofstLookup = new ROFSTLookup(tmp.ROFstID); + tmp.ROLookup = null; + } + else + { + Csla.Validation.BrokenRulesCollection brc = tmp.ValidationRules.GetBrokenRules(); + tmp._ErrorMessage = "Failed Validation:"; + foreach (Csla.Validation.BrokenRule br in brc) + { + tmp._ErrorMessage += "\r\n\tFailure: " + br.RuleName; + } + } + + return tmp; + } + public static ROFst Get(int rOFstID) { if (!CanGetObject()) @@ -662,11 +711,13 @@ namespace VEPROMS.CSLA.Library tmp = DataPortal.Fetch(new PKCriteria(rOFstID)); AddToCache(tmp); } + if (tmp.ErrorMessage == "No Record Found") { tmp.Dispose(); // Clean-up ROFst tmp = null; } + return tmp; } catch (Exception ex) @@ -674,6 +725,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on ROFst.Get", ex); } } + public static ROFst GetByRODbID_DTS(int rODbID, DateTime dts) { if (!CanGetObject()) @@ -735,6 +787,7 @@ namespace VEPROMS.CSLA.Library RemoveFromDictionaries(); // if save is successful remove the previous Folder from the cache AddToCache(rOFst);//Refresh the item in AllList ProcessRefreshList(); + rOFst.ROLookup = null; // B2022-026 RO Memory reduction return rOFst; } catch (Exception ex) @@ -781,6 +834,7 @@ namespace VEPROMS.CSLA.Library // CSLATODO: Add any defaults that are necessary ValidationRules.CheckRules(); } + private void ReadData(SafeDataReader dr) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ROFst.ReadData", GetHashCode()); @@ -788,7 +842,8 @@ namespace VEPROMS.CSLA.Library { _ROFstID = dr.GetInt32("ROFstID"); _RODbID = dr.GetInt32("RODbID"); - _ROLookup = (byte[])dr.GetValue("ROLookup"); + //_ROLookup = (byte[])dr.GetValue("ROLookup"); + _ROLookup = null; // B2022-026 RO Memory reduction _Config = dr.GetString("Config"); _DTS = dr.GetDateTime("DTS"); _UserID = dr.GetString("UserID"); @@ -804,6 +859,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ROFst.ReadData", ex); } } + private void DataPortal_Fetch(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ROFst.DataPortal_Fetch", GetHashCode()); @@ -846,6 +902,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ROFst.DataPortal_Fetch", ex); } } + private void DataPortal_Fetch(RODbID_DTSCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ROFst.DataPortal_Fetch", GetHashCode()); @@ -883,6 +940,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ROFst.DataPortal_Fetch", ex); } } + [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Insert() { @@ -908,6 +966,7 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ROFst.DataPortal_Insert", GetHashCode()); } } + [Transactional(TransactionalTypes.TransactionScope)] internal void SQLInsert() { @@ -921,12 +980,14 @@ namespace VEPROMS.CSLA.Library cm.CommandType = CommandType.StoredProcedure; cm.CommandTimeout = Database.SQLTimeout; cm.CommandText = "addROFst"; + // Input All Fields - Except Calculated Columns cm.Parameters.AddWithValue("@RODbID", RODbID); cm.Parameters.AddWithValue("@ROLookup", _ROLookup); cm.Parameters.AddWithValue("@Config", _Config); if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); cm.Parameters.AddWithValue("@UserID", _UserID); + // Output Calculated Columns SqlParameter param_ROFstID = new SqlParameter("@newROFstID", SqlDbType.Int); param_ROFstID.Direction = ParameterDirection.Output; @@ -934,11 +995,15 @@ namespace VEPROMS.CSLA.Library SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); param_LastChanged.Direction = ParameterDirection.Output; cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure _ROFstID = (int)cm.Parameters["@newROFstID"].Value; _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + + // Clear Out Any Rofst Binary (Bytes[]) - B2022-026 RO Memory reduction + _ROLookup = null; } MarkOld(); // update child objects @@ -953,6 +1018,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ROFst.SQLInsert", ex); } } + [Transactional(TransactionalTypes.TransactionScope)] public static byte[] Add(SqlConnection cn, ref int rOFstID, RODb myRODb, byte[] rOLookup, string config, DateTime dts, string userID) { @@ -964,12 +1030,14 @@ namespace VEPROMS.CSLA.Library cm.CommandType = CommandType.StoredProcedure; cm.CommandTimeout = Database.SQLTimeout; cm.CommandText = "addROFst"; + // Input All Fields - Except Calculated Columns cm.Parameters.AddWithValue("@RODbID", myRODb.RODbID); cm.Parameters.AddWithValue("@ROLookup", rOLookup); cm.Parameters.AddWithValue("@Config", config); if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UserID", userID); + // Output Calculated Columns SqlParameter param_ROFstID = new SqlParameter("@newROFstID", SqlDbType.Int); param_ROFstID.Direction = ParameterDirection.Output; @@ -977,8 +1045,12 @@ namespace VEPROMS.CSLA.Library SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); param_LastChanged.Direction = ParameterDirection.Output; cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + + // Clear Out Any Rofst Binary (Bytes[]) - B2022-026 RO Memory reduction + rOLookup = null; + // Save all values being returned from the Procedure rOFstID = (int)cm.Parameters["@newROFstID"].Value; return (byte[])cm.Parameters["@newLastChanged"].Value; @@ -990,6 +1062,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ROFst.Add", ex); } } + [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Update() { @@ -1013,6 +1086,7 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } + [Transactional(TransactionalTypes.TransactionScope)] internal void SQLUpdate() { @@ -1029,20 +1103,23 @@ namespace VEPROMS.CSLA.Library cm.CommandType = CommandType.StoredProcedure; cm.CommandTimeout = Database.SQLTimeout; cm.CommandText = "updateROFst"; + // All Fields including Calculated Fields cm.Parameters.AddWithValue("@ROFstID", _ROFstID); cm.Parameters.AddWithValue("@RODbID", RODbID); - cm.Parameters.AddWithValue("@ROLookup", _ROLookup); + cm.Parameters.AddWithValue("@ROLookup", ROFSTLookup.GetRofstLookupBytes(_ROFstID)); // B2022-026 RO Memory reduction - new calls cm.Parameters.AddWithValue("@Config", _Config); if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); cm.Parameters.AddWithValue("@UserID", _UserID); cm.Parameters.AddWithValue("@LastChanged", _LastChanged); + // Output Calculated Columns SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); param_LastChanged.Direction = ParameterDirection.Output; cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; } @@ -1059,6 +1136,7 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } + internal void Update() { if (!this.IsDirty) return; @@ -1074,17 +1152,23 @@ namespace VEPROMS.CSLA.Library if (_ROFstAssociations != null) _ROFstAssociations.Update(this); if (_ROFstFigures != null) _ROFstFigures.Update(this); } + [Transactional(TransactionalTypes.TransactionScope)] public static byte[] Update(SqlConnection cn, ref int rOFstID, int rODbID, byte[] rOLookup, string config, DateTime dts, string userID, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ROFst.Update", 0); try { + // B2022-026 RO Memory reduction - check if we need to get the rOLookup + if (rOLookup == null) + rOLookup = ROFSTLookup.GetRofstLookupBytes(rOFstID); + using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandTimeout = Database.SQLTimeout; cm.CommandText = "updateROFst"; + // Input All Fields - Except Calculated Columns cm.Parameters.AddWithValue("@ROFstID", rOFstID); cm.Parameters.AddWithValue("@RODbID", rODbID); @@ -1093,12 +1177,14 @@ namespace VEPROMS.CSLA.Library if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@LastChanged", lastChanged); + // Output Calculated Columns SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); param_LastChanged.Direction = ParameterDirection.Output; cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure return (byte[])cm.Parameters["@newLastChanged"].Value; } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ROFstInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ROFstInfo.cs index 6a937e51..3e63897e 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ROFstInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ROFstInfo.cs @@ -39,7 +39,11 @@ namespace VEPROMS.CSLA.Library private static List _CacheList = new List(); protected static void AddToCache(ROFstInfo rOFstInfo) { - if (!_CacheList.Contains(rOFstInfo)) _CacheList.Add(rOFstInfo); // In AddToCache + if (!_CacheList.Contains(rOFstInfo)) + { + rOFstInfo.ClearROLookupBytes(); // B2022-026 RO Memory reduction + _CacheList.Add(rOFstInfo); // In AddToCache + } } protected static void RemoveFromCache(ROFstInfo rOFstInfo) { @@ -56,6 +60,7 @@ namespace VEPROMS.CSLA.Library { _CacheByPrimaryKey[pKey] = new List(); // Add new list for PrimaryKey } + tmp.ClearROLookupBytes(); // B2022-026 RO Memory reduction _CacheByPrimaryKey[pKey].Add(tmp); // Add to Primary Key list _CacheList.RemoveAt(0); // Remove the first ROFstInfo } @@ -122,6 +127,7 @@ namespace VEPROMS.CSLA.Library return _MyRODb; } } + private byte[] _ROLookup; public byte[] ROLookup { @@ -129,9 +135,17 @@ namespace VEPROMS.CSLA.Library get { CanReadProperty("ROLookup", true); - return _ROLookup; + //if (_ROLookup == null) + //{ + // _ROLookup = ROFSTLookup.GetRofstLookupBytes(_ROFstID); + //} + //return _ROLookup; + + // B2022-026 RO Memory reduction + return null; } } + private string _Config = string.Empty; public string Config { @@ -238,16 +252,7 @@ namespace VEPROMS.CSLA.Library foreach (ROFstInfo tmp in _CacheByPrimaryKey[_ROFstID.ToString()]) tmp._ROFstFigureCount = -1; // This will cause the data to be requeried } - // CSLATODO: Replace base ROFstInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current ROFstInfo - //public override string ToString() - //{ - // return base.ToString(); - //} - // CSLATODO: Check ROFstInfo.GetIdValue to assure that the ID returned is unique + /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// @@ -256,8 +261,11 @@ namespace VEPROMS.CSLA.Library { return MyROFstInfoUnique; // Absolutely Unique ID } + #endregion + #region Factory Methods + private static int _ROFstInfoUnique = 0; private static int ROFstInfoUnique { get { return ++_ROFstInfoUnique; } } @@ -272,6 +280,7 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; + private static int IncrementCountCreated { get { return ++_CountCreated; } } private int _CountWhenCreated = IncrementCountCreated; @@ -309,6 +318,12 @@ namespace VEPROMS.CSLA.Library foreach (ROFstInfo tmpInfo in _CacheByPrimaryKey[key]) tmpInfo.RefreshFields(tmp); } + // B2022-026 RO Memory reduction + public void ClearROLookupBytes() + { + _ROLookup = null; + } + protected virtual void RefreshFields(ROFst tmp) { if (_RODbID != tmp.RODbID) @@ -318,7 +333,8 @@ namespace VEPROMS.CSLA.Library } _MyRODb = null; // Reset list so that the next line gets a new list if (MyRODb != null) MyRODb.RefreshRODbROFsts(); // Update List for new value - _ROLookup = tmp.ROLookup; + //_ROLookup = tmp.ROLookup; + _ROLookup = null; // B2022-026 RO Memory reduction _Config = tmp.Config; _DTS = tmp.DTS; _UserID = tmp.UserID; @@ -335,7 +351,8 @@ namespace VEPROMS.CSLA.Library } protected virtual void RefreshFields(RODbROFst tmp) { - _ROLookup = tmp.ROLookup; + //_ROLookup = tmp.ROLookup; + _ROLookup = null; // B2022-026 RO Memory reduction _Config = tmp.Config; _DTS = tmp.DTS; _UserID = tmp.UserID; @@ -344,8 +361,6 @@ namespace VEPROMS.CSLA.Library } public static ROFstInfo Get(int rOFstID) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a ROFst"); try { ROFstInfo tmp = GetCachedByPrimaryKey(rOFstID); @@ -354,11 +369,18 @@ namespace VEPROMS.CSLA.Library tmp = DataPortal.Fetch(new PKCriteria(rOFstID)); AddToCache(tmp); } + if (tmp.ErrorMessage == "No Record Found") { tmp.Dispose(); // Clean-up ROFstInfo tmp = null; } + + if (tmp != null) + { + tmp.ClearROLookupBytes(); // B2022-026 RO Memory reduction + } + return tmp; } catch (Exception ex) @@ -366,8 +388,11 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on ROFstInfo.Get", ex); } } + #endregion + #region Data Access Portal + internal ROFstInfo(SafeDataReader dr) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ROFstInfo.Constructor", GetHashCode()); @@ -381,6 +406,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ROFstInfo.Constructor", ex); } } + [Serializable()] protected class PKCriteria { @@ -392,6 +418,7 @@ namespace VEPROMS.CSLA.Library _ROFstID = rOFstID; } } + private void ReadData(SafeDataReader dr) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ROFstInfo.ReadData", GetHashCode()); @@ -399,7 +426,8 @@ namespace VEPROMS.CSLA.Library { _ROFstID = dr.GetInt32("ROFstID"); _RODbID = dr.GetInt32("RODbID"); - _ROLookup = (byte[])dr.GetValue("ROLookup"); + //_ROLookup = (byte[])dr.GetValue("ROLookup"); + _ROLookup = null; // B2022-026 RO Memory reduction _Config = dr.GetString("Config"); _DTS = dr.GetDateTime("DTS"); _UserID = dr.GetString("UserID"); @@ -413,6 +441,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ROFstInfo.ReadData", ex); } } + private void DataPortal_Fetch(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ROFstInfo.DataPortal_Fetch", GetHashCode()); @@ -449,7 +478,9 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ROFstInfo.DataPortal_Fetch", ex); } } + #endregion + // Standard Refresh #region extension ROFstInfoExtension _ROFstInfoExtension = new ROFstInfoExtension(); @@ -463,7 +494,9 @@ namespace VEPROMS.CSLA.Library } #endregion } // Class + #region Converter + internal class ROFstInfoConverter : ExpandableObjectConverter { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) @@ -476,5 +509,6 @@ namespace VEPROMS.CSLA.Library return base.ConvertTo(context, culture, value, destType); } } + #endregion } // Namespace diff --git a/PROMS/Volian.Controls.Library/DisplayRO.Designer.cs b/PROMS/Volian.Controls.Library/DisplayRO.Designer.cs index 83251584..2e0f231d 100644 --- a/PROMS/Volian.Controls.Library/DisplayRO.Designer.cs +++ b/PROMS/Volian.Controls.Library/DisplayRO.Designer.cs @@ -28,17 +28,16 @@ namespace Volian.Controls.Library /// private void InitializeComponent() { - System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DisplayRO)); this.tvROFST = new System.Windows.Forms.TreeView(); this.panelValue = new System.Windows.Forms.Panel(); this.lbROId = new DevComponents.DotNetBar.LabelX(); this.lblROID = new DevComponents.DotNetBar.LabelX(); this.pnlROButtons = new System.Windows.Forms.Panel(); + this.btnFindDocRO = new DevComponents.DotNetBar.ButtonX(); this.btnGoToRO = new DevComponents.DotNetBar.ButtonX(); this.btnPreviewRO = new DevComponents.DotNetBar.ButtonX(); this.btnCancelRO = new DevComponents.DotNetBar.ButtonX(); this.btnSaveRO = new DevComponents.DotNetBar.ButtonX(); - this.btnFindDocRO = new DevComponents.DotNetBar.ButtonX(); this.panelRoValue = new System.Windows.Forms.Panel(); this.tbROValue = new DevComponents.DotNetBar.Controls.TextBoxX(); this.lblROValue = new DevComponents.DotNetBar.LabelX(); @@ -53,10 +52,9 @@ namespace Volian.Controls.Library // this.tvROFST.Dock = System.Windows.Forms.DockStyle.Fill; this.tvROFST.HideSelection = false; - this.tvROFST.Location = new System.Drawing.Point(0, 248); - this.tvROFST.Margin = new System.Windows.Forms.Padding(4); + this.tvROFST.Location = new System.Drawing.Point(0, 202); this.tvROFST.Name = "tvROFST"; - this.tvROFST.Size = new System.Drawing.Size(311, 376); + this.tvROFST.Size = new System.Drawing.Size(233, 305); this.tvROFST.TabIndex = 5; this.tvROFST.BeforeExpand += new System.Windows.Forms.TreeViewCancelEventHandler(this.tvROFST_BeforeExpand); this.tvROFST.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.tvROFST_AfterSelect); @@ -70,9 +68,8 @@ namespace Volian.Controls.Library this.panelValue.Controls.Add(this.panelRoValue); this.panelValue.Dock = System.Windows.Forms.DockStyle.Top; this.panelValue.Location = new System.Drawing.Point(0, 0); - this.panelValue.Margin = new System.Windows.Forms.Padding(4); this.panelValue.Name = "panelValue"; - this.panelValue.Size = new System.Drawing.Size(311, 180); + this.panelValue.Size = new System.Drawing.Size(233, 146); this.panelValue.TabIndex = 7; // // lbROId @@ -83,10 +80,10 @@ namespace Volian.Controls.Library this.lbROId.BackgroundStyle.CornerType = DevComponents.DotNetBar.eCornerType.Square; this.lbROId.Dock = System.Windows.Forms.DockStyle.Left; this.lbROId.ForeColor = System.Drawing.SystemColors.Highlight; - this.lbROId.Location = new System.Drawing.Point(61, 30); - this.lbROId.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); + this.lbROId.Location = new System.Drawing.Point(48, 24); + this.lbROId.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); this.lbROId.Name = "lbROId"; - this.lbROId.Size = new System.Drawing.Size(244, 40); + this.lbROId.Size = new System.Drawing.Size(183, 33); this.superTooltip1.SetSuperTooltip(this.lbROId, new DevComponents.DotNetBar.SuperTooltipInfo("RO ID", "", "The RO ID for the selected RO Value will be displayed here. Double-Click to open" + " the RO Editor.", null, null, DevComponents.DotNetBar.eTooltipColor.Gray, true, true, new System.Drawing.Size(150, 80))); this.lbROId.TabIndex = 11; @@ -99,14 +96,13 @@ namespace Volian.Controls.Library // this.lblROID.BackgroundStyle.CornerType = DevComponents.DotNetBar.eCornerType.Square; this.lblROID.Dock = System.Windows.Forms.DockStyle.Left; - this.lblROID.Location = new System.Drawing.Point(0, 30); - this.lblROID.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); + this.lblROID.Location = new System.Drawing.Point(0, 24); + this.lblROID.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); this.lblROID.Name = "lblROID"; - this.lblROID.Size = new System.Drawing.Size(61, 40); + this.lblROID.Size = new System.Drawing.Size(48, 33); this.superTooltip1.SetSuperTooltip(this.lblROID, new DevComponents.DotNetBar.SuperTooltipInfo("RO ID", "", "The RO ID for the selected RO Value will be displayed here.", null, null, DevComponents.DotNetBar.eTooltipColor.Gray, true, true, new System.Drawing.Size(150, 80))); this.lblROID.TabIndex = 10; this.lblROID.Text = "RO ID:"; - this.lblROID.TextAlignment = System.Drawing.StringAlignment.Center; // // pnlROButtons // @@ -116,27 +112,41 @@ namespace Volian.Controls.Library this.pnlROButtons.Controls.Add(this.btnCancelRO); this.pnlROButtons.Controls.Add(this.btnSaveRO); this.pnlROButtons.Dock = System.Windows.Forms.DockStyle.Bottom; - this.pnlROButtons.Location = new System.Drawing.Point(0, 70); - this.pnlROButtons.Margin = new System.Windows.Forms.Padding(4); + this.pnlROButtons.Location = new System.Drawing.Point(0, 57); this.pnlROButtons.Name = "pnlROButtons"; - this.pnlROButtons.Size = new System.Drawing.Size(311, 110); + this.pnlROButtons.Size = new System.Drawing.Size(233, 89); this.pnlROButtons.TabIndex = 9; // + // btnFindDocRO + // + this.btnFindDocRO.AccessibleRole = System.Windows.Forms.AccessibleRole.PushButton; + this.btnFindDocRO.ColorTable = DevComponents.DotNetBar.eButtonColor.OrangeWithBackground; + this.btnFindDocRO.Dock = System.Windows.Forms.DockStyle.Top; + this.btnFindDocRO.Enabled = false; + this.btnFindDocRO.Location = new System.Drawing.Point(0, 73); + this.btnFindDocRO.Name = "btnFindDocRO"; + this.btnFindDocRO.Size = new System.Drawing.Size(233, 18); + this.superTooltip1.SetSuperTooltip(this.btnFindDocRO, new DevComponents.DotNetBar.SuperTooltipInfo("Find Doc RO", "", "Determine if there are any ROs for the selected text in a Word Document. If found" + + ", the list of ROs is displayed.", null, null, DevComponents.DotNetBar.eTooltipColor.Gray)); + this.btnFindDocRO.TabIndex = 9; + this.btnFindDocRO.Text = "Find Doc RO"; + this.btnFindDocRO.Click += new System.EventHandler(this.btnFindDocRO_Click); + // // btnGoToRO // this.btnGoToRO.AccessibleRole = System.Windows.Forms.AccessibleRole.PushButton; this.btnGoToRO.ColorTable = DevComponents.DotNetBar.eButtonColor.OrangeWithBackground; this.btnGoToRO.Dock = System.Windows.Forms.DockStyle.Top; this.btnGoToRO.Enabled = false; - this.btnGoToRO.Location = new System.Drawing.Point(0, 89); + this.btnGoToRO.Location = new System.Drawing.Point(0, 55); + this.btnGoToRO.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); this.btnGoToRO.Name = "btnGoToRO"; - this.btnGoToRO.Size = new System.Drawing.Size(311, 22); + this.btnGoToRO.Size = new System.Drawing.Size(233, 18); this.btnGoToRO.Style = DevComponents.DotNetBar.eDotNetBarStyle.StyleManagerControlled; + this.superTooltip1.SetSuperTooltip(this.btnGoToRO, new DevComponents.DotNetBar.SuperTooltipInfo("Go To", "", "Opens the RO Editor and positions to the selected RO.", null, null, DevComponents.DotNetBar.eTooltipColor.Gray)); this.btnGoToRO.TabIndex = 11; this.btnGoToRO.Text = "Go To"; this.btnGoToRO.Click += new System.EventHandler(this.btnGoToRO_Click); - this.superTooltip1.SetSuperTooltip(this.btnGoToRO, new DevComponents.DotNetBar.SuperTooltipInfo("Go To", "", "Opens the RO Editor and positions to the selected RO.", null, null, DevComponents.DotNetBar.eTooltipColor.Gray)); // C2020-020 - // // btnPreviewRO // @@ -144,10 +154,10 @@ namespace Volian.Controls.Library this.btnPreviewRO.ColorTable = DevComponents.DotNetBar.eButtonColor.OrangeWithBackground; this.btnPreviewRO.Dock = System.Windows.Forms.DockStyle.Top; this.btnPreviewRO.Enabled = false; - this.btnPreviewRO.Location = new System.Drawing.Point(0, 67); - this.btnPreviewRO.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); + this.btnPreviewRO.Location = new System.Drawing.Point(0, 37); + this.btnPreviewRO.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); this.btnPreviewRO.Name = "btnPreviewRO"; - this.btnPreviewRO.Size = new System.Drawing.Size(311, 22); + this.btnPreviewRO.Size = new System.Drawing.Size(233, 18); this.superTooltip1.SetSuperTooltip(this.btnPreviewRO, new DevComponents.DotNetBar.SuperTooltipInfo("Preview", "", "This will Preview the selected RO Table, X/Y Plot, or Image.", null, null, DevComponents.DotNetBar.eTooltipColor.Gray, true, true, new System.Drawing.Size(150, 80))); this.btnPreviewRO.TabIndex = 10; this.btnPreviewRO.Text = "Preview"; @@ -159,10 +169,9 @@ namespace Volian.Controls.Library this.btnCancelRO.ColorTable = DevComponents.DotNetBar.eButtonColor.OrangeWithBackground; this.btnCancelRO.Dock = System.Windows.Forms.DockStyle.Top; this.btnCancelRO.Enabled = false; - this.btnCancelRO.Location = new System.Drawing.Point(0, 44); - this.btnCancelRO.Margin = new System.Windows.Forms.Padding(4); + this.btnCancelRO.Location = new System.Drawing.Point(0, 18); this.btnCancelRO.Name = "btnCancelRO"; - this.btnCancelRO.Size = new System.Drawing.Size(311, 23); + this.btnCancelRO.Size = new System.Drawing.Size(233, 19); this.superTooltip1.SetSuperTooltip(this.btnCancelRO, new DevComponents.DotNetBar.SuperTooltipInfo("Cancel", "", "This become active when you about to replace an existing RO link in you procedure" + ".\r\n\r\nNOTE: This willL NOT un-do after you select the Save RO button.", null, null, DevComponents.DotNetBar.eTooltipColor.Gray, true, true, new System.Drawing.Size(195, 145))); this.btnCancelRO.TabIndex = 9; @@ -175,40 +184,22 @@ namespace Volian.Controls.Library this.btnSaveRO.ColorTable = DevComponents.DotNetBar.eButtonColor.OrangeWithBackground; this.btnSaveRO.Dock = System.Windows.Forms.DockStyle.Top; this.btnSaveRO.Enabled = false; - this.btnSaveRO.Location = new System.Drawing.Point(0, 22); - this.btnSaveRO.Margin = new System.Windows.Forms.Padding(4); + this.btnSaveRO.Location = new System.Drawing.Point(0, 0); this.btnSaveRO.Name = "btnSaveRO"; - this.btnSaveRO.Size = new System.Drawing.Size(311, 22); - this.superTooltip1.SetSuperTooltip(this.btnSaveRO, new DevComponents.DotNetBar.SuperTooltipInfo("Save RO", "", "Saves the RO at the cursor location in either a step or a Word document.", null, null, DevComponents.DotNetBar.eTooltipColor.Gray)); // C2020-020 + this.btnSaveRO.Size = new System.Drawing.Size(233, 18); + this.superTooltip1.SetSuperTooltip(this.btnSaveRO, new DevComponents.DotNetBar.SuperTooltipInfo("Save RO", "", "Saves the RO at the cursor location in either a step or a Word document.", null, null, DevComponents.DotNetBar.eTooltipColor.Gray)); this.btnSaveRO.TabIndex = 8; this.btnSaveRO.Text = "Save RO"; this.btnSaveRO.Click += new System.EventHandler(this.btnSaveRO_Click); // - // btnFindDocRO - // - this.btnFindDocRO.AccessibleRole = System.Windows.Forms.AccessibleRole.PushButton; - this.btnFindDocRO.ColorTable = DevComponents.DotNetBar.eButtonColor.OrangeWithBackground; - this.btnFindDocRO.Dock = System.Windows.Forms.DockStyle.Top; - this.btnFindDocRO.Enabled = false; - this.btnFindDocRO.Location = new System.Drawing.Point(0, 0); - this.btnFindDocRO.Margin = new System.Windows.Forms.Padding(4); - this.btnFindDocRO.Name = "btnFindDocRO"; - this.btnFindDocRO.Size = new System.Drawing.Size(311, 22); - //see if there are any ro's for the selected text & if so, display in the lbFound li - this.superTooltip1.SetSuperTooltip(this.btnFindDocRO, new DevComponents.DotNetBar.SuperTooltipInfo("Find Doc RO", "", "Determine if there are any ROs for the selected text in a Word Document. If found, the list of ROs is displayed." , null, null, DevComponents.DotNetBar.eTooltipColor.Gray)); // C2020-020 - this.btnFindDocRO.TabIndex = 9; - this.btnFindDocRO.Text = "Find Doc RO"; - this.btnFindDocRO.Click += new System.EventHandler(this.btnFindDocRO_Click); - // // panelRoValue // this.panelRoValue.Controls.Add(this.tbROValue); this.panelRoValue.Controls.Add(this.lblROValue); this.panelRoValue.Dock = System.Windows.Forms.DockStyle.Top; this.panelRoValue.Location = new System.Drawing.Point(0, 0); - this.panelRoValue.Margin = new System.Windows.Forms.Padding(4); this.panelRoValue.Name = "panelRoValue"; - this.panelRoValue.Size = new System.Drawing.Size(311, 30); + this.panelRoValue.Size = new System.Drawing.Size(233, 24); this.panelRoValue.TabIndex = 8; // // tbROValue @@ -220,11 +211,10 @@ namespace Volian.Controls.Library this.tbROValue.Border.Class = "TextBoxBorder"; this.tbROValue.Border.CornerType = DevComponents.DotNetBar.eCornerType.Square; this.tbROValue.Dock = System.Windows.Forms.DockStyle.Top; - this.tbROValue.Location = new System.Drawing.Point(64, 0); - this.tbROValue.Margin = new System.Windows.Forms.Padding(4); + this.tbROValue.Location = new System.Drawing.Point(48, 0); this.tbROValue.Name = "tbROValue"; this.tbROValue.ReadOnly = true; - this.tbROValue.Size = new System.Drawing.Size(247, 22); + this.tbROValue.Size = new System.Drawing.Size(185, 20); this.superTooltip1.SetSuperTooltip(this.tbROValue, new DevComponents.DotNetBar.SuperTooltipInfo("RO Value", "", "The value of selected RO will be displayed here.\r\n\r\nExceptions:\r\n- Tables, X/Y Pl" + "ots, and Images will state what they are. The Preview button will display the va" + "lue.", null, null, DevComponents.DotNetBar.eTooltipColor.Gray, true, true, new System.Drawing.Size(230, 135))); @@ -239,17 +229,15 @@ namespace Volian.Controls.Library // this.lblROValue.BackgroundStyle.CornerType = DevComponents.DotNetBar.eCornerType.Square; this.lblROValue.Dock = System.Windows.Forms.DockStyle.Left; - this.lblROValue.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lblROValue.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblROValue.Location = new System.Drawing.Point(0, 0); - this.lblROValue.Margin = new System.Windows.Forms.Padding(4); this.lblROValue.Name = "lblROValue"; - this.lblROValue.Size = new System.Drawing.Size(64, 30); + this.lblROValue.Size = new System.Drawing.Size(48, 24); this.superTooltip1.SetSuperTooltip(this.lblROValue, new DevComponents.DotNetBar.SuperTooltipInfo("RO Value", "", "The value of selected RO will be displayed here.\r\n\r\nExceptions:\r\n- Tables, X/Y Pl" + "ots, and Images will state what they are. The Preview button will display the va" + "lue.", null, null, DevComponents.DotNetBar.eTooltipColor.Gray, true, true, new System.Drawing.Size(230, 135))); this.lblROValue.TabIndex = 6; this.lblROValue.Text = "RO Value:"; - this.lblROValue.TextLineAlignment = System.Drawing.StringAlignment.Near; // // superTooltip1 // @@ -260,11 +248,9 @@ namespace Volian.Controls.Library // this.lbFound.Dock = System.Windows.Forms.DockStyle.Top; this.lbFound.FormattingEnabled = true; - this.lbFound.ItemHeight = 16; - this.lbFound.Location = new System.Drawing.Point(0, 180); - this.lbFound.Margin = new System.Windows.Forms.Padding(4); + this.lbFound.Location = new System.Drawing.Point(0, 146); this.lbFound.Name = "lbFound"; - this.lbFound.Size = new System.Drawing.Size(311, 68); + this.lbFound.Size = new System.Drawing.Size(233, 56); this.superTooltip1.SetSuperTooltip(this.lbFound, new DevComponents.DotNetBar.SuperTooltipInfo("Available ROs", "", "ROs that are available are displayed in a tree view. ", null, null, DevComponents.DotNetBar.eTooltipColor.Gray)); this.lbFound.TabIndex = 8; this.lbFound.Visible = false; @@ -272,14 +258,13 @@ namespace Volian.Controls.Library // // DisplayRO // - this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.tvROFST); this.Controls.Add(this.lbFound); this.Controls.Add(this.panelValue); - this.Margin = new System.Windows.Forms.Padding(4); this.Name = "DisplayRO"; - this.Size = new System.Drawing.Size(311, 624); + this.Size = new System.Drawing.Size(233, 507); this.panelValue.ResumeLayout(false); this.pnlROButtons.ResumeLayout(false); this.panelRoValue.ResumeLayout(false); diff --git a/PROMS/Volian.Controls.Library/DisplayRO.cs b/PROMS/Volian.Controls.Library/DisplayRO.cs index 6854b29d..dd58f13f 100644 --- a/PROMS/Volian.Controls.Library/DisplayRO.cs +++ b/PROMS/Volian.Controls.Library/DisplayRO.cs @@ -12,61 +12,131 @@ using DevComponents.DotNetBar; using System.Text.RegularExpressions; using Volian.Base.Library; using JR.Utils.GUI.Forms; -//using VG; namespace Volian.Controls.Library { public partial class DisplayRO : UserControl { + #region Log4Net + private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); + + #endregion + + #region Fields + + private const string DummyNodeText = "VLN_DUMMY_NODE"; + private const int MaxNumSearchRecords = 1000; + + // B2019-161 When tracking timing time this action + private static VolianTimer _timeActivity = new VolianTimer("DisplayRO MyRTB_SelectionChanged", 117); + private static Regex _regExGetNumber = new Regex(@"^ *[+-]?[.,0-9/]+(E[+-]?[0-9]+)?"); + private static UserInfo _myUserInfo = null; + + private Timer _searchTimer; + private string _lastSearchValue = string.Empty; + + private ProgressBarItem _progressBar; + private DisplayTabControl _tabControl; + private StepRTB _myRTB; + private string _selectedRoidBeforeRoEditor = null; + + private ROFstInfo _myROFST; + private ROFSTLookup _myROFSTLookup; + private DocVersionInfo _docVersionInfo; + private RoUsageInfo _savCurROLink; + private E_ROValueType _roTypeFilter = E_ROValueType.All; + + private ROFstInfo _curROFST = null; + private ROFSTLookup _curROFSTLookup = null; + private RoUsageInfo _curROLink; + private E_ROValueType _curROTypeFilter = E_ROValueType.All; + + private ROFSTLookup.rochild selectedChld; + + #endregion + #region Properties - private DisplayTabControl _TabControl; + + public ProgressBarItem ProgressBar + { + get { return _progressBar; } + set { _progressBar = value; } + } public DisplayTabControl TabControl { - get { return _TabControl; } - set { _TabControl = value; } + get { return _tabControl; } + set { _tabControl = value; } } - private ROFstInfo _CurROFST = null; - private ROFSTLookup _CurROFSTLookup = null; - private ROFSTLookup _MyROFSTLookup; - public ROFSTLookup MyROFSTLookup - { - get { return _MyROFSTLookup; } - set - { - _MyROFSTLookup = value; - LoadTree(); - } - } - private ROFstInfo _MyROFST; + public ROFstInfo MyROFST { - get { return _MyROFST; } + get { return _myROFST; } set { - if (!Visible) return; // don't reset anything if the form is invisible. - _MyROFST = value; // define the tree nodes based on this rofst - LoadTree(); + if (!Visible) return; // don't reset anything if the form is invisible. + + // define the tree nodes based on this rofst + _myROFST = value; + + if (_myROFST != null && _myROFST.ROFstAssociations != null && _myROFST.ROFstAssociationCount > 0) + { + _myROFSTLookup = new ROFSTLookup(_myROFST.ROFstID, _myROFST.ROFstAssociations[0].MyDocVersion); + } + + //LoadTree(); } } - private RoUsageInfo _CurROLink; + + public ROFSTLookup MyROFSTLookup + { + get { return _myROFSTLookup; } + set + { + if (!Visible) return; // don't reset anything if the form is invisible. + + _myROFSTLookup = value; + _docVersionInfo = (_myROFSTLookup != null) ? _myROFSTLookup.MyDocVersionInfo : null; + //LoadTree(); + } + } + + 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(); + } + } + + public DocVersionInfo MyDvi + { + get { return _docVersionInfo; } + } + public RoUsageInfo CurROLink { - get { return _CurROLink; } + get { return _curROLink; } set { if (!Visible) return; // don't reset anything if the form is invisible. + if (value != null) // modify - set the controls to the current ro { - if (_CurROLink == value) return; - _CurROLink = value; - _SavCurROLink = _CurROLink; + if (_curROLink == value) return; + _curROLink = value; + _savCurROLink = _curROLink; UpdateROTree(); } - else // insert - clear out controls + else // insert - clear out controls { - _CurROLink = value; + _curROLink = value; tbROValue.Text = null; lbROId.Text = ""; tvROFST.SelectedNode = null; @@ -74,147 +144,181 @@ namespace Volian.Controls.Library } } } - private RoUsageInfo _SavCurROLink; - private StepRTB _MyRTB; + public StepRTB MyRTB { - get { return _MyRTB; } + get { return _myRTB; } set { - if (!Visible) return; + if (!Visible) return; // don't reset anything if the form is invisible. + int origRoDbId = -1; - if (_MyRTB != null) + + if (_myRTB != null) { - _MyRTB.LinkChanged -= new StepRTBLinkEvent(MyRTB_LinkChanged); - _MyRTB.SelectionChanged -= new EventHandler(MyRTB_SelectionChanged); - if (_MyRTB.MyItemInfo.MyDocVersion.DocVersionAssociationCount>0) - origRoDbId = _MyRTB.MyItemInfo.MyDocVersion.DocVersionAssociations[0].MyROFst.RODbID; + _myRTB.LinkChanged -= new StepRTBLinkEvent(MyRTB_LinkChanged); + _myRTB.SelectionChanged -= new EventHandler(MyRTB_SelectionChanged); + + if (_myRTB.MyItemInfo.MyDocVersion.DocVersionAssociationCount > 0) + { + origRoDbId = _myRTB.MyItemInfo.MyDocVersion.DocVersionAssociations[0].MyROFst.RODbID; + } } + if (value == null) return; - _MyRTB = value; + + _myRTB = value; MyRTB.LinkChanged += new StepRTBLinkEvent(MyRTB_LinkChanged); MyRTB.SelectionChanged+=new EventHandler(MyRTB_SelectionChanged); + if (MyRTB.MyLinkText == null) { CurROLink = null; - _SavCurROLink = null; + _savCurROLink = null; } + // Test to see if this myrtf is using the same rofst as the previous. If // not we may have to reset the ro.fst for the tree if the new working // draft has a different ro.fst than the original: - if (_MyRTB != null && _MyRTB.MyItemInfo.MyDocVersion.DocVersionAssociationCount > 0) + if (_myRTB != null && _myRTB.MyItemInfo.MyDocVersion.DocVersionAssociationCount > 0) { - if (origRoDbId != _MyRTB.MyItemInfo.MyDocVersion.DocVersionAssociations[0].MyROFst.RODbID) - MyROFST = _MyRTB.MyItemInfo.MyDocVersion.DocVersionAssociations[0].MyROFst; + if (origRoDbId != _myRTB.MyItemInfo.MyDocVersion.DocVersionAssociations[0].MyROFst.RODbID) + { + MyROFST = _myRTB.MyItemInfo.MyDocVersion.DocVersionAssociations[0].MyROFst; + LoadTree(); // B2022-026 RO Memory Reduction code + } } - // This docversion doesn't have an rofst associated with it, clear the ro tree. - else if (_MyRTB.MyItemInfo.MyDocVersion.DocVersionAssociationCount <= 0) + else if (_myRTB.MyItemInfo.MyDocVersion.DocVersionAssociationCount <= 0) + { + // This docversion doesn't have an rofst associated with it, clear the ro tree. MyROFST = null; - } - } - // B2019-161 When tracking timing time this action - private static VolianTimer _TimeActivity = new VolianTimer("DisplayRO MyRTB_SelectionChanged", 117); - - void MyRTB_SelectionChanged(object sender, EventArgs e) - { - _TimeActivity.Open(); - lbFound.SelectionMode = SelectionMode.None; - lbFound.DataSource = null; - //Spin through ROs looking for the selected text - if (MyRTB.SelectedText != "") - { - string lookFor = MyRTB.SelectedText.Replace('\u2011', '-').Replace(@"\u9586?", @"\\"); - List children = null; - if (_MyROFST != null) children = _MyROFST.GetROFSTLookup(Mydvi).GetRosByValue(lookFor); - if (children != null) - { - lbFound.Visible = true; - lbFound.DataSource = children.ToArray(); - lbFound.SelectionMode = SelectionMode.One; - lbFound.SelectedIndex = -1; + LoadTree(); // B2022-026 RO Memory Reduction code } - else - lbFound.Visible = false; - } - else - lbFound.Visible = false; - _TimeActivity.Close(); - } - - void MyRTB_LinkChanged(object sender, StepPanelLinkEventArgs args) - { - if (MyRTB.MyLinkText == null) - CurROLink = null; - else - { - CurROLink = args.MyLinkText.MyRoUsageInfo; } } - //private DocVersionInfo _Mydvi; - - public DocVersionInfo Mydvi - { - get { return MyROFSTLookup != null ? MyROFSTLookup.MyDocVersionInfo : null; } -// get { return _Mydvi; } - //set { _Mydvi = value; } - } - - - private ProgressBarItem _ProgressBar; - - public ProgressBarItem ProgressBar - { - get { return _ProgressBar; } - set { _ProgressBar = value; } - } - - //public int ProgBarMax - //{ - // get { return _ProgressBar.Maximum; } - // set { _ProgressBar.Maximum = value; } - //} - - //public int ProgBarValue - //{ - // get { return _ProgressBar.Value; } - // set { _ProgressBar.Value = value; } - //} - - //public string ProgBarText - //{ - // get { return _ProgressBar.Text; } - // set - // { - // _ProgressBar.TextVisible = true; - // _ProgressBar.Text = value; - // } - //} - - private static UserInfo _MyUserInfo = null; - public static UserInfo MyUserInfo { - get { return _MyUserInfo; } - set { _MyUserInfo = value; } + get { return _myUserInfo; } + set { _myUserInfo = value; } } #endregion + #region Constructors - public DisplayRO() // B2019-043 jsj 2019Mar21 - Removed the DisplayTabControl parameter from the constructor + + public DisplayRO() { InitializeComponent(); - // jsj 2019Mar21 - This is initialized in frmVEPROMS.Designer.cs and in frmVEPROMS.cs in the constructor after the call to InitializeComponent() - // When we had passed in the DisplayTabControl as a parameter, "DisplayRO(DisplayTabControl tc)", the frmVEPROMS designer would not include a NEW call for DisplayRO - // in the "Windows Form Designer generated code" Region and thus cause the design view to no longer appear. - //TabControl = tc;// B2017-074 Added DisplayTabControl to the constructor to assure that it is set - _ProgressBar = null; + panelRoValue.BackColor = Color.Cornsilk; panelValue.BackColor = Color.Cornsilk; + + if (_searchTimer == null) + { + _searchTimer = new Timer(); + _searchTimer.Interval = 1000; + _searchTimer.Tick += new EventHandler(SelectionTimer_Tick); + _searchTimer.Stop(); + } + + _progressBar = null; } + #endregion - #region Events - ROFSTLookup.rochild selectedChld; + + #region Event Handlers + + #region (Progress Bar) + + private void ProgressBar_Initialize(int max, string desc) + { + if (_progressBar != null) + { + _progressBar.Maximum = max; + _progressBar.Text = desc; + _progressBar.TextVisible = true; + } + } + + private void ProgressBar_SetValue(int curval) + { + if (_progressBar != null) + { + _progressBar.Value = curval; + } + } + + private void ProgressBar_Clear() + { + if (_progressBar != null) + { + _progressBar.Text = string.Empty; + _progressBar.Maximum = 0; + _progressBar.Value = 0; + } + } + + #endregion + + #region (RTB) + + public void MyRTB_LinkChanged(object sender, StepPanelLinkEventArgs args) + { + CurROLink = null; + if (MyRTB.MyLinkText != null) CurROLink = args.MyLinkText.MyRoUsageInfo; + } + + public void MyRTB_SelectionChanged(object sender, EventArgs e) + { + _timeActivity.Open(); + + _searchTimer.Stop(); + if (!string.IsNullOrEmpty(MyRTB.SelectedText)) + { + _searchTimer.Start(); + } + + _timeActivity.Close(); + } + + private void SelectionTimer_Tick(object sender, EventArgs e) + { + // Stop the timer + _searchTimer.Stop(); + + // Jake [2022.05.11]: Added try catch to prevent unhandled exception when the timer ticks and + // tries to process a search while the main tab/procedure is closing + try + { + // Process RO Search + if (MyRTB != null) + { + ProcessSearch(MyRTB.SelectedText, (int)ROFSTLookup.SearchType.StartsWith); + } + + } + catch { } + } + + #endregion + + #region (Tree Node) + + private void tvROFST_DoubleClick(object sender, EventArgs e) + { + // B2016-132: don't process a double click on an RO if on an enhanced step: + if (MyRTB != null && MyRTB.MyItemInfo != null && MyRTB.MyItemInfo.IsEnhancedStep) + return; + + SaveRO(); + } + + private void tvROFST_BeforeExpand(object sender, TreeViewCancelEventArgs e) + { + LoadChildren(e.Node); + } + private void tvROFST_AfterSelect(object sender, TreeViewEventArgs e) { tbROValue.Text = null; @@ -228,26 +332,30 @@ namespace Volian.Controls.Library { ROFSTLookup.rochild chld = (ROFSTLookup.rochild)e.Node.Tag; selectedChld = chld; + if (chld.value != null) { RoUsageInfo SavROLink = null; - if (_SavCurROLink != null) - SavROLink = _SavCurROLink; ; + if (_savCurROLink != null) SavROLink = _savCurROLink; lbROId.Text = chld.appid; + // Allow the user to select a different return value. - //btnSaveRO.Enabled = ((_SavCurROLink == null) || !(chld.roid.Substring(0, 12).ToLower().Equals(SavROLink.ROID.Substring(0, 12).ToLower()))); - //btnCancelRO.Enabled = ((_SavCurROLink != null) && chld.roid.Substring(0, 12).ToLower() != SavROLink.ROID.Substring(0, 12).ToLower()); + //btnSaveRO.Enabled = ((_savCurROLink == null) || !(chld.roid.Substring(0, 12).ToLower().Equals(SavROLink.ROID.Substring(0, 12).ToLower()))); + //btnCancelRO.Enabled = ((_savCurROLink != null) && chld.roid.Substring(0, 12).ToLower() != SavROLink.ROID.Substring(0, 12).ToLower()); string childroid = chld.roid.ToLower() + "0000"; childroid = childroid.Substring(0, 16); bool isenh = MyRTB != null && MyRTB.MyItemInfo != null && MyRTB.MyItemInfo.IsEnhancedStep; - //B2017-245 Disable SAveRO buttton for Procedues and Sections + + //B2017-245 Disable SAveRO button for Procedures and Sections bool isNotStep = MyRTB != null && MyRTB.MyItemInfo != null && (MyRTB.MyItemInfo.IsProcedure || MyRTB.MyItemInfo.IsSection); + //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') bool isInWordDoc = TabControl.SelectedDisplayTabItem.MyDSOTabPanel != null; - btnSaveRO.Enabled = (isInWordDoc || (!isNotStep && !isenh)) && UserInfo.CanEdit(MyUserInfo, Mydvi) && ((_SavCurROLink == null) || !(childroid.Equals(SavROLink.ROID.ToLower()))); //added security check (UserInfo.CanEdit) - btnCancelRO.Enabled = ((_SavCurROLink != null) && childroid != SavROLink.ROID.ToLower()); - btnGoToRO.Enabled = UserInfo.CanEditROs(MyUserInfo, Mydvi); // Writers and Reviewers cannot edit ROs (run the RO Editor) + btnSaveRO.Enabled = (isInWordDoc || (!isNotStep && !isenh)) && UserInfo.CanEdit(MyUserInfo, MyDvi) && ((_savCurROLink == null) || !(childroid.Equals(SavROLink.ROID.ToLower()))); //added security check (UserInfo.CanEdit) + btnCancelRO.Enabled = ((_savCurROLink != null) && childroid != SavROLink.ROID.ToLower()); + 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 @@ -255,95 +363,311 @@ namespace Volian.Controls.Library roval = GetPCDefaultValue(roval); // C2021-026 get the default RO value from P/C RO value information tbROValue.Text = roval; btnPreviewRO.Enabled = false; - if (chld.roid.StartsWith("FFFF")) - btnGoToRO.Enabled = false; + if (chld.roid.StartsWith("FFFF")) btnGoToRO.Enabled = false; break; + case 2: // Table RO type case 3: // This is type 3 when part of a multiple return value tbROValue.Text = "(Table)"; btnPreviewRO.Enabled = true; break; + case 4: // X/Y Plot RO type tbROValue.Text = "(Graph)"; btnPreviewRO.Enabled = true; break; - case 8: // Intergrated Graphics RO type + + case 8: // Integrated Graphics RO type tbROValue.Text = "(Image)"; btnPreviewRO.Enabled = true; break; } } } + } + #endregion - //if (e.Node.Tag is ROFST.rochild) + #region (Buttons) + + private void btnSaveRO_Click(object sender, EventArgs e) + { + SaveRO(); + } + + private void btnCancelRO_Click(object sender, EventArgs e) + { + _curROLink = _savCurROLink; + btnCancelRO.Enabled = false; + UpdateROTree(); + } + + private void btnPreviewRO_Click(object sender, EventArgs e) + { + if (selectedChld.type == 8) // integrated graphic + { + string fname = selectedChld.value.Substring(0, selectedChld.value.IndexOf('\n')); + int thedot = fname.LastIndexOf('.'); + ROImageInfo tmp = null; + + if (thedot == -1 || (thedot != (fname.Length - 4))) + { + tmp = ROImageInfo.GetByROFstID_FileName(MyROFST.ROFstID, fname); + fname += string.Format(".{0}", MyROFST.MyRODb.RODbConfig.GetDefaultGraphicExtension()); + } + + if (tmp == null) tmp = ROImageInfo.GetByROFstID_FileName(MyROFST.ROFstID, fname); + if (tmp == null) tmp = MyROFST.GetROImageByFilename(fname, null); + + if (tmp != null) + { + ROImageConfig rc = new ROImageConfig(tmp); + int size = Convert.ToInt32(rc.Image_Size); + PreviewROImage pvROImg = new PreviewROImage(ROImageInfo.Decompress(tmp.Content, size), selectedChld.title); + pvROImg.ShowDialog(); + } + else + { + FlexibleMessageBox.Show(string.Format("Cannot Find Image Data: {0}, {1}", MyROFST.ROFstID, fname)); + } + } + else if (selectedChld.type == 2) // table + { + PreviewMultiLineRO pmlROTable = new PreviewMultiLineRO(selectedChld.value, selectedChld.title); + pmlROTable.ShowDialog(); + } + else if (selectedChld.type == 4) // x/y plot + { + frmXYPlot plot = new frmXYPlot(selectedChld.appid + " - " + selectedChld.title, selectedChld.value); + plot.Show(); + } + } + + private void btnGoToRO_Click(object sender, EventArgs e) + { + if (tvROFST.SelectedNode == null) return; + RunRoEditor(); + } + + private void btnFindDocRO_Click(object sender, EventArgs e) + { + // C2016-044: support click of the 'Find Doc RO' button: + DisplayTabItem dti = (_tabControl == null) ? null : _tabControl.SelectedDisplayTabItem; + + if (dti != null && dti.MyDSOTabPanel != null) + { + // the currently selected tab control is a word document - see if it has an + // active selection. If not, tell the user that text needs to be selected before the ro can be found. + string mytext = dti.MyDSOTabPanel.GetSelectedString(); + + if (string.IsNullOrEmpty(mytext)) + { + FlexibleMessageBox.Show(this, "Text must be selected in the document in order for an RO find to be performed.", "Select Text", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); + return; + } + else + { + ProcessSearch(mytext, (int)ROFSTLookup.SearchType.StartsWith); + } + } + } + + #endregion + + #region (Labels) + + private void lbROId_DoubleClick(object sender, EventArgs e) + { + if (tvROFST.SelectedNode == null) + return; + + // do not allow writers and reviews to run the RO Editor + if (!UserInfo.CanEditROs(MyUserInfo, MyDvi)) + return; + + if (VlnSettings.ReleaseMode.Equals("DEMO")) + { + FlexibleMessageBox.Show("Referenced Object Editor not available in the Demo version.", "PROMS Demo Version"); + return; + } + + string roapp = Volian.Base.Library.ExeInfo.GetROEditorPath(); // get the path to the RO Editor Executable + object obj = tvROFST.SelectedNode.Tag; + + if (obj is ROFSTLookup.rochild) + { + ROFSTLookup.rochild roch = (ROFSTLookup.rochild)obj; + + _selectedRoidBeforeRoEditor = roch.roid; + string args = "\"" + MyROFST.MyRODb.FolderPath + "\" " + roch.roid.ToLower(); + + // C2017-003: ro data in sql server, check for sql connection string + if (MyROFST.MyRODb.DBConnectionString != "cstring") args = args + " \"" + MyROFST.MyRODb.DBConnectionString + "\""; + + // C2021-026 pass in Parent/Child information (list of the children) + // B2022-019 look at all DocVersions to find ParentChild information + // to ensure we pass in Parent/Child even when not coming from a Parent/Child procedure set + + DocVersionInfoList dvil = DocVersionInfoList.Get(); + + foreach (DocVersionInfo dvi in dvil) + { + DocVersionConfig dvc = dvi.DocVersionConfig; + if (dvc != null && dvc.Unit_Name != "" && dvc.Unit_Name != "0") + { + args += " \"PC=" + dvc.Unit_Name + "\""; + } + break; + } + + System.Diagnostics.Process.Start(roapp, args); + } + } + + private void lbFound_SelectedValueChanged(object sender, EventArgs e) + { + if (lbFound.Visible && lbFound.SelectedIndex >= 0 && lbFound.SelectedValue != null) + { + ExpandNode(Convert.ToString(lbFound.SelectedValue)); + } + } + + #endregion + + #endregion + + #region Public Methods + + public void RefreshRoTree() + { + _curROFST = null; + _curROFSTLookup = null; + + LoadTree(); + + if (!string.IsNullOrEmpty(_selectedRoidBeforeRoEditor)) + { + ExpandNode(_selectedRoidBeforeRoEditor); + _selectedRoidBeforeRoEditor = null; + } + } + + public void SetFindDocROButton(bool enabled) + { + this.btnFindDocRO.Enabled = enabled; + } + + public static bool GreaterValue(string value1, string value2) + { + Match match1 = _regExGetNumber.Match(value1); + Match match2 = _regExGetNumber.Match(value2); + + if (match1.Success && !match1.Value.Contains("/") && match2.Success && !match2.Value.Contains("/")) // Compare the numeric value + { + double dbl1; + double dbl2; + + //B2017-232 changed from Parse to TryParse. AEP had figure title that had a number containing two periods which caused Parse to error + if (double.TryParse(match1.ToString(), out dbl1) && double.TryParse(match2.ToString(), out dbl2)) + { + if (dbl1 != dbl2) //B2021-144 if the numerical is identical default to the string comparison + return dbl1 > dbl2; + } + } + + return string.Compare(value1, value2, true) > 0; + } + + #endregion + + #region Private Methods + + public void LoadTree() + { + if (_myROFST == null) + { + tvROFST.Nodes.Clear(); + _curROFST = null; + _curROFSTLookup = null; + return; + } + + if (MyROFST ==_curROFST && ROTypeFilter == _curROTypeFilter && MyROFSTLookup == _curROFSTLookup) + return; + + //_MyLog.WarnFormat("Load Tree \r\n_curROfst = {0}\r\n MyROFST {1}", _curROFST,MyROFST); + //_MyLog.WarnFormat("{0}", Volian.Base.Library.vlnStackTrace.StackToStringLocal(2, 3)); + + tvROFST.Nodes.Clear(); + + _myROFSTLookup = new ROFSTLookup(MyROFST.ROFstID, MyDvi); + + _curROFST = _myROFST; + _curROFSTLookup = _myROFSTLookup; + _curROTypeFilter = _roTypeFilter; + + ROFSTLookup.rodbi[] dbs = MyROFSTLookup.GetRODatabaseList(false); + + for (int i = 0; i < dbs.Length; i++) + { + ROFSTLookup.rodbi db = dbs[i]; + + db.children = MyROFSTLookup.GetRoChildrenByID(db.ID, db.dbiID, true); + + TreeNode tn = new TreeNode(db.dbiTitle); + tn.Tag = db; + tvROFST.Nodes.Add(tn); + + AddDummyGroup(db, tn); + } + + if ((ROTypeFilter == E_ROValueType.Text || ROTypeFilter == E_ROValueType.All) && this.MyDvi != null && this.MyDvi.MultiUnitCount > 1) + { + 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 //{ - // ROFST.rochild chld = (ROFST.rochild)e.Node.Tag; - // if (chld.type == 1 && chld.value != null) - // { - // string SavROLink = ""; - // if (_SavCurROLink != null) - // SavROLink = _SavCurROLink.Substring(_SavCurROLink.IndexOf(' ') + 1, 12); - // tbROValue.Text = chld.value; - // btnSaveRO.Enabled = ((_SavCurROLink == null) || !(chld.roid.Equals(SavROLink))); - // btnCancelRO.Enabled = ((_SavCurROLink != null) && !(chld.roid.Equals(SavROLink))); - // } - // //else - // //{ - // // tbROValue.Text = null; - // // btnCancelRO.Enabled = btnSaveRO.Enabled = false; - // //} + // _MyLog.Warn("Unit Designtor not loaded"); + // _MyLog.Warn(Volian.Base.Library.vlnStackTrace.StackToStringLocal(2,3)); //} - ////else - ////{ - //// tbROValue.Text = null; - //// btnCancelRO.Enabled = btnSaveRO.Enabled = false; - ////} - } - private void tvROFST_BeforeExpand(object sender, TreeViewCancelEventArgs e) - { - LoadChildren(e.Node); - } - private E_ROValueType _ROTypeFilter = E_ROValueType.All; - - public E_ROValueType ROTypeFilter - { - get { return _ROTypeFilter; } - set - { - _ROTypeFilter = value; - LoadTree(); - } - } - private E_ROValueType _CurrentROTypeFilter = E_ROValueType.All; - - // 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 pannel - private string GetPCDefaultValue(string roval) - { - 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 maded 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 void LoadChildren(TreeNode tn) { + //Check if node has already been loaded + if (tn.FirstNode != null && tn.FirstNode.Text != DummyNodeText) + return; + + if (tn.FirstNode != null && tn.FirstNode.Text == DummyNodeText) + tn.FirstNode.Remove(); + + object tag = tn.Tag; - if (tn.FirstNode != null && tn.FirstNode.Text != "VLN_DUMMY_FOR_TREE") return; // already loaded. - if (tn.FirstNode != null && tn.FirstNode.Text == "VLN_DUMMY_FOR_TREE") tn.FirstNode.Remove(); + ROFSTLookup.rochild[] chld = null; if (tn.Tag is ROFSTLookup.rodbi) @@ -354,6 +678,16 @@ namespace Volian.Controls.Library else if (tn.Tag is ROFSTLookup.rochild) { ROFSTLookup.rochild ch = (ROFSTLookup.rochild)tn.Tag; + + if (!string.IsNullOrEmpty(ch.appid)) + { + ch = MyROFSTLookup.GetRoChild(ch.roid); + } + else if (ch.children == null || ch.children.Length <= 0) + { + ch.children = MyROFSTLookup.GetRoChildrenByRoid(ch.roid, true); + } + chld = ch.children; } else @@ -361,51 +695,59 @@ namespace Volian.Controls.Library Console.WriteLine("error - no type"); return; } + // if children, add dummy node if (chld != null && chld.Length > 0) { ProgressBar_Initialize(chld.Length, tn.Text); + for (int i = 0; i < chld.Length; i++) { ProgressBar_SetValue(i); TreeNode tmp = null; + // if this is a group, i.e. type 0, add a dummy node if (chld[i].type == 0 && chld[i].children == null) + { //skip it. // TODO: KBR how to handle this? //Console.WriteLine("ro junk"); continue; + } else if (ROTypeFilter != E_ROValueType.All && (chld[i].type & (uint)ROTypeFilter) == 0) - continue; // ignore if does not match filter - else if (/*chld[i].type == 1 && */ chld[i].value == null) { + continue; // ignore if does not match filter + } + else if (chld[i].value == null) + { + if (!string.IsNullOrEmpty(chld[i].appid)) + { + chld[i] = MyROFSTLookup.GetRoChild(chld[i].roid); + } + else if (chld[i].children == null || chld[i].children.Length <= 0) + { + chld[i].children = MyROFSTLookup.GetRoChildrenByRoid(chld[i].roid, true); + } + tmp = new TreeNode(chld[i].title); tmp.Tag = chld[i]; //tn.Nodes.Add(tmp); int index = FindIndex(tn.Nodes, tmp.Text); tn.Nodes.Insert(index, tmp); - TreeNode sub = new TreeNode("VLN_DUMMY_FOR_TREE"); + TreeNode sub = new TreeNode(DummyNodeText); tmp.Nodes.Add(sub); } - //else if (chld[i].type == 2 && chld[i].value == null) // table - //{ - // if ((MyRTB.MyItemInfo.MyContent.Type % 10000) == (int)E_FromType.Table) - // { - // tmp = new TreeNode(chld[i].title); - // tmp.Tag = chld[i]; - // tn.Nodes.Add(tmp); - // TreeNode sub = new TreeNode("VLN_DUMMY_FOR_TREE"); - // tmp.Nodes.Add(sub); - // } - //} else { string ntitle = chld[i].title.Replace(@"\u160?", " "); ntitle = GetPCDefaultValue(ntitle); // C2021-026 get the default RO value from P/C RO value information tmp = new TreeNode(ntitle); tmp.Tag = chld[i]; + if (chld[i].roid.Length == 16) + { tn.Nodes.Add(tmp); + } else { int index = FindIndex(tn.Nodes, tmp.Text); @@ -414,171 +756,54 @@ namespace Volian.Controls.Library } } } + ProgressBar_Clear(); } - private int FindIndex(TreeNodeCollection nodes, string value) - { - int index = 0; - foreach (TreeNode node in nodes) - { - if (GreaterValue(node.Text, value)) return index; - index++; - } - return index; - } - private static Regex _RegExGetNumber = new Regex(@"^ *[+-]?[.,0-9/]+(E[+-]?[0-9]+)?"); - // Sort by numeric value if possible, Otherwise sort alphabetically. - public static bool GreaterValue(string value1, string value2) - { - Match match1 = _RegExGetNumber.Match(value1); - Match match2 = _RegExGetNumber.Match(value2); - if (match1.Success && !match1.Value.Contains("/") && match2.Success && !match2.Value.Contains("/")) // Compare the numeric value - { - double dbl1; - double dbl2; - //B2017-232 changed from Parse to TryParse. AEP had figure title that had a number containing two periods which caused Parse to error - if (double.TryParse(match1.ToString(), out dbl1) && double.TryParse(match2.ToString(), out dbl2)) - if (dbl1 != dbl2) //B2021-144 if the numerical is identical default to the string comparision - return dbl1 > dbl2; - } - return String.Compare(value1, value2, true) > 0; - } - public void RefreshRoTree() - { - string roid = null; - if (tvROFST.SelectedNode != null) - { - if (tvROFST.SelectedNode.Tag is ROFSTLookup.rochild) - { - ROFSTLookup.rochild chld = (ROFSTLookup.rochild)tvROFST.SelectedNode.Tag; - roid = chld.roid; - } - } - _CurROFST = null; - _CurROFSTLookup = null; - LoadTree(); - if (_SelectedRoidBeforeRoEditor != null) - { - ExpandTree(_SelectedRoidBeforeRoEditor); - _SelectedRoidBeforeRoEditor = null; - } - } - private void LoadTree() - { - if (_MyROFST == null) - { - tvROFST.Nodes.Clear(); - _CurROFST = null; - _CurROFSTLookup = null; - return; - } - if (_MyROFST == _CurROFST && ROTypeFilter == _CurrentROTypeFilter && _MyROFSTLookup == _CurROFSTLookup) return; - tvROFST.Nodes.Clear(); - _CurROFST = _MyROFST; - _CurROFSTLookup = _MyROFSTLookup; - _CurrentROTypeFilter = ROTypeFilter; - for (int i = 0; i < _MyROFST.GetROFSTLookup(Mydvi).myHdr.myDbs.Length; i++) - { - TreeNode tn = new TreeNode(_MyROFST.GetROFSTLookup(Mydvi).myHdr.myDbs[i].dbiTitle); - tn.Tag = _MyROFST.GetROFSTLookup(Mydvi).myHdr.myDbs[i]; - tvROFST.Nodes.Add(tn); - AddDummyGroup(_MyROFST.GetROFSTLookup(Mydvi).myHdr.myDbs[i], tn); - } - if ((ROTypeFilter == E_ROValueType.Text || ROTypeFilter == E_ROValueType.All) && this.Mydvi != null && this.Mydvi.MultiUnitCount > 1) - { - TreeNode tnn = tvROFST.Nodes.Add("Unit Information"); - /* - if (ROID == "FFFF00000001") return _ROFstInfo.docVer.DocVersionConfig.Unit_Number; - if (ROID == "FFFF00000002") return _ROFstInfo.docVer.DocVersionConfig.Other_Unit_Number; - if (ROID == "FFFF00000003") return _ROFstInfo.docVer.DocVersionConfig.Unit_Text; - if (ROID == "FFFF00000004") return _ROFstInfo.docVer.DocVersionConfig.Other_Unit_Text; - if (ROID == "FFFF00000005") return _ROFstInfo.docVer.DocVersionConfig.Unit_ID; - if (ROID == "FFFF00000006") return _ROFstInfo.docVer.DocVersionConfig.Other_Unit_ID; - if (ROID == "FFFF00000007") return _ROFstInfo.docVer.DocVersionConfig.Unit_Name; - if (ROID == "FFFF00000008") return _ROFstInfo.docVer.DocVersionConfig.Other_Unit_Name; - */ - /* - TreeNode cn = tnn.Nodes.Add("Number"); - cn.Tag = MyROFST.ROFSTLookup.GetRoChild("FFFF00000001"); - cn = tnn.Nodes.Add("Other Number"); - cn.Tag = MyROFST.ROFSTLookup.GetRoChild("FFFF00000002"); - cn = tnn.Nodes.Add("Text"); - cn.Tag = MyROFST.ROFSTLookup.GetRoChild("FFFF00000003"); - cn = tnn.Nodes.Add("Other Text"); - cn.Tag = MyROFST.ROFSTLookup.GetRoChild("FFFF00000004"); - cn = tnn.Nodes.Add("ID"); - cn.Tag = MyROFST.ROFSTLookup.GetRoChild("FFFF00000005"); - cn = tnn.Nodes.Add("Other ID"); - cn.Tag = MyROFST.ROFSTLookup.GetRoChild("FFFF00000006"); - cn = tnn.Nodes.Add("Name"); - cn.Tag = MyROFST.ROFSTLookup.GetRoChild("FFFF00000007"); - cn = tnn.Nodes.Add("Other Name"); - cn.Tag = MyROFST.ROFSTLookup.GetRoChild("FFFF00000008"); - */ - 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"); - } - } + private void AddDummyGroup(ROFSTLookup.rodbi rodbi, TreeNode tn) { if (rodbi.children != null && rodbi.children.Length > 0) { - TreeNode tmp = new TreeNode("VLN_DUMMY_FOR_TREE"); + TreeNode tmp = new TreeNode(DummyNodeText); tn.Nodes.Add(tmp); } } - private void UpdateROTree() - { - // walk down from root of tree, expanding values in the string - // that represents the ro link. - //string tmpstr = _CurROLink; - //int sp = tmpstr.IndexOf(" "); // because parse of ro info is wrong!! - //int rousageid = System.Convert.ToInt32(tmpstr.Substring(0, sp)); - ExpandTree(_CurROLink.ROID);// tmpstr.Substring(sp + 1, tmpstr.Length - sp - 1); - } - private void ExpandTree(string roid) + private void ExpandNode(string roid) { string db = roid.Substring(0, 4); bool multValSel = false; + if (roid.Length == 16) multValSel = true; 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) { path.Insert(0, myid); myid = rochld.ParentID; - String pROID = string.Format("{0}{1:X08}",db,myid); + string pROID = string.Format("{0}{1:X08}", db, myid); rochld = MyROFSTLookup.GetRoChild(pROID); - //rochld = MyROFST.ROFSTLookup.GetRoChildFromID(myid); Did not include db + if (rochld.ID == -1) myid = -1; } + TreeNode tnExpand = null; int titm = System.Convert.ToInt32(db, 16); //(db); + // find database first foreach (TreeNode tn in tvROFST.Nodes) { if (tn.Tag != null) { ROFSTLookup.rodbi thisdb = (ROFSTLookup.rodbi)tn.Tag; + if (thisdb.dbiID == titm) { LoadChildren(tn); @@ -587,12 +812,15 @@ namespace Volian.Controls.Library } } } + if (tnExpand == null) return; // something went wrong? + // use the path id list to load/find the treeview's nodes. foreach (int citm in path) { LoadChildren(tnExpand); tnExpand.Expand(); + foreach (TreeNode tn in tnExpand.Nodes) { ROFSTLookup.rochild chld = (ROFSTLookup.rochild)tn.Tag; @@ -611,11 +839,13 @@ namespace Volian.Controls.Library { LoadChildren(tnExpand); tnExpand.Expand(); + foreach (TreeNode tn in tnExpand.Nodes) { if (tn.Tag != null) { ROFSTLookup.rochild chld = (ROFSTLookup.rochild)tn.Tag; + if (chld.roid.ToUpper() == roid.ToUpper()) { tnExpand = tn; @@ -624,31 +854,77 @@ namespace Volian.Controls.Library } } } + tvROFST.SelectedNode = tnExpand; } } - private void btnSaveRO_Click(object sender, EventArgs e) + + private void UpdateROTree() { - SaveRO(); + ExpandNode(_curROLink.ROID); } + + 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 maded 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; + + foreach (TreeNode node in nodes) + { + if (GreaterValue(node.Text, value)) return index; + index++; + } + + return index; + } + private void SaveRO() { - if (tbROValue.Text == null || tbROValue.Text == "") + //Check if an RO Node is selected from the TreeView + if (string.IsNullOrEmpty(tbROValue.Text)) { FlexibleMessageBox.Show("Must select an RO Value from the tree."); return; } + + Object obj = tvROFST.SelectedNode.Tag; + if (obj is ROFSTLookup.rochild) { ROFSTLookup.rochild roch = (ROFSTLookup.rochild)obj; DisplayTabItem dti = TabControl.SelectedDisplayTabItem; //.OpenItem(_ItemInfo); // open the corresponding procedure text + if (dti.MyDSOTabPanel != null) // A Word Document tab is the active tab { int dbiId = System.Convert.ToInt32(roch.roid.Substring(0, 4), 16); - ROFSTLookup.rodbi[] dbs = MyROFSTLookup.GetRODatabaseList(); + ROFSTLookup.rodbi[] dbs = MyROFSTLookup.GetRODatabaseList(false); bool dbFound = false; ROFSTLookup.rodbi db = dbs[0]; + foreach (ROFSTLookup.rodbi rodbi in dbs) { if (dbiId == rodbi.dbiID) @@ -658,7 +934,9 @@ namespace Volian.Controls.Library break; } } + string AccPageID; + if (!dbFound) { if (roch.roid.StartsWith("FFFF")) @@ -673,17 +951,13 @@ namespace Volian.Controls.Library } else { - string accPrefix = db.dbiAP.Replace(Mydvi.DocVersionConfig.RODefaults_graphicsprefix, "IG"); - accPrefix = accPrefix.Replace(Mydvi.DocVersionConfig.RODefaults_setpointprefix, "SP"); + string accPrefix = db.dbiAP.Replace(MyDvi.DocVersionConfig.RODefaults_graphicsprefix, "IG"); + accPrefix = accPrefix.Replace(MyDvi.DocVersionConfig.RODefaults_setpointprefix, "SP"); // string accPrefix = (roch.type == 8) ? _Mydvi.DocVersionConfig.RODefaults_graphicsprefix : _Mydvi.DocVersionConfig.RODefaults_setpointprefix; string suffix = (roch.roid.Length == 12 || roch.roid.Substring(12, 4) == "0041") ? "" : "." + ((char)Convert.ToInt32(roch.roid.Substring(12, 4), 16)).ToString(); AccPageID = string.Format("<{0}-{1}{2}>", accPrefix, roch.appid, suffix);// makes for example Console.WriteLine(AccPageID); } - //string AccPageID = string.Format("{0} <{1}-{2}>", ConvertSymbolsAndStuff(selectedChld.value), accPrefix, roch.appid); // value and accesory ID - //string AccPageID = string.Format("{0} {1}", ConvertSymbolsAndStuff(selectedChld.value), string.Format(@"#Link:ReferencedObject: {0} {1}", roch.roid, _MyROFST.MyRODb.RODbID)); // value and link reference - //if (MessageBox.Show(AccPageID,"Place on Windows Clipboard?",MessageBoxButtons.YesNo) == DialogResult.Yes) - // Clipboard.SetText(AccPageID); // 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 @@ -697,23 +971,28 @@ namespace Volian.Controls.Library // 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 = (roch.roid.Length <= 12) ? roch.roid + "0000" : roch.roid; - string linktxt = string.Format(@"#Link:ReferencedObject: {0} {1}", padroid, _MyROFST.MyRODb.RODbID); + string linktxt = string.Format(@"#Link:ReferencedObject: {0} {1}", padroid, _myROFST.MyRODb.RODbID); // Resolve symbols and scientific notation in the RO return value - string valtxt = _MyROFST.GetROFSTLookup(Mydvi).GetTranslatedRoValue(padroid, MyRTB.MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.ConvertCaretToDelta, MyRTB.MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.UseTildaPoundCharsForSuperSubScriptInROValues); //ConvertSymbolsAndStuff(selectedChld.value); - MyRTB.OnRoInsert(this, new StepRTBRoEventArgs(valtxt, selectedChld.value, linktxt, padroid, _MyROFST.MyRODb.RODbID)); + string valtxt = _myROFSTLookup.GetTranslatedRoValue(padroid, MyRTB.MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.ConvertCaretToDelta, MyRTB.MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.UseTildaPoundCharsForSuperSubScriptInROValues); //ConvertSymbolsAndStuff(selectedChld.value); + MyRTB.OnRoInsert(this, new StepRTBRoEventArgs(valtxt, selectedChld.value, linktxt, padroid, _myROFST.MyRODb.RODbID)); } + btnGoToRO.Enabled = btnSaveRO.Enabled = btnCancelRO.Enabled = btnPreviewRO.Enabled = false; - _SavCurROLink = null; + _savCurROLink = null; CurROLink = null; } } + + ProcessSearch(string.Empty, (int)ROFSTLookup.SearchType.StartsWith); } + private bool CheckROSelection(ROFSTLookup.rochild selectedRO) { bool goodToGo = true; - bool replacingRO = (_SavCurROLink != null); + bool replacingRO = (_savCurROLink != null); string insrpl = (replacingRO) ? "Cannot Replace" : "Cannot Insert"; string errormsg = ""; + switch (selectedRO.type) { case 1: // regular text RO @@ -723,6 +1002,7 @@ namespace Volian.Controls.Library goodToGo = false; } break; + case 2: // table RO if (MyRTB.MyItemInfo.IsFigure) { @@ -736,6 +1016,7 @@ namespace Volian.Controls.Library goodToGo = false; } break; + case 4: // X/Y Plot RO type if (!MyRTB.MyItemInfo.IsAccPages) { @@ -744,6 +1025,7 @@ namespace Volian.Controls.Library goodToGo = false; } break; + case 8: // figure (intergrated graphics) if (!MyRTB.MyItemInfo.IsFigure && !MyRTB.MyItemInfo.IsAccPages) { @@ -753,196 +1035,15 @@ namespace Volian.Controls.Library } break; } + if (!goodToGo) + { FlexibleMessageBox.Show(string.Format("{0} {1}", insrpl, errormsg), (replacingRO) ? "Invalid RO Replacement" : "Invalid RO Insert"); + } + return goodToGo; } - private void btnCancelRO_Click(object sender, EventArgs e) - { - _CurROLink = _SavCurROLink; - btnCancelRO.Enabled = false; - UpdateROTree(); - } - - private void btnPreviewRO_Click(object sender, EventArgs e) - { - if (selectedChld.type == 8) // integrated graphic - { - string fname = selectedChld.value.Substring(0, selectedChld.value.IndexOf('\n')); - int thedot = fname.LastIndexOf('.'); - ROImageInfo tmp = null; - if (thedot == -1 || (thedot != (fname.Length - 4))) - { - tmp = ROImageInfo.GetByROFstID_FileName(MyROFST.ROFstID, fname); - fname += string.Format(".{0}", MyROFST.MyRODb.RODbConfig.GetDefaultGraphicExtension()); - } - if (tmp == null) tmp = ROImageInfo.GetByROFstID_FileName(MyROFST.ROFstID, fname); - if (tmp == null) tmp = MyROFST.GetROImageByFilename(fname, null); - if (tmp !=null) - { - ROImageConfig rc = new ROImageConfig(tmp); - int size = Convert.ToInt32(rc.Image_Size); - PreviewROImage pvROImg = new PreviewROImage(ROImageInfo.Decompress(tmp.Content,size), selectedChld.title); - pvROImg.ShowDialog(); - } - else - FlexibleMessageBox.Show(string.Format("Cannot Find Image Data: {0}, {1}", MyROFST.ROFstID, fname)); - } - else if (selectedChld.type == 2) // table - { - PreviewMultiLineRO pmlROTable = new PreviewMultiLineRO(selectedChld.value, selectedChld.title); - pmlROTable.ShowDialog(); - } - else if (selectedChld.type == 4) // x/y plot - { -/* - //PreviewMultiLineRO pmlROTable = new PreviewMultiLineRO(selectedChld.value, selectedChld.title); - //pmlROTable.ShowDialog(); // This will show the graph commands - this.Cursor = Cursors.WaitCursor; - // TemporaryFolder is magical. It will automatically (behind the scenes) build a path to a temporary - // folder on the user's machine. It does this only the first time it's reference (GET), after that - // it uses what it has. - string pdfname = TemporaryFolder; //@"G:\debugdat\testplot\"; - pdfname += "\\" + selectedChld.appid + ".pdf"; - //if (File.Exists(pdfname)) - // File.Delete(pdfname); - XYPlot ROGraph = new XYPlot(selectedChld.value); - VGOut_C1PDF pdf = VGOut_C1PDF.Create(); - ROGraph.Process(pdf); - pdf.Save(pdfname); - this.Cursor = Cursors.Default; - - // Run an internet browser window - WebBrowser wb = new WebBrowser(pdfname); - wb.TitleText = selectedChld.title; - wb.ShowDialog();// .Show(); - - // Run the default PDF reader - //System.Diagnostics.Process ActRdr = System.Diagnostics.Process.Start(pdfname); - //ActRdr.WaitForExit(); - - // Wait for the PDF viewing process to close then delete the temporary file - // wait for a one minute max - if (!WaitToDeleteFile(pdfname,1)) - MessageBox.Show(string.Format("The PDF viewer was holding this file open: \n\n{0}",pdfname),"Cannot Delete Temporary File"); -*/ - frmXYPlot plot = new frmXYPlot(selectedChld.appid + " - " + selectedChld.title, selectedChld.value); - plot.Show(); - } - } - private void ProgressBar_Initialize(int max, string desc) - { - if (_ProgressBar != null) - { - _ProgressBar.Maximum = max; - _ProgressBar.Text = desc; - _ProgressBar.TextVisible = true; - } - } - - private void ProgressBar_SetValue(int curval) - { - if (_ProgressBar != null) - { - _ProgressBar.Value = curval; - } - } - - private void ProgressBar_Clear() - { - if (_ProgressBar != null) - { - _ProgressBar.Text = ""; - _ProgressBar.Maximum = 0; - _ProgressBar.Value = 0; - //_ProgressBar.TextVisible = false; // B2017-125 text in progress was not alway being displayed - } - } - - #region Utils - /// - /// Keep trying to delete the given file until successful OR until MaxMinutes has elasped - /// - /// File to delete (including path) - /// Maxium Minutes to keep trying - /// - private static bool WaitToDeleteFile(string fname, int MaxMinutes) - { - bool deletedfile = false; - DateTime dt_start = DateTime.Now; - DateTime dt_loop = dt_start; - int mins_start = dt_start.Minute; - int mins_loop = dt_loop.Minute; - while (!deletedfile && ((mins_loop - mins_start) < MaxMinutes)) - { - try - { - dt_loop = DateTime.Now; - File.Delete(fname); - deletedfile = true; - } - catch - { - continue; // The process is still holding file, try again. - } - } - return deletedfile; - } - - #endregion // utils - - private string _SelectedRoidBeforeRoEditor = null; - private void lbROId_DoubleClick(object sender, EventArgs e) - { - if (tvROFST.SelectedNode == null) return; - if (!UserInfo.CanEditROs(MyUserInfo, Mydvi)) return; // do not allow writers and reviews to run the RO Editor - if (VlnSettings.ReleaseMode.Equals("DEMO")) - { - FlexibleMessageBox.Show("Referenced Object Editor not available in the Demo version.", "PROMS Demo Version"); - return; - } - //string roapp = Environment.GetEnvironmentVariable("roapp"); - string roapp = Volian.Base.Library.ExeInfo.GetROEditorPath(); // get the path to the RO Editor Executable - Object obj = tvROFST.SelectedNode.Tag; - if (obj is ROFSTLookup.rochild) - { - ROFSTLookup.rochild roch = (ROFSTLookup.rochild)obj; - _SelectedRoidBeforeRoEditor = roch.roid; - string args = "\"" + _MyROFST.MyRODb.FolderPath + "\" " + roch.roid.ToLower(); - // C2017-003: ro data in sql server, check for sql connection string - if (_MyROFST.MyRODb.DBConnectionString != "cstring") args = args + " \"" + _MyROFST.MyRODb.DBConnectionString + "\""; - // C2021-026 pass in Parent/Child information (list of the children) - // B2022-019 look at all DocVersions to find ParentChild information - // to ensure we pass in Parent/Child even when not coming from a Parent/Child procedure set - DocVersionInfoList dvil = DocVersionInfoList.Get(); - foreach (DocVersionInfo dvi in dvil) - { - DocVersionConfig dvc = dvi.DocVersionConfig as DocVersionConfig; - if (dvc != null && dvc.Unit_Name != "" && dvc.Unit_Name != "0") - args += " \"PC=" + dvc.Unit_Name + "\""; - break; - } - System.Diagnostics.Process.Start(roapp, args); - } - } - #endregion - - private void lbFound_SelectedValueChanged(object sender, EventArgs e) - { - ROFSTLookup.roChild child = lbFound.SelectedValue as ROFSTLookup.roChild; - if (child != null) - { - ExpandTree(child.MyChild.roid); - } - } - - private void btnGoToRO_Click(object sender, EventArgs e) - { - if (tvROFST.SelectedNode == null) return; - RunRoEditor(); - } - private void RunRoEditor() { if (VlnSettings.ReleaseMode.Equals("DEMO")) @@ -950,81 +1051,92 @@ namespace Volian.Controls.Library FlexibleMessageBox.Show("Referenced Object Editor not available in the Demo version.", "PROMS Demo Version"); return; } - //string roapp = Environment.GetEnvironmentVariable("roapp"); + + string roapp = Volian.Base.Library.ExeInfo.GetROEditorPath(); // get the path to the RO Editor Executable Object obj = tvROFST.SelectedNode.Tag; + if (obj is ROFSTLookup.rochild) { ROFSTLookup.rochild roch = (ROFSTLookup.rochild)obj; - _SelectedRoidBeforeRoEditor = roch.roid; - string args = "\"" + _MyROFST.MyRODb.FolderPath + "\" " + roch.roid.ToLower(); - if (!Directory.Exists(_MyROFST.MyRODb.FolderPath)) + _selectedRoidBeforeRoEditor = roch.roid; + string args = "\"" + _myROFST.MyRODb.FolderPath + "\" " + roch.roid.ToLower(); + + if (!Directory.Exists(_myROFST.MyRODb.FolderPath)) { - FlexibleMessageBox.Show(string.Format("RO Database directory does not exist: {0}", _MyROFST.MyRODb.FolderPath)); + FlexibleMessageBox.Show(string.Format("RO Database directory does not exist: {0}", _myROFST.MyRODb.FolderPath)); return; } + // C2017-003: ro data in sql server, check for sql connection string - if (_MyROFST.MyRODb.DBConnectionString != "cstring") args = args + " \"" + _MyROFST.MyRODb.DBConnectionString + "\""; + if (_myROFST.MyRODb.DBConnectionString != "cstring") args = args + " \"" + _myROFST.MyRODb.DBConnectionString + "\""; // C2021-026 pass in Parent/Child information (list of the children) // B2022-019 look at all DocVersions to find ParentChild information // to ensure we pass in Parent/Child even when not coming from a Parent/Child procedure set + DocVersionInfoList dvil = DocVersionInfoList.Get(); + foreach (DocVersionInfo dvi in dvil) { - DocVersionConfig jdvc = dvi.DocVersionConfig as DocVersionConfig; - if (jdvc != null && jdvc.Unit_Name != "" && jdvc.Unit_Name!= "0") + DocVersionConfig jdvc = dvi.DocVersionConfig; + + if (jdvc != null && jdvc.Unit_Name != "" && jdvc.Unit_Name != "0") + { args += " \"PC=" + jdvc.Unit_Name + "\""; + } + break; } + System.Diagnostics.Process.Start(roapp, args); } } - private void tvROFST_DoubleClick(object sender, EventArgs e) + private void ProcessSearch(string searchValue, int searchTypeID) { - // B2016-132: don't process a double click on an RO if on an enhanced step: - if (MyRTB != null && MyRTB.MyItemInfo != null && MyRTB.MyItemInfo.IsEnhancedStep) return; - //if (tvROFST.SelectedNode == null) return; - //RunRoEditor(); - SaveRO(); - } - public void SetFindDocROButton(bool enabled) - { - this.btnFindDocRO.Enabled = enabled; - } + lbFound.SelectedValueChanged -= new EventHandler(lbFound_SelectedValueChanged); - // C2016-044: support click of the 'Find Doc RO' button: - private void btnFindDocRO_Click(object sender, EventArgs e) - { - DisplayTabItem dti = _TabControl==null?null:_TabControl.SelectedDisplayTabItem; - if (dti != null && dti.MyDSOTabPanel != null) + if (!string.IsNullOrEmpty(searchValue)) { - // the currently selected tab control is a word document - see if it has an - // active selection. If not, tell the user that text needs to be selected before - // the ro can be found. - string mytext = dti.MyDSOTabPanel.GetSelectedString(); - if (mytext == null || mytext == "") + Dictionary dicRoVals = new Dictionary(); + + searchValue = searchValue.Replace('\u2011', '-').Replace(@"\u9586?", @"\\"); + + if (MyROFST != null && searchValue.Length >= 2) { - FlexibleMessageBox.Show(this, "Text must be selected in the document in order for an RO find to be performed.", "Select Text", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); - return; + dicRoVals = new ROFSTLookup(MyROFST.ROFstID, MyDvi).Search(searchValue, searchTypeID, MaxNumSearchRecords); + } + + if (dicRoVals != null && dicRoVals.Count > 0) + { + lbFound.DataSource = new BindingSource(dicRoVals, null); + lbFound.ValueMember = "Key"; // roid + lbFound.DisplayMember = "Value"; // default value + + lbFound.SelectionMode = SelectionMode.One; + lbFound.SelectedIndex = -1; + lbFound.Visible = true; } else { - // see if there are any ro's for the selected text & if so, display in the lbFound list: - string lookFor = mytext.Replace('\u2011', '-').Replace(@"\u9586?", @"\\"); - List children = null; - if (_MyROFST != null) children = _MyROFST.GetROFSTLookup(Mydvi).GetRosByValue(lookFor); - if (children != null) - { - lbFound.Visible = true; - lbFound.DataSource = children.ToArray(); - lbFound.SelectionMode = SelectionMode.One; - lbFound.SelectedIndex = -1; - } - else - lbFound.Visible = false; + lbFound.DataSource = null; + lbFound.Visible = false; } } + else + { + lbFound.DataSource = null; + lbFound.Visible = false; + } + + lbFound.SelectedValueChanged += new EventHandler(lbFound_SelectedValueChanged); + + if (lbFound.Items != null && lbFound.Items.Count == 1) + lbFound.SelectedIndex = 0; + + _lastSearchValue = searchValue; } + + #endregion } } diff --git a/PROMS/Volian.Controls.Library/DisplayReports.cs b/PROMS/Volian.Controls.Library/DisplayReports.cs index c86f98b9..3cbfc221 100644 --- a/PROMS/Volian.Controls.Library/DisplayReports.cs +++ b/PROMS/Volian.Controls.Library/DisplayReports.cs @@ -17,20 +17,40 @@ namespace Volian.Controls.Library { public partial class DisplayReports : UserControl { - #region Events + #region Public Events/Handlers + public event DisplayReportsEvent PrintRequest; + private void OnPrintRequest(DisplayReportsEventArgs args) { if (PrintRequest != null) PrintRequest(this, args); } + #endregion + + #region Fields + + // B2022-026 RO Memeory reduction logic change - defined dummy node text variable to ensure consistancy + private const string DummyNodeText = "VLN_DUMMY_NODE"; + private List lstCheckedDocVersions = new List(); private List lstCheckedROs = new List(); private List lstReportResults = new List(); private List ROList = new List(); private List lstROObj = new List(); private int _MyRODbID; + + private DocVersionInfo _MyDocVersion; + private ROFSTLookup _MyROFSTLookup; + private ItemInfoList _ReportResult; + private Dictionary AccIDROIDdic = new Dictionary(); + static int blankKeyCnt = 0; + + #endregion + + #region Properties + private string DocVersionList { get @@ -49,13 +69,14 @@ namespace Volian.Controls.Library return ""; } } - private DocVersionInfo _MyDocVersion; + public DocVersionInfo Mydocversion { get { return _MyDocVersion; } set { if (DesignMode) return; // B2019-043 need to check if we are just saving changes to the user interface + _MyDocVersion = value; if (_MyDocVersion != null) { @@ -69,13 +90,14 @@ namespace Volian.Controls.Library _MyDocVersion.RefreshDocVersionAssociations(); if (_MyDocVersion.DocVersionAssociations.Count == 0) return; } + MyROFSTLookup = _MyDocVersion.DocVersionAssociations[0].MyROFst.GetROFSTLookup(_MyDocVersion); _MyRODbID = _MyDocVersion.DocVersionAssociations[0].MyROFst.RODbID; } } } } - private ROFSTLookup _MyROFSTLookup; + public ROFSTLookup MyROFSTLookup { get { return _MyROFSTLookup; } @@ -89,7 +111,6 @@ namespace Volian.Controls.Library } } - private ItemInfoList _ReportResult; public ItemInfoList ReportResult { get { return _ReportResult; } @@ -99,315 +120,76 @@ namespace Volian.Controls.Library } } - private Dictionary AccIDROIDdic = new Dictionary(); + #endregion - private void GenerateAccIDSortedROList() - { - //Dictionary AccIDROIDdic = new Dictionary(); - List AccPgIDsList = new List(); - AccIDROIDdic.Clear(); - string rtnStr = ""; - ROFSTLookup.rochild[] chld = null; - ROFSTLookup.rochild ch; - ROList.Clear(); - foreach (object rolkup in lstCheckedROs) - { - if (rolkup == null) // All Referenced Objects selected, return list of RO databases - { - foreach (ROFSTLookup.rodbi rodbi in _MyROFSTLookup.GetRODatabaseList()) - { - rtnStr = _MyRODbID.ToString() + ":" + string.Format("{0}", rodbi.dbiID.ToString("X4")); - //ROList.Add(rtnStr); - if (rodbi.children != null) - foreach (ROFSTLookup.rochild roc in rodbi.children) - PutROChildrenInDictionary(_MyRODbID.ToString() + ":", roc); - else - ROList.Add(rtnStr); - } - continue; - } - else if (rolkup is ROFSTLookup.rodbi) - { - //rtnStr = _MyRODbID.ToString() + ":" + string.Format("{0}", ((ROFSTLookup.rodbi)rolkup).dbiID.ToString("X4")); - ROFSTLookup.rodbi rodbi = (ROFSTLookup.rodbi)rolkup; - if (rodbi.children != null) - foreach (ROFSTLookup.rochild roc in rodbi.children) - PutROChildrenInDictionary(_MyRODbID.ToString() + ":", roc); - else - ROList.Add(_MyRODbID.ToString() + ":"+ string.Format("{0}",rodbi.dbiID.ToString("X4"))); - } - else if (rolkup is ROFSTLookup.rochild) - { - ch = (ROFSTLookup.rochild)rolkup; - chld = ch.children; - //rtnStr = _MyRODbID.ToString() + ":" + GetROChildren(rolkup).TrimEnd(','); - PutROChildrenInDictionary(_MyRODbID.ToString() + ":", rolkup); - } - //else if (rolkup is ROFSTLookup.rogrp) - // Console.WriteLine("RO Group"); - //else if (rolkup is ROFSTLookup.roHdr) - // Console.WriteLine("RO Header"); - //ROList.Add(rtnStr); - } - foreach (string k in AccIDROIDdic.Keys) - AccPgIDsList.Add(k); - string[] AccPgIdListArray = AccPgIDsList.ToArray(); - Array.Sort(AccPgIdListArray, new AlphanumComparatorFast()); - foreach (string accid in AccPgIdListArray) - ROList.Add(AccIDROIDdic[accid]); - } - static int blankKeyCnt = 0; - private string GetNextBlankKey() - { - return string.Format(" _{0}", blankKeyCnt++); - } - private void PutROChildrenInDictionary(string rodbidPrefix, object roObj) - { - ROFSTLookup.rochild chld = (ROFSTLookup.rochild)roObj; - string rtnstr = rodbidPrefix;// ""; - string keystr = ((chld.appid == "") ? GetNextBlankKey() : chld.appid) + chld.roid.Substring(0,4); - if (chld.children == null) // get a single ROID - { - rtnstr = rodbidPrefix + string.Format("{0}", chld.roid); - if (rtnstr.Length == 12) rtnstr += "0000"; // last four digits are used for multiple return values - AccIDROIDdic.Add(keystr, rtnstr); - } - else if (!cbxROUsage.Checked && chld.children[0].ParentID == 0) - { - rtnstr = rodbidPrefix + string.Format("{0},", chld.roid); // doing a RO Summary or RO Complete report - don't want children that are multiple return values - AccIDROIDdic.Add(keystr, rtnstr); - } - else - { // spin through the child list and get the ROIDs. - // if the child has children, then call this function recursivly - foreach (ROFSTLookup.rochild roc in chld.children) - { - // Don't get the children if we are doing a RO Summary or RO Complete report & children are the multiple return values - if (roc.children != null && (cbxROUsage.Checked || roc.children[0].ParentID != 0)) - PutROChildrenInDictionary(rodbidPrefix, roc); - else if (roc.appid != null && roc.appid != "") - { - rtnstr = rodbidPrefix + string.Format("{0}", roc.roid); - keystr = ((roc.appid == "") ? GetNextBlankKey() : roc.appid) + chld.roid.Substring(0, 4); - if (AccIDROIDdic.ContainsKey(keystr)) // For duplicates, append the parent title (B2017-011) so adding to dictionary doesn't crash. - { - keystr = keystr + "|" + chld.title; - } - AccIDROIDdic.Add(keystr, rtnstr); - } - } - } - } + #region Constructors - private void GenerateROList() - { - string rtnStr = ""; - ROFSTLookup.rochild[] chld = null; - ROFSTLookup.rochild ch; - ROList.Clear(); - foreach (object rolkup in lstCheckedROs) - { - if (rolkup == null) // All Referenced Objects selected, return list of RO databases - { - foreach (ROFSTLookup.rodbi rodbi in _MyROFSTLookup.GetRODatabaseList()) - { - rtnStr = _MyRODbID.ToString() + ":" + string.Format("{0}", rodbi.dbiID.ToString("X4")); - ROList.Add(rtnStr); - } - continue; - } - else if (rolkup is ROFSTLookup.rodbi) - rtnStr = _MyRODbID.ToString() + ":" + string.Format("{0}", ((ROFSTLookup.rodbi)rolkup).dbiID.ToString("X4")); - else if (rolkup is ROFSTLookup.rochild) - { - ch = (ROFSTLookup.rochild)rolkup; - chld = ch.children; - rtnStr = _MyRODbID.ToString() + ":" + GetROChildren(rolkup).TrimEnd(','); - } - //else if (rolkup is ROFSTLookup.rogrp) - // Console.WriteLine("RO Group"); - //else if (rolkup is ROFSTLookup.roHdr) - // Console.WriteLine("RO Header"); - ROList.Add(rtnStr); - } - } - - // same function as GetROsToSearch in DisplaySearch.cs - private string GetROChildren(object roObj) - { - ROFSTLookup.rochild chld = (ROFSTLookup.rochild)roObj; - string rtnstr = ""; - if (chld.children == null) // get a single ROID - { - rtnstr += string.Format("{0}", chld.roid); - if (rtnstr.Length == 12) rtnstr += "0000"; // last four digits are used for multiple return values - } - else if (!cbxROUsage.Checked && chld.children[0].ParentID == 0) - { - rtnstr += string.Format("{0},", chld.roid); // doing a RO Summary or RO Complete report - don't want children that are multiple return values - } - else - { // spin through the child list and get the ROIDs. - // if the child has children, then call this function recursivly - foreach (ROFSTLookup.rochild roc in chld.children) - { - // Don't get the children if we are doing a RO Summary or RO Complete report & children are the multiple return values - if (roc.children != null && (cbxROUsage.Checked || roc.children[0].ParentID != 0)) - rtnstr += GetROChildren(roc); - else - rtnstr += string.Format("{0},", roc.roid); - } - } - return rtnstr; - } - private string GetListOfROs(bool keepRODbID) - { - string rtnStr = ""; - string strRODbID = ""; - int cnt = 0; - foreach (string rostr in ROList) - { - int ndxOf = rostr.IndexOf(":"); - if (ndxOf > 0) - { - string tstr = rostr.Substring(0, ndxOf + 1); - if (tstr != strRODbID && keepRODbID) - { - strRODbID = tstr; - rtnStr += rostr; - } - else - rtnStr += rostr.Substring(ndxOf + 1); - } - else - rtnStr += rostr; - if (rtnStr.EndsWith(",")) rtnStr = rtnStr.Substring(0, rtnStr.Length - 1); - if (++cnt < ROList.Count) - rtnStr += ","; - } - return rtnStr; - } public DisplayReports() { InitializeComponent(); EnableOrDisablePrintButton(); + cmbxROUsageSort.SelectedIndex = 0; tabTransitionReports.Visible = false; cbxComplete.Enabled = true; cbxSummary.Enabled = true; + if (cbxROUsage.Checked) cbxIncldMissingROs.Text = "Include Missing ROs (red ? in the editor)"; else if (cbxComplete.Checked) cbxIncldMissingROs.Text = "Include Empty RO Fields"; + cbxIncldMissingROs.Checked = false;// !cbxSummary.Checked; cbxIncldMissingROs.Visible = cbxROUsage.Checked || cbxComplete.Checked; cbxSortBySetpointID.Checked = false; cbxSortBySetpointID.Visible = cbxComplete.Checked || cbxSummary.Checked; } + #endregion + + #region Public Methods + public void SelectReferencedObjectTab() { tabROReports.PerformClick(); } - private void AddSelectedROChildren(DevComponents.AdvTree.NodeCollection chldrn) + public void advTreeROFillIn(bool blSeachTabClicked) { - if (chldrn.Count > 0) + DevComponents.AdvTree.Node topnode = null; + advTreeRO.Nodes.Clear(); + + if (_MyROFSTLookup == null) return; + + advTreeRO.BeforeExpand += new AdvTreeNodeCancelEventHandler(advTreeRO_BeforeExpand); + advTreeRO.AfterExpand += new AdvTreeNodeEventHandler(advTreeRO_AfterExpandorCollapse); + advTreeRO.AfterCollapse += new AdvTreeNodeEventHandler(advTreeRO_AfterExpandorCollapse); + + topnode = new DevComponents.AdvTree.Node(); + topnode.Text = "All Referenced Objects"; + topnode.Tag = null; + topnode.CheckBoxVisible = true; + + advTreeRO.Nodes.Add(topnode); + + ROFSTLookup.rodbi[] dbs = _MyROFSTLookup.GetRODatabaseList(true); + + if (dbs != null && dbs.Length > 0) { - foreach (DevComponents.AdvTree.Node n in chldrn) + for (int i = 0; i < dbs.Length; i++) { - if (n.Checked) - lstCheckedROs.Add(n.Tag); - else - AddSelectedROChildren(n.Nodes); + DevComponents.AdvTree.Node tn = new DevComponents.AdvTree.Node(); + ROFSTLookup.rodbi db = dbs[i]; + + tn.Text = db.dbiTitle; + tn.Tag = db; + tn.CheckBoxVisible = true; + topnode.Nodes.Add(tn); + + AddDummyGroup(db, tn); } } } - private void BuildCheckedROsList() - { - lstCheckedROs.Clear(); - if (advTreeRO.Nodes.Count == 0) return; - DevComponents.AdvTree.Node node = advTreeRO.Nodes[0]; - if (node.Checked) // top node (all Referenced Objects) selected - lstCheckedROs.Add(node.Tag); - else - AddSelectedROChildren(node.Nodes); - } - - private void EnableOrDisablePrintButton() - { - switch (tctrlReports.SelectedTabIndex) - { - case 0: // Transition Reports - btnPrintReport.Enabled = (lstCheckedDocVersions.Count > 0); - break; - case 1: // Referenced Objects Reports - BuildCheckedROsList(); // this list is sent to the report generator - if (cbxROUsage.Checked) - btnPrintReport.Enabled = (lstCheckedDocVersions.Count > 0 && lstCheckedROs.Count > 0); - else - btnPrintReport.Enabled = ((cbxComplete.Checked || cbxSummary.Checked) && lstCheckedROs.Count > 0); - break; - } - if (cbxROUsage.Checked) - cbxIncldMissingROs.Text = "Include Missing ROs (red ? in the editor)"; - else if (cbxComplete.Checked) - cbxIncldMissingROs.Text = "Include Empty RO Fields"; - //cbxIncldMissingROs.Checked = cbxROUsage.Checked || cbxComplete.Checked; - cbxIncldMissingROs.Visible = cbxROUsage.Checked || cbxComplete.Checked; - cbxSortBySetpointID.Visible = cbxComplete.Checked || cbxSummary.Checked; - labelX1.Visible = cmbxROUsageSort.Visible = !cbxSortBySetpointID.Visible; - } - - private void tabTransitionReports_Click(object sender, EventArgs e) - { - xpSetToReport.Enabled = true; - xpSetToReport.Expanded = true; - xpSelROs.Expanded = false; - xpSelROs.Enabled = false; - EnableOrDisablePrintButton(); - } - - private void tabROReports_Click(object sender, EventArgs e) - { - xpSetToReport.Enabled = cbxROUsage.Checked; - xpSetToReport.Expanded = cbxROUsage.Checked; - labelX1.Visible = cmbxROUsageSort.Visible = cbxROUsage.Checked; - xpSelROs.Enabled = true; - xpSelROs.Expanded = true; - cbxIncldMissingROs.Checked = false;// !cbxSummary.Checked; - cbxSortBySetpointID.Checked = false; - cbxSortBySetpointID.Visible = !cbxROUsage.Checked; - EnableOrDisablePrintButton(); - } - - private void cbxROUsage_CheckedChanged(object sender, EventArgs e) - { - xpSetToReport.Enabled = cbxROUsage.Checked; - xpSetToReport.Expanded = cbxROUsage.Checked; - labelX1.Visible = cmbxROUsageSort.Visible = cbxROUsage.Checked; - // reset the RO tree and clear anything that was selected - advTreeROFillIn(true); - lstCheckedROs.Clear(); - cbxIncldMissingROs.Checked = false;// !cbxSummary.Checked; - cbxSortBySetpointID.Checked = false; - cbxSortBySetpointID.Visible = !cbxROUsage.Checked; - EnableOrDisablePrintButton(); - } - #region Procedure List - private DevComponents.AdvTree.Node NewAdvTreeNode(string nodetext, bool selectable, bool chxbxvisable) - { - DevComponents.AdvTree.Node newnode; - newnode = new DevComponents.AdvTree.Node(); - newnode.Text = nodetext; - newnode.Selectable = selectable; - newnode.CheckBoxAlignment = DevComponents.AdvTree.eCellPartAlignment.NearCenter; - newnode.CheckBoxStyle = eCheckBoxStyle.CheckBox; - newnode.CheckBoxThreeState = false; - newnode.CheckBoxVisible = chxbxvisable; - return newnode; - } - public void advTreeProcSetsFillIn(bool blSeachTabClicked) { @@ -448,10 +230,10 @@ namespace Volian.Controls.Library // tmp = topnode.Nodes.Add(newnode); //} cntnd++; - if (fic.ChildFolderCount > 0 || fic.FolderDocVersionCount > 0) // allow for '+' for tree expansion + if (fic.ChildFolderCount > 0 || fic.FolderDocVersionCount > 0) // allow for '+' for tree expansion { DevComponents.AdvTree.Node tnt = new DevComponents.AdvTree.Node(); - tnt.Text = "VLN_DUMMY"; + tnt.Text = DummyNodeText; newnode.Nodes.Add(tnt); topnode.Nodes.Add(newnode); } @@ -479,13 +261,586 @@ namespace Volian.Controls.Library //if (blSeachTabClicked) // cbxTextSearchText.Focus(); // set initial focus to enter search text } - void advTreeProcSets_BeforeExpand(object sender, DevComponents.AdvTree.AdvTreeNodeCancelEventArgs e) + + #endregion + + #region Private Methods + + private void GenerateAccIDSortedROList() + { + //Dictionary AccIDROIDdic = new Dictionary(); + List AccPgIDsList = new List(); + AccIDROIDdic.Clear(); + + string rtnStr = ""; + ROFSTLookup.rochild[] chld = null; + ROFSTLookup.rochild ch; + ROList.Clear(); + + foreach (object rolkup in lstCheckedROs) + { + if (rolkup == null) // All Referenced Objects selected, return list of RO databases + { + foreach (ROFSTLookup.rodbi rodbi in _MyROFSTLookup.GetRODatabaseList(true)) + { + rtnStr = _MyRODbID.ToString() + ":" + string.Format("{0}", rodbi.dbiID.ToString("X4")); + + if (rodbi.children != null) + { + foreach (ROFSTLookup.rochild roc in rodbi.children) + { + PutROChildrenInDictionary(_MyRODbID.ToString() + ":", roc); + } + } + else + { + ROList.Add(rtnStr); + } + } + + continue; + } + else if (rolkup is ROFSTLookup.rodbi) + { + ROFSTLookup.rodbi rodbi = (ROFSTLookup.rodbi)rolkup; + + //Try to lazy load the children - B2022-026 RO Memory Reduction code + if (rodbi.children == null || rodbi.children.Length <= 0) + rodbi.children = MyROFSTLookup.GetRoChildrenByID(rodbi.ID, rodbi.dbiID, true); + + if (rodbi.children != null) + { + foreach (ROFSTLookup.rochild roc in rodbi.children) + { + PutROChildrenInDictionary(_MyRODbID.ToString() + ":", roc); + } + } + else + { + ROList.Add(_MyRODbID.ToString() + ":" + string.Format("{0}", rodbi.dbiID.ToString("X4"))); + } + } + else if (rolkup is ROFSTLookup.rochild) + { + ch = (ROFSTLookup.rochild)rolkup; + chld = ch.children; + + //Try to lazy load the children - B2022-026 RO Memory Reduction code + if (ch.children == null || ch.children.Length <= 0) + ch.children = MyROFSTLookup.GetRoChildrenByRoid(ch.roid, true); + + PutROChildrenInDictionary(_MyRODbID.ToString() + ":", rolkup); + } + } + + foreach (string k in AccIDROIDdic.Keys) + { + AccPgIDsList.Add(k); + } + + string[] AccPgIdListArray = AccPgIDsList.ToArray(); + Array.Sort(AccPgIdListArray, new AlphanumComparatorFast()); + + foreach (string accid in AccPgIdListArray) + { + ROList.Add(AccIDROIDdic[accid]); + } + } + + private string GetNextBlankKey() + { + return string.Format(" _{0}", blankKeyCnt++); + } + + private void PutROChildrenInDictionary(string rodbidPrefix, object roObj) + { + ROFSTLookup.rochild chld = (ROFSTLookup.rochild)roObj; + string rtnstr = rodbidPrefix;// ""; + string keystr = ((chld.appid == "") ? GetNextBlankKey() : chld.appid) + chld.roid.Substring(0,4); + + //Try to lazy load the children - B2022-026 RO Memory Reduction + if (chld.children == null || chld.children.Length <= 0) + chld.children = MyROFSTLookup.GetRoChildrenByRoid(chld.roid, true); + + // If still no children - B2022-026 RO Memory Reduction code - check children length + if (chld.children == null || chld.children.Length <= 0) // get a single ROID + { + rtnstr = rodbidPrefix + string.Format("{0}", chld.roid); + if (rtnstr.Length == 12) rtnstr += "0000"; // last four digits are used for multiple return values + + AccIDROIDdic.Add(keystr, rtnstr); + } + else if (!cbxROUsage.Checked && chld.children[0].ParentID == 0) + { + rtnstr = rodbidPrefix + string.Format("{0},", chld.roid); // doing a RO Summary or RO Complete report - don't want children that are multiple return values + AccIDROIDdic.Add(keystr, rtnstr); + } + else + { + // spin through the child list and get the ROIDs. + // if the child has children, then call this function recursively + for (int i = 0; i < chld.children.Length; i++) + { + ROFSTLookup.rochild roc = chld.children[i]; + + //Try to lazy load the children - B2022-026 RO Memory Reduction code + if (roc.children == null || roc.children.Length <= 0) + roc.children = MyROFSTLookup.GetRoChildrenByRoid(roc.roid, true); + + // Don't get the children if we are doing a RO Summary or RO Complete report & children are the multiple return values + if (roc.children != null && roc.children.Length > 0 && (cbxROUsage.Checked || roc.children[0].ParentID != 0)) + { + PutROChildrenInDictionary(rodbidPrefix, roc); + } + else if (roc.appid != null && roc.appid != "") + { + rtnstr = rodbidPrefix + string.Format("{0}", roc.roid); + keystr = ((roc.appid == "") ? GetNextBlankKey() : roc.appid) + chld.roid.Substring(0, 4); + + if (AccIDROIDdic.ContainsKey(keystr)) // For duplicates, append the parent title (B2017-011) so adding to dictionary doesn't crash. + { + keystr = keystr + "|" + chld.title; + } + + AccIDROIDdic.Add(keystr, rtnstr); + } + } + + } + } + + private void GenerateROList() + { + string rtnStr = ""; + ROFSTLookup.rochild[] chld = null; + ROFSTLookup.rochild ch; + ROList.Clear(); + + foreach (object rolkup in lstCheckedROs) + { + if (rolkup == null) // All Referenced Objects selected, return list of RO databases + { + // B2022-026 RO Memory Reduction code - added flag to load all children + foreach (ROFSTLookup.rodbi rodbi in _MyROFSTLookup.GetRODatabaseList(true)) + { + rtnStr = _MyRODbID.ToString() + ":" + string.Format("{0}", rodbi.dbiID.ToString("X4")); + ROList.Add(rtnStr); + } + continue; + } + else if (rolkup is ROFSTLookup.rodbi) + { + rtnStr = _MyRODbID.ToString() + ":" + string.Format("{0}", ((ROFSTLookup.rodbi)rolkup).dbiID.ToString("X4")); + } + else if (rolkup is ROFSTLookup.rochild) + { + ch = (ROFSTLookup.rochild)rolkup; + + //Try to lazy load the children - B2022-026 RO Memory Reduction code + if (ch.children == null || ch.children.Length <= 0) + ch.children = MyROFSTLookup.GetRoChildrenByRoid(ch.roid, true); + + chld = ch.children; + + rtnStr = _MyRODbID.ToString() + ":" + GetROChildren(rolkup).TrimEnd(','); + } + + ROList.Add(rtnStr); + } + } + + // same function as GetROsToSearch in DisplaySearch.cs + private string GetROChildren(object roObj) + { + ROFSTLookup.rochild chld = (ROFSTLookup.rochild)roObj; + string rtnstr = ""; + + //Try to lazy load the children - B2022-026 RO Memory Reduction code + if (chld.children == null || chld.children.Length <= 0) + chld.children = MyROFSTLookup.GetRoChildrenByRoid(chld.roid, true); + + // If still no children + if (chld.children == null || chld.children.Length <= 0) // get a single ROID + { + rtnstr += string.Format("{0}", chld.roid); + if (rtnstr.Length == 12) rtnstr += "0000"; // last four digits are used for multiple return values + } + else if (!cbxROUsage.Checked && chld.children[0].ParentID == 0) + { + rtnstr += string.Format("{0},", chld.roid); // doing a RO Summary or RO Complete report - don't want children that are multiple return values + } + else + { // spin through the child list and get the ROIDs. + // if the child has children, then call this function recursivly + foreach (ROFSTLookup.rochild roc in chld.children) + { + // Don't get the children if we are doing a RO Summary or RO Complete report & children are the multiple return values + if (roc.children != null && (cbxROUsage.Checked || roc.children[0].ParentID != 0)) + rtnstr += GetROChildren(roc); + else + rtnstr += string.Format("{0},", roc.roid); + } + } + return rtnstr; + } + + private string GetListOfROs(bool keepRODbID) + { + string rtnStr = ""; + string strRODbID = ""; + int cnt = 0; + foreach (string rostr in ROList) + { + int ndxOf = rostr.IndexOf(":"); + if (ndxOf > 0) + { + string tstr = rostr.Substring(0, ndxOf + 1); + if (tstr != strRODbID && keepRODbID) + { + strRODbID = tstr; + rtnStr += rostr; + } + else + rtnStr += rostr.Substring(ndxOf + 1); + } + else + rtnStr += rostr; + if (rtnStr.EndsWith(",")) rtnStr = rtnStr.Substring(0, rtnStr.Length - 1); + if (++cnt < ROList.Count) + rtnStr += ","; + } + return rtnStr; + } + + private void AddSelectedROChildren(DevComponents.AdvTree.NodeCollection chldrn) + { + if (chldrn.Count > 0) + { + foreach (DevComponents.AdvTree.Node n in chldrn) + { + if (n.Checked) + lstCheckedROs.Add(n.Tag); + else + AddSelectedROChildren(n.Nodes); + } + } + } + + private void BuildCheckedROsList() + { + lstCheckedROs.Clear(); + if (advTreeRO.Nodes.Count == 0) return; + + DevComponents.AdvTree.Node node = advTreeRO.Nodes[0]; + if (node.Checked) // top node (all Referenced Objects) selected + lstCheckedROs.Add(node.Tag); + else + AddSelectedROChildren(node.Nodes); + } + + private void EnableOrDisablePrintButton() + { + switch (tctrlReports.SelectedTabIndex) + { + case 0: // Transition Reports + btnPrintReport.Enabled = (lstCheckedDocVersions.Count > 0); + break; + + case 1: // Referenced Objects Reports + BuildCheckedROsList(); // this list is sent to the report generator + if (cbxROUsage.Checked) + btnPrintReport.Enabled = (lstCheckedDocVersions.Count > 0 && lstCheckedROs.Count > 0); + else + btnPrintReport.Enabled = ((cbxComplete.Checked || cbxSummary.Checked) && lstCheckedROs.Count > 0); + break; + } + + if (cbxROUsage.Checked) + cbxIncldMissingROs.Text = "Include Missing ROs (red ? in the editor)"; + else if (cbxComplete.Checked) + cbxIncldMissingROs.Text = "Include Empty RO Fields"; + + //cbxIncldMissingROs.Checked = cbxROUsage.Checked || cbxComplete.Checked; + cbxIncldMissingROs.Visible = cbxROUsage.Checked || cbxComplete.Checked; + cbxSortBySetpointID.Visible = cbxComplete.Checked || cbxSummary.Checked; + labelX1.Visible = cmbxROUsageSort.Visible = !cbxSortBySetpointID.Visible; + } + + private void tabTransitionReports_Click(object sender, EventArgs e) + { + xpSetToReport.Enabled = true; + xpSetToReport.Expanded = true; + xpSelROs.Expanded = false; + xpSelROs.Enabled = false; + + EnableOrDisablePrintButton(); + } + + private void tabROReports_Click(object sender, EventArgs e) + { + xpSetToReport.Enabled = cbxROUsage.Checked; + xpSetToReport.Expanded = cbxROUsage.Checked; + labelX1.Visible = cmbxROUsageSort.Visible = cbxROUsage.Checked; + xpSelROs.Enabled = true; + xpSelROs.Expanded = true; + cbxIncldMissingROs.Checked = false;// !cbxSummary.Checked; + cbxSortBySetpointID.Checked = false; + cbxSortBySetpointID.Visible = !cbxROUsage.Checked; + + EnableOrDisablePrintButton(); + } + + private void cbxROUsage_CheckedChanged(object sender, EventArgs e) + { + xpSetToReport.Enabled = cbxROUsage.Checked; + xpSetToReport.Expanded = cbxROUsage.Checked; + labelX1.Visible = cmbxROUsageSort.Visible = cbxROUsage.Checked; + + // reset the RO tree and clear anything that was selected + advTreeROFillIn(true); + lstCheckedROs.Clear(); + + cbxIncldMissingROs.Checked = false;// !cbxSummary.Checked; + cbxSortBySetpointID.Checked = false; + cbxSortBySetpointID.Visible = !cbxROUsage.Checked; + + EnableOrDisablePrintButton(); + } + + private void DisplayReports_Load(object sender, EventArgs e) + { + tabTransitionReports.PerformClick(); + } + + // when a node is checked (selected) then uncheck any of its children + private void UncheckChildren(DevComponents.AdvTree.NodeCollection chldrn) + { + if (chldrn.Count > 0) + { + foreach (DevComponents.AdvTree.Node n in chldrn) + { + if (n.Checked) + n.Checked = false; + else + UncheckChildren(n.Nodes); + } + } + } + + // when a node is checked (selected), uncheck the parents, grand parents, great grand parents, etc. + private void UncheckParents(DevComponents.AdvTree.Node pNode) + { + while (pNode != null) + { + if (pNode.Checked) pNode.Checked = false; + pNode = pNode.Parent; + } + } + + private void advTreeRO_AfterCheck(object sender, AdvTreeCellEventArgs e) + { + DevComponents.AdvTree.Node n = advTreeRO.SelectedNode; + + if (n.Checked) + { + UncheckChildren(n.Nodes); + UncheckParents(n.Parent); + } + + EnableOrDisablePrintButton(); + } + + private void cbxTransToProcs_CheckedChanged(object sender, EventArgs e) + { + EnableOrDisablePrintButton(); + } + + private void cbxTransFromProcs_CheckedChanged(object sender, EventArgs e) + { + EnableOrDisablePrintButton(); + } + + private void cbxComplete_CheckedChanged(object sender, EventArgs e) + { + cbxIncldMissingROs.Checked = false;// !cbxSummary.Checked; + cbxSortBySetpointID.Checked = false; + EnableOrDisablePrintButton(); + } + + private void cbxSummary_CheckedChanged(object sender, EventArgs e) + { + EnableOrDisablePrintButton(); + } + + private string BuildRODataFile(string ROList) + { + DocVersionInfo MyDVI = Mydocversion; + string roDataFile = "PRINT.TMP"; + + if (VlnSettings.ReleaseMode.Equals("DEMO")) + { + MessageBox.Show("Referenced Object Reports not available in the Demo version.", "PROMS Demo Version"); + return ""; + } + + //string roapp = Environment.GetEnvironmentVariable("roapp"); + string roapp = Volian.Base.Library.ExeInfo.GetROEditorPath(); // get the path to the RO Editor Executable + if (roapp == null) + { + MessageBox.Show("Could not find path to Ro Editor, check 'roapp' environment variable"); + return ""; + } + + if (MyDVI == null || MyDVI.DocVersionAssociationCount < 1) + { + MessageBox.Show("Could not find associated path for ro data.", "No RO Data", MessageBoxButtons.OK, MessageBoxIcon.Information); + return ""; + } + + //string roloc = "\"" + MyDVI.DocVersionAssociations[0].MyROFst.MyRODb.FolderPath + "\" " + "\"" + ROList + "\""; + if (!Directory.Exists(MyDVI.DocVersionAssociations[0].MyROFst.MyRODb.FolderPath)) + { + MessageBox.Show(string.Format("RO Database directory does not exist: {0}", MyDVI.DocVersionAssociations[0].MyROFst.MyRODb.FolderPath)); + return ""; + } + + string cmpRptExePath = roapp.Substring(0, roapp.LastIndexOf("\\")) + "\\CmpRpt.exe "; + roDataFile = MyDVI.DocVersionAssociations[0].MyROFst.MyRODb.FolderPath + "\\" + roDataFile; + + try + { + if (File.Exists(roDataFile)) File.Delete(roDataFile); + Application.DoEvents(); + + string fname = VlnSettings.TemporaryFolder + "\\ROCompleteRprt.txt"; + FileInfo fi = new FileInfo(fname); + using (StreamWriter sw = fi.CreateText()) + { + sw.Write(ROList); + sw.Close(); + } + + string roloc = "\"" + MyDVI.DocVersionAssociations[0].MyROFst.MyRODb.FolderPath + "\" \"/f=" + fname + "\""; + // C2017-003: ro data in sql server, check for sql connection string + if (MyDVI.DocVersionAssociations[0].MyROFst.MyRODb.DBConnectionString != "cstring") roloc = roloc + " \"/sql=" + MyDVI.DocVersionAssociations[0].MyROFst.MyRODb.DBConnectionString + "\""; + + // C2021-026 pass in Parent/Child information (list of the children) + // B2022-019 look at all DocVersions to find ParentChild information + // to ensure we pass in Parent/Child even when not coming from a Parent/Child procedure set + DocVersionInfoList dvil = DocVersionInfoList.Get(); + foreach (DocVersionInfo dvi in dvil) + { + DocVersionConfig dvc = dvi.DocVersionConfig as DocVersionConfig; + if (dvc != null && dvc.Unit_Name != "" && dvc.Unit_Name != "0") + roloc += " \"/PC=" + dvc.Unit_Name + "\""; + break; + } + + System.Diagnostics.Process p = System.Diagnostics.Process.Start(cmpRptExePath, roloc); + // need to wait, sometimes the Print.tmp file that is generated is not available + p.WaitForExit(); // without arguments, this will wait indefinitely + Application.DoEvents(); + } + catch (Exception ex) + { + while (ex.InnerException != null) + ex = ex.InnerException; + string tmpmsg = ex.Message; + MessageBox.Show(tmpmsg, "RO Report Error: " + ex.GetType().Name); + } + return roDataFile; + } + + private void btnPrintReport_Click(object sender, EventArgs e) + { + string paperSize = "Letter"; + + if (Mydocversion != null && Mydocversion.ActiveFormat != null) + paperSize = Mydocversion.ActiveFormat.PlantFormat.FormatData.PDFPageSize.PaperSize; // C2020-002 paper size is now set in the format files + + //B2019-144 Set the document text color to Red (overlay) or Black (normal) + Color lastColor = MSWordToPDF.OverrideColor;// B2019-144 Remember override color + if (MSWordToPDF.OverrideColor != Color.Black) + MSWordToPDF.OverrideColor = Color.Black; + + Cursor curcur = Cursor; + Cursor = Cursors.WaitCursor; + + if (cbxSummary.Checked) // RO Summary Report + { + if (cbxSortBySetpointID.Checked) + GenerateAccIDSortedROList(); + else + GenerateROList(); + + OnPrintRequest(new DisplayReportsEventArgs("RO Summary Report", "RO Summary Report", MyROFSTLookup, ROList, paperSize)); + } + else if (cbxComplete.Checked) // Complete RO Report + { + if (cbxSortBySetpointID.Checked) + GenerateAccIDSortedROList(); + else + GenerateROList(); + + string ROList = GetListOfROs(false);//don't include the RODbID in the RO list + string roDataFile = BuildRODataFile(ROList); + + if (Mydocversion != null) + OnPrintRequest(new DisplayReportsEventArgs("Complete RO Report", "Complete RO Report", roDataFile, MyROFSTLookup, cbxComplete.Checked, Mydocversion.ActiveFormat.PlantFormat.FormatData.SectData.ConvertCaretToDelta, cbxIncldMissingROs.Checked, paperSize)); + } + else if (cbxROUsage.Checked) + { + bool usageSortedByProcedure = (cmbxROUsageSort.SelectedIndex == 1); + GenerateROList(); + string SearchString = GetListOfROs(true);// Include the RODbID in the RO list + ItemInfoList SearchResults = ItemInfoList.GetListFromROReport(DocVersionList, "", SearchString, ""); + + if (!usageSortedByProcedure) // sort on ROs + { + Csla.SortedBindingList sortedResults = new Csla.SortedBindingList(SearchResults); + sortedResults.ApplySort("FoundROID", ListSortDirection.Ascending); + OnPrintRequest(new DisplayReportsEventArgs("Referenced Objects Usage By RO", "RO Usage", sortedResults, usageSortedByProcedure, cbxIncldMissingROs.Checked, paperSize)); + } + else + { + OnPrintRequest(new DisplayReportsEventArgs("Referenced Objects Usage By Procedure", "RO Usage", SearchResults, usageSortedByProcedure, cbxIncldMissingROs.Checked, paperSize)); + } + } + else if (cbxTransFromProcs.Checked) + { + } + else if (cbxTransToProcs.Checked) + { + } + + Cursor = curcur; + //B2019-144 Set the document text color to Red (overlay) or Black (normal) + if (MSWordToPDF.OverrideColor != lastColor)// B2019-144 Restore override color + MSWordToPDF.OverrideColor = lastColor; + } + + #region (Procedure List) + + private DevComponents.AdvTree.Node NewAdvTreeNode(string nodetext, bool selectable, bool chxbxvisable) + { + DevComponents.AdvTree.Node newnode; + newnode = new DevComponents.AdvTree.Node(); + newnode.Text = nodetext; + newnode.Selectable = selectable; + newnode.CheckBoxAlignment = DevComponents.AdvTree.eCellPartAlignment.NearCenter; + newnode.CheckBoxStyle = eCheckBoxStyle.CheckBox; + newnode.CheckBoxThreeState = false; + newnode.CheckBoxVisible = chxbxvisable; + return newnode; + } + + private void advTreeProcSets_BeforeExpand(object sender, DevComponents.AdvTree.AdvTreeNodeCancelEventArgs e) { DevComponents.AdvTree.Node par = e.Node; - // get first child's text, if it has one & if the text is VLN_DUMMY, load children + // get first child's text, if it has one & if the text is "VLN_DUMMY_NODE", load children DevComponents.AdvTree.Node tn = null; if (par.Nodes.Count > 0) tn = par.Nodes[0]; - if (tn.Text == "VLN_DUMMY") // expand this + if (tn.Text == DummyNodeText) // expand this { par.Nodes.Clear(); Object obj = par.Tag; @@ -502,7 +857,7 @@ namespace Volian.Controls.Library if (fic.HasChildren) // allow for '+' for tree expansion { DevComponents.AdvTree.Node tnt = new DevComponents.AdvTree.Node(); - tnt.Text = "VLN_DUMMY"; + tnt.Text = DummyNodeText; newnode.Nodes.Add(tnt); } } @@ -524,6 +879,7 @@ namespace Volian.Controls.Library } } } + private void advTreeProcSets_AfterCheck(object sender, DevComponents.AdvTree.AdvTreeCellEventArgs e) { DevComponents.AdvTree.Node n = advTreeProcSets.SelectedNode; @@ -571,10 +927,12 @@ namespace Volian.Controls.Library //buildSetToSearchPanelTitle(); EnableOrDisablePrintButton(); } + private void advTreeProcSets_AfterNodeSelect(object sender, AdvTreeNodeEventArgs e) { DevComponents.AdvTree.Node n = advTreeProcSets.SelectedNode; } + private void advTreeProcSetsPreSelect() { bool keeplooking = true; @@ -606,6 +964,7 @@ namespace Volian.Controls.Library } } } + private Node LookInTree(NodeCollection monkeys, string bananna) { Node foundit = null; @@ -624,81 +983,21 @@ namespace Volian.Controls.Library } return foundit; } + #endregion - #region RO Tree - public void advTreeROFillIn(bool blSeachTabClicked) - { - DevComponents.AdvTree.Node topnode = null; - advTreeRO.Nodes.Clear(); - if (_MyROFSTLookup == null) return; - advTreeRO.BeforeExpand += new AdvTreeNodeCancelEventHandler(advTreeRO_BeforeExpand); - advTreeRO.AfterExpand += new AdvTreeNodeEventHandler(advTreeRO_AfterExpandorCollapse); - advTreeRO.AfterCollapse += new AdvTreeNodeEventHandler(advTreeRO_AfterExpandorCollapse); - topnode = new DevComponents.AdvTree.Node(); - topnode.Text = "All Referenced Objects"; - topnode.Tag = null; - topnode.CheckBoxVisible = true; - advTreeRO.Nodes.Add(topnode); - for (int i = 0; i < _MyROFSTLookup.myHdr.myDbs.Length; i++) - { - DevComponents.AdvTree.Node tn = new DevComponents.AdvTree.Node(); - tn.Text = _MyROFSTLookup.myHdr.myDbs[i].dbiTitle; - tn.Tag = _MyROFSTLookup.myHdr.myDbs[i]; - tn.CheckBoxVisible = true; - topnode.Nodes.Add(tn); - AddDummyGroup(_MyROFSTLookup.myHdr.myDbs[i], tn); - } - - - //foreach (FolderInfo fic in fi.ChildFolders) - //{ - // DevComponents.AdvTree.Node newnode = new DevComponents.AdvTree.Node(); - // newnode.Text = fic.ToString(); - // newnode.Tag = fic; - - // cntnd++; - // if (fic.ChildFolderCount > 0 || fic.FolderDocVersionCount > 0) // allow for '+' for tree expansion - // { - // DevComponents.AdvTree.Node tnt = new DevComponents.AdvTree.Node(); - // tnt.Text = "VLN_DUMMY"; - // newnode.Nodes.Add(tnt); - // topnode.Nodes.Add(newnode); - // } - //} - - //// if nothing was added to the tree, just put in the node above the docversions... - //if (advTreeProcSets.Nodes.Count == 0) - //{ - // cntnd++; - // fi = Mydocversion.MyFolder; - // topnode = new DevComponents.AdvTree.Node(); - // topnode.Text = fi.ToString(); - // advTreeProcSets.Nodes.Add(topnode); - // topnode.Tag = fi; - //} - - //advTreeProcSets.BeforeExpand += new DevComponents.AdvTree.AdvTreeNodeCancelEventHandler(advTreeProcSets_BeforeExpand); - - //// position to the procedure set in the tree if we have a procedure open - //if (Mydocversion != null) - // advTreeProcSetsPreSelect(); - //else - // advTreeProcSets.Nodes[0].SelectedCell = advTreeProcSets.Nodes[0].Cells[0]; // select the first node - fixes cosmetic problem - - //if (blSeachTabClicked) - // cbxTextSearchText.Focus(); // set initial focus to enter search text - } + #region (RO Tree) private void AddDummyGroup(ROFSTLookup.rodbi rodbi, DevComponents.AdvTree.Node tn) { if (rodbi.children != null && rodbi.children.Length > 0) { DevComponents.AdvTree.Node tmp = new DevComponents.AdvTree.Node(); - tmp.Text = "VLN_DUMMY_FOR_TREE"; + tmp.Text = DummyNodeText; tn.Nodes.Add(tmp); } } + private void advTreeRO_BeforeExpand(object sender, DevComponents.AdvTree.AdvTreeNodeCancelEventArgs e) { LoadChildren(e.Node); @@ -706,19 +1005,31 @@ namespace Volian.Controls.Library private void LoadChildren(DevComponents.AdvTree.Node tn) { + //Check if node has already been loaded + if (tn.HasChildNodes && tn.Nodes[0].Text != DummyNodeText) return; // already loaded. + if (tn.HasChildNodes && tn.Nodes[0].Text == DummyNodeText) tn.Nodes[0].Remove(); + object tag = tn.Tag; - if (tn.HasChildNodes && tn.Nodes[0].Text != "VLN_DUMMY_FOR_TREE") return; // already loaded. - if (tn.HasChildNodes && tn.Nodes[0].Text == "VLN_DUMMY_FOR_TREE") tn.Nodes[0].Remove(); ROFSTLookup.rochild[] chld = null; if (tn.Tag is ROFSTLookup.rodbi) { ROFSTLookup.rodbi db = (ROFSTLookup.rodbi)tn.Tag; + + //Try to lazy load the children - B2022-026 RO Memory Reduction code + if (db.children == null || db.children.Length <= 0) + db.children = MyROFSTLookup.GetRoChildrenByID(db.ID, db.dbiID, true); + chld = db.children; } else if (tn.Tag is ROFSTLookup.rochild) { ROFSTLookup.rochild ch = (ROFSTLookup.rochild)tn.Tag; + + //Try to lazy load the children - B2022-026 RO Memory Reduction code + if (ch.children == null || ch.children.Length <= 0) + ch.children = MyROFSTLookup.GetRoChildrenByRoid(ch.roid, true); + chld = ch.children; } else @@ -726,7 +1037,9 @@ namespace Volian.Controls.Library Console.WriteLine("error - no type"); return; } + // if children, add dummy node + // B2022-026 RO Memory Reduction code - check child length if (chld != null && chld.Length > 0) { //ProgressBar_Initialize(chld.Length, tn.Text); @@ -734,13 +1047,18 @@ namespace Volian.Controls.Library { //ProgressBar_SetValue(i); DevComponents.AdvTree.Node tmp = null; + + // Try to Lazy Load children - B2022-026 RO Memory Reduction code + if (chld[i].children == null || chld[i].children.Length <= 0) + chld[i].children = MyROFSTLookup.GetRoChildrenByRoid(chld[i].roid, true); + // if this is a group, i.e. type 0, add a dummy node if (chld[i].type == 0 && chld[i].children == null) - //skip it. - // TODO: KBR how to handle this? - //Console.WriteLine("ro junk"); + { + // Ignore: Junk Scenario continue; - else if (chld[i].value == null && (cbxROUsage.Checked || chld[i].children[0].ParentID != 0)) + } + else if (chld[i].value == null && (cbxROUsage.Checked || (chld[i].children != null && chld[i].children[0].ParentID != 0))) { tmp = new DevComponents.AdvTree.Node(); tmp.Text = chld[i].title; @@ -749,7 +1067,7 @@ namespace Volian.Controls.Library int index = FindIndex(tn.Nodes, tmp.Text); tn.Nodes.Insert(index, tmp); DevComponents.AdvTree.Node sub = new DevComponents.AdvTree.Node(); - sub.Text = "VLN_DUMMY_FOR_TREE"; + sub.Text = DummyNodeText; tmp.Nodes.Add(sub); } else @@ -763,47 +1081,57 @@ namespace Volian.Controls.Library } } } - //ProgressBar_Clear(); } - void advTreeRO_AfterExpandorCollapse(object sender, AdvTreeNodeEventArgs e) + + private void advTreeRO_AfterExpandorCollapse(object sender, AdvTreeNodeEventArgs e) { Node bottomNode = BottomTreeNode(advTreeRO.Nodes); Node lastNode = advTreeRO.Nodes[advTreeRO.Nodes.Count - 1]; + int top = advTreeRO.Nodes[0].Bounds.Top; int bottom = bottomNode.Bounds.Bottom + 5; int hScrollBarHeight = advTreeRO.HScrollBar != null ? advTreeRO.HScrollBar.Height : 0; bottom = bottomNode.Bounds.Bottom + 5; advTreeRO.Size = new Size(advTreeRO.Size.Width, Math.Min(525, bottom - top + hScrollBarHeight)); + if (advTreeRO.VScrollBar != null && bottom < advTreeRO.Size.Height) { int yLookFor = (bottom - advTreeRO.Size.Height) + 2 * hScrollBarHeight; Node topNode = FindTreeNodeAt(advTreeRO.Nodes, yLookFor); + if (topNode != null) topNode.EnsureVisible(); } } + private Node FindTreeNodeAt(NodeCollection nodes, int y) { foreach (Node node in nodes) { if (node.Bounds.Top <= y && node.Bounds.Bottom >= y) return node; + if (node.Bounds.Top > y) { if (node.PrevNode != null && node.PrevNode.Expanded) return FindTreeNodeAt(node.PrevNode.Nodes, y); + return node; } } return null; } + private Node BottomTreeNode(NodeCollection nodes) { Node bottomNode = nodes[nodes.Count - 1]; // Return bottom node in collection + if (bottomNode.Expanded) // If expanded return bottom child return BottomTreeNode(bottomNode.Nodes); + return bottomNode; } + private int FindIndex(NodeCollection nodes, string value) { int index = 0; @@ -814,305 +1142,146 @@ namespace Volian.Controls.Library } return index; } - //private static Regex _RegExGetNumber = new Regex(@"^ *[+-]?[.,0-9]+(E[+-]?[0-9]+)?"); + private bool GreaterValue(string value1, string value2) { return DisplayRO.GreaterValue(value1, value2); - // Match match1 = _RegExGetNumber.Match(value1); - // Match match2 = _RegExGetNumber.Match(value2); - // if (match1.Success && match2.Success) // Compare the numeric value - // { - // double dbl1 = double.Parse(match1.ToString()); - // double dbl2 = double.Parse(match2.ToString()); - // return dbl1 > dbl2; - // } - // return String.Compare(value1, value2, true) > 0; } - #endregion - private void DisplayReports_Load(object sender, EventArgs e) - { - tabTransitionReports.PerformClick(); - } - - // when a node is checked (selected) then uncheck any of its children - private void UncheckChildren(DevComponents.AdvTree.NodeCollection chldrn) - { - if (chldrn.Count > 0) - { - foreach (DevComponents.AdvTree.Node n in chldrn) - { - if (n.Checked) - n.Checked = false; - else - UncheckChildren(n.Nodes); - } - } - } - // when a node is checked (selected), uncheck the parents, grand parents, great grand parents, etc. - private void UncheckParents(DevComponents.AdvTree.Node pNode) - { - while (pNode != null) - { - if (pNode.Checked) pNode.Checked = false; - pNode = pNode.Parent; - } - } - - private void advTreeRO_AfterCheck(object sender, AdvTreeCellEventArgs e) - { - DevComponents.AdvTree.Node n = advTreeRO.SelectedNode; - if (n.Checked) - { - UncheckChildren(n.Nodes); - UncheckParents(n.Parent); - } - - EnableOrDisablePrintButton(); - } - - private void cbxTransToProcs_CheckedChanged(object sender, EventArgs e) - { - EnableOrDisablePrintButton(); - } - - private void cbxTransFromProcs_CheckedChanged(object sender, EventArgs e) - { - EnableOrDisablePrintButton(); - } - - private void cbxComplete_CheckedChanged(object sender, EventArgs e) - { - cbxIncldMissingROs.Checked = false;// !cbxSummary.Checked; - cbxSortBySetpointID.Checked = false; - EnableOrDisablePrintButton(); - } - - private void cbxSummary_CheckedChanged(object sender, EventArgs e) - { - EnableOrDisablePrintButton(); - } - private string BuildRODataFile(string ROList) - { - DocVersionInfo MyDVI = Mydocversion; - string roDataFile = "PRINT.TMP"; - - if (VlnSettings.ReleaseMode.Equals("DEMO")) - { - MessageBox.Show("Referenced Object Reports not available in the Demo version.", "PROMS Demo Version"); - return ""; - } - //string roapp = Environment.GetEnvironmentVariable("roapp"); - string roapp = Volian.Base.Library.ExeInfo.GetROEditorPath(); // get the path to the RO Editor Executable - if (roapp == null) - { - MessageBox.Show("Could not find path to Ro Editor, check 'roapp' environment variable"); - return ""; - } - if (MyDVI == null || MyDVI.DocVersionAssociationCount < 1) - { - MessageBox.Show("Could not find associated path for ro data.", "No RO Data", MessageBoxButtons.OK, MessageBoxIcon.Information); - return ""; - } - //string roloc = "\"" + MyDVI.DocVersionAssociations[0].MyROFst.MyRODb.FolderPath + "\" " + "\"" + ROList + "\""; - if (!Directory.Exists(MyDVI.DocVersionAssociations[0].MyROFst.MyRODb.FolderPath)) - { - MessageBox.Show(string.Format("RO Database directory does not exist: {0}", MyDVI.DocVersionAssociations[0].MyROFst.MyRODb.FolderPath)); - return ""; - } - string cmpRptExePath = roapp.Substring(0, roapp.LastIndexOf("\\")) + "\\CmpRpt.exe "; - roDataFile = MyDVI.DocVersionAssociations[0].MyROFst.MyRODb.FolderPath + "\\" + roDataFile; - try - { - if (File.Exists(roDataFile)) File.Delete(roDataFile); - Application.DoEvents(); - string fname = VlnSettings.TemporaryFolder + "\\ROCompleteRprt.txt"; - FileInfo fi = new FileInfo(fname); - using (StreamWriter sw = fi.CreateText()) - { - sw.Write(ROList); - sw.Close(); - } - string roloc = "\"" + MyDVI.DocVersionAssociations[0].MyROFst.MyRODb.FolderPath + "\" \"/f=" + fname + "\""; - // C2017-003: ro data in sql server, check for sql connection string - if (MyDVI.DocVersionAssociations[0].MyROFst.MyRODb.DBConnectionString != "cstring") roloc = roloc + " \"/sql=" + MyDVI.DocVersionAssociations[0].MyROFst.MyRODb.DBConnectionString + "\""; - - // C2021-026 pass in Parent/Child information (list of the children) - // B2022-019 look at all DocVersions to find ParentChild information - // to ensure we pass in Parent/Child even when not coming from a Parent/Child procedure set - DocVersionInfoList dvil = DocVersionInfoList.Get(); - foreach (DocVersionInfo dvi in dvil) - { - DocVersionConfig dvc = dvi.DocVersionConfig as DocVersionConfig; - if (dvc != null && dvc.Unit_Name != "" && dvc.Unit_Name != "0") - roloc += " \"/PC=" + dvc.Unit_Name + "\""; - break; - } - - System.Diagnostics.Process p = System.Diagnostics.Process.Start(cmpRptExePath, roloc); - // need to wait, sometimes the Print.tmp file that is generated is not available - p.WaitForExit(); // without arguments, this will wait indefinitely - Application.DoEvents(); - } - catch (Exception ex) - { - while (ex.InnerException != null) - ex = ex.InnerException; - string tmpmsg = ex.Message; - MessageBox.Show(tmpmsg, "RO Report Error: " + ex.GetType().Name); - } - return roDataFile; - } - private void btnPrintReport_Click(object sender, EventArgs e) - { - string paperSize = "Letter"; - if (Mydocversion != null && Mydocversion.ActiveFormat != null) - paperSize = Mydocversion.ActiveFormat.PlantFormat.FormatData.PDFPageSize.PaperSize; // C2020-002 paper size is now set in the format files - //B2019-144 Set the document text color to Red (overlay) or Black (normal) - Color lastColor = MSWordToPDF.OverrideColor;// B2019-144 Remember override color - if (MSWordToPDF.OverrideColor != Color.Black) - MSWordToPDF.OverrideColor = Color.Black; - Cursor curcur = Cursor; - Cursor = Cursors.WaitCursor; - if (cbxSummary.Checked) // RO Summary Report - { - if (cbxSortBySetpointID.Checked) - GenerateAccIDSortedROList(); - else - GenerateROList(); - OnPrintRequest(new DisplayReportsEventArgs("RO Summary Report", "RO Summary Report", MyROFSTLookup, ROList, paperSize)); - } - else if (cbxComplete.Checked) // Complete RO Report - { - if (cbxSortBySetpointID.Checked) - GenerateAccIDSortedROList(); - else - GenerateROList(); - string ROList = GetListOfROs(false);//don't include the RODbID in the RO list - string roDataFile = BuildRODataFile(ROList); - if (Mydocversion != null) - OnPrintRequest(new DisplayReportsEventArgs("Complete RO Report", "Complete RO Report", roDataFile, MyROFSTLookup, cbxComplete.Checked, Mydocversion.ActiveFormat.PlantFormat.FormatData.SectData.ConvertCaretToDelta, cbxIncldMissingROs.Checked, paperSize)); - } - else if (cbxROUsage.Checked) - { - bool usageSortedByProcedure = (cmbxROUsageSort.SelectedIndex == 1); - GenerateROList(); - string SearchString = GetListOfROs(true);// Include the RODbID in the RO list - ItemInfoList SearchResults = ItemInfoList.GetListFromROReport(DocVersionList, "", SearchString, ""); - if (!usageSortedByProcedure) // sort on ROs - { - Csla.SortedBindingList sortedResults = new Csla.SortedBindingList(SearchResults); - sortedResults.ApplySort("FoundROID", ListSortDirection.Ascending); - OnPrintRequest(new DisplayReportsEventArgs("Referenced Objects Usage By RO", "RO Usage", sortedResults, usageSortedByProcedure, cbxIncldMissingROs.Checked, paperSize)); - } - else - OnPrintRequest(new DisplayReportsEventArgs("Referenced Objects Usage By Procedure", "RO Usage", SearchResults, usageSortedByProcedure, cbxIncldMissingROs.Checked, paperSize)); - } - else if (cbxTransFromProcs.Checked) - { - } - else if (cbxTransToProcs.Checked) - { - } - Cursor = curcur; - //B2019-144 Set the document text color to Red (overlay) or Black (normal) - if (MSWordToPDF.OverrideColor != lastColor)// B2019-144 Restore override color - MSWordToPDF.OverrideColor = lastColor; - - } - + #endregion } + + #region DisplayReportsEventArgs Class + public class DisplayReportsEventArgs { + #region Fields + private string _ReportTitle; + private string _TypesSelected; + private ICollection _MyItemInfoList; + private bool _SortUsageByProcedure; + private string _RODataFile = ""; + private bool _CompleteROReport = true; + private ROFSTLookup _rofstLookup; + private List _ROListForReport; + private bool _IncludeMissingROs = true; + private bool _ConvertCaretToDelta = true; + private bool _IncludeEmptyROFields = true; + private string _PaperSize = "Letter"; + + #endregion + + #region Properties + public string ReportTitle { get { return _ReportTitle; } set { _ReportTitle = value; } } - private string _TypesSelected; + public string TypesSelected { get { return _TypesSelected; } set { _TypesSelected = value; } } - private ICollection _MyItemInfoList; + public ICollection MyItemInfoList { get { return _MyItemInfoList; } set { _MyItemInfoList = value; } } - private bool _SortUsageByProcedure; + public bool SortUsageByProcedure { get { return _SortUsageByProcedure; } set { _SortUsageByProcedure = value; } } - private string _RODataFile = ""; + public string RODataFile { get { return _RODataFile; } set { _RODataFile = value; } } - private bool _CompleteROReport = true; + public bool CompleteROReport { get { return _CompleteROReport; } set { _CompleteROReport = value; } } - private ROFSTLookup _rofstLookup; + public ROFSTLookup RofstLookup { get { return _rofstLookup; } set { _rofstLookup = value; } } - private List _ROListForReport; public List ROListForReport { get { return _ROListForReport; } set { _ROListForReport = value; } } - private bool _IncludeMissingROs = true; public bool IncludeMissingROs { get { return _IncludeMissingROs; } set { _IncludeMissingROs = value; } } - private bool _ConvertCaretToDelta = true; public bool ConvertCaretToDelta { get { return _ConvertCaretToDelta; } set { _ConvertCaretToDelta = value; } } - private bool _IncludeEmptyROFields = true; public bool IncludeEmptyROFields { get { return _IncludeEmptyROFields; } set { _IncludeEmptyROFields = value; } } - private string _PaperSize = "Letter"; + public string PaperSize // C2020-002 paper size is now set in the format files { get { return _PaperSize; } set { _PaperSize = value; } } + + #endregion + + #region Constructors + + /// + /// RO Usage Report + /// + /// + /// + /// + /// + /// + /// public DisplayReportsEventArgs(string reportTitle, string typesSelected, ICollection myItemInfoList, bool sortByProcedure, bool includeMissingROs, string paperSize) { - // RO Usage Report _ReportTitle = reportTitle; _TypesSelected = typesSelected; _MyItemInfoList = myItemInfoList; _SortUsageByProcedure = sortByProcedure; _IncludeMissingROs = includeMissingROs; _PaperSize = paperSize; // C2020-002 paper size is now set in the format files - } + + /// + /// RO Complete + /// + /// + /// + /// + /// + /// + /// + /// + /// public DisplayReportsEventArgs(string reportTitle, string typesSelected, string roDataFile, ROFSTLookup rofstLookUp, bool completeROReport, bool convertCaretToDelta, bool includeEmptyROFields, string paperSize) { _ReportTitle = reportTitle; @@ -1124,25 +1293,44 @@ namespace Volian.Controls.Library _IncludeEmptyROFields = includeEmptyROFields; _PaperSize = paperSize; // C2020-002 paper size is now set in the format files } + + /// + /// RO Summary Report + /// + /// + /// + /// + /// + /// public DisplayReportsEventArgs(string reportTitle, string typesSelected, ROFSTLookup rofstLookUp, List roListForReport, string paperSize) { - // RO Summary Report _ReportTitle = reportTitle; _TypesSelected = typesSelected; _rofstLookup = rofstLookUp; _ROListForReport = roListForReport; _PaperSize = paperSize; // C2020-002 paper size is now set in the format files } + + #endregion } + + #endregion + public delegate void DisplayReportsEvent(object sender, DisplayReportsEventArgs args); + + #region AlphanumComparatorFast Class + public class AlphanumComparatorFast : IComparer { - List GetList(string s1) + #region Public Methods + + public List GetList(string s1) { List SB1 = new List(); string st1, st2, st3; st1 = ""; bool flag = char.IsDigit(s1[0]); + foreach (char c in s1) { if (flag != char.IsDigit(c) || !(char.IsDigit(c) || char.IsLetter(c)))// || c == '\'') @@ -1160,15 +1348,11 @@ namespace Volian.Controls.Library { st1 += c; } - - } SB1.Add(st1); return SB1; } - - public int Compare(string x, string y) { string s1 = x;// as string; @@ -1281,18 +1465,8 @@ namespace Volian.Controls.Library return result; } - // sample usage - // List marks = new List(); - // marks.Add("M'00Z1"); - // marks.Add("M'0A27"); - // marks.Add("M'00Z0"); - // marks.Add("0000A27"); - // marks.Add("100Z0"); - - //string[] Markings = marks.ToArray(); - - // Array.Sort(Markings, new AlphanumComparatorFast()); + #endregion } - + #endregion } diff --git a/PROMS/Volian.Controls.Library/DisplaySearch.cs b/PROMS/Volian.Controls.Library/DisplaySearch.cs index 123b8440..fd59441b 100644 --- a/PROMS/Volian.Controls.Library/DisplaySearch.cs +++ b/PROMS/Volian.Controls.Library/DisplaySearch.cs @@ -16,49 +16,42 @@ namespace Volian.Controls.Library { public partial class DisplaySearch : UserControl { - #region Events + #region Public Events/Handlers + public event DisplaySearchEvent PrintRequest; + public event DisplaySearchEvent SearchComplete; + private void OnPrintRequest(DisplaySearchEventArgs args) { if (PrintRequest != null) PrintRequest(this, args); } - public event DisplaySearchEvent SearchComplete; + private void OnSearchComplete(DisplaySearchEventArgs args) { if (SearchComplete != null) SearchComplete(this, args); } + #endregion - #region Properties - // C2020-033: SearchIncTransII represents the item that the transitions go to. It can be either the item the user - // tried to delete or that the user selected to get Incoming Transitions from tree view or ribbon. + + #region Fields + // B2022-026 RO Memeory reduction logic change - defined dummy node text variable to ensure consistancy + private const string DummyNodeText = "VLN_DUMMY_NODE"; + + // B2019-161 When tracking timing time this action + private static VolianTimer _TimeActivity = new VolianTimer("DisplaySearch _TmrRefresh_Tick", 399); + private Timer _TmrRefresh = null; + + public FormatVersionList myFormatVersionList; private ItemInfo _SearchIncTransII = null; - public ItemInfo SearchIncTransII - { - get - { - return _SearchIncTransII; - } - set - { - _SearchIncTransII = value; - if (_SearchIncTransII != null) lblSrchIncTran.Text = _SearchIncTransII.Path; - else lblSrchIncTran.Text = ""; - } - } private static UserInfo _MyUserInfo = null; - public static UserInfo MyUserInfo - { - get { return _MyUserInfo; } - set { _MyUserInfo = value; } - } - private string _strSrchText = ""; + private string _strSrchText = string.Empty; private List lstCheckedDocVersions = new List(); private List lstCheckedStepTypes = new List(); private List lstCheckedStepTypesStr = new List(); private AnnotationDetails _AnnotationDetails = null; - ItemInfo _ItemInfo = null; + public ItemInfo _ItemInfo = null; private DisplayTabControl _TabControl; private DocVersionInfo _MyDocVersion; private Color saveXpSetToSearchColor; @@ -68,56 +61,105 @@ namespace Volian.Controls.Library private Color saveGpFindROsColor; private Color saveGrpPanSearchResults; private ItemInfoList _SearchResults; + + private string _DisplayMember = "SearchPath"; + private bool _OpenDocFromSearch; + private ROFSTLookup _MyROFSTLookup; + private bool _LoadingList = false; + private int LastResultsMouseOverIndex = -1; + private ProgressBarItem _ProgressBar; + + DevComponents.AdvTree.Node wordSectionTreeNode = null; // C2020-010: Disable Word Section choice for Transition search + + private static int _lastRoFstId = -1; + private Dictionary dicSelectedFolderNodes = new Dictionary(); + private Dictionary dicExpandedFolderNodes = new Dictionary(); + private int _TopFolderID = 1; + private bool _ProcessingSelectedValueChanged = false; + + // Search Related Fields + private bool _LastSearchWasAnnotations = false; // B2019-119 only refresh annotation search results if an annotation search was done + + // ProcSetSelection Related Fields + private int _MyRODbID; + private static bool checkingChildren = false; + + // A timer updated the step type tree but if it was loaded from xml the timer update overwrite what + // was loaded in from the xml file. Added a flag that gets set on load and set to false on new Search + private bool _fromLoad = false; + private string _ReportTitle; + private string _SearchString = null; + private string _TypesSelected; + + private bool fromTranCvtBtn = false; + + #endregion + + #region Properties + + // C2020-033: SearchIncTransII represents the item that the transitions go to. It can be either the item the user + // tried to delete or that the user selected to get Incoming Transitions from tree view or ribbon. + public ItemInfo SearchIncTransII + { + get { return _SearchIncTransII; } + set + { + _SearchIncTransII = value; + + if (_SearchIncTransII != null) + lblSrchIncTran.Text = _SearchIncTransII.Path; + else + lblSrchIncTran.Text = string.Empty; + } + } + + public static UserInfo MyUserInfo + { + get { return _MyUserInfo; } + set { _MyUserInfo = value; } + } + public ItemInfoList SearchResults { get { return _SearchResults; } set { if (DesignMode) return; // B2019-043 need to check if we are just saving changes to the user interface + _SearchResults = value; + if (value != null) // Don't select an item from the list when it is updated _SearchResults.ListChanged += new ListChangedEventHandler(_SearchResults_ListChanged); + DisplayResults(); + // B2022-044: don't set selection to top of list (commented out/changed if). Remove event that does this // after results are displayed. Without this, the code in _SearchResults_ListChanged was run upon selections if (value != null) _SearchResults.ListChanged -= new ListChangedEventHandler(_SearchResults_ListChanged); } } - void _SearchResults_ListChanged(object sender, ListChangedEventArgs e) - { - lbSrchResults.SelectedIndex = -1; // Don't select an item from the new list - lbSrchResultsIncTrans.SelectedIndex = -1; - } - - private string _DisplayMember = "SearchPath"; - - //public string Status - //{ - // get { return tsslStatus.Text; } - // set { tsslStatus.Text = value; Application.DoEvents(); } - //} - - private bool _OpenDocFromSearch; public bool OpenDocFromSearch { get { return _OpenDocFromSearch; } - //set { _OpenDocFromSearch = value; } } + public DocVersionInfo Mydocversion { get { return _MyDocVersion; } set { if (DesignMode) return; // B2019-043 need to check if we are just saving changes to the user interface + _MyDocVersion = value; + if (_MyDocVersion != null) { if (_MyDocVersion.DocVersionAssociationCount > 0) { // if the count variable is not consistent with the actual list count, - // do a refresh. There was a bug, B2012-040, that was not reproducable.. + // do a refresh. There was a bug, B2012-040, that was not reproducible.. // so this is an attempt to fix it. if (_MyDocVersion.DocVersionAssociations.Count == 0) { @@ -129,43 +171,201 @@ namespace Volian.Controls.Library } } else + { MyROFSTLookup = null; + } } } - private ROFSTLookup _MyROFSTLookup; public ROFSTLookup MyROFSTLookup { get { return _MyROFSTLookup; } set { if (DesignMode) return; // B2019-043 need to check if we are just saving changes to the user interface + bool beforeIsNotNull = _MyROFSTLookup != null; bool afterIsNotNull = value != null; //if (!Visible) return; // don't reset anything if the form is invisible. - _MyROFSTLookup = value; // define the tree nodes based on this rofst - if(beforeIsNotNull || afterIsNotNull)LoadROComboTree();// B2017-215 Added logic so that database is not accessed during initialization. + _MyROFSTLookup = value; // define the tree nodes based on this rofst + + if (beforeIsNotNull || afterIsNotNull) + { + LoadROComboTree();// B2017-215 Added logic so that database is not accessed during initialization. + } } } - private bool _LoadingList = false; + public bool LoadingList { get { return _LoadingList; } set { _LoadingList = value; } } - private int LastResultsMouseOverIndex = -1; - - private ProgressBarItem _ProgressBar; - public ProgressBarItem ProgressBar { get { return _ProgressBar; } set { _ProgressBar = value; } } + + public Timer TmrRefresh + { + get + { + if (_TmrRefresh == null) + { + _TmrRefresh = new Timer(); + _TmrRefresh.Interval = 1000; + _TmrRefresh.Tick += _TmrRefresh_Tick; + } + return _TmrRefresh; + } + } + + public int TopFolderID + { + get { return _TopFolderID; } + set { _TopFolderID = value; } + } + + public string ReportTitle + { + get { return _ReportTitle; } + set { _ReportTitle = value; } + } + + public string SearchString + { + get { return _SearchString; } + set { _SearchString = value; } + } + + public string TypesSelected + { + get { return _TypesSelected; } + set { _TypesSelected = value; } + } + + #region (Search) + + private string DVISearchList + { + get + { + // append list of document versions to search + if (lstCheckedDocVersions.Count > 0) + { + string strRtnStr = string.Empty; + // get list of doc versions to search + foreach (DocVersionInfo dvi in lstCheckedDocVersions) + { + strRtnStr += string.Format(",{0}", dvi.VersionID.ToString()); + } + return strRtnStr.Substring(1); + } + return string.Empty; + } + } + + private string TypeSearchList + { + get + { + // append list of step types to search + if (lstCheckedStepTypes.Count > 0) + { + string strRtnStr = string.Empty; + // get list of selected types + foreach (int typ in lstCheckedStepTypes) + { + int tmp = typ; + if (tmp == 0) + tmp = 10000; // this is the accessory page type + else + tmp += 20000; // step/substep types + strRtnStr += string.Format(",{0}", tmp); + } + return strRtnStr.Substring(1); + } + + return string.Empty; + } + } + + private string TextSearchString + { + get + { + if (tabSearchTypes.SelectedTab == tabSearchTypes.Tabs[0]) + return ConvertSpecialChars(cbxTextSearchText.Text); + + return string.Empty; + } + } + + private string AnnotationSearchType + { + get + { + if (tabSearchTypes.SelectedTab == tabSearchTypes.Tabs[1]) + return ((AnnotationTypeSearch)cbxAnnoTypes.SelectedValue).ID; + + return string.Empty; + } + } + + private string ROSearchList + { + get + { + if (tabSearchTypes.SelectedTab == tabSearchTypes.Tabs[2]) + { // RO Search + ROFSTLookup.rochild[] chld = null; + ROFSTLookup.rochild ch; + if (cmboTreeROs.SelectedNode != null) + { + if (cbxFndUnLnkROVals.Enabled && cbxFndUnLnkROVals.Checked) + { + ch = (ROFSTLookup.rochild)cmboTreeROs.SelectedNode.Tag; + _strSrchText = string.Format("{0}", ch.value); + return _strSrchText; // append RO Value text to search + } + else + { + if (cmboTreeROs.SelectedNode.Tag is ROFSTLookup.rodbi) + { + ROFSTLookup.rodbi db = (ROFSTLookup.rodbi)cmboTreeROs.SelectedNode.Tag; + return _MyRODbID.ToString() + ":" + string.Format("{0}", db.dbiID.ToString("X4")); + } + else if (cmboTreeROs.SelectedNode.Tag is ROFSTLookup.rochild) + { + ch = (ROFSTLookup.rochild)cmboTreeROs.SelectedNode.Tag; + chld = ch.children; + // build a list of ROs to search + return _MyRODbID.ToString() + ":" + GetROsToSearch(chld); + //return _MyRODbID.ToString() + ":" + ch.roid + "0000," + GetROsToSearch(chld); + //if (strRtnStr.EndsWith(",")) + // strRtnStr = strRtnStr.Substring(0, strRtnStr.Length - 1); + } + } + } + } + return string.Empty; + } + } + + public bool LastSearchWasAnnotations + { + get { return _LastSearchWasAnnotations; } + set { _LastSearchWasAnnotations = value; } + } + #endregion - #region setup + #endregion + + #region Constructor + public DisplaySearch() { InitializeComponent(); @@ -189,7 +389,17 @@ namespace Volian.Controls.Library //SetupContextMenu(); // so that the symbol list is available without selecting a procedure set or procedure } - void tabSearchTypes_SelectedTabChanged(object sender, TabStripTabChangedEventArgs e) + #endregion + + #region Public Methods + + public void _SearchResults_ListChanged(object sender, ListChangedEventArgs e) + { + lbSrchResults.SelectedIndex = -1; // Don't select an item from the new list + lbSrchResultsIncTrans.SelectedIndex = -1; + } + + public void tabSearchTypes_SelectedTabChanged(object sender, TabStripTabChangedEventArgs e) { if(wordSectionTreeNode != null) //B2020-070 NULL reference check wordSectionTreeNode.Enabled = true; @@ -273,7 +483,7 @@ namespace Volian.Controls.Library } } - void cbxTranFormat_SelectedIndexChanged(object sender, EventArgs e) + public void cbxTranFormat_SelectedIndexChanged(object sender, EventArgs e) { #region 1st cut //if (cbxTranFormat.SelectedItem.ToString() == "All") @@ -300,6 +510,7 @@ namespace Volian.Controls.Library // cbxTranCategory.SelectedIndex = 0; //} #endregion + #region 2nd cut if (cbxTranFormat.SelectedItem.ToString().Contains("{Proc")) { @@ -319,28 +530,11 @@ namespace Volian.Controls.Library cbxTranCategory.SelectedIndex = 0; } #endregion + btnSearch.Enabled = true; // B2017-038 enable search button if when a format selected } - FormatVersionList myFormatVersionList; - private void LoadSearchTextListBox() - { - // Setup SearchText Combo - cbxTextSearchText.Items.Clear(); - if (Properties.Settings.Default["SearchList"] != null && Properties.Settings.Default.SearchList.Count > 0) - { - foreach (string str in Properties.Settings.Default.SearchList) - cbxTextSearchText.Items.Add(str); - } - // Setup SearchAnnotation Combo - cbxTextSearchAnnotation.Items.Clear(); - if (Properties.Settings.Default["SearchAList"] != null && Properties.Settings.Default.SearchAList.Count > 0) - { - foreach (string str in Properties.Settings.Default.SearchAList) - cbxTextSearchAnnotation.Items.Add(str); - } - } - void cbxTranVersion_SelectedIndexChanged(object sender, EventArgs e) + public void cbxTranVersion_SelectedIndexChanged(object sender, EventArgs e) { this.Cursor = Cursors.WaitCursor; string versionList = string.Empty; @@ -409,56 +603,56 @@ namespace Volian.Controls.Library this.Cursor = Cursors.Default; } - private DevComponents.AdvTree.Node NewAdvTreeNode(string nodetext, bool selectable, bool chxbxvisable) + // C2020-033: Update the search panel for Incoming transitions. This gets called from the tree view & the ribbon + public void UpdateSearchIncTransResults() { - DevComponents.AdvTree.Node newnode; - newnode = new DevComponents.AdvTree.Node(); - newnode.Text = nodetext; - newnode.Selectable = selectable; - AddCheckBox(chxbxvisable, newnode);//C2016-045 Allow Folders to be selected. - return newnode; - } - //C2016-045 Allow Folders to be selected. - private void AddCheckBox(bool chxbxvisable, DevComponents.AdvTree.Node newnode) - { - newnode.CheckBoxAlignment = DevComponents.AdvTree.eCellPartAlignment.NearCenter; - newnode.CheckBoxStyle = eCheckBoxStyle.CheckBox; - newnode.CheckBoxThreeState = false; - newnode.CheckBoxVisible = chxbxvisable; - // Set newnode.Checked = parent.Checked - if(newnode.Parent != null) - newnode.Checked = newnode.Parent.Checked; - } - private Timer _TmrRefresh = null; - public Timer TmrRefresh - { - get - { - if (_TmrRefresh == null) - { - _TmrRefresh = new Timer(); - _TmrRefresh.Interval = 1000; - _TmrRefresh.Tick += _TmrRefresh_Tick; - } - return _TmrRefresh; - } - } - // B2019-161 When tracking timing time this action - private static VolianTimer _TimeActivity = new VolianTimer("DisplaySearch _TmrRefresh_Tick", 399); + //IncTransSelectedCount = 0; + tabSearchTypes.SelectedTab = tabSearchTypes.Tabs[4]; - // B2016-258 Hang after selecting a procedure if the Step Type panel is open on the search panel - void _TmrRefresh_Tick(object sender, EventArgs e) - { - _TimeActivity.Open(); - TmrRefresh.Enabled = false; - if (!_fromLoad)AdvTreeStepTypesFillIn(); // Don't reload if coming from Load - this overwrites the load settings - _TimeActivity.Close(); + lbSrchResultsIncTrans.DataSource = null; + lbSrchResultsIncTrans.Items.Clear(); + // Get item to do search for, either from tree or from editor + if (SearchIncTransII != null) + { + // B2021-010: Use IncomingTranGetMergedTranList to get a complete list of incoming transitions (transitions to procedure + // were only included if there were NO transitions to items within procedure) + SearchResults = IncomingTranGetMergedTranList(); + ReportTitle = string.Format("Search For Incoming Transitions to {0}: ", SearchIncTransII.Path); + } + if (SearchResults != null && SearchResults.Count > 0) + { + AddMessageForEmptyAnnotations(); + cmbResultsStyle.SelectedIndex = 1; //display step locations in results + DisplayResults(); + } + else + { + btnPrnSrchRslts.Enabled = false; + btnClearSearchResults.Enabled = false; + btnCopySearchResults.Enabled = false; + btnSaveSearchResults.Enabled = false; + cmbResultsStyle.Enabled = false; + if (!fromTranCvtBtn) FlexibleMessageBox.Show("No Matches Found.", "Search"); // B2021-009: Research after convert transitions to text + } + btnTranCvtAllToTxt.Enabled = IncTransCvtAllToTextPerm(); + btnTranCvtSelToTxt.Enabled = false; + btnSearch.Enabled = false; // C2021 - 002: disable search button - no functionality for Incoming Transitions } + + public bool IncTranCvtPerm() + { + FolderInfo topFolder = FolderInfo.Get(1); + FolderConfig fc = topFolder.MyConfig as FolderConfig; + return fc.General_IncTranCvtPerm; + } + + #region (ROFST Combo Tree) + public void StartAdvTreeStepTypesFillIn()// B2016-258 Hang after selecting a procedure if the Step Type panel is open on the search panel { TmrRefresh.Enabled = true; } - DevComponents.AdvTree.Node wordSectionTreeNode = null; // C2020-010: Disable Word Section choice for Transition search + public void AdvTreeStepTypesFillIn() { DevComponents.AdvTree.Node topnode = new DevComponents.AdvTree.Node(); @@ -492,7 +686,7 @@ namespace Volian.Controls.Library //newnode.CheckBoxStyle = eCheckBoxStyle.CheckBox; //newnode.CheckBoxThreeState = false; //newnode.CheckBoxVisible = true; - newnode = NewAdvTreeNode("WORD Sections", true, true); // C2020-010: Change Accessory Sections to Word Sections + newnode = NewAdvTreeNode("WORD Sections", true, true); // C2020-010: Change Accessory Sections to Word Sections wordSectionTreeNode = newnode; // C2021-028: RNO Only search, disable Word section tree node wordSectionTreeNode.Enabled = !(tabSearchTypes.SelectedTab == tabTranSearch || cbxRnoOnly.Checked); @@ -548,7 +742,7 @@ namespace Volian.Controls.Library // Group by High Level Steps, Substeps, Cautions, Notes, Figures, Tables and Equations while (!parentName.Equals("Base") && !parentName.Equals("Substep") && !parentName.Equals("High") && !parentName.Equals("Caution") && !parentName.Equals("Note") && !parentName.Equals("Table") && - !parentName.Equals("Figure") && !parentName.Equals("Title") && + !parentName.Equals("Figure") && !parentName.Equals("Title") && !parentName.Equals("And") && !parentName.Equals("Or") && !parentName.Equals("Paragraph") && !parentName.Equals("Equation")) { StepData tmpsd = (StepData)parnode.Tag; @@ -568,13 +762,7 @@ namespace Volian.Controls.Library } buildStepTypePannelTitle(); } - private int _TopFolderID = 1; - public int TopFolderID - { - get { return _TopFolderID; } - set { _TopFolderID = value; } - } public void advTreeProcSetsFillIn(bool blSeachTabClicked) { DevComponents.AdvTree.Node topnode = null; @@ -601,12 +789,12 @@ namespace Volian.Controls.Library newnode.DataKey = fi.FolderID; AddCheckBox(true, newnode);//C2016-045 Allow Folders to be selected. cntnd++; - if (fic.ChildFolderCount > 0 || fic.FolderDocVersionCount > 0) // allow for '+' for tree expansion + if (fic.ChildFolderCount > 0 || fic.FolderDocVersionCount > 0) // allow for '+' for tree expansion { - if (fic.ChildFolderCount > 0) // B2017-176: Do not display the Working Draft node (don't create dummy for expander) + if (fic.ChildFolderCount > 0) // B2017-176: Do not display the Working Draft node (don't create dummy for expander) { DevComponents.AdvTree.Node tnt = new DevComponents.AdvTree.Node(); - tnt.Text = "VLN_DUMMY"; + tnt.Text = DummyNodeText; newnode.Nodes.Add(tnt); } topnode.Nodes.Add(newnode); @@ -648,27 +836,13 @@ namespace Volian.Controls.Library cbxTextSearchText.Focus(); // set initial focus to enter search text } - //void advTreeProcSets_AfterNodeInsert(object sender, TreeNodeCollectionEventArgs e) - //{ - // IVEDrillDownReadOnly tmp = e.Node.Tag as IVEDrillDownReadOnly; - // if (tmp != null) - // { - // Console.WriteLine("Has Children {0} {1}", tmp.HasChildren, tmp.ToString()); - // FolderInfo fi = tmp as FolderInfo; - // //if (fi != null) - // // Console.WriteLine("dvi Count {0}", fi.FolderDocVersionCount); - // } - // vlnStackTrace.ShowStackLocal(e.Node.Text,1,10); - //} - private Dictionary dicSelectedFolderNodes = new Dictionary(); - private Dictionary dicExpandedFolderNodes = new Dictionary(); - void advTreeProcSets_BeforeExpand(object sender, DevComponents.AdvTree.AdvTreeNodeCancelEventArgs e) + public void advTreeProcSets_BeforeExpand(object sender, DevComponents.AdvTree.AdvTreeNodeCancelEventArgs e) { DevComponents.AdvTree.Node par = e.Node; - // get first child's text, if it has one & if the text is VLN_DUMMY, load children + // get first child's text, if it has one & if the text is "VLN_DUMMY_NODE", load children DevComponents.AdvTree.Node tn = null; if (par.Nodes.Count > 0) tn = par.Nodes[0]; - if (tn.Text == "VLN_DUMMY") // expand this + if (tn.Text == DummyNodeText) // expand this { par.Nodes.Clear(); Object obj = par.Tag; @@ -685,15 +859,15 @@ namespace Volian.Controls.Library par.Nodes.Add(newnode); AddCheckBox(true, newnode);//C2016-045 Allow Folders to be selected. newnode.Enabled = true; - if (fic.ChildFolderCount > 0) // B2017-176: Only expand if folder has folders (not working draft nodes) + if (fic.ChildFolderCount > 0) // B2017-176: Only expand if folder has folders (not working draft nodes) { DevComponents.AdvTree.Node tnt = new DevComponents.AdvTree.Node(); - tnt.Text = "VLN_DUMMY"; + tnt.Text = DummyNodeText; newnode.Nodes.Add(tnt); // B2017-176: Only expand if folder has folders (not working draft nodes): the following was moved from the code // that would check if this should be enabled if seraching for transition types. The transition controls // had a list of associated docversions, so needed to get the docversion in the folder: - if (tabSearchTypes.SelectedTab == tabTranSearch) + if (tabSearchTypes.SelectedTab == tabTranSearch) { if (!dicSelectedFolderNodes.ContainsKey(newnode)) dicSelectedFolderNodes.Add(newnode, false); // get the docversion for this folder, if it has one and determine whether it is enabled for transitions: @@ -707,6 +881,170 @@ namespace Volian.Controls.Library } } } + + public void AdvTree_AfterExpandorCollapse(object sender, AdvTreeNodeEventArgs e) + { + Node bottomNode = BottomTreeNode(cmboTreeROs.AdvTree.Nodes); + Node lastNode = cmboTreeROs.AdvTree.Nodes[cmboTreeROs.AdvTree.Nodes.Count - 1]; + + int top = cmboTreeROs.AdvTree.Nodes[0].Bounds.Top; + int bottom = bottomNode.Bounds.Bottom + 5; + int hScrollBarHeight = cmboTreeROs.AdvTree.HScrollBar != null ? cmboTreeROs.AdvTree.HScrollBar.Height : 0; + bottom = bottomNode.Bounds.Bottom + 5; + cmboTreeROs.AdvTree.Size = new Size(cmboTreeROs.AdvTree.Size.Width, Math.Min(525, bottom - top + hScrollBarHeight)); + + if (cmboTreeROs.AdvTree.VScrollBar != null && bottom < cmboTreeROs.AdvTree.Size.Height) + { + int yLookFor = (bottom - cmboTreeROs.AdvTree.Size.Height) + 2 * hScrollBarHeight; + Node topNode = FindTreeNodeAt(cmboTreeROs.AdvTree.Nodes, yLookFor); + if (topNode != null) + { + topNode.EnsureVisible(); + } + } + } + + #endregion + + #region (Annotation Search) + + public void SetupAnnotationSearch(AnnotationDetails annotationDetails, DisplayTabControl tc) + { + _AnnotationDetails = annotationDetails; + List annoTypes = new List(); + annoTypes.Add(new AnnotationTypeSearch("All Annotations", string.Empty)); + AnnotationTypeInfoList annoList = AnnotationTypeInfoList.Get(); + foreach (AnnotationTypeInfo ati in annoList) + annoTypes.Add(new AnnotationTypeSearch(ati.Name, ati.TypeID.ToString())); + cbxAnnoTypes.DisplayMember = "Name"; + cbxAnnoTypes.DataSource = annoTypes; + lbSrchResults.MouseMove += new MouseEventHandler(lbSrchResults_MouseMove); + _TabControl = tc; + } + + #endregion + + #region (Search Results) + + public void UpdateAnnotationSearchResults() + { + if (!LastSearchWasAnnotations) return; // B2019-119 only refresh annotation search results if an annotation search was done + // B2019-004: update search results list when an annotation is removed. (before bug fix, code method & code below was commented out) + string unitPrefix = string.Empty; + + if (Mydocversion != null) + unitPrefix = Mydocversion.DocVersionConfig.Unit_ProcedureNumber; + + if (unitPrefix.EndsWith("#")) + unitPrefix = unitPrefix.Replace("#", string.Empty); + + SearchResults = ItemInfoList.GetListFromAnnotationSearch(DVISearchList, TypeSearchList, AnnotationSearchType, cbxTextSearchAnnotation.Text, cbxCaseSensitiveAnnoText.Checked, unitPrefix); + + DisplayResults(); + } + + #endregion + + #region (ContextMenu) + + // Changed to a public so that it could be called after the /DB parameter has been processed + public void SetupContextMenu() + { + galSymbols.SubItems.Clear(); + // Bug fix B2014-057 + // if we are searching for a symbol character in all procedure sets MyDocVersion is null + // when MyDocVersion is null, get the symbol list directly from the PROMS base format (BaseAll.xml) + // this will populate the context menu of the Search text entry field so that a symbol can be selected without first selecting a procedure set + FormatData fmtdata = (_MyDocVersion != null) ? _MyDocVersion.ActiveFormat.PlantFormat.FormatData : FormatInfo.PROMSBaseFormat.FormatData; + + if (fmtdata != null && fmtdata.SymbolList != null) + { + SymbolList sl = fmtdata.SymbolList; + + if (sl == null || sl.Count <= 0) + { + FlexibleMessageBox.Show("No symbols are available, check with administrator"); + return; + } + + foreach (Symbol sym in sl) + { + DevComponents.DotNetBar.ButtonItem btnCM = new DevComponents.DotNetBar.ButtonItem(); + + btnCM.Text = string.Format("{0}", (char)sym.Unicode); + // to name button use unicode rather than desc, desc may have spaces or odd chars + btnCM.Name = "btnCM" + sym.Unicode.ToString(); + btnCM.Tooltip = sym.Desc; + btnCM.Tag = string.Format(@"{0}", sym.Unicode); + btnCM.FontBold = true; + btnCM.Click += new System.EventHandler(btnSym_Click); + galSymbols.SubItems.Add(btnCM); + } + } + } + + #endregion + + #region (Refresh Timer) + + public void _TmrRefresh_Tick(object sender, EventArgs e) + { + // B2016-258 Hang after selecting a procedure if the Step Type panel is open on the search panel + _TimeActivity.Open(); + + TmrRefresh.Enabled = false; + if (!_fromLoad) AdvTreeStepTypesFillIn(); // Don't reload if coming from Load - this overwrites the load settings + + _TimeActivity.Close(); + } + + #endregion + + #endregion + + #region Private Methods + + private void LoadSearchTextListBox() + { + // Setup SearchText Combo + cbxTextSearchText.Items.Clear(); + if (Properties.Settings.Default["SearchList"] != null && Properties.Settings.Default.SearchList.Count > 0) + { + foreach (string str in Properties.Settings.Default.SearchList) + cbxTextSearchText.Items.Add(str); + } + // Setup SearchAnnotation Combo + cbxTextSearchAnnotation.Items.Clear(); + if (Properties.Settings.Default["SearchAList"] != null && Properties.Settings.Default.SearchAList.Count > 0) + { + foreach (string str in Properties.Settings.Default.SearchAList) + cbxTextSearchAnnotation.Items.Add(str); + } + } + + private DevComponents.AdvTree.Node NewAdvTreeNode(string nodetext, bool selectable, bool chxbxvisable) + { + DevComponents.AdvTree.Node newnode; + newnode = new DevComponents.AdvTree.Node(); + newnode.Text = nodetext; + newnode.Selectable = selectable; + AddCheckBox(chxbxvisable, newnode);//C2016-045 Allow Folders to be selected. + return newnode; + } + + private void AddCheckBox(bool chxbxvisable, DevComponents.AdvTree.Node newnode) + { + //C2016-045 Allow Folders to be selected. + newnode.CheckBoxAlignment = DevComponents.AdvTree.eCellPartAlignment.NearCenter; + newnode.CheckBoxStyle = eCheckBoxStyle.CheckBox; + newnode.CheckBoxThreeState = false; + newnode.CheckBoxVisible = chxbxvisable; + + // Set newnode.Checked = parent.Checked + if(newnode.Parent != null) + newnode.Checked = newnode.Parent.Checked; + } + private Node LookInTree(NodeCollection monkeys, string bananna) { Node foundit = null; @@ -726,6 +1064,473 @@ namespace Volian.Controls.Library return foundit; } + // C2020-033: Before allowing conversion of Incoming Transitions to text, get list of results that the user has permission edit. + private List TranCvtCheckPermission(bool all) + { + // check if a non-reader can convert transitions to text even if a reader - this is set by an administrator on the top + // folder properties dialog + bool allowNonAdmin = IncTranCvtPerm(); + List itmsEditable = new List(); // return this list + int listCount = 0; + if (all) // Check all in list + { + listCount = _SearchResults.Count; + foreach (ItemInfo ii in _SearchResults) + { + if (allowNonAdmin || UserInfo.CanEdit(MyUserInfo, ii.MyDocVersion)) itmsEditable.Add(ii.ContentID); + } + } + else // check only the items selected + { + listCount = lbSrchResultsIncTrans.CheckedItems.Count; + List lbis = lbSrchResultsIncTrans.CheckedItems; + foreach (ListBoxItem lbi in lbis) + { + ItemBindingData tmpii = lbi.Tag as ItemBindingData; + ItemInfo ii = tmpii.DataItem as ItemInfo; + if (allowNonAdmin || UserInfo.CanEdit(MyUserInfo, ii.MyDocVersion)) itmsEditable.Add(ii.ContentID); + } + } + // Prompt user if convert to text should continue. If some items cannot be edited, also state that + // not all can be converted to text. If count of itmsEditable & lbis are different some cannot be edited. + if (itmsEditable.Count == 0) + { + FlexibleMessageBox.Show("You do not have permission to edit any of the procedures, sections, and/or steps" + (all ? "." : " that are selected."), + "Convert Transition to Text", MessageBoxButtons.OK, MessageBoxIcon.Information); + return null; + } + else if (itmsEditable.Count != listCount) + { + DialogResult ans = FlexibleMessageBox.Show("You only have permission to edit some of the procedures, sections, and/or steps that are selected.procedures, sections, and/or steps" + (all ? "." : " that are selected.") + + "\r\n\r\n Should the conversion of the transitions to text continue?", + "Convert Transition to Text", MessageBoxButtons.YesNo, MessageBoxIcon.Question); + if (ans == DialogResult.No) return null; + } + else + { + DialogResult ans = FlexibleMessageBox.Show("Are you sure you want to convert the transitions to text?", + "Convert Transition to Text", MessageBoxButtons.YesNo, MessageBoxIcon.Question); + if (ans == DialogResult.No) return null; + } + + return itmsEditable; + } + + // C2020-033: convert selected transitions to text + private void btnTranCvtSelToTxt_Click(object sender, EventArgs e) + { + // First see if all selected can be converted, i.e. user has permission to edit + List lbis = lbSrchResultsIncTrans.CheckedItems; + List itmsEditable = TranCvtCheckPermission(false); + if (itmsEditable == null || itmsEditable.Count == 0) return; + TranCvtToTxt(itmsEditable); + fromTranCvtBtn = true; + UpdateSearchIncTransResults(); // B2021-009: Research after convert transitions to text + fromTranCvtBtn = false; + } + + // B2021-010: IncomingTranGetMergedTranList gets a complete list of incoming transitions (before fix transitions to procedure + // were only included if there were NO transitions to items within procedure, the GetExternalTransitionsToChildren query + // did not get transitions 'incoming to' the item itself) + private ItemInfoList IncomingTranGetMergedTranList() + { + ItemInfoList iil = null; + bool first = true; + + using (TransitionInfoList exTrans = TransitionInfoList.GetExternalTransitionsToChildren(SearchIncTransII.ItemID)) + { + foreach (TransitionInfo ti in exTrans) + { + if (first) + { + ContentInfo ci = ContentInfo.Get(ti.FromID); + ItemInfo tmp = ci.ContentItems[0]; + iil = new ItemInfoList(tmp); + first = false; + } + else + { + ContentInfo ci = ContentInfo.Get(ti.FromID); + ItemInfo tmp = ci.ContentItems[0]; + iil.AddItem(tmp); + } + } + } + using (TransitionInfoList exTrans = TransitionInfoList.GetExternalTransitions(SearchIncTransII.ItemID)) + { + foreach (TransitionInfo ti in exTrans) + { + if (first) + { + ContentInfo ci = ContentInfo.Get(ti.FromID); + ItemInfo tmp = ci.ContentItems[0]; + iil = new ItemInfoList(tmp); + first = false; + } + else + { + ContentInfo ci = ContentInfo.Get(ti.FromID); + ItemInfo tmp = ci.ContentItems[0]; + + // B2021-014: if in list, don't add another + if (!iil.Contains(tmp)) iil.AddItem(tmp); + } + } + } + + return iil; + } + + // C2020-033: For items in list, do the actual conversion of the Incoming Transition to text + private void TranCvtToTxt(List itmsEditable) + { + ItemInfo trII = SearchIncTransII; + + if (trII != null) + { + using (TransitionInfoList exTrans = TransitionInfoList.GetExternalTransitionsToChildren(trII.ItemID)) + { + foreach (TransitionInfo ti in exTrans) + { + // See if the 'item to' id is to be converted and if so do it. To figure this out, + // see if it is in the list itmsEditable. + if (itmsEditable.Contains(ti.FromID)) + { + ContentInfo ci = ContentInfo.Get(ti.FromID); + ItemInfo tmp = ci.ContentItems[0]; + + using (Content content = Content.Get(tmp.ContentID)) + { + content.FixTransitionText(ti, true); + content.Save(); + } + } + } + + } + + // B2021-010: Convert the text of transitions pointing (incoming) to the item itself + using (TransitionInfoList exTrans = TransitionInfoList.GetExternalTransitions(trII.ItemID)) + { + foreach (TransitionInfo ti in exTrans) + { + // See if the 'item to' id is to be converted and if so do it. To figure this out, + // see if it is in the list itmsEditable. + if (itmsEditable.Contains(ti.FromID)) + { + ContentInfo ci = ContentInfo.Get(ti.FromID); + ItemInfo tmp = ci.ContentItems[0]; + + using (Content content = Content.Get(tmp.ContentID)) + { + content.FixTransitionText(ti, true); + content.Save(); + } + } + } + + } + } + } + + #region (ProgressBar) + + private void ProgressBar_Initialize(int max, string desc) + { + if (_ProgressBar != null) + { + _ProgressBar.Maximum = max; + _ProgressBar.Text = desc; + _ProgressBar.TextVisible = true; + } + } + + private void ProgressBar_SetValue(int curval) + { + if (_ProgressBar != null) + _ProgressBar.Value = curval; + } + + private void ProgressBar_Clear() + { + if (_ProgressBar != null) + { + _ProgressBar.Text = string.Empty; + _ProgressBar.Maximum = 0; + _ProgressBar.Value = 0; + } + } + + #endregion + + #region (ROFST Combo Tree) + + private void LoadROComboTree() + { + lblSrchRoMsg.Visible = false; // C2019-041: start out with no message about rofsts and folder(s) compatibility + // if only one docversion selected, this RoFst can be used. If more than one or none (none is all docversions), then check if they + // use the same RO fst. If not, put a message as the first tree node and return, otherwise, load the tree. + List dvilTmp = new List(); + + if (lstCheckedDocVersions == null || lstCheckedDocVersions.Count == 0) + { + DocVersionInfoList dvil = DocVersionInfoList.Get(); + foreach (DocVersionInfo dvi in dvil) dvilTmp.Add(dvi); + } + else + { + dvilTmp = lstCheckedDocVersions; + } + + bool same = true; + // get the first rofstId for comparing to the rest: + int rofstId = (dvilTmp.Count > 0)? (dvilTmp[0].DocVersionAssociations != null && dvilTmp[0].DocVersionAssociations.Count > 0) ? dvilTmp[0].DocVersionAssociations[0].ROFstID: -1 : -1; + + // for remaining folder/docversions in the list, check if they have an associated rofst & if so, if it is the same as the first in list. + for (int i = 1; i < dvilTmp.Count; i++) + { + if (dvilTmp[i].DocVersionAssociations != null && dvilTmp[i].DocVersionAssociations.Count > 0) + { + if (rofstId != dvilTmp[i].DocVersionAssociations[0].ROFstID) + { + same = false; + break; + } + } + } + + // rofsts for selected folder/docversions are not the same, cannot do an ro search: + if (!same) + { + DevComponents.AdvTree.Node tn = new DevComponents.AdvTree.Node(); + // C2019-041: if selected folders do not have the same ro.fst then clear the ro list and let user know. + cmboTreeROs.Nodes.Clear(); + + if (lstCheckedDocVersions == null || lstCheckedDocVersions.Count == 0) + lblSrchRoMsg.Text = "RO values are incompatible between the folders. This may be due to the RO values needing to be updated."; + else + lblSrchRoMsg.Text = "This folder(s) RO values are incompatible with the currently selected folder(s). This may be due to the RO values needing to be updated."; + + lblSrchRoMsg.Visible = true; + _lastRoFstId = -1; + return; + } + + // C2019-041: if requested rofst is same as last one, just return; + if (_lastRoFstId == rofstId) return; + + lblSrchRoMsg.Refresh(); + _lastRoFstId = rofstId; // C2019-041: Save this rofstid in case a new one is processed. + cmboTreeROs.Nodes.Clear(); + this.cmboTreeROs.AdvTree.BeforeExpand += new DevComponents.AdvTree.AdvTreeNodeCancelEventHandler(this.cmboTreeROs_BeforeExpand); + cmboTreeROs.AdvTree.AfterExpand += new AdvTreeNodeEventHandler(AdvTree_AfterExpandorCollapse); + cmboTreeROs.AdvTree.AfterCollapse += new AdvTreeNodeEventHandler(AdvTree_AfterExpandorCollapse); + + // populate the tree - only 1 folder/docversion is selected or all selected use the same rofst: + if (lstCheckedDocVersions != null && lstCheckedDocVersions.Count > 0) + { + _MyDocVersion = lstCheckedDocVersions[0]; + + if (_MyDocVersion.DocVersionAssociations != null && _MyDocVersion.DocVersionAssociations.Count > 0) + { + _MyROFSTLookup = _MyDocVersion.DocVersionAssociations[0].MyROFst.GetROFSTLookup(_MyDocVersion); + + ROFSTLookup.rodbi[] dbs = _MyROFSTLookup.GetRODatabaseList(true); + + if (dbs != null && dbs.Length > 0) + { + for (int i = 0; i < dbs.Length; i++) + { + DevComponents.AdvTree.Node tn = new DevComponents.AdvTree.Node(); + + ROFSTLookup.rodbi db = dbs[i]; + tn.Text = db.dbiTitle; + tn.Tag = db; + cmboTreeROs.Nodes.Add(tn); + + AddDummyGroup(db, tn); + } + } + + //for (int i = 0; i < _MyROFSTLookup.myHdr.myDbs.Length; i++) + //{ + // DevComponents.AdvTree.Node tn = new DevComponents.AdvTree.Node(); + // tn.Text = _MyROFSTLookup.myHdr.myDbs[i].dbiTitle; + // tn.Tag = _MyROFSTLookup.myHdr.myDbs[i]; + // cmboTreeROs.Nodes.Add(tn); + // AddDummyGroup(_MyROFSTLookup.myHdr.myDbs[i], tn); + //} + } + } + } + + private Node FindTreeNodeAt(NodeCollection nodes, int y) + { + foreach (Node node in nodes) + { + if (node.Bounds.Top <= y && node.Bounds.Bottom >= y) + return node; + if (node.Bounds.Top > y) + { + if (node.PrevNode != null && node.PrevNode.Expanded) + return FindTreeNodeAt(node.PrevNode.Nodes, y); + return node; + } + } + return null; + } + + private Node BottomTreeNode(NodeCollection nodes) + { + Node bottomNode = nodes[nodes.Count - 1]; // Return bottom node in collection + if (bottomNode.Expanded) // If expanded return bottom child + return BottomTreeNode(bottomNode.Nodes); + return bottomNode; + } + + private void AddDummyGroup(ROFSTLookup.rodbi rodbi, DevComponents.AdvTree.Node tn) + { + if (rodbi.children != null && rodbi.children.Length > 0) + { + DevComponents.AdvTree.Node tmp = new DevComponents.AdvTree.Node(); + tmp.Text = DummyNodeText; + tn.Nodes.Add(tmp); + } + } + + private void cmboTreeROs_BeforeExpand(object sender, DevComponents.AdvTree.AdvTreeNodeCancelEventArgs e) + { + LoadChildren(e.Node); + } + + private void LoadChildren(DevComponents.AdvTree.Node tn) + { + object tag = tn.Tag; + if (tn.HasChildNodes && tn.Nodes[0].Text != DummyNodeText) return; // already loaded. + if (tn.HasChildNodes && tn.Nodes[0].Text == DummyNodeText) tn.Nodes[0].Remove(); + ROFSTLookup.rochild[] chld = null; + + if (tn.Tag is ROFSTLookup.rodbi) + { + ROFSTLookup.rodbi db = (ROFSTLookup.rodbi)tn.Tag; + + // Try to Lazy Load children - B2022-026 RO Memory Reduction code + if (db.children == null || db.children.Length <= 0) + db.children = MyROFSTLookup.GetRoChildrenByID(db.ID, db.dbiID, true); + + chld = db.children; + } + else if (tn.Tag is ROFSTLookup.rochild) + { + ROFSTLookup.rochild ch = (ROFSTLookup.rochild)tn.Tag; + + // Try to Lazy Load children - B2022-026 RO Memory Reduction code + if (ch.children == null || ch.children.Length <= 0) + ch.children = MyROFSTLookup.GetRoChildrenByRoid(ch.roid, true); + + chld = ch.children; + } + else + { + Console.WriteLine("error - no type"); + return; + } + // if children, add dummy node + // B2022-026 RO Memory Reduction code - need to check length + if (chld != null && chld.Length > 0) + { + ProgressBar_Initialize(chld.Length, tn.Text); + + for (int i = 0; i < chld.Length; i++) + { + ProgressBar_SetValue(i); + DevComponents.AdvTree.Node tmp = null; + + // Try to Lazy Load children - B2022-026 RO Memory Reduction code + if (chld[i].children == null || chld[i].children.Length <= 0) + chld[i].children = MyROFSTLookup.GetRoChildrenByRoid(chld[i].roid, true); + + // if this is a group, i.e. type 0, add a dummy node + // B2022-026 RO Memory Reduction code - check children length + if (chld[i].type == 0 && (chld[i].children == null || chld[i].children.Length <= 0)) + { + //skip it. + // TODO: KBR how to handle this? + //Console.WriteLine("ro junk"); + continue; + } + else if (chld[i].value == null) + { + tmp = new DevComponents.AdvTree.Node(); + + tmp.Text = chld[i].title; + tmp.Tag = chld[i]; + int index = FindIndex(tn.Nodes, tmp.Text); + tn.Nodes.Insert(index, tmp); + //tn.Nodes.Add(tmp); + DevComponents.AdvTree.Node sub = new DevComponents.AdvTree.Node(); + sub.Text = DummyNodeText; + + tmp.Nodes.Add(sub); + } + else + { + tmp = new DevComponents.AdvTree.Node(); + + tmp.Text = chld[i].title; + tmp.Tag = chld[i]; + int index = FindIndex(tn.Nodes, tmp.Text); + + tn.Nodes.Insert(index, tmp); + //tn.Nodes.Add(tmp); + } + } + } + + ProgressBar_Clear(); + } + + private int FindIndex(NodeCollection nodes, string value) + { + int index = 0; + foreach (Node node in nodes) + { + if (GreaterValue(node.Text, value)) return index; + index++; + } + return index; + } + + private bool GreaterValue(string value1, string value2) + { + return DisplayRO.GreaterValue(value1, value2); + } + + private void cmboTreeROs_SelectedIndexChanged(object sender, EventArgs e) + { + if (cmboTreeROs.SelectedIndex == -1 || cmboTreeROs.SelectedNode.Tag is ROFSTLookup.rodbi) + { + cbxFndUnLnkROVals.Enabled = false; + } + else if (cmboTreeROs.SelectedNode.Tag is ROFSTLookup.rochild) + { + ROFSTLookup.rochild ro = (ROFSTLookup.rochild)cmboTreeROs.SelectedNode.Tag; + // B2022-026 RO Memory Reduction code - check children length + cbxFndUnLnkROVals.Enabled = (ro.children == null || ro.children.Length <= 0); + } + + if (!cbxFndUnLnkROVals.Enabled) + cbxFndUnLnkROVals.Checked = false; + } + + private void gpFindROs_EnabledChanged(object sender, EventArgs e) + { + if (gpFindROs.Enabled) + gpFindROs.Style.BackColor = Color.Yellow; + else + gpFindROs.Style.BackColor = saveGpFindROsColor; + } + private void advTreeProcSetsPreSelect() { bool keeplooking = true; @@ -764,259 +1569,7 @@ namespace Volian.Controls.Library #endregion - #region ROFST Combo Tree - static private int _lastRoFstId = -1; - private void LoadROComboTree() - { - lblSrchRoMsg.Visible = false; // C2019-041: start out with no message about rofsts and folder(s) compatibility - // if only one docversion selected, this RoFst can be used. If more than one or none (none is all docversions), then check if they - // use the same RO fst. If not, put a message as the first tree node and return, otherwise, load the tree. - List dvilTmp = new List(); - if (lstCheckedDocVersions == null || lstCheckedDocVersions.Count == 0) - { - DocVersionInfoList dvil = DocVersionInfoList.Get(); - foreach (DocVersionInfo dvi in dvil) dvilTmp.Add(dvi); - } - else - dvilTmp = lstCheckedDocVersions; - - bool same = true; - // get the first rofstId for comparing to the rest: - int rofstId = (dvilTmp.Count > 0)? (dvilTmp[0].DocVersionAssociations != null && dvilTmp[0].DocVersionAssociations.Count > 0) ? dvilTmp[0].DocVersionAssociations[0].ROFstID: -1 : -1; - - // for remaining folder/docversions in the list, check if they have an associated rofst & if so, if it is the same as the first in list. - for (int i = 1; i < dvilTmp.Count; i++) - { - if (dvilTmp[i].DocVersionAssociations != null && dvilTmp[i].DocVersionAssociations.Count > 0) - { - if (rofstId != dvilTmp[i].DocVersionAssociations[0].ROFstID) - { - same = false; - break; - } - } - } - - // rofsts for selected folder/docversions are not the same, cannot do an ro search: - if (!same) - { - DevComponents.AdvTree.Node tn = new DevComponents.AdvTree.Node(); - // C2019-041: if selected folders do not have the same ro.fst then clear the ro list and let user know. - cmboTreeROs.Nodes.Clear(); - if (lstCheckedDocVersions == null || lstCheckedDocVersions.Count == 0) - lblSrchRoMsg.Text = "RO values are incompatible between the folders. This may be due to the RO values needing to be updated."; - else - lblSrchRoMsg.Text = "This folder(s) RO values are incompatible with the currently selected folder(s). This may be due to the RO values needing to be updated."; - lblSrchRoMsg.Visible = true; - _lastRoFstId = -1; - return; - } - // C2019-041: if requested rofst is same as last one, just return; - if (_lastRoFstId == rofstId) return; - lblSrchRoMsg.Refresh(); - _lastRoFstId = rofstId; // C2019-041: Save this rofstid in case a new one is processed. - cmboTreeROs.Nodes.Clear(); - this.cmboTreeROs.AdvTree.BeforeExpand += new DevComponents.AdvTree.AdvTreeNodeCancelEventHandler(this.cmboTreeROs_BeforeExpand); - cmboTreeROs.AdvTree.AfterExpand += new AdvTreeNodeEventHandler(AdvTree_AfterExpandorCollapse); - cmboTreeROs.AdvTree.AfterCollapse += new AdvTreeNodeEventHandler(AdvTree_AfterExpandorCollapse); - // populate the tree - only 1 folder/docversion is selected or all selected use the same rofst: - if (lstCheckedDocVersions != null && lstCheckedDocVersions.Count > 0) - { - _MyDocVersion = lstCheckedDocVersions[0]; - if (_MyDocVersion.DocVersionAssociations != null && _MyDocVersion.DocVersionAssociations.Count > 0) - { - _MyROFSTLookup = _MyDocVersion.DocVersionAssociations[0].MyROFst.GetROFSTLookup(_MyDocVersion); - - for (int i = 0; i < _MyROFSTLookup.myHdr.myDbs.Length; i++) - { - DevComponents.AdvTree.Node tn = new DevComponents.AdvTree.Node(); - tn.Text = _MyROFSTLookup.myHdr.myDbs[i].dbiTitle; - tn.Tag = _MyROFSTLookup.myHdr.myDbs[i]; - cmboTreeROs.Nodes.Add(tn); - AddDummyGroup(_MyROFSTLookup.myHdr.myDbs[i], tn); - } - } - } - } - void AdvTree_AfterExpandorCollapse(object sender, AdvTreeNodeEventArgs e) - { - Node bottomNode = BottomTreeNode(cmboTreeROs.AdvTree.Nodes); - Node lastNode = cmboTreeROs.AdvTree.Nodes[cmboTreeROs.AdvTree.Nodes.Count - 1]; - int top = cmboTreeROs.AdvTree.Nodes[0].Bounds.Top; - int bottom = bottomNode.Bounds.Bottom + 5; - int hScrollBarHeight = cmboTreeROs.AdvTree.HScrollBar != null ? cmboTreeROs.AdvTree.HScrollBar.Height : 0; - bottom = bottomNode.Bounds.Bottom + 5; - cmboTreeROs.AdvTree.Size = new Size(cmboTreeROs.AdvTree.Size.Width, Math.Min(525, bottom - top + hScrollBarHeight)); - if (cmboTreeROs.AdvTree.VScrollBar != null && bottom < cmboTreeROs.AdvTree.Size.Height) - { - int yLookFor = (bottom - cmboTreeROs.AdvTree.Size.Height) + 2 * hScrollBarHeight; - Node topNode = FindTreeNodeAt(cmboTreeROs.AdvTree.Nodes, yLookFor); - if (topNode != null) - topNode.EnsureVisible(); - } - } - private Node FindTreeNodeAt(NodeCollection nodes, int y) - { - foreach (Node node in nodes) - { - if (node.Bounds.Top <= y && node.Bounds.Bottom >= y) - return node; - if (node.Bounds.Top > y) - { - if (node.PrevNode != null && node.PrevNode.Expanded) - return FindTreeNodeAt(node.PrevNode.Nodes, y); - return node; - } - } - return null; - } - private Node BottomTreeNode(NodeCollection nodes) - { - Node bottomNode = nodes[nodes.Count - 1]; // Return bottom node in collection - if (bottomNode.Expanded) // If expanded return bottom child - return BottomTreeNode(bottomNode.Nodes); - return bottomNode; - } - private void AddDummyGroup(ROFSTLookup.rodbi rodbi, DevComponents.AdvTree.Node tn) - { - if (rodbi.children != null && rodbi.children.Length > 0) - { - DevComponents.AdvTree.Node tmp = new DevComponents.AdvTree.Node(); - tmp.Text = "VLN_DUMMY_FOR_TREE"; - tn.Nodes.Add(tmp); - } - } - private void cmboTreeROs_BeforeExpand(object sender, DevComponents.AdvTree.AdvTreeNodeCancelEventArgs e) - { - LoadChildren(e.Node); - } - - private void LoadChildren(DevComponents.AdvTree.Node tn) - { - object tag = tn.Tag; - if (tn.HasChildNodes && tn.Nodes[0].Text != "VLN_DUMMY_FOR_TREE") return; // already loaded. - if (tn.HasChildNodes && tn.Nodes[0].Text == "VLN_DUMMY_FOR_TREE") tn.Nodes[0].Remove(); - ROFSTLookup.rochild[] chld = null; - - if (tn.Tag is ROFSTLookup.rodbi) - { - ROFSTLookup.rodbi db = (ROFSTLookup.rodbi)tn.Tag; - chld = db.children; - } - else if (tn.Tag is ROFSTLookup.rochild) - { - ROFSTLookup.rochild ch = (ROFSTLookup.rochild)tn.Tag; - chld = ch.children; - } - else - { - Console.WriteLine("error - no type"); - return; - } - // if children, add dummy node - if (chld != null && chld.Length > 0) - { - ProgressBar_Initialize(chld.Length, tn.Text); - for (int i = 0; i < chld.Length; i++) - { - ProgressBar_SetValue(i); - DevComponents.AdvTree.Node tmp = null; - // if this is a group, i.e. type 0, add a dummy node - if (chld[i].type == 0 && chld[i].children == null) - //skip it. - // TODO: KBR how to handle this? - //Console.WriteLine("ro junk"); - continue; - else if (chld[i].value == null) - { - tmp = new DevComponents.AdvTree.Node(); - tmp.Text = chld[i].title; - tmp.Tag = chld[i]; - int index = FindIndex(tn.Nodes, tmp.Text); - tn.Nodes.Insert(index, tmp); - //tn.Nodes.Add(tmp); - DevComponents.AdvTree.Node sub = new DevComponents.AdvTree.Node(); - sub.Text = "VLN_DUMMY_FOR_TREE"; - tmp.Nodes.Add(sub); - } - else - { - tmp = new DevComponents.AdvTree.Node(); - tmp.Text = chld[i].title; - tmp.Tag = chld[i]; - int index = FindIndex(tn.Nodes, tmp.Text); - tn.Nodes.Insert(index, tmp); - //tn.Nodes.Add(tmp); - } - } - } - ProgressBar_Clear(); - } - - private int FindIndex(NodeCollection nodes, string value) - { - int index = 0; - foreach (Node node in nodes) - { - if (GreaterValue(node.Text, value)) return index; - index++; - } - return index; - } -// private static Regex _RegExGetNumber = new Regex(@"^ *[+-]?[.,0-9]+(E[+-]?[0-9]+)?"); - private bool GreaterValue(string value1, string value2) - { - return DisplayRO.GreaterValue(value1, value2); - //Match match1 = _RegExGetNumber.Match(value1); - //Match match2 = _RegExGetNumber.Match(value2); - //if (match1.Success && match2.Success) // Compare the numeric value - //{ - // double dbl1 = double.Parse(match1.ToString()); - // double dbl2 = double.Parse(match2.ToString()); - // return dbl1 > dbl2; - //} - //return String.Compare(value1, value2, true) > 0; - } - - private void cmboTreeROs_SelectedIndexChanged(object sender, EventArgs e) - { - if (cmboTreeROs.SelectedIndex == -1 || cmboTreeROs.SelectedNode.Tag is ROFSTLookup.rodbi) - cbxFndUnLnkROVals.Enabled = false; - else if (cmboTreeROs.SelectedNode.Tag is ROFSTLookup.rochild) - { - ROFSTLookup.rochild ro = (ROFSTLookup.rochild)cmboTreeROs.SelectedNode.Tag; - cbxFndUnLnkROVals.Enabled = (ro.children == null); - } - if (!cbxFndUnLnkROVals.Enabled) - cbxFndUnLnkROVals.Checked = false; - } - - private void gpFindROs_EnabledChanged(object sender, EventArgs e) - { - if (gpFindROs.Enabled) - gpFindROs.Style.BackColor = Color.Yellow; - else - gpFindROs.Style.BackColor = saveGpFindROsColor; - } - - #endregion - - #region Annotation Search - - public void SetupAnnotationSearch(AnnotationDetails annotationDetails, DisplayTabControl tc) - { - _AnnotationDetails = annotationDetails; - List annoTypes = new List(); - annoTypes.Add(new AnnotationTypeSearch("All Annotations", "")); - AnnotationTypeInfoList annoList = AnnotationTypeInfoList.Get(); - foreach (AnnotationTypeInfo ati in annoList) - annoTypes.Add(new AnnotationTypeSearch(ati.Name, ati.TypeID.ToString())); - cbxAnnoTypes.DisplayMember = "Name"; - cbxAnnoTypes.DataSource = annoTypes; - lbSrchResults.MouseMove += new MouseEventHandler(lbSrchResults_MouseMove); - _TabControl = tc; - } - + #region (Annotation Search) private void cbxTextSearchAnnotation_Leave(object sender, EventArgs e) { @@ -1047,36 +1600,8 @@ namespace Volian.Controls.Library #endregion - #region ProgressBar - private void ProgressBar_Initialize(int max, string desc) - { - if (_ProgressBar != null) - { - _ProgressBar.Maximum = max; - _ProgressBar.Text = desc; - _ProgressBar.TextVisible = true; - } - } + #region (Search Results) - private void ProgressBar_SetValue(int curval) - { - if (_ProgressBar != null) - _ProgressBar.Value = curval; - } - - private void ProgressBar_Clear() - { - if (_ProgressBar != null) - { - _ProgressBar.Text = ""; - _ProgressBar.Maximum = 0; - _ProgressBar.Value = 0; - //_ProgressBar.TextVisible = false; // B2017-125 text was not always being displayed - } - } - #endregion - - #region Search Results private void DisplayResults() { _LoadingList = true; @@ -1134,38 +1659,6 @@ namespace Volian.Controls.Library } - //private void PopulatelbSrcResults(ICollection _SearchResults) - //{ - // foreach (ItemInfo ii in _SearchResults) - // { - // lbSrchResults.Items.Add(ii); - // } - // Console.WriteLine("{0} Populate", DateTime.Now); - //} - public void UpdateAnnotationSearchResults() - { - if (!LastSearchWasAnnotations) return; // B2019-119 only refresh annotation search results if an annotation search was done - // B2019-004: update search results list when an annotation is removed. (before bug fix, code method & code below was commented out) - string unitPrefix = ""; - if (Mydocversion != null) - unitPrefix = Mydocversion.DocVersionConfig.Unit_ProcedureNumber; - if (unitPrefix.EndsWith("#")) - unitPrefix = unitPrefix.Replace("#", ""); - SearchResults = ItemInfoList.GetListFromAnnotationSearch(DVISearchList, TypeSearchList, AnnotationSearchType, cbxTextSearchAnnotation.Text, cbxCaseSensitiveAnnoText.Checked, unitPrefix); - DisplayResults(); - /* - AnnotationTypeInfo ati = cbxAnnoTypes.SelectedValue as AnnotationTypeInfo; - _LoadingList = true; - lbSrchResults.DataSource = ati.AnnotationTypeAnnotations; - lbSrchResults.SelectedIndex = -1; - LastResultsMouseOverIndex = -1; - if (lbSrchResults.Items.Count > 0) - btnPrnSrchRslts.Enabled = true; - else - btnPrnSrchRslts.Enabled = false; - _LoadingList = false; - * */ - } private void lbSrchResults_MouseMove(object sender, MouseEventArgs e) { int ResultsMouseOverIndex = lbSrchResults.IndexFromPoint(e.Location); @@ -1179,6 +1672,7 @@ namespace Volian.Controls.Library LastResultsMouseOverIndex = ResultsMouseOverIndex; } } + // B2021-018: Removed code that was tracking the number of items checked in the incoming transition // listbox. Found that could just look at the CheckedItems.Count value. (Previous fixes // that were removed are B2021-003 & part of C2020-033 (part was for permissions, which was not removed) @@ -1206,6 +1700,7 @@ namespace Volian.Controls.Library btnTranCvtSelToTxt.Enabled = (lbSrchResultsIncTrans.CheckedItems.Count > 0); } } + private void GrpPanSearchResults_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { // B2021-004: If a multiple selection occurred in the results list for Incoming Transitions, tell user that @@ -1213,7 +1708,7 @@ namespace Volian.Controls.Library if (!lbSrchResultsIncTrans.Enabled) FlexibleMessageBox.Show("Processing a request to open a procedure. Try again when complete.", "Try Again", MessageBoxButtons.OK, MessageBoxIcon.Information); } - private bool _ProcessingSelectedValueChanged = false; + private void lbSrchResults_SelectedValueChanged(object sender, EventArgs e) { if (_LoadingList) return; @@ -1257,9 +1752,9 @@ namespace Volian.Controls.Library if (dti != null) { if (dti.MyDSOTabPanel != null) - dti.MyDSOTabPanel.SearchString = _strSrchText == null || _strSrchText == "" ? this.cbxTextSearchText.Text : _strSrchText; + dti.MyDSOTabPanel.SearchString = _strSrchText == null || _strSrchText == string.Empty ? this.cbxTextSearchText.Text : _strSrchText; if (dti.MyStepTabPanel != null) - dti.MyStepTabPanel.SearchString = _strSrchText == null || _strSrchText == "" ? this.cbxTextSearchText.Text : _strSrchText; + dti.MyStepTabPanel.SearchString = _strSrchText == null || _strSrchText == string.Empty ? this.cbxTextSearchText.Text : _strSrchText; _OpenDocFromSearch = false; } } @@ -1305,113 +1800,16 @@ namespace Volian.Controls.Library DisplayResults(); Cursor = savcursor; } + #endregion - #region Search - private string DVISearchList - { - get - { - // append list of document versions to search - if (lstCheckedDocVersions.Count > 0) - { - string strRtnStr = ""; - // get list of doc versions to search - foreach (DocVersionInfo dvi in lstCheckedDocVersions) - { - strRtnStr += string.Format(",{0}", dvi.VersionID.ToString()); - } - return strRtnStr.Substring(1); - } - return ""; - } - } - private string TypeSearchList - { - get - { - // append list of step types to search - if (lstCheckedStepTypes.Count > 0) - { - string strRtnStr = ""; - // get list of selected types - foreach (int typ in lstCheckedStepTypes) - { - int tmp = typ; - if (tmp == 0) - tmp = 10000; // this is the accessory page type - else - tmp += 20000; // step/substep types - strRtnStr += string.Format(",{0}", tmp); - } - return strRtnStr.Substring(1); - } - return ""; - } - } - private string TextSearchString - { - get - { - if (tabSearchTypes.SelectedTab == tabSearchTypes.Tabs[0]) - return ConvertSpecialChars(cbxTextSearchText.Text);//string.Format("{0}", cbxTextSearchText.Text); - return ""; - } - } - private string AnnotationSearchType - { - get - { - if (tabSearchTypes.SelectedTab == tabSearchTypes.Tabs[1]) - return ((AnnotationTypeSearch)cbxAnnoTypes.SelectedValue).ID; - return ""; - } - } - private string ROSearchList - { - get - { - if (tabSearchTypes.SelectedTab == tabSearchTypes.Tabs[2]) - { // RO Search - ROFSTLookup.rochild[] chld = null; - ROFSTLookup.rochild ch; - if (cmboTreeROs.SelectedNode != null) - { - if (cbxFndUnLnkROVals.Enabled && cbxFndUnLnkROVals.Checked) - { - ch = (ROFSTLookup.rochild)cmboTreeROs.SelectedNode.Tag; - _strSrchText = string.Format("{0}", ch.value); - return _strSrchText; // append RO Value text to search - } - else - { - if (cmboTreeROs.SelectedNode.Tag is ROFSTLookup.rodbi) - { - ROFSTLookup.rodbi db = (ROFSTLookup.rodbi)cmboTreeROs.SelectedNode.Tag; - return _MyRODbID.ToString() + ":" + string.Format("{0}", db.dbiID.ToString("X4")); - } - else if (cmboTreeROs.SelectedNode.Tag is ROFSTLookup.rochild) - { - ch = (ROFSTLookup.rochild)cmboTreeROs.SelectedNode.Tag; - chld = ch.children; - // build a list of ROs to search - return _MyRODbID.ToString() + ":" + GetROsToSearch(chld); - //return _MyRODbID.ToString() + ":" + ch.roid + "0000," + GetROsToSearch(chld); - //if (strRtnStr.EndsWith(",")) - // strRtnStr = strRtnStr.Substring(0, strRtnStr.Length - 1); - } - } - } - } - return ""; - } - } + #region (Search) private string ConvertSpecialChars(string str) { string rtnVal = str; - rtnVal = rtnVal.Replace("\u00A0", @"\u160?"); //convert \u00A0 to a hard space (\u00A0 shows as a blank in the search text field) - rtnVal = rtnVal.Replace("\n", @"\line "); //B2018-020 SQL content record has "\line " for the hard return + rtnVal = rtnVal.Replace("\u00A0", @"\u160?"); //convert \u00A0 to a hard space (\u00A0 shows as a blank in the search text field) + rtnVal = rtnVal.Replace("\n", @"\line "); //B2018-020 SQL content record has "\line " for the hard return // Bug fix B2014-057 // if we are searching for a symbol character in all procedure sets MyDocVersion is null // when MyDocVersion is null, get the symbol list directly from the PROMS base format (BaseAll.xml) @@ -1430,11 +1828,13 @@ namespace Volian.Controls.Library } return rtnVal; } + // Same funtion as GetROChildren in DisplayReport.cs private string GetROsToSearch(ROFSTLookup.rochild[] chld) { - string rtnstr = ""; - if (chld == null) // get a single ROID + string rtnstr = string.Empty; + // B2022-026 RO Memory Reduction code - check chilren length + if (chld == null || chld.Length <= 0) // get a single ROID { ROFSTLookup.rochild ro = (ROFSTLookup.rochild)cmboTreeROs.SelectedNode.Tag; rtnstr += string.Format("{0}", ro.roid); @@ -1445,7 +1845,8 @@ namespace Volian.Controls.Library // if the child has children, then call this function recursivly foreach (ROFSTLookup.rochild roc in chld) { - if (roc.children != null) + // B2022-026 RO Memory Reduction code - check children length + if (roc.children != null && roc.children.Length > 0) rtnstr += GetROsToSearch(roc.children); else rtnstr += string.Format("{0},", roc.roid); @@ -1454,13 +1855,6 @@ namespace Volian.Controls.Library return rtnstr; } - private bool _LastSearchWasAnnotations = false; // B2019-119 only refresh annotation search results if an annotation search was done - public bool LastSearchWasAnnotations - { - get { return _LastSearchWasAnnotations; } - set { _LastSearchWasAnnotations = value; } - } - private void btnSearch_Click(object sender, EventArgs e) { _fromLoad = false; @@ -1484,11 +1878,11 @@ namespace Volian.Controls.Library //TypesSelected = "Step Types Searched: " + ((typstr != null) ? typstr : "all step types"); //TypesSelected = "Searched Step Types: " + ((typstr != null) ? typstr : "all step types"); //TypesSelected = (typstr != null) ? "Searched Step Types: " + typstr : "Searched All Step Types"; - string unitPrefix = ""; + string unitPrefix = string.Empty; if(Mydocversion != null) unitPrefix = Mydocversion.DocVersionConfig.Unit_ProcedureNumber; if (unitPrefix.EndsWith("#")) - unitPrefix = unitPrefix.Replace("#", ""); + unitPrefix = unitPrefix.Replace("#", string.Empty); if (tabSearchTypes.SelectedTab == tabSearchTypes.Tabs[0]) // Text Search { @@ -1509,13 +1903,13 @@ namespace Volian.Controls.Library ReportTitle = "Step Element Report"; //"Proms - Search by Type: " + typstr; TypesSelected = "Filtered By: " + typstr; SearchString = null; - SearchResults = ItemInfoList.GetListFromTextSearch(DVISearchList, TypeSearchList, "", cbxBooleanTxtSrch.Checked ? 2 : cbxCaseSensitive.Checked ? 1 : 0, ItemSearchIncludeLinks.Value, includeRTFformat, includeSpecialChars, unitPrefix, "", ""); + SearchResults = ItemInfoList.GetListFromTextSearch(DVISearchList, TypeSearchList, string.Empty, cbxBooleanTxtSrch.Checked ? 2 : cbxCaseSensitive.Checked ? 1 : 0, ItemSearchIncludeLinks.Value, includeRTFformat, includeSpecialChars, unitPrefix, string.Empty, string.Empty); cmbResultsStyleIndex = 1; //display step locations in results } } else { - //if (textSearchString.Equals("")) + //if (textSearchString.Equals(string.Empty)) //{ // MessageBox.Show("Please enter some search text, then click the Search button", "No Search Text"); // cbxTextSearchText.Focus(); @@ -1526,8 +1920,8 @@ namespace Volian.Controls.Library ReportTitle = string.Format("Search for '{0}'", TextSearchString); // C2020-009: Search - Allow search 'By Word'. - string byWordPrefix = ""; - string byWordSuffix = ""; + string byWordPrefix = string.Empty; + string byWordSuffix = string.Empty; if (cbxByWord.Checked) { // Generate a prefix & suffix to be used in the sql query around the search string. @@ -1567,13 +1961,13 @@ namespace Volian.Controls.Library LastSearchWasAnnotations = true; // B2019-119 only refresh annotation search results if an annotation search was done SearchString = null; //ReportTitle = string.Format("Proms - Annotation Search for '{0}'", cbxTextSearchAnnotation.Text); - if (cbxTextSearchAnnotation.Text == null || cbxTextSearchAnnotation.Text == "") + if (cbxTextSearchAnnotation.Text == null || cbxTextSearchAnnotation.Text == string.Empty) { - ReportTitle = string.Format("Find {0}{1}", cbxAnnoTypes.Text, (cbxAnnoTypes.SelectedIndex > 0) ? " Annotations" : ""); + ReportTitle = string.Format("Find {0}{1}", cbxAnnoTypes.Text, (cbxAnnoTypes.SelectedIndex > 0) ? " Annotations" : string.Empty); } else { - ReportTitle = string.Format("Search {0}{1} For '{2}'", cbxAnnoTypes.Text, (cbxAnnoTypes.SelectedIndex > 0) ? " Annotations" : "", cbxTextSearchAnnotation.Text); + ReportTitle = string.Format("Search {0}{1} For '{2}'", cbxAnnoTypes.Text, (cbxAnnoTypes.SelectedIndex > 0) ? " Annotations" : string.Empty, cbxTextSearchAnnotation.Text); } //ReportTitle = string.Format("Search Annotations for '{0}'", cbxTextSearchAnnotation.Text); //string srchStr = ConvertSpecialChars(cbxTextSearchAnnotation.Text);//cbxTextSearchAnnotation.Text; @@ -1595,7 +1989,7 @@ namespace Volian.Controls.Library //TypesSelected = "Searched Step Types: " + ((typstr != null) ? typstr : "All Step Types"); if (cbxFndUnLnkROVals.Enabled && cbxFndUnLnkROVals.Checked) { - SearchResults = ItemInfoList.GetListFromTextSearch(DVISearchList, TypeSearchList, ROSearchList, cbxBooleanTxtSrch.Checked ? 2 : cbxCaseSensitive.Checked ? 1 : 0, ItemSearchIncludeLinks.Nothing, includeRTFformat, includeSpecialChars, unitPrefix, "", ""); + SearchResults = ItemInfoList.GetListFromTextSearch(DVISearchList, TypeSearchList, ROSearchList, cbxBooleanTxtSrch.Checked ? 2 : cbxCaseSensitive.Checked ? 1 : 0, ItemSearchIncludeLinks.Nothing, includeRTFformat, includeSpecialChars, unitPrefix, string.Empty, string.Empty); cmbResultsStyleIndex = 3; // display step text in results } else @@ -1623,9 +2017,9 @@ namespace Volian.Controls.Library } // B2018-134 to search specifically for Outside Transitions, set docVeronList to empty string so that all procedure sets are considered if (cbxTranCategory.SelectedItem.ToString() == "Outside") - docVersionList = ""; + docVersionList = string.Empty; // added TypeSearchList for bug fix B2015-055 - SearchResults = ItemInfoList.GetListFromTransitionSearch(docVersionList, cbxTranFormat.SelectedIndex - 1, cbxTranCategory.SelectedItem.ToString() == "All" ? "" : cbxTranCategory.SelectedItem.ToString(), TypeSearchList); + SearchResults = ItemInfoList.GetListFromTransitionSearch(docVersionList, cbxTranFormat.SelectedIndex - 1, cbxTranCategory.SelectedItem.ToString() == "All" ? string.Empty : cbxTranCategory.SelectedItem.ToString(), TypeSearchList); cmbResultsStyleIndex = 3; // display step text in results // C2019-001: Search in RNO steps only if (cbxRnoOnlyTrans.Checked) GetInRNOResults(); @@ -1675,7 +2069,7 @@ namespace Volian.Controls.Library //if (VlnSettings.DebugMode) // MessageBox.Show(string.Format("{0} Milliseconds", TimeSpan.FromTicks(DateTime.Now.Ticks - start.Ticks).TotalMilliseconds)); } - + private void ClearResults() // B2021-103 if no results when RNO only, clear results list. (moved from btnSearch_Click) { if (tabSearchTypes.SelectedTab != tabSearchTypes.Tabs[4]) @@ -1697,6 +2091,7 @@ namespace Volian.Controls.Library { bool first = true; ItemInfoList iil = null; + foreach (ItemInfo ii in SearchResults) { if (ii.SearchPath.Contains(".RNO.")) @@ -1720,9 +2115,11 @@ namespace Volian.Controls.Library ClearResults(); // B2021-103 Clear results list if none found. } } + private void AddMessageForEmptyAnnotations() { bool hasAnnot = false; + foreach (ItemInfo ii in SearchResults) { if (ii.ItemAnnotations != null && ii.ItemAnnotationCount > 0) @@ -1786,10 +2183,8 @@ namespace Volian.Controls.Library { if (rbtnSrchTxt.Checked) cbxTextSearchText.Focus(); - } - private void gpSrchText_EnabledChanged(object sender, EventArgs e) { if (gpSrchText.Enabled) @@ -1819,45 +2214,56 @@ namespace Volian.Controls.Library InsertAnnotationSearchCriteria(); } } + #endregion - #region ProcSetSelection - private int _MyRODbID; - private static bool checkingChildren = false; + #region (ProcSetSelection) + private void advTreeProcSets_AfterCheck(object sender, DevComponents.AdvTree.AdvTreeCellEventArgs e) { // this method gets called if child nodes get checked by the code, return if doing this process. - if (checkingChildren) return; + if (checkingChildren) + return; + DevComponents.AdvTree.Node n = advTreeProcSets.SelectedNode; dicSelectedFolderNodes[n] = n.Checked; + // if this tree node is checked, and there are children, check the children too. if (n.Checked) { checkingChildren = true; - if (n.Nodes != null && n.Nodes.Count > 0 && n.Nodes[0].Text != "VLN_DUMMY") CheckTreeNodeChildren(n.Nodes); + if (n.Nodes != null && n.Nodes.Count > 0 && n.Nodes[0].Text != DummyNodeText) CheckTreeNodeChildren(n.Nodes); checkingChildren = false; } + // if the selected folder has a docversion, handle it: FolderInfo fi = (FolderInfo)n.Tag; RefreshLstCheckedDocVersions(); RefreshStepTypes();// Refresh Step Types after Working Draft is checked. + if (lstCheckedDocVersions.Count == 1 && fi.FolderDocVersions != null && fi.FolderDocVersions.Count > 0) { Mydocversion = fi.FolderDocVersions[0]; StartAdvTreeStepTypesFillIn();// B2016-258 Hang after selecting a procedure if the Step Type panel is open on the search panel } + SetupContextMenu(); buildSetToSearchPanelTitle(); } + // check all folder nodes below this private void CheckTreeNodeChildren(NodeCollection nodeCollection) { foreach (Node tn in nodeCollection) { - if (!tn.Checked) tn.Checked = true; - if (tn.Nodes != null && tn.Nodes.Count > 0 && tn.Nodes[0].Text != "VLN_DUMMY") CheckTreeNodeChildren(tn.Nodes); + if (!tn.Checked) + tn.Checked = true; + + if (tn.Nodes != null && tn.Nodes.Count > 0 && tn.Nodes[0].Text != DummyNodeText) + CheckTreeNodeChildren(tn.Nodes); } } + // The 'lstCheckedDocVersions' maintains a list of the docversions that are associated with folders that are checked // on the search tree of folders, i.e. procedure sets that should be included in the search. private void RefreshLstCheckedDocVersions() @@ -1866,34 +2272,47 @@ namespace Volian.Controls.Library AddFromTreeNodes(advTreeProcSets.Nodes); // add docversions to the list LoadROComboTree(); // reset the ro tree based on docversion selections. } + private void AddFromTreeNodes(NodeCollection nodeCollection) { foreach (Node tn in nodeCollection) + { AddFromTreeNode(tn); + } } + private void AddFromTreeNode(Node tn) { if (tn.Checked) { - tn.Style = DevComponents.AdvTree.NodeStyles.Apple; // sets green background on selected folder(s) + tn.Style = DevComponents.AdvTree.NodeStyles.Apple; // sets green background on selected folder(s) FolderInfo fi = (FolderInfo)tn.Tag; + // if this folder has a docversion, use its id: - if (tn.Nodes != null && tn.Nodes.Count > 0 && tn.Nodes[0].Text != "VLN_DUMMY") // Folder has been expanded, so add its docversion list + if (tn.Nodes != null && tn.Nodes.Count > 0 && tn.Nodes[0].Text != DummyNodeText) // Folder has been expanded, so add its docversion list { if (fi.FolderDocVersionCount > 0) lstCheckedDocVersions.Add(fi.FolderDocVersions[0]); } else // it has not been expanded process all below. + { AddAllChildVersions(fi); + } } else // not checked, set style so no background color + { tn.Style = null; - if (tn.Nodes != null) AddFromTreeNodes(tn.Nodes); + } + + if (tn.Nodes != null) + AddFromTreeNodes(tn.Nodes); } + private void RemoveAllVersions(FolderInfo child) { RemoveAllChildVersions(child); RefreshStepTypes(); // Refresh the Step Type TreeView } + /// /// RessetStepTypes - Clear Step Type Treeview /// @@ -1901,6 +2320,7 @@ namespace Volian.Controls.Library { ResetStepTypes("....select a procedure set for types to appear..."); } + private void ResetStepTypes(string str) { advTreeStepTypes.Nodes.Clear(); @@ -1911,11 +2331,13 @@ namespace Volian.Controls.Library advTreeStepTypes.Nodes.Add(newnode); buildStepTypePannelTitle(); } + private void AddAllVersions(FolderInfo child) { AddAllChildVersions(child); RefreshStepTypes(); } + /// /// RefreshStepTypes - Updates the StepType TreeView to allow step types to be specified. /// @@ -1926,7 +2348,9 @@ namespace Volian.Controls.Library ResetStepTypes(); return; } + string formatName = lstCheckedDocVersions[0].ActiveFormat.Name; + foreach (DocVersionInfo dvi in lstCheckedDocVersions) { if (formatName != dvi.ActiveFormat.Name) @@ -1935,40 +2359,70 @@ namespace Volian.Controls.Library return; } } + _MyDocVersion = lstCheckedDocVersions[0]; - StartAdvTreeStepTypesFillIn();// B2016-258 Hang after selecting a procedure if the Step Type panel is open on the search panel + + // B2016-258 Hang after selecting a procedure if the Step Type panel is open on the search panel + StartAdvTreeStepTypesFillIn(); } + // remove all docversion children private void RemoveAllChildVersions(FolderInfo myFolderInfo) { if (myFolderInfo.FolderDocVersionCount > 0) - foreach(DocVersionInfo dvi in myFolderInfo.FolderDocVersions) - if(lstCheckedDocVersions.Contains (dvi)) - lstCheckedDocVersions.Remove(dvi); + { + foreach (DocVersionInfo dvi in myFolderInfo.FolderDocVersions) + { + if (lstCheckedDocVersions.Contains(dvi)) + lstCheckedDocVersions.Remove(dvi); + } + } + if (myFolderInfo.ChildFolders != null) + { foreach (FolderInfo folderChild in myFolderInfo.ChildFolders) + { RemoveAllChildVersions(folderChild); + } + } } + // add all docversion children private void AddAllChildVersions(FolderInfo myFolderInfo) { if (myFolderInfo.FolderDocVersionCount > 0) - foreach(DocVersionInfo dvi in myFolderInfo.FolderDocVersions) + { + foreach (DocVersionInfo dvi in myFolderInfo.FolderDocVersions) + { if (!lstCheckedDocVersions.Contains(dvi)) lstCheckedDocVersions.Add(dvi); + } + } + if (myFolderInfo.ChildFolders != null) + { foreach (FolderInfo folderChild in myFolderInfo.ChildFolders) + { AddAllChildVersions(folderChild); + } + } } + private void cbxTranFormatFillIn(string vid) { vid = vid.IndexOf(",") < 0 ? vid : vid.Substring(0, cbxTranVersion.Tag.ToString().IndexOf(",")); + DocVersionInfo dvi = DocVersionInfo.Get(int.Parse(vid)); TransTypeList ttl = dvi.ActiveFormat.PlantFormat.FormatData.TransData.TransTypeList; + cbxTranFormat.Items.Clear(); cbxTranFormat.Items.Add("All"); + for (int i = 0; i < ttl.MaxIndex; i++) - cbxTranFormat.Items.Add(new TransItem(ttl[i].TransMenu.Replace("?.", ""), ttl[i].TransFormat.Replace("?.", ""))); + { + cbxTranFormat.Items.Add(new TransItem(ttl[i].TransMenu.Replace("?.", string.Empty), ttl[i].TransFormat.Replace("?.", string.Empty))); + } + cbxTranFormat.SelectedIndex = 0; cbxTranCategory.Items.Clear(); cbxTranCategory.Items.Add("All"); @@ -1976,16 +2430,13 @@ namespace Volian.Controls.Library cbxTranCategory.Items.Add("External"); cbxTranCategory.Items.Add("Outside"); cbxTranCategory.SelectedIndex = 0; - /* - groupPanelTranFmt.Style.BackColor = (_CurTrans == null && _TranFmtIndx==0) ? Color.Yellow : Color.Orange; - E_TransUI etm = (E_TransUI)_CurItemFrom.ActiveFormat.PlantFormat.FormatData.TransData.TransTypeList[_TranFmtIndx].TransUI; - _DoingRange = (etm & E_TransUI.StepLast) == E_TransUI.StepLast; - */ } + private void xpSetToSearch_ExpandedChanged(object sender, ExpandedChangeEventArgs e) { buildSetToSearchPanelTitle(); } + private void buildSetToSearchPanelTitle() { if (lstCheckedDocVersions.Count == 0) @@ -1994,29 +2445,21 @@ namespace Volian.Controls.Library xpSetToSearch.TitleStyle.BackColor1.Color = Color.PapayaWhip; btnSearch.Enabled = true; tabSearchTypes.Enabled = true; // enable all the search tabs - // xpSetToSearch.Expanded = true; - // xpSetToSearch.TitleStyle.BackColor1.Color = Color.Crimson; - // btnSearch.Enabled = false; - // tabSearchTypes.Enabled = false; // disable all the search tabs - // //if (xpSetToSearch.Expanded) - // xpSetToSearch.TitleText = "Select Procedure Sets to Search"; - // //else - // // xpSetToSearch.TitleText = "Click Here to Select Procedure Sets"; - - // //xpSetToSearch.TitleStyle.BackColor1.Color = saveXpSetToSearchColor; } - else //if (lstCheckedDocVersions.Count > 0) + else { - // display the number of selected procedure sets whether pannel is expanded or not + // display the number of selected procedure sets whether panel is expanded or not xpSetToSearch.TitleText = string.Format("{0} Procedure Sets Selected", lstCheckedDocVersions.Count); xpSetToSearch.TitleStyle.BackColor1.Color = Color.PapayaWhip; btnSearch.Enabled = true; tabSearchTypes.Enabled = true; // enable all the search tabs } } + private void advTreeProcSets_AfterNodeSelect(object sender, AdvTreeNodeEventArgs e) { DevComponents.AdvTree.Node n = advTreeProcSets.SelectedNode; + if (advTreeStepTypes.Nodes.Count == 1 && n.Checked) { if (n.Tag is DocVersionInfo) // Only set MyDocVersion if it is a DocVersion @@ -2026,18 +2469,25 @@ namespace Volian.Controls.Library } } } + #endregion - #region StepTypeSelection + #region (StepTypeSelection) + private void advTreeStepTypes_AfterCheck(object sender, DevComponents.AdvTree.AdvTreeCellEventArgs e) { xpStepTypes.TitleStyle.BackColor1.Color = saveXpStepTypeTitleColor; DevComponents.AdvTree.Node n = advTreeStepTypes.SelectedNode; - if (n == null) return; + + if (n == null) + return; + StepData sd = (StepData)n.Tag; + if (n.Checked) { n.Style = DevComponents.AdvTree.NodeStyles.Apple; + if (sd == null) { if (!lstCheckedStepTypesStr.Contains("WORD Sections")) @@ -2058,6 +2508,7 @@ namespace Volian.Controls.Library else { n.Style = null; + if (sd == null) { lstCheckedStepTypesStr.Remove("WORD Sections"); @@ -2066,15 +2517,18 @@ namespace Volian.Controls.Library else { lstCheckedStepTypes.Remove((int)sd.Index); - //lstCheckedStepTypesStr.Remove(sd.Type); lstCheckedStepTypesStr.Remove(advTreeStepTypes.SelectedNode.Text); } } + buildStepTypePannelTitle(); + // B2021-100: Enable/disable the RNO Only checkbox & WORD Sections tree node in Step Elements to Search. // The only time the RNO Only checkbox is disabled is if the only selection in Step Elements to Search is WORD Sections. cbxRnoOnly.Enabled = true; - if (OnlyWordSectTypeSel()) cbxRnoOnly.Checked = cbxRnoOnly.Enabled = false; + + if (OnlyWordSectTypeSel()) + cbxRnoOnly.Checked = cbxRnoOnly.Enabled = false; } private void xpStepTypes_ExpandedChanged(object sender, ExpandedChangeEventArgs e) @@ -2088,35 +2542,41 @@ namespace Volian.Controls.Library { if (xpStepTypes.Expanded) { - xpStepTypes.TitleText = "Select Step Elements To Search";//"Select Types To Search"; + xpStepTypes.TitleText = "Select Step Elements To Search"; //"Select Types To Search"; advTreeStepTypes.Focus(); advTreeStepTypes.Nodes[0].SelectedCell = advTreeStepTypes.Nodes[0].Cells[0]; } else - xpStepTypes.TitleText = "Click Here To Search By Step Element";//"Click Here To Search By Types"; + { + xpStepTypes.TitleText = "Click Here To Search By Step Element"; //"Click Here To Search By Types"; + } xpStepTypes.TitleStyle.BackColor1.Color = saveXpStepTypeTitleColor; } else //lstCheckedStepTypes.Count > 0 { - // show how many selected whether pannel is expanded or not - //xpStepTypes.TitleText = string.Format("{0} Step Styles Selected", lstCheckedStepTypes.Count); - xpStepTypes.TitleText = string.Format("{0} Step Element{1} Selected", lstCheckedStepTypes.Count, (lstCheckedStepTypes.Count > 1)?"s":""); // B2018-132 changed second {0} to {1} + // show how many selected whether panel is expanded or not + xpStepTypes.TitleText = string.Format("{0} Step Element{1} Selected", lstCheckedStepTypes.Count, (lstCheckedStepTypes.Count > 1)?"s":string.Empty); // B2018-132 changed second {0} to {1} xpStepTypes.TitleStyle.BackColor1.Color = Color.PapayaWhip; } } #endregion - #region ContextMenu + #region (ContextMenu) private void btnSym_Click(object sender, EventArgs e) { DevComponents.DotNetBar.ButtonItem b = (DevComponents.DotNetBar.ButtonItem)sender; + if (cbxTextSearchAnnotation.Focused) + { cbxTextSearchAnnotation.SelectedText = (string)b.Text; + } else if (cbxTextSearchText.Focused) + { cbxTextSearchText.SelectedText = (string)b.Text; + } } private void cmFndTxtInsHardSp_Click(object sender, EventArgs e) @@ -2124,72 +2584,54 @@ namespace Volian.Controls.Library // We use \u00A0 to represent a hard space because it show in the search text field as a blank // It will get translated to a real hard space character prior to searching if (cbxTextSearchAnnotation.Focused) - cbxTextSearchAnnotation.SelectedText = "\u00A0"; - else if (cbxTextSearchText.Focused) - cbxTextSearchText.SelectedText = "\u00A0"; - } - // Changed to a public so that it could be called after the /DB parameter has been processed - public void SetupContextMenu() - { - galSymbols.SubItems.Clear(); - // Bug fix B2014-057 - // if we are searching for a symbol character in all procedure sets MyDocVersion is null - // when MyDocVersion is null, get the symbol list directly from the PROMS base format (BaseAll.xml) - // this will populate the context menu of the Search text entry field so that a symbol can be selected without first selecting a procedure set - FormatData fmtdata = (_MyDocVersion != null) ? _MyDocVersion.ActiveFormat.PlantFormat.FormatData : FormatInfo.PROMSBaseFormat.FormatData; - if (fmtdata != null && fmtdata.SymbolList != null) { - SymbolList sl = fmtdata.SymbolList; - if (sl == null || sl.Count <= 0) - { - FlexibleMessageBox.Show("No symbols are available, check with administrator"); - return; - } - foreach (Symbol sym in sl) - { - DevComponents.DotNetBar.ButtonItem btnCM = new DevComponents.DotNetBar.ButtonItem(); - btnCM.Text = string.Format("{0}", (char)sym.Unicode); - // to name button use unicode rather than desc, desc may have spaces or odd chars - btnCM.Name = "btnCM" + sym.Unicode.ToString(); - btnCM.Tooltip = sym.Desc; - btnCM.Tag = string.Format(@"{0}", sym.Unicode); - btnCM.FontBold = true; - btnCM.Click += new System.EventHandler(btnSym_Click); - galSymbols.SubItems.Add(btnCM); - } + cbxTextSearchAnnotation.SelectedText = "\u00A0"; + } + else if (cbxTextSearchText.Focused) + { + cbxTextSearchText.SelectedText = "\u00A0"; } } - + private void cmFndTxtCut_Click(object sender, EventArgs e) { Clipboard.Clear(); DataObject myDO = new DataObject(DataFormats.Text, cbxTextSearchAnnotation.Focused ? cbxTextSearchAnnotation.SelectedText : cbxTextSearchText.SelectedText); Clipboard.SetDataObject(myDO); + // Need to check which combo box activated the context menu so that we know where to take/put selected text if (cbxTextSearchAnnotation.Focused) - cbxTextSearchAnnotation.SelectedText = ""; + { + cbxTextSearchAnnotation.SelectedText = string.Empty; + } else if (cbxTextSearchText.Focused) - cbxTextSearchText.SelectedText = ""; - + { + cbxTextSearchText.SelectedText = string.Empty; + } } private void cmFndTxtCopy_Click(object sender, EventArgs e) { // Need to check which combo box activated the context menu so that we know where to take/put selected text DataObject myDO = new DataObject(DataFormats.Text, cbxTextSearchAnnotation.Focused ? cbxTextSearchAnnotation.SelectedText : cbxTextSearchText.SelectedText); + if (cbxTextSearchText.Focused || cbxTextSearchAnnotation.Focused) { Clipboard.Clear(); Clipboard.SetDataObject(myDO); } } + private bool OnlyWordSectTypeSel() { // B2021-100: Enable/disable the RNO Only checkbox & WORD Sections tree node in Step Elements to Search. // lstCheckedStepTypes[x] = 0 for Word sections: - if (lstCheckedStepTypes != null && lstCheckedStepTypes.Count == 1 && lstCheckedStepTypes[0] == 0) return true; + if (lstCheckedStepTypes != null && lstCheckedStepTypes.Count == 1 && lstCheckedStepTypes[0] == 0) + return true; + return false; } + private void CbxRnoOnly_Click(object sender, System.EventArgs e) { // C2021-028: RNO Only search, disable Word section tree node: @@ -2209,28 +2651,27 @@ namespace Volian.Controls.Library if (!wordSectionTreeNode.Enabled) wordSectionTreeNode.Checked = false; } else // turning off - WORD Sections tree node is enabled. + { wordSectionTreeNode.Enabled = true; + } } + private void cmFndTxtPaste_Click(object sender, EventArgs e) { // Need to check which combo box activated the context menu so that we know where to take/put selected text IDataObject myDO = Clipboard.GetDataObject(); - //if (myDO.GetDataPresent(DataFormats.Rtf)) - //{ - // RichTextBox rtb = new RichTextBox(); - // rtb.SelectedRtf = ItemInfo.StripLinks(myDO.GetData(DataFormats.Rtf).ToString()); - // if (cbxTextSearchAnnotation.Focused) - // cbxTextSearchAnnotation.SelectedText = rtb.Text; - // else if (cbxTextSearchText.Focused) - // cbxTextSearchText.SelectedText = rtb.Text;// .SelectedText;//myDO.GetData(DataFormats.Text,true).ToString(); - //} - //else if (myDO.GetDataPresent(DataFormats.Text)) if (myDO.GetDataPresent(DataFormats.Text)) + { if (cbxTextSearchAnnotation.Focused) + { cbxTextSearchAnnotation.SelectedText = Clipboard.GetText(); + } else if (cbxTextSearchText.Focused) - cbxTextSearchText.SelectedText = Clipboard.GetText();//myDO.GetData(DataFormats.Text).ToString(); + { + cbxTextSearchText.SelectedText = Clipboard.GetText(); + } + } } private void btnCMIFindText_PopupOpen(object sender, PopupOpenEventArgs e) @@ -2248,15 +2689,19 @@ namespace Volian.Controls.Library cbxTextSearchText.Focus(); } } + #endregion + + #region (Button/UI Event Handlers) + private void buttonItem2_Click(object sender, EventArgs e) { if (cbxTextSearchAnnotation.Focused) cbxTextSearchAnnotation.SelectedText = "*"; else if (cbxTextSearchText.Focused) cbxTextSearchText.SelectedText = "*"; - } + private void buttonItem3_Click(object sender, EventArgs e) { if (cbxTextSearchAnnotation.Focused) @@ -2265,6 +2710,7 @@ namespace Volian.Controls.Library cbxTextSearchText.SelectedText = "?"; } + private void buttonItem4_Click(object sender, EventArgs e) { if (cbxTextSearchAnnotation.Focused) @@ -2272,6 +2718,7 @@ namespace Volian.Controls.Library else if (cbxTextSearchText.Focused) cbxTextSearchText.SelectedText = "?*"; } + private void cbxBooleanTxtSrch_CheckedChanged(object sender, EventArgs e) { // If the Boolean search is not working - run the following two commands in SQL: @@ -2284,15 +2731,12 @@ namespace Volian.Controls.Library // Another file exists in that directory, tsenu.xml, this is a thesaurus. RHM tried // to use around 2010, but couldn't get it to work for words like 'dg' versus 'diesel generator', // and 'sg' versus 'steam generator'. + if (cbxBooleanTxtSrch.Checked) { gpSrchText.Style.BackColor = Color.Orange; btnCMIFindText.SubItems[1].SubItems[2].Visible = false; btnCMIFindText.SubItems[1].SubItems[3].Visible = true; - //cbxCaseSensitive.Checked = false; - //cbxCaseSensitive.Enabled = false; - //cbxIncROTextSrch.Checked = true; - //cbxIncROTextSrch.Enabled = false; cbxCaseSensitive.Enabled = false; cbxIncROTextSrch.Enabled = false; } @@ -2301,12 +2745,11 @@ namespace Volian.Controls.Library gpSrchText.Style.BackColor = Color.Yellow; btnCMIFindText.SubItems[1].SubItems[2].Visible = true; btnCMIFindText.SubItems[1].SubItems[3].Visible = false; - //cbxCaseSensitive.Enabled = true; - //cbxIncROTextSrch.Enabled = true; cbxCaseSensitive.Enabled = true; cbxIncROTextSrch.Enabled = true; } } + private void cbxBooleanAnoTxtSrch_CheckedChanged(object sender, EventArgs e) { if (cbxBooleanAnoTxtSrch.Checked) @@ -2322,22 +2765,23 @@ namespace Volian.Controls.Library btnCMIFindText.SubItems[1].SubItems[3].Visible = false; } } + private void btnAND_Click(object sender, EventArgs e) { if (cbxTextSearchAnnotation.Focused) cbxTextSearchAnnotation.SelectedText = " AND "; else if (cbxTextSearchText.Focused) cbxTextSearchText.SelectedText = " AND "; - } + private void btnOR_Click(object sender, EventArgs e) { if (cbxTextSearchAnnotation.Focused) cbxTextSearchAnnotation.SelectedText = " OR "; else if (cbxTextSearchText.Focused) cbxTextSearchText.SelectedText = " OR "; - } + private void btnNOT_Click(object sender, EventArgs e) { if (cbxTextSearchAnnotation.Focused) @@ -2345,44 +2789,48 @@ namespace Volian.Controls.Library else if (cbxTextSearchText.Focused) cbxTextSearchText.SelectedText = " NOT "; } + private void tabAnnotationSearch_Click(object sender, EventArgs e) { cbxAnnoTypes.Focus(); cbxBooleanAnoTxtSrch_CheckedChanged(sender, e); } + private void btnClearSearchResults_Click(object sender, EventArgs e) { if (tabSearchTypes.SelectedTab == tabIncTrans) // C2020-033: Clear the Incoming Transitions list box { lbSrchResultsIncTrans.DataSource = null; - lbSrchResultsIncTrans.Items.Clear(); + lbSrchResultsIncTrans.Items.Clear(); } else + { lbSrchResults.DataSource = null; + } + _SearchResults = null; DisplayResults(); btnTranCvtAllToTxt.Enabled = false; } - // A timer updated the step type tree but if it was loaded from xml the timer update overwrite what - // was loaded in from the xml file. Added a flag that gets set on load and set to false on new Search - private bool _fromLoad = false; private void btnLoadSearchResults_Click(object sender, System.EventArgs e) { _fromLoad = true; _LoadingList = true; ofdSearchResults.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\VEPROMS"; + if (ofdSearchResults.ShowDialog(this) == DialogResult.OK) { lbSrchResults.DataSource = null; lbSrchResults.Items.Clear(); toolTip1.SetToolTip(lbSrchResults, null); - string unitPrefix = ""; + string unitPrefix = string.Empty; if (Mydocversion != null) unitPrefix = Mydocversion.DocVersionConfig.Unit_ProcedureNumber; if (unitPrefix.EndsWith("#")) - unitPrefix = unitPrefix.Replace("#", ""); + unitPrefix = unitPrefix.Replace("#", string.Empty); Cursor = Cursors.WaitCursor; + try // B2021-045: don't crash if xml file cannot be loaded. { SearchResults = ItemInfoList.GetByContentID(0); @@ -2412,8 +2860,10 @@ namespace Volian.Controls.Library } Mydocversion = tmpdvi == null ? fromLoadFiledvi : tmpdvi; } + AdvTreeStepTypesFillIn(); System.Xml.XmlNodeList nl1 = xd.SelectNodes("search/StepType/type"); + if (nl1 != null) { foreach (System.Xml.XmlNode nd in nl1) @@ -2429,6 +2879,7 @@ namespace Volian.Controls.Library lstCheckedStepTypes.Add((int)sd.Index); } } + string typstr = null; foreach (string s in lstCheckedStepTypesStr) typstr = typstr == null ? s : typstr + ", " + s; TypesSelected = "Filtered By: " + ((typstr != null) ? typstr : "All Step Types"); @@ -2437,6 +2888,7 @@ namespace Volian.Controls.Library advTreeStepTypes.RefreshItems(); buildStepTypePannelTitle(); } + cmbResultsStyle.Text = xd.SelectSingleNode("search/results/@style").InnerText; int sti = int.Parse(xd.SelectSingleNode("search/criteria/@index").InnerText); switch (sti) @@ -2445,6 +2897,7 @@ namespace Volian.Controls.Library { System.Xml.XmlNode xn = xd.SelectSingleNode("search/criteria/@text"); tabSearchTypes.SelectedTab = tabStepTypeSearch; + if (xn != null) // text search { cbxTextSearchText.Text = xn.InnerText; @@ -2469,6 +2922,7 @@ namespace Volian.Controls.Library DisplayResults(); break; } + case 1: //annotation { cbxAnnoTypes.Text = xd.SelectSingleNode("search/criteria/@type").InnerText; @@ -2477,6 +2931,7 @@ namespace Volian.Controls.Library tabSearchTypes.SelectedTab = tabAnnotationSearch; cmbResultsStyle.Text = xd.SelectSingleNode("search/results/@style").InnerText; System.Xml.XmlNodeList nl = xd.SelectNodes("search/results/item"); + foreach (System.Xml.XmlNode nd in nl) { int itemID = int.Parse(nd.Attributes.GetNamedItem("id").InnerText); @@ -2489,16 +2944,19 @@ namespace Volian.Controls.Library } SearchResults.AddItemInfo(ii); } + lbSrchResults.DataSource = SearchResults; DisplayResults(); break; } + case 2: //referenced object case 3: // transitions { FlexibleMessageBox.Show(this, "Loading Referenced Objects and Transitions searches is under construction.", "Under Construction", MessageBoxButtons.OK); break; } + case 4: // Incoming transitions { tabSearchTypes.SelectedTab = tabIncTrans; @@ -2524,8 +2982,10 @@ namespace Volian.Controls.Library FlexibleMessageBox.Show("An error occurred while reading the xml file.\r\n\r\nThis can happen when the file selected for the Load is not saved\r\n" + "from a PROMS Search or if some of the steps no longer exist.", "Search Load Failed", MessageBoxButtons.OK); } + Cursor = Cursors.Default; } + btnTranCvtAllToTxt.Enabled = IncTransCvtAllToTextPerm(); // C2020-033: does user have access to at least one item _LoadingList = false; } @@ -2533,13 +2993,20 @@ namespace Volian.Controls.Library private void btnSaveSearchResults_Click(object sender, System.EventArgs e) { ICollection myList = lbSrchResults.DataSource as ICollection; - if (tabSearchTypes.SelectedTab == tabSearchTypes.Tabs[4]) myList = lbSrchResultsIncTrans.DataSource as ICollection; // C2020-033: use Incoming transition list + + if (tabSearchTypes.SelectedTab == tabSearchTypes.Tabs[4]) + { + myList = lbSrchResultsIncTrans.DataSource as ICollection; // C2020-033: use Incoming transition list + } + if (tabSearchTypes.SelectedTabIndex == 2 || tabSearchTypes.SelectedTabIndex == 3) // ROs & Transitions are not coded yet { FlexibleMessageBox.Show(this, "Saving Referenced Objects and Transitions searches is under construction.", "Under Construction", MessageBoxButtons.OK); return; } + sfdSearchResults.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\VEPROMS"; + if (sfdSearchResults.ShowDialog(this) == DialogResult.OK) { // C2021-006: removed all file type options except xml @@ -2556,11 +3023,13 @@ namespace Volian.Controls.Library // do procsets selected System.Xml.XmlElement xp = null; System.Xml.XmlElement xst = null; - if (sti != 4) // C2020-033: no procsets or step types for Incoming transitions + + if (sti != 4) // C2020-033: no procsets or step types for Incoming transitions { if (lstCheckedDocVersions != null && lstCheckedDocVersions.Count > 0) { xp = xd.CreateElement("procsets"); + foreach (DocVersionInfo dvi in lstCheckedDocVersions) { System.Xml.XmlElement xee = xd.CreateElement("set"); @@ -2570,9 +3039,11 @@ namespace Volian.Controls.Library xp.AppendChild(xee); } } + if (lstCheckedStepTypesStr != null && lstCheckedStepTypesStr.Count > 0) { xst = xd.CreateElement("StepType"); + foreach (string str in lstCheckedStepTypesStr) // Limited by step types { System.Xml.XmlElement xee = xd.CreateElement("type"); @@ -2583,105 +3054,105 @@ namespace Volian.Controls.Library } } } + switch (sti) { case 0: //text + if (!cbxSrchTypeUsage.Checked) // text search { - - if (!cbxSrchTypeUsage.Checked) // text search - { - xa = xd.CreateAttribute("text"); - xa.InnerText = cbxTextSearchText.Text; - xe.Attributes.SetNamedItem(xa); - xa = xd.CreateAttribute("case"); - xa.InnerText = cbxCaseSensitive.Checked.ToString(); - xe.Attributes.SetNamedItem(xa); - xa = xd.CreateAttribute("ro"); - xa.InnerText = cbxIncROTextSrch.Checked.ToString(); - xe.Attributes.SetNamedItem(xa); - xa = xd.CreateAttribute("byword"); - xa.InnerText = cbxByWord.Checked.ToString(); - xe.Attributes.SetNamedItem(xa); - xd.DocumentElement.AppendChild(xe); - - } - if (xp != null) xd.DocumentElement.AppendChild(xp); // want criteria as first xml node - if (xst != null) xd.DocumentElement.AppendChild(xst); // do procsets & steptypes after - // do results - xe = xd.CreateElement("results"); - xa = xd.CreateAttribute("style"); - xa.InnerText = cmbResultsStyle.Text; - xe.Attributes.SetNamedItem(xa); - foreach (ItemInfo ii in myList) - { - System.Xml.XmlElement xee = xd.CreateElement("item"); - xa = xd.CreateAttribute("id"); - xa.InnerText = ii.ItemID.ToString(); - xee.Attributes.SetNamedItem(xa); - xe.AppendChild(xee); - } - xd.DocumentElement.AppendChild(xe); - xd.Save(sfdSearchResults.FileName); - break; - } - case 1: //annotation - { - xa = xd.CreateAttribute("type"); - xa.InnerText = cbxAnnoTypes.Text; - xe.Attributes.SetNamedItem(xa); xa = xd.CreateAttribute("text"); - xa.InnerText = cbxTextSearchAnnotation.Text; + xa.InnerText = cbxTextSearchText.Text; xe.Attributes.SetNamedItem(xa); xa = xd.CreateAttribute("case"); - xa.InnerText = cbxCaseSensitiveAnnoText.Checked.ToString(); + xa.InnerText = cbxCaseSensitive.Checked.ToString(); + xe.Attributes.SetNamedItem(xa); + xa = xd.CreateAttribute("ro"); + xa.InnerText = cbxIncROTextSrch.Checked.ToString(); + xe.Attributes.SetNamedItem(xa); + xa = xd.CreateAttribute("byword"); + xa.InnerText = cbxByWord.Checked.ToString(); xe.Attributes.SetNamedItem(xa); xd.DocumentElement.AppendChild(xe); - if (xp != null) xd.DocumentElement.AppendChild(xp); // want criteria as first xml node - if (xst != null) xd.DocumentElement.AppendChild(xst); // do procsets & steptypes after - xe = xd.CreateElement("results"); - xa = xd.CreateAttribute("style"); - xa.InnerText = cmbResultsStyle.Text; - xe.Attributes.SetNamedItem(xa); - foreach (ItemInfo ii in myList) - { - System.Xml.XmlElement xee = xd.CreateElement("item"); - xa = xd.CreateAttribute("id"); - xa.InnerText = ii.ItemID.ToString(); - xee.Attributes.SetNamedItem(xa); - xe.AppendChild(xee); - } - xd.DocumentElement.AppendChild(xe); - xd.Save(sfdSearchResults.FileName); - break; } + + if (xp != null) xd.DocumentElement.AppendChild(xp); // want criteria as first xml node + if (xst != null) xd.DocumentElement.AppendChild(xst); // do procsets & steptypes after + // do results + xe = xd.CreateElement("results"); + xa = xd.CreateAttribute("style"); + xa.InnerText = cmbResultsStyle.Text; + xe.Attributes.SetNamedItem(xa); + + foreach (ItemInfo ii in myList) + { + System.Xml.XmlElement xee = xd.CreateElement("item"); + xa = xd.CreateAttribute("id"); + xa.InnerText = ii.ItemID.ToString(); + xee.Attributes.SetNamedItem(xa); + xe.AppendChild(xee); + } + + xd.DocumentElement.AppendChild(xe); + xd.Save(sfdSearchResults.FileName); + break; + + case 1: //annotation + xa = xd.CreateAttribute("type"); + xa.InnerText = cbxAnnoTypes.Text; + xe.Attributes.SetNamedItem(xa); + xa = xd.CreateAttribute("text"); + xa.InnerText = cbxTextSearchAnnotation.Text; + xe.Attributes.SetNamedItem(xa); + xa = xd.CreateAttribute("case"); + xa.InnerText = cbxCaseSensitiveAnnoText.Checked.ToString(); + xe.Attributes.SetNamedItem(xa); + xd.DocumentElement.AppendChild(xe); + if (xp != null) xd.DocumentElement.AppendChild(xp); // want criteria as first xml node + if (xst != null) xd.DocumentElement.AppendChild(xst); // do procsets & steptypes after + xe = xd.CreateElement("results"); + xa = xd.CreateAttribute("style"); + xa.InnerText = cmbResultsStyle.Text; + xe.Attributes.SetNamedItem(xa); + + foreach (ItemInfo ii in myList) + { + System.Xml.XmlElement xee = xd.CreateElement("item"); + xa = xd.CreateAttribute("id"); + xa.InnerText = ii.ItemID.ToString(); + xee.Attributes.SetNamedItem(xa); + xe.AppendChild(xee); + } + + xd.DocumentElement.AppendChild(xe); + xd.Save(sfdSearchResults.FileName); + break; + case 2: // ro case 3: // transitions - { - FlexibleMessageBox.Show(this, "Saving Search Results for this search type is under construction.", "Under Construction", MessageBoxButtons.OK); - break; - } + FlexibleMessageBox.Show(this, "Saving Search Results for this search type is under construction.", "Under Construction", MessageBoxButtons.OK); + break; + case 4: // C2020-033: Incoming Transitions + xe = xd.CreateElement("results"); + xa = xd.CreateAttribute("style"); + xa.InnerText = cmbResultsStyle.Text; + xe.Attributes.SetNamedItem(xa); + xa = xd.CreateAttribute("toid"); + xa.InnerText = SearchIncTransII.ItemID.ToString(); + xe.Attributes.SetNamedItem(xa); + + foreach (ItemInfo ii in myList) { - // do results - xe = xd.CreateElement("results"); - xa = xd.CreateAttribute("style"); - xa.InnerText = cmbResultsStyle.Text; - xe.Attributes.SetNamedItem(xa); - xa = xd.CreateAttribute("toid"); - xa.InnerText = SearchIncTransII.ItemID.ToString(); - xe.Attributes.SetNamedItem(xa); - foreach (ItemInfo ii in myList) - { - System.Xml.XmlElement xee = xd.CreateElement("item"); - xa = xd.CreateAttribute("id"); - xa.InnerText = ii.ItemID.ToString(); - xee.Attributes.SetNamedItem(xa); - xe.AppendChild(xee); - } - xd.DocumentElement.AppendChild(xe); - xd.Save(sfdSearchResults.FileName); - break; + System.Xml.XmlElement xee = xd.CreateElement("item"); + xa = xd.CreateAttribute("id"); + xa.InnerText = ii.ItemID.ToString(); + xee.Attributes.SetNamedItem(xa); + xe.AppendChild(xee); } + + xd.DocumentElement.AppendChild(xe); + xd.Save(sfdSearchResults.FileName); + break; } } } @@ -2693,44 +3164,28 @@ namespace Volian.Controls.Library StringBuilder sb = new StringBuilder(); sb.Append("\"Location\"\t\"Type\"\t\"Text\"\t\"High-Level\"\t\"Annotations\""); List ItemsProcessed = new List(); + foreach (ItemInfo myItem in myList) { if (!ItemsProcessed.Contains(myItem.ItemID)) { ItemsProcessed.Add(myItem.ItemID); sb.Append(string.Format("\r\n\"{0}\"\t\"{1}\"\t\"{2}\"\t\"{3}\"", myItem.ShortPath, myItem.ToolTip, - myItem.DisplayText, !myItem.IsSection && !myItem.IsHigh ? (myItem.MyHLS == null ? "" : myItem.MyHLS.DisplayText) : "")); + myItem.DisplayText, !myItem.IsSection && !myItem.IsHigh ? (myItem.MyHLS == null ? string.Empty : myItem.MyHLS.DisplayText) : string.Empty)); if (myItem.ItemAnnotationCount > 0) foreach (AnnotationInfo myAnnotation in myItem.ItemAnnotations) sb.Append(string.Format("\t\"{0}\"", myAnnotation.SearchText)); } } + Clipboard.Clear(); Clipboard.SetText(sb.ToString()); FlexibleMessageBox.Show("Results Copied to Clipboard", "Copy Results", MessageBoxButtons.OK, MessageBoxIcon.Information); } - private string _ReportTitle; - public string ReportTitle - { - get { return _ReportTitle; } - set { _ReportTitle = value; } - } - private string _SearchString = null; - public string SearchString - { - get { return _SearchString; } - set { _SearchString = value; } - } - private string _TypesSelected; - public string TypesSelected - { - get { return _TypesSelected; } - set { _TypesSelected = value; } - } private void btnPrnSrchRslts_Click(object sender, EventArgs e) { - string sortedBy = ""; + string sortedBy = string.Empty; if (cbSorted.Checked) sortedBy = string.Format("Sorted By: {0}", cmbResultsStyle.Text); //C2019-013 pass in sorted by information ICollection srchres = lbSrchResults.DataSource as ICollection; @@ -2738,11 +3193,13 @@ namespace Volian.Controls.Library if (tabSearchTypes.SelectedTab == tabSearchTypes.Tabs[4]) srchres = lbSrchResultsIncTrans.DataSource as ICollection; OnPrintRequest(new DisplaySearchEventArgs(ReportTitle, TypesSelected, SearchString, srchres,sortedBy)); } + private void panSearchButtons_Resize(object sender, EventArgs e) { cmbResultsStyle.Left = labelX1.Right + 3; cmbResultsStyle.Width = btnClearSearchResults.Left - cmbResultsStyle.Left - 3; } + // C2020-033: Convert All (that have permissions) Incoming Transitions to text private void btnTranCvtAllToTxt_Click(object sender, EventArgs e) { @@ -2753,6 +3210,7 @@ namespace Volian.Controls.Library UpdateSearchIncTransResults(); // B2021-009: Research after convert transitions to text fromTranCvtBtn = false; } + // C22020-033: Use IncTransCvtAllToTextPerm to see if user has at least edit permissions to 1 in list. This // is used to see if Convert All button is enabled. private bool IncTransCvtAllToTextPerm() @@ -2766,207 +3224,14 @@ namespace Volian.Controls.Library } return false; } - // C2020-033: Update the search panel for Incoming transitions. This gets called from the tree view & the ribbon - public void UpdateSearchIncTransResults() - { - //IncTransSelectedCount = 0; - tabSearchTypes.SelectedTab = tabSearchTypes.Tabs[4]; - - lbSrchResultsIncTrans.DataSource = null; - lbSrchResultsIncTrans.Items.Clear(); - // Get item to do search for, either from tree or from editor - if (SearchIncTransII != null) - { - // B2021-010: Use IncomingTranGetMergedTranList to get a complete list of incoming transitions (transitions to procedure - // were only included if there were NO transitions to items within procedure) - SearchResults = IncomingTranGetMergedTranList(); - ReportTitle = string.Format("Search For Incoming Transitions to {0}: ", SearchIncTransII.Path); - } - if (SearchResults != null && SearchResults.Count > 0) - { - AddMessageForEmptyAnnotations(); - cmbResultsStyle.SelectedIndex = 1; //display step locations in results - DisplayResults(); - } - else - { - btnPrnSrchRslts.Enabled = false; - btnClearSearchResults.Enabled = false; - btnCopySearchResults.Enabled = false; - btnSaveSearchResults.Enabled = false; - cmbResultsStyle.Enabled = false; - if (!fromTranCvtBtn) FlexibleMessageBox.Show("No Matches Found.", "Search"); // B2021-009: Research after convert transitions to text - } - btnTranCvtAllToTxt.Enabled = IncTransCvtAllToTextPerm(); - btnTranCvtSelToTxt.Enabled = false; - btnSearch.Enabled = false; // C2021 - 002: disable search button - no functionality for Incoming Transitions - } - public bool IncTranCvtPerm() - { - FolderInfo topFolder = FolderInfo.Get(1); - FolderConfig fc = topFolder.MyConfig as FolderConfig; - return fc.General_IncTranCvtPerm; - } - // C2020-033: Before allowing conversion of Incoming Transitions to text, get list of results that the user has permission edit. - private List TranCvtCheckPermission(bool all) - { - // check if a non-reader can convert transitions to text even if a reader - this is set by an administrator on the top - // folder properties dialog - bool allowNonAdmin = IncTranCvtPerm(); - List itmsEditable = new List(); // return this list - int listCount = 0; - if (all) // Check all in list - { - listCount = _SearchResults.Count; - foreach (ItemInfo ii in _SearchResults) - { - if (allowNonAdmin || UserInfo.CanEdit(MyUserInfo, ii.MyDocVersion)) itmsEditable.Add(ii.ContentID); - } - } - else // check only the items selected - { - listCount = lbSrchResultsIncTrans.CheckedItems.Count; - List lbis = lbSrchResultsIncTrans.CheckedItems; - foreach (ListBoxItem lbi in lbis) - { - ItemBindingData tmpii = lbi.Tag as ItemBindingData; - ItemInfo ii = tmpii.DataItem as ItemInfo; - if (allowNonAdmin || UserInfo.CanEdit(MyUserInfo, ii.MyDocVersion)) itmsEditable.Add(ii.ContentID); - } - } - // Prompt user if convert to text should continue. If some items cannot be edited, also state that - // not all can be converted to text. If count of itmsEditable & lbis are different some cannot be edited. - if (itmsEditable.Count == 0) - { - FlexibleMessageBox.Show("You do not have permission to edit any of the procedures, sections, and/or steps" + (all ? "." : " that are selected."), - "Convert Transition to Text", MessageBoxButtons.OK, MessageBoxIcon.Information); - return null; - } - else if (itmsEditable.Count != listCount) - { - DialogResult ans = FlexibleMessageBox.Show("You only have permission to edit some of the procedures, sections, and/or steps that are selected.procedures, sections, and/or steps" + (all ? "." : " that are selected.") + - "\r\n\r\n Should the conversion of the transitions to text continue?", - "Convert Transition to Text", MessageBoxButtons.YesNo, MessageBoxIcon.Question); - if (ans == DialogResult.No) return null; - } - else - { - DialogResult ans = FlexibleMessageBox.Show("Are you sure you want to convert the transitions to text?", - "Convert Transition to Text", MessageBoxButtons.YesNo, MessageBoxIcon.Question); - if (ans == DialogResult.No) return null; - } - return itmsEditable; - } - private bool fromTranCvtBtn = false; - // C2020-033: convert selected transitions to text - private void btnTranCvtSelToTxt_Click(object sender, EventArgs e) - { - // First see if all selected can be converted, i.e. user has permission to edit - List lbis = lbSrchResultsIncTrans.CheckedItems; - List itmsEditable = TranCvtCheckPermission(false); - if (itmsEditable == null || itmsEditable.Count == 0) return; - TranCvtToTxt(itmsEditable); - fromTranCvtBtn = true; - UpdateSearchIncTransResults(); // B2021-009: Research after convert transitions to text - fromTranCvtBtn = false; - } - // B2021-010: IncomingTranGetMergedTranList gets a complete list of incoming transitions (before fix transitions to procedure - // were only included if there were NO transitions to items within procedure, the GetExternalTransitionsToChildren query - // did not get transitions 'incoming to' the item itself) - private ItemInfoList IncomingTranGetMergedTranList() - { - ItemInfoList iil = null; - bool first = true; - using (TransitionInfoList exTrans = TransitionInfoList.GetExternalTransitionsToChildren(SearchIncTransII.ItemID)) - { - foreach (TransitionInfo ti in exTrans) - { - if (first) - { - ContentInfo ci = ContentInfo.Get(ti.FromID); - ItemInfo tmp = ci.ContentItems[0]; - iil = new ItemInfoList(tmp); - first = false; - } - else - { - ContentInfo ci = ContentInfo.Get(ti.FromID); - ItemInfo tmp = ci.ContentItems[0]; - iil.AddItem(tmp); - } - } - } - using (TransitionInfoList exTrans = TransitionInfoList.GetExternalTransitions(SearchIncTransII.ItemID)) - { - foreach (TransitionInfo ti in exTrans) - { - if (first) - { - ContentInfo ci = ContentInfo.Get(ti.FromID); - ItemInfo tmp = ci.ContentItems[0]; - iil = new ItemInfoList(tmp); - first = false; - } - else - { - ContentInfo ci = ContentInfo.Get(ti.FromID); - ItemInfo tmp = ci.ContentItems[0]; - // B2021-014: if in list, don't add another - if (!iil.Contains(tmp))iil.AddItem(tmp); - } - } - } - return iil; - } - // C2020-033: For items in list, do the actual conversion of the Incoming Transition to text - private void TranCvtToTxt(List itmsEditable) - { - ItemInfo trII = SearchIncTransII; - if (trII != null) - { - using (TransitionInfoList exTrans = TransitionInfoList.GetExternalTransitionsToChildren(trII.ItemID)) - { - foreach (TransitionInfo ti in exTrans) - { - // See if the 'item to' id is to be converted and if so do it. To figure this out, - // see if it is in the list itmsEditable. - if (itmsEditable.Contains(ti.FromID)) - { - ContentInfo ci = ContentInfo.Get(ti.FromID); - ItemInfo tmp = ci.ContentItems[0]; - using (Content content = Content.Get(tmp.ContentID)) - { - content.FixTransitionText(ti, true); - content.Save(); - } - } - } - } - // B2021-010: Convert the text of transitions pointing (incoming) to the item itself - using (TransitionInfoList exTrans = TransitionInfoList.GetExternalTransitions(trII.ItemID)) - { - foreach (TransitionInfo ti in exTrans) - { - // See if the 'item to' id is to be converted and if so do it. To figure this out, - // see if it is in the list itmsEditable. - if (itmsEditable.Contains(ti.FromID)) - { - ContentInfo ci = ContentInfo.Get(ti.FromID); - ItemInfo tmp = ci.ContentItems[0]; - using (Content content = Content.Get(tmp.ContentID)) - { - content.FixTransitionText(ti, true); - content.Save(); - } - } - } + #endregion - } - } - } + #endregion } - #region Annoation Search Type Class + + #region AnnotationTypeSearch Class + // this class is used to generate the list of annotations to search. // this also allow us to add a dummy type which is used to search for all annotations public class AnnotationTypeSearch @@ -2990,7 +3255,11 @@ namespace Volian.Controls.Library } } - #endregion + + #endregion + + #region DisplaySearchEventArgs Class + public class DisplaySearchEventArgs { private string _ReportTitle; @@ -2999,47 +3268,54 @@ namespace Volian.Controls.Library get { return _ReportTitle; } set { _ReportTitle = value; } } + private string _SearchString = null; public string SearchString { get { return _SearchString; } set { _SearchString = value; } } + private string _TypesSelected; public string TypesSelected { get { return _TypesSelected; } set { _TypesSelected = value; } } + private string _SortedBy = null; public string SortedBy // C2019-013 pass in sorted by information to print report { get { return _SortedBy; } set { _SortedBy = value; } } + private ICollection _MyItemInfoList; public ICollection MyItemInfoList { get { return _MyItemInfoList; } set { _MyItemInfoList = value; } } + private TimeSpan _HowLong = TimeSpan.FromTicks(0); public TimeSpan HowLong { get { return _HowLong; } set { _HowLong = value; } } - private string _PaperSize; + private string _PaperSize; public string PaperSize // C2020-002 paper size is now set in the format files { get { return _PaperSize; } set { _PaperSize = value; } } + public DisplaySearchEventArgs(TimeSpan howLong) { HowLong = howLong; } + public DisplaySearchEventArgs(string reportTitle, string typesSelected, string searchString, ICollection myItemInfoList, string sortedBy) { _ReportTitle = reportTitle; @@ -3047,6 +3323,7 @@ namespace Volian.Controls.Library _MyItemInfoList = myItemInfoList; _SearchString = searchString; _SortedBy = sortedBy; // C2019-013 pass in sorted by information + foreach (ItemInfo tmpII in myItemInfoList) if (tmpII != null && tmpII.ActiveFormat != null) { @@ -3055,5 +3332,8 @@ namespace Volian.Controls.Library } } } - public delegate void DisplaySearchEvent(object sender, DisplaySearchEventArgs args); + + #endregion + + public delegate void DisplaySearchEvent(object sender, DisplaySearchEventArgs args); } diff --git a/PROMS/Volian.Controls.Library/DisplayTabControl.cs b/PROMS/Volian.Controls.Library/DisplayTabControl.cs index f0ea33ef..8855adc1 100644 --- a/PROMS/Volian.Controls.Library/DisplayTabControl.cs +++ b/PROMS/Volian.Controls.Library/DisplayTabControl.cs @@ -537,7 +537,8 @@ namespace Volian.Controls.Library } else { - ActivateRemainingTab((Bar)sender); + if (!ShuttingDown) // B2022-026 RO Memory Reduction code - don't activate if shutting down PROMS + ActivateRemainingTab((Bar)sender); } } #endregion diff --git a/PROMS/Volian.Controls.Library/StepTabRibbon.cs b/PROMS/Volian.Controls.Library/StepTabRibbon.cs index d6e5a2b2..516f72e5 100644 --- a/PROMS/Volian.Controls.Library/StepTabRibbon.cs +++ b/PROMS/Volian.Controls.Library/StepTabRibbon.cs @@ -3347,10 +3347,17 @@ namespace Volian.Controls.Library using (DocVersion dv = DocVersion.Get(Mydvi.VersionID)) { + swROUpdate = new System.IO.StreamWriter(ROFstInfo.ROUpdateResultsPath(Mydvi)); + // B2022-026 RO Memory Reduction code - first load the new ro.fst so that we can assign the ROTableUpdate event to the correct roFstInfo + if (dv.ROfstLoadingFigures || dv.NewerRoFst) // B2017-125 see if loading figures was completed + { + // only load the RO.fst + ROFstInfo.UpdateRoFst(roFstInfo.MyRODb, dv, roFstInfo, DoProgressBarRefresh); + roFstInfo = Mydvi.DocVersionAssociations[0].MyROFst; + } roFstInfo.ROTableUpdate += new ROFstInfoROTableUpdateEvent(roFstInfo_ROTableUpdate); - swROUpdate = new System.IO.StreamWriter(ROFstInfo.ROUpdateResultsPath(Mydvi));// RO changes placed in file in the Documents\VEPROMS folder ContentInfo.StaticContentInfoChange += ContentInfo_StaticContentInfoChange; // write changes to a text file - ROFst newrofst = ROFstInfo.RefreshROFst(roFstInfo.MyRODb, dv.DocVersionAssociations[0], dv, roFstInfo, DoProgressBarRefresh, null); + ROFst newrofst = ROFstInfo.RefreshROFst(dv, roFstInfo, DoProgressBarRefresh, null); swROUpdate.Close(); ContentInfo.StaticContentInfoChange -= ContentInfo_StaticContentInfoChange; roFstInfo.ROTableUpdate -= new ROFstInfoROTableUpdateEvent(roFstInfo_ROTableUpdate); @@ -3720,12 +3727,12 @@ namespace Volian.Controls.Library } private void btnRefObjRefresh_Click(object sender, System.EventArgs e) { - // This code is disabled - Button is not visible - this.Cursor = Cursors.WaitCursor; - ProcedureInfo.ResetROCounters(); - ProcedureInfo.RefreshReferenceObjects(MyItemInfo.MyProcedure as ProcedureInfo); - this.Cursor = Cursors.Default; - FlexibleMessageBox.Show(this, string.Format("Checked {0} referenced objects, fixed {1} referenced objects", ProcedureInfo.ROCheckCount, ProcedureInfo.ROFixCount), "Results of Refresh Referenced Objects", MessageBoxButtons.OK, MessageBoxIcon.Information); + //// This code is disabled - Button is not visible + //this.Cursor = Cursors.WaitCursor; + // ProcedureInfo.ResetROCounters(); + // ProcedureInfo.RefreshReferenceObjects(MyItemInfo.MyProcedure as ProcedureInfo); + // this.Cursor = Cursors.Default; + //FlexibleMessageBox.Show(this, string.Format("Checked {0} referenced objects, fixed {1} referenced objects", ProcedureInfo.ROCheckCount, ProcedureInfo.ROFixCount), "Results of Refresh Referenced Objects", MessageBoxButtons.OK, MessageBoxIcon.Information); } //private FindReplace dlgFindReplace = null; private void btnFindRplDlg_Click(object sender, EventArgs e) diff --git a/PROMS/Volian.Controls.Library/vlnTreeView.cs b/PROMS/Volian.Controls.Library/vlnTreeView.cs index f9ceb014..66b6739b 100644 --- a/PROMS/Volian.Controls.Library/vlnTreeView.cs +++ b/PROMS/Volian.Controls.Library/vlnTreeView.cs @@ -1955,10 +1955,17 @@ namespace Volian.Controls.Library int ownerid = MySessionInfo.CheckOutItem(MyDVI.VersionID, CheckOutType.DocVersion); using (DocVersion dv = DocVersion.Get(MyDVI.VersionID)) { - roFstInfo.ROTableUpdate += new ROFstInfoROTableUpdateEvent(roFstInfo_ROTableUpdate); swROUpdate = new System.IO.StreamWriter(ROFstInfo.ROUpdateResultsPath(MyDVI)); // RO changes placed in file in the Documents\VEPROMS folder + // B2022-026 RO Memory Reduction code - first load the new ro.fst so that we can assign the ROTableUpdate event to the correct roFstInfo + if (dv.ROfstLoadingFigures || dv.NewerRoFst) // B2017-125 see if loading figures was completed + { + // only load the RO.fst + ROFstInfo.UpdateRoFst(roFstInfo.MyRODb, dv, roFstInfo, DoProgressBarRefresh); + roFstInfo = MyDVI.DocVersionAssociations[0].MyROFst; + } + roFstInfo.ROTableUpdate += new ROFstInfoROTableUpdateEvent(roFstInfo_ROTableUpdate); ContentInfo.StaticContentInfoChange += ContentInfo_StaticContentInfoChange; // write changes to a text file - ROFst newrofst = ROFstInfo.RefreshROFst(roFstInfo.MyRODb, dv.DocVersionAssociations[0], dv, roFstInfo, DoProgressBarRefresh, null); + ROFst newrofst = ROFstInfo.RefreshROFst(dv, roFstInfo, DoProgressBarRefresh, null); swROUpdate.Close(); ContentInfo.StaticContentInfoChange -= ContentInfo_StaticContentInfoChange; roFstInfo.ROTableUpdate -= new ROFstInfoROTableUpdateEvent(roFstInfo_ROTableUpdate); diff --git a/PROMS/Volian.Print.Library/PDFReport.cs b/PROMS/Volian.Print.Library/PDFReport.cs index 08db4313..d1c29a04 100644 --- a/PROMS/Volian.Print.Library/PDFReport.cs +++ b/PROMS/Volian.Print.Library/PDFReport.cs @@ -6,12 +6,15 @@ using iTextSharp.text.pdf; using iTextSharp.text; using System.IO; using System.Text.RegularExpressions; +using System.Collections; namespace Volian.Print.Library { - + // B2022-026 New code for RO Memory reduction - now use SQL tables instead of building dictionarys to get RO values public class PDFReport { + #region Enums + public enum ReportType { SearchResults = 0, @@ -21,60 +24,26 @@ namespace Volian.Print.Library ReferencedObjectSummary = 4, ReferencedObjectComplete = 5 } + + #endregion + + #region Fields + private PdfWriter _MyPdfWriter; private ICollection _ResultList; - public ICollection ResultList - { - get { return _ResultList; } - set { _ResultList = value; } - } - private string _FileName; - public string FileName - { - get { return _FileName; } - set { _FileName = value; } - } - private string _ReportTitle; - public string ReportTitle - { - get { return _ReportTitle; } - set { _ReportTitle = value; } - } - private string _TypesSelected; - public string TypesSelected - { - get { return _TypesSelected; } - set { _TypesSelected = value; } - } + private string _FileName; + private string _ReportTitle; + private string _TypesSelected; private bool _ShowAnnotations = true; - public bool ShowAnnotations - { - get { return _ShowAnnotations; } - set { _ShowAnnotations = value; } - } private string _SearchString; - public string SearchString - { - get { return _SearchString; } - set { _SearchString = VEPROMS.CSLA.Library.ItemInfo.ConvertToDisplayText(value); } - } private string _SortedBy; // C2019-013 pass in sorting information - public string SortedBy - { - get { return _SortedBy; } - set { _SortedBy = value; } - } private DocumentInfoList _LibDocList; - public DocumentInfoList LibDocList - { - get { return _LibDocList; } - set { _LibDocList = value; } - } + private int _ReportType = 0; private string _ByLine; private bool _SortUsageByProcedure = false; - private string _RODataFile = ""; + private string _RODataFile = string.Empty; private List _ROList; private ROFSTLookup _ROFSTLookup; private bool _IncludeMissingROs = false; @@ -82,7 +51,107 @@ namespace Volian.Print.Library private bool _IncludeEmptyROFields = false; private string _PaperSize = "Letter"; // C2020-002 paper size is now set in the format files - // Search Results Report + private string _RegexSearchString = null; + private ArrayList ProcSetList; + + #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; } + set { _ShowAnnotations = value; } + } + + public string SearchString + { + get { return _SearchString; } + set { _SearchString = VEPROMS.CSLA.Library.ItemInfo.ConvertToDisplayText(value); } + } + + public string SortedBy + { + get { return _SortedBy; } + set { _SortedBy = value; } + } + + public DocumentInfoList LibDocList + { + get { return _LibDocList; } + set { _LibDocList = value; } + } + + private string RegexSearchString + { + get + { + if (_RegexSearchString == null) + { + _RegexSearchString = _SearchString; + + // Make it match the smallest matching string + _RegexSearchString = _RegexSearchString.Replace("*", ".*?"); + + // If search string starts with a wildcard use the beginning of line token (^) + if (_RegexSearchString.StartsWith(".*?")) + { + _RegexSearchString = "^" + _RegexSearchString; + } + + // If search string ends with a wildcard use the end of line token ($) + if (_RegexSearchString.EndsWith(".*?")) + { + _RegexSearchString = _RegexSearchString + "$"; + } + + _RegexSearchString = _RegexSearchString.Replace("[", @"\["); + _RegexSearchString = _RegexSearchString.Replace("]", @"\]"); + _RegexSearchString = _RegexSearchString.Replace("(", @"\("); + _RegexSearchString = _RegexSearchString.Replace(")", @"\)"); + } + + return _RegexSearchString; + } + } + + #endregion + + #region Constructors + + /// + /// Search Results Report + /// + /// + /// + /// + /// + /// + /// public PDFReport(string reportTitle, string typesSelected, ICollection resultList, string fileName, string paperSize, string sortedBy) { _ResultList = resultList; @@ -96,7 +165,13 @@ namespace Volian.Print.Library } - // Library Document Report + /// + /// Library Document Report + /// + /// + /// + /// + /// public PDFReport(string reportTitle, DocumentInfoList libDocList, string fileName, string paperSize) { _LibDocList = libDocList; @@ -107,7 +182,15 @@ namespace Volian.Print.Library _PaperSize = paperSize; } - // RO Usage + /// + /// RO Usage + /// + /// + /// + /// + /// + /// + /// public PDFReport(string reportTitle, ICollection resultList, string fileName, bool sortUsageByProcedure, bool includeMissingROs, string paperSize) { _ResultList = resultList; @@ -120,7 +203,17 @@ namespace Volian.Print.Library _PaperSize = paperSize; } - // RO Complete RO Report + /// + /// RO Complete RO Report + /// + /// + /// + /// + /// + /// + /// + /// + /// public PDFReport(string reportTitle, string roDataFile, string outfile, ROFSTLookup fstlookup, bool completeReport, bool convertCaretToDelta, bool includeEmptyROFields, string paperSize) { _FileName = outfile; @@ -134,7 +227,14 @@ namespace Volian.Print.Library _PaperSize = paperSize; } - // RO Summary Report + /// + /// RO Summary Report + /// + /// + /// + /// + /// + /// public PDFReport(string reportTitle, string outfile, ROFSTLookup fstlookup, List roList, string paperSize) { _FileName = outfile; @@ -146,181 +246,19 @@ namespace Volian.Print.Library _PaperSize = paperSize; } - private string AddGroup(PdfPTable datatable, string dvPath, string lastDvPath, Font f2, bool StripLast, Color bgColor, bool skipFirst) - { - int level = 0; - string retval = ""; - StringBuilder sb = new StringBuilder(); - string ttt = dvPath.Replace("\x11", " "); - string[] OldPath = lastDvPath.Split("\x7".ToCharArray()); - string[] NewPath = dvPath.Split("\x7".ToCharArray()); - string sep = ""; - bool foundMisMatch = false; - // n-1 Exclude the "Working Draft" entry from the list - int n = NewPath.Length-1; - int jstart = (skipFirst) ? 1 : 0; - if (StripLast) - { - retval = NewPath[--n]; - if (retval.Contains("\x11")) - retval = retval.Substring(0, retval.IndexOf("\x11")); // this is the step number - } - if (n == 0) - { - // B2020-006: 'clean-up' the output string by making string replaces as in 'else' below. - sb.Append(dvPath.Replace("\x11", " ").Replace(@"\u8209?", "-").Replace(@"\u160?", " ").Replace(@"\u9586?", @"\")); - } - else - { - for (int j = jstart; j < n; j++) - { - if (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?",@"\"); - sep = "\r\n"; - foundMisMatch = true; - } - level++; - } - } - if (sb.ToString() != "") - { - PdfPCell cell = new PdfPCell(new Phrase(sb.ToString(), f2)); - cell.Colspan = 2; - cell.BackgroundColor = bgColor; - cell.BorderWidthTop = 1; - datatable.AddCell(cell); - } - return retval; - } + #endregion + #region Public Methods + + public void AddMainRODatabaseTitle(PdfPTable datatable, int dbTitleIndex, Font f2, Color bgColor) + { + string dbTitle = _ROFSTLookup.GetRODatabaseTitle(dbTitleIndex); - - private string AddGroupLibDoc(PdfPTable datatable, string dvPath, string lastDvPath, Font f2, bool StripLast, Color bgColor, bool skipFirst) - { - int level = 0; - string retval = ""; - StringBuilder sb = new StringBuilder(); - string ttt = dvPath.Replace("\x11", " "); - string[] OldPath = lastDvPath.Split("\x7".ToCharArray()); - string[] NewPath = dvPath.Split("\x7".ToCharArray()); - string sep = ""; - bool foundMisMatch = false; - int n = NewPath.Length - 1; - int jstart = (skipFirst) ? 1 : 0; - if (StripLast) - { - retval = NewPath[--n]; - if (retval.Contains("\x11")) - retval = retval.Substring(0, retval.IndexOf("\x11")); // this is the step number - } - //If no colons output tthe entire text - if (n == 0) - { - sb.Append(dvPath); - } - else - { - for (int j = jstart; j < n; j++) - { - if (NewPath[j] != "" && (foundMisMatch || OldPath.Length < j + 1 || NewPath[j] != OldPath[j])) - { - sb.Append(sep + "".PadLeft(2 * level) + NewPath[j].Replace("\x11", " ")).Replace(@"\u8209?", "-").Replace(@"\u9586?", @"\"); - sep = "\r\n"; - foundMisMatch = true; - } - level++; - } - } - if (sb.ToString() != "") - { - PdfPCell cell = new PdfPCell(new Phrase(sb.ToString(), f2)); - cell.Colspan = 2; - cell.BackgroundColor = bgColor; - cell.BorderWidthTop = 1; - datatable.AddCell(cell); - } - return retval; - } - - private void AddProcedureSectionGroup(PdfPTable datatable, string curProc, string lastProc, string curSect, string lastSect, Font f2, Color bgColor) - { - string headerText = ""; - if (curProc != lastProc) - headerText = curProc + "\r\n"; - if (curSect != lastSect) - headerText += " " + curSect; - if (headerText.Length > 0) - { - headerText = headerText.Replace(@"\u8209?", "-");// repace unicode with dash char - headerText = headerText.Replace(@"\u160?", " "); // replace Hard Space with normal Space - headerText = headerText.Replace(@"\u9586?", @"\"); // replace backslash symbol with a backslash - PdfPCell cell = new PdfPCell(new Phrase(headerText, f2)); - cell.Colspan = 2; - cell.BackgroundColor = bgColor; - cell.BorderWidthTop = 1; - datatable.AddCell(cell); - } - } - - private string GetCurProcNum(string path) - { - string[] NewPath = path.Split("\x7".ToCharArray()); - string pnumtitle = NewPath[1]; - pnumtitle = pnumtitle.Replace('\x11', ' '); - return pnumtitle; - } - private string GetCurSectionNumTitle(ItemInfo itm) - { - string rtnstr = ""; - if (itm.ActiveSection != null) - { - rtnstr = itm.ActiveSection.DisplayNumber; - if (rtnstr.Length > 0) rtnstr += " "; - rtnstr += itm.ActiveSection.DisplayText; - } - return rtnstr; // srting containing section and subsection number/titles - } - //private string GetStepNumberFromSearchPath(string path) - //{ - // string[] NewPath = path.Split("\x7".ToCharArray()); - // int idx = NewPath.Length - 1; - // string retval = NewPath[idx]; - // if (retval.Contains("\x11")) - // retval = retval.Substring(0, retval.IndexOf("\x11")); // this is the step number - // return retval; - //} - private int FindSpitLevel() - { - int level = 0; - bool foundMisMatch = false; - string lastPath = ""; - foreach (string p in ProcSetList) - { - string[] NewPath = p.Split("\x7".ToCharArray()); - if (lastPath != "") - { - string[] OldPath = lastPath.Split("\x7".ToCharArray()); - int n = NewPath.Length; - int lvl = 0; - foundMisMatch = false; - for (int j = 0; j < n && !foundMisMatch; j++) - { - if (NewPath[j] != "" && (OldPath.Length < j + 1 || NewPath[j] != OldPath[j])) - foundMisMatch = true; - lvl++; - } - if (level == 0) level = lvl; - if (foundMisMatch) - level = Math.Min(level, lvl); - } - lastPath = p; - if (ProcSetList.Count == 1) - level = NewPath.Length - 1; - } - //if (level > 0) level--; - return level; + PdfPCell cell = new PdfPCell(new Phrase(dbTitle, f2)); + cell.BorderColor = Color.WHITE; + cell.Colspan = 2; + cell.BackgroundColor = bgColor; + datatable.AddCell(cell); } public void AddMainPathGroup(PdfPTable datatable, string dvPath, int splitLevel, Font f2, Color bgColor, int colSpan) @@ -328,31 +266,37 @@ namespace Volian.Print.Library int level = 0; StringBuilder sb = new StringBuilder(); string[] NewPath = dvPath.Split("\x7".ToCharArray()); - string sep = ""; + string sep = string.Empty; int n = NewPath.Length; + for (int j = 1; j < n && j < splitLevel; j++) { sb.Append(sep + "".PadLeft(2 * level) + NewPath[j].Replace("\x11", " ")).Replace(@"\u8209?", "-").Replace(@"\u9586?", @"\"); sep = "\r\n"; level++; } - if (sb.ToString() != "") + + if (sb.Length > 0) { PdfPCell cell = new PdfPCell(new Phrase(sb.ToString(), f2)); + cell.Colspan = colSpan; cell.BackgroundColor = bgColor; cell.BorderWidthTop = 1; + datatable.AddCell(cell); } } + public void AddSubPathGroup(PdfPTable datatable, string oldDVPath, string dvPath, int splitLevel, Font f2, Color bgColor, int colSpan) { int level = 0; StringBuilder sb = new StringBuilder(); string[] NewPath = dvPath.Split("\x7".ToCharArray()); string[] OldPath = oldDVPath.Split("\x7".ToCharArray()); - string sep = ""; - int n = NewPath.Length-1; + string sep = string.Empty; + int n = NewPath.Length - 1; + for (int i = 0; i < n; i++) { if (OldPath[i] != NewPath[i]) @@ -361,6 +305,7 @@ namespace Volian.Print.Library break; } } + if (splitLevel < n) { for (int j = splitLevel; j < n; j++) @@ -369,21 +314,27 @@ namespace Volian.Print.Library sep = "\r\n"; level++; } - if (sb.ToString() != "") + + if (sb.Length > 0) { PdfPCell cell = new PdfPCell(new Phrase(sb.ToString(), f2)); + cell.Colspan = colSpan; cell.BackgroundColor = bgColor; cell.BorderWidthTop = 1; + datatable.AddCell(cell); } } } + public void Build() { - //iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.LETTER, 36, 36, 36, 36); iTextSharp.text.Document document = new iTextSharp.text.Document(PDFPageSize.UsePaperSize(_PaperSize), 36, 36, 36, 36); // C2020-002 paper size is now set in the format files - if (!CreateResultsPDF(document, _ReportType)) return; + + if (!CreateResultsPDF(document, _ReportType)) + return; + try { switch (_ReportType) // set in the PDFReport constructor @@ -391,18 +342,22 @@ namespace Volian.Print.Library case (int)ReportType.SearchResults: BuildSearchResultsTable(document); break; + case (int)ReportType.LibraryDocUsage: BuildLibDocUsageReport(document); break; + case (int)ReportType.ReferencedObjectsUsage: if (_SortUsageByProcedure) BuildROUsageTableByProcedure(document); else BuildROUsageTableByRO(document); break; + case (int)ReportType.ReferencedObjectComplete: BuildCompleteROReport(document); break; + case (int)ReportType.ReferencedObjectSummary: BuildROSummaryReport(document); break; @@ -412,6 +367,7 @@ namespace Volian.Print.Library { StringBuilder msg = new StringBuilder(); document.Add(new Paragraph("Error:")); + while (ex != null) { document.Add(new Paragraph(ex.GetType().Name)); @@ -430,6 +386,216 @@ namespace Volian.Print.Library } } } + + #endregion + + #region Private Methods + + private string AddGroup(PdfPTable datatable, string dvPath, string lastDvPath, Font f2, bool StripLast, Color bgColor, bool skipFirst) + { + int level = 0; + string retval = string.Empty; + StringBuilder sb = new StringBuilder(); + string ttt = dvPath.Replace("\x11", " "); + string[] OldPath = lastDvPath.Split("\x7".ToCharArray()); + string[] NewPath = dvPath.Split("\x7".ToCharArray()); + string sep = string.Empty; + bool foundMisMatch = false; + + // n-1 Exclude the "Working Draft" entry from the list + int n = NewPath.Length-1; + int jstart = (skipFirst) ? 1 : 0; + + if (StripLast) + { + retval = NewPath[--n]; + if (retval.Contains("\x11")) + { + retval = retval.Substring(0, retval.IndexOf("\x11")); // this is the step number + } + } + + if (n == 0) + { + // B2020-006: 'clean-up' the output string by making string replaces as in 'else' below. + sb.Append(dvPath.Replace("\x11", " ").Replace(@"\u8209?", "-").Replace(@"\u160?", " ").Replace(@"\u9586?", @"\")); + } + else + { + for (int j = jstart; j < n; j++) + { + 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?",@"\"); + sep = "\r\n"; + foundMisMatch = true; + } + + level++; + } + } + + if (sb.Length > 0) + { + PdfPCell cell = new PdfPCell(new Phrase(sb.ToString(), f2)); + + cell.Colspan = 2; + cell.BackgroundColor = bgColor; + cell.BorderWidthTop = 1; + datatable.AddCell(cell); + } + + return retval; + } + + private string AddGroupLibDoc(PdfPTable datatable, string dvPath, string lastDvPath, Font f2, bool StripLast, Color bgColor, bool skipFirst) + { + int level = 0; + string retval = string.Empty; + StringBuilder sb = new StringBuilder(); + string ttt = dvPath.Replace("\x11", " "); + string[] OldPath = lastDvPath.Split("\x7".ToCharArray()); + string[] NewPath = dvPath.Split("\x7".ToCharArray()); + string sep = string.Empty; + bool foundMisMatch = false; + int n = NewPath.Length - 1; + int jstart = (skipFirst) ? 1 : 0; + + if (StripLast) + { + retval = NewPath[--n]; + if (retval.Contains("\x11")) + { + retval = retval.Substring(0, retval.IndexOf("\x11")); // this is the step number + } + } + + //If no colons output the entire text + if (n == 0) + { + sb.Append(dvPath); + } + else + { + for (int j = jstart; j < n; j++) + { + if (!string.IsNullOrEmpty(NewPath[j]) && (foundMisMatch || OldPath.Length < j + 1 || NewPath[j] != OldPath[j])) + { + sb.Append(sep + "".PadLeft(2 * level) + NewPath[j].Replace("\x11", " ")).Replace(@"\u8209?", "-").Replace(@"\u9586?", @"\"); + sep = "\r\n"; + foundMisMatch = true; + } + + level++; + } + } + + if (sb.Length > 0) + { + PdfPCell cell = new PdfPCell(new Phrase(sb.ToString(), f2)); + + cell.Colspan = 2; + cell.BackgroundColor = bgColor; + cell.BorderWidthTop = 1; + datatable.AddCell(cell); + } + + return retval; + } + + private void AddProcedureSectionGroup(PdfPTable datatable, string curProc, string lastProc, string curSect, string lastSect, Font f2, Color bgColor) + { + string headerText = string.Empty; + + if (curProc != lastProc) + headerText = curProc + "\r\n"; + + if (curSect != lastSect) + headerText += " " + curSect; + + if (headerText.Length > 0) + { + headerText = headerText.Replace(@"\u8209?", "-");// repace unicode with dash char + headerText = headerText.Replace(@"\u160?", " "); // replace Hard Space with normal Space + headerText = headerText.Replace(@"\u9586?", @"\"); // replace backslash symbol with a backslash + + PdfPCell cell = new PdfPCell(new Phrase(headerText, f2)); + cell.Colspan = 2; + cell.BackgroundColor = bgColor; + cell.BorderWidthTop = 1; + datatable.AddCell(cell); + } + } + + private string GetCurProcNum(string path) + { + string[] NewPath = path.Split("\x7".ToCharArray()); + string pnumtitle = NewPath[1]; + pnumtitle = pnumtitle.Replace('\x11', ' '); + + return pnumtitle; + } + + private string GetCurSectionNumTitle(ItemInfo itm) + { + string rtnstr = string.Empty; + + if (itm.ActiveSection != null) + { + rtnstr = itm.ActiveSection.DisplayNumber; + if (rtnstr.Length > 0) rtnstr += " "; + rtnstr += itm.ActiveSection.DisplayText; + } + + return rtnstr; // string containing section and subsection number/titles + } + + private int FindSpitLevel() + { + int level = 0; + bool foundMisMatch = false; + string lastPath = string.Empty; + + foreach (string p in ProcSetList) + { + string[] NewPath = p.Split("\x7".ToCharArray()); + + if (lastPath != string.Empty) + { + string[] OldPath = lastPath.Split("\x7".ToCharArray()); + int n = NewPath.Length; + int lvl = 0; + foundMisMatch = false; + + for (int j = 0; j < n && !foundMisMatch; j++) + { + if (NewPath[j] != string.Empty && (OldPath.Length < j + 1 || NewPath[j] != OldPath[j])) + { + foundMisMatch = true; + } + + lvl++; + } + + if (level == 0) + level = lvl; + + if (foundMisMatch) + level = Math.Min(level, lvl); + } + + lastPath = p; + + if (ProcSetList.Count == 1) + { + level = NewPath.Length - 1; + } + } + + return level; + } + /// /// Attempt to open a file for the PDF output. /// If the file cannot be opened because it is in use, try adding a suffix @@ -440,33 +606,41 @@ namespace Volian.Print.Library private bool CreateResultsPDF(iTextSharp.text.Document document,int typ) { int topMargin = 36; + switch (typ) { case (int)ReportType.LibraryDocUsage: topMargin = 80; // Add some space for the Report Header for the Library Document Report break; } + bool result = false; - string suffix = ""; + string suffix = string.Empty; int i = 0; + // Try to open a file for creating the PDF. while (result == false) { string fileName = _FileName.ToLower().Replace(".pdf", suffix + ".pdf"); + try { _MyPdfWriter = PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create)); _MyPdfWriter.PageEvent = new MyPageHelper(_ByLine); // JSJ - 7/8/2011 + document.SetMargins(36, 36, topMargin, 36); document.Open(); + _FileName = fileName; + result = true; } catch (System.IO.IOException exIO) { - if (exIO.Message.Contains("because it is being used by another process")) + { suffix = string.Format("_{0}", ++i);// If this file is in use, increment the suffix and try again + } else // If some other error, display a message and don't print the results { ShowException(exIO); @@ -479,23 +653,10 @@ namespace Volian.Print.Library return false; // Could not open the output file } } + return true; } - private static void ShowException(Exception ex) - { - Console.WriteLine("{0} - {1}", ex.GetType().Name, ex.Message); - StringBuilder msg = new StringBuilder(); - string sep = ""; - string indent = ""; - while (ex != null) - { - msg.Append(string.Format("{0}{1}{2}:\r\n{1}{3}", sep, indent, ex.GetType().Name, ex.Message)); - ex = ex.InnerException; - sep = "\r\n"; - indent += " "; - } - System.Windows.Forms.MessageBox.Show(msg.ToString(), "Error during PDF creation for search:", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation); - } + /// /// Use Cells within Cells to see if I can limit the way Cells break from Page to Page /// @@ -508,6 +669,7 @@ namespace Volian.Print.Library //datatable.FooterRows = 1; 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); @@ -517,8 +679,9 @@ namespace Volian.Print.Library 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):""), 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); @@ -532,63 +695,68 @@ namespace Volian.Print.Library datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER; AddCell(colHeader, "Step", f2, subHeaderColor); AddCell(colHeader, "Text", f2, subHeaderColor); - //datatable.AddCell(colHeader); - // This puts "Step" and "Text" column headers at the bottom of the page - //AddCell(datatable, "Step", f2, subHeaderColor); - //AddCell(datatable, "Text", f2, subHeaderColor); + datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT; - string lastPath = ""; + string lastPath = string.Empty; Color AnnoColor = new Color(0xFF, 0xFF, 0xC0); // yellow Color TextColor = Color.WHITE; Color WordSectColor = new Color(0xE8, 0xE8, 0xE8);// light grey Color StepSectColor = new Color(0xE7, 0xFF, 0xE7); // lighter green PdfPTable subTable = new PdfPTable(headerwidths); - string lastProcNum = ""; - string lastDVPath = ""; - string lastSectNumAndTitle = ""; + string lastProcNum = string.Empty; + string lastDVPath = string.Empty; + string lastSectNumAndTitle = string.Empty; List processedItems = new List(); + foreach (ItemInfo item in _ResultList) { if (!processedItems.Contains(item.ItemID)) { processedItems.Add(item.ItemID); + if (lastDVPath != item.SearchDVPath) { datatable.AddCell(subTable); subTable = new PdfPTable(headerwidths); AddMainPathGroup(datatable, item.SearchDVPath, splitAt, f2, new Color(0xB0, 0xF0, 0xF0), 0);// little brighter cyan datatable.AddCell(colHeader); - lastProcNum = ""; - lastSectNumAndTitle = ""; // C2020-019 reset we are processing a different procedure set + lastProcNum = string.Empty; + lastSectNumAndTitle = string.Empty; // C2020-019 reset we are processing a different procedure set } + lastDVPath = item.SearchDVPath; string curProcNum = GetCurProcNum(item.SearchPath); + if (subTable.Rows.Count > 0) // prevent first page from being blank { datatable.AddCell(subTable); subTable = new PdfPTable(headerwidths); } + if (curProcNum != lastProcNum) - lastSectNumAndTitle = ""; // C2020-019 reset we are processing a different procedure + { + 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 != "" && curSectNumTitle != lastSectNumAndTitle && !item.IsSection) + + if (curSectNumTitle != string.Empty && curSectNumTitle != lastSectNumAndTitle && !item.IsSection) { AddColSpanCell(subTable, curSectNumTitle, f2, StepSectColor, 2, 0); lastSectNumAndTitle = curSectNumTitle; } + lastPath = item.SearchPath ?? item.ShortPath; stepPath = BuildStepTab(item); AddCell(subTable, stepPath, f2, (item.IsSection ? WordSectColor : TextColor)); - // This was for the old 16-bit style of table - jsj 7/7/2011 - //if (item.DisplayText.Contains("|")) // Need a better way to determine if it is a table. - // AddCell(datatable, item.DisplayText, f3, TextColor); - //else - //AddCell(datatable, item.DisplayText, f2, (item.IsSection ? SectColor : TextColor)); AddCell(subTable, item.DisplayText, f2, (item.IsSection ? WordSectColor : TextColor)); + if (ShowAnnotations && item.ItemAnnotationCount > 0) { foreach (AnnotationInfo ai in item.ItemAnnotations) @@ -599,6 +767,7 @@ namespace Volian.Print.Library } } } + datatable.AddCell(subTable); document.Add(datatable); } @@ -606,88 +775,84 @@ namespace Volian.Print.Library private void AddCell(PdfPTable datatable, string str, iTextSharp.text.Font fnt, Color bgColor) { iTextSharp.text.Font fntBold = new Font(fnt.BaseFont, fnt.Size, Font.BOLD, Color.RED); + Phrase p = BuildPhrase2(str, fnt, fntBold); PdfPCell cell = new PdfPCell(p); cell.PaddingBottom = 4; cell.BackgroundColor = bgColor; + datatable.AddCell(cell); } private void AddColSpanCell(PdfPTable datatable, string str, iTextSharp.text.Font fnt, Color bgColor, int span, int txtAlign) { iTextSharp.text.Font fntBold = new Font(fnt.BaseFont, fnt.Size, Font.BOLD, Color.RED); + Phrase p = BuildPhrase2(str, fnt, fntBold); PdfPCell cell = new PdfPCell(p); cell.PaddingBottom = 4; cell.BackgroundColor = bgColor; cell.Colspan = span; cell.HorizontalAlignment = txtAlign; + datatable.AddCell(cell); } private Phrase BuildPhrase(string str, Font fnt, Font fntBold) { Phrase p = new Phrase(); + if (_SearchString != null) { while (str.ToLower().Contains(_SearchString.ToLower())) { int iStart = str.ToLower().IndexOf(_SearchString.ToLower()); - if (iStart > 0) p.Add(new Phrase(str.Substring(0, iStart), fnt)); + + if (iStart > 0) + { + p.Add(new Phrase(str.Substring(0, iStart), fnt)); + } + Phrase p2 = new Phrase(str.Substring(iStart, _SearchString.Length), fntBold); p.Add(p2); + str = str.Substring(iStart + _SearchString.Length); } } - if (str.Length > 0) p.Add(new Phrase(str, fnt)); + + if (str.Length > 0) + p.Add(new Phrase(str, fnt)); + return p; } - private string _RegexSearchString = null; - private string RegexSearchString - { - get - { - if (_RegexSearchString == null) - { - _RegexSearchString = _SearchString; - // Make it match the smallest matching string - _RegexSearchString = _RegexSearchString.Replace("*", ".*?"); - // If search string starts with a wildcard use the beginning of line token (^) - if (_RegexSearchString.StartsWith(".*?")) - _RegexSearchString = "^" + _RegexSearchString; - // If search string ends with a wildcard use the end of line token ($) - if (_RegexSearchString.EndsWith(".*?")) - _RegexSearchString = _RegexSearchString + "$"; - _RegexSearchString = _RegexSearchString.Replace("[", @"\["); - _RegexSearchString = _RegexSearchString.Replace("]", @"\]"); - _RegexSearchString = _RegexSearchString.Replace("(", @"\("); - _RegexSearchString = _RegexSearchString.Replace(")", @"\)"); - } - return _RegexSearchString; - } - } + private Phrase BuildPhrase2(string str, Font fnt, Font fntBold) { Phrase p = new Phrase(); int lastIndex = 0; - if ((_SearchString ?? "") != "") + + if ((_SearchString ?? string.Empty) != string.Empty) { Regex reg = new Regex(RegexSearchString, RegexOptions.Multiline | RegexOptions.IgnoreCase); + foreach (Match m in reg.Matches(str)) { if (m.Index > 0) p.Add(new Phrase(str.Substring(lastIndex, m.Index - lastIndex), fnt)); + Chunk chk = new Chunk(m.Value, fnt); - //Phrase p2 = new Phrase(); - //foreach (Chunk chk in p2.Chunks) chk.SetBackground(Color.YELLOW); p.Add(chk); + lastIndex = m.Index + m.Length; } } + p.Add(new Phrase(str.Substring(lastIndex), fnt)); + return p; } + private void BuildLibDocUsageReport(iTextSharp.text.Document document) { // Adjusted from 20,80 to 25,75 to account for long Procedure Numbers @@ -696,48 +861,53 @@ namespace Volian.Print.Library // 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 - string lastDvPath = ""; + 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); + foreach (DocumentInfo di in _LibDocList) { - //PdfPTable datatable = LibDocTable(document, headerwidths, f2, di); - //AddMainPathGroup(datatable, ProcSetList[0].ToString(), splitAt, f2, Color.LIGHT_GRAY, 0);//2); PdfPTable subtable; subtable = BuildSubTable(document, headerwidths); - AddGroupLibDoc(subtable, di.DocumentTitle, "", f2, false, new Color(0xC0, 0xFF, 0xC0), false); // Library Document Title + AddGroupLibDoc(subtable, di.DocumentTitle, string.Empty, f2, false, new Color(0xC0, 0xFF, 0xC0), false); // Library Document Title + if (di.DocumentConfig.LibDoc_Comment != null && di.DocumentConfig.LibDoc_Comment.Length > 0) { AddCell(subtable, "Comment", f2, AnnoBackgroundColor); AddCell(subtable, di.DocumentConfig.LibDoc_Comment, f2, AnnoBackgroundColor); // lib doc comment } + if (di.DocumentEntries == null || di.DocumentEntries.Count == 0) { - AddGroupLibDoc(subtable, "* No References To This Library Document *", "", f2, false, TextBackgroundColor, false); // Library Document Title + AddGroupLibDoc(subtable, "* No References To This Library Document *", string.Empty, f2, false, TextBackgroundColor, false); // Library Document Title } else { subtable.HeaderRows = 2; System.Collections.ArrayList LibDocUsageList = GetSortedItemInfoList(di.LibraryDocumentUsageList); - lastDvPath = ""; + lastDvPath = string.Empty; + foreach (ItemInfo item in LibDocUsageList)//di.LibraryDocumentUsageList) { if (item.SearchDVPath != lastDvPath) { - if (lastDvPath != "") + if (lastDvPath != string.Empty) { document.Add(subtable); subtable = BuildSubTable(document, headerwidths); subtable.HeaderRows = 2; - AddGroupLibDoc(subtable, di.DocumentTitle, "", f2, false, new Color(0xC0, 0xFF, 0xC0), false); // Library Document Title + AddGroupLibDoc(subtable, di.DocumentTitle, string.Empty, f2, false, new Color(0xC0, 0xFF, 0xC0), false); // Library Document Title } + AddSubPathGroup(subtable, lastDvPath, item.SearchDVPath, splitAt, f2, Color.LIGHT_GRAY, 2);//new Color(0xC0, 0xFF, 0xC0)); } + lastDvPath = item.SearchDVPath; string ProcNumber = item.MyProcedure.ProcedureConfig.Number; ProcNumber = ProcNumber.Replace(@"\u8209?", "-"); // repace unicode with dash char @@ -748,22 +918,11 @@ namespace Volian.Print.Library } } + document.Add(subtable); } } - private static PdfPTable BuildSubTable(iTextSharp.text.Document document, float[] headerwidths) - { - PdfPTable subtable; - subtable = new PdfPTable(headerwidths); - subtable.HeaderRows = 1; - subtable.KeepTogether = true; - subtable.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin; - subtable.LockedWidth = true; - subtable.DefaultCell.Padding = 4; - return subtable; - } - private PdfPTable LibDocTable(iTextSharp.text.Document document, float[] headerwidths, iTextSharp.text.Font f2, DocumentInfo di) { PdfPTable datatable = new PdfPTable(1);// (headerwidths); @@ -772,6 +931,7 @@ namespace Volian.Print.Library 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); @@ -779,24 +939,32 @@ namespace Volian.Print.Library PdfPCell cell = new PdfPCell(new Phrase(ReportTitle, f1)); cell.HorizontalAlignment = Element.ALIGN_CENTER; //cell.Colspan = 2; + cell.BackgroundColor = new Color(0xD0, 0xF0, 0xF0); datatable.AddCell(cell); + Color subHeaderColor = new Color(0xD0, 0xF0, 0xD0); datatable.DefaultCell.Padding = 4; datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER; AddCell(colheader, "Procedure", f2, subHeaderColor); AddCell(colheader, "Section", f2, subHeaderColor); datatable.AddCell(colheader); + datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT; + return datatable; } + private void AddROUsages(ItemInfo item, Dictionary> roUse) { - if (item.FoundROID != null && item.FoundROID != "") + if (item != null && !string.IsNullOrEmpty(item.FoundROID)) { string roid = item.FoundROID; + if (roUse.ContainsKey(roid)) + { ((List)roUse[roid]).Add(item); + } else { List itmIfoLst = new List(); @@ -805,182 +973,64 @@ 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); + foreach (string roKey in rosused.Keys) { PdfPTable rotable = new PdfPTable(headerwidths); - string rotitle = ""; + string rotitle = string.Empty; + foreach (ItemInfo itm in rosused[roKey]) { - if (rotitle == "") + if (string.IsNullOrEmpty(rotitle)) { rotitle = GetROTitleAndGroup(roKey, itm); - if (rotitle != null && rotitle != "") + + if (!string.IsNullOrEmpty(rotitle)) { PdfPCell ROTitleCell = new PdfPCell(new Phrase(rotitle, f2)); ROTitleCell.Colspan = 2; ROTitleCell.HorizontalAlignment = Element.ALIGN_LEFT; + if (rotitle.StartsWith("Missing RO")) + { ROTitleCell.BackgroundColor = Color.PINK; + } else + { 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 } } - string stepnum = ""; - string sectitle = (itm.ActiveSection != null) ? itm.ActiveSection.DisplayText : ""; + + string stepnum = string.Empty; + string sectitle = (itm.ActiveSection != null) ? itm.ActiveSection.DisplayText : string.Empty; + if (itm.IsSection) - stepnum = (itm.ActiveSection != null) ? itm.ActiveSection.DisplayNumber : ""; + { + stepnum = (itm.ActiveSection != null) ? itm.ActiveSection.DisplayNumber : string.Empty; + } else - stepnum = BuildStepTab(itm);//GetStepNumberFromSearchPath(itm.SearchPath);//stepnum.Substring(itm.SearchPath.LastIndexOf(sectitle) + sectitle.Length +1); + { + stepnum = BuildStepTab(itm); + } + AddCell(rotable, stepnum, f2, Color.WHITE); AddCell(rotable, itm.DisplayText, f2, Color.WHITE); + } + curTable.AddCell(rotable); } } - private static string BuildStepTab(ItemInfo item) - { - if (item == null) return ""; - string sret = ""; - switch (item.MyContent.Type / 10000) - { - case 0: //procedure - sret = ProcedureInfo.Get(item.ItemID).MyTab.CleanText; - break; - case 1: // section - sret = SectionInfo.Get(item.ItemID).MyTab.CleanText; - break; - case 2: // step - - ItemInfo pitem = item; - bool hasDelim = item.ActiveFormat.PlantFormat.FormatData.TransData.StepSubstepDelimeter != null; - List DelimList = null; - DelimList = new List(); - if (!hasDelim) - { - SeqTabFmtList seqtabs = item.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.SeqTabFmtList; - foreach (SeqTabFmt seqtab in seqtabs) - { - string delim = seqtab.PrintTabFormat.Replace("{seq}", ""); - if (!DelimList.Contains(delim)) - DelimList.Add(delim.Trim()); - } - } - else - { - string stpdelms = item.ActiveFormat.PlantFormat.FormatData.TransData.StepSubstepDelimeter; - foreach (char c in stpdelms) - { - if (!DelimList.Contains(c.ToString())) - DelimList.Add(c.ToString()); - } - } - // B2016-160 Support transitions to sections - while (!pitem.IsSection && !pitem.IsHigh) - { - StepInfo stpinfo = StepInfo.Get(pitem.ItemID); - string thisTab = stpinfo.MyTab.CleanText; //StepInfo.Get(pitem.ItemID).MyTab.CleanText; - if (IncludesParentToHLS(stpinfo)) - if (!thisTab.Contains("\u25CF")) //Remove Bullet - return thisTab; - else - thisTab = null; - string typeName = stpinfo.FormatStepData.StepEditData.TypeMenu.MenuItem;//stpinfo.FormatStepData.ToString(); - // remove delimiters of '.' and ')' in tab. - if (thisTab != null) - { - // get list of delimiters to remove from the format: - foreach (string rmvDelim in DelimList) thisTab = thisTab.Replace(rmvDelim, ""); - } - if (thisTab != null) thisTab = thisTab.Trim(); - // if the tab is null or - // if the the tab is not a letter or number OR - // the tab is an AND or OR type and is the letter "o" - // then reset the tab an empty string so that the type name along with the count of that type - // (ex. "AND 2", "OR 3") - if (thisTab == null || (thisTab != "" && (!(char.IsLetterOrDigit(thisTab[0])) || ((pitem.IsAnd || pitem.IsOr || pitem.IsCaution || pitem.IsNote) && thisTab.Contains("o"))))) - thisTab = ""; - if (pitem.IsRNOPart) - { - if (thisTab == "") - sret = "RNO." + sret; //"RNO." + sret; - else - { - thisTab = thisTab.Trim(" ".ToCharArray()); - if (!thisTab.EndsWith(".") && !thisTab.EndsWith(")")) thisTab = thisTab + "."; - sret = "RNO." + thisTab + sret; //"RNO." + thisTab + sret; - } - } - else if (pitem.IsCaution || pitem.IsNote) - { - // add the Caution or Note count to the tab (ex "Caution 1", "Note 2") - if (thisTab == "") - sret = "{" + typeName + " " + pitem.Ordinal.ToString() + "}"; - else - { - thisTab = thisTab.Trim(" ".ToCharArray()); - sret = thisTab + " " + pitem.Ordinal.ToString() + sret; - } - } - else - { - if (thisTab != "") - { - thisTab = thisTab.Trim(" ".ToCharArray()); - if (!thisTab.EndsWith(".") && !thisTab.EndsWith(")")) thisTab = thisTab + "."; - } - else - thisTab = "{" + typeName + " " + pitem.Ordinal.ToString() + "}."; - sret = thisTab + sret; - } - pitem = pitem.ActiveParent as ItemInfo; - if (pitem == null) break; - } - // add hls tab if it's not already in the tab. - if (pitem.IsHigh) - { - StepInfo stpinfo = StepInfo.Get(pitem.ItemID); - - string hlsTab = stpinfo.MyTab.CleanTextNoSymbols; //StepInfo.Get(pitem.ItemID).MyTab.CleanTextNoSymbols; - string typeName = stpinfo.FormatStepData.StepEditData.TypeMenu.MenuItem;//stpinfo.FormatStepData.GetPDDisplayName(); //.ToString(); - // C2020-043: don't remove delimiters on tabs if this step's tab has the parent tab included. - bool hasParent = false; - if (IncludesParentToHLS(stpinfo) && !hlsTab.Contains("\u25CF")) - { - hlsTab = hlsTab.Trim(" ".ToCharArray()).TrimEnd(".".ToCharArray()); - hasParent = true; - } - if (hlsTab == null || hlsTab == "") - hlsTab = "{" + typeName + " " + pitem.Ordinal.ToString() + "}."; - else if (!hasParent && !sret.StartsWith(hlsTab.Trim(" ".ToCharArray()))) - { - foreach (string rmvDelim in DelimList) hlsTab = hlsTab.Replace(rmvDelim, ""); - hlsTab = hlsTab.Trim(" ".ToCharArray()); - if (!hlsTab.EndsWith(".") && !hlsTab.EndsWith(")")) hlsTab = hlsTab + "."; - } - sret = hlsTab + sret; - } - break; - } - sret = sret.Trim(" .)".ToCharArray()); - return sret; - } - - private static bool IncludesParentToHLS(StepInfo stpinfo) - { - if (stpinfo.IsHigh) - return true; - StepInfo parent = StepInfo.Get((stpinfo.ActiveParent as ItemInfo).ItemID); - if (stpinfo.MyTab.CleanText.StartsWith(parent.MyTab.CleanText.Trim()) && stpinfo.MyTab.CleanText.Length > parent.MyTab.CleanText.Length) - return IncludesParentToHLS(parent); - return false; - } private void BuildROUsageTableByProcedure(iTextSharp.text.Document document) { @@ -991,6 +1041,7 @@ namespace Volian.Print.Library //datatable.FooterRows = 1; 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); @@ -1004,11 +1055,12 @@ namespace Volian.Print.Library BuildSearchResultsProcSetList(); datatable.HeaderRows = 2;//3 + (ProcSetList.Count == 1 ? 1 : 0); - int splitAt = FindSpitLevel(); // find the split level of the common path - for all procedure sets that use these library documents + int splitAt = FindSpitLevel(); // find the split level of the common path Color subHeaderColor = new Color(0xD0, 0xF0, 0xF0); // light blue //new Color(0xD0, 0xF0, 0xD0);//ligt green datatable.DefaultCell.Padding = 4; datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER; + // This puts "Step" and "Text" column headers at the bottom of the page AddCell(colHeader, "Step", f2, subHeaderColor); AddCell(colHeader, "Text", f2, subHeaderColor); @@ -1019,33 +1071,45 @@ namespace Volian.Print.Library Color SectColor = new Color(0xE0, 0xFF, 0xE0);//new Color(0xC0, 0xFF, 0xC0);//Color.LIGHT_GRAY; PdfPTable subTable = new PdfPTable(headerwidths); datatable.AddCell(subTable); - string lastProcNum = ""; - string lastSection = ""; - string lastDVPath = ""; + + string lastProcNum = string.Empty; + string lastSection = string.Empty; + string lastDVPath = string.Empty; + foreach (ItemInfo item in _ResultList) { + bool differentProcSet = false; + bool differentRO = false; // Check Doc Version path - if (lastDVPath != item.SearchDVPath) + // if more than one procedure set is in the report data, then + // we will output the procedure set title inside the grouping of each RO + // otherwise, if we are reporting on only one procedure set, print the + // procedure set title at the top of the report (once). + if (lastDVPath != "" && lastDVPath != item.SearchDVPath) { subTable = new PdfPTable(headerwidths); AddMainPathGroup(datatable, item.SearchDVPath, splitAt, f2, Color.LIGHT_GRAY, 0); - lastProcNum = ""; - lastSection = ""; + lastProcNum = string.Empty; + lastSection = string.Empty; } + lastDVPath = item.SearchDVPath; //check for different procedure number string curProcNum = GetCurProcNum(item.SearchPath); string curSection = GetCurSectionNumTitle(item); - if (lastProcNum != "" && (curProcNum != lastProcNum)) + + if (!string.IsNullOrEmpty(lastProcNum) && (curProcNum != lastProcNum)) { if (roUse.Count > 0) { PutROusageForProcedure(datatable, roUse, headerwidths); roUse.Clear(); } - lastSection = ""; + + lastSection = string.Empty; } - if (lastSection != "" && (curSection != lastSection)) + + if (!string.IsNullOrEmpty(lastSection) && (curSection != lastSection)) { if (roUse.Count > 0) { @@ -1053,22 +1117,29 @@ namespace Volian.Print.Library roUse.Clear(); } } + AddROUsages(item, roUse); // add the used ro to the list for this procedure AddProcedureSectionGroup(datatable, curProcNum, lastProcNum, curSection, lastSection, f2, new Color(0xC0, 0xFF, 0xC0)); + lastProcNum = curProcNum; lastSection = curSection; } + PutROusageForProcedure(datatable, roUse, headerwidths); + document.Add(datatable); } private void AddProcROUse(ItemInfo item, SortedDictionary> procRoUse) { string dictKey = GetCurProcNum(item.SearchPath) + " " + GetCurSectionNumTitle(item); - if (dictKey != null && dictKey != "") + + if (dictKey != null && dictKey != string.Empty) { if (procRoUse.ContainsKey(dictKey)) + { ((List)procRoUse[dictKey]).Add(item); + } else { List itmIfoLst = new List(); @@ -1083,27 +1154,33 @@ namespace Volian.Print.Library // 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) { string stepnum = (itm.IsSection && itm.ActiveSection != null) ? itm.ActiveSection.DisplayNumber : stepnum = BuildStepTab(itm);// C2018-003 fixed use of getting the active section AddCell(rotable, stepnum, f2, Color.WHITE); AddCell(rotable, itm.DisplayText, f2, Color.WHITE); } + sortedStepList.Clear(); } + private void PutROusageForROID(PdfPTable curTable, SortedDictionary> procRoUse, float[] headerwidths, int splitAt , bool moreThanOneProcSet) { - SortedDictionary sortedStepList = new SortedDictionary(); // 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); - string lastProcKey = ""; - string lastProcNumTitle = ""; - string lastDVPath = ""; - string curProcNumTitle = ""; + + SortedDictionary sortedStepList = new SortedDictionary(); + string lastProcKey = string.Empty; + string lastProcNumTitle = string.Empty; + string lastDVPath = string.Empty; + string curProcNumTitle = string.Empty; + foreach (string procKey in procRoUse.Keys) { PdfPTable rotable = new PdfPTable(headerwidths); + foreach (ItemInfo itm in procRoUse[procKey]) { bool didProcSetTitle = false; @@ -1116,19 +1193,28 @@ namespace Volian.Print.Library didProcSetTitle = true; } else + { didProcSetTitle = false; + } + lastDVPath = itm.SearchDVPath; if (didProcSetTitle || procKey != lastProcKey) { - if (sortedStepList.Count > 0) PutStepListForProcedure(rotable, sortedStepList); - string procNumTitleSect = ""; + if (sortedStepList.Count > 0) + { + PutStepListForProcedure(rotable, sortedStepList); + } + + string procNumTitleSect = string.Empty; curProcNumTitle = GetCurProcNum(itm.SearchPath); - if (lastProcNumTitle == "" || lastProcNumTitle != curProcNumTitle) + + if (lastProcNumTitle == string.Empty || lastProcNumTitle != curProcNumTitle) { procNumTitleSect = curProcNumTitle + "\r\n"; lastProcNumTitle = curProcNumTitle; } + procNumTitleSect += " " + GetCurSectionNumTitle(itm); procNumTitleSect = procNumTitleSect.Replace(@"\u8209?", "-"); // repace unicode with dash char procNumTitleSect = procNumTitleSect.Replace(@"\u160?", " "); // replace Hard Space with normal Space @@ -1140,23 +1226,34 @@ namespace Volian.Print.Library rotable.AddCell(ProcTitleCell); // put RO value and description lastProcKey = procKey; } + string stepnum = (itm.IsSection && itm.ActiveSection != null) ? itm.ActiveSection.DisplayNumber : BuildStepTab(itm);// C2018-003 fixed use of getting the active section string itemkey = stepnum + " " + itm.ItemID.ToString(); // add ItemId to stepnum, sometimes we have idential stepnum text for different steps (ex: blank section numbers) + if (!sortedStepList.ContainsKey(itemkey)) + { sortedStepList.Add(itemkey, itm); + } } - if (sortedStepList.Count > 0) PutStepListForProcedure(rotable, sortedStepList); + + if (sortedStepList.Count > 0) + { + PutStepListForProcedure(rotable, sortedStepList); + } + curTable.AddCell(rotable); } } - //private static string GetROTitleAndGroup(string roid, ItemInfo itm) private string GetROTitleAndGroup(string roid, ItemInfo itm) { - string rotitle = ""; + string rotitle = string.Empty; + 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) @@ -1164,6 +1261,8 @@ namespace Volian.Print.Library else rotitle += roTitleList[cnt] + "\n "; } + } + return rotitle; } @@ -1183,7 +1282,6 @@ namespace Volian.Print.Library } } - private void BuildROUsageTableByRO(iTextSharp.text.Document document) { SortedDictionary> procRoUse = new SortedDictionary>(); @@ -1193,6 +1291,7 @@ namespace Volian.Print.Library //datatable.FooterRows = 1; 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); @@ -1214,77 +1313,97 @@ namespace Volian.Print.Library AddCell(colHeader, "Step", f2, subHeaderColor); AddCell(colHeader, "Text", f2, subHeaderColor); datatable.AddCell(colHeader); + datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT; Color AnnoColor = new Color(0xFF, 0xFF, 0xC0); Color TextColor = Color.WHITE; Color SectColor = new Color(0xE0, 0xFF, 0xE0);//new Color(0xC0, 0xFF, 0xC0);//Color.LIGHT_GRAY; PdfPTable subTable = new PdfPTable(headerwidths); datatable.AddCell(subTable); - string lastDVPath = ""; - string lastROID = ""; + + string lastDVPath = string.Empty; + string lastROID = string.Empty; bool moreThanOneProcSet = false; bool printedSetTitle = false; bool printedROHeader = false; ItemInfo lastItem = null; + if (_ResultList.Count == 0) { PdfPCell cell2 = new PdfPCell(new Phrase("Selected RO is not used", f2)); + cell2.Colspan = 0; cell2.BorderWidthTop = 1; datatable.AddCell(cell2); document.Add(datatable); + return; } + foreach (ItemInfo item in _ResultList) { bool differentProcSet = false; bool differentRO = false; + // Check Doc Version path // if more than one procedure set is in the report data, then // we will output the procedure set title inside the grouping of each RO // otherwise, if we are reporting on only one procedure set, print the // procedure set title at the top of the report (once). - if (lastDVPath != "" && lastDVPath != item.SearchDVPath) + if (!string.IsNullOrEmpty(lastDVPath) && lastDVPath != item.SearchDVPath) { moreThanOneProcSet = true; differentProcSet = true; } + lastDVPath = item.SearchDVPath; // Check for different ROID string curROID = item.FoundROID; - differentRO = lastROID != "" && curROID.Substring(0, 12) != lastROID.Substring(0, 12); + differentRO = lastROID != string.Empty && curROID.Substring(0, 12) != lastROID.Substring(0, 12); + if (procRoUse.Count > 0 && (differentProcSet || differentRO)) { - if (!moreThanOneProcSet && !printedSetTitle) - { - AddMainPathGroup(datatable, lastDVPath, splitAt, f2, Color.LIGHT_GRAY, 0); - printedSetTitle = true; - } - if (!printedROHeader) - { - AddROHeaderGroup(datatable, lastROID, lastItem, f2, new Color(0xC0, 0xFF, 0xC0)); - printedROHeader = true; - } - PutROusageForROID(datatable, procRoUse, headerwidths, splitAt, moreThanOneProcSet); - procRoUse.Clear(); + if (!moreThanOneProcSet && !printedSetTitle) + { + AddMainPathGroup(datatable, lastDVPath, splitAt, f2, Color.LIGHT_GRAY, 0); + printedSetTitle = true; + } + + if (!printedROHeader) + { + AddROHeaderGroup(datatable, lastROID, lastItem, f2, new Color(0xC0, 0xFF, 0xC0)); + printedROHeader = true; + } + + PutROusageForROID(datatable, procRoUse, headerwidths, splitAt, moreThanOneProcSet); + procRoUse.Clear(); + differentProcSet = false; } + if (differentRO) + { printedROHeader = false; + } + AddProcROUse(item, procRoUse); + lastROID = curROID; lastItem = item; } + if (!moreThanOneProcSet && !printedSetTitle) AddMainPathGroup(datatable, lastDVPath, splitAt, f2, Color.LIGHT_GRAY, 0); + if (!printedROHeader) AddROHeaderGroup(datatable, lastROID, lastItem, f2, new Color(0xC0, 0xFF, 0xC0)); + PutROusageForROID(datatable, procRoUse, headerwidths, splitAt, moreThanOneProcSet); + document.Add(datatable); } - private System.Collections.ArrayList ProcSetList; private void BuildSearchResultsProcSetList() { ProcSetList = new System.Collections.ArrayList(); @@ -1294,6 +1413,7 @@ namespace Volian.Print.Library ProcSetList.Add(item.SearchDVPath); } } + private void BuildLibDocProcSetList() { ProcSetList = new System.Collections.ArrayList(); @@ -1307,7 +1427,8 @@ namespace Volian.Print.Library } } } - private System.Collections.ArrayList GetSortedItemInfoList(ItemInfoList orgIFL) + + private ArrayList GetSortedItemInfoList(ItemInfoList orgIFL) { System.Collections.ArrayList libDocProcSetList = new System.Collections.ArrayList(); System.Collections.ArrayList rtnIFL = new System.Collections.ArrayList(); @@ -1340,10 +1461,11 @@ namespace Volian.Print.Library compRORpt.ROFstID = _ROFSTLookup.MyDocVersionInfo.DocVersionAssociations[0].MyROFst.ROFstID; compRORpt.Run(); } + private string GetROTitleAndGroupsForSummary(ListroTitleList, List prevROTitleList) { - string rotitle = ""; - string indent = ""; + string rotitle = string.Empty; + string indent = string.Empty; for (int icnt = 0; icnt < roTitleList.Count; icnt++) { indent += " "; @@ -1354,13 +1476,14 @@ namespace Volian.Print.Library } if (prevROTitleList == null || (icnt < roTitleList.Count && icnt < prevROTitleList.Count && prevROTitleList[icnt] != roTitleList[icnt])) { - if (rotitle == "" && prevROTitleList != null) + 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) { List roTitleList = _ROFSTLookup.GetROTitleAndGroupPath(curROID,_IncludeMissingROs,_ConvertCaretToDelta); @@ -1378,16 +1501,6 @@ namespace Volian.Print.Library } return roTitleList; } - public void AddMainRODatabaseTitle(PdfPTable datatable, int dbTitleIndex, Font f2, Color bgColor) - { - string dbTitle = _ROFSTLookup.GetRODatabaseTitle(dbTitleIndex); - PdfPCell cell = new PdfPCell(new Phrase(dbTitle, f2)); - cell.BorderColor = Color.WHITE; - cell.Colspan = 2; - cell.BackgroundColor = bgColor; - datatable.AddCell(cell); - return; - } private void BuildROSummaryReport(iTextSharp.text.Document document) { @@ -1395,12 +1508,15 @@ namespace Volian.Print.Library PdfPTable datatable = new PdfPTable(1); 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); + PdfPCell cell = new PdfPCell(new Phrase(ReportTitle, f1)); + cell.HorizontalAlignment = Element.ALIGN_CENTER; //cell.Colspan = 2; cell.BackgroundColor = Color.WHITE;//new Color(0xD0, 0xF0, 0xF0); // light blue @@ -1414,35 +1530,46 @@ namespace Volian.Print.Library datatable.HeaderRows = 2;//3 + (ProcSetList.Count == 1 ? 1 : 0); datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT; - string lastROID = ""; + string lastROID = string.Empty; 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[] roIdslst = rolst.Split(','); + foreach (string cROID in roIdslst) { - if (cROID == "") break; + if (string.IsNullOrEmpty(cROID)) + break; + if (cROID.Length == 4) ProcessROdb(datatable, f2, f3, ref cell, ref lastROID, ref prevROTitleList, ref lastDBindex, cROID); else ProcessROID(datatable, f2, f3, ref cell, ref lastROID, ref prevROTitleList, ref lastDBindex, cROID); } } + document.Add(datatable); } private void ProcessROdb(PdfPTable datatable, iTextSharp.text.Font f2, iTextSharp.text.Font f3, ref PdfPCell cell, ref string lastROID, ref List prevROTitleList, ref int lastDBindex, string cROID) { - ROFSTLookup.rodbi roDBI = _ROFSTLookup.GetRODatabase(cROID); - if (roDBI.children != null) - foreach (ROFSTLookup.rochild cld in roDBI.children) - ProcessROChild(datatable, f2, f3, ref cell, ref lastROID, ref prevROTitleList, ref lastDBindex, cld); + ROFSTLookup.rodbi roDBI = _ROFSTLookup.GetRODatabase(cROID, true, true); + + if (roDBI.children != null && roDBI.children.Length > 0) + { + for (int i = 0; i < roDBI.children.Length; i++) + { + ProcessROChild(datatable, f2, f3, ref cell, ref lastROID, ref prevROTitleList, ref lastDBindex, roDBI.children[i]); + } + } else { ProcessROID(datatable, f2, f3, ref cell, ref lastROID, ref prevROTitleList, ref lastDBindex, cROID); + cell = new PdfPCell(new Phrase(" ", f2)); cell.BorderColor = Color.WHITE; datatable.AddCell(cell); @@ -1454,18 +1581,27 @@ 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) { - if (cld.children == null) // leaf node - ProcessROID(datatable, f2, f3, ref cell, ref lastROID, ref prevROTitleList, ref lastDBindex, cld.roid); + if (cld.children == null || cld.children.Length <= 0) // leaf node + { + ProcessROID(datatable, f2, f3, ref cell, ref lastROID, ref prevROTitleList, ref lastDBindex, cld.roid); + } else if (cld.children[0].ParentID == 0) // multiple return value - ProcessROID(datatable, f2, f3, ref cell, ref lastROID, ref prevROTitleList, ref lastDBindex, cld.roid); + { + ProcessROID(datatable, f2, f3, ref cell, ref lastROID, ref prevROTitleList, ref lastDBindex, cld.roid); + } else - foreach (ROFSTLookup.rochild gcld in cld.children) - ProcessROChild(datatable, f2, f3, ref cell, ref lastROID, ref prevROTitleList, ref lastDBindex, gcld); + { + for (int i = 0; i < cld.children.Length; i++) + { + ProcessROChild(datatable, f2, f3, ref cell, ref lastROID, ref prevROTitleList, ref lastDBindex, cld.children[i]); + } + } } private void ProcessROID(PdfPTable datatable, iTextSharp.text.Font f2, iTextSharp.text.Font f3, ref PdfPCell cell, ref string lastROID, ref List prevROTitleList, ref int lastDBindex, string cROID) { - int curDBindex = _ROFSTLookup.GetRODatabaseTitleIndex(cROID);// Convert.ToInt32(cROID.Substring(0, 4)); + int curDBindex = _ROFSTLookup.GetRODatabaseTitleIndex(cROID); + if (lastDBindex == -1 || curDBindex != lastDBindex) { if (prevROTitleList != null) @@ -1475,80 +1611,345 @@ namespace Volian.Print.Library cell.BorderColor = Color.WHITE; datatable.AddCell(cell); } + AddMainRODatabaseTitle(datatable, curDBindex, f3, Color.WHITE); lastDBindex = curDBindex; } - if (lastROID == "" || cROID != lastROID) + + if (string.IsNullOrEmpty(lastROID) || cROID != lastROID) prevROTitleList = AddROHeaderGroupForSummary(datatable, cROID, prevROTitleList, f2, new Color(0xC0, 0xFF, 0xC0)); + lastROID = cROID; } + + #endregion + + #region Private Static Methods + + private static PdfPTable BuildSubTable(iTextSharp.text.Document document, float[] headerwidths) + { + PdfPTable subtable = new PdfPTable(headerwidths); + + subtable.HeaderRows = 1; + subtable.KeepTogether = true; + subtable.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin; + subtable.LockedWidth = true; + subtable.DefaultCell.Padding = 4; + + return subtable; + } + + private static void ShowException(Exception ex) + { + Console.WriteLine("{0} - {1}", ex.GetType().Name, ex.Message); + StringBuilder msg = new StringBuilder(); + string sep = string.Empty; + string indent = string.Empty; + + while (ex != null) + { + msg.Append(string.Format("{0}{1}{2}:\r\n{1}{3}", sep, indent, ex.GetType().Name, ex.Message)); + ex = ex.InnerException; + sep = "\r\n"; + indent += " "; + } + + System.Windows.Forms.MessageBox.Show(msg.ToString(), "Error during PDF creation for search:", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation); + } + + private static string BuildStepTab(ItemInfo item) + { + if (item == null) + return string.Empty; + + string sret = string.Empty; + + switch (item.MyContent.Type / 10000) + { + case 0: //procedure + sret = ProcedureInfo.Get(item.ItemID).MyTab.CleanText; + break; + + case 1: // section + sret = SectionInfo.Get(item.ItemID).MyTab.CleanText; + break; + + case 2: // step + ItemInfo pitem = item; + bool hasDelim = item.ActiveFormat.PlantFormat.FormatData.TransData.StepSubstepDelimeter != null; + List DelimList = null; + DelimList = new List(); + + if (!hasDelim) + { + SeqTabFmtList seqtabs = item.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.SeqTabFmtList; + + foreach (SeqTabFmt seqtab in seqtabs) + { + string delim = seqtab.PrintTabFormat.Replace("{seq}", string.Empty); + + if (!DelimList.Contains(delim)) + { + DelimList.Add(delim.Trim()); + } + } + } + else + { + string stpdelms = item.ActiveFormat.PlantFormat.FormatData.TransData.StepSubstepDelimeter; + + foreach (char c in stpdelms) + { + if (!DelimList.Contains(c.ToString())) + { + DelimList.Add(c.ToString()); + } + } + } + + // B2016-160 Support transitions to sections + while (!pitem.IsSection && !pitem.IsHigh) + { + StepInfo stpinfo = StepInfo.Get(pitem.ItemID); + string thisTab = stpinfo.MyTab.CleanText; + + if (IncludesParentToHLS(stpinfo)) + { + if (!thisTab.Contains("\u25CF")) //Remove Bullet + { + return thisTab; + } + else + { + thisTab = null; + } + } + + string typeName = stpinfo.FormatStepData.StepEditData.TypeMenu.MenuItem;//stpinfo.FormatStepData.ToString(); + + // remove delimiters of '.' and ')' in tab. + if (!string.IsNullOrEmpty(thisTab)) + { + // get list of delimiters to remove from the format: + foreach (string rmvDelim in DelimList) + { + thisTab = thisTab.Replace(rmvDelim, string.Empty); + } + } + + if (!string.IsNullOrEmpty(thisTab)) + { + thisTab = thisTab.Trim(); + } + + // if the tab is null or + // if the the tab is not a letter or number OR + // the tab is an AND or OR type and is the letter "o" + // then reset the tab an empty string so that the type name along with the count of that type + // (ex. "AND 2", "OR 3") + if (string.IsNullOrEmpty(thisTab) || (thisTab != string.Empty && (!(char.IsLetterOrDigit(thisTab[0])) || ((pitem.IsAnd || pitem.IsOr || pitem.IsCaution || pitem.IsNote) && thisTab.Contains("o"))))) + { + thisTab = string.Empty; + } + + if (pitem.IsRNOPart) + { + if (string.IsNullOrEmpty(thisTab)) + { + sret = "RNO." + sret; //"RNO." + sret; + } + else + { + thisTab = thisTab.Trim(" ".ToCharArray()); + + if (!thisTab.EndsWith(".") && !thisTab.EndsWith(")")) + { + thisTab = thisTab + "."; + } + + sret = "RNO." + thisTab + sret; //"RNO." + thisTab + sret; + } + } + else if (pitem.IsCaution || pitem.IsNote) + { + // add the Caution or Note count to the tab (ex "Caution 1", "Note 2") + if (string.IsNullOrEmpty(thisTab)) + { + sret = "{" + typeName + " " + pitem.Ordinal.ToString() + "}"; + } + else + { + thisTab = thisTab.Trim(" ".ToCharArray()); + sret = thisTab + " " + pitem.Ordinal.ToString() + sret; + } + } + else + { + if (!string.IsNullOrEmpty(thisTab)) + { + thisTab = thisTab.Trim(" ".ToCharArray()); + + if (!thisTab.EndsWith(".") && !thisTab.EndsWith(")")) + { + thisTab = thisTab + "."; + } + } + else + { + thisTab = "{" + typeName + " " + pitem.Ordinal.ToString() + "}."; + } + + sret = thisTab + sret; + } + + pitem = pitem.ActiveParent as ItemInfo; + + if (pitem == null) + break; + } + + // add hls tab if it's not already in the tab. + if (pitem.IsHigh) + { + StepInfo stpinfo = StepInfo.Get(pitem.ItemID); + + string hlsTab = stpinfo.MyTab.CleanTextNoSymbols; //StepInfo.Get(pitem.ItemID).MyTab.CleanTextNoSymbols; + string typeName = stpinfo.FormatStepData.StepEditData.TypeMenu.MenuItem;//stpinfo.FormatStepData.GetPDDisplayName(); //.ToString(); + // C2020-043: don't remove delimiters on tabs if this step's tab has the parent tab included. + bool hasParent = false; + + if (IncludesParentToHLS(stpinfo) && !hlsTab.Contains("\u25CF")) + { + hlsTab = hlsTab.Trim(" ".ToCharArray()).TrimEnd(".".ToCharArray()); + hasParent = true; + } + + if (string.IsNullOrEmpty(hlsTab)) + { + hlsTab = "{" + typeName + " " + pitem.Ordinal.ToString() + "}."; + } + else if (!hasParent && !sret.StartsWith(hlsTab.Trim(" ".ToCharArray()))) + { + foreach (string rmvDelim in DelimList) + { + hlsTab = hlsTab.Replace(rmvDelim, string.Empty); + } + + hlsTab = hlsTab.Trim(" ".ToCharArray()); + + if (!hlsTab.EndsWith(".") && !hlsTab.EndsWith(")")) + { + hlsTab = hlsTab + "."; + } + } + + sret = hlsTab + sret; + } + + break; + } + + return sret.Trim(" .)".ToCharArray()); + } + + private static bool IncludesParentToHLS(StepInfo stpinfo) + { + if (stpinfo.IsHigh) + return true; + + StepInfo parent = StepInfo.Get((stpinfo.ActiveParent as ItemInfo).ItemID); + + if (stpinfo.MyTab.CleanText.StartsWith(parent.MyTab.CleanText.Trim()) && stpinfo.MyTab.CleanText.Length > parent.MyTab.CleanText.Length) + { + return IncludesParentToHLS(parent); + } + + return false; + } + + #endregion } + + public class MyPageHelper : PdfPageEventHelper { + #region Fields + private PdfPTable _HeaderTable = null; - public PdfPTable HeaderTable - { - get { return _HeaderTable; } - set { _HeaderTable = value; } - } protected PdfTemplate total; protected BaseFont helv; private int ptSize = 10; // text point size of page number and page total string _ByLine = "PROMS"; + #endregion + + #region Properties + + public PdfPTable HeaderTable + { + get { return _HeaderTable; } + set { _HeaderTable = value; } + } + + #endregion + + #region Constructors + public MyPageHelper(string byLine) { _ByLine = byLine; } + + #endregion + + #region Public Methods + public override void OnOpenDocument(PdfWriter writer, iTextSharp.text.Document document) { total = writer.DirectContent.CreateTemplate(100, 100); total.BoundingBox = new Rectangle(-20, -20, 100, 100); - //try - //{ - helv = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); - //} - //catch (Exception) - //{ - // //throw new ExceptionConverter(e); - //} + helv = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); } + public override void OnEndPage(PdfWriter writer, iTextSharp.text.Document document) { PdfContentByte cb = writer.DirectContent; + cb.SaveState(); + if (HeaderTable != null) 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); - //if ((writer.PageNumber % 2) == 1) - //{ - // cb.SetTextMatrix(document.Left, textBase); - // cb.ShowText(text); - // cb.EndText(); - // cb.AddTemplate(total, document.Left + textSize, textBase); - //} - //else - //{ - // float adjust = helv.GetWidthPoint("0", 12); - // cb.SetTextMatrix( - // document.Right - textSize - adjust, textBase); - // cb.ShowText(text); - // cb.EndText(); - // cb.AddTemplate(total, document.Right - adjust, textBase); - //} + 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); AddDateFooter(writer, document); } + public override void OnCloseDocument(PdfWriter writer, iTextSharp.text.Document document) + { + total.BeginText(); + total.SetFontAndSize(helv, ptSize); + total.SetTextMatrix(0, 0); + total.ShowText((writer.PageNumber - 1).ToString()); + total.EndText(); + + base.OnCloseDocument(writer, document); + } + + #endregion + + #region Private Methods + private void AddVolianFooter(PdfWriter writer, iTextSharp.text.Document document) { PdfContentByte cb = writer.DirectContent; @@ -1580,16 +1981,7 @@ namespace Volian.Print.Library cb.RestoreState(); } - - public override void OnCloseDocument(PdfWriter writer, iTextSharp.text.Document document) - { - total.BeginText(); - total.SetFontAndSize(helv, ptSize); - total.SetTextMatrix(0, 0); - total.ShowText((writer.PageNumber - 1).ToString()); - total.EndText(); - base.OnCloseDocument(writer, document); - } + #endregion } }