diff --git a/PROMS/VEPROMS User Interface/frmVEPROMS.cs b/PROMS/VEPROMS User Interface/frmVEPROMS.cs index 07f0ab5a..d9ce5f40 100644 --- a/PROMS/VEPROMS User Interface/frmVEPROMS.cs +++ b/PROMS/VEPROMS User Interface/frmVEPROMS.cs @@ -4499,7 +4499,6 @@ namespace VEPROMS { infoPanel.Expanded = true; infoTabs.SelectedTab = infotabTags; - displayTags.HighlightChangeStep(); } else if (args.PanelTabName == "Change Image Size") { @@ -4620,7 +4619,7 @@ namespace VEPROMS // also change the text on the buttons to read either Find or Find/Replace // also toggle the Replace tab on the dialog based on the user's accessibility to the procedure bool isReviewer = !MyUserInfo.IsAllowedToEdit(tc.SelectedDisplayTabItem.MyItemInfo.MyDocVersion); - pnl.MyStepTabPanel.MyStepTabRibbon.SetButtonAndMenuEnabling(true); + pnl.MyStepTabPanel.MyStepTabRibbon.SetButtonAndMenuEnabling(); this.dlgFindReplace.ToggleReplaceTab(isReviewer ? E_ViewMode.View : E_ViewMode.Edit); pnl.MyStepTabPanel.MyStepTabRibbon.ToggleFindReplaceToolTip(isReviewer); } @@ -5266,8 +5265,8 @@ namespace VEPROMS { if (SelectedDVI != null) displayReports.Mydocversion = SelectedDVI; - displayReports.advTreeProcSetsFillIn(reportFocus); - displayReports.advTreeROFillIn(reportFocus); + displayReports.advTreeProcSetsFillIn(); + displayReports.advTreeROFillIn(); displayReports.SelectReferencedObjectTab(); // to enable RO selection } } diff --git a/PROMS/Volian.Controls.Library/AlphabeticalNumbering.cs b/PROMS/Volian.Controls.Library/AlphabeticalNumbering.cs deleted file mode 100644 index c008ab32..00000000 --- a/PROMS/Volian.Controls.Library/AlphabeticalNumbering.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Volian.Controls.Library -{ - class AlphabeticalNumbering - { - //private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - private static string Letter(int number) - { - char c = (char)(number + 64); - return c.ToString(); - } - public static string Convert(int number) - { - string retval=string.Empty; - if (number > 26) retval += Letter((number-1) / 26); - retval += Letter(1 + ((number-1) % 26)); - return retval; - } - //private static int[] _TestLetters = new int[] { - // 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27, - // 52,53,78,79,104,105 - // }; - //public static void ShowLetters() - //{ - // for (int i = 0; i < _TestLetters.Length; i++) - // { - // if(_MyLog.IsInfoEnabled)_MyLog.InfoFormat("{0},{1}", _TestLetters[i], Convert(_TestLetters[i])); - // } - //} - } -} diff --git a/PROMS/Volian.Controls.Library/AnnotationDetails.cs b/PROMS/Volian.Controls.Library/AnnotationDetails.cs index 45cbeb1d..bf9c380a 100644 --- a/PROMS/Volian.Controls.Library/AnnotationDetails.cs +++ b/PROMS/Volian.Controls.Library/AnnotationDetails.cs @@ -1,16 +1,11 @@ using JR.Utils.GUI.Forms; using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; using System.Diagnostics; -using System.Drawing; -using System.Text; +using System.Linq; using System.Text.RegularExpressions; using System.Windows.Forms; using System.Xml; using VEPROMS.CSLA.Library; -using Volian.Base.Library; using Volian.Pipe.Library; namespace Volian.Controls.Library @@ -64,14 +59,14 @@ namespace Volian.Controls.Library AddAttribute(xe, "Text", myItemInfo.DisplayText); _ProcList.DocumentElement.AppendChild(xe); - if (myItemInfo.Cautions != null) foreach (StepInfo caui in myItemInfo.Cautions) AddItem(myItemInfo.ItemID, caui); - if (myItemInfo.Notes != null) foreach (StepInfo noti in myItemInfo.Notes) AddItem(myItemInfo.ItemID, noti); - if (myItemInfo.RNOs != null) foreach (StepInfo rnoi in myItemInfo.RNOs) AddItem(myItemInfo.ItemID, rnoi); - if (myItemInfo.Sections != null) foreach (SectionInfo seci in myItemInfo.Sections) AddItem(myItemInfo.ItemID, seci); + if (myItemInfo.Cautions != null) foreach (StepInfo caui in myItemInfo.Cautions.OfType()) AddItem(myItemInfo.ItemID, caui); + if (myItemInfo.Notes != null) foreach (StepInfo noti in myItemInfo.Notes.OfType()) AddItem(myItemInfo.ItemID, noti); + if (myItemInfo.RNOs != null) foreach (StepInfo rnoi in myItemInfo.RNOs.OfType()) AddItem(myItemInfo.ItemID, rnoi); + if (myItemInfo.Sections != null) foreach (SectionInfo seci in myItemInfo.Sections.OfType()) AddItem(myItemInfo.ItemID, seci); if (myItemInfo.Steps != null) { if(myItemInfo.IsSection || (myItemInfo.IsHigh && SubStepHasRNOs(myItemInfo.Steps))) - foreach (StepInfo stpi in myItemInfo.Steps) AddItem(myItemInfo.ItemID, stpi); + foreach (StepInfo stpi in myItemInfo.Steps.OfType()) AddItem(myItemInfo.ItemID, stpi); } } } @@ -102,7 +97,6 @@ namespace Volian.Controls.Library { _CurrentItem = value; SetupCurrentItemValues(); - SetupConfigEdit(); // B2017-126 Only turn-on NamedPipe if Command Line parameter /NamedPipe is used. // This eliminates waiting for the Pipe if the command line parameter is not used. if (ExeType > 0 && Volian.Base.Library.VlnSettings.GetCommandFlag("NamedPipe")) SendPromsAnnotationData(); @@ -130,10 +124,7 @@ namespace Volian.Controls.Library if (ai.TypeID == ExeType) return ai; return null; } - private void SetupConfigEdit() - { - //if (ExeType == 0) ; // initialize ExeType - } + private string _ExePath; private string _PipeOut; private string _PipeIn; @@ -256,9 +247,6 @@ namespace Volian.Controls.Library public AnnotationDetails() { InitializeComponent(); -//#if(DEBUG) - //Resize+=new EventHandler(AnnotationDetails_Resize); // Debug the resize event -//#endif Resize += AnnotationDetails_Resize; } @@ -284,17 +272,12 @@ namespace Volian.Controls.Library // CSM B2024-068 / B2024-069 - check if current annotation is not selected before removal of annotation if (CurrentAnnotation != null) { - //using (Annotation annotation = CurrentAnnotation.Get()) - //{ - // annotation.Delete(); _AnnotationSearch.LoadingList = true; Annotation.DeleteAnnotation(CurrentAnnotation); - // annotation.Save(); _AnnotationSearch.LoadingList = false; CurrentAnnotation = null; UpdateAnnotationGrid(); _AnnotationSearch.UpdateAnnotationSearchResults(); // B2019-004: update search results list when an annotation is removed. - //} } else { @@ -425,14 +408,6 @@ namespace Volian.Controls.Library } } - private void CheckClientProcess() - { - if (ClientProcess.HasExited) - { - ClientProcess = null; - StartClientProcess(); - } - } void ClientProcess_Exited(object sender, EventArgs e) { ClientProcess = null; @@ -477,7 +452,6 @@ namespace Volian.Controls.Library { XmlDocument xdConfig = new XmlDocument(); xdConfig.LoadXml(ai.Config); - ProcedureInfo currentProc = CurrentItem.MyProcedure; XmlNode nd = xdMessage.DocumentElement.SelectSingleNode("//PromsAnnotationConfig"); nd.AppendChild(xdMessage.ImportNode(xdConfig.DocumentElement, true)); } @@ -595,7 +569,7 @@ namespace Volian.Controls.Library } private XmlNode GetNode(XmlDocument xd, string nodeName) { - return xd.DocumentElement.SelectSingleNode("//" + nodeName); + return xd.DocumentElement.SelectSingleNode($"//{nodeName}"); } private string GetAttribute(XmlDocument xd, string nodeName, string attrName) { @@ -670,8 +644,8 @@ namespace Volian.Controls.Library if (!_LoadingGrid && (dgAnnotations.FirstDisplayedScrollingRowIndex != -1)) dgAnnotations.FirstDisplayedScrollingRowIndex = row; } - catch (Exception ex) - { + catch (Exception) + { _MyLog.InfoFormat("Trying to open an annotation which has been removed"); } } @@ -692,8 +666,6 @@ namespace Volian.Controls.Library using (Annotation annotation = Annotation.MakeAnnotation(myItem, annotationType, rtxbComment.Rtf, rtxbComment.Text, "")) { CurrentAnnotation = AnnotationInfo.Get(annotation.AnnotationID); - //annotation.DTS = DateTime.Now; - //annotation.Save(); } } } @@ -724,7 +696,7 @@ namespace Volian.Controls.Library private void btnEPAnnotation_Click(object sender, EventArgs e) { frmEPAnnotationDetails EPfrm = new frmEPAnnotationDetails(CurrentAnnotation); - DialogResult dr = EPfrm.ShowDialog(this); - } + _ = EPfrm.ShowDialog(this); + } } } diff --git a/PROMS/Volian.Controls.Library/BorderListBox.cs b/PROMS/Volian.Controls.Library/BorderListBox.cs index 72f0a1d6..7e1bc722 100644 --- a/PROMS/Volian.Controls.Library/BorderListBox.cs +++ b/PROMS/Volian.Controls.Library/BorderListBox.cs @@ -1,8 +1,5 @@ using System; using System.ComponentModel; -using System.Collections.Generic; -using System.Diagnostics; -using System.Text; using System.Drawing; using System.Windows.Forms; @@ -10,19 +7,11 @@ namespace Volian.Controls.Library { public partial class BorderListBox : ListBox { - #region Properties - public GridLinePattern SelectedLinePattern - { - get { return (Items[SelectedIndex] as GridLBItem).LinePattern; } - } - #endregion - #region ctor - public BorderListBox() - { - InitializeComponent(); - SetupOptions(); - } - public BorderListBox(IContainer container) + #region Properties + public GridLinePattern SelectedLinePattern => (Items[SelectedIndex] as GridLBItem).LinePattern; + #endregion + #region ctor + public BorderListBox(IContainer container) { container.Add(this); InitializeComponent(); @@ -31,9 +20,7 @@ namespace Volian.Controls.Library private void SetupOptions() { this.DrawMode = DrawMode.OwnerDrawFixed; - //this.Font.Size; DrawItem += new DrawItemEventHandler(BorderListBox_DrawItem); - //MeasureItem += new MeasureItemEventHandler(BorderListBox_MeasureItem); Items.Add(new GridLBItem(GridLinePattern.None)); Items.Add(new GridLBItem(GridLinePattern.Single)); Items.Add(new GridLBItem(GridLinePattern.Double)); @@ -55,10 +42,6 @@ namespace Volian.Controls.Library } #endregion #region Event Handlers - //void BorderListBox_MeasureItem(object sender, MeasureItemEventArgs e) - //{ - // e.ItemHeight = 22; - //} private int _MaxLabelWidth = 0; private int MaxLabelWidth(Graphics gr) { @@ -102,25 +85,14 @@ namespace Volian.Controls.Library } public class GridLBItem { - #region Properties - private GridLinePattern _LinePattern; - public GridLinePattern LinePattern - { - get { return _LinePattern; } - set { _LinePattern = value; } - } - #endregion - #region ctor - public GridLBItem(GridLinePattern linePattern) - { - LinePattern = linePattern; - } - #endregion - #region Public Methods - public override string ToString() - { - return LinePattern.ToString(); - } - #endregion - } + #region Properties + public GridLinePattern LinePattern { get; set; } + #endregion + #region ctor + public GridLBItem(GridLinePattern linePattern) => LinePattern = linePattern; + #endregion + #region Public Methods + public override string ToString() => LinePattern.ToString(); + #endregion + } } diff --git a/PROMS/Volian.Controls.Library/BorderSelectionPanel.cs b/PROMS/Volian.Controls.Library/BorderSelectionPanel.cs index 85378e83..3ff763db 100644 --- a/PROMS/Volian.Controls.Library/BorderSelectionPanel.cs +++ b/PROMS/Volian.Controls.Library/BorderSelectionPanel.cs @@ -1,8 +1,5 @@ using System; using System.ComponentModel; -using System.Collections.Generic; -using System.Diagnostics; -using System.Text; using System.Windows.Forms; using System.Drawing; using C1.Win.C1FlexGrid; @@ -16,8 +13,8 @@ namespace Volian.Controls.Library public event BorderSelectionPanelEvent BordersChanged; private void OnBordersChanged(object sender, EventArgs args) { - if (BordersChanged != null) BordersChanged(sender, args); - } + BordersChanged?.Invoke(sender, args); + } #endregion #region Properties private bool _HasRows = true; @@ -155,8 +152,6 @@ namespace Volian.Controls.Library } public void InitializeBorder(VlnFlexGrid myFlexGrid, CellRange myRange) { - //if (myRange.r1 == 0 && myRange.c1 == 0 && myRange.r2 == 2 && myRange.c2 == 2) - //Console.WriteLine("here"); _TopBorder = GridLinePattern.Unknown; _InsideHorizontalBorder = GridLinePattern.Unknown; _BottomBorder = GridLinePattern.Unknown; @@ -249,18 +244,11 @@ namespace Volian.Controls.Library DrawBackground(e, x1, y1, x2, y2, w1, h1, w2, h2, offset, HasRows, HasColumns); DrawBorder(e, x1, y1, x2, y2); } - private static void DrawBackground(PaintEventArgs e, int x1, int y1, int x2, int y2, int w1, int h1, int w2, int h2, int offset,bool hasRows, bool hasColumns) - { +#pragma warning disable IDE0060 // Remove unused parameter + private static void DrawBackground(PaintEventArgs e, int x1, int y1, int x2, int y2, int w1, int h1, int w2, int h2, int offset,bool hasRows, bool hasColumns) +#pragma warning restore IDE0060 // Remove unused parameter + { e.Graphics.FillRectangle(Brushes.White, offset, offset, w2 - 2* offset, h2 - 2* offset); - // Old Backgound - Shows corners - //e.Graphics.DrawLine(Pens.LightBlue, x1, offset, x1, y1); - //e.Graphics.DrawLine(Pens.LightBlue, x2, offset, x2, y1); - //e.Graphics.DrawLine(Pens.LightBlue, x1, y2, x1, h2 - offset); - //e.Graphics.DrawLine(Pens.LightBlue, x2, y2, x2, h2 - offset); - //e.Graphics.DrawLine(Pens.LightBlue, offset, y1, x1, y1); - //e.Graphics.DrawLine(Pens.LightBlue, x2, y1, w2 - offset, y1); - //e.Graphics.DrawLine(Pens.LightBlue, offset, y2, x1, y2); - //e.Graphics.DrawLine(Pens.LightBlue, x2, y2, w2 - offset, y2); // Horizontal Lines e.Graphics.DrawLine(Pens.LightBlue, offset, y1, w2 - offset, y1); if (hasRows) e.Graphics.DrawLine(Pens.LightBlue, x1 + offset, (y1 + y2) / 2, x2 - offset , (y1 + y2) / 2); @@ -287,8 +275,8 @@ namespace Volian.Controls.Library if (LineWidth(linePattern) == 3) { dxo2 = dxo1 = -1; - dyi2 = dyo1 = LineWidth(startPattern) == 3 ? -1 : 0; - dyi1 =dyo2 = LineWidth(endPattern) == 3 ? 1 : 0; + dyo1 = LineWidth(startPattern) == 3 ? -1 : 0; + dyo2 = LineWidth(endPattern) == 3 ? 1 : 0; dxi1 = -dxo1; dxi2 = -dxo2; dyi1 = -dyo1; dyi2 = -dyo2; if (linePattern == GridLinePattern.Thick) dyo2++; // Fix for bug in Graphics. Seems to happen when line is thick. } @@ -303,8 +291,8 @@ namespace Volian.Controls.Library if (LineWidth(linePattern) == 3) { dyo2 = dyo1 = 1; - dxi2 = dxo1 = LineWidth(startPattern) == 3 ? -1 : 0; - dxi1 = dxo2 = LineWidth(endPattern) == 3 ? 1 : 0; + dxo1 = LineWidth(startPattern) == 3 ? -1 : 0; + dxo2 = LineWidth(endPattern) == 3 ? 1 : 0; dxi1 = -dxo1;dxi2 = -dxo2;dyi1 = -dyo1;dyi2 = -dyo2; if (linePattern == GridLinePattern.Thick) dxo2++; // Fix for bug in Graphics. Seems to happen when line is thick. } @@ -347,7 +335,7 @@ namespace Volian.Controls.Library { if (linePattern == GridLinePattern.None) return; int dyi1 = 0; int dyi2 = 0; int dxi1 = 0; int dxi2 = 0; - int dyo1 = 0; int dyo2 = 0; int dxo1 = 0; int dxo2 = 0; + int dyo1; int dyo2; int dxo1 = 0; int dxo2 = 0; if (LineWidth(linePattern) == 3) { dxo2 = dxo1 = 1; @@ -368,7 +356,7 @@ namespace Volian.Controls.Library { if (linePattern == GridLinePattern.None) return; int dyi1 = 0; int dyi2 = 0; int dxi1 = 0; int dxi2 = 0; - int dyo1 = 0; int dyo2 = 0; int dxo1 = 0; int dxo2 = 0; + int dyo1 = 0; int dyo2 = 0; int dxo1; int dxo2; if (LineWidth(linePattern) == 3) { dyo2 = dyo1 = -1; diff --git a/PROMS/Volian.Controls.Library/ConvertTable.cs b/PROMS/Volian.Controls.Library/ConvertTable.cs index c11a5530..59949954 100644 --- a/PROMS/Volian.Controls.Library/ConvertTable.cs +++ b/PROMS/Volian.Controls.Library/ConvertTable.cs @@ -1,33 +1,24 @@ using C1.Win.C1FlexGrid; using System; -using System.Collections.Generic; using System.Drawing; -using System.Linq; using System.Text; using System.Text.RegularExpressions; -using System.Threading.Tasks; using System.Windows.Forms; using System.Xml; -using VEPROMS.CSLA.Library; -using Volian.Controls.Library; namespace Volian.Controls.Library { public partial class frmImportWordContents : Form - { - private static string GetTableText() - { - return TblFlexGrid.GetSearchableText(); - } - private static VlnFlexGrid _TblFlexGrid = null; + { + private static VlnFlexGrid _TblFlexGrid = null; public static VlnFlexGrid TblFlexGrid { get { if (_TblFlexGrid == null) _TblFlexGrid = new VlnFlexGrid(); - return frmImportWordContents._TblFlexGrid; + return _TblFlexGrid; } - set { frmImportWordContents._TblFlexGrid = value; } + set { _TblFlexGrid = value; } } private static void LoadTable2(XmlNode xn) @@ -54,15 +45,7 @@ namespace Volian.Controls.Library fg.BringToFront(); fg.Invalidate(); Application.DoEvents(); - //ShowColumnWidths(fg); fg.MakeRTFcells(false); - //ShowMergedCells(fg); - //ShowColumnWidths(fg); - //Well, Can I save the table - //using (Step step = MakeCSLAStep(mySteps, mySteps.Count, null, {TableContent}, 20008, E_FromType.Table)) - //{ - // Grid.MakeGrid(step.MyContent, fg.GetXMLData(), ""); - //} } public static VlnFlexGrid _MyFlexGrid = null; private static void AddTableRow(XmlNode xr, VlnFlexGrid fg, int rows) @@ -73,14 +56,7 @@ namespace Volian.Controls.Library foreach (XmlNode xc in xr.ChildNodes) { ++cols; - //if (xc.InnerText.Contains("RC-V200")) - // Console.WriteLine(xc.InnerText); - //if (xc.InnerText.Contains("RC-V121")) - // Console.WriteLine(xc.InnerText); - //if (xc.InnerXml.Contains("AB 137") || xc.InnerXml.Contains("3013N01")) - // Console.WriteLine("here"); CellRange cr2 = GetMyMergedRange(fg, rows - 1, cols - 1); - //Console.WriteLine("Check {0}", cr2); while (cr2.c1 != cols - 1 || cr2.r1 != rows - 1) { cols++; @@ -123,7 +99,6 @@ namespace Volian.Controls.Library break; } } - //ShowMergedCells(fg); if (xc.Name == "td") { AddTableColumn(xc, fg, rows, cols); @@ -131,26 +106,9 @@ namespace Volian.Controls.Library } } - //private static void ShowColumnWidths(VlnFlexGrid fg) - //{ - // foreach (Column c in fg.Cols) - // Console.WriteLine("Width[{0}]={1}", c.Index, c.Width); - //} - private static void ShowMergedCells(VlnFlexGrid fg) + private static int GetSpan(string span) { - for (int r = 0; r < fg.Rows.Count; r++) - { - for (int c = 0; c < fg.Cols.Count; c++) - { - CellRange cr3 = GetMyMergedRange(fg, r, c); - if (fg.MergedRanges.Contains(cr3)) - Console.WriteLine("cr3 r={0},c={1},rng={2}", r, c, cr3); - } - } - } - private static int GetSpan(string span) - { - int retval = int.Parse("0" + (span ?? "")); + int retval = int.Parse($"0{span ?? ""}"); if (retval == 0) return 0; return retval - 1; } @@ -175,12 +133,14 @@ namespace Volian.Controls.Library if (r2 > fg.Rows.Count) fg.Rows.Count = r2; int c2 = c1 + GetSpan(colspan); if (c2 > fg.Cols.Count) fg.Cols.Count = c2; - CellRange cr = new CellRange(); - cr.r1 = r1 - 1; - cr.r2 = r2 - 1; - cr.c1 = c1 - 1; - cr.c2 = c2 - 1; - fg.MergedRanges.Add(cr); + CellRange cr = new CellRange + { + r1 = r1 - 1, + r2 = r2 - 1, + c1 = c1 - 1, + c2 = c2 - 1 + }; + fg.MergedRanges.Add(cr); //Console.WriteLine("Merged {0}", cr); } } @@ -194,7 +154,7 @@ namespace Volian.Controls.Library } return fg.GetMergedRange(r, c); } - private static Regex regNumber = new Regex("^[0-9]+$", RegexOptions.Compiled); + private static readonly Regex regNumber = new Regex("^[0-9]+$", RegexOptions.Compiled); private static void AddTableColumn(XmlNode xc, VlnFlexGrid fg, int rows, int cols) { //Console.WriteLine("Rows {0}, Cols {1}", rows, cols); @@ -218,7 +178,7 @@ namespace Volian.Controls.Library { if (xn.Name == "p") { - sb.Append(prefix + xn.InnerText); + sb.Append($"{prefix}{xn.InnerText}"); } if (xn.Name == "ul") { @@ -226,11 +186,11 @@ namespace Volian.Controls.Library { if (xn2.Name == "li") { - sb.Append(prefix + "*" + xn.InnerText); + sb.Append($"{prefix}*{xn.InnerText}"); } if (xn2.Name == "p") { - sb.Append(prefix + xn.InnerText); + sb.Append($"{prefix}{xn.InnerText}"); } } } diff --git a/PROMS/Volian.Controls.Library/CustomMessageBox.cs b/PROMS/Volian.Controls.Library/CustomMessageBox.cs index a16a59d1..70a521bd 100644 --- a/PROMS/Volian.Controls.Library/CustomMessageBox.cs +++ b/PROMS/Volian.Controls.Library/CustomMessageBox.cs @@ -1,11 +1,4 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using System.Windows.Forms; namespace Volian.Controls.Library diff --git a/PROMS/Volian.Controls.Library/DSOTabPanel.cs b/PROMS/Volian.Controls.Library/DSOTabPanel.cs index a97e038a..9fe40cd0 100644 --- a/PROMS/Volian.Controls.Library/DSOTabPanel.cs +++ b/PROMS/Volian.Controls.Library/DSOTabPanel.cs @@ -1,12 +1,7 @@ using System; -using System.ComponentModel; -using System.Collections.Generic; -using System.Diagnostics; using System.Text; -using System.Drawing; using System.Windows.Forms; using VEPROMS.CSLA.Library; -using Volian.Controls.Library; using System.Reflection; using LBWordLibrary; using JR.Utils.GUI.Forms; @@ -17,7 +12,7 @@ namespace Volian.Controls.Library public partial class DSOTabPanel : DevComponents.DotNetBar.PanelDockContainer { #region Private Fields - private DisplayTabControl _MyDisplayTabControl; + private readonly DisplayTabControl _MyDisplayTabControl; private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private AxEDWordLib.AxEDWord _MyEdWord; // B2017-133 Edraw DSO Framer Replacement public AxEDWordLib.AxEDWord MyEdWord @@ -26,9 +21,7 @@ namespace Volian.Controls.Library set { _MyEdWord = value; } } private TransparentPanel _MyTransparentPanel; - private static int _Count = 0; - private DocumentInfo _MyDocumentInfo; - private int _MyCount; + private readonly DocumentInfo _MyDocumentInfo; private DisplayTabItem _MyDisplayTabItem; private DSOFile _DSOFile; public static int MSWordLimit = 10; @@ -43,11 +36,7 @@ namespace Volian.Controls.Library /// /// Count of DSO Pages open. Limited to 18 in DisplayTabControl /// - public static int Count - { - get { return _Count; } - set { _Count = value; } - } + public static int Count { get; set; } = 0; /// /// Pointer to the related DisplayTabItem /// @@ -90,23 +79,17 @@ namespace Volian.Controls.Library if (_MyEdWord == null) return false; // B2017-133 Edraw Is Dirty Property // B2017-249 Recover Temporary File And AutoSave support for MSWord return _MyEdWord.IsDirty() || MyDSOFile.ContentIsDirty; - //LBDocumentClass doc = new LBDocumentClass(_MyEdWord.ActiveDocument()); - //return !doc.Saved; } } - private bool _OverrideClose = false; - public bool OverrideClose - { - get { return _OverrideClose; } - set { _OverrideClose = value; } - } + + public bool OverrideClose { get; set; } = false; public E_ViewMode PanelViewEditMode = E_ViewMode.Edit; #endregion //private frmPG _frm = null; #region Constructors - private Timer _RefreshTimer; - private ItemInfo _ItemInfo; - private bool _AllowedToEdit; + private readonly Timer _RefreshTimer; + private readonly ItemInfo _ItemInfo; + private readonly bool _AllowedToEdit; public DSOTabPanel(DocumentInfo documentInfo, DisplayTabControl myDisplayTabControl, ItemInfo itemInfo, bool allowedToEdit) { _MyDisplayTabControl = myDisplayTabControl; @@ -117,8 +100,10 @@ namespace Volian.Controls.Library _MyDocumentInfo = documentInfo; SetupDSO(); if (_MyEdWord == null) return; //B2017-219 could not open the word attachment so just return - _RefreshTimer = new Timer(); // Enabled is false and interval is 1/10th of second. - _RefreshTimer.Interval = 500;// B2017-133 Edraw + _RefreshTimer = new Timer + { + Interval = 500// B2017-133 Edraw + }; // Enabled is false and interval is 1/10th of second. ClientSizeChanged += new EventHandler(DSOTabPanel_ClientSizeChanged); _RefreshTimer.Tick += new EventHandler(_RefreshTimer_Tick); // B2018-070 Activate MS Word Panel @@ -145,21 +130,14 @@ namespace Volian.Controls.Library _MyEdWord.DisablePrintHotKey(true); } // B2019-161 When tracking timing time this action - private static VolianTimer _TimeActivity = new VolianTimer("DSOTabPanel.cs _RefreshTimer_Tick", 148); + private static readonly VolianTimer _TimeActivity = new VolianTimer("DSOTabPanel.cs _RefreshTimer_Tick", 148); void _RefreshTimer_Tick(object sender, EventArgs e) { _TimeActivity.Open(); _RefreshTimer.Enabled = false; - if (_MyEdWord != null)// B2017-133 Edraw - { - // B2018-070 Activate MS Word Panel - _MyEdWord.GotoItem(EDWordLib.WdGoToItem.wdGoToObject, EDWordLib.WdGoToDirection.wdGoToNext, 0, null); - } - //else - //{ - // _MyDisplayTabControl.CloseTabItem(_MyDisplayTabItem); - //} + // B2018-070 Activate MS Word Panel + _MyEdWord?.GotoItem(EDWordLib.WdGoToItem.wdGoToObject, EDWordLib.WdGoToDirection.wdGoToNext, 0, null); _TimeActivity.Close(); } @@ -180,8 +158,7 @@ namespace Volian.Controls.Library } private void SetupDSO() { - _Count++; // Increment the count of open Word documents (Limit = MSWordLimit) - _MyCount = _Count; + Count++; // Increment the count of open Word documents (Limit = MSWordLimit) this._MyTransparentPanel = new TransparentPanel(); this._MyEdWord = new AxEDWordLib.AxEDWord();// B2017-133 Edraw _MyEdWord.BeginInit(); @@ -195,14 +172,8 @@ namespace Volian.Controls.Library this._MyTransparentPanel.Font = new System.Drawing.Font("Tahoma", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this._MyTransparentPanel.ForeColor = System.Drawing.Color.Brown; // This is the color used to show InActive on the right side on the Word // document menu line. - //this._MyTransPanel.Location = new System.Drawing.Point(0, 0); - //this._MyTransPanel.Name = "transPanel1"; - //this._MyTransPanel.Size = new System.Drawing.Size(370, 423); - //this._MyTransPanel.TabIndex = 1; this._MyTransparentPanel.Click += new EventHandler(_MyTransparentPanel_Click); this._MyEdWord.Dock = System.Windows.Forms.DockStyle.Fill; - //System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(WordDSOTab)); - //this._DSOFramer.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("_FC.OcxState"))); _MyEdWord.EndInit(); LBDocumentClass doc; try @@ -215,18 +186,13 @@ namespace Volian.Controls.Library this._MyEdWord.Open(MyDSOFile.MyFile.FullName); doc = new LBDocumentClass(_MyEdWord.ActiveDocument()); } - catch (Exception ex) + catch (Exception) { // B2017-137 Restore Previous valid version if the current version cannot be opened, using (DocumentAuditInfoList dail = DocumentAuditInfoList.Get(MyDocumentInfo.DocID)) { if (dail.Count > 0) { - //DocumentAuditInfo dai = dail[0]; - //foreach (DocumentAuditInfo tmpa in dail) - //{ - // if (tmpa.DTS > dai.DTS) dai = tmpa; - //} if (MessageBox.Show("Do you want to revert to a previous version?", "Error in MS Word section", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { @@ -242,12 +208,6 @@ namespace Volian.Controls.Library MyDSOFile.SaveFile(0, "", _ItemInfo, false, StatusChanged); // B2017-219 save the restored document to database this._MyEdWord = null; // B2017-219 Set MyEdWord to null - we will check for this in the calling functions return; - //_MyDocumentInfo = DocumentInfo.Get(MyDocumentInfo.DocID); - //DocumentInfo.Refresh(myDoc); - ////_DSOFile = null; - //this._MyEdWord.Open(MyDSOFile.MyFile.FullName); - //doc = new LBDocumentClass(_MyEdWord.ActiveDocument()); - //doc.Range(1, 1); } } @@ -267,19 +227,16 @@ namespace Volian.Controls.Library } doc = new LBDocumentClass(_MyEdWord.ActiveDocument()); //Console.WriteLine("Version {0}", doc.Application.Version); - float ver; - if (!float.TryParse(doc.Application.Version, out ver)) + if (!float.TryParse(doc.Application.Version, out float ver)) ver = 12.0F; this.Enter += new EventHandler(DSOTabPanel_Enter); // B2018-070 Use InDSOTabPanel to determine if the word panel should be activated - Activate MS Word Panel this.Leave += DSOTabPanel_Leave; Application.DoEvents(); - // The following line corrects Symbol characters in MSWord Sections - // CheckForSymbolCharacters(doc); InitializeWordDocument(doc); FindSearchString(); } - catch (Exception ex) + catch (Exception) { //string message = ShowException(ex); //Console.WriteLine("\r\n-------------\r\n{0}{1}{2}\r\n-------------\r\n", MyDSOFile.MyFile.FullName, ex.GetType().Name, message); @@ -301,8 +258,6 @@ namespace Volian.Controls.Library DocStyle ds = MyDocumentInfo.DocumentEntries[0].MyContent.ContentItems[0].MyDocStyle; // this will cause an error and goto the Catch if the family or size is null, // Westinghouse needs it to to this - at least for now - //if (ds.Font.Family != null) doc.Application.Selection.Font.Name = ds.Font.Family; - //if (ds.Font.Size != null) doc.Application.Selection.Font.Size = (float)ds.Font.Size; doc.Application.Selection.Font.Name = ds.Font.Family; doc.Application.Selection.Font.Size = (float)ds.Font.Size; doc.Application.Selection.ParagraphFormat.SpaceBefore = 0; @@ -314,12 +269,12 @@ namespace Volian.Controls.Library if (doc.ActiveWindow.ActivePane.View.Zoom.Percentage < 40) doc.ActiveWindow.ActivePane.View.Zoom.Percentage = 100; } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0059:Unnecessary assignment of a value", Justification = "found set for debugging purposes")] public void FindSearchString() { if (SearchString == null) return; // Get the Document LBDocumentClass wordDoc = new LBDocumentClass(_MyEdWord.ActiveDocument()); - //LBSelection sel = wordDoc.Application.Selection; LBFind find = wordDoc.Application.Selection.Find; find.ClearFormatting(); bool wildCards = SearchString.Contains("?") || SearchString.Contains("*"); @@ -350,51 +305,10 @@ namespace Volian.Controls.Library if (sel.Start == sel.End) return null; return sel.Text; } - - private string ShowException(Exception ex) - { - string sep = "\r\n "; - StringBuilder sb = new StringBuilder(); - do - { - sb.Append(sep + ex.Message); - sep += " "; - ex = ex.InnerException; - } while (ex != null); - return sb.ToString(); - } - - //void _MyDSOFramer_Leave(object sender, EventArgs e) - //{ - // vlnStackTrace.ShowStack("DSO Leave {0}", this.MyDocumentInfo.DocID); - //} - - //void _MyDSOFramer_Enter(object sender, EventArgs e) - //{ - // vlnStackTrace.ShowStack("DSO Enter {0}", this.MyDocumentInfo.DocID); - //} - - //void _MyDSOFramer_GotFocus(object sender, EventArgs e) - //{ - // vlnStackTrace.ShowStack("DSO Got Focus {0}",this.MyDocumentInfo.DocID); - //} - - //void _MyDSOFramer_LostFocus(object sender, EventArgs e) - //{ - // vlnStackTrace.ShowStack("DSO Lost Focus {0}", this.MyDocumentInfo.DocID); - //} public void EnterPanel() { DSOTabPanel_Enter(this, new EventArgs()); } - //void DSOTabPanel_LostFocus(object sender, EventArgs e) - //{ - // vlnStackTrace.ShowStack("DSOTabPanel_LostFocus {0} DocID {1} Index {2} {3}", _In_DSOTabPanel_Enter, this._MyDocumentInfo.DocID, _MyDisplayTabControl.MyBar.SelectedDockTab, sender.GetType().FullName); - //} - //void DSOTabPanel_GotFocus(object sender, EventArgs e) - //{ - // vlnStackTrace.ShowStack("DSOTabPanel_GotFocus {0} DocID {1} Index {2} {3}", _In_DSOTabPanel_Enter, this._MyDocumentInfo.DocID, _MyDisplayTabControl.MyBar.SelectedDockTab, sender.GetType().FullName); - //} #endregion #region Event Handlers /// @@ -415,29 +329,16 @@ namespace Volian.Controls.Library { this.Select(); } - ///// - ///// If the user presses the save button, tell the file to save it's contents to the database - ///// - ///// - ///// - //void _MyDSOFramer_OnSaveCompleted(object sender, AxDSOFramer._DFramerCtlEvents_OnSaveCompletedEvent e) - //{ - // _MyLog.WarnFormat("_MyDSOFramer_OnSaveCompleted"); - // Volian.Base.Library.vlnStackTrace.ShowStack("_MyDSOFramer_OnSaveCompleted"); - // SaveDSO_Phase2(); - //} private void SaveDSO_Phase2() { // Unfortunately, the only way to handle view mode for DSO Framer is to not save. if (PanelViewEditMode == E_ViewMode.View) { - MessageBox.Show("Currently in VIEW mode,\r\n cannot Save " + _MyDisplayTabItem.Tooltip); + MessageBox.Show($"Currently in VIEW mode,\r\n cannot Save {_MyDisplayTabItem.Tooltip}"); return; } LBDocumentClass doc = new LBDocumentClass(_MyEdWord.ActiveDocument()); - //while (doc.Saved = false) - // Application.DoEvents(); string tmp = GetReflectiveProperty(_MyEdWord.ActiveDocument(), "FullName"); if (System.IO.File.Exists(tmp)) MyDSOFile.FullName = tmp; @@ -451,10 +352,7 @@ namespace Volian.Controls.Library if (myei != null && myei.MyDocument != null && myei.MyDocument.LibTitle != null && myei.MyDocument.LibTitle != "") { // C2019-033 - make save options more clear with respect to library documents - string msgstr = "Save to Library Document?" + - "\n\n YES - Save for all usages of this Library Document." + - "\n\n NO - Unlink this Section from the Library Document and Save in this Word Section.\n\n" + - _MyDocumentInfo.LibraryDocumentUsageAll; + string msgstr = $"Save to Library Document?\n\n YES - Save for all usages of this Library Document.\n\n NO - Unlink this Section from the Library Document and Save in this Word Section.\n\n{_MyDocumentInfo.LibraryDocumentUsageAll}"; DialogResult ans = FlexibleMessageBox.Show(msgstr, "Document Save", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (ans == DialogResult.No) cvtLibDoc = true; } @@ -475,16 +373,6 @@ namespace Volian.Controls.Library tc.ONStatusChanged(this, new DisplayTabControlStatusEventArgs(type, count, text)); } } - ///// - ///// Before a document closes check to see if it's contents should be saved. - ///// - ///// - ///// - //void _MyDSOFramer_BeforeDocumentClosed(object sender, AxDSOFramer._DFramerCtlEvents_BeforeDocumentClosedEvent e) - //{ - // SaveDSOPhase1(); - //} - private void SaveDSO_Phase1() { try @@ -494,7 +382,6 @@ namespace Volian.Controls.Library this.Enter -= new EventHandler(DSOTabPanel_Enter); // B2018-070 Use InDSOTabPanel to determine if the word panel should be activated - Activate MS Word Panel this.Leave -= DSOTabPanel_Leave; - // SaveDirty(); // SaveDirty happens in CloseDSO(bool) } catch (Exception ex) { @@ -514,11 +401,6 @@ namespace Volian.Controls.Library bool stat = _MyEdWord.Save();// B2017-133 Edraw //Console.WriteLine("Save = {0}", stat); SaveDSO_Phase2(); - //_MyDSOFramer_OnSaveCompleted(this, null); - // These are handled in the method above - //LBDocumentClass doc = new LBDocumentClass(_MyDSOFramer.ActiveDocument); - //MyDSOFile.FullName = GetReflectiveProperty(_MyDSOFramer.ActiveDocument, "FullName"); - //MyDSOFile.SaveFile(doc.Length, doc.Ascii); } catch (Exception ex) { @@ -543,13 +425,12 @@ namespace Volian.Controls.Library // Unfortunately, the only way to handle view mode for DSO Framer is to not save. if (PanelViewEditMode == E_ViewMode.View || !_AllowedToEdit) { - MessageBox.Show("Currently in VIEW mode,\r\n cannot Save " + _MyDisplayTabItem.Tooltip); + MessageBox.Show($"Currently in VIEW mode,\r\n cannot Save {_MyDisplayTabItem.Tooltip}"); return false; } - //if (MessageBox.Show("Save changes to " + _MyDisplayTabItem.MyItemInfo.TabTitle + "\r\n" + _MyDisplayTabItem.MyItemInfo.TabToolTip, "Document has Changed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) // B2017-249 Recover Temporary File And AutoSave support for MSWord // C2019-033 - make save options more clear with respect to library documents second dialog will appear if Yes is selected and it's a library document - string msgstr = "Save changes to " + (MyDSOFile.MyDocument.ContentIsDirty ? "Recovered Version of " : "") + _MyDisplayTabItem.Text; + string msgstr = $"Save changes to {(MyDSOFile.MyDocument.ContentIsDirty ? "Recovered Version of " : "")}{_MyDisplayTabItem.Text}"; if (FlexibleMessageBox.Show(msgstr, (IsDirty ? "Document has Changed" : "Previous Changes were not Saved"), MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) return SaveDSO(); //Console.WriteLine("Delete {0}", MyDSOFile.MyFile.Name); @@ -595,15 +476,6 @@ namespace Volian.Controls.Library StepTabPanel stpanel = _MyDisplayTabControl.GetProcedureTabPanel(MyDisplayTabItem.MyItemInfo); PanelViewEditMode = (stpanel == null) ? E_ViewMode.Edit : stpanel.MyStepPanel.VwMode; } - try - { - //_MyDSOFramer.EventsEnabled = true; - //_MyEdWord.FrameHookPolicy = DSOFramer.dsoFrameHookPolicy.dsoResetNow; - } - catch (Exception ex) - { - if (_MyLog.IsErrorEnabled) _MyLog.ErrorFormat("DSOTabPage_Enter", ex); - } if (_In_DSOTabPanel_Enter) return; //vlnStackTrace.ShowStack("DSOTabPanel_Enter {0} DocID {1} Index {2} {3}",_In_DSOTabPanel_Enter, this._MyDocumentInfo.DocID, _MyDisplayTabControl.MyBar.SelectedDockTab, sender.GetType().FullName); _In_DSOTabPanel_Enter = true; @@ -628,15 +500,6 @@ namespace Volian.Controls.Library /// /// public bool CloseDSO() - { - return CloseDSO(false); - } - /// - /// Cleans-up the DSO Framer window - /// - /// - /// - public bool CloseDSO(bool force) { _MyLog.Debug("CloseDSO"); bool result = true; @@ -652,38 +515,21 @@ namespace Volian.Controls.Library _MyEdWord = null; // B2017-249 Recover Temporary File And AutoSave support for MSWord if (DeleteOnClose) MyDSOFile.MyFile.Delete(); - _Count--; + Count--; } } catch (Exception ex) { - if (_MyLog.IsErrorEnabled) _MyLog.Error("SaveDSO - " + this.Name, ex); + if (_MyLog.IsErrorEnabled) _MyLog.Error($"SaveDSO - {this.Name}", ex); result = false; } return result; } - /// - /// Activates the current DSO Framer window (Word) - /// - public void Activate() - { - try - { - //this._MyEdWord.Activate(); - //if (_MyCount <= MSWordLimit) - // this._MyEdWord.FrameHookPolicy = DSOFramer.dsoFrameHookPolicy.dsoResetNow; - } - catch (Exception ex) - { - if (_MyLog.IsErrorEnabled) _MyLog.Error("Activate", ex); - } - } #endregion #region DocumentProperties private string GetReflectiveProperty(object objectToInspect, string propertyName) { - string returnString = ""; //To use reflection on an object, you // first need to get an instance // of that object's type. diff --git a/PROMS/Volian.Controls.Library/DisplayApplicability.cs b/PROMS/Volian.Controls.Library/DisplayApplicability.cs index e9b68be0..a89f7ff7 100644 --- a/PROMS/Volian.Controls.Library/DisplayApplicability.cs +++ b/PROMS/Volian.Controls.Library/DisplayApplicability.cs @@ -1,8 +1,6 @@ using JR.Utils.GUI.Forms; -using log4net.Util; using System; using System.Collections.Generic; -using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; @@ -18,9 +16,8 @@ namespace Volian.Controls.Library public event DisplayApplicabilityEvent ApplicabilityViewModeChanged; private void OnApplicabilityViewModeChanged() { - if (ApplicabilityViewModeChanged != null) - ApplicabilityViewModeChanged(this, new EventArgs()); - } + ApplicabilityViewModeChanged?.Invoke(this, new EventArgs()); + } private DisplayTabItem _MyDisplayTabItem = null; public DisplayTabItem MyDisplayTabItem @@ -93,21 +90,21 @@ namespace Volian.Controls.Library private DevComponents.DotNetBar.Controls.GroupPanel InitializegpSubItem() //B2026-043 Fix "Set All At Level" button. { DevComponents.DotNetBar.Controls.GroupPanel gpSubItem; - gpSubItem = new DevComponents.DotNetBar.Controls.GroupPanel - { - AutoSize = true, - AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink, - CanvasColor = System.Drawing.SystemColors.Control, - ColorSchemeStyle = DevComponents.DotNetBar.eDotNetBarStyle.Office2007, - DisabledBackColor = System.Drawing.Color.Empty, - Dock = System.Windows.Forms.DockStyle.Top, - Location = new System.Drawing.Point(0, 49), - Margin = new System.Windows.Forms.Padding(4), - Name = "gpSubItem", - Padding = new System.Windows.Forms.Padding(13, 12, 13, 37) - }; - gpSubItem.BackColor = Color.Transparent; - gpSubItem.Style.TextAlignment = DevComponents.DotNetBar.eStyleTextAlignment.Center; + gpSubItem = new DevComponents.DotNetBar.Controls.GroupPanel + { + AutoSize = true, + AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink, + CanvasColor = System.Drawing.SystemColors.Control, + ColorSchemeStyle = DevComponents.DotNetBar.eDotNetBarStyle.Office2007, + DisabledBackColor = System.Drawing.Color.Empty, + Dock = System.Windows.Forms.DockStyle.Top, + Location = new System.Drawing.Point(0, 49), + Margin = new System.Windows.Forms.Padding(4), + Name = "gpSubItem", + Padding = new System.Windows.Forms.Padding(13, 12, 13, 37), + BackColor = Color.Transparent + }; + gpSubItem.Style.TextAlignment = DevComponents.DotNetBar.eStyleTextAlignment.Center; gpSubItem.Style.TextColorSchemePart = DevComponents.DotNetBar.eColorSchemePart.PanelText; gpSubItem.Style.TextLineAlignment = DevComponents.DotNetBar.eStyleTextAlignment.Near; gpSubItem.StyleMouseDown.CornerType = DevComponents.DotNetBar.eCornerType.Square; @@ -118,8 +115,10 @@ namespace Volian.Controls.Library gpSubItem.Size = new System.Drawing.Size(400, 250); return gpSubItem; } - private Dictionary MyCheckBoxes = new Dictionary(); - private string _MyApplicability = string.Empty; +#pragma warning disable IDE0044 // Add readonly modifier + private Dictionary MyCheckBoxes = new Dictionary(); +#pragma warning restore IDE0044 // Add readonly modifier + private string _MyApplicability = string.Empty; public string MyApplicability { get { return _MyApplicability; } @@ -132,15 +131,17 @@ namespace Volian.Controls.Library private void AddItemMode(string name, string value, ref DevComponents.DotNetBar.Controls.GroupPanel gpSubItem) { - CheckBox cb = new CheckBox(); - cb.BackColor = Color.Transparent; - cb.Height = 24; - cb.Width = 75; - cb.AutoSize = true; - cb.Text = name; - cb.Tag = value; - cb.Dock = DockStyle.Top; - gpSubItem.Controls.Add(cb); + CheckBox cb = new CheckBox + { + BackColor = Color.Transparent, + Height = 24, + Width = 75, + AutoSize = true, + Text = name, + Tag = value, + Dock = DockStyle.Top + }; + gpSubItem.Controls.Add(cb); cb.BringToFront(); cb.CheckedChanged += new EventHandler(cb_CheckedChanged); MyCheckBoxes.Add(value == null ? -1 : int.Parse(value), cb); @@ -219,7 +220,7 @@ namespace Volian.Controls.Library List invalidTrans = WillTransitionsBeValidCommand.Execute(MyItemInfo.ItemID, MyApplicability); // B2021-149: for Procedure level PC/PC, continue processing if all 'invalid' transitions are internal (query used // return internal and external for the procedure level) - if ((!MyItemInfo.IsProcedure && invalidTrans.Count == 0) || IsProcWithNoExternalTrans(MyItemInfo, invalidTrans)) + if ((!MyItemInfo.IsProcedure && invalidTrans.Count == 0) || IsProcWithNoExternalTrans(invalidTrans)) { // C2021 - 027: Procedure level PC/PC if (MyItemInfo.IsProcedure && MyItemInfo.ActiveFormat.PlantFormat.FormatData.ProcData.ProcAppl) @@ -279,7 +280,7 @@ namespace Volian.Controls.Library // C2026-023: Check for Transitions when setting Applicability to all for a level List invalidTrans = WillTransitionsBeValidCommand.Execute(startitm.ItemID, MasterSlave_ApplicabilityTmp.ToString()); - if (IsProcWithNoExternalTrans(startitm, invalidTrans)) + if (IsProcWithNoExternalTrans(invalidTrans)) { StepConfig sc2 = startitm.MyConfig as StepConfig; using (Content cnt = Content.Get(startitm.MyContent.ContentID)) @@ -319,7 +320,7 @@ namespace Volian.Controls.Library } // B2021-149: for procedure, only consider external transitions as invalid - private bool IsProcWithNoExternalTrans(ItemInfo ii, List invalidTrans) + private bool IsProcWithNoExternalTrans(List invalidTrans) { if (invalidTrans.Count == 0) return true; foreach (InvalidTransition iT in invalidTrans) @@ -434,18 +435,17 @@ namespace Volian.Controls.Library foreach (CheckBox cb in MyCheckBoxes.Values) cb.Enabled = true; } - private void AddViewMode(string name, string value) + + private void AddViewMode(string name, string value, bool selected) { - AddViewMode(name, value, false); - } - private void AddViewMode(string name, string value, bool selected) - { - RadioButton rb = new RadioButton(); - rb.BackColor = Color.Transparent; - rb.Text = name; - rb.Tag = value; - rb.Dock = DockStyle.Top; - gpMode.Controls.Add(rb); + RadioButton rb = new RadioButton + { + BackColor = Color.Transparent, + Text = name, + Tag = value, + Dock = DockStyle.Top + }; + gpMode.Controls.Add(rb); rb.BringToFront(); rb.Checked = selected; rb.CheckedChanged += new EventHandler(rb_CheckedChanged); @@ -469,7 +469,7 @@ namespace Volian.Controls.Library // C2021 - 027: Procedure level PC/PC - handle procedure level too for viewing in editor if (MyDisplayTabItem.MyStepTabPanel.SelectedItemInfo != null && MyDisplayTabItem.MyStepTabPanel.SelectedItemInfo.IsProcedure) ei = MyDisplayTabItem.MyStepTabPanel.SelectedEditItem; - if (ei != null) ei.MyStepRTB.Focus(); + ei?.MyStepRTB.Focus(); } } @@ -489,7 +489,7 @@ namespace Volian.Controls.Library void DisplayApplicability_VisibleChanged(object sender, EventArgs e) { MyItemInfo = MyItemInfo; - gpItem.Enabled = ShowItemSelection && UserInfo.CanEdit(MyUserInfo,(MyItemInfo == null) ? null : MyItemInfo.MyDocVersion); //Can Change Applicability + gpItem.Enabled = ShowItemSelection && UserInfo.CanEdit(MyUserInfo,MyItemInfo?.MyDocVersion); //Can Change Applicability } } } diff --git a/PROMS/Volian.Controls.Library/DisplayBookMarks.cs b/PROMS/Volian.Controls.Library/DisplayBookMarks.cs index 6e273885..274a6a41 100644 --- a/PROMS/Volian.Controls.Library/DisplayBookMarks.cs +++ b/PROMS/Volian.Controls.Library/DisplayBookMarks.cs @@ -1,9 +1,4 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Drawing; -using System.Data; -using System.Text; using System.Windows.Forms; using VEPROMS.CSLA.Library; using JR.Utils.GUI.Forms; @@ -18,9 +13,8 @@ namespace Volian.Controls.Library public event ResetBookMarksInPROMSWindowsEvent ResetBookMarksInPROMSWindows; private void OnResetBookMarksInPROMSWindows() { - if (ResetBookMarksInPROMSWindows != null) - ResetBookMarksInPROMSWindows(this, new EventArgs()); - } + ResetBookMarksInPROMSWindows?.Invoke(this, new EventArgs()); + } #endregion //delegates and Events #region Properties private MostRecentItemList _MyBookMarks; @@ -30,8 +24,7 @@ namespace Volian.Controls.Library set { _MyBookMarks = value; } } private ItemInfo _CurItemInfo = null; - private bool _Initalizing = false; - private DisplayTabControl _MyDisplayTabControl; + private DisplayTabControl _MyDisplayTabControl; public DisplayTabControl MyDisplayTabControl { get { return _MyDisplayTabControl; } @@ -53,24 +46,11 @@ namespace Volian.Controls.Library _CurItemInfo = MyEditItem.MyItemInfo; } } - //private StepRTB _MyRTB; - //public StepRTB MyRTB - //{ - // get { return _MyRTB; } - // set - // { - // if (value == null) return; - // if (_CurItemInfo != null && _CurItemInfo.ItemID == value.MyItemInfo.ItemID) return; - // _MyRTB = value; - // _CurItemInfo = MyRTB.MyItemInfo; - // } - //} #endregion #region Constructors public DisplayBookMarks() { InitializeComponent(); - //SetupBookMarks(); } public void SetupBookMarks() { @@ -81,9 +61,6 @@ namespace Volian.Controls.Library } lbxBookMarks.SelectedValueChanged += new EventHandler(lbxBookMarks_SelectedValueChanged); RefreshBookMarkData(); - //btnPrevPos.Enabled = false; - //lbxBookMarks.Enabled = false; - //_PrevBookMark = null; } void _MyBookMarks_AfterRemove(object sender) @@ -92,8 +69,8 @@ namespace Volian.Controls.Library } private void RefreshBookMarkData() { - ResetBookMarkList(); - OnResetBookMarksInPROMSWindows(); // C2015-022 trigger event to update child PROMS windows with current bookmark list + ResetBookMarkList(); + OnResetBookMarksInPROMSWindows(); // C2015-022 trigger event to update child PROMS windows with current bookmark list SaveBookMarks(); } @@ -148,10 +125,9 @@ namespace Volian.Controls.Library } private void lbxBookMarks_Click(object sender, EventArgs e) { - MostRecentItem itm = lbxBookMarks.SelectedValue as MostRecentItem; - if(itm != null) - MyDisplayTabControl.OpenItem(itm.MyItemInfo); - } + if (lbxBookMarks.SelectedValue is MostRecentItem itm) + MyDisplayTabControl.OpenItem(itm.MyItemInfo); + } #endregion } } diff --git a/PROMS/Volian.Controls.Library/DisplayFoldoutMaint.cs b/PROMS/Volian.Controls.Library/DisplayFoldoutMaint.cs index 411e0208..0491db1d 100644 --- a/PROMS/Volian.Controls.Library/DisplayFoldoutMaint.cs +++ b/PROMS/Volian.Controls.Library/DisplayFoldoutMaint.cs @@ -1,9 +1,5 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Drawing; -using System.Data; -using System.Text; +using System.Linq; using System.Windows.Forms; using VEPROMS.CSLA.Library; @@ -30,7 +26,7 @@ namespace Volian.Controls.Library { if (!DesignMode && _MainStepSection == null) // B2019-043 need to check if we are just saving changes to the user interface { - foreach (SectionInfo si in MyItemInfo.MyProcedure.Sections) + foreach (SectionInfo si in MyItemInfo.MyProcedure.Sections.OfType()) { SectionConfig sc = (SectionConfig)si.MyConfig; if (sc.Section_OriginalSteps == "Y") _MainStepSection = si; @@ -39,9 +35,6 @@ namespace Volian.Controls.Library return _MainStepSection; } } - //private ItemInfo _firstStep; - //private ItemInfo _lastStep; - private bool _Initializing; public DisplayFoldoutMaint() { @@ -56,11 +49,10 @@ namespace Volian.Controls.Library if (MyItemInfo != null) { if (MyItemInfo.MyProcedure.Sections == null || MyItemInfo.MyProcedure.Sections.Count == 0) return; - _Initializing = true; ProcedureInfo pi = MyItemInfo.MyProcedure; listBoxFoldouts.Items.Clear(); lstCBSteps.Items.Clear(); - foreach (SectionInfo si in pi.Sections) + foreach (SectionInfo si in pi.Sections.OfType()) if (si.DisplayText.ToUpper().StartsWith("FOLDOUT")) listBoxFoldouts.Items.Add(si); if (listBoxFoldouts.Items.Count > 0) listBoxFoldouts.SelectedIndex = 0; else @@ -71,7 +63,6 @@ namespace Volian.Controls.Library // find default step section & use its steps to fill in tree. FillInSteps(); - _Initializing = false; } } private void FillInSteps() @@ -80,19 +71,18 @@ namespace Volian.Controls.Library ItemInfo startitm = MainStepSection.Steps != null && MainStepSection.Steps.Count > 0 ? MainStepSection.Steps[0] : null; while (startitm != null) { - StepConfig sc = startitm.MyConfig as StepConfig; - if (sc != null) - { - if (sc.Step_FloatingFoldout == foldOutselected.ItemID) - { - lstCBSteps.Items.Add(startitm, CheckState.Checked); - } - else - lstCBSteps.Items.Add(startitm, CheckState.Unchecked); - } - else - lstCBSteps.Items.Add(startitm, CheckState.Unchecked); - startitm = startitm.GetNext(); + if (startitm.MyConfig is StepConfig sc) + { + if (sc.Step_FloatingFoldout == foldOutselected.ItemID) + { + lstCBSteps.Items.Add(startitm, CheckState.Checked); + } + else + lstCBSteps.Items.Add(startitm, CheckState.Unchecked); + } + else + lstCBSteps.Items.Add(startitm, CheckState.Unchecked); + startitm = startitm.GetNext(); } } private void listBoxFoldouts_SelectedIndexChanged(object sender, EventArgs e) @@ -102,12 +92,11 @@ namespace Volian.Controls.Library for (int i = 0; i < lstCBSteps.Items.Count; i++) { ItemInfo startitm = lstCBSteps.Items[i] as ItemInfo; - StepConfig sc = startitm.MyConfig as StepConfig; - if (sc != null) - lstCBSteps.SetItemChecked(itemInList, sc.Step_FloatingFoldout == foldOutselected.ItemID); - else - lstCBSteps.SetItemChecked(itemInList, false); - itemInList++; + if (startitm.MyConfig is StepConfig sc) + lstCBSteps.SetItemChecked(itemInList, sc.Step_FloatingFoldout == foldOutselected.ItemID); + else + lstCBSteps.SetItemChecked(itemInList, false); + itemInList++; } } private void btnSave_Click(object sender, EventArgs e) diff --git a/PROMS/Volian.Controls.Library/DisplayHistory.cs b/PROMS/Volian.Controls.Library/DisplayHistory.cs index e00facf0..f2df0f2e 100644 --- a/PROMS/Volian.Controls.Library/DisplayHistory.cs +++ b/PROMS/Volian.Controls.Library/DisplayHistory.cs @@ -1,9 +1,7 @@ using System; using System.Collections.Generic; -using System.ComponentModel; using System.Drawing; using System.Data; -using System.Text; using System.Windows.Forms; using VEPROMS.CSLA.Library; using System.IO; @@ -11,7 +9,7 @@ using System.Text.RegularExpressions; using JR.Utils.GUI.Forms; using Volian.Base.Library; using System.Linq; - + namespace Volian.Controls.Library { public partial class DisplayHistory : UserControl @@ -21,30 +19,22 @@ namespace Volian.Controls.Library public event DisplayHistoryReportEvent SummaryPrintRequest; private void OnChronologyPrintRequest(DisplayHistoryReportEventArgs args) { - if (ChronologyPrintRequest != null) - ChronologyPrintRequest(this, args); - } + ChronologyPrintRequest?.Invoke(this, args); + } private void OnSummaryPrintRequest(DisplayHistoryReportEventArgs args) { - if (SummaryPrintRequest != null) - SummaryPrintRequest(this, args); - } + SummaryPrintRequest?.Invoke(this, args); + } public event DisplayHistoryEvent HistorySelectionChanged; private void OnHistorySelectionChanged(DisplayHistoryEventArgs args) { - if (HistorySelectionChanged != null) - HistorySelectionChanged(this, args); - } - public event ItemRestoredHandler ItemRestored; - private void OnItemRestored(ItemInfo restoredItemInfo) - { - if (ItemRestored != null) ItemRestored(restoredItemInfo); - } + HistorySelectionChanged?.Invoke(this, args); + } public event AnnotationRestoredHandler AnnotationRestored; private void OnAnnotationRestored(AnnotationInfo restoredAnnotationInfo, ItemInfo currentItem) { - if (AnnotationRestored != null) AnnotationRestored(restoredAnnotationInfo, currentItem); - } + AnnotationRestored?.Invoke(restoredAnnotationInfo, currentItem); + } #endregion private ContentAuditInfoList _ChronologyAuditList; private ContentAuditInfoList _SummaryAuditList; @@ -176,10 +166,8 @@ namespace Volian.Controls.Library SetRevDate(MyProcedureInfo.DTS); else { - DateTime revDate; - if (!DateTime.TryParse(cfg.Print_RevDate, out revDate)) revDate = MyProcedureInfo.ChangeBarDate; // DateTime.Now; - SetRevDate(revDate); - //SetRevDate(DateTime.Parse(cfg.Print_RevDate)); + if (!DateTime.TryParse(cfg.Print_RevDate, out DateTime revDate)) revDate = MyProcedureInfo.ChangeBarDate; // DateTime.Now; + SetRevDate(revDate); } } } @@ -222,42 +210,39 @@ namespace Volian.Controls.Library { if (lbChanges.SelectedIndex > -1) { - ContentAuditInfo cai = lbChanges.SelectedItem as ContentAuditInfo; - if (cai != null) - { - // The following line was incorrectly showing a message stating that the item was deleted when it was not. - //if (cai.DeleteStatus > 0 || (cai.DeleteStatus == 0 && cai.ActionWhen.Year == DateTime.MinValue.Year)) - if (cai.DeleteStatus > 0) - FlexibleMessageBox.Show("This item has been deleted.", "Deleted Item", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); - else - { - try - { - OnHistorySelectionChanged(new DisplayHistoryEventArgs(cai.ItemID)); - } - // If the selected item is deleted display a message rather than crashing - catch (Exception ex) - { - FlexibleMessageBox.Show("This item has been deleted.", "Deleted Item", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); - } - } - } - else - { - AnnotationAuditInfo aai = lbChanges.SelectedItem as AnnotationAuditInfo; - OnHistorySelectionChanged(new DisplayHistoryEventArgs(aai.ItemID)); - } - } + if (lbChanges.SelectedItem is ContentAuditInfo cai) + { + // The following line was incorrectly showing a message stating that the item was deleted when it was not. + //if (cai.DeleteStatus > 0 || (cai.DeleteStatus == 0 && cai.ActionWhen.Year == DateTime.MinValue.Year)) + if (cai.DeleteStatus > 0) + FlexibleMessageBox.Show("This item has been deleted.", "Deleted Item", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); + else + { + try + { + OnHistorySelectionChanged(new DisplayHistoryEventArgs(cai.ItemID)); + } + // If the selected item is deleted display a message rather than crashing + catch (Exception) + { + FlexibleMessageBox.Show("This item has been deleted.", "Deleted Item", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); + } + } + } + else + { + AnnotationAuditInfo aai = lbChanges.SelectedItem as AnnotationAuditInfo; + OnHistorySelectionChanged(new DisplayHistoryEventArgs(aai.ItemID)); + } + } } private void UpdateHistory() { this.Cursor = Cursors.WaitCursor; - //DateTime start = DateTime.Now; //Console.WriteLine(start); #region setup btnRestore.Enabled = false; myRTB.Clear(); - //myRTB.LastRtf = string.Empty; myVFG.Clear(); myPicBox.Image = null; if (!tvAudits.IsDisposed) // fixes a crash that happend while debugging separate windows, have not been able to reproduce. left this IF check in just in case. - jsj 2-1-2018 @@ -269,8 +254,6 @@ namespace Volian.Controls.Library } MyItemInfo.RefreshItemAnnotations(); #endregion - //if (AnnotationOnly) - //{ #region annotation deleted //annotation deleted by itemid TreeNode annotationDeleted = null; @@ -319,14 +302,11 @@ namespace Volian.Controls.Library } //end annotation change #endregion - // return; - //} #region content changes //content changes TreeNode contentHistory = null; if (MyItemInfo == null) return; ContentAuditInfoList cail = ContentAuditInfoList.Get(MyItemInfo.ContentID, MyItemInfo.MyProcedure.DTS); - // ContentAuditInfoList cail = ContentAuditInfoList.GetChronology(MyItemInfo.MyProcedure.ItemID, MyItemInfo.ItemID, false); ContentInfo ci = ContentInfo.Get(MyItemInfo.ContentID); foreach (ContentAuditInfo cai in cail) { @@ -378,155 +358,10 @@ namespace Volian.Controls.Library #endregion #region items TreeNode deletedItems = null; - TreeNode previousItem = null; - TreeNode nextItem = null; - TreeNode procedurePart = null; - TreeNode sectionPart = null; - TreeNode cautionPart = null; - TreeNode notePart = null; - TreeNode rnoPart = null; - TreeNode stepPart = null; - TreeNode tablePart = null; #endregion ItemAuditInfoList iail = ItemAuditInfoList.Get(MyItemInfo.ItemID); foreach (ItemAuditInfo iai in iail) { - #region old style - // switch (iai.Level) - // { - // #region previous item - // case 0: //previous item - // { - // #region old style - // //if (previousItem == null) - // // previousItem = tvAudits.Nodes.Add("Deleted Previous Item"); //previousItem = tvAudits.Nodes.Add("Previous Item"); - // //TreeNode tn = previousItem.Nodes.Add(iai.ToString()); - // //tn.Tag = iai; - // #endregion - // #region new style - // if (deletedItems == null) - // deletedItems = tvAudits.Nodes.Add("Deleted Items"); - // TreeNode tnn = deletedItems.Nodes.Add(iai.ToString()); - // tnn.Tag = iai; - // #endregion - // break; - // } - // #endregion - // #region next item - // case 1: //next item - // { - // #region old style - // //if (nextItem == null) - // // nextItem = tvAudits.Nodes.Add("Deleted Next Item"); //nextItem = tvAudits.Nodes.Add("Next Item"); - // //TreeNode tn = nextItem.Nodes.Add(iai.ToString()); - // //tn.Tag = iai; - // #endregion - // #region new style - // if (deletedItems == null) - // deletedItems = tvAudits.Nodes.Add("Deleted Items"); - // TreeNode tnn = deletedItems.Nodes.Add(iai.ToString()); - // tnn.Tag = iai; - // #endregion - // break; - // } - // #endregion - // case 2: //parts - // { - // #region old style - // //PartAuditInfoList pail = null; - // //pail = PartAuditInfoList.GetByDeleteStatus(iai.DeleteStatus); - // //if (pail.Count == 0) - // // pail = PartAuditInfoList.GetByItemID(iai.ItemID); - // //foreach (PartAuditInfo pai in pail) - // //{ - // // if (pai.ContentID == MyItemInfo.ContentID) - // // { - // // switch (pai.FromType) - // // { - // // #region procedure part - // // case 1: //procedures - // // { - // // if (procedurePart == null) - // // procedurePart = tvAudits.Nodes.Add("Deleted Procedures"); //procedurePart = tvAudits.Nodes.Add("Procedures"); - // // TreeNode tn = procedurePart.Nodes.Add(iai.ToString()); - // // tn.Tag = iai; - // // break; - // // } - // // #endregion - // // #region section part - // // case 2: //sections - // // { - // // if (sectionPart == null) - // // sectionPart = tvAudits.Nodes.Add("Deleted Sections"); //sectionPart = tvAudits.Nodes.Add("Sections"); - // // TreeNode tn = sectionPart.Nodes.Add(iai.ToString()); - // // tn.Tag = iai; - // // break; - // // } - // // #endregion - // // #region caution part - // // case 3: //cautions - // // { - // // if (cautionPart == null) - // // cautionPart = tvAudits.Nodes.Add("Deleted Cautions"); //cautionPart = tvAudits.Nodes.Add("Cautions"); - // // TreeNode tn = cautionPart.Nodes.Add(iai.ToString()); - // // tn.Tag = iai; - // // break; - // // } - // // #endregion - // // #region note part - // // case 4: //notes - // // { - // // if (notePart == null) - // // notePart = tvAudits.Nodes.Add("Deleted Notes"); //notePart = tvAudits.Nodes.Add("Notes"); - // // TreeNode tn = notePart.Nodes.Add(iai.ToString()); - // // tn.Tag = iai; - // // break; - // // } - // // #endregion - // // #region rno part - // // case 5: //rnos - // // { - // // if (rnoPart == null) - // // rnoPart = tvAudits.Nodes.Add("Deleted RNOs"); //rnoPart = tvAudits.Nodes.Add("RNOs"); - // // TreeNode tn = rnoPart.Nodes.Add(iai.ToString()); - // // tn.Tag = iai; - // // break; - // // } - // // #endregion - // // #region step part - // // case 6: //steps - // // { - // // if (stepPart == null) - // // stepPart = tvAudits.Nodes.Add("Deleted Steps"); //stepPart = tvAudits.Nodes.Add("Steps"); - // // TreeNode tn = stepPart.Nodes.Add(iai.ToString()); - // // tn.Tag = iai; - // // break; - // // } - // // #endregion - // // #region table part - // // case 7: //tables - // // { - // // if (tablePart == null) - // // tablePart = tvAudits.Nodes.Add("Deleted Tables"); //tablePart = tvAudits.Nodes.Add("Tables"); - // // TreeNode tn = tablePart.Nodes.Add(iai.ToString()); - // // tn.Tag = iai; - // // break; - // // } - // // #endregion - // // } - // // } - // //} - // #endregion - // #region new style - // if (deletedItems == null) - // deletedItems = tvAudits.Nodes.Add("Deleted Items"); - // TreeNode tnn = deletedItems.Nodes.Add(iai.ToString()); - // tnn.Tag = iai; - // #endregion - // break; - // } - //} - #endregion #region new style // B2023-117 if DeleteStatus is zero,don't try to get Audit Info List if (iai.DeleteStatus == 0) continue; @@ -552,7 +387,7 @@ namespace Volian.Controls.Library } } } - TreeNode tnn = deletedItems.Nodes.Add(iai.ToString() + "; Reason: " + strR); + TreeNode tnn = deletedItems.Nodes.Add($"{iai}; Reason: {strR}"); tnn.Tag = iai; #endregion } @@ -572,10 +407,8 @@ namespace Volian.Controls.Library } private void WalkProcedure() { - //return; this.ParentForm.Cursor = Cursors.WaitCursor; Application.DoEvents(); - //DateTime start = DateTime.Now; //Console.WriteLine(start); lbChanges.Items.Clear(); if (MyProcedureInfo == null) @@ -584,10 +417,10 @@ namespace Volian.Controls.Library btnViewSummaryReport.Enabled = btnViewChronologyReport.Enabled = cbSumExcludeAnn.Enabled = DT_SumAsOf.Enabled = lbChanges.Items.Count > 0; return; } - ContentAuditInfoList cail2; - ContentAuditInfoList cail3; - AnnotationAuditInfoList aail2; - if (ApplDisplayMode > 0) + ContentAuditInfoList cail2; + ContentAuditInfoList cail3; + AnnotationAuditInfoList aail2; + if (ApplDisplayMode > 0) { cail2 = ContentAuditInfoList.GetChronologyByUnit(MyProcedureInfo.ItemID, MyProcedureInfo.ItemID, false, ApplDisplayMode, MyProcedureInfo.ChangeBarDate); cail3 = ContentAuditInfoList.GetSummaryByUnit(MyProcedureInfo.ItemID, MyProcedureInfo.ItemID, false, ApplDisplayMode, MyProcedureInfo.ChangeBarDate); @@ -611,8 +444,8 @@ namespace Volian.Controls.Library // in the list box and should not be because some MyRevDate's did not have time included. if (CompareDateOrDateTime(cai.DTS, MyRevDate) || cai.ActionWhen > MyRevDate) { - string itemTitle = FixPath(cai.Path); - lbChanges.Items.Add(cai); + _ = FixPath(cai.Path); + lbChanges.Items.Add(cai); } } foreach (AnnotationAuditInfo aai in aail2) @@ -630,7 +463,7 @@ namespace Volian.Controls.Library { ItemInfo iii = aai.MyItemInfo; if (iii != null) - stepnum = FixPath(iii.SearchPath); + _ = FixPath(iii.SearchPath); } if (aai.DTS > MyRevDate) lbChanges.Items.Add(aai); @@ -650,25 +483,13 @@ namespace Volian.Controls.Library private void btnViewChronologyReport_Click(object sender, EventArgs e) { RefreshList(); - //if (lbChanges.Items.Count > 0) - //{ - //jcb added 20120425 to suppress annotations in report - //jcb commented out 20130409 per bug C2012-022 - //_AnnotationList = AnnotationAuditInfoList.GetChronology(0, 0, MyProcedureInfo.ChangeBarDate); //added setting selected slave in order for reports to replace unit number,etc jcb 20101010 MyItemInfo.MyProcedure.MyDocVersion.DocVersionConfig.SelectedSlave = ApplDisplayMode; - // OnChronologyPrintRequest(new DisplayHistoryReportEventArgs(Volian.Base.Library.VlnSettings.TemporaryFolder + @"\MyChronology.pdf", MyItemInfo.MyProcedure, _ChronologyAuditList, _AnnotationList)); OnChronologyPrintRequest(new DisplayHistoryReportEventArgs(string.Format(@"{0}\{1} Chronology of Changes.pdf", Volian.Base.Library.VlnSettings.TemporaryFolder, MyItemInfo.MyProcedure.PDFNumber), MyItemInfo.MyProcedure, _ChronologyAuditList, _AnnotationList)); - //} } private void btnViewSummaryReport_Click(object sender, EventArgs e) { RefreshList(); - //if (lbChanges.Items.Count > 0) - //{ - //jcb added 20120425 to suppress annotations in report - //jcb commented out 20130409 per bug C2012-022 - //_AnnotationList = AnnotationAuditInfoList.GetChronology(0, 0, MyProcedureInfo.ChangeBarDate); //added setting selected slave in order for reports to replace unit number,etc jcb 20101010 MyItemInfo.MyProcedure.MyDocVersion.DocVersionConfig.SelectedSlave = ApplDisplayMode; @@ -676,7 +497,6 @@ namespace Volian.Controls.Library //C2024- 038 - Summary of Changes report generation enhancements //check if need to modify - // _SummaryAuditList if (DT_SumAsOf.Checked) dhr.AuditList = FilterSummaryByDate(_SummaryAuditList, DT_SumAsOf.Value); else @@ -685,7 +505,6 @@ namespace Volian.Controls.Library //C2024- 038 - Summary of Changes report generation enhancements // if Exclude Annotations Checked // send an empty list instead of - //_AnnotationList if (cbSumExcludeAnn.Checked) dhr.AnnotationList = new AnnotationAuditInfoList(null); else if (DT_SumAsOf.Checked) @@ -799,11 +618,7 @@ namespace Volian.Controls.Library if (myRoFst != null) myRoFst.ROTableUpdate += new ROFstInfoROTableUpdateEvent(myRoFst_ROTableUpdate); ii = MyItemInfo.RestoreItem(iai, myRoFst); if (myRoFst != null) myRoFst.ROTableUpdate -= new ROFstInfoROTableUpdateEvent(myRoFst_ROTableUpdate); - //_MyEditItem.AddChild((E_FromType)fromtype, contenttype); - //ii.ItemParts[0].FromType - //ii.MyContent.Type EditItem nextItem = MyEditItem.GetNextItem((E_FromType)ii.ItemParts[0].FromType, ii); - //MyEditItem.AddChild(ii.MyContent.Text, (E_FromType)ii.ItemParts[0].FromType, (int)ii.MyContent.Type, null); if (ii.IsStep) ii = StepInfo.Get(ii.ItemID); else if (ii.IsSection) @@ -1051,10 +866,6 @@ namespace Volian.Controls.Library myRTB.Visible = true; myRTB.BringToFront(); myVFG.Visible = false; - // myRTB.Font = new Font("Arial", 12, FontStyle.Regular); - // myRTB.Text = cai.Text; - //myRTB.SetupRichText("bozo", MyItemInfo.FormatStepData == null ? MyItemInfo.ActiveFormat.PlantFormat.FormatData.Font : MyItemInfo.FormatStepData.Font); - //myRTB.LastRtf = string.Empty; myRTB.SetupRichText(cai.Text, MyItemInfo.FormatStepData == null ? MyItemInfo.ActiveFormat.PlantFormat.FormatData.Font : MyItemInfo.FormatStepData.Font); } } @@ -1067,8 +878,6 @@ namespace Volian.Controls.Library { if (cai.DeleteStatus == iai.DeleteStatus) { - //myRTB.Font = new Font("Arial", 12, FontStyle.Regular); - //myRTB.Text = cai.Text; myRTB.SetupRichText(cai.Text, MyItemInfo.FormatStepData == null ? MyItemInfo.ActiveFormat.PlantFormat.FormatData.Font : MyItemInfo.FormatStepData.Font); } } @@ -1079,7 +888,6 @@ namespace Volian.Controls.Library AnnotationAuditInfo iai = tn.Tag as AnnotationAuditInfo; myRTB.Font = new Font("Arial", 12, FontStyle.Regular); myRTB.Rtf = iai.RtfText; - //myRTB.Rtf = iai.RtfText; } } else @@ -1121,7 +929,7 @@ namespace Volian.Controls.Library myTimer.Enabled = true; } // B2019-161 When tracking timing time this action - private static VolianTimer _TimeActivity = new VolianTimer("DisplayHistory myTimer_Tick", 974); + private static readonly VolianTimer _TimeActivity = new VolianTimer("DisplayHistory myTimer_Tick", 974); private void myTimer_Tick(object sender, System.EventArgs e) { diff --git a/PROMS/Volian.Controls.Library/DisplayLibDocs.cs b/PROMS/Volian.Controls.Library/DisplayLibDocs.cs index 2bb90099..0d8dda9c 100644 --- a/PROMS/Volian.Controls.Library/DisplayLibDocs.cs +++ b/PROMS/Volian.Controls.Library/DisplayLibDocs.cs @@ -1,14 +1,7 @@ using System; -using System.Collections; -using System.Collections.Generic; -using System.ComponentModel; using System.Drawing; -using System.Data; -using System.Text; using System.Windows.Forms; -using System.Text.RegularExpressions; using System.IO; -using AT.STO.UI.Win; using VEPROMS.CSLA.Library; namespace Volian.Controls.Library @@ -30,7 +23,7 @@ namespace Volian.Controls.Library get { return _LibDocList; } set { _LibDocList = value; } } - private Color saveGroupPanelUsages; + private readonly Color saveGroupPanelUsages; #endregion #region Constructors public DisplayLibDocs() @@ -76,9 +69,8 @@ namespace Volian.Controls.Library public event DisplayLibDocEvent PrintRequest; private void OnPrintRequest(DisplayLibDocEventArgs args) { - if (PrintRequest != null) - PrintRequest(this, args); - } + PrintRequest?.Invoke(this, args); + } private void listBoxLibDocs_Click(object sender, EventArgs e) { @@ -125,9 +117,9 @@ namespace Volian.Controls.Library foreach (ItemInfo ii in dicnt.LibraryDocumentUsageList) { if (ii.MyDocVersion != null) - listBoxUsages.Items.Add(ii.MyProcedure.ToString() + " - " + ii.DisplayNumber + " " + ii.DisplayText); + listBoxUsages.Items.Add($"{ii.MyProcedure} - {ii.DisplayNumber} {ii.DisplayText}"); } - btnPrint.Enabled = listBoxLibDocs.Items.Count > 0 ? true : false; + btnPrint.Enabled = listBoxLibDocs.Items.Count > 0; } private void btnDelLibDoc_Click(object sender, EventArgs e) { @@ -139,7 +131,7 @@ namespace Volian.Controls.Library } catch (Exception ex) { - Console.WriteLine("error deleting doc = " + ex.Message); + Console.WriteLine($"error deleting doc = {ex.Message}"); } LibDocListFillIn(_DisplayTabControl); } @@ -203,14 +195,15 @@ namespace Volian.Controls.Library private void btnImpLibDoc_Click(object sender, EventArgs e) { - OpenFileDialog openFileDialog1 = new OpenFileDialog(); + OpenFileDialog openFileDialog1 = new OpenFileDialog + { + InitialDirectory = "c:\\", + Filter = "Word files (*.doc;*.rtf;*.docx)|*.doc;*.rtf;*.docx|All files (*.*)|*.*", + FilterIndex = 0, + RestoreDirectory = true + }; - openFileDialog1.InitialDirectory = "c:\\"; - openFileDialog1.Filter = "Word files (*.doc;*.rtf;*.docx)|*.doc;*.rtf;*.docx|All files (*.*)|*.*"; - openFileDialog1.FilterIndex = 0; - openFileDialog1.RestoreDirectory = true; - - if (openFileDialog1.ShowDialog() == DialogResult.OK) + if (openFileDialog1.ShowDialog() == DialogResult.OK) { int done = 0; int ntry = 0; @@ -352,24 +345,6 @@ namespace Volian.Controls.Library get { return _PaperSize; } set { _PaperSize = 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 ICollection _MyItemInfoList; - //public ICollection MyItemInfoList - //{ - // get { return _MyItemInfoList; } - // set { _MyItemInfoList = value; } - //} public DisplayLibDocEventArgs(string reportTitle, DocumentInfoList libDocList, string paperSize) { _ReportTitle = reportTitle; diff --git a/PROMS/Volian.Controls.Library/DisplayRO.cs b/PROMS/Volian.Controls.Library/DisplayRO.cs index 7c271a05..718ae4b8 100644 --- a/PROMS/Volian.Controls.Library/DisplayRO.cs +++ b/PROMS/Volian.Controls.Library/DisplayRO.cs @@ -7,7 +7,6 @@ using System.Drawing; using System.IO; using System.Linq; using System.Text.RegularExpressions; -using System.Threading.Tasks; using System.Windows.Forms; using VEPROMS.CSLA.Library; using Volian.Base.Library; @@ -17,29 +16,22 @@ 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 readonly VolianTimer _timeActivity = new VolianTimer("DisplayRO MyRTB_SelectionChanged", 117); + private static readonly Regex _regExGetNumber = new Regex(@"^ *[+-]?[.,0-9/]+(E[+-]?[0-9]+)?"); private static UserInfo _myUserInfo = null; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Timer Not ReadOnly")] private Timer _searchTimer = null; - private string _lastSearchValue = string.Empty; private ProgressBarItem _progressBar; private DisplayTabControl _tabControl; private StepRTB _myRTB; - private string _selectedRoidBeforeRoEditor = null; private ROFstInfo _myROFST; private DocVersionInfo _docVersionInfo; @@ -51,12 +43,9 @@ namespace Volian.Controls.Library private int? _currDocVersionID = null; private RoUsageInfo _curROLink; - private E_ROValueType _curROTypeFilter = E_ROValueType.All; private ROFSTLookup.rochild selectedChld; - private DisplayTags displayTags; - #endregion @@ -286,15 +275,17 @@ namespace Volian.Controls.Library if (_searchTimer == null) { - _searchTimer = new Timer(); - _searchTimer.Interval = 1000; + _searchTimer = new Timer + { + Interval = 1000 + }; _searchTimer.Tick += new EventHandler(SelectionTimer_Tick); _searchTimer.Stop(); } // Initialize the DisplayTags object - displayTags = new DisplayTags(); + _ = new DisplayTags(); } @@ -405,9 +396,8 @@ namespace Volian.Controls.Library { // B2022-088: [JPR] Find Doc Ro button not working in Word Sections // B2022-098: [JPR] ROs not being resolved in Word Sections - if (e.Node.Tag is ROFSTLookup.rochild) + if (e.Node.Tag is ROFSTLookup.rochild chld) { - ROFSTLookup.rochild chld = (ROFSTLookup.rochild)e.Node.Tag; selectedChld = chld; if (chld.value != null) @@ -513,7 +503,7 @@ namespace Volian.Controls.Library } else if (selectedChld.type == 4) // x/y plot { - frmXYPlot plot = new frmXYPlot(selectedChld.appid + " - " + selectedChld.title, selectedChld.value); + frmXYPlot plot = new frmXYPlot($"{selectedChld.appid} - {selectedChld.title}", selectedChld.value); plot.Show(); } } @@ -527,7 +517,7 @@ namespace Volian.Controls.Library 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; + DisplayTabItem dti = _tabControl?.SelectedDisplayTabItem; if (dti != null && dti.MyDSOTabPanel != null) { @@ -567,15 +557,12 @@ namespace Volian.Controls.Library 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) + if (obj is ROFSTLookup.rochild roch) { - ROFSTLookup.rochild roch = (ROFSTLookup.rochild)obj; - - _selectedRoidBeforeRoEditor = roch.roid; - string args = "\"" + MyROFST.MyRODb.FolderPath + "\" " + roch.roid.Substring(0,12).ToLower(); + string args = $"\"{MyROFST.MyRODb.FolderPath}\" {roch.roid.Substring(0, 12).ToLower()}"; // C2017-003: ro data in sql server, check for sql connection string - if (MyROFST.MyRODb.DBConnectionString != "cstring") args = args + " \"" + MyROFST.MyRODb.DBConnectionString + "\""; + 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 @@ -589,7 +576,7 @@ namespace Volian.Controls.Library DocVersionConfig dvc = dvi.DocVersionConfig; if (dvc != null && dvc.Unit_Name != "" && dvc.Unit_Count > 1) // B2021-089 only pass in applicability info if defined for more than one unit { - args += " \"PC=" + dvc.Unit_Name + "\""; + args += $" \"PC={dvc.Unit_Name}\""; break; } } @@ -700,8 +687,10 @@ namespace Volian.Controls.Library { ROFSTLookup.rodbi db = dbs[i]; - TreeNode tn = new TreeNode(db.dbiTitle); - tn.Tag = db; + TreeNode tn = new TreeNode(db.dbiTitle) + { + Tag = db + }; tvROFST.Nodes.Add(tn); AddDummyGroup(db, tn); @@ -770,8 +759,6 @@ namespace Volian.Controls.Library tvROFST.Nodes.Remove(unitInfoNode); } - _curROTypeFilter = _roTypeFilter; - return updatedROs; } @@ -787,11 +774,9 @@ namespace Volian.Controls.Library 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 (double.TryParse(match1.ToString(), out double dbl1) && double.TryParse(match2.ToString(), out double dbl2)) { if (dbl1 != dbl2) //B2021-144 if the numerical is identical default to the string comparison? return dbl1 > dbl2; @@ -814,15 +799,13 @@ namespace Volian.Controls.Library //object tag = tn.Tag; ROFSTLookup.rochild[] children = null; - if (tn.Tag is ROFSTLookup.rodbi) + if (tn.Tag is ROFSTLookup.rodbi db) { - ROFSTLookup.rodbi db = (ROFSTLookup.rodbi)tn.Tag; MyROFSTLookup.LoadChildren(ref db); children = db.children; } - else if (tn.Tag is ROFSTLookup.rochild) + else if (tn.Tag is ROFSTLookup.rochild ch) { - ROFSTLookup.rochild ch = (ROFSTLookup.rochild)tn.Tag; MyROFSTLookup.LoadChildren(ref ch); children = ch.children; } @@ -861,8 +844,10 @@ namespace Volian.Controls.Library if (roc.value == null) { - tmp = new TreeNode(roc.title); - tmp.Tag = roc; + tmp = new TreeNode(roc.title) + { + Tag = roc + }; int index = FindIndex(tn.Nodes, tmp.Text); tn.Nodes.Insert(index, tmp); @@ -873,8 +858,10 @@ namespace Volian.Controls.Library else { - tmp = new TreeNode(roc.title); - tmp.Tag = roc; + tmp = new TreeNode(roc.title) + { + Tag = roc + }; if (tmp.Text.IndexOf("\\u") > -1) // RO Editor add symbols C2022 - 003 { @@ -909,7 +896,7 @@ namespace Volian.Controls.Library // Clean-up Roid if necessary roid = ROFSTLookup.FormatRoidKey(roid); - bool multValSel = (roid.Length == 16) ? true : false; + bool multValSel = (roid.Length == 16); string db = roid.Substring(0, 4); int dbiID = MyROFSTLookup.GetRODatabaseTitleIndex(roid); @@ -938,7 +925,7 @@ namespace Volian.Controls.Library if (roid.StartsWith("FFFF")) dbNode = tvROFST.Nodes.Cast().Where(x => (x.Tag.Equals(null)) && (x.Text.Equals("Unit Information"))).FirstOrDefault(); else - dbNode = tvROFST.Nodes.Cast().Where(x => (x.Tag is ROFSTLookup.rodbi) && ((ROFSTLookup.rodbi)x.Tag).dbiID == dbiID).FirstOrDefault(); + dbNode = tvROFST.Nodes.Cast().Where(x => (x.Tag is ROFSTLookup.rodbi rodbi) && rodbi.dbiID == dbiID).FirstOrDefault(); if (dbNode != null) { @@ -954,7 +941,7 @@ namespace Volian.Controls.Library LoadChildren(tnExpand); tnExpand.Expand(); - TreeNode chldNode = tnExpand.Nodes.Cast().Where(x => (x.Tag is ROFSTLookup.rochild) && ((ROFSTLookup.rochild)x.Tag).ID == citm).FirstOrDefault(); + TreeNode chldNode = tnExpand.Nodes.Cast().FirstOrDefault(x => (x.Tag is ROFSTLookup.rochild rochild) && rochild.ID == citm); if (chldNode != null) { tnExpand = chldNode; @@ -1006,10 +993,9 @@ namespace Volian.Controls.Library Object obj = tvROFST.SelectedNode.Tag; - if (obj is ROFSTLookup.rochild) + if (obj is ROFSTLookup.rochild roc) { - ROFSTLookup.rochild roc = (ROFSTLookup.rochild)obj; - DisplayTabItem dti = TabControl.SelectedDisplayTabItem; //.OpenItem(_ItemInfo); // open the corresponding procedure text + DisplayTabItem dti = TabControl.SelectedDisplayTabItem; if (dti.MyDSOTabPanel != null) // A Word Document tab is the active tab { @@ -1017,10 +1003,7 @@ namespace Volian.Controls.Library // Insert the RO text at the current cursor position in the word document // NOTE: assuming any type of RO can be put in an Accessory (MSWord) Document - if (dti.MyDSOTabPanel != null) - { - dti.MyDSOTabPanel.InsertText(accPageID); - } + dti.MyDSOTabPanel?.InsertText(accPageID); } else if (MyRTB != null) // a Procedure Steps section tab is active { @@ -1122,12 +1105,9 @@ namespace Volian.Controls.Library 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) + if (obj is ROFSTLookup.rochild roc) { - ROFSTLookup.rochild roc = (ROFSTLookup.rochild)obj; - _selectedRoidBeforeRoEditor = roc.roid; - - string args = "\"" + _myROFST.MyRODb.FolderPath + "\" " + roc.roid.ToLower(); + string args = $"\"{_myROFST.MyRODb.FolderPath}\" {roc.roid.ToLower()}"; if (!Directory.Exists(_myROFST.MyRODb.FolderPath)) { @@ -1136,7 +1116,7 @@ namespace Volian.Controls.Library } // 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 @@ -1150,7 +1130,7 @@ namespace Volian.Controls.Library if (jdvc != null && jdvc.Unit_Name != "" && jdvc.Unit_Count > 1) // B2021-089 only pass in applicability info if defined for more than one unit { - args += " \"PC=" + jdvc.Unit_Name + "\""; + args += $" \"PC={jdvc.Unit_Name}\""; break; } } @@ -1194,7 +1174,6 @@ namespace Volian.Controls.Library lbFound.DataSource = null; lbFound.Visible = false; - _lastSearchValue = searchValue; } else if (searchValue.Contains("#Link:ReferencedObject")) // RO Link (roid) { @@ -1216,7 +1195,6 @@ namespace Volian.Controls.Library lbFound.DataSource = null; lbFound.Visible = false; - _lastSearchValue = searchValue; } else // if (searchValue != _lastSearchValue) { @@ -1245,12 +1223,10 @@ namespace Volian.Controls.Library lbFound.Visible = false; } - _lastSearchValue = searchValue; } } else { - _lastSearchValue = string.Empty; lbFound.DataSource = null; lbFound.Visible = false; } diff --git a/PROMS/Volian.Controls.Library/DisplayReports.cs b/PROMS/Volian.Controls.Library/DisplayReports.cs index a347edda..eeeaccf3 100644 --- a/PROMS/Volian.Controls.Library/DisplayReports.cs +++ b/PROMS/Volian.Controls.Library/DisplayReports.cs @@ -1,15 +1,11 @@ using System; using System.Collections.Generic; -using System.ComponentModel; using System.Drawing; -using System.Data; -using System.Text; using System.Windows.Forms; using System.IO; using VEPROMS.CSLA.Library; using DevComponents.DotNetBar; using DevComponents.AdvTree; -using System.Text.RegularExpressions; using Volian.Base.Library; @@ -23,9 +19,8 @@ namespace Volian.Controls.Library private void OnPrintRequest(DisplayReportsEventArgs args) { - if (PrintRequest != null) - PrintRequest(this, args); - } + PrintRequest?.Invoke(this, args); + } #endregion @@ -34,17 +29,18 @@ namespace Volian.Controls.Library // 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(); +#pragma warning disable IDE0044 // Add readonly modifier + private List lstCheckedDocVersions = new List(); + private List lstCheckedROs = new List(); private List ROList = new List(); - private List lstROObj = new List(); - private int _MyRODbID; +#pragma warning restore IDE0044 // Add readonly modifier + private int _MyRODbID; private DocVersionInfo _MyDocVersion; private ROFSTLookup _MyROFSTLookup; private ItemInfoList _ReportResult; - private Dictionary AccIDROIDdic = new Dictionary(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private Dictionary AccIDROIDdic = new Dictionary(); static int blankKeyCnt = 0; #endregion @@ -104,10 +100,8 @@ namespace Volian.Controls.Library set { if (DesignMode) return; // B2019-043 need to check if we are just saving changes to the user interface - //if (!Visible) return; // don't reset anything if the form is invisible. _MyROFSTLookup = value; // define the tree nodes based on this rofst - advTreeROFillIn(true); - //LoadROComboTree(); + advTreeROFillIn(); } } @@ -154,7 +148,7 @@ namespace Volian.Controls.Library tabROReports.PerformClick(); } - public void advTreeROFillIn(bool blSeachTabClicked) + public void advTreeROFillIn() { DevComponents.AdvTree.Node topnode = null; advTreeRO.Nodes.Clear(); @@ -168,12 +162,14 @@ namespace Volian.Controls.Library advTreeRO.AfterCollapse -= 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; + topnode = new DevComponents.AdvTree.Node + { + Text = "All Referenced Objects", + Tag = null, + CheckBoxVisible = true + }; - advTreeRO.Nodes.Add(topnode); + advTreeRO.Nodes.Add(topnode); ROFSTLookup.rodbi[] dbs = _MyROFSTLookup.GetRODatabaseList(true); @@ -194,7 +190,7 @@ namespace Volian.Controls.Library } } - public void advTreeProcSetsFillIn(bool blSeachTabClicked) + public void advTreeProcSetsFillIn() { DevComponents.AdvTree.Node topnode = null; int cntnd = 0; @@ -203,41 +199,29 @@ namespace Volian.Controls.Library int fiCount = fi.ChildFolderCount; advTreeProcSets.Nodes.Clear(); lstCheckedDocVersions.Clear(); - topnode = new DevComponents.AdvTree.Node(); - topnode.Text = "Available Procedure Sets"; - topnode.Tag = fi; - advTreeProcSets.Nodes.Add(topnode); - //advTreeProcSets.AfterNodeInsert += new TreeNodeCollectionEventHandler(advTreeProcSets_AfterNodeInsert); - + topnode = new DevComponents.AdvTree.Node + { + Text = "Available Procedure Sets", + Tag = fi + }; + advTreeProcSets.Nodes.Add(topnode); foreach (FolderInfo fic in fi.SortedChildFolders) { - DevComponents.AdvTree.Node newnode = new DevComponents.AdvTree.Node(); - newnode.Text = fic.ToString(); - newnode.Tag = fic; + DevComponents.AdvTree.Node newnode = new DevComponents.AdvTree.Node + { + Text = fic.ToString(), + Tag = fic + }; - //int tmp; - //if (topnode == null) - //{ - // newnode.Text = "Available Procedure Sets"; - // tmp = advTreeProcSets.Nodes.Add(newnode); - // topnode = newnode; - //} - //else - //{ - // newnode.Selectable = true; - // newnode.CheckBoxAlignment = DevComponents.AdvTree.eCellPartAlignment.NearCenter; - // newnode.CheckBoxStyle = eCheckBoxStyle.CheckBox; - // newnode.CheckBoxThreeState = false; - // newnode.CheckBoxVisible = true; - // tmp = topnode.Nodes.Add(newnode); - //} - cntnd++; + cntnd++; if (fic.ChildFolderCount > 0 || fic.FolderDocVersionCount > 0) // allow for '+' for tree expansion { - DevComponents.AdvTree.Node tnt = new DevComponents.AdvTree.Node(); - tnt.Text = DummyNodeText; - newnode.Nodes.Add(tnt); + DevComponents.AdvTree.Node tnt = new DevComponents.AdvTree.Node + { + Text = DummyNodeText + }; + newnode.Nodes.Add(tnt); topnode.Nodes.Add(newnode); } } @@ -247,9 +231,11 @@ namespace Volian.Controls.Library { cntnd++; fi = Mydocversion.MyFolder; - topnode = new DevComponents.AdvTree.Node(); - topnode.Text = fi.ToString(); - advTreeProcSets.Nodes.Add(topnode); + topnode = new DevComponents.AdvTree.Node + { + Text = fi.ToString() + }; + advTreeProcSets.Nodes.Add(topnode); topnode.Tag = fi; } @@ -262,8 +248,6 @@ namespace Volian.Controls.Library 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 } #endregion @@ -272,13 +256,9 @@ namespace Volian.Controls.Library private void GenerateAccIDSortedROList() { - //Dictionary AccIDROIDdic = new Dictionary(); List AccPgIDsList = new List(); AccIDROIDdic.Clear(); - - string rtnStr = ""; - ROFSTLookup.rochild[] chld = null; - ROFSTLookup.rochild ch; + ROFSTLookup.rochild ch; ROList.Clear(); foreach (object rolkup in lstCheckedROs) @@ -287,9 +267,9 @@ namespace Volian.Controls.Library { foreach (ROFSTLookup.rodbi rodbi in _MyROFSTLookup.GetRODatabaseList(true)) { - rtnStr = _MyRODbID.ToString() + ":" + string.Format("{0}", rodbi.dbiID.ToString("X4")); + string rtnStr = $"{_MyRODbID}:{string.Format("{0}", rodbi.dbiID.ToString("X4"))}"; - if (rodbi.children != null) + if (rodbi.children != null) { foreach (ROFSTLookup.rochild roc in rodbi.children) { @@ -304,38 +284,37 @@ namespace Volian.Controls.Library continue; } - else if (rolkup is ROFSTLookup.rodbi) - { - ROFSTLookup.rodbi rodbi = (ROFSTLookup.rodbi)rolkup; + else if (rolkup is ROFSTLookup.rodbi rodbi) + { - //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); + //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; + if (rodbi.children != null) + { + foreach (ROFSTLookup.rochild roc in rodbi.children) + { + PutROChildrenInDictionary(_MyRODbID.ToString() + ":", roc); + } + } + else + { + ROList.Add($"{_MyRODbID}:{string.Format("{0}", rodbi.dbiID.ToString("X4"))}"); + } + } + else if (rolkup is ROFSTLookup.rochild rochild) + { + ch = rochild; + ROFSTLookup.rochild[] 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); + //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); - } - } + PutROChildrenInDictionary(_MyRODbID.ToString() + ":", rolkup); + } + } foreach (string k in AccIDROIDdic.Keys) { @@ -359,65 +338,64 @@ namespace Volian.Controls.Library 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); + 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) + //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 - // B2023-094: Don't crash when trying to add another ro if it has same key. Note that this is coming in as an RO but is really a group. - if (!AccIDROIDdic.ContainsKey(keystr))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]; + string rtnstr; + // 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 + // B2023-094: Don't crash when trying to add another ro if it has same key. Note that this is coming in as an RO but is really a group. + if (!AccIDROIDdic.ContainsKey(keystr)) 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); + //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); + // 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; - } + 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); - } - } + AccIDROIDdic.Add(keystr, rtnstr); + } + } - } - } + } + } private void GenerateROList() { string rtnStr = ""; - ROFSTLookup.rochild[] chld = null; - ROFSTLookup.rochild ch; + ROFSTLookup.rochild ch; ROList.Clear(); foreach (object rolkup in lstCheckedROs) @@ -427,26 +405,26 @@ namespace Volian.Controls.Library // 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")); + rtnStr = $"{_MyRODbID}:{string.Format("{0}", rodbi.dbiID.ToString("X4"))}"; ROList.Add(rtnStr); } continue; } - else if (rolkup is ROFSTLookup.rodbi) + else if (rolkup is ROFSTLookup.rodbi rodbi) { - rtnStr = _MyRODbID.ToString() + ":" + string.Format("{0}", ((ROFSTLookup.rodbi)rolkup).dbiID.ToString("X4")); + rtnStr = $"{_MyRODbID}:{string.Format("{0}", rodbi.dbiID.ToString("X4"))}"; } - else if (rolkup is ROFSTLookup.rochild) + else if (rolkup is ROFSTLookup.rochild rochild) { - ch = (ROFSTLookup.rochild)rolkup; + ch = rochild; //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; + ROFSTLookup.rochild[] chld = ch.children; - rtnStr = _MyRODbID.ToString() + ":" + GetROChildren(rolkup).TrimEnd(','); // GetROChildren(rolkup).TrimEnd(',') grabs the children of the selected item + rtnStr = $"{_MyRODbID}:{GetROChildren(rolkup).TrimEnd(',')}"; // GetROChildren(rolkup).TrimEnd(',') grabs the children of the selected item } ROList.Add(rtnStr); @@ -603,7 +581,7 @@ namespace Volian.Controls.Library labelX1.Visible = cmbxROUsageSort.Visible = cbxROUsage.Checked; // reset the RO tree and clear anything that was selected - advTreeROFillIn(true); + advTreeROFillIn(); lstCheckedROs.Clear(); cbxIncldMissingROs.Checked = false;// !cbxSummary.Checked; @@ -689,7 +667,6 @@ namespace Volian.Controls.Library return ""; } - //string roapp = Environment.GetEnvironmentVariable("roapp"); string roapp = Volian.Base.Library.ExeInfo.GetROEditorPath(); // get the path to the RO Editor Executable if (roapp == null) { @@ -703,7 +680,6 @@ namespace Volian.Controls.Library 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)); @@ -711,14 +687,14 @@ namespace Volian.Controls.Library } string cmpRptExePath = roapp.Substring(0, roapp.LastIndexOf("\\")) + "\\CmpRpt.exe "; - roDataFile = MyDVI.DocVersionAssociations[0].MyROFst.MyRODb.FolderPath + "\\" + roDataFile; + roDataFile = $"{MyDVI.DocVersionAssociations[0].MyROFst.MyRODb.FolderPath}\\{roDataFile}"; try { if (File.Exists(roDataFile)) File.Delete(roDataFile); Application.DoEvents(); - string fname = VlnSettings.TemporaryFolder + "\\ROCompleteRprt.txt"; + string fname = $"{VlnSettings.TemporaryFolder}\\ROCompleteRprt.txt"; FileInfo fi = new FileInfo(fname); using (StreamWriter sw = fi.CreateText()) { @@ -726,9 +702,9 @@ namespace Volian.Controls.Library sw.Close(); } - string roloc = "\"" + MyDVI.DocVersionAssociations[0].MyROFst.MyRODb.FolderPath + "\" \"/f=" + fname + "\""; + 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 + "\""; + 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 @@ -736,10 +712,9 @@ namespace Volian.Controls.Library DocVersionInfoList dvil = DocVersionInfoList.Get(); foreach (DocVersionInfo dvi in dvil) { - DocVersionConfig dvc = dvi.DocVersionConfig as DocVersionConfig; - if (dvc != null && dvc.Unit_Name != "" && dvc.Unit_Count > 1) // B2021-089 only pass in applicability info if defined for more than one unit - roloc += " \"/PC=" + dvc.Unit_Name + "\""; - break; + if (dvi.DocVersionConfig is DocVersionConfig dvc && dvc.Unit_Name != "" && dvc.Unit_Count > 1) // B2021-089 only pass in applicability info if defined for more than one unit + roloc += $" \"/PC={dvc.Unit_Name}\""; + break; } System.Diagnostics.Process p = System.Diagnostics.Process.Start(cmpRptExePath, roloc); @@ -752,7 +727,7 @@ namespace Volian.Controls.Library while (ex.InnerException != null) ex = ex.InnerException; string tmpmsg = ex.Message; - MessageBox.Show(tmpmsg, "RO Report Error: " + ex.GetType().Name); + MessageBox.Show(tmpmsg, $"RO Report Error: {ex.GetType().Name}"); } return roDataFile; } @@ -827,19 +802,6 @@ namespace Volian.Controls.Library #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; @@ -856,15 +818,19 @@ namespace Volian.Controls.Library { foreach (FolderInfo fic in fi.SortedChildFolders) { - DevComponents.AdvTree.Node newnode = new DevComponents.AdvTree.Node(); - newnode.Text = fic.ToString(); - newnode.Tag = fic; - par.Nodes.Add(newnode); + DevComponents.AdvTree.Node newnode = new DevComponents.AdvTree.Node + { + Text = fic.ToString(), + Tag = fic + }; + par.Nodes.Add(newnode); if (fic.HasChildren) // allow for '+' for tree expansion { - DevComponents.AdvTree.Node tnt = new DevComponents.AdvTree.Node(); - tnt.Text = DummyNodeText; - newnode.Nodes.Add(tnt); + DevComponents.AdvTree.Node tnt = new DevComponents.AdvTree.Node + { + Text = DummyNodeText + }; + newnode.Nodes.Add(tnt); } } } @@ -872,15 +838,17 @@ namespace Volian.Controls.Library { foreach (DocVersionInfo dv in fi.FolderDocVersions) { - DevComponents.AdvTree.Node newnode = new DevComponents.AdvTree.Node(); - newnode.Text = dv.ToString(); - newnode.Tag = dv; - newnode.Selectable = true; - newnode.CheckBoxAlignment = DevComponents.AdvTree.eCellPartAlignment.NearCenter; - newnode.CheckBoxStyle = eCheckBoxStyle.CheckBox; - newnode.CheckBoxThreeState = false; - newnode.CheckBoxVisible = true; - par.Nodes.Add(newnode); + DevComponents.AdvTree.Node newnode = new DevComponents.AdvTree.Node + { + Text = dv.ToString(), + Tag = dv, + Selectable = true, + CheckBoxAlignment = DevComponents.AdvTree.eCellPartAlignment.NearCenter, + CheckBoxStyle = eCheckBoxStyle.CheckBox, + CheckBoxThreeState = false, + CheckBoxVisible = true + }; + par.Nodes.Add(newnode); } } } @@ -913,31 +881,16 @@ namespace Volian.Controls.Library { if (lstCheckedDocVersions.Count == 0) Mydocversion = null; - // do this if either none, or more than one procedure set selected - //advTreeStepTypes.Nodes.Clear(); - //lstCheckedStepTypes.Clear(); - //lstCheckedStepTypesStr.Clear(); - //Node newnode = new DevComponents.AdvTree.Node(); - //newnode.Text = "....select a procedure set for types to appear..."; - //advTreeStepTypes.Nodes.Add(newnode); - //buildStepTypePannelTitle(); } } - //// Enable the RO combo list only if at least one procedure set node - //// is selected - //cmboTreeROs.Enabled = (lstCheckedDocVersions.Count > 0); - //gpFindROs.Enabled = cmboTreeROs.Enabled; - //SetupContextMenu(); - - //buildSetToSearchPanelTitle(); EnableOrDisablePrintButton(); } private void advTreeProcSets_AfterNodeSelect(object sender, AdvTreeNodeEventArgs e) { - DevComponents.AdvTree.Node n = advTreeProcSets.SelectedNode; - } + _ = advTreeProcSets.SelectedNode; + } private void advTreeProcSetsPreSelect() { @@ -998,9 +951,11 @@ namespace Volian.Controls.Library { if (rodbi.children != null && rodbi.children.Length > 0) { - DevComponents.AdvTree.Node tmp = new DevComponents.AdvTree.Node(); - tmp.Text = DummyNodeText; - tn.Nodes.Add(tmp); + DevComponents.AdvTree.Node tmp = new DevComponents.AdvTree.Node + { + Text = DummyNodeText + }; + tn.Nodes.Add(tmp); } } @@ -1015,99 +970,97 @@ namespace Volian.Controls.Library 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; - ROFSTLookup.rochild[] chld = null; + ROFSTLookup.rochild[] chld; + if (tn.Tag is ROFSTLookup.rodbi db) + { - if (tn.Tag is ROFSTLookup.rodbi) + //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 ch) + { + + //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 + { + 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) { - 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 - { - 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); 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); + // 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) - { - // Ignore: Junk Scenario - continue; - } - // B2023-094: don't crash if chld[i].children count is 0, signals an empty group - else if (chld[i].value == null && (cbxROUsage.Checked || (chld[i].children != null && chld[i].children.Length > 0 && chld[i].children[0].ParentID != 0))) - { - tmp = new DevComponents.AdvTree.Node(); - tmp.Text = chld[i].title; - tmp.Tag = chld[i]; - tmp.CheckBoxVisible = true; - int index = FindIndex(tn.Nodes, tmp.Text); - tn.Nodes.Insert(index, 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]; - tmp.CheckBoxVisible = true; - int index = FindIndex(tn.Nodes, tmp.Text); - tn.Nodes.Insert(index, tmp); - } - } + Node tmp; + // if this is a group, i.e. type 0, add a dummy node + if (chld[i].type == 0 && chld[i].children == null) + { + // Ignore: Junk Scenario + continue; + } + // B2023-094: don't crash if chld[i].children count is 0, signals an empty group + else if (chld[i].value == null && (cbxROUsage.Checked || (chld[i].children != null && chld[i].children.Length > 0 && chld[i].children[0].ParentID != 0))) + { + tmp = new DevComponents.AdvTree.Node + { + Text = chld[i].title, + Tag = chld[i], + CheckBoxVisible = true + }; + int index = FindIndex(tn.Nodes, tmp.Text); + tn.Nodes.Insert(index, tmp); + DevComponents.AdvTree.Node sub = new DevComponents.AdvTree.Node + { + Text = DummyNodeText + }; + tmp.Nodes.Add(sub); + } + else + { + tmp = new DevComponents.AdvTree.Node + { + Text = chld[i].title, + Tag = chld[i], + CheckBoxVisible = true + }; + int index = FindIndex(tn.Nodes, tmp.Text); + tn.Nodes.Insert(index, tmp); + } + } } } private void advTreeRO_AfterExpandorCollapse(object sender, AdvTreeNodeEventArgs e) { Node bottomNode = BottomTreeNode(advTreeRO.Nodes); - Node lastNode = advTreeRO.Nodes[advTreeRO.Nodes.Count - 1]; + _ = 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)); + int top = advTreeRO.Nodes[0].Bounds.Top; + int hScrollBarHeight = advTreeRO.HScrollBar != null ? advTreeRO.HScrollBar.Height : 0; + int 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(); + topNode?.EnsureVisible(); } } @@ -1164,118 +1117,59 @@ namespace Volian.Controls.Library public class DisplayReportsEventArgs { - #region Fields + #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 + #endregion - #region Properties + #region Properties - public string ReportTitle + public string ReportTitle { get; set; } + + public string TypesSelected { get; set; } + + public ICollection MyItemInfoList { get; set; } + + public bool SortUsageByProcedure { get; set; } + + public string RODataFile { get; set; } = ""; + + public bool CompleteROReport { get; set; } = true; + + public ROFSTLookup RofstLookup { get; set; } + + public List ROListForReport { get; set; } + + public bool IncludeMissingROs { get; set; } = true; + + public bool ConvertCaretToDelta { get; set; } = true; + + public bool IncludeEmptyROFields { get; set; } = true; + + public string PaperSize // C2020-002 paper size is now set in the format files + { get; set; } = "Letter"; + + #endregion + + #region Constructors + + /// + /// RO Usage Report + /// + /// + /// + /// + /// + /// + /// + public DisplayReportsEventArgs(string reportTitle, string typesSelected, ICollection myItemInfoList, bool sortByProcedure, bool includeMissingROs, string paperSize) { - get { return _ReportTitle; } - set { _ReportTitle = value; } - } - - public string TypesSelected - { - get { return _TypesSelected; } - set { _TypesSelected = value; } - } - - public ICollection MyItemInfoList - { - get { return _MyItemInfoList; } - set { _MyItemInfoList = value; } - } - - public bool SortUsageByProcedure - { - get { return _SortUsageByProcedure; } - set { _SortUsageByProcedure = value; } - } - - public string RODataFile - { - get { return _RODataFile; } - set { _RODataFile = value; } - } - - public bool CompleteROReport - { - get { return _CompleteROReport; } - set { _CompleteROReport = value; } - } - - public ROFSTLookup RofstLookup - { - get { return _rofstLookup; } - set { _rofstLookup = value; } - } - - public List ROListForReport - { - get { return _ROListForReport; } - set { _ROListForReport = value; } - } - - public bool IncludeMissingROs - { - get { return _IncludeMissingROs; } - set { _IncludeMissingROs = value; } - } - - public bool ConvertCaretToDelta - { - get { return _ConvertCaretToDelta; } - set { _ConvertCaretToDelta = value; } - } - - public bool IncludeEmptyROFields - { - get { return _IncludeEmptyROFields; } - set { _IncludeEmptyROFields = value; } - } - - 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) - { - _ReportTitle = reportTitle; - _TypesSelected = typesSelected; - _MyItemInfoList = myItemInfoList; - _SortUsageByProcedure = sortByProcedure; - _IncludeMissingROs = includeMissingROs; - _PaperSize = paperSize; // C2020-002 paper size is now set in the format files + ReportTitle = reportTitle; + TypesSelected = typesSelected; + MyItemInfoList = myItemInfoList; + SortUsageByProcedure = sortByProcedure; + IncludeMissingROs = includeMissingROs; + PaperSize = paperSize; // C2020-002 paper size is now set in the format files } /// @@ -1291,14 +1185,14 @@ namespace Volian.Controls.Library /// public DisplayReportsEventArgs(string reportTitle, string typesSelected, string roDataFile, ROFSTLookup rofstLookUp, bool completeROReport, bool convertCaretToDelta, bool includeEmptyROFields, string paperSize) { - _ReportTitle = reportTitle; - _TypesSelected = typesSelected; - _RODataFile = roDataFile; - _CompleteROReport = completeROReport; - _ConvertCaretToDelta = convertCaretToDelta; - _rofstLookup = rofstLookUp; - _IncludeEmptyROFields = includeEmptyROFields; - _PaperSize = paperSize; // C2020-002 paper size is now set in the format files + ReportTitle = reportTitle; + TypesSelected = typesSelected; + RODataFile = roDataFile; + CompleteROReport = completeROReport; + ConvertCaretToDelta = convertCaretToDelta; + RofstLookup = rofstLookUp; + IncludeEmptyROFields = includeEmptyROFields; + PaperSize = paperSize; // C2020-002 paper size is now set in the format files } /// @@ -1311,11 +1205,11 @@ namespace Volian.Controls.Library /// public DisplayReportsEventArgs(string reportTitle, string typesSelected, ROFSTLookup rofstLookUp, List roListForReport, string paperSize) { - _ReportTitle = reportTitle; - _TypesSelected = typesSelected; - _rofstLookup = rofstLookUp; - _ROListForReport = roListForReport; - _PaperSize = paperSize; // C2020-002 paper size is now set in the format files + ReportTitle = reportTitle; + TypesSelected = typesSelected; + RofstLookup = rofstLookUp; + ROListForReport = roListForReport; + PaperSize = paperSize; // C2020-002 paper size is now set in the format files } #endregion @@ -1334,13 +1228,13 @@ namespace Volian.Controls.Library public List GetList(string s1) { List SB1 = new List(); - string st1, st2, st3; + string st1; st1 = ""; bool flag = char.IsDigit(s1[0]); foreach (char c in s1) { - if (flag != char.IsDigit(c) || !(char.IsDigit(c) || char.IsLetter(c)))// || c == '\'') + if (flag != char.IsDigit(c) || !(char.IsDigit(c) || char.IsLetter(c))) { if (st1 != "") SB1.Add(st1); @@ -1376,10 +1270,6 @@ namespace Volian.Controls.Library { return 0; } - int len1 = s1.Length; - int len2 = s2.Length; - int marker1 = 0; - int marker2 = 0; // Walk through two the strings with two markers. List str1 = GetList(s1); @@ -1395,18 +1285,16 @@ namespace Volian.Controls.Library str2.Add(""); } } - int x1 = 0; int res = 0; int x2 = 0; string y2 = ""; - bool status = false; - string y1 = ""; bool s1Status = false; bool s2Status = false; - //s1status ==false then string ele int; - //s2status ==false then string ele int; - int result = 0; + int x1 = 0; int x2 = 0; + bool s1Status; bool s2Status; + //s1status ==false then string else int; + //s2status ==false then string else int; + int result = 0; for (int i = 0; i < str1.Count && i < str2.Count; i++) { - status = int.TryParse(str1[i].ToString(), out res); - if (res == 0) + _ = int.TryParse(str1[i].ToString(), out int res); + if (res == 0) { - y1 = str1[i].ToString(); s1Status = false; } else @@ -1415,10 +1303,9 @@ namespace Volian.Controls.Library s1Status = true; } - status = int.TryParse(str2[i].ToString(), out res); - if (res == 0) + _ = int.TryParse(str2[i].ToString(), out res); + if (res == 0) { - y2 = str2[i].ToString(); s2Status = false; } else diff --git a/PROMS/Volian.Controls.Library/DisplayTabControl.cs b/PROMS/Volian.Controls.Library/DisplayTabControl.cs index c332a18a..0d70607b 100644 --- a/PROMS/Volian.Controls.Library/DisplayTabControl.cs +++ b/PROMS/Volian.Controls.Library/DisplayTabControl.cs @@ -1,12 +1,9 @@ using System; using System.Collections.Generic; -using System.ComponentModel; using System.Drawing; using System.Data; -using System.Text; using System.Windows.Forms; using VEPROMS.CSLA.Library; -using Volian.Controls.Library; using DevComponents.DotNetBar; using JR.Utils.GUI.Forms; using Volian.Base.Library; @@ -59,14 +56,8 @@ namespace Volian.Controls.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion - private static bool _SyncronizeEnahnced = false; - public static bool SyncronizeEnhanced - { - get { return DisplayTabControl._SyncronizeEnahnced; } - set { DisplayTabControl._SyncronizeEnahnced = value; } - } - - private static Dictionary _AllDTCs = new Dictionary(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private static Dictionary _AllDTCs = new Dictionary(); private int _VersionID = 0; // zero tells us to PROMS just opened and no procedure was selected yet so use the main proms window // when the first procedure is opened, the VersionID is set and added to _AllDTCs @@ -75,11 +66,11 @@ namespace Volian.Controls.Library get { return _VersionID; } set { - if ((int)value != 0) + if (value != 0) { if (!_AllDTCs.ContainsKey((int)value)) { - _AllDTCs.Add((int)value, this); + _AllDTCs.Add(value, this); if (_VersionID == 0) _VersionID = value; else @@ -148,9 +139,8 @@ namespace Volian.Controls.Library public event ItemSelectedChangedEvent OpenInSeparateWindow; public void OnOpenInSeparateWindow(ItemSelectedChangedEventArgs args) { - if (OpenInSeparateWindow != null) - OpenInSeparateWindow(this, args); - } + OpenInSeparateWindow?.Invoke(this, args); + } // C2020-033: Provide way to expand/fill in Search/Incoming Transition panel public event DisplayTabControlEditorSearchIncTransEvent SearchIncTrans; public ItemInfo OnSearchIncTrans(object sender, vlnTreeItemInfoEventArgs args) @@ -161,32 +151,30 @@ namespace Volian.Controls.Library public event ItemSelectedChangedEvent RefreshEnhancedDocument; public void OnRefreshEnhancedDocument(ItemSelectedChangedEventArgs args) { - if (RefreshEnhancedDocument != null) - RefreshEnhancedDocument(this, args); - } + RefreshEnhancedDocument?.Invoke(this, args); + } public event DisplayTabControlStatusEvent StatusChanged; public void ONStatusChanged(object Sender, DisplayTabControlStatusEventArgs args) { - if (StatusChanged != null) StatusChanged(Sender, args); - } + StatusChanged?.Invoke(Sender, args); + } public event DisplayTabControlEvent ToggleRibbonExpanded; public void OnToggleRibbonExpanded(object sender, EventArgs args) { - if (ToggleRibbonExpanded != null) ToggleRibbonExpanded(sender, args); - } + ToggleRibbonExpanded?.Invoke(sender, args); + } public event DisplayTabControlEvent SelectedDisplayTabItemChanged; public void OnSelectedDisplayTabItemChanged(object sender, EventArgs args) { - if (SelectedDisplayTabItemChanged != null) SelectedDisplayTabItemChanged(sender, args); - } + SelectedDisplayTabItemChanged?.Invoke(sender, args); + } // C2015-022 added copystep event to commuicate with child windows public event ItemChangedEventHandler CopyStepSelected; public void OnCopyStepSelected(ItemChangedEventArgs args) { - if (CopyStepSelected != null) - CopyStepSelected(this, args); - } + CopyStepSelected?.Invoke(this, args); + } #region Private Fields @@ -228,6 +216,8 @@ namespace Volian.Controls.Library } private StepRTB _MyStepRTB = null; private bool _RibbonExpanded = true; + + //Keeping for possible future references public StepRTB MyStepRTB { get { return _MyStepRTB; } @@ -302,8 +292,8 @@ namespace Volian.Controls.Library /// internal void OnItemClick(object sender, StepPanelEventArgs args) { - if (ItemClick != null) ItemClick(sender, args); - } + ItemClick?.Invoke(sender, args); + } /// /// This occurs when the user moves onto or off of a link within a RichTextBox /// or moves between RichTextBoxes or Pages. @@ -408,8 +398,8 @@ namespace Volian.Controls.Library _MyEditItem = null; _MyStepRTB = null; } - if (ItemSelectedChanged != null) ItemSelectedChanged(sender, args); - } + ItemSelectedChanged?.Invoke(sender, args); + } void _MyStepRTB_Disposed(object sender, EventArgs e) { @@ -476,8 +466,7 @@ namespace Volian.Controls.Library void DisplayTabControl_Resize(object sender, EventArgs e) { // If the currently selected Item is in a Step, then adjust the scroll as necessary to keep it visible - if (_MyEditItem != null) - _MyEditItem.ItemShow(); + _MyEditItem?.ItemShow(); } private void SetupBar(Bar myBar) { @@ -531,15 +520,11 @@ namespace Volian.Controls.Library DisplayTabItem dti = e.DockContainerItem as DisplayTabItem; if (dti != null && dti.MyStepTabPanel != null) dti.MyStepTabPanel.MyStepPanel.Dispose(); - DisplayTabItem myTabItem = e.DockContainerItem as DisplayTabItem; - if (myTabItem != null) - { - if (myTabItem.MyDSOTabPanel != null) - { - myTabItem.MyDSOTabPanel.CloseDSO(); - } - } - MySessionInfo.CheckInItem(dti.OwnerID); + if (e.DockContainerItem is DisplayTabItem myTabItem) + { + myTabItem.MyDSOTabPanel?.CloseDSO(); + } + MySessionInfo.CheckInItem(dti.OwnerID); if (((Bar)sender).Items == null) return; if (((Bar)sender).Items.Count == 1)// Remove bar if last item is closed... { @@ -551,17 +536,16 @@ namespace Volian.Controls.Library OnEnableDisableStepProperties(new StepTabRibbonEventArgs(MyEditItem.MyItemInfo, 0, E_ViewMode.Edit)); } - Bar bar = sender as Bar; - if (bar != null) - { - if (dotNetBarManager1.Bars.Contains(bar.Name)) - dotNetBarManager1.Bars.Remove(bar); - ActivateRemainingTab(); - } - // B2018-123 the last tab in the main window was closed. - // remove the procedure version id from the _AllDTCs dictionary - // reset VersionID to zero so that we know the main window is available - _AllDTCs.Remove(VersionID); + if (sender is Bar bar) + { + if (dotNetBarManager1.Bars.Contains(bar.Name)) + dotNetBarManager1.Bars.Remove(bar); + ActivateRemainingTab(); + } + // B2018-123 the last tab in the main window was closed. + // remove the procedure version id from the _AllDTCs dictionary + // reset VersionID to zero so that we know the main window is available + _AllDTCs.Remove(VersionID); VersionID = 0; } else @@ -574,15 +558,14 @@ namespace Volian.Controls.Library public event StepTabRibbonEvent EnableDisableStepProperties; private void OnEnableDisableStepProperties(StepTabRibbonEventArgs args) { - if (EnableDisableStepProperties != null) - EnableDisableStepProperties(this, args); + EnableDisableStepProperties?.Invoke(this, args); } #endregion #region Public Methods public void RefreshItem(ItemInfo myItemInfo) { ItemInfo proc = myItemInfo.MyProcedure; // Find procedure Item - string key = "Item - " + proc.ItemID.ToString(); + string key = $"Item - {proc.ItemID}"; if (_MyDisplayTabItems.ContainsKey(key)) // If procedure page open use it { @@ -717,9 +700,8 @@ namespace Volian.Controls.Library if (EDOfficeViewerX == null || EDWordCtrl == null) { - MessageBox.Show("Edraw needs to be installed or reinstalled on this device. " + Environment.NewLine + "" + Environment.NewLine + - "Please contact your IT Administrator to install and register Edraw that was provided with the PROMS Installation media. If additional support is needed, please contact Volian.", "Error in Word section", - MessageBoxButtons.OK, MessageBoxIcon.Exclamation); + MessageBox.Show($"Edraw needs to be installed or reinstalled on this device. {Environment.NewLine}{Environment.NewLine}Please contact your IT Administrator to install and register Edraw that was provided with the PROMS Installation media. If additional support is needed, please contact Volian.", + "Error in Word section", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return null; } else @@ -730,19 +712,13 @@ namespace Volian.Controls.Library } } - public T GetValue(string registryKeyPath, string value, T defaultValue = default(T)) - { - T retVal = default(T); - - retVal = (T)Registry.GetValue(registryKeyPath, value, defaultValue); - - return retVal; - } - public bool PasteRTBItem(ItemInfo myItemInfo, int copyStartID, ItemInfo.EAddpingPart pasteType, int type) + public T GetValue(string registryKeyPath, string value, T defaultValue = default) => (T)Registry.GetValue(registryKeyPath, value, defaultValue); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping type for future usage")] + public bool PasteRTBItem(ItemInfo myItemInfo, int copyStartID, ItemInfo.EAddpingPart pasteType, int type) { CleanUpClosedItems(); ItemInfo proc = myItemInfo.MyProcedure; // Find procedure Item - string key = "Item - " + proc.ItemID.ToString(); + string key = $"Item - {proc.ItemID}"; if (_MyDisplayTabItems.ContainsKey(key) && pasteType != ItemInfo.EAddpingPart.Replace) // If procedure page open use it unless replace { @@ -769,7 +745,7 @@ namespace Volian.Controls.Library EditItem ei = edtitm.PasteReplace(copyStartID); if (ei == null) { - CloseTabItem(_MyDisplayTabItems["Item - " + myItemInfo.ItemID.ToString()]); //Grab itemID and set to close open tab. + CloseTabItem(_MyDisplayTabItems[$"Item - {myItemInfo.ItemID}"]); //Grab itemID and set to close open tab. return false; //B2017-179 PasteReplace will return null if was aborted } @@ -788,7 +764,7 @@ namespace Volian.Controls.Library else if (_MyDisplayTabItems.ContainsKey(key) && pasteType == ItemInfo.EAddpingPart.Replace) { // B2024-038: changed tab key to procedure (was item, which caused crash if section) - CloseTabItem(_MyDisplayTabItems["Item - " + proc.ItemID.ToString()]); //Grab itemID and set to close open tab. + CloseTabItem(_MyDisplayTabItems[$"Item - {proc.ItemID}"]); //Grab itemID and set to close open tab. return false; //B2017-179 PasteReplace will return null if was aborted } return false; @@ -800,7 +776,7 @@ namespace Volian.Controls.Library //removeitem! ItemInfo proc = myItemInfo.MyProcedure; // Find procedure Item - string key = "Item - " + proc.ItemID.ToString(); + string key = $"Item - {proc.ItemID}"; if (_MyDisplayTabItems.ContainsKey(key)) // If procedure page open use it { @@ -826,7 +802,7 @@ namespace Volian.Controls.Library { CleanUpClosedItems(); ItemInfo proc = myItemInfo.MyProcedure; // Find procedure Item - string key = "Item - " + proc.ItemID.ToString(); + string key = $"Item - {proc.ItemID}"; if (_MyDisplayTabItems.ContainsKey(key)) // If procedure page open use it { @@ -875,17 +851,16 @@ namespace Volian.Controls.Library string key = "Doc - "; // there is no entry if it is an auto table of contents: if (myItemInfo.MyContent.MyEntry != null) - key = key + myItemInfo.MyContent.MyEntry.MyDocument.DocID.ToString(); + key += myItemInfo.MyContent.MyEntry.MyDocument.DocID.ToString(); else - key = key + "0"; - DisplayTabItem myTabItem = null; - if (_MyDisplayTabItems.ContainsKey(key)) // If page open, close it + key += "0"; + if (_MyDisplayTabItems.ContainsKey(key)) // If page open, close it { - myTabItem = _MyDisplayTabItems[key]; - if (myTabItem.MyDSOTabPanel != null) + _ = _MyDisplayTabItems[key]; + if (((DisplayTabItem)null).MyDSOTabPanel != null) { - myTabItem.MyDSOTabPanel.IsBeingDeleted = isBeingDeleted; - CloseTabItem(myTabItem); + ((DisplayTabItem)null).MyDSOTabPanel.IsBeingDeleted = isBeingDeleted; + CloseTabItem(null); } } } @@ -893,23 +868,22 @@ namespace Volian.Controls.Library public void CloseTabItem(DisplayTabItem myTabItem) { if (myTabItem.ContainerControl == null) return; - Bar b = myTabItem.ContainerControl as Bar; - if (b != null) - { - try + if (myTabItem.ContainerControl is Bar b) + { + try { b.CloseDockTab(myTabItem); } - catch - { - //This is to work around a bug inside 3rd party DotNetBar - //The bug occurs when events happen out of order and it tries - //to remove a TabItem from the Collection the has already been removed - } + catch + { + //This is to work around a bug inside 3rd party DotNetBar + //The bug occurs when events happen out of order and it tries + //to remove a TabItem from the Collection the has already been removed + } RemoveItem(myTabItem); - } - } + } + } /// /// Look for a tab and set it to active. /// @@ -948,10 +922,9 @@ namespace Volian.Controls.Library if (_RemovedDisplayTabItems.Contains(myBar.SelectedDockContainerItem as DisplayTabItem)) myBar.SelectedDockContainerItem = FindRemainingTab(myBar); myBar.SelectedDockContainerItem.Selected = true; - StepTabPanel pnl = myBar.SelectedDockContainerItem.Control as StepTabPanel; - if (pnl != null) - pnl.MyStepPanel.ItemShow(); - } + if (myBar.SelectedDockContainerItem.Control is StepTabPanel pnl) + pnl.MyStepPanel.ItemShow(); + } } #endregion #region Public Properties @@ -1035,7 +1008,7 @@ namespace Volian.Controls.Library PnlCaret.Visible = false; } // B2019-161 When tracking timing time this action - private static VolianTimer _TimeActivity = new VolianTimer("DisplayTabControl.cs tmrCaret_Tick", 881); + private static readonly VolianTimer _TimeActivity = new VolianTimer("DisplayTabControl.cs tmrCaret_Tick", 881); private void tmrCaret_Tick(object sender, EventArgs e) { @@ -1045,22 +1018,6 @@ namespace Volian.Controls.Library } #endregion #region Private Methods - ///// - ///// Gets and sets the SelectedDisplayTabItem (Active Tab) - ///// - //public DisplayTabItem SelectedDisplayTabItem1 - //{ - // get { return (DisplayTabItem)_MyBar.SelectedDockContainerItem; } - // set - // { - // //Volian.Base.Library.vlnStackTrace.ShowStackLocal("SelectedDisplayTabItem"); - // if (value != null) - // { - // value.Focus(); - // value.Selected = true; - // } - // } - //} public void SelectDisplayTabItem(DisplayTabItem myDisplayTabItem) { if (myDisplayTabItem != null) @@ -1112,11 +1069,10 @@ namespace Volian.Controls.Library if (myBar == null) myBar = b;// Remember the first available bar if a specific bar cannot be found foreach (object itm in b.Items) { - DisplayTabItem myTabItem = itm as DisplayTabItem; - if (myTabItem != null && myTabItem.MyStepTabPanel != null && myItemInfo != null) - if (myTabItem.MyStepTabPanel.MyProcedureItemInfo.ItemID == myItemInfo.MyProcedure.ItemID) - return b; - } + if (itm is DisplayTabItem myTabItem && myTabItem.MyStepTabPanel != null && myItemInfo != null) + if (myTabItem.MyStepTabPanel.MyProcedureItemInfo.ItemID == myItemInfo.MyProcedure.ItemID) + return b; + } } } if (myBar == null) @@ -1125,7 +1081,7 @@ namespace Volian.Controls.Library _UniqueBarCount++; myBar = BarUtilities.CreateDocumentBar(); myBar.DockTabClosing += new DockTabClosingEventHandler(myBar_DockTabClosing); - myBar.Name = "barDocuments" + _UniqueBarCount.ToString(); + myBar.Name = $"barDocuments{_UniqueBarCount}"; fillDocDockSite.GetDocumentUIManager().Dock(myBar); SetupBar(myBar); } @@ -1141,11 +1097,10 @@ namespace Volian.Controls.Library if (myBar == null) myBar = b;// Remember the first available bar if a specific bar cannot be found foreach (object itm in b.Items) { - DisplayTabItem myTabItem = itm as DisplayTabItem; - if (myTabItem != null && myTabItem.MyStepTabPanel != null && myTabItem.MyStepTabPanel.MyProcedureItemInfo != null) - if (myTabItem.MyStepTabPanel.MyProcedureItemInfo.ItemID == myItemInfo.MyProcedure.ItemID) - return myTabItem.MyStepTabPanel; - } + if (itm is DisplayTabItem myTabItem && myTabItem.MyStepTabPanel != null && myTabItem.MyStepTabPanel.MyProcedureItemInfo != null) + if (myTabItem.MyStepTabPanel.MyProcedureItemInfo.ItemID == myItemInfo.MyProcedure.ItemID) + return myTabItem.MyStepTabPanel; + } } } return null; @@ -1173,8 +1128,7 @@ namespace Volian.Controls.Library if (stp != null) { EditItem ei = stp.SelectedEditItem; - if (ei != null) - ei.SaveCurrentAndContents(); + ei?.SaveCurrentAndContents(); } } } @@ -1182,41 +1136,17 @@ namespace Volian.Controls.Library public DisplayTabItem GetProcDisplayTabItem(ItemInfo myItemInfo) { ItemInfo proc = myItemInfo.MyProcedure; // Find procedure Item - string key = "Item - " + proc.ItemID.ToString(); - DisplayTabItem pg = null; + string key = $"Item - {proc.ItemID}"; if (_MyDisplayTabItems.ContainsKey(key)) // If procedure page open use it return _MyDisplayTabItems[key]; return null; } - /// - /// This opens a Step page based upon a ItemInfo. - /// - /// - /// - /// - //public bool IsItemInfoProcedureOpen(ItemInfo ii) - // if (ii == null) return false; //{ - // ItemInfo proc = ii.MyProcedure; // Find procedure Item - // if (dicEnhancedDocuments.ContainsKey(ii.MyProcedure.MyDocVersion)) - // { - // frmEnhanced frm = dicEnhancedDocuments[ii.MyProcedure.MyDocVersion]; - // string key = "Item - " + proc.ItemID.ToString(); - // if (frm.MyDisplayTabClntrol._MyDisplayTabItems.ContainsKey(key)) - // return true; - // } - // // return true; - // //return false; - // return false; - //} - //public Dictionary dicEnhancedDocuments = new Dictionary(); - private DisplayTabItem OpenStepTabPage(ItemInfo myItemInfo, bool setFocus, bool viewonlymode = false) { ItemInfo proc = myItemInfo.MyProcedure; // Find procedure Item - string key = "Item - " + proc.ItemID.ToString(); - DisplayTabItem pg = null; - - if (_MyDisplayTabItems.ContainsKey(key)) // If procedure page open use it + string key = $"Item - {proc.ItemID}"; + DisplayTabItem pg; + if (_MyDisplayTabItems.ContainsKey(key)) // If procedure page open use it { pg = _MyDisplayTabItems[key]; if (setFocus) @@ -1237,9 +1167,6 @@ namespace Volian.Controls.Library HandleChangeId(myItemInfo, pg); SelectDisplayTabItem(pg); - // If this is an enhanced document, check for refresh of text items: - //if (myItemInfo.IsProcedure) - //{ // make the myiteminfo into a procedureinfo (depending on where this is called from, just // casting it crashed: ProcedureInfo pi = ProcedureInfo.Get(myItemInfo.MyProcedure.ItemID); @@ -1254,7 +1181,6 @@ namespace Volian.Controls.Library pi.EnhancedProcedureRefreshTextDifferences(iil); } } - //} } pg.MyStepTabPanel.MyProcedureItemInfo = proc; @@ -1269,11 +1195,6 @@ namespace Volian.Controls.Library } Application.DoEvents(); pg.SelectedItemInfo = myItemInfo; // Select the item - //StepConfig sc = new StepConfig(myItemInfo.MyContent.Config); - //if (sc.Step_SourceToBackground != null || sc.Step_SourceToDeviation != null) - // pg.MyStepTabPanel.MyStepTabRibbon.btnEnhancedDocSync.Visible = true; - //else - // pg.MyStepTabPanel.MyStepTabRibbon.btnEnhancedDocSync.Visible = false; return pg; } private bool _SyncEnhancedDocuments; @@ -1294,7 +1215,7 @@ namespace Volian.Controls.Library { if (!Volian.Base.Library.VlnSettings.GetCommandFlag("NOCHGID")) { - dlgChgId dlgCI = new dlgChgId(this); //, null); + dlgChgId dlgCI = new dlgChgId(this); dlgCI.ShowDialog(this); } ItemsChangeIds.Add(myItemInfo.MyProcedure.ItemID, ChgId); @@ -1303,11 +1224,6 @@ namespace Volian.Controls.Library private void SetChangeId(string chgid, DisplayTabItem pg, ItemInfo ii) { - //if (pg == null || pg.MyStepTabPanel == null) - //{ - // ChgId = null; - // return; - //} if (pg != null && pg.MyStepTabPanel != null) pg.MyStepTabPanel.MyStepTabRibbon.SetChangeId(chgid, ii); ChgId = chgid; } @@ -1315,7 +1231,7 @@ namespace Volian.Controls.Library private bool LibDocAlreadyOpen(ItemInfo myItemInfo) { EntryInfo myEntry = myItemInfo.MyContent.MyEntry; - string key = "Doc - " + myEntry.DocID; + string key = $"Doc - {myEntry.DocID}"; DisplayTabItem pg = null; return LibDocAlreadyOpen(myItemInfo, key, ref pg, false); } @@ -1359,7 +1275,7 @@ namespace Volian.Controls.Library { DisplayTabItem pg = null; EntryInfo myEntry = myItemInfo.MyContent.MyEntry; - string key = "Doc - " + myEntry.DocID; + string key = $"Doc - {myEntry.DocID}"; bool libDocAlreadyOpen = LibDocAlreadyOpen(myItemInfo, key, ref pg, true); if (!libDocAlreadyOpen && pg == null) { @@ -1368,8 +1284,6 @@ namespace Volian.Controls.Library FlexibleMessageBox.Show("Too many Word Documents Open. Please close one of the Documents before attempting to open another"); return null; } - //if ((myItemInfo.MyContent.MyEntry.MyDocument.LibTitle ?? "") != "") - // MessageBox.Show("WARNING: All edits made to this Library Document will be applied to all uses of the Document"); pg = new DisplayTabItem(this.components, this, myItemInfo, key); // Open a new document page // B2917-219 if MyEdWord is null that means we had trouble opening the word attachment and either a blank document was created or a previous version was recovered // so we now we want to open the now blank or recovered attachment @@ -1391,21 +1305,21 @@ namespace Volian.Controls.Library { _MyBar = GetParentBar(null); // B2016-131 - allow open of a non-referenced library document CleanUpClosedItems(); - DisplayTabItem pg = null; - string key = "Doc - " + myDocumentInfo.DocID; - if (_MyDisplayTabItems.ContainsKey(key)) // If document page open use it - pg = _MyDisplayTabItems[key]; - else - { - if (DSOTabPanel.Count > DSOTabPanel.MSWordLimit) //18) // Limit the number of open document pages to 18 - { - FlexibleMessageBox.Show("Too many Word Documents Open. Please close one of the Documents before attempting to open another"); - return null; - } - pg = new DisplayTabItem(this.components, this, myDocumentInfo, key); // Open a new document page - _MyDisplayTabItems.Add(key, pg); - } - SelectDisplayTabItem(pg); + string key = $"Doc - {myDocumentInfo.DocID}"; + DisplayTabItem pg; + if (_MyDisplayTabItems.ContainsKey(key)) // If document page open use it + pg = _MyDisplayTabItems[key]; + else + { + if (DSOTabPanel.Count > DSOTabPanel.MSWordLimit) //18) // Limit the number of open document pages to 18 + { + FlexibleMessageBox.Show("Too many Word Documents Open. Please close one of the Documents before attempting to open another"); + return null; + } + pg = new DisplayTabItem(this.components, this, myDocumentInfo, key); // Open a new document page + _MyDisplayTabItems.Add(key, pg); + } + SelectDisplayTabItem(pg); pg.MyDSOTabPanel.EnterPanel(); return pg; } @@ -1422,12 +1336,10 @@ namespace Volian.Controls.Library _MyDisplayTabItems.Remove(myDisplayTabItem.MyKey); // Dispose of the procedure tab panel - if (myDisplayTabItem.MyStepTabPanel != null) - myDisplayTabItem.MyStepTabPanel.Dispose(); + myDisplayTabItem.MyStepTabPanel?.Dispose(); // Dispose of the MS Word Panel - if (myDisplayTabItem.MyDSOTabPanel != null) - myDisplayTabItem.MyDSOTabPanel.CloseDSO(); + myDisplayTabItem.MyDSOTabPanel?.CloseDSO(); components.Remove(myDisplayTabItem); myDisplayTabItem.Dispose(); diff --git a/PROMS/Volian.Controls.Library/DisplayTabItem.cs b/PROMS/Volian.Controls.Library/DisplayTabItem.cs index 8206bf3c..576292ac 100644 --- a/PROMS/Volian.Controls.Library/DisplayTabItem.cs +++ b/PROMS/Volian.Controls.Library/DisplayTabItem.cs @@ -1,9 +1,5 @@ using System; using System.ComponentModel; -using System.Collections.Generic; -using System.Diagnostics; -using System.Text; -using System.Drawing; using VEPROMS.CSLA.Library; using JR.Utils.GUI.Forms; @@ -12,29 +8,21 @@ namespace Volian.Controls.Library public partial class DisplayTabItem : DevComponents.DotNetBar.DockContainerItem { #region Private Fields - private DisplayTabControl _MyDisplayTabControl; - private ItemInfo _MyItemInfo; - private StepTabPanel _MyStepTabPanel; - private string _MyKey; - private DSOTabPanel _MyDSOTabPanel; - private DocumentInfo _MyDocumentInfo; + private readonly DisplayTabControl _MyDisplayTabControl; + private readonly ItemInfo _MyItemInfo; + private readonly string _MyKey; + private readonly DocumentInfo _MyDocumentInfo; - #endregion - #region Properties - /// - /// ItemInfo associated with this DisplayTabItem - /// - private int _OwnerID; - public int OwnerID - { - get { return _OwnerID; } - set { _OwnerID = value; } - } - public ItemInfo MyItemInfo + #endregion + #region Properties + /// + /// ItemInfo associated with this DisplayTabItem + /// + public int OwnerID { get; set; } + public ItemInfo MyItemInfo { get { return _MyItemInfo; } - //set { _MyItemInfo = value; } } /// /// get Key Either: @@ -45,48 +33,29 @@ namespace Volian.Controls.Library { get { return _MyKey; } } - /// - /// Related StepTabPanel for a Step page - /// - public StepTabPanel MyStepTabPanel - { - get { return _MyStepTabPanel; } - set { _MyStepTabPanel = value; } - } - /// - /// Related DSOTabPanle for a Word page - /// - public DSOTabPanel MyDSOTabPanel - { - get { return _MyDSOTabPanel; } - set { _MyDSOTabPanel = value; } - } - private string _MyUserRole; - public string MyUserRole - { - get { return _MyUserRole; } - set { _MyUserRole = value; } - } - private bool _Closed = false; - public bool Closed - { - get { return _Closed; } - set { _Closed = value; } - } - /// - /// Current SelectedItemInfo for this page - /// - public ItemInfo SelectedItemInfo + /// + /// Related StepTabPanel for a Step page + /// + public StepTabPanel MyStepTabPanel { get; set; } + /// + /// Related DSOTabPanle for a Word page + /// + public DSOTabPanel MyDSOTabPanel { get; set; } + public string MyUserRole { get; set; } + /// + /// Current SelectedItemInfo for this page + /// + public ItemInfo SelectedItemInfo { get { - if (_MyStepTabPanel == null) return null; - return _MyStepTabPanel.SelectedItemInfo; + if (MyStepTabPanel == null) return null; + return MyStepTabPanel.SelectedItemInfo; } set {// B2018-074 Don't crash if opening MSWord section from Tools window in Debug Mode - if (_MyStepTabPanel != null) - _MyStepTabPanel.SelectedItemInfo = value; + if (MyStepTabPanel != null) + MyStepTabPanel.SelectedItemInfo = value; } } /// @@ -121,14 +90,6 @@ namespace Volian.Controls.Library else SetupDSOTabPanel(); SetupSecurity(myItemInfo); - // B2022-055 assigning the Name caused a duplicate name error - // we found that the procedure tab control remained in the Control list after the procedure was closed - // later on we need to find out why it isn't removed when the procedure is closed - //if (MyDSOTabPanel == null || MyDSOTabPanel.MyEdWord != null) // B2017-219 check needed if we could not open a word attachment - //{ - // //Name = string.Format("DisplayTabItem {0}", myItemInfo.ItemID); - //} - } private bool MesssageShown = false; public void SetupSecurity(ItemInfo myItem) @@ -172,43 +133,37 @@ namespace Volian.Controls.Library FlexibleMessageBox.Show("Security has not been defined for PROMS. All functionality has been defaulted to the lowest level for all users until security is defined.", "no security defined", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning); MesssageShown = true; } - _MyStepTabPanel.MyStepTabRibbon.SetupReviewerMode(); + MyStepTabPanel.MyStepTabRibbon.SetupReviewerMode(); } else if (ui.IsAdministrator()) { - if (_MyStepTabPanel != null) - _MyStepTabPanel.MyStepTabRibbon.SetupAdminMode(); + MyStepTabPanel?.MyStepTabRibbon.SetupAdminMode(); MyUserRole = Volian.Base.Library.VlnSettings.UserID + " - Administrator"; } else if (ui.IsSetAdministrator(myItem.MyDocVersion)) { - if (_MyStepTabPanel != null) - _MyStepTabPanel.MyStepTabRibbon.SetupSetAdminMode(); + MyStepTabPanel?.MyStepTabRibbon.SetupSetAdminMode(); MyUserRole = Volian.Base.Library.VlnSettings.UserID + " - Set Administrator"; } else if (ui.IsROEditor(myItem.MyDocVersion) && !ui.IsWriter(myItem.MyDocVersion)) { - if (_MyStepTabPanel != null) - _MyStepTabPanel.MyStepTabRibbon.SetupROEditorMode(); + MyStepTabPanel?.MyStepTabRibbon.SetupROEditorMode(); MyUserRole = Volian.Base.Library.VlnSettings.UserID + " - RO Editor"; } else if (ui.IsWriter(myItem.MyDocVersion)) { - if (_MyStepTabPanel != null) - _MyStepTabPanel.MyStepTabRibbon.SetupWriterMode(); + MyStepTabPanel?.MyStepTabRibbon.SetupWriterMode(); MyUserRole = Volian.Base.Library.VlnSettings.UserID + " - Writer"; } else if (ui.IsReviewer(myItem.MyDocVersion)) { - if (_MyStepTabPanel != null) - _MyStepTabPanel.MyStepTabRibbon.SetupReviewerMode(); + MyStepTabPanel?.MyStepTabRibbon.SetupReviewerMode(); MyUserRole = Volian.Base.Library.VlnSettings.UserID + " - Reviewer"; } else { - if (_MyStepTabPanel != null) - _MyStepTabPanel.MyStepTabRibbon.SetupReviewerMode(); + MyStepTabPanel?.MyStepTabRibbon.SetupReviewerMode(); MyUserRole = Volian.Base.Library.VlnSettings.UserID + " - Reviewer"; } } @@ -222,42 +177,19 @@ namespace Volian.Controls.Library InitializeComponent(); this.Click += new EventHandler(DisplayTabItem_Click); SetupLibraryDocumentDSOTabPanel(); - // B2022-055 assigning the Name caused a duplicate name error - // we found that the procedure tab control remained in the Control list after the procedure was closed - // later on we need to find out why it isn't removed when the procedure is closed - //Name = string.Format("DisplayTabLibraryDocument {0}", myDocumentInfo.DocID); } protected override void OnDisplayedChanged() { //Console.WriteLine("=>=>=>=> OnDisplayedChanged"); - if (_MyStepTabPanel != null) - _MyStepTabPanel.MyStepPanel.DisplayItemChanging = true; + if (MyStepTabPanel != null) + MyStepTabPanel.MyStepPanel.DisplayItemChanging = true; base.OnDisplayedChanged(); - if (_MyStepTabPanel != null) - _MyStepTabPanel.MyStepPanel.DisplayItemChanging = false; + if (MyStepTabPanel != null) + MyStepTabPanel.MyStepPanel.DisplayItemChanging = false; //Console.WriteLine("<=<=<=<= OnDisplayedChanged"); } - //void DisplayTabItem_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e) - //{ - // Console.WriteLine("DisplayTabItem_MouseUp"); - //} - - //void DisplayTabItem_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) - //{ - // Console.WriteLine("DisplayTabItem_MouseDown"); - //} - - //void DisplayTabItem_LostFocus(object sender, EventArgs e) - //{ - // Console.WriteLine("DisplayTabItem_LostFocus"); - //} - - //void DisplayTabItem_GotFocus(object sender, EventArgs e) - //{ - // Console.WriteLine("DisplayTabItem_GotFocus"); - //} #endregion #region Event Handlers /// @@ -267,12 +199,10 @@ namespace Volian.Controls.Library /// private void DisplayTabItem_Click(object sender, EventArgs e) { - // Tell the TabControl that the ItemSelected has changed - DisplayTabItem myTabItem = sender as DisplayTabItem; - if (myTabItem == null) return; - StepTabPanel myTabPanel = myTabItem.MyStepTabPanel as StepTabPanel; - if (myTabPanel == null) return; - if (MyStepTabPanel.SelectedEditItem == null) return; + // Tell the TabControl that the ItemSelected has changed + if (!(sender is DisplayTabItem myTabItem)) return; + if (!(myTabItem.MyStepTabPanel is StepTabPanel)) return; + if (MyStepTabPanel.SelectedEditItem == null) return; MyStepTabPanel.MyDisplayTabControl.HandleChangeId(MyStepTabPanel.SelectedEditItem.MyItemInfo, myTabItem); _MyDisplayTabControl.OnItemSelectedChanged(this, new ItemSelectedChangedEventArgs(MyStepTabPanel.SelectedEditItem)); } @@ -285,33 +215,28 @@ namespace Volian.Controls.Library { ((System.ComponentModel.ISupportInitialize)(_MyDisplayTabControl.MyBar)).BeginInit(); _MyDisplayTabControl.MyBar.SuspendLayout(); - _MyStepTabPanel = new StepTabPanel(_MyDisplayTabControl); + MyStepTabPanel = new StepTabPanel(_MyDisplayTabControl); // // tabItem // - Control = _MyStepTabPanel; - // B2022-055 assigning the Name caused a duplicate name error - // we found that the procedure tab control remained in the Control list after the procedure was closed - // later on we need to find out why it isn't removed when the procedure is closed - //Name = "tabItem Item " + _MyItemInfo.ItemID; + Control = MyStepTabPanel; Text = _MyItemInfo.TabTitle; _MyItemInfo.Changed += new ItemInfoEvent(_MyItemInfo_Changed); Tooltip = _Tooltip = _MyItemInfo.TabToolTip.Replace("\u2011", "-").Replace(@"\u9586?", @"\"); MouseMove += new System.Windows.Forms.MouseEventHandler(DisplayTabItem_MouseMove); LostFocus += new EventHandler(DisplayTabItem_LostFocus); - // - _MyDisplayTabControl.Controls.Add(_MyStepTabPanel); + + _MyDisplayTabControl.Controls.Add(MyStepTabPanel); _MyDisplayTabControl.MyBar.Items.Add(this); _MyDisplayTabControl.MyBar.Width = 300; // This triggers the bar to resize itself // // tabPanel // - _MyStepTabPanel.MyDisplayTabItem = this; + MyStepTabPanel.MyDisplayTabItem = this; ((System.ComponentModel.ISupportInitialize)(_MyDisplayTabControl.MyBar)).EndInit(); _MyDisplayTabControl.MyBar.ResumeLayout(false); - DocVersionInfo dvi = _MyItemInfo.MyProcedure.ActiveParent as DocVersionInfo; //MyRTBItem.MyItemInfo.MyProcedure.ActiveParent as DocVersionInfo; - if (dvi == null) return; - if (dvi.VersionType > 127 || viewonlymode) + if (!(_MyItemInfo.MyProcedure.ActiveParent is DocVersionInfo dvi)) return; + if (dvi.VersionType > 127 || viewonlymode) MyStepTabPanel.MyStepPanel.VwMode = E_ViewMode.View; // C2021 - 027: Procedure level PC/PC - add _MyIteminfo to argument list if (dvi.MultiUnitCount > 1) @@ -345,21 +270,17 @@ namespace Volian.Controls.Library { EntryInfo myEntry = _MyItemInfo.MyContent.MyEntry; UserInfo ui = UserInfo.GetByUserID(OwnerInfo.Get(OwnerID).SessionUserID); - _MyDSOTabPanel = new DSOTabPanel(myEntry.MyDocument, _MyDisplayTabControl, _MyItemInfo, UserInfo.CanEdit(ui, MyItemInfo.MyDocVersion)); - if (_MyDSOTabPanel.MyEdWord == null) return; // B2017-219 if we could not open the word attachment just return + MyDSOTabPanel = new DSOTabPanel(myEntry.MyDocument, _MyDisplayTabControl, _MyItemInfo, UserInfo.CanEdit(ui, MyItemInfo.MyDocVersion)); + if (MyDSOTabPanel.MyEdWord == null) return; // B2017-219 if we could not open the word attachment just return // // tabItem // - Control = _MyDSOTabPanel; - // B2022-055 assigning the Name caused a duplicate name error - // we found that the procedure tab control remained in the Control list after the procedure was closed - // later on we need to find out why it isn't removed when the procedure is closed - //Name = "tabItem Item " + _MyItemInfo.ItemID; + Control = MyDSOTabPanel; Text = _MyItemInfo.TabTitle; Tooltip = _Tooltip = _MyItemInfo.TabToolTip.Replace("\u2011", "-").Replace(@"\u9586?", @"\"); MouseMove += new System.Windows.Forms.MouseEventHandler(DisplayTabItem_MouseMove); LostFocus += new EventHandler(DisplayTabItem_LostFocus); - _MyDisplayTabControl.Controls.Add(_MyDSOTabPanel); + _MyDisplayTabControl.Controls.Add(MyDSOTabPanel); DSOTabPanel.IgnoreEnter = true; //Console.WriteLine("AddRange {0}", Name); _MyDisplayTabControl.MyBar.Items.AddRange(new DevComponents.DotNetBar.BaseItem[] { @@ -368,7 +289,7 @@ namespace Volian.Controls.Library // tabPanel // _MyDisplayTabControl.SelectDisplayTabItem(this); - _MyDSOTabPanel.MyDisplayTabItem = this; + MyDSOTabPanel.MyDisplayTabItem = this; DSOTabPanel.IgnoreEnter = false; } private void SetupLibraryDocumentDSOTabPanel() @@ -377,21 +298,17 @@ namespace Volian.Controls.Library // B2016-131 if myiteminfo is null, then the lib doc is not referenced. // - Allow editting only if you are an Administrator // - Cannot check if you are a Writer or Set Aministrator because we don't have a Doc Verion - _MyDSOTabPanel = new DSOTabPanel(_MyDocumentInfo, _MyDisplayTabControl, _MyItemInfo, (MyItemInfo != null) ? UserInfo.CanEdit(ui, MyItemInfo.MyDocVersion) : ui.IsAdministrator()); + MyDSOTabPanel = new DSOTabPanel(_MyDocumentInfo, _MyDisplayTabControl, _MyItemInfo, (MyItemInfo != null) ? UserInfo.CanEdit(ui, MyItemInfo.MyDocVersion) : ui.IsAdministrator()); // // tabItem // - Control = _MyDSOTabPanel; - // B2022-055 assigning the Name caused a duplicate name error - // we found that the procedure tab control remained in the Control list after the procedure was closed - // later on we need to find out why it isn't removed when the procedure is closed - //Name = "tabLibraryDocument " + _MyDocumentInfo.DocID; + Control = MyDSOTabPanel; Text = _MyDocumentInfo.LibTitle; DocumentConfig dc = new DocumentConfig(_MyDocumentInfo); Tooltip = _Tooltip = dc.LibDoc_Comment; MouseMove += new System.Windows.Forms.MouseEventHandler(DisplayTabItem_MouseMove); LostFocus += new EventHandler(DisplayTabItem_LostFocus); - _MyDisplayTabControl.Controls.Add(_MyDSOTabPanel); + _MyDisplayTabControl.Controls.Add(MyDSOTabPanel); DSOTabPanel.IgnoreEnter = true; _MyDisplayTabControl.MyBar.Items.AddRange(new DevComponents.DotNetBar.BaseItem[] { this}); @@ -399,7 +316,7 @@ namespace Volian.Controls.Library // tabPanel // _MyDisplayTabControl.SelectDisplayTabItem(this); - _MyDSOTabPanel.MyDisplayTabItem = this; + MyDSOTabPanel.MyDisplayTabItem = this; DSOTabPanel.IgnoreEnter = false; } #endregion diff --git a/PROMS/Volian.Controls.Library/DisplayTags.cs b/PROMS/Volian.Controls.Library/DisplayTags.cs index 4d5c12b1..411f3beb 100644 --- a/PROMS/Volian.Controls.Library/DisplayTags.cs +++ b/PROMS/Volian.Controls.Library/DisplayTags.cs @@ -1,9 +1,6 @@ using System; using System.Collections.Generic; -using System.ComponentModel; using System.Drawing; -using System.Data; -using System.Text; using System.Windows.Forms; using VEPROMS.CSLA.Library; using JR.Utils.GUI.Forms; @@ -13,18 +10,14 @@ namespace Volian.Controls.Library { public partial class DisplayTags : UserControl { - #region Properties - private ItemInfo _CurItemInfo = null; - /// - /// Current ItemInfo - /// - public ItemInfo CurItemInfo - { - get { return _CurItemInfo; } - set { _CurItemInfo = value; } - } - private bool _Initalizing = false; - private IList _MyStepTypeInd = null; // use to keep track of step types put in step type menu + #region Properties + /// + /// Current ItemInfo + /// + public ItemInfo CurItemInfo { get; set; } = null; + private bool _Initalizing = false; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private IList _MyStepTypeInd = null; // use to keep track of step types put in step type menu /// /// This stores the last selected EditItem when the Panel was not visible /// This allows the panel to be filled when the when it is made visible @@ -70,23 +63,6 @@ namespace Volian.Controls.Library CurItemInfo = value.MyItemInfo; _MyEditItem.MyStepPropertiesPanel = this; // this allows us to access the Step Property pannel and toggle check boxes with shortcut keystrokes - // originally the change all (for step type) checkbox was initialized based - // on whether all steps at level were same type, i.e. if same type, default - // it to checked. This may confuse the user, so we decided to always default - // to not checked. The code was left in here in case that decision is changed. - // MRC, JSJ & KBR were in on discussion on 2/27/12: - // only change all at level if all substeps are of same type - //bool allSameType = true; - //ItemInfo itmp = CurItemInfo.FirstSibling; - //while (itmp != null) - //{ - // if (CurItemInfo.MyContent.Type != itmp.MyContent.Type) - // { - // allSameType = false; - // break; - // } - // itmp = itmp.NextItem; - //} cbChgAll.Checked = false; TagsFillIn(); } @@ -119,7 +95,6 @@ namespace Volian.Controls.Library cbTCAS.Checked = false; cbCAS.Enabled = false; cbTCAS.Enabled = false; - //txbxAltConActSumText.Enabled = false; rbChgBarOff.Enabled = false; rbChgBarOn.Enabled = false; listBoxStepTypes.Items.Clear(); @@ -134,21 +109,13 @@ namespace Volian.Controls.Library } private bool StepOverRide() { - ItemInfo myparent = CurItemInfo.MyActiveParent as ItemInfo; - if (CurItemInfo.IsRNOPart && myparent !=null && myparent.IsHigh) - { - // does the high level step of an RNO have a checkoff, if so it - // can be overridden? - StepConfig sc = myparent.MyConfig as StepConfig; - if (sc != null && sc.Step_CheckOffIndex != -1) return true; - } - return false; - } - public void HighlightChangeStep() - { - // As per MRC - don't bother to color it. - // left here in case we change our mind. - //groupPanelChgStepType.Style.BackColor = Color.PaleVioletRed; + if (CurItemInfo.IsRNOPart && CurItemInfo.MyActiveParent is ItemInfo myparent && myparent.IsHigh) + { + // does the high level step of an RNO have a checkoff, if so it + // can be overridden? + if (myparent.MyConfig is StepConfig sc && sc.Step_CheckOffIndex != -1) return true; + } + return false; } public void FocusOnImageSize() { @@ -246,7 +213,8 @@ namespace Volian.Controls.Library } } - private Dictionary _CheckOffIndex = new Dictionary(); // C2020-003 translate the sorted index number to the actual checkoff index + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private Dictionary _CheckOffIndex = new Dictionary(); // C2020-003 translate the sorted index number to the actual checkoff index private void TagsFillIn() { _Initalizing = true; @@ -289,7 +257,6 @@ namespace Volian.Controls.Library { cbPlaceKeeper.Enabled = cbPlaceKeeperCont.Enabled = false; } - //cbCAS.Enabled = true; rbChgBarOff.Enabled = true; rbChgBarOn.Enabled = true; @@ -303,7 +270,6 @@ namespace Volian.Controls.Library if (cmbShwRplWds.Visible) { cmbShwRplWds.SelectedIndex = 0; - //StepConfig sc = CurItemInfo.MyConfig as StepConfig; cmbShwRplWds.Enabled = true; cmbShwRplWds.SelectedIndex = sc.Step_ShwRplWdsIndex; } @@ -350,12 +316,6 @@ namespace Volian.Controls.Library cbCAS.Checked = (sc.Step_CAS != null) ? sc.Step_CAS == "True" : CurItemInfo.IncludeOnContActSum; // Set the Time Critical Action Summary check box - if nothing in config set to false cbTCAS.Checked = (sc.Step_TCAS != null) ? sc.Step_TCAS == "True" : CurItemInfo.IncludeOnTimeCriticalActionSum; - //// if alternative continuous action text is saved in the config, then show it and check the checkbox - //if (sc.Step_AlternateContActSumText != null && sc.Step_AlternateContActSumText != "") - //{ - // txbxAltConActSumText.Text = sc.Step_AlternateContActSumText; - // cbCAS.Checked = true; - //} } bool _checkoffsAllowed = true; if (fmtdata.ProcData.CheckOffData.CheckoffOnSubStepsOnly) @@ -365,7 +325,7 @@ namespace Volian.Controls.Library if (_checkoffsAllowed && !(fmtdata.ProcData.CheckOffData.CheckOffList == null) && !(maxindx == 0)) { CheckOffList chkoffList = fmtdata.ProcData.CheckOffData.CheckOffList; - if (chkoffList != null) chkoffList.Sort(CompareCheckoffUsingOrderBy); // C2020-003 sort the checkoff list via the Index and/or OrderBy elements + chkoffList?.Sort(CompareCheckoffUsingOrderBy); // C2020-003 sort the checkoff list via the Index and/or OrderBy elements cmbCheckoff.Items.Clear(); _CheckOffIndex.Clear(); // C2020-003 clear the checkoff index dictionary int sortedIndx = 0; @@ -423,15 +383,6 @@ namespace Volian.Controls.Library tbFSWd.Text = wd.ToString(); tbFSHt.Text = ht.ToString(); - - //trBarFS.Maximum = Math.Max((int)wd2, trBarFS.Maximum); - //if (wd > trBarFS.Maximum) trBarFS.Maximum = wd + 1; - //trBarFS.Minimum = Math.Min(wd, 72); - //trBarFS.Value = (int)wd; - //ImageItem ii = MyEditItem as ImageItem; - //_origFigureSizeWidth = ii.MyPictureBox.Width; - //tbFSWd.Text = ii.MyPictureBox.Width.ToString(); - //tbFSHt.Text = ii.MyPictureBox.Height.ToString(); } else { @@ -458,11 +409,6 @@ namespace Volian.Controls.Library // There is also an override flag in the config for the step, used to override the change bar to 'off' // if the date show it as having one, or allow a change bar to be 'on' if there the dates are // not different. Note also that a user may edit data after the change bar is set to 'on'. - //DateTime curDts; - //using (Item itm = Item.Get(CurItemInfo.ItemID)) - //{ - // curDts = itm.DTS; - //} // set change bar radio buttons for the default that there is no change // bar & override sets it to On. @@ -486,24 +432,13 @@ namespace Volian.Controls.Library } else { - rbChgBarOff.Checked = (sc.Step_CBOverride == "Off") ? true : false; - rbChgBarOn.Checked = (sc.Step_CBOverride == "On") ? true : false; + rbChgBarOff.Checked = (sc.Step_CBOverride == "Off"); + rbChgBarOn.Checked = (sc.Step_CBOverride == "On"); // there is override settings in the config... If the date time stamp says that text was changed // so a change bar should exist - check override to see how change bar controls are set: // If the date of this is greater than the procedure, a change bar should be displayed - // see what the override says. The override states whether change bar is on/off (not // whether override is on/off) - //if (curDts > CurItemInfo.MyProcedure.DTS) - //{ - // rbChgBarOff.Text = "OFF (Override)"; - // rbChgBarOn.Text = "ON"; - //} - //else - //{ - // // date time stamp says no change bar should be displayed: - // rbChgBarOff.Text = "OFF"; - // rbChgBarOn.Text = "ON (Override)"; - //} } // see if the change id label & text box are visible, i.e. plant has multiple change ids. @@ -575,18 +510,15 @@ namespace Volian.Controls.Library } public void SetFigure(double wd, double wd2) { - // Check MyEditItem type and cast if needed - ImageItem ii = MyEditItem as ImageItem; - if (ii == null) return; + // Check MyEditItem type and cast if needed + if (!(MyEditItem is ImageItem ii)) return; - // Set the values as needed - trBarFS.Maximum = Math.Max((int)wd2, trBarFS.Maximum); + // Set the values as needed + trBarFS.Maximum = Math.Max((int)wd2, trBarFS.Maximum); if (wd > trBarFS.Maximum) trBarFS.Maximum = (int)wd + 1; trBarFS.Minimum = Math.Min((int)wd, 72); trBarFS.Value = (int)wd; _origFigureSizeWidth = ii.MyPictureBox.Width; - //tbFSWd.Text = ii.MyPictureBox.Width.ToString(); - //tbFSHt.Text = ii.MyPictureBox.Height.ToString(); } private int DoListStepTypes(FormatData fmtdata, StepData topType, string curType) @@ -611,27 +543,14 @@ namespace Volian.Controls.Library } return cursel; } - //private void AddToGallery(StepData sd, string curType) - //{ - // DevComponents.DotNetBar.ButtonItem bi = new DevComponents.DotNetBar.ButtonItem("btn" + sd.Type, sd.Type); - // bi.ButtonStyle = DevComponents.DotNetBar.eButtonStyle.ImageAndText; - // bi.Image = this.imageListStepTypes.Images[0]; - // bi.ImagePosition = DevComponents.DotNetBar.eImagePosition.Top; - - // bi.Checked = (sd.Type == curType); - - // galleryContainerStepTypes.SubItems.Add(bi); - // listBoxStepTypes.Items.Add(sd.Type); - //} #endregion #region Events private void cbPageBreak_CheckedChanged(object sender, EventArgs e) { if (_Initalizing) return; MyEditItem.SaveContents(); - StepConfig sc = CurItemInfo.MyConfig as StepConfig; - if (sc == null) return; - MyEditItem.ChangeBarForConfigItemChange = false; + if (!(CurItemInfo.MyConfig is StepConfig sc)) return; + MyEditItem.ChangeBarForConfigItemChange = false; if (CurItemInfo.IsHigh) sc.Step_NewManualPagebreak = cbPageBreak.Checked; else // C2023-018: allow for sub-step page breaks @@ -642,9 +561,8 @@ namespace Volian.Controls.Library { if (_Initalizing) return; MyEditItem.SaveContents(); - StepConfig sc = CurItemInfo.MyConfig as StepConfig; - if (sc == null) return; - MyEditItem.ChangeBarForConfigItemChange = false; + if (!(CurItemInfo.MyConfig is StepConfig sc)) return; + MyEditItem.ChangeBarForConfigItemChange = false; sc.Step_CAS = (cbCAS.Checked) ? "True" : "False"; MyEditItem.ChangeBarForConfigItemChange = true; // C2026-003 (put in for Vogtle 3&4) refresh the RNO step tab if including it on the Continuous Action Summary @@ -656,9 +574,8 @@ namespace Volian.Controls.Library { if (_Initalizing) return; MyEditItem.SaveContents(); - StepConfig sc = CurItemInfo.MyConfig as StepConfig; - if (sc == null) return; - MyEditItem.ChangeBarForConfigItemChange = false; + if (!(CurItemInfo.MyConfig is StepConfig sc)) return; + MyEditItem.ChangeBarForConfigItemChange = false; sc.Step_TCAS = (cbTCAS.Checked) ? "True" : "False"; MyEditItem.ChangeBarForConfigItemChange = true; } @@ -666,9 +583,8 @@ namespace Volian.Controls.Library { if (_Initalizing) return; MyEditItem.SaveContents(); - StepConfig sc = CurItemInfo.MyConfig as StepConfig; - if (sc == null) return; - MyEditItem.ChangeBarForConfigItemChange = false; + if (!(CurItemInfo.MyConfig is StepConfig sc)) return; + MyEditItem.ChangeBarForConfigItemChange = false; sc.Step_Placekeeper = (cbPlaceKeeper.Checked) ? "Y" : "N"; MyEditItem.ChangeBarForConfigItemChange = true; if (cbPlaceKeeper.Checked) @@ -682,9 +598,8 @@ namespace Volian.Controls.Library { if (_Initalizing) return; MyEditItem.SaveContents(); - StepConfig sc = CurItemInfo.MyConfig as StepConfig; - if (sc == null) return; - MyEditItem.ChangeBarForConfigItemChange = false; + if (!(CurItemInfo.MyConfig is StepConfig sc)) return; + MyEditItem.ChangeBarForConfigItemChange = false; sc.Step_Placekeeper = (cbPlaceKeeperCont.Checked) ? "C" : "N"; MyEditItem.ChangeBarForConfigItemChange = true; if (cbPlaceKeeperCont.Checked) @@ -698,9 +613,8 @@ namespace Volian.Controls.Library { if (_Initalizing) return; MyEditItem.SaveContents(); - StepConfig sc = CurItemInfo.MyConfig as StepConfig; - if (sc == null) return; - MyEditItem.ChangeBarForConfigItemChange = false; + if (!(CurItemInfo.MyConfig is StepConfig sc)) return; + MyEditItem.ChangeBarForConfigItemChange = false; sc.Step_IncludeInTOC = cbIncludeInTOC.Checked; MyEditItem.ChangeBarForConfigItemChange = true; } @@ -716,8 +630,8 @@ namespace Volian.Controls.Library EditItem topEditItem = MyEditItem; MyEditItem.SaveContents(); FormatData fmtdata = CurItemInfo.ActiveFormat.PlantFormat.FormatData; - string msgBox = null; - if (cbChgAll.Checked) + string msgBox; + if (cbChgAll.Checked) { ItemInfo startitm = CurItemInfo.FirstSibling; topEditItem = MyEditItem.MyStepPanel._LookupEditItems[startitm.ItemID]; @@ -733,12 +647,6 @@ namespace Volian.Controls.Library } // B2018-120: if caution/note steps have enhanced - change their type too if (startitm.IsNote || startitm.IsCaution) chgEnh = ChangeTypesEnhanced(startitm); - //using (Item itm = Item.Get(startitm.ItemID)) - //{ - // itm.DTS = DateTime.Now; - // itm.UserID = Volian.Base.Library.VlnSettings.UserID; - // itm.Save(); - //} startitm = startitm.GetNext(); } msgBox = chgEnh ? string.Format("All Step Types at this level and associated enhanced steps were changed to {0}", listBoxStepTypes.Items[listBoxStepTypes.SelectedIndex]) : @@ -757,17 +665,9 @@ namespace Volian.Controls.Library bool chgEnh = false; // B2018-120: if caution/note steps have enhanced - change their type too if (CurItemInfo.IsNote || CurItemInfo.IsCaution) chgEnh = ChangeTypesEnhanced(CurItemInfo); - //using (Item itm1 = Item.Get(CurItemInfo.ItemID)) - //{ - // itm1.DTS = DateTime.Now; - // itm1.UserID = Volian.Base.Library.VlnSettings.UserID; - // itm1.Save(); - //} msgBox = chgEnh ? string.Format("This Step Type and associated enhanced step were changed to {0}", listBoxStepTypes.Items[listBoxStepTypes.SelectedIndex]): string.Format("This Step Type was changed to {0}", listBoxStepTypes.Items[listBoxStepTypes.SelectedIndex]); } - // the follow line was to try and fix a refresh problem when you change the type of a new substep - //topEditItem.MyStepPanel.Reset(); topEditItem.SetAllTabs(); FlexibleMessageBox.Show(msgBox); @@ -821,12 +721,6 @@ namespace Volian.Controls.Library { StepConfig sc = CurItemInfo.MyConfig as StepConfig; sc.Step_CBOverride = CurItemInfo.HasChanges ? null : "On"; - //using (Content cnt = Content.Get(CurItemInfo.MyContent.ContentID)) - //{ - // cnt.DTS = DateTime.Now; - // cnt.UserID = Volian.Base.Library.VlnSettings.UserID; - // cnt.Save(); - //} } } private void rbChgBarOvrRideOff_CheckedChanged(object sender, EventArgs e) @@ -840,12 +734,6 @@ namespace Volian.Controls.Library { StepConfig sc = CurItemInfo.MyConfig as StepConfig; sc.Step_CBOverride = CurItemInfo.HasChanges ? "Off" :null; - //using (Content cnt = Content.Get(CurItemInfo.MyContent.ContentID)) - //{ - // cnt.DTS = CurItemInfo.MyProcedure.DTS; - // cnt.UserID = CurItemInfo.MyProcedure.UserID; - // cnt.Save(); - //} } } private void cmbCheckoff_SelectedIndexChanged(object sender, EventArgs e) @@ -856,25 +744,14 @@ namespace Volian.Controls.Library int indx = _CheckOffIndex[cmbCheckoff.SelectedIndex]; // C2020-003 get the non-sorted index from the sorted index StepConfig sc = CurItemInfo.MyConfig as StepConfig; sc.Step_CheckOffIndex = indx; - //using (Content cnt = Content.Get(CurItemInfo.MyContent.ContentID)) - //{ - // cnt.DTS = CurItemInfo.MyProcedure.DTS; - // cnt.UserID = CurItemInfo.MyProcedure.UserID; - // cnt.Save(); - //} } // C2029-025 Show or hide replace words. Can highlight replace words in editor. private void cmbShwRplWds_SelectedIndexChanged(object sender, EventArgs e) // new show replace words { - - // -------- - if (_Initalizing) return; MyEditItem.SaveContents(); - StepConfig sc = CurItemInfo.MyConfig as StepConfig; - if (sc == null) return; - MyEditItem.ChangeBarForConfigItemChange = false; - //sc.Step_DisableInitialLine = cbInitialLine.Checked; + if (!(CurItemInfo.MyConfig is StepConfig sc)) return; + MyEditItem.ChangeBarForConfigItemChange = false; sc.Step_ShwRplWdsIndex = cmbShwRplWds.SelectedIndex; MyEditItem.ChangeBarForConfigItemChange = true; @@ -890,11 +767,10 @@ namespace Volian.Controls.Library // off of the High Level Step private void tbRespons_Leave(object sender, EventArgs e) { - // User left responsibilty field. If text changed, then prompt - // to see if save should occur. - StepConfig sc = CurItemInfo.MyConfig as StepConfig; - if (sc == null) return; - bool bothEmpty = (sc.Step_Responsibility == null || sc.Step_Responsibility == "") && (tbRespons.Text == null || tbRespons.Text == ""); + // User left responsibilty field. If text changed, then prompt + // to see if save should occur. + if (!(CurItemInfo.MyConfig is StepConfig sc)) return; + bool bothEmpty = (sc.Step_Responsibility == null || sc.Step_Responsibility == "") && (tbRespons.Text == null || tbRespons.Text == ""); if (!bothEmpty && sc.Step_Responsibility != tbRespons.Text) { if (FlexibleMessageBox.Show(this, "Do you want to save the Responsibility Text?", "Confirm Save", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) @@ -917,19 +793,19 @@ namespace Volian.Controls.Library { if (MyEditItem is ImageItem) { - int wd = 0; - int ht = 0; - try - { - wd = int.Parse(tbFSWd.Text); - ht = int.Parse(tbFSHt.Text); - } - catch (Exception ex) - { - wd = 0; - ht = 0; - } - if (wd != 0 && ht != 0) (MyEditItem as ImageItem).SizeImage(wd, ht); + int wd; + int ht; + try + { + wd = int.Parse(tbFSWd.Text); + ht = int.Parse(tbFSHt.Text); + } + catch (Exception) + { + wd = 0; + ht = 0; + } + if (wd != 0 && ht != 0) (MyEditItem as ImageItem).SizeImage(wd, ht); } } private float _origFigureSizeRatio = 0; // keep original ratio & width in case of 'restore' @@ -966,8 +842,8 @@ namespace Volian.Controls.Library { newHt = int.Parse(tbFSWd.Text); } - catch (Exception ex) - { + catch (Exception) + { invaliddata = true; } if (invaliddata || newHt < trBarFS.Minimum || newHt > trBarFS.Maximum) @@ -984,9 +860,8 @@ namespace Volian.Controls.Library { if (_Initalizing) return; MyEditItem.SaveContents(); - StepConfig sc = CurItemInfo.MyConfig as StepConfig; - if (sc == null) return; - MyEditItem.ChangeBarForConfigItemChange = false; + if (!(CurItemInfo.MyConfig is StepConfig sc)) return; + MyEditItem.ChangeBarForConfigItemChange = false; sc.Step_PreferredPagebreak = cbPrefPageBreak.Checked; MyEditItem.ChangeBarForConfigItemChange = true; } @@ -995,9 +870,8 @@ namespace Volian.Controls.Library { if (_Initalizing) return; MyEditItem.SaveContents(); - StepConfig sc = CurItemInfo.MyConfig as StepConfig; - if (sc == null) return; - MyEditItem.ChangeBarForConfigItemChange = false; + if (!(CurItemInfo.MyConfig is StepConfig sc)) return; + MyEditItem.ChangeBarForConfigItemChange = false; sc.Step_DisableInitialLine = cbInitialLine.Checked; MyEditItem.ChangeBarForConfigItemChange = true; @@ -1023,25 +897,5 @@ namespace Volian.Controls.Library } } - //private void txbxAltConActSumText_Leave(object sender, EventArgs e) - //{ - // // User left Atlernate Continuous Action Text field. If text changed, then prompt - // // to see if save should occur. - // StepConfig sc = CurItemInfo.MyConfig as StepConfig; - // if (sc == null) return; - // bool bothEmpty = (sc.Step_AlternateContActSumText == null || sc.Step_AlternateContActSumText == "") && (txbxAltConActSumText.Text == null || txbxAltConActSumText.Text == ""); - // if (!bothEmpty && sc.Step_AlternateContActSumText != txbxAltConActSumText.Text) - // { - // if (MessageBox.Show(this, "Do you want to save the Alternate Continuous Action Text?", "Confirm Save", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) - // { - // MyEditItem.SaveContents(); - // sc.Step_AlternateContActSumText = txbxAltConActSumText.Text; // this actually saves the config - // } - // else - // txbxAltConActSumText.Text = sc.Step_AlternateContActSumText; - // } - - //} - } } diff --git a/PROMS/Volian.Controls.Library/DisplayTransition.cs b/PROMS/Volian.Controls.Library/DisplayTransition.cs index 5134ecbb..12f91412 100644 --- a/PROMS/Volian.Controls.Library/DisplayTransition.cs +++ b/PROMS/Volian.Controls.Library/DisplayTransition.cs @@ -1,16 +1,13 @@ using System; using System.Collections; using System.Collections.Generic; -using System.ComponentModel; using System.Drawing; -using System.Data; using System.Text; using System.Windows.Forms; -using System.Text.RegularExpressions; using AT.STO.UI.Win; using VEPROMS.CSLA.Library; -using Volian.Base.Library; using JR.Utils.GUI.Forms; +using System.Linq; namespace Volian.Controls.Library { @@ -116,15 +113,9 @@ namespace Volian.Controls.Library private bool _DoingRange = false; // flags if in 'range' transition mode private VETreeNode _RangeNode1; private VETreeNode _RangeNode2; - // Use _RangeColor to show highlighting for steps selected in range. This is set from - // calling methods from application settings. If not default to aquamarine. - private Color _RangeColor = Color.LightGray; - public Color RangeColor - { - get { return _RangeColor; } - set { _RangeColor = value; } - } - private StepRTB _MyRTB; // Current MyDisplayRTB, i.e. insert transition to it. + + public Color RangeColor { get; set; } = Color.LightGray; + private StepRTB _MyRTB; // Current MyDisplayRTB, i.e. insert transition to it. public StepRTB MyRTB { get { return _MyRTB; } @@ -148,7 +139,6 @@ namespace Volian.Controls.Library CurTrans = args.MyLinkText.MyTransitionInfo; } private ItemInfo _CurrentItemProcedure; // the selected item's procedure - private ItemInfo _CurrentToProcedure; // the 'to' location's procedure (may be same as _CurrentItemProcedure) private ItemInfo _CurrentProcedure; // current procedure used to set all of the controls (may switch between above two) private int _CurrentProcIndex; private bool _AlwaysDisableSets; // true if there is only 1 item in tree/combo for sets @@ -219,7 +209,6 @@ namespace Volian.Controls.Library } } _CurrentProcedure = tmpitm; - _CurrentToProcedure = _CurrentProcedure; if (_CurTrans == null) _CurrentItemProcedure = _CurrentProcedure; else @@ -271,7 +260,6 @@ namespace Volian.Controls.Library else if (secitm != null && secitm.Steps != null && secitm.Steps.Count > 0) stpitm = selitm.Steps[0]; if (!_DoingRange) tvTranFillIn(stpitm); // range code fills in tree. - //if (_DoingRange) tvInitHiliteRange(rangeSameLevel, stpitm, rngitm, (i1 < i2) ? i2 : i1); } else { @@ -283,16 +271,13 @@ namespace Volian.Controls.Library } private void tvInitHiliteRange() //bool rangeSameLevel, ItemInfo stpitm, ItemInfo rngitm, int uplevel) { - ItemInfo toItm = _CurTrans.MyItemToID; - ItemInfo rngItm = null; - // figure out whether at same level, have same parent and have same HLS: - ItemInfo itm1 = _CurTrans.MyItemToID; + _ = _CurTrans.MyItemToID; + // figure out whether at same level, have same parent and have same HLS: + ItemInfo itm1 = _CurTrans.MyItemToID; ItemInfo itm2 = _CurTrans.MyItemRangeID; // Invalid existing transition if (itm2.ActiveParent == null || itm1.ActiveParent == null) return; - //if (_CurTrans.TranType == 2 && itm1.ItemID == itm2.ItemID) itm2 = itm1.LastSibling; - bool samHLS = itm1.MyHLS.ItemID == itm2.MyHLS.ItemID; int lev1 = 0; int lev2 = 0; while (!itm1.IsHigh) @@ -305,7 +290,6 @@ namespace Volian.Controls.Library lev2++; itm2 = itm2.MyParent; } - bool samLevel = lev1 == lev2; // For each range item, go to common level's parent. int cnt = lev1+1; ItemInfo sameParent1 = _CurTrans.MyItemToID; @@ -327,7 +311,7 @@ namespace Volian.Controls.Library // now add nodes for the subtrees so that highlighting can be done. Do 'to' item // first. If 'range' item is at same level, won't need to do anymore processing. ItemInfo toItem = sameParent1.Ordinal<=sameParent2.Ordinal?_CurTrans.MyItemToID:_CurTrans.MyItemRangeID; - ItemInfo rngItem = null; + ItemInfo rngItem; if (_CurTrans.TranType == 2 && _CurTrans.MyItemToID == _CurTrans.MyItemRangeID) { @@ -452,51 +436,6 @@ namespace Volian.Controls.Library vlnTreeComboSets.DropDownControl.SelectedNode = topnode; vlnTreeComboSets.DropDownControl.BeforeExpand += new TreeViewCancelEventHandler(vlnTreeComboSets_BeforeExpand); - #region CheckIfNeeded Commented Out - //vlnTreeComboSets.DropDownControl. = vlnTreeComboSets.Width; - // The DropDownNode should be at a DocVersion now. The expanded DocVersion - // is the one that matches mydocversion - //tmpfi = mydocversion.ActiveParent as FolderInfo; - //DocVersionInfoList dvlist = tmpfi.FolderDocVersions; - //DropDownNode tnDV = null; - // Once at a docversions, only allow working - // draft sets. Use DocVersion that we're in, to expand it showing the active procedure. - // first count how many versions can be displayed, i.e. only workingdraft? - // if more than one, put out a tree node for them. - //int cntdocv = 0; - //foreach (DocVersionInfo dv in dvlist) - //{ - // if ((VersionTypeEnum)dv.VersionType == VersionTypeEnum.WorkingDraft) cntdocv++; - - //} - //if (cntdocv>1) - //{ - // foreach (DocVersionInfo dv in dvlist) - // { - // if ((VersionTypeEnum)dv.VersionType == VersionTypeEnum.WorkingDraft) - // { - // DropDownNode tn = new DropDownNode(dv.VersionID, dv.ToString()); - // tn.Tag = dv; - // if (topnode != null) - // topnode.Nodes.Add(tn); - // else - // vlnTreeComboSets.DropDownControl.Nodes.Add(tn); - // if (dv.VersionID == mydocversion.VersionID) - // { - // tnDV = tn; - // vlnTreeComboSets.Value = tnDV; - // vlnTreeComboSets.DropDownControl.SelectedNode = tnDV; - - // } - // //else if (dv.HasChildren) // allow for '+' for tree expansion - // //{ - // // DropDownNode tnt = new DropDownNode(0,"VLN_DUMMY"); - // // tn.Nodes.Add(tnt); - // //} - // } - // } - //} - #endregion } private void ListBoxTranFmtFillIn() { @@ -504,7 +443,7 @@ namespace Volian.Controls.Library listBoxTranFmt.Items.Clear(); for (int i = 0; i < ttl.MaxIndex; i++) listBoxTranFmt.Items.Add(new TransItem(ttl[i].TransMenu.Replace("?.",""),ttl[i].TransFormat.Replace("?.",""))); - //listBoxTranFmt.Items.Add(ttl[i].TransFormat.Replace("?.","")); + listBoxTranFmt.SelectedIndex = _TranFmtIndx; E_TransUI etm = (E_TransUI)_CurItemFrom.ActiveFormat.PlantFormat.FormatData.TransData.TransTypeList[_TranFmtIndx].TransUI; _DoingRange = (etm & E_TransUI.StepLast) == E_TransUI.StepLast; @@ -532,18 +471,8 @@ namespace Volian.Controls.Library if (startitm.MyContent.Type < 20000) return; groupPanelTranstionSteps.Style.BackColor = Color.Cornsilk; // For the tree view, use parent, unless already at HLS. If at HLS, use this level. - //ItemInfo selitm2 = startitm.MyHLS; ItemInfo selSubSec = secitm.Sections[0]; - // The commented out code below is for displaying the steps from the first sub-section B2025-035 - //ItemInfo subSelStep = selSubSec.Steps[0]; - //E_TransUI etm2 = (E_TransUI)_CurItemFrom.ActiveFormat.PlantFormat.FormatData.TransData.TransTypeList[listBoxTranFmt.SelectedIndex].TransUI; - //if (subSelStep.IsInRNO) - // startitm = subSelStep.FirstSibling; // if in RNO tree, start out with HLS - //else - // startitm = subSelStep != null ? subSelStep.FirstSibling : startitm.FirstSibling; - - // B2025-035 ItemInfo subSelStep = secitm.Sections[0]; E_TransUI etm2 = (E_TransUI)_CurItemFrom.ActiveFormat.PlantFormat.FormatData.TransData.TransTypeList[listBoxTranFmt.SelectedIndex].TransUI; if (subSelStep.IsInRNO) @@ -551,13 +480,14 @@ namespace Volian.Controls.Library else startitm = subSelStep != null ? subSelStep.FirstSibling : startitm.FirstSibling; - // B2025-035 bool setsel2 = false; while (startitm != null) { - VETreeNode tvn = new VETreeNode(startitm, false); - tvn.Tag = startitm; - int active = this.tvTran.Nodes.Add(tvn); + VETreeNode tvn = new VETreeNode(startitm, false) + { + Tag = startitm + }; + int active = this.tvTran.Nodes.Add(tvn); if (subSelStep != null && startitm.ItemID == subSelStep.ItemID) { tvTran.SelectedNode = tvTran.Nodes[active]; @@ -580,7 +510,6 @@ namespace Volian.Controls.Library groupPanelTranstionSteps.Style.BackColor = Color.Cornsilk; // For the tree view, use parent, unless already at HLS. If at HLS, use this level. ItemInfo selitm = startitm.MyHLS; - //if (_CurTrans == null)selitm = startitm.MyHLS; E_TransUI etm = (E_TransUI)_CurItemFrom.ActiveFormat.PlantFormat.FormatData.TransData.TransTypeList[listBoxTranFmt.SelectedIndex].TransUI; if (startitm.IsInRNO) startitm = selitm.FirstSibling; // if in RNO tree, start out with HLS @@ -589,9 +518,11 @@ namespace Volian.Controls.Library bool setsel = false; while (startitm != null) { - VETreeNode tvn = new VETreeNode(startitm, false); - tvn.Tag = startitm; - int active = this.tvTran.Nodes.Add(tvn); + VETreeNode tvn = new VETreeNode(startitm, false) + { + Tag = startitm + }; + int active = this.tvTran.Nodes.Add(tvn); if (selitm !=null && startitm.ItemID == selitm.ItemID) { tvTran.SelectedNode = tvTran.Nodes[active]; @@ -614,10 +545,8 @@ namespace Volian.Controls.Library if (secitm == null || secitm.MyContent.Type < 10000) return; // if sectstart is not -1, then use this as the section to select, otherwise // use the id for the item passed in. - int startitm = secstart; if (clear && secstart < 0) secstart = secitm.ItemID; - ItemInfo selitm = secitm; // this is the selected 'section' - secitm = secitm.FirstSibling; + secitm = secitm.FirstSibling; while (secitm != null) { // if the selected transition format requires a step be selected (show only step sections), only add step sections @@ -793,19 +722,6 @@ namespace Volian.Controls.Library } } } - // B2018-009 Eliminate Working Draft (DocVersions) from the procedure tree for transitions - //else if (fi.FolderDocVersionCount > 0) - //{ - // foreach (DocVersionInfo dv in fi.FolderDocVersions) - // { - // if ((VersionTypeEnum)dv.VersionType == VersionTypeEnum.WorkingDraft) - // { - // DropDownNode newnode = new DropDownNode(dv.VersionID, dv.ToString()); - // newnode.Tag = dv; - // par.Nodes.Add(newnode); - // } - // } - //} } vlnTreeComboSets.Value = par; vlnTreeComboSets.DropDownControl.SelectedNode = par; @@ -821,9 +737,9 @@ namespace Volian.Controls.Library // selected the docversion itself.... bool defines_set = false; FolderInfo fi = null; - if (obj is FolderInfo) + if (obj is FolderInfo finfo) { - fi = (FolderInfo)obj; + fi = finfo; if (fi.ChildFolderCount == 0) { // note that the folder may contain more than one docversion, check for @@ -955,16 +871,6 @@ namespace Volian.Controls.Library if (_DoingRange) tvTran.SelectedNode = null; SaveCancelEnabling(); } - //private void btnUp1_Click(object sender, EventArgs e) - //{ - // // if StepAllowNone, then use the second node in the tree view. - // int indx = 0; - // if (tvTran.Nodes[0].Tag == null) indx = 1; - // // if at HLS, don't do anything. - // ItemInfo curitm = (ItemInfo)((VETreeNode)tvTran.Nodes[indx]).VEObject; - // if (curitm.IsHigh) return; - // tvTranFillIn(curitm); - //} private void tvTran_BeforeExpand(object sender, TreeViewCancelEventArgs e) { VETreeNode tn = ((VETreeNode)e.Node); @@ -985,19 +891,15 @@ namespace Volian.Controls.Library // it & disable. ItemInfo secitm = (ItemInfo)cbTranSects.SelectedItem; - //if (secitm.IsStepSection) - //{ - // cbTranSects.SelectedItem.Sections[0]; - - //} - if (!secitm.IsStepSection) + if (!secitm.IsStepSection) { tvTran.Nodes.Clear(); tvTran.Enabled = false; cbIncStepNum.Enabled = false; // C2020-028: disable/uncheck 'Include Step Number' if on Word doc cbIncStepNum.Checked = false; // Set Save & Cancel enabling, depending on whether section can be an endpoint. - E_TransUI etm = (E_TransUI)_CurItemFrom.ActiveFormat.PlantFormat.FormatData.TransData.TransTypeList[_TranFmtIndx].TransUI; + //Following line is for Debugging + //E_TransUI etm = (E_TransUI)_CurItemFrom.ActiveFormat.PlantFormat.FormatData.TransData.TransTypeList[_TranFmtIndx].TransUI; SaveCancelEnabling(); } else @@ -1065,7 +967,7 @@ namespace Volian.Controls.Library // 1) Look in ProcedureConfig/SectionStart ProcedureConfig pc = (ProcedureConfig)prcitm.MyConfig; int sectstartid = -1; - string ss = pc == null ? null : pc.SectionStart; + string ss = pc?.SectionStart; SectionInfo si = null; if (ss != null && ss != "") { @@ -1077,7 +979,7 @@ namespace Volian.Controls.Library if (si.MyProcedure.ItemID == prcitm.ItemID) return sectstartid; // The following code fixes the sectionstart property for the Copy Procedure function. This code will correct // any procedures that were copied prior to the implementation of this the copy procedure function fix. - foreach (SectionInfo si1 in prcitm.Sections) + foreach (SectionInfo si1 in prcitm.Sections.OfType()) { if (si.DisplayNumber == si1.DisplayNumber && si.DisplayText == si1.DisplayText) { @@ -1096,22 +998,21 @@ namespace Volian.Controls.Library // 2) Look in SectionConfig/OriginalSteps = 'Y' if (prcitm.Sections != null) { - foreach (SectionInfo sio in prcitm.Sections) + foreach (SectionInfo sio in prcitm.Sections.OfType()) { - SectionConfig sc = sio.MyConfig as SectionConfig; - if (sc != null && sc.Section_OriginalSteps == "Y") - { - return sio.ItemID; - } - } + if (sio.MyConfig is SectionConfig sc && sc.Section_OriginalSteps == "Y") + { + return sio.ItemID; + } + } // 3) Find if any of the section titles contain 'PROCEDURES STEPS' - foreach (SectionInfo sit in prcitm.Sections) + foreach (SectionInfo sit in prcitm.Sections.OfType()) { if (sit.DisplayText.ToUpper().Contains("PROCEDURE STEPS")) return sit.ItemID; } - foreach (SectionInfo sit in prcitm.Sections) + foreach (SectionInfo sit in prcitm.Sections.OfType()) { if (sit.DisplayText.ToUpper().Equals("PROCEDURE"))// bug fix: B2015-003 return sit.ItemID; @@ -1120,17 +1021,17 @@ namespace Volian.Controls.Library // 4) Format has flag that a default section is not required so return 1st section. if (prcitm.Sections != null) { - foreach (SectionInfo sid in prcitm.Sections) + foreach (SectionInfo sid in prcitm.Sections.OfType()) { if (sid.IsStepSection && sid.ActiveFormat.PlantFormat.FormatData.TransData.NoDefaultSectReq) return sid.ItemID; } // 3) Find if any of the section titles contain 'PROCEDURES STEPS' - foreach (SectionInfo sit in prcitm.Sections) + foreach (SectionInfo sit in prcitm.Sections.OfType()) { if (sit.DisplayText.ToUpper().Contains("PROCEDURE STEPS")) return sit.ItemID; } - foreach (SectionInfo sit in prcitm.Sections) + foreach (SectionInfo sit in prcitm.Sections.OfType()) { if (sit.DisplayText.ToUpper().Equals("PROCEDURE"))// bug fix: B2015-003 return sit.ItemID; @@ -1173,13 +1074,12 @@ namespace Volian.Controls.Library // check if node is a true end-point, i.e. not a 'part' node. If part node, don't // allow selection. VETreeNode vt = tvTran.SelectedNode as VETreeNode; - ItemInfo selii = vt.VEObject as ItemInfo; - if (selii == null) - { - FlexibleMessageBox.Show("Must select a valid step, not a grouping part such as 'RNO', 'Steps', etc"); - return; - } - SaveCancelEnabling(); + if (!(vt.VEObject is ItemInfo selii)) + { + FlexibleMessageBox.Show("Must select a valid step, not a grouping part such as 'RNO', 'Steps', etc"); + return; + } + SaveCancelEnabling(); //CSM-C2024-026 Evaluate the transitions panel //Create a way to keep it from reverting the transition display panel to the currently selected item/transition. @@ -1197,7 +1097,7 @@ namespace Volian.Controls.Library if (_RangeNode1 == null || (_RangeNode1 != null && _RangeNode2 != null)) { if (_RangeNode1 != null) tvTranRangeHilites(false, _RangeNode1, _RangeNode2); - tvTran.SelectedNode.BackColor = _RangeColor; + tvTran.SelectedNode.BackColor = RangeColor; _RangeNode1 = (VETreeNode)tvTran.SelectedNode; _RangeNode2 = null; lblxTranRangeTip.Text = "Select Last Step \r\nfor Range"; @@ -1208,7 +1108,7 @@ namespace Volian.Controls.Library { if (_RangeNode2 != null) tvTranRangeHilites(false, _RangeNode1, _RangeNode2); _RangeNode2 = (VETreeNode)tvTran.SelectedNode; - tvTran.SelectedNode.BackColor = _RangeColor; + tvTran.SelectedNode.BackColor = RangeColor; tvTranRangeHilites(true, _RangeNode1, _RangeNode2); lblxTranRangeTip.Text = "Select First Transition\r\nfor Range"; lblxTranRangeTip.BackColor = Color.Yellow; @@ -1219,8 +1119,6 @@ namespace Volian.Controls.Library } private void SaveCancelEnabling() { - //bool hasChanged = _CurItemFrom != _SavCurItemFrom || _TranFmtIndx != _SavTranFmtIndx - // || ( selii != null && _CurTrans.ToID != selii.ItemID); bool hasChanged = SettingsChanged; bool isenh = MyRTB != null && MyRTB.MyItemInfo != null && MyRTB.MyItemInfo.IsEnhancedStep; // B2018-002 - Invalid Transitions - Set button enabled if it has a default section or it doesn't need a default @@ -1240,25 +1138,6 @@ namespace Volian.Controls.Library null, null, DevComponents.DotNetBar.eTooltipColor.Gray)); // B2024-007 color of transition panel was not toggling properly groupPanelTranFmt.Style.BackColor = !HasDefault && NeedsDefault ? Color.Red : Color.Orange; - //btnTranSave.Enabled = allowSave; - //if (CurTrans != null && selii != null) - //{ - // if (CurTrans.ToID == selii.ItemID) - // { - // // if the checkbox for including a page number (UseTransitionModifier flag is true) - // // then need to check if this has been changed, and allow a save/cancel if so. - // if (cbPageNum.Visible && _ModExistingPageNum != cbPageNum.Checked) - // btnTranCancel.Enabled = btnTranSave.Enabled = true; - // else - // btnTranCancel.Enabled = btnTranSave.Enabled = false; - // } - // else - // { - // btnTranCancel.Enabled = true; - // btnTranSave.Enabled = allowSave; - // } - //} - //else btnTranCancel.Enabled = btnTranSave.Enabled = allowSave; } private void btnTranCancel_Click(object sender, EventArgs e) { @@ -1314,7 +1193,7 @@ namespace Volian.Controls.Library } private void btnTranSave_Click(object sender, EventArgs e) { - string trantxt = "(Resolved Transition Text)"; + string trantxt; //Resolved Transition Text string linktxt = null; E_TransUI etm = (E_TransUI)_CurItemFrom.ActiveFormat.PlantFormat.FormatData.TransData.TransTypeList[listBoxTranFmt.SelectedIndex].TransUI; // if must have a step, test for this first. @@ -1370,16 +1249,13 @@ namespace Volian.Controls.Library // be sure that the order is right, i.e. to is before range in list. if (toItem.ItemID != rangeItem.ItemID) { - Boolean switchIds = false; - // check for order of hls first, then do within sibling list. - switchIds = RangeItemAndToItemNeedsSwitched(toItem, rangeItem); // B2021-115 switchIds was being set to true when it should not have + // check for order of hls first, then do within sibling list. + Boolean switchIds = RangeItemAndToItemNeedsSwitched(toItem, rangeItem); // B2021-115 switchIds was being set to true when it should not have if (switchIds) { - ItemInfo switchItem = toItem; - toItem = rangeItem; - rangeItem = switchItem; - } - } + (rangeItem, toItem) = (toItem, rangeItem); + } + } linktxt = string.Format("#Link:TransitionRange:{0} {1} {2}", listBoxTranFmt.SelectedIndex, toItem.ItemID, rangeItem.ItemID); } else if ((etm & E_TransUI.StepFirst) == E_TransUI.StepFirst) @@ -1496,7 +1372,7 @@ namespace Volian.Controls.Library if (node1==null && node2==null) return; if (node1 != null && node2 == null) { - node1.BackColor = on ? _RangeColor : tvTran.BackColor; + node1.BackColor = on ? RangeColor : tvTran.BackColor; return; } // If node2 is below node1 in the tree switch them... get to high level step & @@ -1520,15 +1396,13 @@ namespace Volian.Controls.Library } if (i1 > i2) { - VETreeNode t = node2; - node2 = node1; - node1 = t; - } + (node1, node2) = (node2, node1); + } - // Turn Hilighting on/off (depending on bool argument) between the two nodes - // they may be at different tree levels. - // find common parent level first and save the 'top parent' node for each selection. - VETreeNode top1 = node1; + // Turn Hilighting on/off (depending on bool argument) between the two nodes + // they may be at different tree levels. + // find common parent level first and save the 'top parent' node for each selection. + VETreeNode top1 = node1; VETreeNode top2 = node2; // loop, walking up node2's tree checking against node1. If not found, go to node1 // parent, etc. @@ -1551,8 +1425,8 @@ namespace Volian.Controls.Library VETreeNode cur = node1; while (cur != null) { - cur.BackColor = on ? _RangeColor : tvTran.BackColor; - cur = (VETreeNode)(cur.NextNode == null ? cur.Parent : cur.NextNode); + cur.BackColor = on ? RangeColor : tvTran.BackColor; + cur = (VETreeNode)(cur.NextNode ?? cur.Parent); // if these nodes were at the same level, then stop after the current node = range2 if (cur == top1) cur = null; // stop at top if (cur == top2) top1 = cur = null; @@ -1561,32 +1435,27 @@ namespace Volian.Controls.Library cur = top1==null?null:(VETreeNode)top1.NextNode; while (cur != null) { - cur.BackColor = on ? _RangeColor : tvTran.BackColor; + cur.BackColor = on ? RangeColor : tvTran.BackColor; cur = (cur == top2) ? null : (VETreeNode)cur.NextNode; } // finish subtree of second node in range. cur = top2==node2?null:node2; while (cur != null) { - cur.BackColor = on ? _RangeColor : tvTran.BackColor; - cur = (VETreeNode)(cur.PrevNode == null ? cur.Parent : cur.PrevNode); + cur.BackColor = on ? RangeColor : tvTran.BackColor; + cur = (VETreeNode)(cur.PrevNode ?? cur.Parent); if (cur == top2) cur = null; // stop at top } // hilite last selection.. - top2.BackColor = on ? _RangeColor : tvTran.BackColor; + top2.BackColor = on ? RangeColor : tvTran.BackColor; } #endregion public DocVersionInfo Mydvi = null; // this is initialized in vlnTreeComboSetsFillIn() - private static UserInfo _MyUserInfo = null; - public static UserInfo MyUserInfo - { - get { return _MyUserInfo; } - set { _MyUserInfo = value; } - } + public static UserInfo MyUserInfo { get; set; } = null; - private void cbIncStepNum_CheckedChanged(object sender, EventArgs e) + private void cbIncStepNum_CheckedChanged(object sender, EventArgs e) { tvTran.Enabled=cbIncStepNum.Checked; if (!_InitializingTrans) SaveCancelEnabling(); @@ -1610,14 +1479,13 @@ namespace Volian.Controls.Library if (cbHoldProcSet.Checked) { VETreeNode vt = tvTran.SelectedNode as VETreeNode; - ItemInfo selii = vt.VEObject as ItemInfo; - if (selii != null) - { - HeldLinkText = string.Format("#Link:Transition:{0} {1}", listBoxTranFmt.SelectedIndex, selii.ItemID); - HeldLink_TranFmtIndx = listBoxTranFmt.SelectedIndex; - HeldLink_CurItemFrom = selii; - } - } + if (vt.VEObject is ItemInfo selii) + { + HeldLinkText = string.Format("#Link:Transition:{0} {1}", listBoxTranFmt.SelectedIndex, selii.ItemID); + HeldLink_TranFmtIndx = listBoxTranFmt.SelectedIndex; + HeldLink_CurItemFrom = selii; + } + } else { HeldLinkText = ""; @@ -1628,29 +1496,17 @@ namespace Volian.Controls.Library } public class TransItem { - private string _ItemDescription; + public string ItemDescription { get; set; } - public string ItemDescription + public string Format { get; set; } + public TransItem(string desc, string fmt) { - get { return _ItemDescription; } - set { _ItemDescription = value; } - } - - private string _Format; - - public string Format - { - get { return _Format; } - set { _Format = value; } - } - public TransItem(string desc, string fmt) - { - _ItemDescription = desc; - _Format = fmt; + ItemDescription = desc; + Format = fmt; } public override string ToString() { - return _ItemDescription; + return ItemDescription; } } } diff --git a/PROMS/Volian.Controls.Library/DropDownNode.cs b/PROMS/Volian.Controls.Library/DropDownNode.cs index 93aa4345..65aea069 100644 --- a/PROMS/Volian.Controls.Library/DropDownNode.cs +++ b/PROMS/Volian.Controls.Library/DropDownNode.cs @@ -1,4 +1,3 @@ -using System; using System.Windows.Forms; using AT.STO.UI.Win; @@ -8,16 +7,9 @@ namespace Volian.Controls.Library internal class DropDownNode : TreeNode, ILookupItem { #region Private Variable Declarations - private long _id = 0; + private readonly long _id = 0; #endregion #region Constructor / Destructor - /// - /// Default constructor. - /// - public DropDownNode() : base() - { - } - /// /// /// /// Some constructors initializing the node with Id. @@ -29,26 +21,11 @@ namespace Volian.Controls.Library { _id = Id; } - - public DropDownNode(long Id, string Text, DropDownNode[] Children) : base(Text, Children) - { - _id = Id; - } - - public DropDownNode(long Id, string Text, int ImageIndex, int SelectedImageIndex) : base(Text, ImageIndex, SelectedImageIndex) - { - _id = Id; - } - - public DropDownNode(long Id, string Text, int ImageIndex, int SelectedImageIndex, DropDownNode[] Children) : base(Text, ImageIndex, SelectedImageIndex, Children) - { - _id = Id; - } #endregion #region Public Methods public override string ToString() { - return this.GetType().Name + " (Id=" + Id.ToString() + ", Name=" + Text + ")"; + return $"{this.GetType().Name} (Id={Id}, Name={Text})"; } #endregion #region ILookupItem Implementation diff --git a/PROMS/Volian.Controls.Library/DropDownTree.cs b/PROMS/Volian.Controls.Library/DropDownTree.cs index 30a66218..7d8fd4e5 100644 --- a/PROMS/Volian.Controls.Library/DropDownTree.cs +++ b/PROMS/Volian.Controls.Library/DropDownTree.cs @@ -21,12 +21,9 @@ namespace Volian.Controls.Library protected override void OnAfterSelect(TreeViewEventArgs e) { base.OnAfterSelect(e); - - if (ValueChanged != null) - { - ValueChanged(this, new DropDownValueChangedEventArgs(e.Node)); - } - } + + ValueChanged?.Invoke(this, new DropDownValueChangedEventArgs(e.Node)); + } /// /// A double click on a node counts as finish editing. /// diff --git a/PROMS/Volian.Controls.Library/EditItem.cs b/PROMS/Volian.Controls.Library/EditItem.cs index 80a47892..0537312a 100644 --- a/PROMS/Volian.Controls.Library/EditItem.cs +++ b/PROMS/Volian.Controls.Library/EditItem.cs @@ -1,13 +1,11 @@ using System; using System.ComponentModel; using System.Collections.Generic; -using System.Diagnostics; using System.Text; using System.Drawing; using System.Windows.Forms; using System.Text.RegularExpressions; using VEPROMS.CSLA.Library; -using Volian.Base.Library; using JR.Utils.GUI.Forms; using System.Linq; @@ -30,25 +28,9 @@ namespace Volian.Controls.Library #endregion public abstract partial class EditItem : UserControl { - #region EditItemUnique - //private static int _EditItemUnique = 0; - //private static int EditItemUnique - //{ - // get - // { - // if (_EditItemUnique == 3) - // Console.WriteLine("here"); - // return ++_EditItemUnique; - // } - //} - //private int _MyEditItemUnique = EditItemUnique; - - //public int MyEditItemUnique - //{ - // get {return _MyEditItemUnique; } - //} - #endregion #region Constructor + + //Even though 0 references, is called due to being abstract public EditItem() { InitializeComponent(); @@ -68,21 +50,17 @@ namespace Volian.Controls.Library if (MyItemInfo.IsRNOPart) str.SetCopyStepButton(allow); //B2019-009 allow the selection of an RNO step type for CopyStep } - public EditItem(IContainer container) + //Even though 0 references, is called due to being abstract + public EditItem(IContainer container) { container.Add(this); InitializeComponent(); this.Enter += EditItem_Enter; } - #endregion - #region Properties - private bool _RTBLastFocus = true; - public bool RTBLastFocus - { - get { return _RTBLastFocus; } - set { _RTBLastFocus = value; } - } - protected static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); + #endregion + #region Properties + public bool RTBLastFocus { get; set; } = true; + protected static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); protected ChildRelation _MyChildRelation; public ChildRelation MyChildRelation { @@ -95,7 +73,7 @@ namespace Volian.Controls.Library protected EditItem _MyPreviousEditItem = null; protected EditItem _MyNextEditItem = null; private bool _ChildrenLoaded = false; - public bool HasChildren + public new bool HasChildren { get { return _MyBeforeEditItems != null || _MyRNOEditItems != null || _MyAfterEditItems != null; } } @@ -123,13 +101,9 @@ namespace Volian.Controls.Library get { return _MySupInfoEditItems; } set { _MySupInfoEditItems = value; } } - private StepSectionLayoutData _MyStepSectionLayoutData; - public StepSectionLayoutData MyStepSectionLayoutData - { - get { return _MyStepSectionLayoutData; } - set { _MyStepSectionLayoutData = value; } - } - private StepData _MyStepData; + + public StepSectionLayoutData MyStepSectionLayoutData { get; set; } + private StepData _MyStepData; public StepData MyStepData { get { return _MyStepData; } @@ -151,19 +125,15 @@ namespace Volian.Controls.Library get { return _Colapsing; } set { _Colapsing = value; } } - private bool _Moving = false; - private int _RNOLevel = 0; - private int _SeqLevel = 0; - private int _ContentType; + + private int _ContentType; public int ContentType { get { return _ContentType; } set { _ContentType = value; } } - private bool _Circle = false; - private bool _CheckOff = false; - private bool _UserCheckOff = false; - private bool _ChangeBar = false; + + private bool _ChangeBar = false; private StepPanel _MyStepPanel; public StepPanel MyStepPanel { @@ -227,19 +197,12 @@ namespace Volian.Controls.Library value.Changed += new ItemInfoEvent(value_Changed); value.OrdinalChanged -= new ItemInfoEvent(value_OrdinalChanged); value.OrdinalChanged += new ItemInfoEvent(value_OrdinalChanged); - // do something like this to draw circle around step numbers - note got NULL reference error on NSP data - //if (value.FormatStepData != null && value.FormatStepData.TabData.IdentPrint.Contains("C0")) Circle = true; } } - private bool _ChangeBarForConfigItemChange = true; - public bool ChangeBarForConfigItemChange - { - get { return _ChangeBarForConfigItemChange; } - set { _ChangeBarForConfigItemChange = value; } - } + public bool ChangeBarForConfigItemChange { get; set; } = true; - void value_Changed(object sender) + void value_Changed(object sender) { ChangeBar = _MyItemInfo.HasChangeBar; } @@ -308,7 +271,7 @@ namespace Volian.Controls.Library } public EditItem ActiveParent { - get { return _MyParentEditItem != null ? _MyParentEditItem : _MyPreviousEditItem?.ActiveParent; } + get { return _MyParentEditItem ?? (_MyPreviousEditItem?.ActiveParent); } } /// /// Return the Parent EditItem @@ -323,19 +286,16 @@ namespace Volian.Controls.Library return null; } } - private Stack _LastMethods = new Stack(); - //private string _LastMethod = ""; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private Stack _LastMethods = new Stack(); + internal void LastMethodsPush(string str) { if (MyStepPanel != null) MyStepPanel._LastAdjust = str; _LastMethods.Push(str); } - internal string LastMethodsPop() - { - //MyStepPanel._LastAdjust = ""; - return _LastMethods.Pop(); - } - internal bool LastMethodsEmpty + internal string LastMethodsPop() => _LastMethods.Pop(); + internal bool LastMethodsEmpty { get { return _LastMethods.Count == 0; } } @@ -472,8 +432,6 @@ namespace Volian.Controls.Library int? bottomRNO = BottomOfParentRNO(); if (lastBottomPrev > bottom) bottom = (int)(lastBottomPrev); // RHM 20090615 ES02 Step8 // Moving from Step 8 to the Note preceeding step 8 caused the step 9 to be positioned in the wrong place. - //if (lastBottomParent > bottom) bottom = lastBottomParent; - //if (bottomRNO == null) return bottom; return (int)max(bottomRNO, bottom); } internal int FindTop(int bottom) @@ -493,18 +451,14 @@ namespace Volian.Controls.Library MyStepPanel.ItemMoving--; } } - private E_ChangeBarPosition _ChangeBarPosition = E_ChangeBarPosition.Right; - public E_ChangeBarPosition ChangeBarPosition - { - get { return _ChangeBarPosition; } - set { _ChangeBarPosition = value; } - } - /// - /// Sets the next item and adjusts the location, - /// This also sets the previous for the "next" item - /// which adjusts other locations. - /// - public EditItem MyNextEditItem + + public E_ChangeBarPosition ChangeBarPosition { get; set; } = E_ChangeBarPosition.Right; + /// + /// Sets the next item and adjusts the location, + /// This also sets the previous for the "next" item + /// which adjusts other locations. + /// + public EditItem MyNextEditItem { get { return _MyNextEditItem; } set @@ -567,9 +521,6 @@ namespace Volian.Controls.Library // return the bottom most of the two results if (tmpr == null) return tmpa; - //if (rnoOffset > 0) - //Console.WriteLine("RNO Bottom Offset {0}", rnoOffset); - //if (tmpa.Bottom >= (tmpr.Bottom + rnoOffset)) if (tmpa.Bottom >= (tmpr.Bottom)) return tmpa; return tmpr; @@ -615,80 +566,47 @@ namespace Volian.Controls.Library return tmp; } } - private ExpandingStatus _MyExpandingStatus = ExpandingStatus.No; - /// - /// Sets or Gets expanding status - /// - public ExpandingStatus MyExpandingStatus - { - get { return _MyExpandingStatus; } - set { _MyExpandingStatus = value; } - } - /// - /// Gets the ItemID from the ItemInfo - /// - public int MyID + + /// + /// Sets or Gets expanding status + /// + public ExpandingStatus MyExpandingStatus { get; set; } = ExpandingStatus.No; + /// + /// Gets the ItemID from the ItemInfo + /// + public int MyID { get { return _MyItemInfo == null ? 0 : _MyItemInfo.ItemID; } } - /// - /// Tracks when a EditItem is moving - /// - public bool Moving - { - get { return _Moving; } - set { _Moving = value; } - } - /// - /// The RNO (Contingency) Level - /// - public int RNOLevel - { - get { return _RNOLevel; } - set { _RNOLevel = value; } - } - /// - /// Sequential Level - Only counts levels of Sequential substeps - /// - public int SeqLevel - { - get { return _SeqLevel; } - set { _SeqLevel = value; } - } - // TODO: This should be changed to get the Circle format from the data - /// - /// Show a circle or not - /// - public bool Circle - { - get { return _Circle; } - set { _Circle = value; } - } - // TODO: This should be changed to get the Checkoff status from the data - /// - /// Has a check-off or not - /// - public bool CheckOff - { - get { return _CheckOff; } - set { _CheckOff = value; } - } - public bool UserCheckOff - { - get { return _UserCheckOff; } - set { _UserCheckOff = value; } - } - private char _UserCheckOffChar; - public char UserCheckOffChar - { - get { return _UserCheckOffChar; } - set { _UserCheckOffChar = value; } - } - // TODO: This should be changed to get the ChangeBar status from the data - /// - /// Has a changebar or not - /// - public bool ChangeBar + /// + /// Tracks when a EditItem is moving + /// + public bool Moving { get; set; } = false; + /// + /// The RNO (Contingency) Level + /// + public int RNOLevel { get; set; } = 0; + /// + /// Sequential Level - Only counts levels of Sequential substeps + /// + public int SeqLevel { get; set; } = 0; + // TODO: This should be changed to get the Circle format from the data + /// + /// Show a circle or not + /// + public bool Circle { get; set; } = false; + // TODO: This should be changed to get the Checkoff status from the data + /// + /// Has a check-off or not + /// + public bool CheckOff { get; set; } = false; + public bool UserCheckOff { get; set; } = false; + public char UserCheckOffChar { get; set; } + // TODO: This should be changed to get the ChangeBar status from the data + /// + /// Has a changebar or not + /// + public bool ChangeBar { get { return _ChangeBar; } set @@ -708,8 +626,10 @@ namespace Volian.Controls.Library { if (siblingEditItems == null) // Create a list of siblings { - siblingEditItems = new List(); - siblingEditItems.Add(this); + siblingEditItems = new List + { + this + }; MyParentEditItem = parentEditItem; } else // Add to the existing list @@ -764,7 +684,6 @@ namespace Volian.Controls.Library MyParentEditItem = parent; // If a parent exists - this will adjust the location and width of the EditItem AdjustForDevDocStepHeight(); } - //nextEditItem.MyPreviousEditItem = this; MyStepPanel.ItemMoving--; } } @@ -782,24 +701,12 @@ namespace Volian.Controls.Library { RefreshTab(); - if (_MyAfterEditItems != null) _MyAfterEditItems[0].SetAllTabs(); // B2020-043: used to loop through all, but then recursion would redo. - if (_MyNextEditItem != null) _MyNextEditItem.SetAllTabs(); + _MyAfterEditItems?[0].SetAllTabs(); // B2020-043: used to loop through all, but then recursion would redo. + _MyNextEditItem?.SetAllTabs(); // Update the RNO tab if it exists - RHM 20100106 if (_MyRNOEditItems != null) foreach (EditItem chld in _MyRNOEditItems) chld.SetAllTabs(); if (_MySupInfoEditItems != null) foreach (EditItem chld in _MySupInfoEditItems) chld.SetAllTabs(); } - /// - /// Add the next item to a list - /// - /// - /// - /// - //public EditItem AddNext(ItemInfo myItemInfo, bool expand) - //{ - // EditItem tmp = new EditItem(myItemInfo, MyStepPanel, MyParentEditItem, ChildRelation.None, expand); - // MyNextEditItem = tmp; - // return tmp; - //} #endregion #region RemoveItem protected void ShowTops(string title) @@ -810,20 +717,13 @@ namespace Volian.Controls.Library //Console.Write("{0}: TopMostY={1}, TopMostParentY={2}, ParentY = {3}",title, TopMostY, TopMostParentY, ParentY); Console.Write("{0}{1},{2},{3}", title, TopMostY, TopMostParentY.ToString() ?? "null", ParentY.ToString() ?? "null"); } - private bool _BeingRemoved = false; - public bool BeingRemoved - { - get { return _BeingRemoved; } - set { _BeingRemoved = value; } - } - public void RemoveItemWithoutDelete() + + public bool BeingRemoved { get; set; } = false; + public void RemoveItemWithoutDelete() { BeingRemoved = true; - int TopMostYBefore = TopMostEditItem.Top; MyStepPanel._LookupEditItems.Remove(MyID); - EditItem newFocus = null; - int? TopMostParentY = (MyParentEditItem == null ? null : (int?)(MyParentEditItem.TopMostEditItem.Top)); - int? ParentY = (MyParentEditItem == null ? null : (int?)(MyParentEditItem.Top)); + EditItem newFocus; RemoveFromParentsChildList(); if (MyNextEditItem != null) { @@ -866,10 +766,9 @@ namespace Volian.Controls.Library private static int xOffset = 0; public void RemoveItem() { - // if this item has enhanced edititems, remove them: - StepConfig sc = MyItemInfo.MyConfig as StepConfig; - List thisEnhs = null; - if (sc != null) + // if this item has enhanced edititems, remove them: + List thisEnhs = null; + if (MyItemInfo.MyConfig is StepConfig sc) thisEnhs = sc.MyEnhancedDocuments; else { @@ -891,13 +790,13 @@ namespace Volian.Controls.Library BeingRemoved = true; EditItem tmpSelEI = MyStepPanel.SelectedEditItem; // B2021-002: if can't remove, reset SelectedEditItem MyStepPanel.SelectedEditItem = null; // Unselect the item to be deleted - //ShowTops("\r\n"); int TopMostYBefore = TopMostEditItem.Top; - //_MyTimer.ActiveProcess = "DeleteItem"; - // Add a Panel temporarily so that AutoScroll will not happen during the delete. - Panel pnl = new Panel(); - pnl.Size = new Size(10, 10); - MyStepPanel.Controls.Add(pnl); + // Add a Panel temporarily so that AutoScroll will not happen during the delete. + Panel pnl = new Panel + { + Size = new Size(10, 10) + }; + MyStepPanel.Controls.Add(pnl); pnl.BackColor = Color.Red; pnl.Location = new Point(xOffset += 15, MyStepPanel.ClientSize.Height + 10); EditItem newFocus = DeleteItem(); @@ -907,7 +806,6 @@ namespace Volian.Controls.Library MyStepPanel.SelectedEditItem = tmpSelEI; // B2021-002: if can't remove, reset SelectedEditItem return; } - //_MyTimer.ActiveProcess = "SetFocus"; int b4topadjust = newFocus.Top; newFocus.SetFocus(); //shifts edititem to center it @@ -928,18 +826,12 @@ namespace Volian.Controls.Library wndowToRefresh?.MyStepTabPanel.MyStepPanel.Reset(wndowToRefresh.MyItemInfo); } - //_MyTimer.ActiveProcess = "Dispose"; Dispose(); - //_MyTimer.ActiveProcess = "SetAllTabs"; newFocus.SetAllTabs(); - //_MyTimer.ActiveProcess = "TopMostYAfter"; int TopMostYAfter = newFocus.TopMostEditItem.Top; if (TopMostYAfter > TopMostYBefore) newFocus.TopMostEditItem.Top = TopMostYBefore; - //_MyTimer.ActiveProcess = "AdjustLocation"; newFocus.AdjustLocation(); - //newFocus.ShowTops(""); - //_MyTimer.ShowElapsedTimes("RemoveItem"); ForceEditItemRefresh(newFocus); MyStepPanel.Controls.Remove(pnl); foreach (int enhId in enhIds) @@ -956,7 +848,7 @@ namespace Volian.Controls.Library else { EditItem prvOrParSupInfo = newFocus.FindPreviousOrParentSupInfo(); - if (prvOrParSupInfo != null) prvOrParSupInfo.AdjustAllForSupInfoHeight(); + prvOrParSupInfo?.AdjustAllForSupInfoHeight(); } } } @@ -975,15 +867,10 @@ namespace Volian.Controls.Library } public EditItem DeleteItem() { - //Volian.Base.Library.VlnTimer _MyTimer = new VlnTimer(); - //_MyTimer.ActiveProcess = "_LookupEditItems.Remove"; MyStepPanel._LookupEditItems.Remove(MyID); - EditItem newFocus = null; - int? TopMostParentY = (MyParentEditItem == null ? null : (int?)(MyParentEditItem.TopMostEditItem.Top)); - int? ParentY = (MyParentEditItem == null ? null : (int?)(MyParentEditItem.Top)); + EditItem newFocus; try { - //_MyTimer.ActiveProcess = "DeleteItemAndChildren"; Item.DeleteItemAndChildren(MyItemInfo); } catch (System.Data.SqlClient.SqlException ex) @@ -999,9 +886,7 @@ namespace Volian.Controls.Library } // Remove EditItems - //_MyTimer.ActiveProcess = "RemoveFromParentsChildList"; RemoveFromParentsChildList(); - //_MyTimer.ActiveProcess = "MyNextEditItem"; if (MyNextEditItem != null) { if (MyPreviousEditItem != null) @@ -1054,7 +939,6 @@ namespace Volian.Controls.Library MyParentEditItem = null; //Console.Write(",\"Parent\","); } - //_MyTimer.ShowElapsedTimes("DeleteItem"); if (newFocus != null) // B2020-043: Fix transition text when previous text is deleted { newFocus.SetAllTabs(); @@ -1063,7 +947,6 @@ namespace Volian.Controls.Library return newFocus; } - //private void HandleSqlExceptionOnDelete(System.Data.SqlClient.SqlException ex) private void HandleSqlExceptionOnDelete(Exception ex) { // C2020-018 made the messaging consistent in the message boxes @@ -1074,8 +957,7 @@ namespace Volian.Controls.Library MyStepPanel.MyStepTabPanel.MyDisplayTabControl.OnSearchIncTrans(this, new vlnTreeItemInfoEventArgs(MyStepRTB.MyItemInfo)); using (TransitionInfoList exTrans = TransitionInfoList.GetExternalTransitionsToChildren(MyID)) // B2020-109: look at substeps too { - DialogResult ans = FlexibleMessageBox.Show("Transitions exist to this step and cannot be adjusted automatically." + - "\r\n\r\nThe list of all locations are shown in the Tools/Search/Incoming Transitions tab.", + DialogResult ans = FlexibleMessageBox.Show("Transitions exist to this step and cannot be adjusted automatically.\r\n\r\nThe list of all locations are shown in the Tools/Search/Incoming Transitions tab.", "Cannot Delete This Step", MessageBoxButtons.OK, MessageBoxIcon.Information); SetFocus(); } @@ -1085,8 +967,7 @@ namespace Volian.Controls.Library MyStepPanel.MyStepTabPanel.MyDisplayTabControl.OnSearchIncTrans(this, new vlnTreeItemInfoEventArgs(MyStepRTB.MyItemInfo)); using (TransitionInfoList exTrans = TransitionInfoList.GetExternalTransitionsToChildren(MyID)) { - DialogResult ans = FlexibleMessageBox.Show("Transitions exist to this procedure." + - "\r\n\r\nThe list of all locations are shown in the Tools/Search/Incoming Transitions tab.", + DialogResult ans = FlexibleMessageBox.Show("Transitions exist to this procedure.\r\n\r\nThe list of all locations are shown in the Tools/Search/Incoming Transitions tab.", "Cannot Delete This Procedure", MessageBoxButtons.OK, MessageBoxIcon.Information); SetFocus(); } @@ -1098,8 +979,7 @@ namespace Volian.Controls.Library MyStepPanel.MyStepTabPanel.MyDisplayTabControl.OnSearchIncTrans(this, new vlnTreeItemInfoEventArgs(MyStepRTB.MyItemInfo)); using (TransitionInfoList exTrans = TransitionInfoList.GetExternalTransitionsToChildren(MyID)) { - DialogResult ans = FlexibleMessageBox.Show("Transitions exist to this section and cannot be adjusted automatically." + - "\r\n\r\nThe list of all locations are shown in the Tools/Search/Incoming Transitions tab.", + DialogResult ans = FlexibleMessageBox.Show("Transitions exist to this section and cannot be adjusted automatically.\r\n\r\nThe list of all locations are shown in the Tools/Search/Incoming Transitions tab.", "Cannot Delete This Section", MessageBoxButtons.OK, MessageBoxIcon.Information); MyStepPanel.SelectedEditItem = this; } @@ -1109,8 +989,7 @@ namespace Volian.Controls.Library MyStepPanel.MyStepTabPanel.MyDisplayTabControl.OnSearchIncTrans(this, new vlnTreeItemInfoEventArgs(MyStepRTB.MyItemInfo)); using (TransitionInfoList exTrans = TransitionInfoList.GetExternalTransitionsToChildren(MyID)) { - DialogResult ans = FlexibleMessageBox.Show("Transitions exist to the substeps of this step and cannot be adjusted automatically." + - "\r\n\r\nThe list of all locations are shown in the Tools/Search/Incoming Transitions tab.", + DialogResult ans = FlexibleMessageBox.Show("Transitions exist to the substeps of this step and cannot be adjusted automatically.\r\n\r\nThe list of all locations are shown in the Tools/Search/Incoming Transitions tab.", "Cannot Delete This Step", MessageBoxButtons.OK, MessageBoxIcon.Information); SetFocus(); } @@ -1151,17 +1030,6 @@ namespace Volian.Controls.Library if (parentEditItem.MyAfterEditItems == null && parentEditItem.MyBeforeEditItems == null && parentEditItem.MyRNOEditItems == null) parentEditItem.CanExpand = false; } - //private void ShowSiblings(string title) - //{ - // Console.WriteLine("---{0} {1}---",title,MyID); - // EditItem top = this; - // while (top.MyPreviousEditItem != null) top = top.MyPreviousEditItem; - // do - // { - // Console.WriteLine("{0} EditItem - {1} {2}", top.MyID == MyID ? "*" : " ", top.MyID, top.MyItemInfo.MyContent.Text); - // top = top.MyNextEditItem; - // } while (top != null); - //} #endregion #region Add Children /// @@ -1171,8 +1039,8 @@ namespace Volian.Controls.Library /// public void AddChildBefore(ItemInfo myItemInfo, bool expand) { - EditItem child = new RTBItem(myItemInfo, MyStepPanel, this, ChildRelation.Before, expand); - } + _ = new RTBItem(myItemInfo, MyStepPanel, this, ChildRelation.Before, expand); + } /// /// Add a list of children before /// @@ -1199,12 +1067,12 @@ namespace Volian.Controls.Library /// public void AddChildRNO(ItemInfo myItemInfo, bool expand) { - EditItem child = new RTBItem(myItemInfo, MyStepPanel, this, ChildRelation.RNO, expand); - } + _ = new RTBItem(myItemInfo, MyStepPanel, this, ChildRelation.RNO, expand); + } public void AddChildSupInfo(ItemInfo myItemInfo, bool expand) { - EditItem child = new RTBItem(myItemInfo, MyStepPanel, this, ChildRelation.SupInfo, expand); - } + _ = new RTBItem(myItemInfo, MyStepPanel, this, ChildRelation.SupInfo, expand); + } /// /// Add a list of RNO (Contingency) children /// @@ -1229,7 +1097,7 @@ namespace Volian.Controls.Library /// public EditItem AddChildAfter(ItemInfo MyItemInfo, bool expand, bool addFirstChld) { - EditItem child = null; + EditItem child; if (MyItemInfo.IsFigure) child = new ImageItem(MyItemInfo, MyStepPanel, this, ChildRelation.After, expand); else if (MyItemInfo.IsRtfRaw) @@ -1242,7 +1110,7 @@ namespace Volian.Controls.Library } public EditItem AddChildAfter(ItemInfo MyItemInfo, EditItem nextEditItem) { - EditItem child = null; + EditItem child; if (MyItemInfo.IsFigure) child = new ImageItem(MyItemInfo, MyStepPanel, this, ChildRelation.After, true, nextEditItem, FigInsType, _MyStepPropertiesPanel); else if (MyItemInfo.IsRtfRaw) @@ -1255,7 +1123,7 @@ namespace Volian.Controls.Library } public EditItem AddChildBefore(ItemInfo MyItemInfo, EditItem nextEditItem) { - EditItem child = null; + EditItem child; if (MyItemInfo.IsFigure) child = new ImageItem(MyItemInfo, MyStepPanel, this, ChildRelation.Before, true, nextEditItem, FigInsType, _MyStepPropertiesPanel); else if (MyItemInfo.IsRtfRaw) @@ -1269,8 +1137,7 @@ namespace Volian.Controls.Library public EditItem AddChildRNO(ItemInfo MyItemInfo, EditItem nextEditItem) { // not sure about this, i.e. whether a grid can be added here. - EditItem child = null; - //if (MyItemInfo.MyContent.ContentGridCount != 0) + EditItem child; if (MyItemInfo.MyContent.MyGrid != null) child = new GridItem(MyItemInfo, MyStepPanel, this, ChildRelation.RNO, true, nextEditItem); else @@ -1279,7 +1146,7 @@ namespace Volian.Controls.Library } public EditItem AddChildSupInfo(ItemInfo MyItemInfo, EditItem nextEditItem) { - EditItem child = null; + EditItem child; if (MyItemInfo.MyContent.MyGrid != null) child = new GridItem(MyItemInfo, MyStepPanel, this, ChildRelation.SupInfo, true, nextEditItem); else @@ -1392,7 +1259,6 @@ namespace Volian.Controls.Library default: // Need debug break; } - //EditItem newEditItem = ActiveParent.AddChildAfter(newItemInfo, ); if (updateStatus) MyStepPanel.SelectedEditItem = newEditItem;//Update Screen } @@ -1459,36 +1325,12 @@ namespace Volian.Controls.Library if (updateSelection) MyStepPanel.SelectedEditItem = newEditItem;//Update Screen } - public void AddSiblingBeforeNoDataSave(ItemInfo newItemInfo, bool updateSelection, EditItem tt) - { - EditItem newEditItem = null; - newEditItem = ActiveParent.AddChildBefore(newItemInfo, this); - //switch (_MyChildRelation) - //{ - // case ChildRelation.After: - // newEditItem = ActiveParent.AddChildAfter(newItemInfo, this); - // break; - // case ChildRelation.Before: - // newEditItem = ActiveParent.AddChildBefore(newItemInfo, this); - // break; - // case ChildRelation.RNO: - // newEditItem = ActiveParent.AddChildRNO(newItemInfo, this); - // break; - // default: // Need debug - // break; - //} - if (updateSelection) - MyStepPanel.SelectedEditItem = newEditItem;//Update Screen - } - private bool specialAdd = false; public void AddSiblingBeforeNoDataSave(ItemInfoList newItemInfos, bool updateSelection) { - specialAdd = true; - EditItem newEditItem = null; + EditItem newEditItem; newEditItem = ActiveParent.AddChildAfter(newItemInfos, false, true); if (updateSelection) MyStepPanel.SelectedEditItem = newEditItem;//Update Screen - specialAdd = false; } private ImageItem.E_ImageSource FigInsType = ImageItem.E_ImageSource.None; public void AddChild(E_FromType fromType, int type, ImageItem.E_ImageSource newSource) @@ -1519,15 +1361,11 @@ namespace Volian.Controls.Library { itm.MyContent.MyGrid.Data = xml; itm.Save(); - // newItemInfo.MyContent.MyGrid.ResetContent(itm.MyContent.MyGrid); // Do I need this? } } // TODO: We need to determine where this will go in the stack of children EditItem nextItem = GetNextItem(fromType, newItemInfo); // TODO: May need similar logic if a Table is being added to a step that has substeps - // else if (fromType == E_FromType.Table && ((ItemInfo)newItemInfo.ActiveParent).Steps != null - //&& ((ItemInfo)newItemInfo.ActiveParent).Steps.Count > 0) - // nextItem = MyStepPanel.FindItem(((ItemInfo)newItemInfo.ActiveParent).Steps[0]); EditItem newEditItem; switch (fromType) { @@ -1631,14 +1469,6 @@ namespace Volian.Controls.Library child = AddChildAfter(item, expand, false); return child; } - public EditItem AddChildAfter(ItemInfoList myItemInfoList, EditItem nextEditItem) - { - EditItem child = null; - if (myItemInfoList != null) - foreach (ItemInfo item in myItemInfoList) - child = AddChildAfter(item, nextEditItem); - return child; - } #endregion #region CopyPaste public void PasteSiblingBefore(int copyStartID) @@ -1730,7 +1560,7 @@ namespace Volian.Controls.Library { // if tabcontrol was open for enhanced, display the steps: ItemInfo proc = newEnh.MyProcedure; // Find procedure Item - string key = "Item - " + proc.ItemID.ToString(); + string key = $"Item - {proc.ItemID}"; if (MyStepPanel.MyStepTabPanel.MyDisplayTabControl._MyDisplayTabItems.ContainsKey(key)) { DisplayTabItem pg = MyStepPanel.MyStepTabPanel.MyDisplayTabControl._MyDisplayTabItems[key]; @@ -1884,7 +1714,6 @@ namespace Volian.Controls.Library fromType = E_FromType.Section; else if (MyItemInfo.MyContent.Type > 19999) { - int tmptype = (int)MyItemInfo.MyContent.Type - 20000; if (MyItemInfo.IsCaution) fromType = E_FromType.Caution; else if (MyItemInfo.IsNote) fromType = E_FromType.Note; else if (MyItemInfo.IsTable) fromType = E_FromType.Table; @@ -1930,7 +1759,8 @@ namespace Volian.Controls.Library ItemInfo newEnh = newItemInfo.EnhancedPasteItem(copyStartID, MyItemInfo, ItemInfo.EAddpingPart.Child, GetChangeId(MyItemInfo)); if (newEnh != null) AddAllEnhancedItemsToDisplay(newItemInfo); } - public EditItem PasteReplace(int copyStartID) + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0059:Unnecessary assignment of a value", Justification = "savOrigPasteConfig kept for Debugging. newFocus kept to shift focus")] + public EditItem PasteReplace(int copyStartID) { if (this is RTBItem) (this as RTBItem).DoingPasteReplace = true; // To allow a Paste Step into an empty (new) step/substep, we need to add a character to the the Text field @@ -1939,10 +1769,9 @@ namespace Volian.Controls.Library MyStepPanel.SelectedEditItem.Empty = false; MyStepPanel.SelectedEditItem = null; // Unselect the item to be deleted ChildRelation childRelation = _MyChildRelation; - EditItem newFocus = null; + EditItem newFocus; EditItem nextEditItem = MyNextEditItem; - EditItem prevEditItem = MyPreviousEditItem; - EditItem parentEditItem = null; // ActiveParent; + EditItem parentEditItem; // ActiveParent; try { parentEditItem = ActiveParent ?? MyStepPanel?.SelectedEditItem?.ActiveParent; @@ -1954,10 +1783,7 @@ namespace Volian.Controls.Library } StepConfig savOrigPasteConfig = MyItemInfo.MyConfig as StepConfig; - int TopMostYBefore = TopMostEditItem.Top; - int? TopMostParentY = (MyParentEditItem == null ? null : (int?)(MyParentEditItem.TopMostEditItem.Top)); - int? ParentY = (MyParentEditItem == null ? null : (int?)(MyParentEditItem.Top)); - ItemInfo newItemInfo = null; + ItemInfo newItemInfo; bool gotoFirstTrans = false; try { @@ -1975,7 +1801,6 @@ namespace Volian.Controls.Library return this; // aborted the replace so just return to the step we were trying to replace } } - //catch (System.Data.SqlClient.SqlException ex) catch (Exception ex) { if (HandleSqlExceptionOnCopy(ex)) return this; @@ -2087,51 +1912,21 @@ namespace Volian.Controls.Library } } } - #endregion - #region Event Handlers - private string WatchThisIndent - { - get { return "".PadLeft(_WatchThis, '\t'); } - } - protected bool RNOBelow - { - get - { - if (_MyRNOEditItems != null) - { - return _MyRNOEditItems[0].RNOLevel > _MyItemInfo.ColumnMode; - //return _MyRNOEditItems[0].Left == Left; - } - return false; - } - } - protected bool RNORight - { - get - { - if (_MyRNOEditItems != null) - { - return _MyRNOEditItems[0].RNOLevel <= _MyItemInfo.ColumnMode; - //return _MyRNOEditItems[0].Left != Left; - } - return false; - } - } - protected void MoveRNO() + #endregion + #region Event Handlers + protected bool RNOBelow => _MyRNOEditItems != null && _MyRNOEditItems[0].RNOLevel > _MyItemInfo.ColumnMode; + protected bool RNORight => _MyRNOEditItems != null && _MyRNOEditItems[0].RNOLevel <= _MyItemInfo.ColumnMode; + protected void MoveRNO() { if (_MyRNOEditItems != null) { if (_MyRNOEditItems[0].TopMostEditItem.Top != Top) { - //if(_MyLog.IsDebugEnabled)_MyLog.DebugFormat("\r\n'Adjust RNO',{0},'Move',{1}", MyID, _RNO[0].MyID); EditItem rnoTop = _MyRNOEditItems[0].TopMostEditItem; if (rnoTop.RNOLevel <= _MyItemInfo.ColumnMode) { - //EditItem tmpBottom = this; - //if (_MyAfterEditItems != null) tmpBottom = _MyAfterEditItems[_MyAfterEditItems.Count - 1].BottomMostEditItem; MyStepPanel.ItemMoving++; rnoTop.LastMethodsPush(string.Format("EditItem_Move RNO Right {0}", rnoTop.MyID)); - //rnoTop.Top = tmpBottom.Bottom; if (rnoTop.Top != Top) rnoTop.Top = Top; rnoTop.LastMethodsPop(); @@ -2164,14 +1959,9 @@ namespace Volian.Controls.Library } } } - private bool _TryAgainLater = false; - public bool TryAgainLater - { - get { return _TryAgainLater; } - set { _TryAgainLater = value; } - } - //static bool _ShowChanges=false; - int _LastTop = 0; + + public bool TryAgainLater { get; set; } = false; + int _LastTop = 0; // Bug Fix: B2017-059 only turn on the spellchecking if the RTB is visible. This controls the number of windows handles created durning spellchecking private void TurnOnSpellCheckIfVisible() @@ -2307,7 +2097,6 @@ namespace Volian.Controls.Library } // Calulate the x location - //int x = myParentEditItem.TextLeft; int x = center - width / 2; if (x + width > rightLimit) x = rightLimit - width; // B2017-043 account for Horizontal Scroll @@ -2319,11 +2108,8 @@ namespace Volian.Controls.Library int y = FindTop(myParentEditItem.Bottom); return new Point(x, y); } - protected void DoMouseWheel(MouseEventArgs e) - { - MyStepPanel.MouseWheel(e); - } - protected void InsertPgBrk() + protected void DoMouseWheel(MouseEventArgs e) => MyStepPanel.MouseWheel(e); + protected void InsertPgBrk() { MyStepPanel.MyStepTabPanel.MyStepTabRibbon.btnInsPgBrk_Click(this, new EventArgs()); MyStepPropertiesPanel.UpdatePageBreakCheckBox(); // update the checkbox on the Step Properties panel @@ -2338,8 +2124,7 @@ namespace Volian.Controls.Library } protected void ToggleContinuousActionSummary() { - if (MyStepPropertiesPanel != null) // bug fix B2016-256 check for a null reference incase we are not on a step element - MyStepPropertiesPanel.ToggleContActSummary(); // update the checkbox on the Step Properties panel + MyStepPropertiesPanel?.ToggleContActSummary(); // update the checkbox on the Step Properties panel if (!MyStepRTB.ContainsFocus) MyStepRTB.Focus(); } @@ -2367,32 +2152,20 @@ namespace Volian.Controls.Library if (!MyStepRTB.ContainsFocus) MyStepRTB.Focus(); } - protected void OpenAnnotations() - { - MyStepPanel.MyStepTabPanel.MyStepTabRibbon.btnAnnots_Click(this, new EventArgs()); - } - protected bool CheckClipboard() - { - return (MyStepPanel.MyStepTabPanel.MyDisplayTabControl.MyCopyStep != null); - } - protected void CopyStep() - { - MyStepPanel.MyStepTabPanel.MyStepTabRibbon.DoCopyStep(); - } - /// - /// Finds the last child in a list - /// - /// - /// - private static EditItem LastChild(List childEditItems) - { - return childEditItems[childEditItems.Count - 1]; - } - /// - /// If the selected EditItem is within the window leave it as it is. - /// If not, scroll so that the selected window is centered. - /// - protected void ScrollToCenter() + protected void OpenAnnotations() => MyStepPanel.MyStepTabPanel.MyStepTabRibbon.btnAnnots_Click(this, new EventArgs()); + protected bool CheckClipboard() => (MyStepPanel.MyStepTabPanel.MyDisplayTabControl.MyCopyStep != null); + protected void CopyStep() => MyStepPanel.MyStepTabPanel.MyStepTabRibbon.DoCopyStep(); + /// + /// Finds the last child in a list + /// + /// + /// + private static EditItem LastChild(List childEditItems) => childEditItems[childEditItems.Count - 1]; + /// + /// If the selected EditItem is within the window leave it as it is. + /// If not, scroll so that the selected window is centered. + /// + protected void ScrollToCenter() { //vlnStackTrace.ShowStack("CenterScroll {0} Current {1} Top {2} Bottom {3} Limit {4}", _MyItem.ItemID, _Panel.VerticalScroll.Value, Top, Bottom, _Panel.Height);// Show StackTrace //Console.WriteLine("CenterScroll {0} Current {1} Top {2} Bottom {3} Limit {4}", _MyItem.ItemID, _Panel.VerticalScroll.Value, Top, Bottom, _Panel.Height); @@ -2404,7 +2177,6 @@ namespace Volian.Controls.Library // Limit scroll location within allowable values scrollValue = Math.Max(MyStepPanel.VerticalScroll.Minimum, Math.Min(MyStepPanel.VerticalScroll.Maximum, scrollValue)); //Console.WriteLine("CenterScroll {0} Current {1} New {2} Min {3} Max {4}", _MyItem.ItemID, _Panel.VerticalScroll.Value, scrollValue, _Panel.VerticalScroll.Minimum, _Panel.VerticalScroll.Maximum); - //if (scrollValue >= MyStepPanel.VerticalScroll.Minimum && scrollValue <= MyStepPanel.VerticalScroll.Maximum) // If it is within range MyStepPanel.VerticalScroll.Value = scrollValue; // Center the item } @@ -2490,35 +2262,6 @@ namespace Volian.Controls.Library } } } - /// - /// Expand a list of children - /// - /// - private void ExpandChildren(List childEditItems) - { - if (childEditItems != null) - { - foreach (EditItem child in childEditItems) - { - if (child.CanExpand) - { - child.Expand(true); - } - child.Hidden = false; - } - } - } - /// - /// Expand children - /// - private void ExpandChildren() - { - // Walk though Children performing Expand - ExpandChildren(_MyBeforeEditItems); - ExpandChildren(_MyRNOEditItems); - ExpandChildren(_MySupInfoEditItems); - ExpandChildren(_MyAfterEditItems); - } private string MyPath { get @@ -2559,6 +2302,7 @@ namespace Volian.Controls.Library if (RNOLevel > 0 && AEREditItem != null) AEREditItem.AdjustLocation(); EditItem nextEditItem = NextDownEditItem; + //For Debugging: //if(_LookForID.Contains(MyID)) // Console.WriteLine("{0}AdjustLocation {1},{2},{3} -> {4},{5} ({6}) {7}", WatchThisIndent, MyID, MyItemInfo.Ordinal, MyPath, // nextEditItem == null ? 0 : nextEditItem.MyID, nextEditItem == null ? 0 : nextEditItem.MyItemInfo.Ordinal, nextEditItem == null ? "Null" : nextEditItem.MyPath, @@ -2591,12 +2335,6 @@ namespace Volian.Controls.Library AdjustForDevDocStepHeight(); } } - // SameRowAsParent - Comanche Peak Step Designator - //FormatData fmtdata = MyItemInfo.ActiveFormat.PlantFormat.FormatData; - //int formatSteptype = MyItemInfo.FormatStepType; - //if (fmtdata.StepDataList[formatSteptype].SameRowAsParent) - //if (MyItemInfo.SameRowAsParent && MyItemInfo.IsCaution2) - // bottom = Top; // If this is a "TitleWithTextRight", don't move down on the screen but only if it has a // child, i.e. want the child to be positioned on line, but if no child, move down on screen: @@ -2635,12 +2373,7 @@ namespace Volian.Controls.Library else // B2018-072 nextEditItem is null, remove "this" from AdjustItems list, otherwise get infinate loop in ProcessAdjustItems() on last HSL with RNO but no AER substeps if (AdjustItems.Contains(this)) AdjustItems.Remove(this); } - private static List _AdjustItems=new List();// B2017-175 Keep a list of EditItems to adjust after expanding - public static List AdjustItems - { - get { return _AdjustItems; } - set { _AdjustItems = value; } - } + public static List AdjustItems { get; set; } = new List(); // B2017-175 Keep a list of EditItems to adjust after expanding private static void AddAdjustItem(EditItem ei)// B2017-175 Add edit item to adjust after expanding { if(!AdjustItems.Contains(ei)) AdjustItems.Add(ei); @@ -2650,16 +2383,11 @@ namespace Volian.Controls.Library while (AdjustItems.Count > 0) AdjustItems[0].AdjustLocation(); } - private int _DevDocHeight = 0; // Deviation Document Step Height B2016-123, B2017-020, B2017-021 - public int DevDocHeight - { - get { return _DevDocHeight; } - set { _DevDocHeight = value; } - } - public void TryAgainNow(int bottom) + + public int DevDocHeight { get; set; } = 0; // Deviation Document Step Height B2016-123, B2017-020, B2017-021 + public void TryAgainNow(int bottom) { TryToSetTop(bottom - 10); - //TryToSetTop(bottom+10); TryToSetTop(bottom); } private void TryToSetTop(int offset) @@ -2692,7 +2420,6 @@ namespace Volian.Controls.Library /// normally equal to _Type > = 20000 (Step) public void Expand(bool expand) { - //// TIMING: DisplayItem.TimeIt("Expand Start"); if (_ChildrenLoaded) { // Unhide Children @@ -2707,18 +2434,14 @@ namespace Volian.Controls.Library } else TopMostEditItem.AdjustLocation(); - //_ShowChanges = true; + AdjustChildren(); - //_ShowChanges = false; - //if(_Before != null ) - // Top = _Before[_Before.Count - 1].BottomMost.Bottom; } else { if (MyItemInfo.IsHigh) MyStepPanel.ExpandingHLS = MyItemInfo; MyExpandingStatus = ExpandingStatus.Expanding; _ChildrenLoaded = true; - //_Panel.SuspendLayout(); AddChildBefore(MyItemInfo.Cautions, expand); AddChildBefore(MyItemInfo.Notes, expand); AddChildAfter(MyItemInfo.Procedures, expand); @@ -2750,7 +2473,6 @@ namespace Volian.Controls.Library if (MyItemInfo.IsHigh) ProcessAdjustItems(); // B2017-175 Adjust after expanding MyExpandingStatus = ExpandingStatus.No; - //// TIMING: DisplayItem.TimeIt("Expand End"); } public EditItem BeforeItem { @@ -2786,11 +2508,6 @@ namespace Volian.Controls.Library if (value1 == null || value2 > value1) return value2; return value1; } - private static int min(int value1, int value2) - { - if (value2 < value1) return value2; - return value1; - } public int FindRight() { if (!RNORight) return Right; @@ -2891,7 +2608,6 @@ namespace Volian.Controls.Library if (this != btm) // If this is not the bottom, then just adjust things with respect to the bottom { EditItem btmNext = btm.NextDownEditItem; - //if (EditItem.MyNextEditItem != null && EditItem.MyNextEditItem.TopMostEditItem.Top != btm.Bottom) if (btmNext != null) { int bottom = btmNext.FindTop(btm.Bottom); @@ -2903,10 +2619,8 @@ namespace Volian.Controls.Library if (btmNext.Top != bottom) { MyStepPanel.ItemMoving++; - //EditItem.MyNextEditItem.TopMostEditItem.Top = btm.Bottom; //Console.WriteLine("{0}***Move in NextDownEditItem {1},{2} From {3} To {4}",WatchThisIndent, btmNext.MyID, btmNext, btmNext.Top, btm.Bottom); btmNext.LastMethodsPush(string.Format("NextDownEditItem {0} {1}", MyID, EditItem.MyID)); - //ShowMe(string.Format("FindTop = {0}", btmNext.FindTop(btm.Bottom))); if (btmNext.Top != bottom) btmNext.Top = bottom; btmNext.LastMethodsPop(); @@ -2916,19 +2630,13 @@ namespace Volian.Controls.Library _NextDownEditItemPath = string.Format("Path 9 {0}", btm); return null; // Not the bottom - don't adjust anything else } - //else - //{ - //} } if (EditItem != null) { // Need to verify that the bottom of the parents RNO does not excede the bottom of this item. EditItem next = EditItem.MyNextEditItem.TopMostEditItem; _NextDownEditItemPath = "Path A"; - //if (Bottom >= (BottomOfParentRNO(next) ?? Bottom)) return next;// if no _After - check to see if there is a Next - //_NextDownEditItemPath = "Path B"; - //return null; } _NextDownEditItemPath = "Path C"; return null; @@ -2943,7 +2651,7 @@ namespace Volian.Controls.Library } public override string ToString() { - return _MyItemInfo == null ? base.ToString() : string.Format("{0},'{1}',{2},{3}", MyID, MyPath, Top, Bottom); // + "-" + MyItemInfo.MyContent.Text; + return _MyItemInfo == null ? base.ToString() : string.Format("{0},'{1}',{2},{3}", MyID, MyPath, Top, Bottom); } #endregion #region Abstract Methods and Properties @@ -2980,8 +2688,6 @@ namespace Volian.Controls.Library public abstract void IdentifyMe(bool highlight); public abstract void SetActive(); public abstract bool Empty { get; set; } - //public abstract bool IsEmpty(); - //public abstract void MakeNotEmpty(); public abstract void RefreshDisplay(bool activeMode); public abstract void ToggleEditView(E_ViewMode vwMode); public abstract int TabLeft { get; set; } @@ -3006,7 +2712,7 @@ namespace Volian.Controls.Library } } protected string _TabFormat; - private static int _WidthAdjust = 5; + private static readonly int _WidthAdjust = 5; protected bool _IgnoreResize = false; private int FindBottomDevDoc // Find Bottom of a Deviation Document Step { @@ -3124,7 +2830,6 @@ namespace Volian.Controls.Library ItemLocation = new Point(_MyParentEditItem.ItemLocation.X + _MyParentEditItem.ItemWidth + 10, _MyParentEditItem.ItemLocation.Y); // F2017-011 added 10 to fix positoning of Purpose text on sceen (enhanced backgrounds) else if (MyItemInfo.MyTab.Offset != 0) ContentLocation = new Point(_MyParentEditItem.ContentLocation.X + 10, _MyParentEditItem.Bottom); - //ItemLocation = new Point(_MyParentEditItem.ItemLocation.X+10, _MyParentEditItem.Bottom); else { // B2016-134 Fix - If a previous step exists, use it to locate the current step @@ -3176,7 +2881,7 @@ namespace Volian.Controls.Library else if (MyItemInfo.MyParent.FormatStepData.Type == "TitleWithTextRight") { ItemWidth = MyStepPanel.ToDisplay(MyStepSectionLayoutData.ColT) + MyStepPanel.ToDisplay(MyStepSectionLayoutData.WidSTableEdit, 0); - ItemWidth = ItemWidth - ItemLocation.X; + ItemWidth -= ItemLocation.X; } else if (MyParentEditItem != null && MyParentEditItem.MyItemInfo.FormatStepData.ReadOnly) ItemWidth = MyStepPanel.ToDisplay(MyStepSectionLayoutData.ColT) + MyStepPanel.ToDisplay(MyStepSectionLayoutData.WidSTableEdit, 0); @@ -3249,12 +2954,9 @@ namespace Volian.Controls.Library _IgnoreResize = false; if (RNOLevel <= MyItemInfo.ColumnMode) { - //int colR = MyStepPanel.ToDisplay(_MyStepSectionLayoutData.ColRTable, Convert.ToInt32(_MyStepSectionLayoutData.PMode) - 1); int colR = MyStepPanel.ToDisplay(MyStepSectionLayoutData.ColRTable, MyItemInfo.ColumnMode); if (colR - _MyParentEditItem.Width < 0) colR = _MyParentEditItem.Width + 0; MyStepPanel.ItemMoving++; - //Left = _MyParentRTBItem.ItemLeft + RNOLevel * colR; - //ItemLocation = new Point(_MyParentRTBItem.ItemLeft + RNOLevel * colR, _MyParentRTBItem.Top); LastMethodsPush(string.Format("set_MyParentRTBItem RNO Right {0}", MyID)); ItemLocation = new Point(_MyParentEditItem.ItemLeft + RNOLevel * colR, _MyParentEditItem.Top); int top = _MyParentEditItem.FindTop(_MyParentEditItem.Top); @@ -3275,34 +2977,21 @@ namespace Volian.Controls.Library LastMethodsPush(string.Format("set_MyParentRTBItem RNO Below {0} {1} {2}", MyID, _MyParentEditItem.BottomMostEditItem.MyID, _MyParentEditItem.BottomMostEditItem.Bottom)); ContentLocation = new Point(_MyParentEditItem.ContentLeft, _MyParentEditItem.BottomMostEditItem.Bottom); LastMethodsPop(); - //TextLocation = new Point(_MyParentRTBItem.TextLeft, FindTop(_MyParentRTBItem.Top)); MyStepPanel.ItemMoving--; } // Same size as the Parent break; case ChildRelation.Before: // Cautions and Notes - //if(_WatchThis > 0 && MyID > 2111) - // Console.WriteLine("Setting MyParent: \r\n\tParent {0},{1} \r\n\tTopMostItem {2},{3} \r\n\tNext {4}, {5}", _MyParentRTBItem.MyID, _MyParentRTBItem - // ,_MyParentRTBItem.TopMostRTBItem.MyID,_MyParentRTBItem.TopMostRTBItem - // , _MyNextRTBItem == null ? 0 : _MyNextRTBItem.MyID, _MyNextRTBItem == null ? "None" : _MyNextRTBItem.ToString()); - - //Location = new Point(_MyParentRTBItem.Left + 20, max(_MyParentRTBItem.Top, (_MyNextRTBItem == null ? 0 : _MyNextRTBItem.Top )) ?? 0); _IgnoreResize = true; int spaceToRTB = 23; _IgnoreResize = false; MyStepPanel.ItemMoving++; - //Location = new Point(_MyParentRTBItem.Left + 20, FindTop(_MyParentRTBItem.Top)); - int myTop = 0; + int myTop; if (MyNextEditItem == null) myTop = _MyParentEditItem.Top; else myTop = MyNextEditItem.Top; - //if (MyItemInfo.SameRowAsParent && MyItemInfo.IsCaution2) - //{ - // if (MyItemInfo.WidthOverride > 0) - // Width = MyStepPanel.ToDisplay(MyItemInfo.WidthOverride) + spaceToRTB; - //} if (MyItemInfo.ActiveFormat.MyStepSectionLayoutData.Dev_Format && (MyItemInfo.IsCaution || MyItemInfo.IsNote)) { // B2017-043 account for Horizontal Scroll @@ -3313,7 +3002,7 @@ namespace Volian.Controls.Library // Get the "bottom" number of the longest Caution/Note on the step/substep above so that // we can position properly on the screen. // EX. Catawba Deviations E-1 step deviation for step 10 - EditItem eitm = (MyParentEditItem.MyPreviousEditItem != null) ? MyParentEditItem.MyPreviousEditItem : MyParentEditItem.MyParentEditItem; + EditItem eitm = MyParentEditItem.MyPreviousEditItem ?? MyParentEditItem.MyParentEditItem; if (eitm != null && eitm.MyBeforeEditItems != null) foreach (EditItem eitmTmp in eitm.MyBeforeEditItems) y = Math.Max(y, eitmTmp.Bottom); @@ -3331,9 +3020,8 @@ namespace Volian.Controls.Library if (MyItemInfo.FormatStepData != null && MyItemInfo.FormatStepData.UseOldTemplate && ((MyItemInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DSS_PageListSpBckgrnd) == E_DocStructStyle.DSS_PageListSpBckgrnd)) widthtpl = MyParentEditItem.Width + MyParentEditItem.Left - Left; - Width = widthtpl; // MyStepPanel.ToDisplay(MyStepSectionLayoutData.WidT) + spaceToRTB; + Width = widthtpl; MyStepPanel.ItemMoving--; - //_MyParentRTBItem.Top = Bottom; // Could be a Caution or Note - Need to get WidT break; } @@ -3343,7 +3031,7 @@ namespace Volian.Controls.Library } private int BottomOfStepImmediatelyAbove() { - int btm = 0; + int btm; if (MyBeforeEditItems != null && MyBeforeEditItems.Count > 0) // Notes & Cautions before btm = MyBeforeEditItems[MyBeforeEditItems.Count - 1].BottomMostEditItem.Bottom; else @@ -3405,9 +3093,6 @@ namespace Volian.Controls.Library } else if (MyPreviousEditItem != null && MyPreviousEditItem.MyItemInfo.FormatStepData != null && MyPreviousEditItem.MyItemInfo.FormatStepData.ReadOnly) ItemWidth = MyStepPanel.ToDisplay(MyStepSectionLayoutData.ColT) + MyStepPanel.ToDisplay(MyStepSectionLayoutData.WidSTableEdit, 0); - // RHM The following lines were commented-out for Facing Pages (Supplemental Information) to test follow the instructions - //else if (MyItemInfo.MyTab.Offset != 0) // Farley - part of bug fix B2015-123 alignment of tabs on the edit screen (Farly is only one using tab offset) - // ContentWidth = (MyPreviousEditItem.MyItemInfo.MyTab.Offset != 0) ? MyPreviousEditItem.ContentWidth : MyPreviousEditItem.ContentWidth + 10; else Width = MyPreviousEditItem.Width; @@ -3416,7 +3101,6 @@ namespace Volian.Controls.Library if (MyItemInfo.ActiveFormat.MyStepSectionLayoutData.Dev_Format && (MyItemInfo.IsNote || MyItemInfo.IsCaution) && (MyPreviousEditItem == null || (MyPreviousEditItem.MyItemInfo.IsCaution && MyItemInfo.IsNote))) - //if ((MyItemInfo.SameRowAsParent && MyItemInfo.IsCaution2) || (MyItemInfo.ActiveFormat.MyStepSectionLayoutData.Dev_Format && (MyItemInfo.IsNote || MyItemInfo.IsCaution))) { // B2017-043 account for Horizontal Scroll int x = MyStepPanel.DisplayRectangle.X + MyStepPanel.ToDisplay(MyItemInfo.ActiveFormat.MyStepSectionLayoutData.ColT); @@ -3432,7 +3116,6 @@ namespace Volian.Controls.Library { int top = FindTop(_MyPreviousEditItem.BottomMostEditItem.Bottom); if (MyItemInfo.ActiveFormat.MyStepSectionLayoutData.Dev_Format && _MyPreviousEditItem.MyItemInfo.IsHigh) - //if (MyItemInfo.SameRowAsParent || (MyItemInfo.ActiveFormat.MyStepSectionLayoutData.Dev_Format && _MyPreviousEditItem.MyItemInfo.IsHigh)) { if (_MyPreviousEditItem.MyBeforeEditItems != null) foreach (EditItem ei in _MyPreviousEditItem.MyBeforeEditItems) @@ -3448,15 +3131,6 @@ namespace Volian.Controls.Library TopMostEditItem.Location = new Point(TopMostEditItem.Left, FindTop(_MyPreviousEditItem.BottomMostEditItem.Bottom)); } _IgnoreResize = false; - //ShowMe(""); - //if (MyID > _StartingID) - // Console.WriteLine("{0}-->Setting MyPreviousRTBItem {1},{2},{3},{4},{5},{6},{7}", WatchThisIndent, MyID, this - // , _MyPreviousRTBItem - // ,Top - // , _MyPreviousRTBItem.BottomMostRTBItem.Bottom - // , FindTop(_MyPreviousRTBItem.BottomMostRTBItem.Bottom) - // , _MyPreviousRTBItem.Bottom); - //Location = new Point(_MyPreviousRTBItem.Left, _MyPreviousRTBItem.BottomMostRTBItem.Bottom); switch (_MyChildRelation) { case ChildRelation.None: @@ -3468,9 +3142,6 @@ namespace Volian.Controls.Library case ChildRelation.SupInfo: break; case ChildRelation.Before: - //MyStepPanel.ItemMoving++; - //UpOneRTBItem.Top = BottomMostRTBItem.Bottom; - //MyStepPanel.ItemMoving--; break; } if (_MyPreviousEditItem.MyNextEditItem != this) _MyPreviousEditItem.MyNextEditItem = this; @@ -3499,7 +3170,7 @@ namespace Volian.Controls.Library // find first edititem below this (EIWsupInfoBelow) or a sibling or child child that have sup info // if found, adjust top of this item to the bottommost edititem above this - EditItem EIWsupInfoBelow = null; + EditItem EIWsupInfoBelow; EIWsupInfoBelow = EIsupInfoPartAbove.MyParentEditItem.FindFirstChildWithSupInfo(EIsupInfoPartAbove.MyParentEditItem.MyItemInfo); if (EIWsupInfoBelow == null) EIWsupInfoBelow = EIsupInfoPartAbove.MyParentEditItem.FindSiblingOrParentSiblingWithSupInfo(EIsupInfoPartAbove.MyParentEditItem.MyItemInfo); @@ -3512,7 +3183,7 @@ namespace Volian.Controls.Library EIWsupInfoBelow.Top = Math.Max(bottomOfAboveSupInfoColumn, bottomOfImmediatelyAbove); EIWsupInfoBelow.AdjustLocation(); MyStepPanel.ItemMoving--; - return EIWsupInfoBelow.MySupInfoEditItems == null ? null : EIWsupInfoBelow.MySupInfoEditItems[0]; + return EIWsupInfoBelow.MySupInfoEditItems?[0]; } } return null; @@ -3532,7 +3203,7 @@ namespace Volian.Controls.Library { return FindSiblingOrParentSiblingWithSupInfo(itm.ActiveParent as ItemInfo); } - EditItem chldOfNext = null; + EditItem chldOfNext; // if section, handle notes/cautions on section and if none, look for hls (children of section) if (itm.NextItem.IsSection) { @@ -3724,29 +3395,6 @@ namespace Volian.Controls.Library sindx = tmp.IndexOf("", sindx + 1); } - //string tmp = str.ToUpper(); - //int sindx = tmp.IndexOf("", sindx + 1); - //string reptmp; - //while (sindx > -1 && eindx > -1) // B2022-007 added while loop to process more than one ") str = str.Replace(reptmp, dvi.DocVersionConfig.Unit_Number); - // else if (tmp == "") str = str.Replace(reptmp, dvi.DocVersionConfig.Unit_Text); - // else if (tmp == "") str = str.Replace(reptmp, dvi.DocVersionConfig.Unit_Number); - // else if (tmp == "") str = str.Replace(reptmp, dvi.DocVersionConfig.Unit_Name); - // else if (tmp == "") str = str.Replace(reptmp, dvi.DocVersionConfig.Unit_ID); - // // B2021-145: For applicability, the tree view & pdf file name are not getting resolved when using any of the ‘OTHER’ tokens - // else if (tmp == "") str = str.Replace(reptmp, dvi.DocVersionConfig.Other_Unit_Text); - // else if (tmp == "") str = str.Replace(reptmp, dvi.DocVersionConfig.Other_Unit_Number); - // else if (tmp == "") str = str.Replace(reptmp, dvi.DocVersionConfig.Other_Unit_Name); - // else if (tmp == "") str = str.Replace(reptmp, dvi.DocVersionConfig.Other_Unit_ID); - // else str = str.Replace(reptmp, tmp.Replace("<", "*?").Replace(">", "?*")); - // tmp = str.ToUpper(); - // sindx = tmp.IndexOf("", sindx + 1); - //} return str; } // C2021-018 used to display Alarm Point Table RO values in the editor @@ -3844,7 +3492,7 @@ namespace Volian.Controls.Library { int indx = token.IndexOf("-"); int qindx = token.IndexOf("?", indx); - string val = null; + string val; if (qindx == -1) { val = procConfig.GetValue("PSI", token.Substring(4, token.Length - 5)); @@ -3868,7 +3516,7 @@ namespace Volian.Controls.Library } return retval; } - private static Regex regexFindToken = new Regex("{[^{}]*}"); + private static readonly Regex regexFindToken = new Regex("{[^{}]*}"); // C2021-018 used to display Alarm Point Table RO values in the editor // Spin through the pagelist for this seciton and grap the Alarm Point Information protected string GetAlarmPointTableInfo(ItemInfo itmInfo) @@ -3878,11 +3526,12 @@ namespace Volian.Controls.Library // get alarm point data from pagelist bool usePSIvalue = false; // C2021-065 used with ROLkUpMatch pagelist flag (Barakah Alarms) int lastRow = -1; - string otherChildUnit = ""; // C2021-065 used when OTHER applicability information is used for the ROLookUp - foreach (VEPROMS.CSLA.Library.PageItem pageItem in itmInfo.MyDocStyle.pagestyle.PageItems) +#pragma warning disable IDE0059 // Unnecessary assignment of a value - otherchildUnit Kept for debugging + string otherChildUnit = ""; // C2021-065 used when OTHER applicability information is used for the ROLookUp +#pragma warning restore IDE0059 // Unnecessary assignment of a value + foreach (VEPROMS.CSLA.Library.PageItem pageItem in itmInfo.MyDocStyle.pagestyle.PageItems) { if (pageItem.Token == null) continue; // can be null if token is dependent on PSI lookup! - //DidHLSText = false; // reset to false for this group of tokens. //if (pageItem.Token.Contains("HLSTEXT")) // Console.WriteLine("{0} - PageList Token", pageItem.Token); @@ -3915,7 +3564,7 @@ namespace Volian.Controls.Library int n = parts.Length - 3; string part0 = parts[0]; for (int i = 0; i < n; i++) // append parts based upon the number of parts (commas) - part0 += "," + parts[i + 1]; + part0 += $",{parts[i + 1]}"; parts[0] = part0; parts[1] = parts[n + 1];// Get the last 2 parts parts[2] = parts[n + 2]; @@ -4009,12 +3658,7 @@ namespace Volian.Controls.Library protected void SetupEditItem(ItemInfo itemInfo, StepPanel myStepPanel, EditItem myParentEditItem, ChildRelation myChildRelation, bool expand, EditItem nextEditItem, bool addFirstChld) { if (myStepPanel.TopMostEditItem == null) myStepPanel.TopMostEditItem = this; - //if (itemInfo.ItemID == 10366) Console.WriteLine("Here"); - //if (itemInfo.ItemID == 225) _MyStepRTB.Resize += new EventHandler(_MyStepRTB_Resize); - //_MyStepRTB.MyRTBItem = this; - //// TIMING: DisplayItem.TimeIt("CSLARTB InitComp"); BackColor = myStepPanel.PanelColor; - //_MyStepRTB.BackColor = myStepPanel.InactiveColor; // TODO: Adjust top based upon format // TODO: Remove Label and just output ident on the paint event TabLeft = 20; @@ -4023,8 +3667,6 @@ namespace Volian.Controls.Library SetupAlarmTableView(itemInfo); // C2021-018 display alarm point table information in the step editor (if the format flag is set) this.Paint -= new PaintEventHandler(EditItem_Paint); this.Paint += new PaintEventHandler(EditItem_Paint); - this.BackColorChanged -= new EventHandler(EditItem_BackColorChanged); - this.BackColorChanged += new EventHandler(EditItem_BackColorChanged); this.Move -= new EventHandler(EditItem_Move); this.Move += new EventHandler(EditItem_Move); this.Resize -= new EventHandler(EditItem_Resize); @@ -4048,9 +3690,11 @@ namespace Volian.Controls.Library // is found, resolve them: if (itemInfo.MyContent.Text.Contains("")) { - DisplayText vlntxt = new DisplayText(itemInfo, E_EditPrintMode.Edit, E_ViewMode.Edit, false, E_FieldToEdit.StepText, true, null, null, false); - vlntxt.SetDTS = false; - vlntxt.CleanUpNewIDs(); + DisplayText vlntxt = new DisplayText(itemInfo, E_EditPrintMode.Edit, E_ViewMode.Edit, false, E_FieldToEdit.StepText, true, null, null, false) + { + SetDTS = false + }; + vlntxt.CleanUpNewIDs(); vlntxt = null; } ContentFont = myStepPanel.StepFont;//lblTab.Font = myStepPanel.StepFont; @@ -4058,7 +3702,6 @@ namespace Volian.Controls.Library MyStepData = itemInfo.ActiveFormat.PlantFormat.FormatData.StepDataList[ContentType % 10000]; break; } - //this.Move += new EventHandler(DisplayItem_Move); } else { @@ -4071,23 +3714,20 @@ namespace Volian.Controls.Library if (myParentEditItem != null) RNOLevel = myParentEditItem.RNOLevel; if (itemInfo != null) { - //// TIMING: DisplayItem.TimeIt("CSLARTB before _Layout"); MyStepSectionLayoutData = itemInfo.ActiveFormat.MyStepSectionLayoutData; - //// TIMING: DisplayItem.TimeIt("CSLARTB _Layout"); if (myParentEditItem != null) SeqLevel = myParentEditItem.SeqLevel + ((myChildRelation == ChildRelation.After || myChildRelation == ChildRelation.Before) && itemInfo.IsSequential ? 1 : 0); - //// TIMING: DisplayItem.TimeIt("CSLARTB seqLevel"); MyItemInfo = itemInfo; MyItemInfo.MyConfig.PropertyChanged -= new PropertyChangedEventHandler(MyConfig_PropertyChanged); MyItemInfo.MyConfig.PropertyChanged += new PropertyChangedEventHandler(MyConfig_PropertyChanged); } - //// TIMING: DisplayItem.TimeIt("CSLARTB MyItem"); myStepPanel.Controls.Add(this); - switch (myChildRelation) +#pragma warning disable CS0197 // Using a field of a marshal-by-reference class as a ref or out value or taking its address may cause a runtime exception + switch (myChildRelation) { case ChildRelation.After: - AddItem(myParentEditItem, ref myParentEditItem._MyAfterEditItems, nextEditItem, addFirstChld); - break; + AddItem(myParentEditItem, ref myParentEditItem._MyAfterEditItems, nextEditItem, addFirstChld); + break; case ChildRelation.Before: AddItem(myParentEditItem, ref myParentEditItem._MyBeforeEditItems, nextEditItem, addFirstChld); break; @@ -4101,7 +3741,8 @@ namespace Volian.Controls.Library case ChildRelation.None: break; } - if (itemInfo != null) +#pragma warning restore CS0197 // Using a field of a marshal-by-reference class as a ref or out value or taking its address may cause a runtime exception + if (itemInfo != null) { // ip2bck's needed the ContentWidth set to get the edit windows to size correctly. if (itemInfo.IsStep && itemInfo.FormatStepData.Type == "TitleWithTextBelow" && @@ -4128,7 +3769,6 @@ namespace Volian.Controls.Library } } } - //// TIMING: DisplayItem.TimeIt("CSLARTB Parent"); //C2026-021 Expand Functionality of Viewing Mode if (MyStepPanel.ApplDisplayMode > 0) @@ -4144,7 +3784,6 @@ namespace Volian.Controls.Library } // B2020-012: table location for sibling table is not correct, and possible first table. if (itemInfo.IsTable) ItemLocation = TableLocation(MyStepSectionLayoutData, this.Width); - //// TIMING: DisplayItem.TimeIt("CSLARTB SetText"); if (itemInfo != null) { Name = string.Format("Item-{0}", itemInfo.ItemID); @@ -4158,8 +3797,6 @@ namespace Volian.Controls.Library else // otherwise only expand one level Expand(false); } - //// TIMING: DisplayItem.TimeIt("CSLARTB before Controls Add"); - //myStepPanel.Controls.Add(this); // If on the first Caution/Note and the parent has a previous, for example a caution off of 5th HLS, go to the // bottom on the previous parent. In the example, the bottom of the 4th HLS. int btm = myStepPanel.DisplayRectangle.Y; @@ -4167,8 +3804,7 @@ namespace Volian.Controls.Library if (MyItemInfo.ActiveFormat.MyStepSectionLayoutData.Dev_Format) if (MyItemInfo.IsCaution || MyItemInfo.IsNote) top = myParentEditItem.TopMostEditItem.Top; - //if ((MyItemInfo.SameRowAsParent && MyItemInfo.IsCaution2) || (MyItemInfo.ActiveFormat.MyStepSectionLayoutData.Dev_Format && (MyItemInfo.IsCaution || MyItemInfo.IsNote))) - // top = myParentEditItem.TopMostEditItem.Top; + if (Top < top) { LastMethodsPush("SetupRTBItem"); @@ -4179,7 +3815,6 @@ namespace Volian.Controls.Library } this.Enabled = this.MyItemInfo.IsApplicable(MyStepPanel.ApplDisplayMode); _Loading = false; - //// TIMING: DisplayItem.TimeIt("CSLARTB Controls Add"); } void MyConfig_PropertyChanged(object sender, PropertyChangedEventArgs e) { @@ -4201,15 +3836,6 @@ namespace Volian.Controls.Library } MyItemInfo.MyConfig.IsDirty = false; } - /// - /// If the background changes, change the background of the RichTextBox - /// - /// - /// - void EditItem_BackColorChanged(object sender, EventArgs e) - { - //IdentifyMe(false); - } // TODO: the format of the circles, Checkoffs and Changebars should come from the format file /// /// This adds drawing items to the RTBItem as needed including @@ -4223,10 +3849,6 @@ namespace Volian.Controls.Library { Graphics g = e.Graphics; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; - //g.DrawString(lblTab.Text, MyItemInfo.MyTab.MyFont.WindowsFont, Brushes.Red, new RectangleF(new PointF(MyStepPanel.MyStepPanelSettings.NumberLocationX, MyStepPanel.MyStepPanelSettings.NumberLocationY), MyStepPanel.MyStepPanelSettings.NumberSize), StringFormat.GenericDefault); - // adjust x location of label by 7, to position correctly. - //g.DrawString(lblTab.Text, MyItemInfo.MyTab.MyFont.WindowsFont, Brushes.Blue, new RectangleF(new PointF(Convert.ToSingle(lblTab.Location.X-7), Convert.ToSingle(lblTab.Location.Y)), MyStepPanel.MyStepPanelSettings.NumberSize), StringFormat.GenericDefault); - //g.DrawLine(Pens.DarkGreen, lblTab.Location.X-7, 0, lblTab.Location.X-7, this.Height); // Show a small E to indicate Enhanced Steps DVEnhancedDocuments dveds = MyItemInfo.MyDocVersion.DocVersionConfig.MyEnhancedDocuments; float x = 0; @@ -4238,11 +3860,6 @@ namespace Volian.Controls.Library // we can retrieve the font from a dictionary instead a doing a New and using another // window handle B2017-117 Font fnt = VE_Font.GetWinSysFont("Arial", 5); - //g.DrawLine(Pens.DarkGreen, 18, 1, 18, 6); - //g.DrawLine(Pens.DarkGreen, 18, 1, 21, 1); - //g.DrawLine(Pens.DarkGreen, 18, 3, 21, 3); - //g.DrawLine(Pens.DarkGreen, 18, 6, 21, 6); - //g.DrawString("B", fnt, Brushes.Green, new RectangleF(new PointF(0,0), this.Size), StringFormat.GenericDefault); g.DrawString(dved.PdfToken, fnt, Brushes.Green, new RectangleF(new PointF(x, y), this.Size), StringFormat.GenericDefault); if (y > 0) { @@ -4252,8 +3869,6 @@ namespace Volian.Controls.Library else y = 14; } - //g.DrawLine(Pens.DarkGreen, MyStepRTB.Location.X - 7, 0, MyStepRTB.Location.X - 7, this.Height); - //g.DrawString(TabText, MyItemInfo.MyTab.MyFont.WindowsFont, Brushes.Black, new RectangleF(new PointF(Convert.ToSingle(TabLocation.X), Convert.ToSingle(TabLocation.Y)), MyStepPanel.MyStepPanelSettings.NumberSize), StringFormat.GenericDefault); Font myWFont = (MyItemInfo.MyTab != null) ? MyItemInfo.MyTab.MyFont.WindowsFont : MyItemInfo.FormatStepData.Font.WindowsFont; // added Try/Catch when working on B2017-143, kept in to prevent PROMS from crashing after printing a procedure that has a seq tab with a different font style @@ -4266,8 +3881,6 @@ namespace Volian.Controls.Library _MyLog.Warn("EditItem DrawString", ex); } - //g.DrawLine(Pens.DarkGreen, lblTab.Location.X, 0, lblTab.Location.X, this.Height); - //g.DrawLine(Pens.DarkGreen, MyStepRTB.Location.X, 0, MyStepRTB.Location.X, this.Height); if (Circle) { Pen penC = new Pen(MyStepPanel.MyStepPanelSettings.CircleColor, MyStepPanel.MyStepPanelSettings.CircleWeight); diff --git a/PROMS/Volian.Controls.Library/FindReplace.cs b/PROMS/Volian.Controls.Library/FindReplace.cs index 8a03c091..35d4b322 100644 --- a/PROMS/Volian.Controls.Library/FindReplace.cs +++ b/PROMS/Volian.Controls.Library/FindReplace.cs @@ -1,8 +1,4 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; using System.Text; using System.Windows.Forms; using VEPROMS.CSLA.Library; @@ -16,14 +12,9 @@ namespace Volian.Controls.Library { private bool doingfind = false; private bool findingbookmarks = false; - private bool _FoundIt = false; - private ItemInfo _StartingItemInfo = null;// C2023-016 used to remember where we started doing the Find/Replace - public bool FoundIt - { - get { return _FoundIt; } - set { _FoundIt = value; } - } - private bool IsFound + private ItemInfo _StartingItemInfo = null;// C2023-016 used to remember where we started doing the Find/Replace + public bool FoundIt { get; set; } = false; + private bool IsFound { get { @@ -43,32 +34,17 @@ namespace Volian.Controls.Library { _MyEditItem = value; if (_MyEditItem == null) return; - _MyDocVersion = _MyEditItem.MyItemInfo.MyProcedure.ActiveParent as DocVersionInfo; + Mydocversion = _MyEditItem.MyItemInfo.MyProcedure.ActiveParent as DocVersionInfo; SetupContextMenu(); } } - private DocVersionInfo _MyDocVersion; - public DocVersionInfo Mydocversion - { - get { return _MyDocVersion; } - set {_MyDocVersion = value; } - } - private DisplayBookMarks _myDisplayBookMarks; - public DisplayBookMarks MyDisplayBookMarks - { - get { return _myDisplayBookMarks; } - set { _myDisplayBookMarks = value; } - } + public DocVersionInfo Mydocversion { get; set; } - private bool _InApproved; + public DisplayBookMarks MyDisplayBookMarks { get; set; } - public bool InApproved - { - get { return _InApproved; } - set { _InApproved = value; } - } - public FindReplace() + public bool InApproved { get; set; } + public FindReplace() { InitializeComponent(); LoadFindReplaceTextListBox(); @@ -203,7 +179,7 @@ namespace Volian.Controls.Library // C2023-016 Find the next element, but stay in the same procedure private ItemInfo FindNextStepElement(ItemInfo curStepElem, string fndStr) { - ItemInfo nxtStepElem = curStepElem; + ItemInfo nxtStepElem; if (_StartingItemInfo == null) _StartingItemInfo = MyEditItem.MyItemInfo; if (cbxReverse.Checked) @@ -267,11 +243,6 @@ namespace Volian.Controls.Library } FoundIt = true; } - private bool FindNextText(ItemInfo next) - { - if (next.MyContent.MyGrid!=null) return true; - return next.MyContent.Text.ToUpper().Contains(cmboFindText.Text.ToUpper()); - } private void AddToComboLists() { bool hastext = this.cmboFindText.Text.Length > 0; @@ -304,11 +275,6 @@ namespace Volian.Controls.Library _StartingItemInfo = null;//C2023-016 reset the starting position } - public void PerformFindNext() - { - btnFindNext.PerformClick(); - } - private void tabFind_Click(object sender, EventArgs e) { lblRplTxt.Visible = false; @@ -360,9 +326,11 @@ namespace Volian.Controls.Library IDataObject myDO = Clipboard.GetDataObject(); if (myDO.GetDataPresent(DataFormats.Rtf)) { - RichTextBox rtb = new RichTextBox(); - rtb.SelectedRtf = ItemInfo.StripLinks(myDO.GetData(DataFormats.Rtf).ToString()); - if (cmboReplaceText.Focused) + RichTextBox rtb = new RichTextBox + { + SelectedRtf = ItemInfo.StripLinks(myDO.GetData(DataFormats.Rtf).ToString()) + }; + if (cmboReplaceText.Focused) cmboReplaceText.SelectedText = rtb.Text; else if (cmboFindText.Focused) cmboFindText.SelectedText = rtb.Text; @@ -394,9 +362,9 @@ namespace Volian.Controls.Library private void SetupContextMenu() { galSymbols.SubItems.Clear(); - if (_MyDocVersion != null) + if (Mydocversion != null) { - FormatData fmtdata = _MyDocVersion.ActiveFormat.PlantFormat.FormatData; + FormatData fmtdata = Mydocversion.ActiveFormat.PlantFormat.FormatData; SymbolList sl = fmtdata.SymbolList; if (sl == null || sl.Count <= 0) { @@ -405,14 +373,16 @@ namespace Volian.Controls.Library } 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); + DevComponents.DotNetBar.ButtonItem btnCM = new DevComponents.DotNetBar.ButtonItem + { + Text = string.Format("{0}", (char)sym.Unicode), + // to name button use unicode rather than desc, desc may have spaces or odd chars + Name = "btnCM" + sym.Unicode.ToString(), + Tooltip = sym.Desc, + Tag = string.Format(@"{0}", sym.Unicode), + FontBold = true + }; + btnCM.Click += new System.EventHandler(btnSym_Click); galSymbols.SubItems.Add(btnCM); } } diff --git a/PROMS/Volian.Controls.Library/FlagEnumEditor.cs b/PROMS/Volian.Controls.Library/FlagEnumEditor.cs index 17f3e65d..d0b08765 100644 --- a/PROMS/Volian.Controls.Library/FlagEnumEditor.cs +++ b/PROMS/Volian.Controls.Library/FlagEnumEditor.cs @@ -1,8 +1,5 @@ using System; -using System.Collections; using System.ComponentModel; -using System.Drawing; -using System.Data; using System.Windows.Forms; using System.Drawing.Design; using System.Windows.Forms.Design; @@ -13,7 +10,8 @@ namespace Volian.Controls.Library public class FlagCheckedListBox : CheckedListBox { - private System.ComponentModel.Container components = null; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private System.ComponentModel.Container components = null; public FlagCheckedListBox() { @@ -28,8 +26,7 @@ namespace Volian.Controls.Library { if (disposing) { - if (components != null) - components.Dispose(); + components?.Dispose(); } base.Dispose(disposing); } @@ -37,9 +34,6 @@ namespace Volian.Controls.Library #region Component Designer generated code private void InitializeComponent() { - // - // FlaggedCheckedListBox - // this.CheckOnClick = true; } @@ -127,7 +121,7 @@ namespace Volian.Controls.Library // If the item has been unchecked, remove its bits from the sum if (cs == CheckState.Unchecked) - sum = sum & (~composite.value); + sum &= (~composite.value); // If the item has been checked, combine its bits with the sum else sum |= composite.value; @@ -239,13 +233,15 @@ namespace Volian.Controls.Library public class FlagEnumUIEditor : UITypeEditor { // The checklistbox - private FlagCheckedListBox flagEnumCB; + private readonly FlagCheckedListBox flagEnumCB; public FlagEnumUIEditor() { - flagEnumCB = new FlagCheckedListBox(); - flagEnumCB.BorderStyle = BorderStyle.None; - } + flagEnumCB = new FlagCheckedListBox + { + BorderStyle = BorderStyle.None + }; + } public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { @@ -269,12 +265,9 @@ namespace Volian.Controls.Library return null; } - public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) - { - return UITypeEditorEditStyle.DropDown; - } + public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) => UITypeEditorEditStyle.DropDown; - } + } } diff --git a/PROMS/Volian.Controls.Library/FormatUtility.cs b/PROMS/Volian.Controls.Library/FormatUtility.cs index 59e34d61..7d13cca9 100644 --- a/PROMS/Volian.Controls.Library/FormatUtility.cs +++ b/PROMS/Volian.Controls.Library/FormatUtility.cs @@ -1,9 +1,6 @@ using Csla; using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using System.Xml; using VEPROMS.CSLA.Library; diff --git a/PROMS/Volian.Controls.Library/GlobalSuppressions.cs b/PROMS/Volian.Controls.Library/GlobalSuppressions.cs new file mode 100644 index 00000000..046248af --- /dev/null +++ b/PROMS/Volian.Controls.Library/GlobalSuppressions.cs @@ -0,0 +1,8 @@ +// This file is used by Code Analysis to maintain SuppressMessage +// attributes that are applied to this project. +// Project-level suppressions either have no target or are given +// a specific target and scoped to a namespace, type, member, etc. + +using System.Diagnostics.CodeAnalysis; + +[assembly: SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Not modifying Naming Styles")] diff --git a/PROMS/Volian.Controls.Library/GridItem.Designer.cs b/PROMS/Volian.Controls.Library/GridItem.Designer.cs index 58198bd8..6cf26924 100644 --- a/PROMS/Volian.Controls.Library/GridItem.Designer.cs +++ b/PROMS/Volian.Controls.Library/GridItem.Designer.cs @@ -34,9 +34,9 @@ namespace Volian.Controls.Library System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(GridItem)); this.lblTab = new System.Windows.Forms.Label(); this._MyToolTip = new DevComponents.DotNetBar.SuperTooltip(); - this._MyFlexGrid = new Volian.Controls.Library.VlnFlexGrid(this.components); + this.MyFlexGrid = new Volian.Controls.Library.VlnFlexGrid(this.components); this._MyDisablePanel = new vlnPanel(); - ((System.ComponentModel.ISupportInitialize)(this._MyFlexGrid)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.MyFlexGrid)).BeginInit(); this.SuspendLayout(); // // lblTab @@ -55,21 +55,21 @@ namespace Volian.Controls.Library // // _MyFlexGrid // - this._MyFlexGrid.AllowMerging = C1.Win.C1FlexGrid.AllowMergingEnum.Custom; - this._MyFlexGrid.AllowResizing = C1.Win.C1FlexGrid.AllowResizingEnum.Both; - this._MyFlexGrid.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(255))))); - this._MyFlexGrid.ColumnInfo = "3,0,0,0,0,40,Columns:"; - this._MyFlexGrid.DrawMode = C1.Win.C1FlexGrid.DrawModeEnum.OwnerDraw; - this._MyFlexGrid.FocusRect = C1.Win.C1FlexGrid.FocusRectEnum.Solid; - this._MyFlexGrid.Location = new System.Drawing.Point(5, 5); - this._MyFlexGrid.Name = "_MyFlexGrid"; - this._MyFlexGrid.Rows.Count = 4; - this._MyFlexGrid.Rows.DefaultSize = 20; - this._MyFlexGrid.Rows.Fixed = 0; - this._MyFlexGrid.ScrollBars = System.Windows.Forms.ScrollBars.None; - this._MyFlexGrid.Size = new System.Drawing.Size(314, 66); - this._MyFlexGrid.StyleInfo = resources.GetString("_MyFlexGrid.StyleInfo"); - this._MyFlexGrid.TabIndex = 4; + this.MyFlexGrid.AllowMerging = C1.Win.C1FlexGrid.AllowMergingEnum.Custom; + this.MyFlexGrid.AllowResizing = C1.Win.C1FlexGrid.AllowResizingEnum.Both; + this.MyFlexGrid.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(255))))); + this.MyFlexGrid.ColumnInfo = "3,0,0,0,0,40,Columns:"; + this.MyFlexGrid.DrawMode = C1.Win.C1FlexGrid.DrawModeEnum.OwnerDraw; + this.MyFlexGrid.FocusRect = C1.Win.C1FlexGrid.FocusRectEnum.Solid; + this.MyFlexGrid.Location = new System.Drawing.Point(5, 5); + this.MyFlexGrid.Name = "_MyFlexGrid"; + this.MyFlexGrid.Rows.Count = 4; + this.MyFlexGrid.Rows.DefaultSize = 20; + this.MyFlexGrid.Rows.Fixed = 0; + this.MyFlexGrid.ScrollBars = System.Windows.Forms.ScrollBars.None; + this.MyFlexGrid.Size = new System.Drawing.Size(314, 66); + this.MyFlexGrid.StyleInfo = resources.GetString("_MyFlexGrid.StyleInfo"); + this.MyFlexGrid.TabIndex = 4; // // _MyDisablePanel // @@ -81,13 +81,13 @@ namespace Volian.Controls.Library // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.Controls.Add(this._MyFlexGrid); + this.Controls.Add(this.MyFlexGrid); this.Controls.Add(this._MyDisablePanel); this.Controls.Add(this.lblTab); this.Margin = new System.Windows.Forms.Padding(2); this.Name = "GridItem"; this.Size = new System.Drawing.Size(320, 72); - ((System.ComponentModel.ISupportInitialize)(this._MyFlexGrid)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.MyFlexGrid)).EndInit(); this.ResumeLayout(false); } @@ -96,7 +96,6 @@ namespace Volian.Controls.Library private System.Windows.Forms.Label lblTab; private DevComponents.DotNetBar.SuperTooltip _MyToolTip; - private VlnFlexGrid _MyFlexGrid; - private vlnPanel _MyDisablePanel; + private vlnPanel _MyDisablePanel; } } diff --git a/PROMS/Volian.Controls.Library/GridItem.cs b/PROMS/Volian.Controls.Library/GridItem.cs index 4b794d91..d3a1a849 100644 --- a/PROMS/Volian.Controls.Library/GridItem.cs +++ b/PROMS/Volian.Controls.Library/GridItem.cs @@ -1,13 +1,8 @@ using System; using System.Collections.Generic; -using System.ComponentModel; using System.Drawing; -using System.Data; -using System.Text; using System.Text.RegularExpressions; -//using System.IO; using System.Windows.Forms; -using System.Xml; using VEPROMS.CSLA.Library; using Volian.Base.Library; using C1.Win.C1FlexGrid; @@ -24,51 +19,32 @@ namespace Volian.Controls.Library { get { - ItemInfo procInfo = MyItemInfo.MyProcedure as ItemInfo; - if (procInfo == null) - _MyDVI = null; - else - _MyDVI = procInfo.ActiveParent as DocVersionInfo; - return _MyDVI; + if (!(MyItemInfo.MyProcedure is ItemInfo procInfo)) + _MyDVI = null; + else + _MyDVI = procInfo.ActiveParent as DocVersionInfo; + return _MyDVI; } } - private static UserInfo _MyUserInfo = null; - public static UserInfo MyUserInfo - { - get { return _MyUserInfo; } - set { _MyUserInfo = value; } - } - private bool _IsSaving; - public bool IsSaving - { - get { return _IsSaving; } - set { _IsSaving = value; } - } - public VlnFlexGrid MyFlexGrid - { - get { return _MyFlexGrid; } - set { _MyFlexGrid = value; } - } - private int _GridMargin = 11; - /// - /// Margin between the EditItem and the VlnFlexGrid. Appears on the Right. - /// Will allow space to draw a Change Bar on the right side of the EditItem. - /// - public int GridMargin - { - get { return _GridMargin; } - set { _GridMargin = value; } - } - #endregion - - #region Event Handlers - /// - /// Raises an ItemClick event when the user clicks on the Tab - /// - /// - /// - private void lblTab_MouseDown(object sender, MouseEventArgs e) + public static UserInfo MyUserInfo { get; set; } = null; + public bool IsSaving { get; set; } + public VlnFlexGrid MyFlexGrid { get; set; } + + /// + /// Margin between the EditItem and the VlnFlexGrid. Appears on the Right. + /// Will allow space to draw a Change Bar on the right side of the EditItem. + /// + public int GridMargin { get; set; } = 11; + #endregion + + #region Event Handlers + /// + /// Raises an ItemClick event when the user clicks on the Tab + /// + /// + /// + private void lblTab_MouseDown(object sender, MouseEventArgs e) { MyStepPanel.OnItemClick(this, new StepPanelEventArgs(this, e)); } @@ -145,7 +121,6 @@ namespace Volian.Controls.Library void MyStepRTB_AdjustTableWidth(object sender, StepRTBTableWidthEventArgs args) { //Console.WriteLine("MyStepRTB_AdjustTableWidth"); - //if ((!_MyItemInfo.IsSection && !_MyItemInfo.IsProcedure) && (_MyItemInfo.IsTable || _MyItemInfo.IsFigure)) if (args.EditMode) { int colR = MyStepPanel.ToDisplay(MyStepSectionLayoutData.ColRTable, MyItemInfo.ColumnMode); @@ -167,28 +142,13 @@ namespace Volian.Controls.Library } } } - bool MyStepRTB_IsNotCurrentSelection(object sender, EventArgs args) - { - return MyStepPanel.SelectedEditItem != this; - } + bool MyStepRTB_IsNotCurrentSelection(object sender, EventArgs args) => MyStepPanel.SelectedEditItem != this; - void MyStepRTB_OpenAnnotations(object sender, EventArgs args) - { - OpenAnnotations(); - } - void MyFlexGrid_OpenAnnotations(object sender, EventArgs args) - { - OpenAnnotations(); - } - void MyStepRTB_DoMouseWheel(object sender, MouseEventArgs args) - { - DoMouseWheel(args); - } - void MyStepRTB_DoSaveContents(object sender, EventArgs args) - { - SaveCurrentAndContents(); - } - void MyStepRTB_VisibleChanged(object sender, EventArgs e) + void MyStepRTB_OpenAnnotations(object sender, EventArgs args) => OpenAnnotations(); + void MyFlexGrid_OpenAnnotations(object sender, EventArgs args) => OpenAnnotations(); + void MyStepRTB_DoMouseWheel(object sender, MouseEventArgs args) => DoMouseWheel(args); + void MyStepRTB_DoSaveContents(object sender, EventArgs args) => SaveCurrentAndContents(); + void MyStepRTB_VisibleChanged(object sender, EventArgs e) { if (MyStepRTB == null) return; MyStepRTB.EditMode = MyStepRTB.Visible; @@ -204,7 +164,6 @@ namespace Volian.Controls.Library void MyFlexGrid_Click(object sender, EventArgs e) { MyFlexGrid.Focus(); - //MyStepPanel.MyStepTabPanel.MyStepTabRibbon.ToggleTableDesignButtons(false); MyStepPanel.MyStepTabPanel.MyStepTabRibbon.SetRibbonForGrid(); MyStepPanel.MyStepTabPanel.MyStepTabRibbon.SetTableButtonsForMergeRangeSelection(); MyStepPanel.MyStepTabPanel.MyStepTabRibbon.SetGridContextMenu(); @@ -235,7 +194,6 @@ namespace Volian.Controls.Library private string _OrigRtf; // used to store original rtf to allow for 'escape' key restore void MyFlexGrid_SelChange(object sender, EventArgs e) { - //if (Initializing) return; //Volian.Base.Library.vlnStackTrace.ShowStackLocal("MyFlexGrid_SelChange {0}",MyFlexGrid.Selection); RTBLastFocus = false; MyStepRTB.Visible = false; // Hide the editor if the Selection Changes @@ -244,7 +202,7 @@ namespace Volian.Controls.Library { // B2020-088: get string using method in case of merged cells string rtf = MyFlexGrid.GetCellRTFString(MyFlexGrid.Row, MyFlexGrid.Col); - _OrigRtf = rtf == null ? string.Empty : rtf; + _OrigRtf = rtf ?? string.Empty; } } void MyStepRTB_KeyDown(object sender, KeyEventArgs e) @@ -310,7 +268,6 @@ namespace Volian.Controls.Library this.MyStepRTB.SetMenu += new StepRTBMenuEvent(MyStepRTB_SetMenu); this.MyStepRTB.OpenContextMenu += new StepRTBLocationEvent(MyStepRTB_OpenContextMenu); this.MyFlexGrid.EnterKeyPressed += new VlnFlexGridkeyEvent(MyFlexGrid_EnterKeyPressed); - //this.MyStepRTB.EnterKeyPressed += new StepRTBCursorKeysEvent(MyStepRTB_EnterKeyPressed); // This Resize event has been useful for debugging purposes numerous times // //this.MyStepRTB.Resize += new EventHandler(MyStepRTB_Resize); @@ -330,12 +287,6 @@ namespace Volian.Controls.Library cs.BackColor = MyFlexGrid.MyShading.GetColor(MyFlexGrid.Row, MyFlexGrid.Col); // C2021-004 reset the last active table cell's shading color when leaving } - //void MyStepRTB_EnterKeyPressed(object sender, KeyEventArgs args) - //{ - // args.Handled = true; - // MyStepPanel.MyStepTabPanel.MyStepTabRibbon.ProcessEnterKey(); - //} - void MyFlexGrid_EnterKeyPressed(object sender, KeyEventArgs args) { args.Handled = true; @@ -352,16 +303,6 @@ namespace Volian.Controls.Library SetMenu(args.MenuGroup); } - // This Resize event been useful for debugging purposes numerous times - // - //void MyStepRTB_Resize(object sender, EventArgs e) - //{ - // if (MyStepRTB.Visible) - // { - // //Volian.Base.Library.vlnStackTrace.ShowStack("MyStepRTB_Resize"); - // Console.WriteLine("MyStepRTB_Resize {0}", MyStepRTB.Width); - // } - //} void MyStepRTB_RoInsert(object sender, StepRTBRoEventArgs args) { //Console.WriteLine("GridItem - Enter MyStepRTB_RoInsert"); @@ -372,12 +313,6 @@ namespace Volian.Controls.Library MyFlexGrid.FixTableCellsHeightWidth(); MyFlexGrid.AdjustGridControlSize(); MyFlexGrid.Visible = true; - //MyFlexGrid.MergedRanges.Clear(); - //MyFlexGrid.Clear(); - //ConvertTableToGrid(args.RawValText, args.RODbID, args.ROID); - //MyFlexGrid.RODbId = args.RODbID; - //MyFlexGrid.ROID = args.ROID; - //SaveContents(); } else { @@ -400,18 +335,7 @@ namespace Volian.Controls.Library #endregion #region Override Method and Properties public override int BorderWidth { get { return (MyFlexGrid.Width - MyFlexGrid.ClientRectangle.Width); } } - //private bool _OnlyOnce = false; - //protected override void OnPaint(PaintEventArgs e) - //{ - // base.OnPaint(e); - // if (!this.Enabled && !_OnlyOnce) - // { - // _OnlyOnce = true; - // _MyDisablePanel.SendToBack(); - // _MyDisablePanel.BringToFront(); - // _OnlyOnce = false; - // } - //} + protected override void OnEnabledChanged(EventArgs e) { base.OnEnabledChanged(e); @@ -430,7 +354,6 @@ namespace Volian.Controls.Library { gr.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver; gr.FillRectangle(new SolidBrush(Color.FromArgb(128, Color.FromKnownColor(KnownColor.ButtonFace))), rect); - //gr.FillEllipse(Brushes.Red, 10, 10, 10, 10); } _MyDisablePanel.Location = this.MyFlexGrid.Location; _MyDisablePanel.Size = this.MyFlexGrid.Size; @@ -446,10 +369,6 @@ namespace Volian.Controls.Library public override string TabFormat { get { return _TabFormat; } set { _TabFormat = value; } } public override void AdjustTableWidthAndLocation() { - //_MyStepRTB.Font = MyStepData.Font.WindowsFont; - //ItemWidth = (int)GetTableWidth(MyStepRTB.Font, MyItemInfo.MyContent.Text, true); - //ItemWidth = MyFlexGrid.Width; - //ItemLocation = new Point(50, _MyParentEditItem.Bottom); // We had a table that was in a funky state. This allows it to appear in editor so // that is could be deleted. @@ -586,11 +505,11 @@ namespace Volian.Controls.Library } } } - c = c + 1; + c++; if (c == w) { c = 0; - r = r + 1; + r++; } } } @@ -651,35 +570,17 @@ namespace Volian.Controls.Library // if no ro has been defined yet, just return null if (MyFlexGrid.ROID == null) return null; ContentRoUsage rousg = null; -// using (Item itm = MyItemInfo.Get()) -// { + using (RODb rodb = RODb.GetJustRoDb(MyFlexGrid.RODbId)) { string padroid = (MyFlexGrid.ROID.Length <= 12) ? MyFlexGrid.ROID + "0000" : MyFlexGrid.ROID; rousg = itm.MyContent.ContentRoUsages.Add(MyFlexGrid.ROID, rodb); } - //itm.Save(); -// } + MyItemInfo.MyContent.RefreshContentRoUsages(); return string.Format(@"#Link:ReferencedObject:{0} {1} {2}", rousg.ROUsageID, MyFlexGrid.ROID, MyFlexGrid.RODbId); } - //private void ConvertTableToGrid(string valtext, int rodbid, string roid) - //{ - // VE_Font vefont = MyItemInfo.GetItemFont(); - // MyFlexGrid.Font = vefont.WindowsFont; - // //Initializing = true; - // MyFlexGrid.MergedRanges.Clear(); - // MyFlexGrid.Clear(); - // MyFlexGrid.ParseTableFromText(valtext); - // MyFlexGrid.AutoSizeCols(); - // MyFlexGrid.AutoSizeRows(); - // MyFlexGrid.MakeRTFcells(); - // MyFlexGrid.RODbId = rodbid; - // MyFlexGrid.ROID = roid; - // MyFlexGrid.IsRoTable = true; - // //Initializing = false; - // SaveContents(); - //} + private bool FinishSave(string searchableText) { // Just in case if the grid was in a mode to change sizes, clear out that setting @@ -691,13 +592,9 @@ namespace Volian.Controls.Library string xml = MyFlexGrid.GetXMLData(); using (Item itm = MyItemInfo.Get()) { - //if (!MatchingXML(itm.MyContent.MyGrid.Data, xml)) - //{ - // CompareXML(itm.MyContent.MyGrid.Data, xml); itm.MyContent.MyGrid.Data = xml; itm.MyContent.MyGrid.DTS = DateTime.Now; itm.MyContent.MyGrid.UserID = Volian.Base.Library.VlnSettings.UserID; - //} // if this is the initial save of an ro table, then the 'DoLinkForRoTable' will // create the usage for it. this code gets run on modify of the ro table and also // on exit of the griditem. We don't want to save the ro usage again, if it's already @@ -705,12 +602,9 @@ namespace Volian.Controls.Library if (MyFlexGrid.IsRoTable && MyFlexGrid.ROID != null && itm.MyContent.ContentRoUsageCount < 1) { searchableText = string.Format(@"\v\v0 ", searchableText, DoLinkForRoTable(itm)); - //if (itm.MyContent.Text != searchableText) - //{ itm.MyContent.Text = searchableText; itm.MyContent.UserID = Volian.Base.Library.VlnSettings.UserID; itm.MyContent.DTS = DateTime.Now; - //} } else { @@ -726,82 +620,30 @@ namespace Volian.Controls.Library if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.ProcData.ChangeBarData.ChangeIds && !this.MyStepPanel.MyStepTabPanel.MyDisplayTabControl.EditorialChange) { - StepConfig sc = itm.MyConfig as StepConfig; - if (sc == null) - sc = new StepConfig(); - sc.Step_ChangeID = this.MyStepPanel.MyStepTabPanel.MyDisplayTabControl.ChgId; + if (!(itm.MyConfig is StepConfig sc)) + sc = new StepConfig(); + sc.Step_ChangeID = this.MyStepPanel.MyStepTabPanel.MyDisplayTabControl.ChgId; if (itm.MyConfig == null) itm.MyContent.Config = sc.ToString(); } itm.Save(); - StepConfig myItmCfg =MyItemInfo.MyConfig as StepConfig; - // We saved changes made to some step text. Reset the change bar override. - // IF there is a step config remove the change bar override by setting the CBOverride value to null - // This fixes a problem reported by Farly where if the change bar or overridden to be off, the next - // time a change was made, the change bar remained turned off. - if (myItmCfg != null) - myItmCfg.Step_CBOverride = null; // clear the change bar override + // We saved changes made to some step text. Reset the change bar override. + // IF there is a step config remove the change bar override by setting the CBOverride value to null + // This fixes a problem reported by Farly where if the change bar or overridden to be off, the next + // time a change was made, the change bar remained turned off. + if (MyItemInfo.MyConfig is StepConfig myItmCfg) + myItmCfg.Step_CBOverride = null; // clear the change bar override - MyItemInfo.MyContent.MyGrid.ResetContent(itm.MyContent.MyGrid); + MyItemInfo.MyContent.MyGrid.ResetContent(itm.MyContent.MyGrid); } return true; } - private void CompareXML(string v1, string v2) - { - v1 = Regex.Replace(v1, "\r\n *", ""); - v1 = Regex.Replace(v1, "version *= *\"[^\"]*\"", ""); - v2 = Regex.Replace(v2, "\r\n *", ""); - v2 = Regex.Replace(v2, "version *= *\"[^\"]*\"", ""); - int iStart = 0; - int l1 = v1.Length; - int l2 = v2.Length; - int l3 = Math.Min(l1, l2); - while (iStart < l3 && v1[iStart] == v2[iStart]) - iStart++; - int iEnd1 = l1 - 1; - int iEnd2 = l2 - 1; - while (iStart < iEnd1 && iStart < iEnd2 && v1[iEnd1] == v2[iEnd2]) - { - iEnd1--; - iEnd2--; - } - if (iStart < iEnd1) Console.WriteLine("v1 = {0}", v1.Substring(iStart, iEnd1 - iStart)); - if (iStart < iEnd2) Console.WriteLine("v2 = {0}", v2.Substring(iStart, iEnd2 - iStart)); - - } - private bool MatchingXML(string v1, string v2) - { - v1 = Regex.Replace(v1, "\r\n *", ""); - v1 = Regex.Replace(v1, "version *= *\"[^\"]*\"", ""); - v2 = Regex.Replace(v2, "\r\n *", ""); - v2 = Regex.Replace(v2, "version *= *\"[^\"]*\"", ""); - int l1 = v1.Length; - int l2 = v2.Length; - if(l1 != l2 )return false; - //int l3 = Math.Min(l1, l2); - //int l4 = Math.Max(l1, l2); - for (int i = 0; i < l1; i++) - if (v1[i] != v2[i]) return false; - return true; - //Console.WriteLine("{0} - {1},{2}",i, showChar(v1[i]), showChar(v2[i])); - //if(l1 > l3)Console.WriteLine("v1 = {0}",v1.Substring(l3)); - //if(l2 > l3)Console.WriteLine("v2 = {0}",v2.Substring(l3)); - } - //private object showChar(char c) - //{ - // int i = (int)c; - // if (i <= 32) - // return string.Format("<{0}>", i); - // else - // return c.ToString(); - //} public void BasicSave() { using (Item itm = MyItemInfo.Get()) { itm.MyContent.MyGrid.Data = MyFlexGrid.GetXMLData(); itm.Save(); - //MyItemInfo.MyContent.MyGrid.ResetContent(itm.MyContent.MyGrid); } } public override bool CanExpand { get { return false; } set { ;} } @@ -821,8 +663,8 @@ namespace Volian.Controls.Library MyFlexGrid.Select(0, 0); MyFlexGrid.FirstEntry = true; // to fix a problem with initial mouse click into table } - catch (Exception ex) - { + catch (Exception) + { FlexibleMessageBox.Show("The content of this table is corrupted. You will either need to restore a previous version or delete it.", "Table Corrupted", MessageBoxButtons.OK, MessageBoxIcon.Information); } } @@ -831,22 +673,14 @@ namespace Volian.Controls.Library { _MyLog.WarnFormat("Attempt to give Focus to Disposed Object {0}", MyID); } - //ScrollToCenter(); } public override void ItemShow() { MyFlexGrid.Focus(); - //ScrollToCenter(); } public StepRTB DisplayRoStepRTB; - public override StepRTB MyStepRTB - { - get - { - return MyFlexGrid.TableCellEditor; - } - } - public override DialogResult ReplaceText(string rpltxt, string fndstr, bool caseSensitive, bool matchWholeWord, bool reverse, bool prompt, IWin32Window fndrpldlg) + public override StepRTB MyStepRTB => MyFlexGrid.TableCellEditor; + public override DialogResult ReplaceText(string rpltxt, string fndstr, bool caseSensitive, bool matchWholeWord, bool reverse, bool prompt, IWin32Window fndrpldlg) { int r = MyFlexGrid.Row; int c = MyFlexGrid.Col; @@ -874,11 +708,11 @@ namespace Volian.Controls.Library if (oldRtf != MyStepRTB.Rtf) MyFlexGrid[r, c] = MyStepRTB.Rtf; if (dr == DialogResult.Yes || dr == DialogResult.Cancel) return dr; } - c = c + 1; + c++; if (c == w) { c = 0; - r = r + 1; + r++; } if (r < h) { @@ -908,11 +742,11 @@ namespace Volian.Controls.Library if (oldRtf != MyStepRTB.Rtf) MyFlexGrid[r, c] = MyStepRTB.Rtf; if (dr == DialogResult.Yes || dr == DialogResult.Cancel) return dr; } - c = c - 1; + c--; if (c < 0) { c = MyFlexGrid.Cols.Count - 1; - r = r - 1; + r--; } cr = MyFlexGrid.GetMergedRange(r, c); if (r >= 0 && cr.r1 == r && cr.c1 == c) @@ -946,11 +780,11 @@ namespace Volian.Controls.Library bool scn = MyStepRTB.FindText(str, caseSensitive, matchWholeWord, reverse); if (scn) return true; } - c = c + 1; + c++; if (c == w) { c = 0; - r = r + 1; + r++; } if (r < h) { @@ -972,11 +806,11 @@ namespace Volian.Controls.Library bool scn = MyStepRTB.FindText(str, caseSensitive, matchWholeWord, reverse); if (scn) return true; } - c = c - 1; + c--; if (c < 0) { c = MyFlexGrid.Cols.Count - 1; - r = r - 1; + r--; } cr = MyFlexGrid.GetMergedRange(r, c); if (r >= 0 && cr.r1 == r && cr.c1 == c) @@ -1002,11 +836,11 @@ namespace Volian.Controls.Library MyFlexGrid.StartEditing(); return; } - c = c - 1; + c--; if (c < 0) { c = MyFlexGrid.Cols.Count - 1; - r = r - 1; + r--; } if (r >= 0) { @@ -1055,11 +889,11 @@ namespace Volian.Controls.Library if (oldRtf != MyStepRTB.Rtf) MyFlexGrid[r, c] = MyStepRTB.Rtf; if (!scn) return false; } - c = c + 1; + c++; if (c == w) { c = 0; - r = r + 1; + r++; } } return true; @@ -1092,29 +926,19 @@ namespace Volian.Controls.Library MyFlexGrid.ShowTableCellShading(); } } - public override void SetActive() - { - AdjustColorsForEditMode(); - } - private bool _Empty = false; + public override void SetActive() => AdjustColorsForEditMode(); + private bool _Empty = false; public override bool Empty { get { return _Empty; } set { _Empty = value; } } - private bool _Initializing = false; - public bool Initializing - { - get { return _Initializing; } - set { _Initializing = value; } - } - private bool _ActiveMode = false; + + public bool Initializing { get; set; } = false; + private bool _ActiveMode = false; public override void RefreshDisplay(bool activeMode) { _ActiveMode = activeMode; - //XmlDocument xd = new XmlDocument(); - //xd.LoadXml(MyItemInfo.MyContent.MyGrid.Data); - //using (StringReader sr = new StringReader()) Initializing = true; MyFlexGrid.LoadGrid(MyItemInfo); Initializing = false; @@ -1148,24 +972,10 @@ namespace Volian.Controls.Library { // if this is an RO Table, regenerate xml. This is done in the case that // the rotable was updated by the ro editor. - //if (MyFlexGrid.IsRoTable) RefreshGridData(); RefreshDisplay(false); IdentifyMe(false); } - //private void RefreshGridData() - //{ - // string ROID = MyFlexGrid.ROID; - // int rodbid = MyFlexGrid.RODbId; - // //MyFlexGrid.Clear(); - // ROFSTLookup MyROFSTLookup = MyItemInfo.MyDocVersion.DocVersionAssociations[0].MyROFst.ROFSTLookup; - // MyFlexGrid.ConvertTableROToGrid(MyROFSTLookup.GetRoValue(ROID), rodbid, ROID); - // //ConvertTableToGrid(MyROFSTLookup.GetRoValue(ROID), rodbid, ROID); - // //MyFlexGrid.RODbId = rodbid; - // //MyFlexGrid.ROID = ROID; - // //MyFlexGrid.IsRoTable = true; - // //SaveContents(); - //} public override void SetExpandAndExpander(ItemInfo itemInfo) { CanExpand = false; } // can't expand a table public void SavePastedCellRoTran() { @@ -1176,7 +986,7 @@ namespace Volian.Controls.Library int h = MyFlexGrid.Rows.Count; int r = 0; int c = 0; - String Rtf = null; + string Rtf; while (r < h) { CellRange cr = MyFlexGrid.GetMergedRange(r, c); @@ -1199,7 +1009,7 @@ namespace Volian.Controls.Library string linkstr = mro.Groups[2].Value; string[] roparts = linkstr.Split(" ".ToCharArray()); ContentRoUsage rousg = null; - int oldid = -1; + int oldid; using (Item itm = MyItemInfo.Get()) { using (RODb rodb = RODb.GetJustRoDb(Convert.ToInt32(roparts[2]))) @@ -1288,11 +1098,11 @@ namespace Volian.Controls.Library SaveContents(); } } - c = c + 1; + c++; if (c == w) { c = 0; - r = r + 1; + r++; } } } @@ -1304,7 +1114,6 @@ namespace Volian.Controls.Library CellRange cr = MyFlexGrid.GetMergedRange(MyFlexGrid.Selection.r1, MyFlexGrid.Selection.c1); // B2018-127 get merged range int row = MyFlexGrid.Row; int col = MyFlexGrid.Col; - //SaveContents(); DoNotRefresh = true; MyStepRTB.Rtf = MyStepRTB.DoNewLinkInGridCell(); DoNotRefresh = false; @@ -1343,11 +1152,11 @@ namespace Volian.Controls.Library return; } } - c = c + 1; + c++; if (c == w) { c = 0; - r = r + 1; + r++; } } } diff --git a/PROMS/Volian.Controls.Library/ImageItem.cs b/PROMS/Volian.Controls.Library/ImageItem.cs index 879ded63..c7bce8f7 100644 --- a/PROMS/Volian.Controls.Library/ImageItem.cs +++ b/PROMS/Volian.Controls.Library/ImageItem.cs @@ -1,9 +1,5 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; using System.Drawing; -using System.Data; -using System.Text; using System.Windows.Forms; using System.IO; using System.Text.RegularExpressions; @@ -16,23 +12,14 @@ namespace Volian.Controls.Library public partial class ImageItem : EditItem { - #region IEditItem - // set this for the imageitem so that other code (menuing/ribbons/treeview, etc) will continue to work. Include the MyItemInfo - public override StepRTB MyStepRTB - { - get { return _MyStepRTB; } - } - public override int TableWidth - { - get - { - return (int)_MyPictureBox.Width + ImageMargin; - } - } - /// - /// The left edge of the Tab - /// - public override int ItemLeft + #region IEditItem + // set this for the imageitem so that other code (menuing/ribbons/treeview, etc) will continue to work. Include the MyItemInfo + public override StepRTB MyStepRTB => _MyStepRTB; + public override int TableWidth => (int)_MyPictureBox.Width + ImageMargin; + /// + /// The left edge of the Tab + /// + public override int ItemLeft { get { return Left + lblTab.Left; } set { Left = value - lblTab.Left; } @@ -109,11 +96,8 @@ namespace Volian.Controls.Library RefreshDisplay(false); SetExpandAndExpander(MyItemInfo); } - public override void RefreshOrdinal() - { - TabFormat = null; - } - public override void HandleResize() {} + public override void RefreshOrdinal() => TabFormat = null; + public override void HandleResize() {} public override void MatchExpanded() {} /// /// Sets the focus to this ImageItem @@ -176,7 +160,7 @@ namespace Volian.Controls.Library SetWidthsAndHeights(img); //need this to trigger update of steptabribbonbuttons: // B2020-083: crash after approve of procedure when no edit window displayed - check for nulls - if (MyStepPanel != null && MyStepPanel.MyStepTabPanel != null) MyStepPanel.MyStepTabPanel.MyStepTabRibbon.SetButtonAndMenuEnabling(true); + if (MyStepPanel != null && MyStepPanel.MyStepTabPanel != null) MyStepPanel.MyStepTabPanel.MyStepTabRibbon.SetButtonAndMenuEnabling(); } public override void ToggleEditView(E_ViewMode vwMode) {} public override string TabFormat @@ -200,15 +184,9 @@ namespace Volian.Controls.Library public override Point TabLocation { get { return lblTab.Location; } } public override Font ContentFont { get { return MyStepRTB.Font; } set { /*MyStepRTB.Font = value*/; } } public override float ContentTop { get { return MyPictureBox.Top; } } - public override DialogResult ReplaceText(string rpltxt, string fndstr, bool caseSensitive, bool matchWholeWord, bool reverse, bool prompt, IWin32Window fndrpldlg) - { - return DialogResult.OK; - } - public override bool FindText(string str, bool caseSensitive, bool matchWholeWord, bool reverse) - { - return false; - } - public override void PositionToEnd() + public override DialogResult ReplaceText(string rpltxt, string fndstr, bool caseSensitive, bool matchWholeWord, bool reverse, bool prompt, IWin32Window fndrpldlg) => DialogResult.OK; + public override bool FindText(string str, bool caseSensitive, bool matchWholeWord, bool reverse) => false; + public override void PositionToEnd() { return; } @@ -216,15 +194,9 @@ namespace Volian.Controls.Library { return; } - public override string SelectedTextForFind - { - get { return null; } - } - public override bool SpellCheckNext() - { - return true; - } - public override bool Empty + public override string SelectedTextForFind => null; + public override bool SpellCheckNext() => true; + public override bool Empty { get { @@ -249,22 +221,17 @@ namespace Volian.Controls.Library get { return _MyPictureBox; } } private string FileName = null; - private static int _ImageMargin = 18; - /// - /// Margin between the EditItem and the ImageItem. Appears on the Right. - /// Will allow space to draw a Change Bar on the right side of the EditItem. - /// - public static int ImageMargin - { - get { return _ImageMargin; } - set { _ImageMargin = value; } - } - private bool _IsDirty = false; + + /// + /// Margin between the EditItem and the ImageItem. Appears on the Right. + /// Will allow space to draw a Change Bar on the right side of the EditItem. + /// + public static int ImageMargin { get; set; } = 18; + private bool _IsDirty = false; private int _origCfgHt = 0; // keep track if original size was stored in cfg private int _origCfgWd = 0; private bool _pastedNew = false; // need this for flagging newly pasted image (may need to clear cfg) private DisplayTags _displayTags = new DisplayTags(); - //House myhouse = new House(); #endregion #region Constructors @@ -390,10 +357,7 @@ namespace Volian.Controls.Library { InsType = insType; FileName = null; - //InitializeComponent(); SetupEditItem(itemInfo, myStepPanel, myParentEditItem, myChildRelation, expand, nextEditItem, false); - //MyPictureBox.Width = 100; - //MyPictureBox.Height = 100; this.Width = 100 + ImageMargin; this.Height = 100; if (insType == ImageItem.E_ImageSource.File) @@ -409,7 +373,7 @@ namespace Volian.Controls.Library MyPictureBox.Image = img; SetWidthsAndHeights(img); string ext = GetImageFormatExtension(img); - FileName = "paste." + ext; + FileName = $"paste.{ext}"; _IsDirty = true; } } @@ -455,54 +419,10 @@ namespace Volian.Controls.Library } } } - //public static System.Drawing.Imaging.ImageFormat GetImageFormat(this System.Drawing.Image img) - //{ - // if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg)) - // return System.Drawing.Imaging.ImageFormat.Jpeg; - // if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Bmp)) - // return System.Drawing.Imaging.ImageFormat.Bmp; - // if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Png)) - // return System.Drawing.Imaging.ImageFormat.Png; - // if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Emf)) - // return System.Drawing.Imaging.ImageFormat.Emf; - // if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Exif)) - // return System.Drawing.Imaging.ImageFormat.Exif; - // if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Gif)) - // return System.Drawing.Imaging.ImageFormat.Gif; - // if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Icon)) - // return System.Drawing.Imaging.ImageFormat.Icon; - // if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.MemoryBmp)) - // return System.Drawing.Imaging.ImageFormat.MemoryBmp; - // if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Tiff)) - // return System.Drawing.Imaging.ImageFormat.Tiff; - // else - // return System.Drawing.Imaging.ImageFormat.Wmf; - //} - private static string GetImageFormatExtension(System.Drawing.Image img) - { - return ("jpg"); // seems that this is the only one that works. - /* - if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg)) - return "jpg"; - if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Bmp)) - return "bmp"; - if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Png)) - return "png"; - if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Emf)) - return "emf"; - if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Gif)) - return "gif"; - if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Icon)) - return "ico"; - if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Tiff)) - return "tif"; - else - return "wmf"; - */ - } - #endregion - #region RO_Images - public void HandleRoImage() + private static string GetImageFormatExtension(System.Drawing.Image img) => ("jpg"); // seems that this is the only one that works. + #endregion + #region RO_Images + public void HandleRoImage() { string imageText = null; ProcedureInfo proc = MyItemInfo.MyProcedure; @@ -750,7 +670,7 @@ namespace Volian.Controls.Library MyPictureBox.Image = img; SetWidthsAndHeights(img); string ext = GetImageFormatExtension(img); - FileName = "paste." + ext; + FileName = $"paste.{ext}"; } } void MyStepRTB_RoInsert(object sender, StepRTBRoEventArgs args) @@ -964,7 +884,7 @@ namespace Volian.Controls.Library { string ext = ImageItem.GetImageFormatExtension(img); - filename = "paste." + ext; + filename = $"paste.{ext}"; } else img = null; diff --git a/PROMS/Volian.Controls.Library/LinkText.cs b/PROMS/Volian.Controls.Library/LinkText.cs index 51c50f7b..89d47a38 100644 --- a/PROMS/Volian.Controls.Library/LinkText.cs +++ b/PROMS/Volian.Controls.Library/LinkText.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; using System.Text.RegularExpressions; using VEPROMS.CSLA.Library; namespace Volian.Controls.Library @@ -19,11 +17,11 @@ namespace Volian.Controls.Library // First parse the string if (_LinkInfoText.Contains(@"\v")) throw new Exception("LinkText.ParseLink found RTF token"); - //_LinkInfoText = _LinkInfoText.Replace(@"\v ", ""); // this is not needed because this is selected Text does not contain RTF tokens // for tran : "2, #, #, # and 4#Link:TransitionRange:2 10 173 166" Match m = Regex.Match(_LinkInfoText, @"(.*)[#]Link:([A-Za-z]*):(.*)"); - _MyValue = m.Groups[1].Value; - _MyLink = "#Link:" + m.Groups[2].Value + ":" + m.Groups[3].Value; + //for debugging + //string _MyValue = m.Groups[1].Value; + //string _MyLink = $"#Link:{m.Groups[2].Value}:{m.Groups[3].Value}"; switch (m.Groups[2].Value) { case "ReferencedObject": @@ -56,12 +54,9 @@ namespace Volian.Controls.Library } } } - private string _LinkInfoText; - public string LinkInfoText - { - get { return _LinkInfoText; } - } - private TransitionInfo _MyTransitionInfo = null; + private readonly string _LinkInfoText; + public string LinkInfoText => _LinkInfoText; + private TransitionInfo _MyTransitionInfo = null; public TransitionInfo MyTransitionInfo { get { ParseLink(); return _MyTransitionInfo; } @@ -74,42 +69,12 @@ namespace Volian.Controls.Library { get { ParseLink(); return _MyTransitionInfo.MyItemRangeID; } } - private string _MyValue = null; - //public string MyValue - //{ - // get { ParseLink(); return _MyValue; } - //} - private string _MyLink = null; - //public string MyLink - //{ - // get { ParseLink(); return _MyLink; } - //} private RoUsageInfo _MyRoUsageInfo; public RoUsageInfo MyRoUsageInfo { get { ParseLink(); return _MyRoUsageInfo; } } - //private string _Roid = null; // TODO: need to return Referenced Object rather than just roid - //public string Roid - //{ - // get { ParseLink(); return _Roid; } - //} - //private string _RoUsageid = null; // TODO: need to return Referenced Object rather than just roid - //public string RoUsageid - //{ - // get { ParseLink(); return _RoUsageid; } - //} - //private string _RoDbid = null; // TODO: need to return Referenced Object rather than just roid - //public string RoDbid - //{ - // get { ParseLink(); return _RoDbid; } - //} private ParsedLinkType _MyParsedLinkType = ParsedLinkType.NotParsed; - //public ParsedLinkType MyParsedLinkType - //{ - // get { ParseLink(); return _MyParsedLinkType; } - //} - } #region enums public enum ParsedLinkType : int diff --git a/PROMS/Volian.Controls.Library/ListBoxMulti.cs b/PROMS/Volian.Controls.Library/ListBoxMulti.cs index 74acaa54..93f1e6ce 100644 --- a/PROMS/Volian.Controls.Library/ListBoxMulti.cs +++ b/PROMS/Volian.Controls.Library/ListBoxMulti.cs @@ -1,8 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using System.Windows.Forms; namespace Volian.Controls.Library diff --git a/PROMS/Volian.Controls.Library/MostRecentItem.cs b/PROMS/Volian.Controls.Library/MostRecentItem.cs index 1380e6ef..f07e9a5a 100644 --- a/PROMS/Volian.Controls.Library/MostRecentItem.cs +++ b/PROMS/Volian.Controls.Library/MostRecentItem.cs @@ -13,15 +13,11 @@ namespace Volian.Controls.Library public event ItemInfoEvent AfterRemove; internal void OnAfterRemove(object sender) { - if (AfterRemove != null) AfterRemove(sender); - } - private int _MaxItems = 10; - public int MaxItems - { - get { return _MaxItems; } - set { _MaxItems = value; } - } - public new MostRecentItem Add(MostRecentItem myMRI) + AfterRemove?.Invoke(sender); + } + + public int MaxItems { get; set; } = 10; + public new MostRecentItem Add(MostRecentItem myMRI) { Refresh(); MostRecentItem tmp = null; @@ -53,20 +49,19 @@ namespace Volian.Controls.Library // when a delete item occurs. void MyItemInfo_BeforeDelete(object sender) { - ItemInfo ii = sender as ItemInfo; - if (ii != null) - { - MostRecentItem tmp = null; - // Look for the ItemID - foreach (MostRecentItem mri in this) - if (mri.ItemID == ii.ItemID) - tmp = mri; - // If it exists - remove it - if (tmp != null) - Remove(tmp); - OnAfterRemove(null); - } - } + if (sender is ItemInfo ii) + { + MostRecentItem tmp = null; + // Look for the ItemID + foreach (MostRecentItem mri in this) + if (mri.ItemID == ii.ItemID) + tmp = mri; + // If it exists - remove it + if (tmp != null) + Remove(tmp); + OnAfterRemove(null); + } + } public MostRecentItem Add(int itemID) { ItemInfo tmp = ItemInfo.Get(itemID); @@ -101,9 +96,11 @@ namespace Volian.Controls.Library public static MostRecentItemList GetMRILst(System.Collections.Specialized.StringCollection list, int maxItems) { - MostRecentItemList mril = new MostRecentItemList(); - mril.MaxItems = maxItems; - if (list != null) + MostRecentItemList mril = new MostRecentItemList + { + MaxItems = maxItems + }; + if (list != null) for (int i = list.Count - 1; i >= 0;i-- )// Add in reverse order so first is last and last is first mril.Add(list[i]); return mril; @@ -127,28 +124,21 @@ namespace Volian.Controls.Library get { if (_MyItemInfo == null) - _MyItemInfo = ItemInfo.Get(_ItemID); + _MyItemInfo = ItemInfo.Get(ItemID); return _MyItemInfo; } set { - _ItemID = value.ItemID; + ItemID = value.ItemID; _MyItemInfo = value; _MenuTitle = GetMenuTitle(); _ToolTip = GetToolTip(_MyItemInfo); } } - internal void Refresh() - { - MyItemInfo = MyItemInfo; - } - private int _ItemID; - public int ItemID - { - get { return _ItemID; } - set { _ItemID = value; } - } - private string _MenuTitle; + internal void Refresh() => MyItemInfo = MyItemInfo; + + public int ItemID { get; set; } + private string _MenuTitle; public string MenuTitle { get @@ -159,11 +149,8 @@ namespace Volian.Controls.Library } set { _MenuTitle = value; } } - private string GetMenuTitle() - { - return MyItemInfo.Path; - } - private string _ToolTip; + private string GetMenuTitle() => MyItemInfo.Path; + private string _ToolTip; public string ToolTip { get @@ -177,10 +164,9 @@ namespace Volian.Controls.Library private static string GetToolTip(ItemInfo item) { // reset active parent if null - // if (MyItemInfo.MyProcedure.ActiveParent == null) MyItemInfo.MyProcedure.ActiveParent = null; DocVersionInfo tmp = (DocVersionInfo)(item.MyProcedure.ActiveParent); StringBuilder sb = new StringBuilder(); - int indent = BuildPath(tmp.MyFolder, ref sb); + _ = BuildPath(tmp.MyFolder, ref sb); //indent return sb.ToString(); } private static int BuildPath(FolderInfo folderInfo, ref StringBuilder sb) @@ -192,7 +178,7 @@ namespace Volian.Controls.Library } public override string ToString() { - return string.Format("{0}~{1}~{2}", _ItemID, MenuTitle, ToolTip); + return string.Format("{0}~{1}~{2}", ItemID, MenuTitle, ToolTip); } private static ItemInfo GetCorrectItemInfoType(int itemId) { @@ -228,9 +214,6 @@ namespace Volian.Controls.Library } return _RetainBadMRIs == 2; } - public MostRecentItem(ItemInfo myItem) - { - MyItemInfo = myItem; - } - } + public MostRecentItem(ItemInfo myItem) => MyItemInfo = myItem; + } } diff --git a/PROMS/Volian.Controls.Library/PreviewMultiLineRO.cs b/PROMS/Volian.Controls.Library/PreviewMultiLineRO.cs index 02ae1c4d..6afaf68b 100644 --- a/PROMS/Volian.Controls.Library/PreviewMultiLineRO.cs +++ b/PROMS/Volian.Controls.Library/PreviewMultiLineRO.cs @@ -1,11 +1,3 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; - namespace Volian.Controls.Library { public partial class PreviewMultiLineRO : DevComponents.DotNetBar.Office2007Form //Form diff --git a/PROMS/Volian.Controls.Library/PreviewROImage.cs b/PROMS/Volian.Controls.Library/PreviewROImage.cs index a3d1f9fb..9d2d7fb8 100644 --- a/PROMS/Volian.Controls.Library/PreviewROImage.cs +++ b/PROMS/Volian.Controls.Library/PreviewROImage.cs @@ -1,10 +1,5 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; using System.Drawing; -using System.Text; -using System.Windows.Forms; using System.IO; namespace Volian.Controls.Library @@ -30,9 +25,6 @@ namespace Volian.Controls.Library this.roImage.Image = thmb; this.Text = title; } - public bool ThumbnailCallback() - { - return false; - } - } + public bool ThumbnailCallback() => false; + } } \ No newline at end of file diff --git a/PROMS/Volian.Controls.Library/RTBAPI.cs b/PROMS/Volian.Controls.Library/RTBAPI.cs index 9d7ed96b..44039de6 100644 --- a/PROMS/Volian.Controls.Library/RTBAPI.cs +++ b/PROMS/Volian.Controls.Library/RTBAPI.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; using System.Windows.Forms; using System.Drawing; using System.Runtime.InteropServices; @@ -450,11 +448,6 @@ namespace Volian.Controls.Library } #endregion #region Structures - //struct CharRange - //{ - // public int cpMin; - // public int cpMax; - //} [StructLayout(LayoutKind.Sequential, Pack = 4, CharSet = CharSet.Auto)] public struct CharFormat2 { @@ -874,25 +867,6 @@ namespace Volian.Controls.Library pft.dySpaceBefore = spaceBefore * 1440 / dpi; SetParaFormat(richTextBox, pft); } - //developed for equation editor interface work, but ended up not needing it. Kept it in - // case it is needed in the future. - //public static void SetSpaceAfter(RichTextBox richTextBox, int spaceAfter) - //{ - // ParaFormatTwo pft = GetParaFormat(richTextBox); - // pft.dwMask = 0; - // pft.dwMask |= ParaFormatMasks.PFM_SPACEAFTER; - // // get the monitor's resolution in DPI and use it to set the linespacing value for - // // the richtextbox. Note that without this, the Arial Unicode font made the appearance of - // // almost double linespacing. Using PFS_Exact makes it appear as regular single spacing. - // Graphics g = richTextBox.CreateGraphics(); - // int dpi = Convert.ToInt32((g.DpiX + g.DpiY) / 2); - // g.Dispose(); - // // dyLineSpacing is Spacing between lines. the PFS_EXACT sets line spacing as the spacing from one - // //line to the next, in twips - thus the 1440. - - // pft.dySpaceAfter = spaceAfter * 1440 / dpi; - // SetParaFormat(richTextBox, pft); - //} public static void SetLineSpacing(RichTextBox richTextBox, ParaSpacing type) { ParaFormatTwo pft = GetParaFormat(richTextBox); @@ -955,22 +929,18 @@ namespace Volian.Controls.Library } SetCharFormat(richTextBox, RTBSelection.SCF_SELECTION, cft); } - public static bool IsSuperScript(RichTextBox richTextBox) - { - return (richTextBox.SelectionCharOffset>0); - } - public static bool IsSubScript(RichTextBox richTextBox) - { - return (richTextBox.SelectionCharOffset < 0); - } - public static void ToggleSubscript(bool bSet, RichTextBox richTextBox, RTBSelection selection) + public static bool IsSuperScript(RichTextBox richTextBox) => (richTextBox.SelectionCharOffset > 0); + public static bool IsSubScript(RichTextBox richTextBox) => (richTextBox.SelectionCharOffset < 0); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping RTBSelection")] + public static void ToggleSubscript(bool bSet, RichTextBox richTextBox, RTBSelection selection) { if (bSet) richTextBox.SelectionCharOffset = -2; else richTextBox.SelectionCharOffset = 0; } - public static void ToggleSuperscript(bool bSet, RichTextBox richTextBox, RTBSelection selection) + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping RTBSelection")] + public static void ToggleSuperscript(bool bSet, RichTextBox richTextBox, RTBSelection selection) { if (bSet) richTextBox.SelectionCharOffset = 2; @@ -1040,70 +1010,6 @@ namespace Volian.Controls.Library } SetCharFormat(richTextBox, selection, cft); } - //public static bool IsLink(RichTextBox richTextBox) - //{ - // CharFormatTwo cft = GetCharFormat(richTextBox, RTBSelection.SCF_SELECTION); - // return ((cft.dwEffects & CharFormatEffects.CFE_PROTECTED) == CharFormatEffects.CFE_PROTECTED); - //} - //public static void ToggleLink(bool bSet, RichTextBox richTextBox, RTBSelection selection) - //{ - // CharFormatTwo cft = GetCharFormat(richTextBox, selection); - // if (bSet) - // { - // cft.dwEffects |= CharFormatEffects.CFE_LINK; - // cft.dwMask |= CharFormatMasks.CFM_LINK; - // } - // else - // { - // cft.dwEffects &= ~RTBAPI.CharFormatEffects.CFE_LINK; - // } - // SetCharFormat(richTextBox, selection, cft); - //} - //public static void UnProtect(RichTextBox richTextBox) //, string type, string text, string link) - //{ - // //richTextBox.DetectUrls = false; - // CharFormatTwo cft = GetCharFormat(richTextBox, RTBAPI.RTBSelection.SCF_SELECTION); ; - // //int position = richTextBox.SelectionStart = richTextBox.TextLength; - // //richTextBox.SelectionLength = 0; - // //richTextBox.SelectedRtf = @"{\rtf1\ansi " + text + @"\v #" + link + @"\v0}"; - // //richTextBox.SelectedRtf = "{" + string.Format(@"\rtf1\ansi\protect\v {0}\v0 {1}\v #{2}", type, text, link) + "}"; - // //richTextBox.Select(position, type.Length + text.Length + link.Length + 1); - // cft.dwMask = RTBAPI.CharFormatMasks.CFM_PROTECTED; - // cft.dwEffects = 0; - // // The lines below can be used to allow link text to be edited - // //charFormat.dwMask = RTBAPI.CharFormatMasks.CFM_LINK; - // //charFormat.dwEffects = RTBAPI.CharFormatEffects.CFE_LINK; - // SetCharFormat(richTextBox, RTBSelection.SCF_SELECTION, cft); - // //rtbRTF.SetSelectionLink(true); - // //richTextBox.SelectionStart = richTextBox.TextLength; - // //richTextBox.SelectionLength = 0; - //} - //public static void Protect(RichTextBox richTextBox) //, string type, string text, string link) - //{ - // CharFormatTwo cft = GetCharFormat(richTextBox, RTBAPI.RTBSelection.SCF_SELECTION); ; - // cft.dwMask = CharFormatMasks.CFM_PROTECTED; - // cft.dwEffects = CharFormatEffects.CFE_PROTECTED; - // SetCharFormat(richTextBox, RTBSelection.SCF_SELECTION, cft); - //} - //public static void SetLink(RichTextBox richTextBox, string type, string text, string link) - //{ - // richTextBox.DetectUrls = false; - // CharFormatTwo cft = GetCharFormat(richTextBox, RTBAPI.RTBSelection.SCF_SELECTION); ; - // int position = richTextBox.SelectionStart = richTextBox.TextLength; - // richTextBox.SelectionLength = 0; - // //richTextBox.SelectedRtf = @"{\rtf1\ansi " + text + @"\v #" + link + @"\v0}"; - // richTextBox.SelectedRtf = "{" + string.Format(@"\rtf1\ansi\protect\v {0}\v0 {1}\v #{2}", type, text, link) + "}"; - // richTextBox.Select(position, type.Length + text.Length + link.Length + 1); - // cft.dwMask = RTBAPI.CharFormatMasks.CFM_LINK | RTBAPI.CharFormatMasks.CFM_PROTECTED; - // cft.dwEffects = RTBAPI.CharFormatEffects.CFE_LINK | RTBAPI.CharFormatEffects.CFE_PROTECTED; - // // The lines below can be used to allow link text to be edited - // //charFormat.dwMask = RTBAPI.CharFormatMasks.CFM_LINK; - // //charFormat.dwEffects = RTBAPI.CharFormatEffects.CFE_LINK; - // SetCharFormat(richTextBox, RTBSelection.SCF_SELECTION, cft); - // //rtbRTF.SetSelectionLink(true); - // richTextBox.SelectionStart = richTextBox.TextLength; - // richTextBox.SelectionLength = 0; - //} #endregion } } diff --git a/PROMS/Volian.Controls.Library/RTBItem.cs b/PROMS/Volian.Controls.Library/RTBItem.cs index cb52e865..0893fb59 100644 --- a/PROMS/Volian.Controls.Library/RTBItem.cs +++ b/PROMS/Volian.Controls.Library/RTBItem.cs @@ -1,9 +1,5 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; using System.Drawing; -using System.Data; -using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms; using VEPROMS.CSLA.Library; @@ -36,14 +32,11 @@ namespace Volian.Controls.Library public Label MyLabel { get { return lblTab; } } - /// - /// Used to connect the RichTextBox with the menus and toolbars - /// - public override StepRTB MyStepRTB - { - get { return _MyStepRTB; } - } - public override int TableWidth { get { return (int)GetTableWidth(_MyStepRTB.Font, MyItemInfo.MyContent.Text, true); } } + /// + /// Used to connect the RichTextBox with the menus and toolbars + /// + public override StepRTB MyStepRTB => _MyStepRTB; + public override int TableWidth { get { return (int)GetTableWidth(_MyStepRTB.Font, MyItemInfo.MyContent.Text, true); } } /// /// The left edge of the Tab @@ -80,8 +73,6 @@ namespace Volian.Controls.Library get { return _MyStepRTB.Width; } set { - // This is wrong for single column (KBR) - RHM Debug: - //MyStepRTB.Width = value; Width = value + lblTab.Left + lblTab.Width + (this.Width - MyStepRTB.Right); } } @@ -167,7 +158,6 @@ namespace Volian.Controls.Library { ItemInfo.ResetTabString(MyID); string tabString = MyItemInfo.IsSection ? MyItemInfo.DisplayNumber.PadRight(MyItemInfo.MyTab.CleanText.Length) : MyItemInfo.MyTab.CleanText; - //string tabString = /*MyItemInfo.IsSection ? MyItemInfo.DisplayNumber : */ MyItemInfo.MyTab.CleanText; if (!MyItemInfo.IsProcedure) lblTab.Text = tabString; // B2021-068: don't reset if procedure (it is blank when initialized) // calculate the width based upon characters per inch considering user's DPI @@ -182,7 +172,6 @@ namespace Volian.Controls.Library bool lastDigitSingle = Regex.IsMatch(tabString, "^.*[^0-9][0-9] *$"); lblTab.Width = ((lastDigitSingle && MyItemInfo.IsStep ? 1 : 0) + tabString.Length) * MyStepPanel.DPI / cpi; Invalidate(); - //if (MyItemInfo.MyTab.Offset == 0) // commented out for Farley bug fix B2015-123 alignment of tabs on the edit screen (Farly is only one using tab offset) { // In the following if statement, the last part, 'IsHigh & PageBreakOnStep' (PageBreakOnStep // flags background steps and IsHigh is for the HLS - Cautions/Notes were ok), was added @@ -199,19 +188,14 @@ namespace Volian.Controls.Library } } - #endregion - #region Properties - private static int _RTBMargin = 3; - /// - /// Margin between the EditItem and the StepRTB. Appears on the Right. - /// Will allow space to draw a Change Bar on the right side of the EditItem. - /// - public static int RTBMargin - { - get { return _RTBMargin; } - set { _RTBMargin = value; } - } - private int? _CheckOffMargin = null; + #endregion + #region Properties + /// + /// Margin between the EditItem and the StepRTB. Appears on the Right. + /// Will allow space to draw a Change Bar on the right side of the EditItem. + /// + public static int RTBMargin { get; set; } = 3; + private int? _CheckOffMargin = null; /// /// Margin between the EditItem and the StepRTB. Appears on the Right. /// Will allow space to draw a CheckOff on the right side of the EditItem. @@ -238,32 +222,17 @@ namespace Volian.Controls.Library } set { _CheckOffMargin = value; } } - private EnhancedAddTypes _EnhAddType = EnhancedAddTypes.No; - public EnhancedAddTypes EnhAddType - { - get { return _EnhAddType; } - set { _EnhAddType = value; } - } - private ItemInfo _EnhAddFromItemInfo = null; - public ItemInfo EnhAddFromItemInfo - { - get { return _EnhAddFromItemInfo; } - set { _EnhAddFromItemInfo = value; } - } - private bool _DoingPasteReplace = false; - public bool DoingPasteReplace - { - get { return _DoingPasteReplace; } - set { _DoingPasteReplace = value; } - } - #endregion - #region Constructors - public RTBItem(ItemInfo itemInfo, StepPanel myStepPanel, EditItem myParentEditItem, ChildRelation myChildRelation, bool expand) + + public EnhancedAddTypes EnhAddType { get; set; } = EnhancedAddTypes.No; + public ItemInfo EnhAddFromItemInfo { get; set; } = null; + public bool DoingPasteReplace { get; set; } = false; + #endregion + #region Constructors + public RTBItem(ItemInfo itemInfo, StepPanel myStepPanel, EditItem myParentEditItem, ChildRelation myChildRelation, bool expand) { // B2016-179 If the parent is a section and the child is not a step then set expand to true. // B2016-211 Added subsection check - don't expand all of the sub sections when you open a section (Farley) expand |= (!itemInfo.IsStepPart && itemInfo.ActiveParent.IsSection) && !itemInfo.IsSubsection; - //// TIMING: DisplayItem.TimeIt("CSLARTB Top"); InitializeComponent();// TODO: Performance 25% SetupEditItem(itemInfo, myStepPanel, myParentEditItem, myChildRelation, expand, null, false); MyStepRTB.TextChanged += new EventHandler(MyStepRTB_TextChanged); @@ -273,7 +242,6 @@ namespace Volian.Controls.Library // B2016-179 If the parent is a section and the child is not a step then set expand to true. // B2016-211 Added subsection check - don't expand all of the sub sections when you open a section (Farley) expand |= (!itemInfo.IsStepPart && itemInfo.ActiveParent is SectionInfo) && !itemInfo.IsSubsection; - //// TIMING: DisplayItem.TimeIt("CSLARTB Top"); InitializeComponent();// TODO: Performance 25% SetupEditItem(itemInfo, myStepPanel, myParentEditItem, myChildRelation, expand, nextEditItem, false); MyStepRTB.TextChanged += new EventHandler(MyStepRTB_TextChanged); @@ -283,124 +251,10 @@ namespace Volian.Controls.Library // B2016-179 If the parent is a section and the child is not a step then set expand to true. // B2016-211 Added subsection check - don't expand all of the sub sections when you open a section (Farley) expand |= (!itemInfo.IsStepPart && itemInfo.ActiveParent is SectionInfo) && !itemInfo.IsSubsection; - //// TIMING: DisplayItem.TimeIt("CSLARTB Top"); InitializeComponent();// TODO: Performance 25% SetupEditItem(itemInfo, myStepPanel, myParentEditItem, myChildRelation, expand, null, addFirstChld); MyStepRTB.TextChanged += new EventHandler(MyStepRTB_TextChanged); } - //private void SetupRTBItem(ItemInfo itemInfo, StepPanel myStepPanel, EditItem myParentEditItem, ChildRelation myChildRelation, bool expand, EditItem nextEditItem) - //{ - // //if (itemInfo.ItemID == 225) _MyStepRTB.Resize += new EventHandler(_MyStepRTB_Resize); - // //_MyStepRTB.MyRTBItem = this; - // //// TIMING: DisplayItem.TimeIt("CSLARTB InitComp"); - // BackColor = myStepPanel.PanelColor; - // //_MyStepRTB.BackColor = myStepPanel.InactiveColor; - // // TODO: Adjust top based upon format - // // TODO: Remove Label and just output ident on the paint event - // lblTab.Left = 20; - // SetupHeader(itemInfo); - // this.Paint += new PaintEventHandler(RTBItem_Paint); - // this.BackColorChanged += new EventHandler(RTBItem_BackColorChanged); - // if (itemInfo != null) - // { - // ContentType = (int)itemInfo.MyContent.Type; - // switch (ContentType / 10000) - // { - // case 0: // Procedure - // _MyStepRTB.Font = myStepPanel.ProcFont;// lblTab.Font = myStepPanel.ProcFont; - // lblTab.Font = itemInfo.MyTab.MyFont.WindowsFont; - // break; - // case 1: // Section - // _MyStepRTB.Font = myStepPanel.SectFont;// lblTab.Font = myStepPanel.SectFont; - // lblTab.Font = itemInfo.MyTab.MyFont.WindowsFont; - // break; - // case 2: // Steps - // _MyStepRTB.Font = myStepPanel.StepFont;//lblTab.Font = myStepPanel.StepFont; - // lblTab.Font = itemInfo.MyTab.MyFont.WindowsFont; - // MyStepData = itemInfo.ActiveFormat.PlantFormat.FormatData.StepDataList[ContentType % 10000]; - // break; - // } - // //this.Move += new EventHandler(DisplayItem_Move); - // } - // else - // { - // if (myStepPanel.MyFont != null) _MyStepRTB.Font = lblTab.Font = myStepPanel.MyFont; - // } - // if (expand) _MyvlnExpander.ShowExpanded(); - // MyStepPanel = myStepPanel; - // if (itemInfo != null) myStepPanel._LookupEditItems.Add(itemInfo.ItemID, this); - // _MyChildRelation = myChildRelation; - // if (myParentEditItem != null) RNOLevel = myParentEditItem.RNOLevel; - // if (itemInfo != null) - // { - // //// TIMING: DisplayItem.TimeIt("CSLARTB before _Layout"); - // MyStepSectionLayoutData = itemInfo.ActiveFormat.MyStepSectionLayoutData; - // //// TIMING: DisplayItem.TimeIt("CSLARTB _Layout"); - // if (myParentEditItem != null) - // SeqLevel = myParentEditItem.SeqLevel + ((myChildRelation == ChildRelation.After || myChildRelation == ChildRelation.Before) && itemInfo.IsSequential ? 1 : 0); - // //// TIMING: DisplayItem.TimeIt("CSLARTB seqLevel"); - // MyItemInfo = itemInfo; - // MyItemInfo.MyConfig.PropertyChanged += new PropertyChangedEventHandler(MyConfig_PropertyChanged); - // } - // //// TIMING: DisplayItem.TimeIt("CSLARTB MyItem"); - // myStepPanel.Controls.Add(this); - - // switch (myChildRelation) - // { - // case ChildRelation.After: - // AddItem(myParentEditItem, ref myParentEditItem._MyAfterEditItems, nextEditItem); - // break; - // case ChildRelation.Before: - // AddItem(myParentEditItem, ref myParentEditItem._MyBeforeEditItems, nextEditItem); - // break; - // case ChildRelation.RNO: - // RNOLevel = myParentEditItem.RNOLevel + 1; - // AddItem(myParentEditItem, ref myParentEditItem._MyRNOEditItems, nextEditItem); - // break; - // case ChildRelation.None: - // break; - // } - // if (itemInfo != null) - // { - // if (myChildRelation == ChildRelation.None) - // { - // if (ContentType == 0 && MyStepSectionLayoutData != null) - // { - // LastMethodsPush(string.Format("SetupRTBItem {0}", MyID)); - // Width = MyStepPanel.ToDisplay(MyStepSectionLayoutData.WidT); - // } - // } - // } - // //// TIMING: DisplayItem.TimeIt("CSLARTB Parent"); - // SetText(); - // //// TIMING: DisplayItem.TimeIt("CSLARTB SetText"); - // if (itemInfo != null) - // { - // Name = string.Format("Item-{0}", itemInfo.ItemID); - // SetExpandAndExpander(itemInfo); - // if (expand && (itemInfo.MyContent.ContentPartCount != 0)) // If it should expand and it can expand - // Expand(true); - // else - // if (myParentEditItem == null)// If it is the top node - // if (ContentType >= 20000) // and it is a step - fully expand - // Expand(true); - // else // otherwise only expand one level - // Expand(false); - // } - // //// TIMING: DisplayItem.TimeIt("CSLARTB before Controls Add"); - // //myStepPanel.Controls.Add(this); - // int top = FindTop(0); - // if (Top < top) - // { - // LastMethodsPush("SetupRTBItem"); - // MyStepPanel.ItemMoving++; - // Top = top; - // MyStepPanel.ItemMoving--; - // LastMethodsPop(); - // } - // _Loading = false; - // //// TIMING: DisplayItem.TimeIt("CSLARTB Controls Add"); - //} private void SetupHeader() { SetupHeader(MyItemInfo); @@ -412,16 +266,13 @@ namespace Volian.Controls.Library { if (MyStepPanel != null && this == MyStepPanel.SelectedEditItem) ScrollToCenter(); - //MyStepPanel.ScrollControlIntoView(this); } void MyStepRTB_TextChanged(object sender, EventArgs e) { if (MyStepPanel != null && this == MyStepPanel.SelectedEditItem) ScrollToCenter(); - //MyStepPanel.ScrollControlIntoView(this); } private Label lblHeader = null; - private Label lblFooter = null; private void SetupHeaderFooter(ref Label lbl, string name, MetaTag mTag) { if (lbl == null) lbl = new Label(); @@ -479,11 +330,9 @@ namespace Volian.Controls.Library if (ed.Type != 0) { ItemInfo ii = ItemInfo.Get(ed.ItemID); - //if (MyStepPanel.MyStepTabPanel.MyDisplayTabControl.IsItemInfoProcedureOpen(ii)) if (ii != null) MyStepPanel.MyStepTabPanel.MyDisplayTabControl.OnRefreshEnhancedDocument(new ItemSelectedChangedEventArgs(ii)); - if (dti != null) - dti.MyStepTabPanel.MyDisplayTabControl.OpenItem(this.MyItemInfo); + dti?.MyStepTabPanel.MyDisplayTabControl.OpenItem(this.MyItemInfo); } } } @@ -511,7 +360,6 @@ namespace Volian.Controls.Library { Cursor tmp = Cursor.Current; Cursor.Current = Cursors.WaitCursor; - int top = TopMostEditItem.Top;// This doesn't work - this is since the last time it was expanded. int topOffset = TopMostEditItem.Top + MyStepPanel.VerticalScroll.Value; Colapsing = true; // Hide Children @@ -519,7 +367,6 @@ namespace Volian.Controls.Library // Adjust Positions int topOffsetAfter = TopMostEditItem.Top + MyStepPanel.VerticalScroll.Value; ExpandPrefix = topOffset - topOffsetAfter; - //ExpandSuffix = BottomMostEditItem.Bottom - Bottom; if (topOffsetAfter != topOffset) { LastMethodsPush(string.Format("Colapse {0}", MyID)); @@ -569,7 +416,7 @@ namespace Volian.Controls.Library /// private void _MyStepRTB_LinkGoTo(object sender, StepPanelLinkEventArgs args) { - _MyLog.DebugFormat("_DisplayRTB_LinkGoTo " + args.LinkInfoText); + _MyLog.DebugFormat($"_DisplayRTB_LinkGoTo {args.LinkInfoText}"); MyStepPanel.OnLinkClicked(sender, args); } void _MyStepRTB_RoInsert(object sender, StepRTBRoEventArgs args) @@ -603,10 +450,6 @@ namespace Volian.Controls.Library { MyStepPanel.CursorMovement(this, args.CursorLocation, args.Key); } - //private void _MyStepRTB_ModeChange(object sender, StepRTBModeChangeEventArgs args) - //{ - // MyStepPanel.OnModeChange(sender as StepRTB, args); - //} void _MyStepRTB_SetMenu(object sender, StepRTBMenuEventArgs args) { if (args.MenuGroup == null) @@ -663,7 +506,6 @@ namespace Volian.Controls.Library foreach (string line in lines) { string lineAdj = Regex.Replace(line, @"\\u....\?", "X"); // Replace Special characters - //line2 = Regex.Replace(line2, @"\\.*? ", ""); // Remove RTF Commands - Really should not be any lineAdj = StepRTB.RemoveLinkComments(lineAdj); // MeasureString doesn't work properly if the line include graphics characters. // So, Measure a string of the same length with 'M's. @@ -795,12 +637,11 @@ namespace Volian.Controls.Library bool success = MyStepRTB.OrigDisplayText.Save((RichTextBox)MyStepRTB); if (success) { - StepConfig sc = MyStepRTB.MyItemInfo.MyConfig as StepConfig; - // if the plant has the change id option, the change id was entered when the program started. - // this should be saved for every piece of edited data. Note that the set of config - // item Step_MultipleChangeID has the save built in to it. - if (sc == null) sc = new StepConfig(); - if (MyStepRTB.MyItemInfo.IsStep && + // if the plant has the change id option, the change id was entered when the program started. + // this should be saved for every piece of edited data. Note that the set of config + // item Step_MultipleChangeID has the save built in to it. + if (!(MyStepRTB.MyItemInfo.MyConfig is StepConfig sc)) sc = new StepConfig(); + if (MyStepRTB.MyItemInfo.IsStep && MyStepRTB.MyItemInfo.ActiveFormat.PlantFormat.FormatData.ProcData.ChangeBarData.ChangeIds && !this.MyStepPanel.MyStepTabPanel.MyDisplayTabControl.EditorialChange) { @@ -884,7 +725,6 @@ namespace Volian.Controls.Library } public override void IdentifyMe(bool highlight) { - //this.BringToFront(); // B2017-187 when called all the time, slows down the display of step and confuses the scroll bar if (highlight) { MyStepRTB.BringToFront(); // B2017-187 when called all the time, slows down the display of step and confuses the scroll bar @@ -931,7 +771,6 @@ namespace Volian.Controls.Library { _MyLog.WarnFormat("Attempt to give Focus to Disposed Object {0}", MyID); } - // if (CanExpand) AutoExpand(); // Expand the item if you can ScrollToCenter(); } /// @@ -942,19 +781,10 @@ namespace Volian.Controls.Library _MyStepRTB.Focus(); ScrollToCenter(); } - public override DialogResult ReplaceText(string rpltxt, string fndstr, bool caseSensitive, bool matchWholeWord, bool reverse, bool prompt, IWin32Window fndrpldlg) - { - return MyStepRTB.ReplaceText(rpltxt, fndstr, caseSensitive, matchWholeWord, reverse, prompt, fndrpldlg); - } - public override bool FindText(string str, bool caseSensitive, bool matchWholeWord, bool reverse) - { - return MyStepRTB.FindText(str, caseSensitive, matchWholeWord, reverse); - } - public override void PositionToEnd() - { - MyStepRTB.SelectionStart = MyStepRTB.Text.Length; - } - public override void PositionToStart() + public override DialogResult ReplaceText(string rpltxt, string fndstr, bool caseSensitive, bool matchWholeWord, bool reverse, bool prompt, IWin32Window fndrpldlg) => MyStepRTB.ReplaceText(rpltxt, fndstr, caseSensitive, matchWholeWord, reverse, prompt, fndrpldlg); + public override bool FindText(string str, bool caseSensitive, bool matchWholeWord, bool reverse) => MyStepRTB.FindText(str, caseSensitive, matchWholeWord, reverse); + public override void PositionToEnd() => MyStepRTB.SelectionStart = MyStepRTB.Text.Length; + public override void PositionToStart() { return; } @@ -973,41 +803,21 @@ namespace Volian.Controls.Library return null; } } - public override bool SpellCheckNext() - { - return MyStepRTB.SpellCheckNext(); - } - public override void SetActive() - { - MyStepRTB.BackColor = MyStepPanel.ActiveColor; - } - public override bool Empty + public override bool SpellCheckNext() => MyStepRTB.SpellCheckNext(); + public override void SetActive() => MyStepRTB.BackColor = MyStepPanel.ActiveColor; + public override bool Empty { get { // Console.WriteLine("step rtb is dirty {0} and rtf is {1}", MyStepRTB.IsDirty, MyStepRTB.Rtf); - // string txt = MyStepRTB.Text; - // Console.WriteLine("step rtb is dirty {0} and rtf is {1}", MyStepRTB.IsDirty, MyStepRTB.Rtf); - // return txt == ""; - //return MyStepRTB.IsEmpty; return MyStepRTB.Text == ""; } set { MyStepRTB.Text = value ? "" : " "; } } - //public override bool IsEmpty() // this becomes 'Empty' property, i.e. get/set. - //{ // for the set, emtpy is following line (= not ==). - // // for not empty - it's code that is in 'MakeNotEmpty' - // return MyStepRTB.Text == ""; - //} - //public override void MakeNotEmpty() - //{ - // MyStepRTB.Text = " "; - //} public override void RefreshDisplay(bool activeMode) { MyStepRTB.VwMode = MyStepPanel.VwMode; MyStepRTB.RefreshDisplay(activeMode); - //MyStepRTB.ViewRTB = !activeMode; } public override void ToggleEditView(E_ViewMode vwMode) { @@ -1026,8 +836,7 @@ namespace Volian.Controls.Library public override void SetupHeader(ItemInfo itemInfo) { lblTab.Top = 3 + ((itemInfo.HasHeader) ? 23 : 0); - _MyStepRTB.Top = lblTab.Top; // 3 + ((itemInfo.HasHeader) ? 23 : 0); - //lblTab.Move += new EventHandler(lblTab_Move); + _MyStepRTB.Top = lblTab.Top; if (itemInfo.HasHeader) SetupHeaderFooter(ref lblHeader, "Header", itemInfo.MyHeader); else @@ -1037,14 +846,11 @@ namespace Volian.Controls.Library lblHeader = null; } } - public override void ShowExpanded() - { - _MyvlnExpander.ShowExpanded(); - } - /// - /// Sets the Item and as a result the text for the RichTextBox - /// - public override void SetText() + public override void ShowExpanded() => _MyvlnExpander.ShowExpanded(); + /// + /// Sets the Item and as a result the text for the RichTextBox + /// + public override void SetText() { LastMethodsPush("SetText"); if (MyItemInfo != null) @@ -1078,10 +884,7 @@ namespace Volian.Controls.Library break; } } - public override void SaveCurrentAndContents() - { - SaveContents(); - } - #endregion - } + public override void SaveCurrentAndContents() => SaveContents(); + #endregion + } } diff --git a/PROMS/Volian.Controls.Library/RichTextBox41.cs b/PROMS/Volian.Controls.Library/RichTextBox41.cs index 027ec6ce..c34a9c98 100644 --- a/PROMS/Volian.Controls.Library/RichTextBox41.cs +++ b/PROMS/Volian.Controls.Library/RichTextBox41.cs @@ -1,13 +1,7 @@ using System; using System.ComponentModel; -using System.Collections.Generic; -using System.Diagnostics; -using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices; -using System.Drawing; -using VEPROMS.CSLA.Library; -using System.Text.RegularExpressions; namespace Volian.Controls.Library { diff --git a/PROMS/Volian.Controls.Library/RomanNumeral.cs b/PROMS/Volian.Controls.Library/RomanNumeral.cs index e687686a..08986a51 100644 --- a/PROMS/Volian.Controls.Library/RomanNumeral.cs +++ b/PROMS/Volian.Controls.Library/RomanNumeral.cs @@ -1,19 +1,14 @@ -using System; -using System.Collections.Generic; -using System.Text; - namespace Volian.Controls.Library { public static class RomanNumeral { - private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private enum RomanOffset : int { Hundreds = 2, Tens = 4, Units = 6 } - private static string _Romans = "MDCLXVI"; + private static readonly string _Romans = "MDCLXVI"; private static string RomanPart(RomanOffset offset, int value) { int iFive = value / 5; @@ -34,21 +29,5 @@ namespace Volian.Controls.Library RomanPart(RomanOffset.Tens, tens) + RomanPart(RomanOffset.Units, units); } - // private static int[] _TestRomans = new int[] { - // 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,25,30,40,50,60,69,70,80,90,99, - // 100,200,400,500,600,666,700,800,900,1000,1444,1666,1945,1997,1999,2000,2007,3000 - // }; - // public static void ShowRomans() - // { - // for (int i = 0; i < _TestRomans.Length; i++) - // { - // if(_MyLog.IsInfoEnabled)_MyLog.InfoFormat("{0},{1}", _TestRomans[i], Convert(_TestRomans[i])); - // } - // //if(_MyLog.IsInfoEnabled)_MyLog.InfoFormat("{0},{1}", 4, Convert(4)); - // //if(_MyLog.IsInfoEnabled)_MyLog.InfoFormat("{0},{1}", 5, Convert(5)); - // //if(_MyLog.IsInfoEnabled)_MyLog.InfoFormat("{0},{1}", 6, Convert(6)); - // //if(_MyLog.IsInfoEnabled)_MyLog.InfoFormat("{0},{1}", 8, Convert(8)); - // //if(_MyLog.IsInfoEnabled)_MyLog.InfoFormat("{0},{1}", 9, Convert(9)); - // } } } diff --git a/PROMS/Volian.Controls.Library/RtfRawItem.cs b/PROMS/Volian.Controls.Library/RtfRawItem.cs index f7664f98..abfcd1b9 100644 --- a/PROMS/Volian.Controls.Library/RtfRawItem.cs +++ b/PROMS/Volian.Controls.Library/RtfRawItem.cs @@ -1,9 +1,5 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; using System.Drawing; -using System.Data; -using System.Text; using System.Windows.Forms; using VEPROMS.CSLA.Library; using Volian.Base.Library; @@ -12,22 +8,13 @@ namespace Volian.Controls.Library { public partial class RtfRawItem : EditItem { - #region IEditItem - public override StepRTB MyStepRTB - { - get { return _MyStepRTB; } - } - public override int TableWidth - { - get - { - return (int)_MyStepRTB.Width + RtfRawMargin; - } - } - /// - /// The left edge of the Tab (no visible tab, but use this for EditItem interfacing - /// - public override int ItemLeft + #region IEditItem + public override StepRTB MyStepRTB => _MyStepRTB; + public override int TableWidth => (int)_MyStepRTB.Width + RtfRawMargin; + /// + /// The left edge of the Tab (no visible tab, but use this for EditItem interfacing + /// + public override int ItemLeft { get { return Left + lblTab.Left; } set { Left = value - lblTab.Left; } @@ -62,11 +49,11 @@ namespace Volian.Controls.Library Width = value + lblTab.Left + lblTab.Width; } } - public override int BorderWidth { get { return (_MyStepRTB.Width - _MyStepRTB.ClientRectangle.Width); } } - /// - /// Location of the RichTextBox - /// - public override Point ContentLocation + public override int BorderWidth => (_MyStepRTB.Width - _MyStepRTB.ClientRectangle.Width); + /// + /// Location of the RichTextBox + /// + public override Point ContentLocation { get { return new Point(Location.X + _MyStepRTB.Left, Location.Y); } set { Location = new Point(value.X - _MyStepRTB.Left, value.Y); } @@ -99,21 +86,15 @@ namespace Volian.Controls.Library _MyToolTip.SetSuperTooltip(MyStepRTB, tpi); ToolTipOnOff(); // B2025-050 Show the tooltip based on User Options Settings } - public override void ToolTipOnOff() - { - _MyToolTip.Enabled = VlnSettings.StepTypeToolTip; // B2025-XXX Show the tooltip based on User Options Settings - } - public override void RefreshContent() + public override void ToolTipOnOff() => _MyToolTip.Enabled = VlnSettings.StepTypeToolTip; // B2025-XXX Show the tooltip based on User Options Settings + public override void RefreshContent() { IdentifyMe(false); MyStepRTB.Rtf = MyItemInfo.MyContent.Text; RefreshDisplay(false); } - public override void RefreshOrdinal() - { - TabFormat = null; - } - public override void HandleResize() {} + public override void RefreshOrdinal() => TabFormat = null; + public override void HandleResize() {} public override void MatchExpanded() {} public override void ItemSelect() { @@ -136,11 +117,8 @@ namespace Volian.Controls.Library _MyStepRTB.Focus(); ScrollToCenter(); } - public override void SetActive() - { - this.BackColor = MyStepPanel.ActiveColor; - } - public override void SetText() + public override void SetActive() => this.BackColor = MyStepPanel.ActiveColor; + public override void SetText() { LastMethodsPush("SetText"); if (MyItemInfo != null) @@ -150,15 +128,9 @@ namespace Volian.Controls.Library } LastMethodsPop(); } - public override void SetExpandAndExpander(ItemInfo itemInfo) - { - CanExpand = false; - } - public override void SaveCurrentAndContents() - { - SaveContents(); - } - public override void RefreshDisplay(bool activeMode) + public override void SetExpandAndExpander(ItemInfo itemInfo) => CanExpand = false; + public override void SaveCurrentAndContents() => SaveContents(); + public override void RefreshDisplay(bool activeMode) { MyStepRTB.VwMode = MyStepPanel.VwMode; Size sz = GetRtfRawSize(MyStepRTB.Rtf); @@ -177,13 +149,10 @@ namespace Volian.Controls.Library Width = sz.Width; Height = _MyStepRTB.Height + _MyStepRTB.Top + 7; ItemWidth = Width; - MyStepPanel.MyStepTabPanel.MyStepTabRibbon.SetButtonAndMenuEnabling(true); + MyStepPanel.MyStepTabPanel.MyStepTabRibbon.SetButtonAndMenuEnabling(); } - public override void ToggleEditView(E_ViewMode vwMode) - { - SaveContents(); - } - public override string TabFormat + public override void ToggleEditView(E_ViewMode vwMode) => SaveContents(); + public override string TabFormat { get { return null; } set { ;} @@ -204,15 +173,9 @@ namespace Volian.Controls.Library public override Point TabLocation { get { return lblTab.Location; } } public override Font ContentFont { get { return MyStepRTB.Font; } set { /*MyStepRTB.Font = value*/; } } public override float ContentTop { get { return MyStepRTB.Top; } } - public override DialogResult ReplaceText(string rpltxt, string fndstr, bool caseSensitive, bool matchWholeWord, bool reverse, bool prompt, IWin32Window fndrpldlg) - { - return DialogResult.OK; - } - public override bool FindText(string str, bool caseSensitive, bool matchWholeWord, bool reverse) - { - return false; - } - public override void PositionToEnd() + public override DialogResult ReplaceText(string rpltxt, string fndstr, bool caseSensitive, bool matchWholeWord, bool reverse, bool prompt, IWin32Window fndrpldlg) => DialogResult.OK; + public override bool FindText(string str, bool caseSensitive, bool matchWholeWord, bool reverse) => false; + public override void PositionToEnd() { return; } @@ -220,15 +183,9 @@ namespace Volian.Controls.Library { return; } - public override string SelectedTextForFind - { - get {return null;} - } - public override bool SpellCheckNext() - { - return false; - } - public override bool Empty + public override string SelectedTextForFind => null; + public override bool SpellCheckNext() => false; + public override bool Empty { get { @@ -236,30 +193,22 @@ namespace Volian.Controls.Library } set { _MyStepRTB.Text = value ? "" : " "; } } - public override void RefreshTab() - { - TabFormat = null; - } - public override void SetupHeader(ItemInfo itemInfo) + public override void RefreshTab() => TabFormat = null; + public override void SetupHeader(ItemInfo itemInfo) { return; } public override void ShowExpanded() {} - #endregion - #region Properties - private static int _RtfRawMargin = 6; // make it a little bigger than rtbitems so it can be seen - /// - /// Margin between the EditItem and the RtfRawItem. Appears on the Right. - /// Will allow space to draw a Change Bar on the right side of the EditItem. - /// - public static int RtfRawMargin - { - get { return _RtfRawMargin; } - set { _RtfRawMargin = value; } - } - #endregion - #region Constructors - public RtfRawItem() + #endregion + #region Properties + /// + /// Margin between the EditItem and the RtfRawItem. Appears on the Right. + /// Will allow space to draw a Change Bar on the right side of the EditItem. + /// + public static int RtfRawMargin { get; set; } = 6; + #endregion + #region Constructors + public RtfRawItem() { InitializeComponent(); } @@ -313,14 +262,10 @@ namespace Volian.Controls.Library Click += new EventHandler(RtfRawItem_Click); MyStepRTB.Click += new EventHandler(RtfRawItem_Click); } - #endregion - #region EventHandlers - void RtfRawItem_Click(object sender, EventArgs e) - { - //if (MyStepPanel.DisplayItemChanging) return; - MyStepPanel.SelectedEditItem = this; - } - private void _MyStepRTB_HeightChanged(object sender, EventArgs args) + #endregion + #region EventHandlers + void RtfRawItem_Click(object sender, EventArgs e) => MyStepPanel.SelectedEditItem = this; + private void _MyStepRTB_HeightChanged(object sender, EventArgs args) { if (this.Height != _MyStepRTB.Height + _MyStepRTB.Top + 7) // add in 7 to make it look good // + 10) { @@ -349,13 +294,10 @@ namespace Volian.Controls.Library if (MyStepPanel.DisplayItemChanging) return; MyStepPanel.SelectedEditItem = this; } - #endregion - #region Methods - public override void SetFocus() - { - MyStepRTB.Focus(); - } - public override void SaveContents() + #endregion + #region Methods + public override void SetFocus() => MyStepRTB.Focus(); + public override void SaveContents() { SaveText(); SaveConfig(); @@ -379,26 +321,27 @@ namespace Volian.Controls.Library _origBitmap = GetBitmap(res); MyStepRTB.ClearUndo(); } - catch (Exception ex) + catch (Exception) { - //MessageBox.Show("The data could not be saved.", "Object Save", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } } public System.Drawing.Bitmap GetBitmap(string rtf) { - Bitmap bmap = null; + Bitmap bmap; try { System.Drawing.Size sz = RtfRawItem.GetRtfRawSize(rtf); - Volian.Controls.Library.RTF myRtb = new RTF(); - myRtb.Size = sz; - myRtb.Rtf = rtf; - bmap = new System.Drawing.Bitmap((int)sz.Width, (int)sz.Height); + Volian.Controls.Library.RTF myRtb = new RTF + { + Size = sz, + Rtf = rtf + }; + bmap = new System.Drawing.Bitmap((int)sz.Width, (int)sz.Height); System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmap); myRtb.RenderClipped(gr, new System.Drawing.Rectangle(0, 0, (int)sz.Width, (int)sz.Height)); } - catch (Exception ex) + catch (Exception) { return null; } @@ -478,14 +421,8 @@ namespace Volian.Controls.Library if (MyStepPanel != null && this == MyStepPanel.SelectedEditItem) ScrollToCenter(); } - private void MyStepRTB_CursorKeyPress(object sender, KeyEventArgs args) - { - MyStepPanel.StepCursorKeys(this, args); - } - private void MyStepRTB_CursorMovement(object sender, StepRTBCursorMovementEventArgs args) - { - MyStepPanel.CursorMovement(this, args.CursorLocation, args.Key); - } - #endregion - } + private void MyStepRTB_CursorKeyPress(object sender, KeyEventArgs args) => MyStepPanel.StepCursorKeys(this, args); + private void MyStepRTB_CursorMovement(object sender, StepRTBCursorMovementEventArgs args) => MyStepPanel.CursorMovement(this, args.CursorLocation, args.Key); + #endregion + } } diff --git a/PROMS/Volian.Controls.Library/StepPanel.cs b/PROMS/Volian.Controls.Library/StepPanel.cs index 9b47a403..3d3b848b 100644 --- a/PROMS/Volian.Controls.Library/StepPanel.cs +++ b/PROMS/Volian.Controls.Library/StepPanel.cs @@ -1,12 +1,9 @@ using System; using System.ComponentModel; using System.Collections.Generic; -using System.Diagnostics; -using System.Text; using System.Windows.Forms; using VEPROMS.CSLA.Library; using System.Drawing; -using System.Text.RegularExpressions; using Volian.Base.Library; using JR.Utils.GUI.Forms; using System.Linq; @@ -16,34 +13,19 @@ namespace Volian.Controls.Library public partial class StepPanel : Panel { #region Fields - private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); /// /// Procedure Item Info - Top ItemInfo /// private ItemInfo _MyProcedureItemInfo; - private E_ViewMode _VwMode = E_ViewMode.Edit; - public E_ViewMode VwMode - { - get { return _VwMode; } - set { _VwMode = value; } - } - private EditItem _TopMostEditItem = null; - public EditItem TopMostEditItem - { - get { return _TopMostEditItem; } - set { _TopMostEditItem = value; } - } - private ItemInfo _ExpandingHLS = null; - public ItemInfo ExpandingHLS - { - get { return _ExpandingHLS; } - set { _ExpandingHLS = value; } - } - // TODO: This is not correct. There should be a dictionary of Section Layouts - /// - /// Lookup Table to convert ItemInfo.ItemID to EditItem - /// - internal Dictionary _LookupEditItems; + + public E_ViewMode VwMode { get; set; } = E_ViewMode.Edit; + public EditItem TopMostEditItem { get; set; } = null; + public ItemInfo ExpandingHLS { get; set; } = null; + // TODO: This is not correct. There should be a dictionary of Section Layouts + /// + /// Lookup Table to convert ItemInfo.ItemID to EditItem + /// + internal Dictionary _LookupEditItems; public EditItem FindItem(ItemInfo itemInfo) { if (itemInfo == null) return null; @@ -60,43 +42,26 @@ namespace Volian.Controls.Library _ApplDisplayMode = value; foreach (Control c in Controls) { - EditItem ei = c as EditItem; - if (ei != null) - { - ei.Enabled = ei.MyItemInfo.IsApplicable(value); - //IItemConfig cfg = ei.MyItemInfo.MyConfig as IItemConfig; - //List apples = cfg.MasterSlave_Applicability.GetFlags(); - //if (value == -1 || apples.Count == 0) - // ei.Enabled = true; - //else - // ei.Enabled = apples.Contains(value); - } - } + if (c is EditItem ei) + { + ei.Enabled = ei.MyItemInfo.IsApplicable(value); + } + } } } /// /// Currently selected ItemInfo /// internal ItemInfo _SelectedItemInfo; - private int _ItemMoving = 0; - private StepPanelSettings _MyStepPanelSettings; - private int _MaxRNO = -1; // TODO: Need to calculate MaxRNO on a section basis rather than for a panel + private StepPanelSettings _MyStepPanelSettings; private Font _MyFont = null; - private Font _ProcFont = new Font("Arial", 12, FontStyle.Bold); - private Font _SectFont = new Font("Arial", 10, FontStyle.Bold); - private Font _StepFont = new Font("Arial", 10); - private Color _ActiveColor = Color.SkyBlue; - private Color _InactiveColor = Color.Linen; - private Color _AnnotationColor = Color.FromArgb(255, 255, 128); - private Color _TabColor = Color.Beige; - private Color _PanelColor = Color.LightGray; + private Color _ActiveColor = Color.SkyBlue; + private Color _PanelColor = Color.LightGray; // Whether panel is in view or edit mode. Toggled from steprtb // or set based on approval/multi-user (these two will be done // later. - //public E_ViewMode PanelViewEditMode = E_ViewMode.Edit; internal string _LastAdjust=""; - private bool _ShowLines = true; - private Graphics _MyGraphics = null; + private Graphics _MyGraphics = null; private int _DPI = 0; #endregion #region Item Events @@ -111,8 +76,8 @@ namespace Volian.Controls.Library /// internal void OnItemClick(object sender, StepPanelEventArgs args) { - if (ItemClick != null) ItemClick(sender, args); - } + ItemClick?.Invoke(sender, args); + } public bool ItemSelectionChangeShown = false; // This keeps OnItemSelectedChanged from being called twice when an item is selected. /// /// Occurs when the selected EditItem changes @@ -126,9 +91,9 @@ namespace Volian.Controls.Library internal void OnItemSelectedChanged(object sender, ItemSelectedChangedEventArgs args) { ItemSelectionChangeShown = true;//Remember that you have run already - //vlnStackTrace.ShowStack(string.Format("OnItemSelectedChanged {0}",args.MyItemInfo.ItemID)); - if (ItemSelectedChanged != null) ItemSelectedChanged(sender, args); - } + //vlnStackTrace.ShowStack(string.Format("OnItemSelectedChanged {0}",args.MyItemInfo.ItemID)); + ItemSelectedChanged?.Invoke(sender, args); + } /// /// Occurs when the user clicks on the Attachment Expander /// @@ -143,45 +108,23 @@ namespace Volian.Controls.Library if (AttachmentClicked != null) AttachmentClicked(sender, args); else FlexibleMessageBox.Show(args.MyEditItem.MyItemInfo.MyContent.MyEntry.MyDocument.DocumentTitle, "Unhandled Attachment Click", MessageBoxButtons.OK, MessageBoxIcon.Information); } - - // Edit/View mode change - //public event StepPanelModeChangeEvent ModeChange; - //internal void OnModeChange(object sender, StepRTBModeChangeEventArgs args) - //{ - // PanelViewEditMode = args.ViewMode; - // ModeChange(sender, args); - //} - // various selections from steptabribbon that need to filter up to frmveproms - // such as 'global search', 'bookmarks' public event StepPanelTabDisplayEvent TabDisplay; - internal void OnTabDisplay(object sender, StepPanelTabDisplayEventArgs args) - { - TabDisplay(sender, args); - } - // close section, if deleting word doc section - public event StepPanelWordSectionCloseEvent WordSectionClose; - internal void OnWordSectionClose(object sender, WordSectionEventArgs args) - { - WordSectionClose(sender, args); - } - // if section deleted, have event to flag in other UI panels - public event StepPanelWordSectionDeletedEvent WordSectionDeleted; - internal void OnWordSectionDeleted(object sender, WordSectionEventArgs args) - { - WordSectionDeleted(sender, args); - } - // if item pasted, have event to flag in other UI panels - public event StepPanelItemPastedEvent ItemPasted; - internal void OnItemPasted(object sender, vlnTreeItemInfoPasteEventArgs args) - { - ItemPasted(sender, args); - } - #endregion - #region Link Events - /// - /// Occurs when the user moves onto or off of a Link - /// - public event StepPanelLinkEvent LinkActiveChanged; + internal void OnTabDisplay(object sender, StepPanelTabDisplayEventArgs args) => TabDisplay(sender, args); + // close section, if deleting word doc section + public event StepPanelWordSectionCloseEvent WordSectionClose; + internal void OnWordSectionClose(object sender, WordSectionEventArgs args) => WordSectionClose(sender, args); + // if section deleted, have event to flag in other UI panels + public event StepPanelWordSectionDeletedEvent WordSectionDeleted; + internal void OnWordSectionDeleted(object sender, WordSectionEventArgs args) => WordSectionDeleted(sender, args); + // if item pasted, have event to flag in other UI panels + public event StepPanelItemPastedEvent ItemPasted; + internal void OnItemPasted(object sender, vlnTreeItemInfoPasteEventArgs args) => ItemPasted(sender, args); + #endregion + #region Link Events + /// + /// Occurs when the user moves onto or off of a Link + /// + public event StepPanelLinkEvent LinkActiveChanged; /// /// Checks to see if the 'LinkActiveChanged' event is handled and launches it /// @@ -274,16 +217,15 @@ namespace Volian.Controls.Library this.BackColorChanged += new EventHandler(StepPanel_BackColorChanged); if (VlnSettings.DebugMode) { - _InactiveColor = Color.Linen; - _TabColor = Color.Beige; + InactiveColor = Color.Linen; + TabColor = Color.Beige; _PanelColor = Color.LightGray; - this.Paint += new PaintEventHandler(StepPanel_Paint); this.DoubleClick += new EventHandler(StepPanel_DoubleClick); // Toggles Vertical lines on and off } else { - _InactiveColor = Color.White; - _TabColor = Color.White; + InactiveColor = Color.White; + TabColor = Color.White; _PanelColor = Color.White; this.BackColor = Color.White; } @@ -301,12 +243,11 @@ namespace Volian.Controls.Library InactiveColor = PanelColor = BackColor; foreach (Control ctrl in Controls) { - if (ctrl is EditItem) - { - EditItem ei = (EditItem)ctrl; - ei.BackColor = BackColor; - } - } + if (ctrl is EditItem ei) + { + ei.BackColor = BackColor; + } + } } #endregion #region Private Methods @@ -323,10 +264,9 @@ namespace Volian.Controls.Library if (_LookupEditItems.ContainsKey(id)) // Expanding Parent should have added it to _LookupEditItems { EditItem itm = _LookupEditItems[id]; - ItemInfo ii = myItemInfo.ActiveParent as ItemInfo; - if (itm.Visible == false && ii != null) - ExpandAsNeeded((ItemInfo)myItemInfo.ActiveParent); - itm.AutoExpand(); // Expand it if it should expand + if (!itm.Visible && myItemInfo.ActiveParent is ItemInfo ii) + ExpandAsNeeded(ii); + itm.AutoExpand(); // Expand it if it should expand } } #endregion @@ -342,19 +282,10 @@ namespace Volian.Controls.Library get { return _MyProcedureItemInfo; } set { - //// TIMING: DisplayItem.TimeIt("pMyItem Start"); _MyProcedureItemInfo = value; - //// TIMING: DisplayItem.TimeIt("pMyItem Layout"); - //this.Layout += new LayoutEventHandler(DisplayPanel_Layout); - //this.Scroll += new ScrollEventHandler(DisplayPanel_Scroll); - //// TIMING: DisplayItem.TimeIt("pMyItem Scroll"); Controls.Clear(); _LookupEditItems = new Dictionary(); - //// TIMING: DisplayItem.TimeIt("pMyItem Clear"); - //SuspendLayout(); new RTBItem(_MyProcedureItemInfo, this, null, ChildRelation.None, false); - //ResumeLayout(); - //// TIMING: DisplayItem.TimeIt("pMyItem End"); } } public bool AutoExpand @@ -369,21 +300,19 @@ namespace Volian.Controls.Library } public void Reset() { - ItemInfo parent = SelectedItemInfo.ActiveParent as ItemInfo; - if (parent != null) ItemInfo.ResetParts(parent.ItemID); // Force data to reload - else ItemInfo.ResetParts(SelectedItemInfo.ItemID); - // The following line actually reloads the procedure item - MyProcedureItemInfo = MyProcedureItemInfo; // see get/set above. - Load Procedure and Sections + if (SelectedItemInfo.ActiveParent is ItemInfo parent) ItemInfo.ResetParts(parent.ItemID); // Force data to reload + else ItemInfo.ResetParts(SelectedItemInfo.ItemID); + // The following line actually reloads the procedure item + MyProcedureItemInfo = MyProcedureItemInfo; // see get/set above. - Load Procedure and Sections // The following line expands the items needed to display SelectedItemInfo ExpandAsNeeded(SelectedItemInfo); } public void Reset(ItemInfo myItemInfo) { - ItemInfo parent = myItemInfo.ActiveParent as ItemInfo; - if (parent != null) ItemInfo.ResetParts(parent.ItemID); // Force data to reload - else ItemInfo.ResetParts(myItemInfo.ItemID); - // The following line actually reloads the procedure item - MyProcedureItemInfo = MyProcedureItemInfo; // see get/set above. - Load Procedure and Sections + if (myItemInfo.ActiveParent is ItemInfo parent) ItemInfo.ResetParts(parent.ItemID); // Force data to reload + else ItemInfo.ResetParts(myItemInfo.ItemID); + // The following line actually reloads the procedure item + MyProcedureItemInfo = MyProcedureItemInfo; // see get/set above. - Load Procedure and Sections // The following line expands the items needed to display SelectedItemInfo ExpandAsNeeded(myItemInfo); } @@ -406,16 +335,6 @@ namespace Volian.Controls.Library // The following line expands the items needed to display SelectedItemInfo ExpandAsNeeded(SelectedItemInfo); } - - /// - /// Currently selected StepRTB - /// - //private StepRTB _SelectedStepRTB = null; - //public StepRTB SelectedStepRTB - //{ - // get { return _SelectedStepRTB; } - // set { _SelectedStepRTB=value;} - //} /// /// Gets or Sets the SelectedItemInfo /// Activates and Expands as necessary @@ -435,7 +354,6 @@ namespace Volian.Controls.Library { ExpandAsNeeded(itemInfo); if (_SelectedItemInfo == null) _SelectedItemInfo = itemInfo; - //if (!_LookupEditItems.ContainsKey(itemInfo.ItemID)) Reset(); if (itemInfo.Moving) { Reset(itemInfo); @@ -445,29 +363,24 @@ namespace Volian.Controls.Library if (!_LookupEditItems.ContainsKey(itemInfo.ItemID)) return null; return _LookupEditItems[itemInfo.ItemID]; } - private bool _DisplayItemChanging = false; - public bool DisplayItemChanging - { - get { return _DisplayItemChanging; } - set { _DisplayItemChanging = value; } - } - /// - /// Returns the SelectedEditItem - /// - private EditItem _SelectedEditItem; + + public bool DisplayItemChanging { get; set; } = false; + /// + /// Returns the SelectedEditItem + /// + private EditItem _SelectedEditItem; public EditItem SelectedEditItem { get { return _SelectedEditItem; - //return (_SelectedItemInfo != null) ? _LookupEditItems[_SelectedItemInfo.ItemID] : null; } set { EditItem newFocus = null; // B2018-152 when empty step is deleted, will contain the new step element focus bool deletingParent = false; // B2018-152 used to tell us user clicked on subtep of step element who's text was removed (special case) EditItem lastEI = _SelectedEditItem; - if (value != null) value.SetActive(); // Set the active color + value?.SetActive(); // Set the active color if (lastEI == value) return; // Same - No Change // B2018-002 - Invalid Transitions - If the current step contains an invalid transition convert it to text if(value != null) ItemInfo.ConvertInvalidTransitionsToText(value.MyItemInfo); @@ -486,16 +399,16 @@ namespace Volian.Controls.Library string msg3 = "Select NO to keep the empty step which can be restored via the History tab on the Step Properties panel."; if (value != null && value.MyItemInfo.HasAncestor(lastEI.MyItemInfo)) { - msg1 = "This step does not have text but you had selected one of its substeps. " + msg1; - msg2 = msg2 + " including the substep you had selected. You will be placed at the next location."; + msg1 = $"This step does not have text but you had selected one of its substeps. {msg1}"; + msg2 += " including the substep you had selected. You will be placed at the next location."; deletingParent = true; // B2018-152 this will tell us that the user selected a substep of a parent being deleted } else { - msg1 = "This step does not have text but has substeps. " + msg1; - msg2 = msg2 + " and its substeps."; + msg1 = $"This step does not have text but has substeps. {msg1}"; + msg2 += " and its substeps."; } - DialogResult result = FlexibleMessageBox.Show(msg1 + "\n\n" + msg2 + "\n\n" + msg3, "Verify Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question); + DialogResult result = FlexibleMessageBox.Show($"{msg1}\n\n{msg2}\n\n{msg3}", "Verify Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.No) shouldDelete = false; } } @@ -504,23 +417,21 @@ namespace Volian.Controls.Library // if this item has enhanced edititems, remove them. Note that this code supports // deleting text in an rtbitem that may be a step or section level. EnhancedDocuments eds = null; - StepConfig sc = lastEI.MyItemInfo.MyConfig as StepConfig; - if (sc != null) eds = sc.MyEnhancedDocuments; - else - { - // if a section, just the title or all contents may be linked. If just title, - // don't delete enhanced, but clear links back from enhanced. - if (lastEI.MyItemInfo.IsSection) - { - SectionConfig sec = lastEI.MyItemInfo.MyConfig as SectionConfig; - if (sec != null) - { - if (sec.Section_LnkEnh == "Y") eds = sec.MyEnhancedDocuments; - else lastEI.MyItemInfo.ClearEnhancedSectionLink(); - } - } - } - List enhIds = new List(); + if (lastEI.MyItemInfo.MyConfig is StepConfig sc) eds = sc.MyEnhancedDocuments; + else + { + // if a section, just the title or all contents may be linked. If just title, + // don't delete enhanced, but clear links back from enhanced. + if (lastEI.MyItemInfo.IsSection) + { + if (lastEI.MyItemInfo.MyConfig is SectionConfig sec) + { + if (sec.Section_LnkEnh == "Y") eds = sec.MyEnhancedDocuments; + else lastEI.MyItemInfo.ClearEnhancedSectionLink(); + } + } + } + List enhIds = new List(); if (eds != null) { foreach (EnhancedDocument ed in eds) @@ -593,8 +504,7 @@ namespace Volian.Controls.Library SelectedItemInfo = value.MyItemInfo; } } - if (lastEI != null) - lastEI.IdentifyMe(false); + lastEI?.IdentifyMe(false); } } /// @@ -608,24 +518,17 @@ namespace Volian.Controls.Library OnItemSelectedChanged(this, new ItemSelectedChangedEventArgs(SelectedEditItem)); } } - public new void MouseWheel(MouseEventArgs e) - { - base.OnMouseWheel(e); - } - /// - /// Used to track movement other than scrolling - /// 0 - Indicates no other movement - /// > 0 - Indicates that other movement is happening - /// - public int ItemMoving - { - get { return _ItemMoving; } - set { _ItemMoving = value; } - } - /// - /// Lazy loaded StepPanelSettings - /// - public StepPanelSettings MyStepPanelSettings + public new void MouseWheel(MouseEventArgs e) => base.OnMouseWheel(e); + /// + /// Used to track movement other than scrolling + /// 0 - Indicates no other movement + /// > 0 - Indicates that other movement is happening + /// + public int ItemMoving { get; set; } = 0; + /// + /// Lazy loaded StepPanelSettings + /// + public StepPanelSettings MyStepPanelSettings { get { @@ -640,36 +543,24 @@ namespace Volian.Controls.Library public Font MyFont { get { return _MyFont; } - set { _ProcFont = _SectFont = _StepFont = _MyFont = value; } + set { ProcFont = SectFont = StepFont = _MyFont = value; } } - /// - /// Gets or sets the font for the Procedure Text - /// - public Font ProcFont - { - get { return _ProcFont; } - set { _ProcFont = value; } - } - /// - /// Gets or sets the font for the Section Text - /// - public Font SectFont - { - get { return _SectFont; } - set { _SectFont = value; } - } - /// - /// Gets or sets the Step Font - /// - public Font StepFont - { - get { return _StepFont; } - set { _StepFont = value; } - } - /// - /// Gets or Sets the Active Color for the Panel - /// - public Color ActiveColor + /// + /// Gets or sets the font for the Procedure Text + /// + public Font ProcFont { get; set; } = new Font("Arial", 12, FontStyle.Bold); + /// + /// Gets or sets the font for the Section Text + /// + public Font SectFont { get; set; } = new Font("Arial", 10, FontStyle.Bold); + /// + /// Gets or sets the Step Font + /// + public Font StepFont { get; set; } = new Font("Arial", 10); + /// + /// Gets or Sets the Active Color for the Panel + /// + public Color ActiveColor { get { // C2015-028 Add Editorial Mode to PROMS Step Editor @@ -679,34 +570,22 @@ namespace Volian.Controls.Library } set { _ActiveColor = value; } } - /// - /// Gets or Sets the Annotation backcolor for StepRTBs in the Panel - /// - public Color AnnotationColor - { - get { return _AnnotationColor; } - set { _AnnotationColor = value; } - } - /// - /// Gets or sets the InActive Color for the Panel - /// - public Color InactiveColor - { - get { return _InactiveColor; } - set { _InactiveColor = value; } - } - /// - /// Gets or sets the Tab Color - /// - public Color TabColor - { - get { return _TabColor; } - set { _TabColor = value; } - } - /// - /// Gets or sets the Panel Color - /// - public Color PanelColor + /// + /// Gets or Sets the Annotation backcolor for StepRTBs in the Panel + /// + public Color AnnotationColor { get; set; } = Color.FromArgb(255, 255, 128); + /// + /// Gets or sets the InActive Color for the Panel + /// + public Color InactiveColor { get; set; } = Color.Linen; + /// + /// Gets or sets the Tab Color + /// + public Color TabColor { get; set; } = Color.Beige; + /// + /// Gets or sets the Panel Color + /// + public Color PanelColor { get { return _PanelColor; } set { _PanelColor = value; @@ -739,70 +618,42 @@ namespace Volian.Controls.Library return _DPI; } } - /// - /// Converts an integer value from Twips to Pixels - /// - /// - /// - public int ToDisplay(int value) - { - //return (DPI * value) / 864; - return (DPI * value) / 72; - } - public int ToDisplay(float? value) - { - //return (DPI * value) / 864; - return (int)(DPI * (value??0)) / 72; - } - /// - /// Converts an integer? value from Twips to Pixels - /// - /// - /// - public int ToDisplay(int? value) - { - return ToDisplay((int)value); - } - /// - /// Converts an string value from Twips to Pixels - /// - /// - /// - public int ToDisplay(string value) - { - return ToDisplay(Convert.ToSingle(value)); - } - /// - /// Converts a value from a list in a string from Twips to Pixels - /// - /// - /// - public int ToDisplay(string value,int i) + /// + /// Converts an integer value from Twips to Pixels + /// + /// + /// + public int ToDisplay(int value) => (DPI * value) / 72; + public int ToDisplay(float? value) => (int)(DPI * (value ?? 0)) / 72; + /// + /// Converts an integer? value from Twips to Pixels + /// + /// + /// + public int ToDisplay(int? value) => ToDisplay((int)value); + /// + /// Converts an string value from Twips to Pixels + /// + /// + /// + public int ToDisplay(string value) => ToDisplay(Convert.ToSingle(value)); + /// + /// Converts a value from a list in a string from Twips to Pixels + /// + /// + /// + public int ToDisplay(string value,int i) { if (i < 0) return 0; string s = value.Split(",".ToCharArray())[i]; return ToDisplay(s); } - #endregion - #region Debug Methods - /// - /// Gets or sets ShowLines so that vertical lines are shown for debugging purposes - /// - public bool ShowLines - { - get { return _ShowLines; } - set { _ShowLines = value; } - } - /// - /// Draw a vertical line - /// - /// - /// - private void VerticalLine(Graphics g, int x) - { - Pen bluePen = new Pen(Color.CornflowerBlue,1); - g.DrawLine(bluePen, x, 0, x, this.Height); - } + #endregion + #region Debug Methods + /// + /// Gets or sets ShowLines so that vertical lines are shown for debugging purposes + /// + public bool ShowLines { get; set; } = true; /// /// Toggle the vertical lines on and off /// @@ -813,38 +664,6 @@ namespace Volian.Controls.Library ShowLines = !ShowLines; Refresh(); } - private void StepPanel_Paint(object sender, PaintEventArgs e) - { - if (ShowLines) - { - //int fifth = Height / 5; - //Rectangle r1 = new Rectangle(0, 0, Width, Height - fifth); - ////Brush b = new System.Drawing.Drawing2D.LinearGradientBrush(r1, Color.FromArgb(128, 0, 32), Color.FromArgb(96, 0, 16), 90); - //Brush b = new System.Drawing.Drawing2D.LinearGradientBrush(r1, Color.FromArgb(255,128, 0, 32), Color.FromArgb(255,96, 0, 16),System.Drawing.Drawing2D.LinearGradientMode.Vertical); - //e.Graphics.FillRectangle(b, r1); - //r1 = new Rectangle(0, Height - fifth, Width, fifth); - //b = new System.Drawing.Drawing2D.LinearGradientBrush(r1, Color.FromArgb(255,96, 0, 16), Color.FromArgb(255,128, 0, 32), 90); - //e.Graphics.FillRectangle(b, r1); - //VerticalLine(e.Graphics, 60); - //VerticalLine(e.Graphics, 102); - //VerticalLine(e.Graphics, 415); - } - } - /// - /// Output all of the EditItem controls to the log - /// - private void ListControls() - { - // Walk through the controls and find the next control for each - if(_MyLog.IsInfoEnabled)_MyLog.InfoFormat("'Item','Next'"); - foreach (Control control in Controls) - if (control is EditItem) - { - EditItem ei = (EditItem)control; - EditItem nxt = ei.NextDownEditItem; - if(_MyLog.IsInfoEnabled)_MyLog.InfoFormat("{0},{1}", ei.MyID, nxt == null ? 0 : nxt.MyID); - } - } #endregion #region Cursor Movement Methods /// @@ -873,14 +692,16 @@ namespace Volian.Controls.Library if (ii.Tables != null && ii.Tables.Count > 0) return BottomPart(ii.Tables[0].LastSibling); return ii; } - /// - /// Supports cursor movement between richtext boxes, including arrow keys/page up,down/ - /// ctrl Home,End - /// - /// StepRTB - /// Point - /// E_ArrowKeys - public void CursorMovement(EditItem ei, Point position, E_ArrowKeys arrow) + /// + /// Supports cursor movement between richtext boxes, including arrow keys/page up,down/ + /// ctrl Home,End + /// + /// StepRTB + /// Point + /// E_ArrowKeys + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0059:Unnecessary assignment of a value", Justification = "Values assigned to ItemInfo ii for Debugging")] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Point position kept for consistancy")] + public void CursorMovement(EditItem ei, Point position, E_ArrowKeys arrow) { ItemInfo ii = null; // The following lines are debug to check that the results of moving down and moving up are the same @@ -907,11 +728,8 @@ namespace Volian.Controls.Library ii = MoveDown(ei, ii); break; case E_ArrowKeys.Left: - //case E_ArrowKeys.CtrlLeft: if (!ei.MyItemInfo.IsProcedure) { - EditItem tmpEI = null; - //SelectedEditItem = _LookupEditItems[ei.MyItemInfo.MyParent.ItemID]; ii = ArrowUp(ei.MyItemInfo); if (ii != null) { @@ -948,7 +766,8 @@ namespace Volian.Controls.Library return tmpEI.MyItemInfo; } - private ItemInfo MoveDown(EditItem ei, ItemInfo ii) + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "ItemInfo ii Kept for Debugging")] + private ItemInfo MoveDown(EditItem ei, ItemInfo ii) { ii = ArrowDown(ei.MyItemInfo); // The following lines are debug to check that the results of moving down and moving up are the same @@ -984,11 +803,8 @@ namespace Volian.Controls.Library if (!ii.IsProcedure) return (ii.MyParent); return null; } - private ItemInfo ArrowDown(ItemInfo ii) - { - return ArrowDown(ii, true, true); - } - private ItemInfo ArrowDown(ItemInfo ii, bool lookAtSub, bool lookAtRNO) + private ItemInfo ArrowDown(ItemInfo ii) => ArrowDown(ii, true, true); + private ItemInfo ArrowDown(ItemInfo ii, bool lookAtSub, bool lookAtRNO) { if (ii.IsSection || ii.IsProcedure) { @@ -1062,28 +878,20 @@ namespace Volian.Controls.Library [TypeConverter(typeof(ExpandableObjectConverter))] public partial class StepPanelSettings { - private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - public StepPanelSettings(StepPanel panel) - { - _MyStepPanel = panel; - } - public StepPanelSettings() + public StepPanelSettings(StepPanel panel) => MyStepPanel = panel; + public StepPanelSettings() { } - private StepPanel _MyStepPanel; - [Browsable(false)] - public StepPanel MyStepPanel - { - get { return _MyStepPanel; } - set { _MyStepPanel = value; } - } - private float _CircleXOffset = -4; + + [Browsable(false)] + public StepPanel MyStepPanel { get; set; } + private float _CircleXOffset = -4; [Category("Circle")] [DisplayName("Circle Horizontal Offset")] public float CircleXOffset { get { return _CircleXOffset; } - set { _CircleXOffset = value; if (_MyStepPanel != null) _MyStepPanel.Refresh(); } + set { _CircleXOffset = value; MyStepPanel?.Refresh(); } } private float _CircleYOffset = -13; [Category("Circle")] @@ -1091,24 +899,15 @@ namespace Volian.Controls.Library public float CircleYOffset { get { return _CircleYOffset; } - set { _CircleYOffset = value; if (_MyStepPanel != null) _MyStepPanel.Refresh(); } + set { _CircleYOffset = value; MyStepPanel?.Refresh(); } } - // Appears to not be used - JSJ - 11-13-2017 - //private Font _CircleFont = new Font("Arial Unicode MS", 23); - //[Category("Circle")] - //[DisplayName("Circle Font")] - //public Font CircleFont - //{ - // get { return _CircleFont; } - // set { _CircleFont = value; if(_MyStepPanel != null) _MyStepPanel.Refresh(); } - //} private Color _CircleColor = Color.Black; [Category("Circle")] [DisplayName("Circle Color")] public Color CircleColor { get { return _CircleColor; } - set { _CircleColor = value; if (_MyStepPanel != null) _MyStepPanel.Refresh(); } + set { _CircleColor = value; MyStepPanel?.Refresh(); } } private int _CircleDiameter = 25; [Category("Circle")] @@ -1116,7 +915,7 @@ namespace Volian.Controls.Library public int CircleDiameter { get { return _CircleDiameter; } - set { _CircleDiameter = value; if (_MyStepPanel != null) _MyStepPanel.Refresh(); } + set { _CircleDiameter = value; MyStepPanel?.Refresh(); } } private int _CircleWeight = 2; [Category("Circle")] @@ -1124,7 +923,7 @@ namespace Volian.Controls.Library public int CircleWeight { get { return _CircleWeight; } - set { _CircleWeight = value; if (_MyStepPanel != null) _MyStepPanel.Refresh(); } + set { _CircleWeight = value; MyStepPanel?.Refresh(); } } private float _NumberLocationX = 20F; [Category("Number")] @@ -1132,7 +931,7 @@ namespace Volian.Controls.Library public float NumberLocationX { get { return _NumberLocationX; } - set { _NumberLocationX = value; if (_MyStepPanel != null) _MyStepPanel.Refresh(); } + set { _NumberLocationX = value; MyStepPanel?.Refresh(); } } private float _NumberLocationY = 4; [Category("Number")] @@ -1140,7 +939,7 @@ namespace Volian.Controls.Library public float NumberLocationY { get { return _NumberLocationY; } - set { _NumberLocationY = value; if (_MyStepPanel != null) _MyStepPanel.Refresh(); } + set { _NumberLocationY = value; MyStepPanel?.Refresh(); } } private SizeF _NumberSize = new SizeF(200F, 23F); [Category("Number")] @@ -1148,7 +947,7 @@ namespace Volian.Controls.Library public SizeF NumberSize { get { return _NumberSize; } - set { _NumberSize = value; if (_MyStepPanel != null) _MyStepPanel.Refresh(); } + set { _NumberSize = value; MyStepPanel?.Refresh(); } } private int _TableWidthAdjust = 4; [Category("Table")] @@ -1156,7 +955,7 @@ namespace Volian.Controls.Library public int TableWidthAdjust { get { return _TableWidthAdjust; } - set { _TableWidthAdjust = value; if (_MyStepPanel != null) _MyStepPanel.Refresh(); } + set { _TableWidthAdjust = value; MyStepPanel?.Refresh(); } } private int _CheckOffWeight = 1; [Category("CheckOff")] @@ -1164,7 +963,7 @@ namespace Volian.Controls.Library public int CheckOffWeight { get { return _CheckOffWeight; } - set { _CheckOffWeight = value; if (_MyStepPanel != null) _MyStepPanel.Refresh(); } + set { _CheckOffWeight = value; MyStepPanel?.Refresh(); } } private Color _CheckOffColor = Color.Black; [Category("CheckOff")] @@ -1172,7 +971,7 @@ namespace Volian.Controls.Library public Color CheckOffColor { get { return _CheckOffColor; } - set { _CheckOffColor = value; if (_MyStepPanel != null) _MyStepPanel.Refresh(); } + set { _CheckOffColor = value; MyStepPanel?.Refresh(); } } private int _CheckOffSize =12; [Category("CheckOff")] @@ -1180,7 +979,7 @@ namespace Volian.Controls.Library public int CheckOffSize { get { return _CheckOffSize; } - set { _CheckOffSize = value; if (_MyStepPanel != null) _MyStepPanel.Refresh(); } + set { _CheckOffSize = value; MyStepPanel?.Refresh(); } } private int _CheckOffX =0; [Category("CheckOff")] @@ -1188,7 +987,7 @@ namespace Volian.Controls.Library public int CheckOffX { get { return _CheckOffX; } - set { _CheckOffX = value; if (_MyStepPanel != null) _MyStepPanel.Refresh(); } + set { _CheckOffX = value; MyStepPanel?.Refresh(); } } private int _CheckOffY =5; [Category("CheckOff")] @@ -1196,7 +995,7 @@ namespace Volian.Controls.Library public int CheckOffY { get { return _CheckOffY; } - set { _CheckOffY = value; if (_MyStepPanel != null) _MyStepPanel.Refresh(); } + set { _CheckOffY = value; MyStepPanel?.Refresh(); } } private int _ChangeBarWeight = 1; @@ -1205,7 +1004,7 @@ namespace Volian.Controls.Library public int ChangeBarWeight { get { return _ChangeBarWeight; } - set { _ChangeBarWeight = value; if (_MyStepPanel != null) _MyStepPanel.Refresh(); } + set { _ChangeBarWeight = value; MyStepPanel?.Refresh(); } } private Color _ChangeBarColor = Color.Black; [Category("ChangeBar")] @@ -1213,116 +1012,65 @@ namespace Volian.Controls.Library public Color ChangeBarColor { get { return _ChangeBarColor; } - set { _ChangeBarColor = value; if (_MyStepPanel != null) _MyStepPanel.Refresh(); } + set { _ChangeBarColor = value; MyStepPanel?.Refresh(); } } } public partial class StepPanelEventArgs { - private EditItem _MyEditItem; - public EditItem MyEditItem - { - get { return _MyEditItem; } - set { _MyEditItem = value; } - } - private MouseEventArgs _MyMouseEventArgs; - public MouseEventArgs MyMouseEventArgs - { - get { return _MyMouseEventArgs; } - set { _MyMouseEventArgs = value; } - } + public EditItem MyEditItem { get; set; } + public MouseEventArgs MyMouseEventArgs { get; set; } - public StepPanelEventArgs(EditItem myEditItem, MouseEventArgs myMouseEventArgs) + public StepPanelEventArgs(EditItem myEditItem, MouseEventArgs myMouseEventArgs) { - _MyEditItem = myEditItem; - _MyMouseEventArgs = myMouseEventArgs; + MyEditItem = myEditItem; + MyMouseEventArgs = myMouseEventArgs; } } public partial class ItemSelectedChangedEventArgs { - private ItemInfo _MyItemInfo; - public ItemInfo MyItemInfo + public ItemInfo MyItemInfo { get; set; } + public EditItem MyEditItem { get; set; } = null; + public ItemSelectedChangedEventArgs(ItemInfo myItemInfo) { - get { return _MyItemInfo; } - set { _MyItemInfo = value; } - } - private EditItem _MyEditItem = null; - public EditItem MyEditItem - { - get { return _MyEditItem; } - set { _MyEditItem = value; } - } - public ItemSelectedChangedEventArgs(ItemInfo myItemInfo) - { - _MyItemInfo = myItemInfo; + MyItemInfo = myItemInfo; } public ItemSelectedChangedEventArgs(EditItem myEditItem) { - _MyItemInfo = myEditItem?.MyItemInfo; - _MyEditItem = myEditItem; + MyItemInfo = myEditItem?.MyItemInfo; + MyEditItem = myEditItem; } } public partial class StepPanelAttachmentEventArgs { - private EditItem _MyEditItem; - public EditItem MyEditItem + public EditItem MyEditItem { get; set; } + public StepPanelAttachmentEventArgs(EditItem myEditItem) { - get { return _MyEditItem; } - set { _MyEditItem = value; } - } - public StepPanelAttachmentEventArgs(EditItem myEditItem) - { - _MyEditItem = myEditItem; + MyEditItem = myEditItem; } } public partial class StepPanelLinkEventArgs : EventArgs { - private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - //private EditItem _LinkedEditItem; - //public EditItem LinkedEditItem - //{ - // get { return _LinkedEditItem; } - //} - private string _LinkInfoText; - public string LinkInfoText + public string LinkInfoText { get; } + public LinkText MyLinkText { get; } + public StepPanelLinkEventArgs(string linkInfoText) { - get { return _LinkInfoText; } - } - private LinkText _MyLinkText; - public LinkText MyLinkText - { - get { return _MyLinkText;} - } - public StepPanelLinkEventArgs(string linkInfoText) - { - //_LinkedEditItem = linkedEditItem; - _LinkInfoText = linkInfoText; - _MyLinkText = new LinkText(_LinkInfoText); - //if(_MyLog.IsInfoEnabled)_MyLog.InfoFormat("\r\n LinkInfo '{0}'\r\n", linkInfo.LinkText); + LinkInfoText = linkInfoText; + MyLinkText = new LinkText(LinkInfoText); + //for Debugging: linkInfo.LinkText } } public partial class StepPanelTabDisplayEventArgs : EventArgs { - private string _PanelTabName; - public string PanelTabName - { - get { return _PanelTabName; } - } - public StepPanelTabDisplayEventArgs(string panelTabname) - { - _PanelTabName = panelTabname; - } - } + public string PanelTabName { get; } + public StepPanelTabDisplayEventArgs(string panelTabname) => PanelTabName = panelTabname; + } public partial class WordSectionEventArgs : EventArgs { - private SectionInfo _MySectionInfo; - public SectionInfo MySectionInfo + public SectionInfo MySectionInfo { get; } + public WordSectionEventArgs(SectionInfo mySectionInfo) { - get { return _MySectionInfo; } - } - public WordSectionEventArgs(SectionInfo mySectionInfo) - { - _MySectionInfo = mySectionInfo; + MySectionInfo = mySectionInfo; } } public delegate void StepPanelEvent(object sender, StepPanelEventArgs args); diff --git a/PROMS/Volian.Controls.Library/StepRTB.cs b/PROMS/Volian.Controls.Library/StepRTB.cs index 5728cf6e..b2c26fd5 100644 --- a/PROMS/Volian.Controls.Library/StepRTB.cs +++ b/PROMS/Volian.Controls.Library/StepRTB.cs @@ -3,10 +3,8 @@ using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Drawing; -using System.Data; using System.Text; using System.Windows.Forms; -using System.Runtime.InteropServices; using System.Text.RegularExpressions; using VEPROMS.CSLA.Library; using Volian.Base.Library; @@ -29,189 +27,84 @@ namespace Volian.Controls.Library { private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - private bool _Disposed = false; - 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; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private bool _Disposed = false; private bool _Finalized = false; ~StepRTB() { - if (!_Finalized) _CountFinalized++; _Finalized = true; } #region Events public event StepRTBRoEvent RoInsert; - public void OnRoInsert(object sender, StepRTBRoEventArgs args) - { - if (RoInsert != null) RoInsert(sender, args); - } - public event StepRTBEvent ReturnToEditor; - public void OnReturnToEditor(object sender, EventArgs args) - { - if (ReturnToEditor != null) ReturnToEditor(sender, args); - } - public event StepRTBEvent EditModeChanged; - public void OnEditModeChanged(object sender, EventArgs args) - { - if (EditModeChanged != null) EditModeChanged(sender, args); - } - public event StepRTBEvent DoSaveContents; - public void OnDoSaveContents(object sender, EventArgs args) - { - if (DoSaveContents != null) DoSaveContents(sender, args); - } - public event StepRTBMouseEvent DoMouseWheel; - public void OnDoMouseWheel(object sender, MouseEventArgs args) - { - if (DoMouseWheel != null) DoMouseWheel(sender, args); - } - public event StepRTBLocationEvent OpenContextMenu; - public void OnOpenContextMenu(object sender, StepRTBLocationEventArgs args) - { - if (OpenContextMenu != null) OpenContextMenu(sender, args); - } - public event StepRTBEvent CopyStep; - public void OnCopyStep(object sender, EventArgs args) - { - if (CopyStep != null) CopyStep(sender, args); - } - public event StepRTBBooleanEvent CheckClipboard; + public void OnRoInsert(object sender, StepRTBRoEventArgs args) => RoInsert?.Invoke(sender, args); + public event StepRTBEvent ReturnToEditor; + public void OnReturnToEditor(object sender, EventArgs args) => ReturnToEditor?.Invoke(sender, args); + public event StepRTBEvent EditModeChanged; + public void OnEditModeChanged(object sender, EventArgs args) => EditModeChanged?.Invoke(sender, args); + public event StepRTBEvent DoSaveContents; + public void OnDoSaveContents(object sender, EventArgs args) => DoSaveContents?.Invoke(sender, args); + public event StepRTBMouseEvent DoMouseWheel; + public void OnDoMouseWheel(object sender, MouseEventArgs args) => DoMouseWheel?.Invoke(sender, args); + public event StepRTBLocationEvent OpenContextMenu; + public void OnOpenContextMenu(object sender, StepRTBLocationEventArgs args) => OpenContextMenu?.Invoke(sender, args); + public event StepRTBEvent CopyStep; + public void OnCopyStep(object sender, EventArgs args) => CopyStep?.Invoke(sender, args); + public event StepRTBBooleanEvent CheckClipboard; public bool OnCheckClipboard(object sender, EventArgs args) { if (CheckClipboard != null) return CheckClipboard(sender, args); return false; } public event StepRTBCursorKeysEvent EnterKeyPressed; - public void OnEnterKeyPressed(object sender, KeyEventArgs args) - { - if (EnterKeyPressed != null) EnterKeyPressed(sender, args); - } - public event StepRTBEvent ToggleChangeBar; // shortcut key - public void OnToggleChangeBar(object sender, EventArgs args) - { - if (ToggleChangeBar != null) ToggleChangeBar(sender, args); - } - public event StepRTBEvent ToggleContinuousActionSummary; // shortcut key - public void OnToggleContinuousActionSummary(object sender, EventArgs args) - { - if (ToggleContinuousActionSummary != null) ToggleContinuousActionSummary(sender, args); - } - public event StepRTBEvent TogglePlaceKeeper; // shortcut key - public void OnTogglePlaceKeeper(object sender, EventArgs args) - { - if (TogglePlaceKeeper != null) TogglePlaceKeeper(sender, args); - } - public event StepRTBEvent TogglePlaceKeeperContAct; // shortcut key - public void OnTogglePlaceKeeperContAct(object sender, EventArgs args) - { - if (TogglePlaceKeeperContAct != null) TogglePlaceKeeperContAct(sender, args); - } - public event StepRTBEvent ToggleSuperScript; // shortcut key <=> - public void OnToggleSuperScript(object sender, EventArgs args) - { - if (ToggleSuperScript != null) ToggleSuperScript(sender, args); - } - public event StepRTBEvent ToggleSubScript; // shortcut key <=> - public void OnToggleSubScript(object sender, EventArgs args) - { - if (ToggleSubScript != null) ToggleSubScript(sender, args); - } - public event StepRTBEvent InsertPgBrk; // short key - public void OnInsertPgBrk(object sender, EventArgs args) - { - if (InsertPgBrk != null) InsertPgBrk(sender, args); - } - public event StepRTBEvent OpenAnnotations; - public void OnOpenAnnotations(object sender, EventArgs args) - { - if (OpenAnnotations != null) OpenAnnotations(sender, args); - } - public event StepRTBBooleanEvent IsNotCurrentSelection; + public void OnEnterKeyPressed(object sender, KeyEventArgs args) => EnterKeyPressed?.Invoke(sender, args); + public event StepRTBEvent ToggleChangeBar; // shortcut key + public void OnToggleChangeBar(object sender, EventArgs args) => ToggleChangeBar?.Invoke(sender, args); + public event StepRTBEvent ToggleContinuousActionSummary; // shortcut key + public void OnToggleContinuousActionSummary(object sender, EventArgs args) => ToggleContinuousActionSummary?.Invoke(sender, args); + public event StepRTBEvent TogglePlaceKeeper; // shortcut key + public void OnTogglePlaceKeeper(object sender, EventArgs args) => TogglePlaceKeeper?.Invoke(sender, args); + public event StepRTBEvent TogglePlaceKeeperContAct; // shortcut key + public void OnTogglePlaceKeeperContAct(object sender, EventArgs args) => TogglePlaceKeeperContAct?.Invoke(sender, args); + public event StepRTBEvent ToggleSuperScript; // shortcut key <=> + public void OnToggleSuperScript(object sender, EventArgs args) => ToggleSuperScript?.Invoke(sender, args); + public event StepRTBEvent ToggleSubScript; // shortcut key <=> + public void OnToggleSubScript(object sender, EventArgs args) => ToggleSubScript?.Invoke(sender, args); + public event StepRTBEvent InsertPgBrk; // short key + public void OnInsertPgBrk(object sender, EventArgs args) => InsertPgBrk?.Invoke(sender, args); + public event StepRTBEvent OpenAnnotations; + public void OnOpenAnnotations(object sender, EventArgs args) => OpenAnnotations?.Invoke(sender, args); + public event StepRTBBooleanEvent IsNotCurrentSelection; public bool OnIsNotCurrentSelection(object sender, EventArgs args) { if (IsNotCurrentSelection != null) return IsNotCurrentSelection(sender, args); return false; } public event StepRTBTableWidthEvent AdjustTableWidth; - public void OnAdjustTableWidth(object sender, StepRTBTableWidthEventArgs args) - { - if (AdjustTableWidth != null) AdjustTableWidth(sender, args); - } - public event StepRTBMenuEvent SetMenu; - private void OnSetMenu(object sender, StepRTBMenuEventArgs args) - { - if (SetMenu != null) SetMenu(sender, args); - } - public event StepRTBEvent RTBSelectionChanged; - private void OnRTBSelectionChanged(object sender, EventArgs args) - { - if (RTBSelectionChanged != null) RTBSelectionChanged(sender, args); - } - public event StepRTBEvent LinkLocationsChanged; - private void OnLinkLocationChanged(object sender, EventArgs args) - { - if (LinkLocationsChanged != null) LinkLocationsChanged(sender, args); - } - public event StepRTBEvent RTBRangeStatusChanged; - private void OnRTBRangeStatusChanged(object sender, EventArgs args) - { - if (RTBRangeStatusChanged != null) RTBRangeStatusChanged(sender, args); - } - public event StepRTBCursorKeysEvent CursorKeyPress; - private void OnCursorKeyPress(object sender, KeyEventArgs args) - { - if (CursorKeyPress != null) CursorKeyPress(sender, args); - } - public event StepRTBCursorMovementEvent CursorMovement; - private void OnCursorMovement(object sender, StepRTBCursorMovementEventArgs args) - { - if (CursorMovement != null) CursorMovement(sender, args); - } + public void OnAdjustTableWidth(object sender, StepRTBTableWidthEventArgs args) => AdjustTableWidth?.Invoke(sender, args); + public event StepRTBMenuEvent SetMenu; + private void OnSetMenu(object sender, StepRTBMenuEventArgs args) => SetMenu?.Invoke(sender, args); + public event StepRTBEvent RTBSelectionChanged; + private void OnRTBSelectionChanged(object sender, EventArgs args) => RTBSelectionChanged?.Invoke(sender, args); + public event StepRTBEvent LinkLocationsChanged; + private void OnLinkLocationChanged(object sender, EventArgs args) => LinkLocationsChanged?.Invoke(sender, args); + public event StepRTBEvent RTBRangeStatusChanged; + private void OnRTBRangeStatusChanged(object sender, EventArgs args) => RTBRangeStatusChanged?.Invoke(sender, args); + public event StepRTBCursorKeysEvent CursorKeyPress; + private void OnCursorKeyPress(object sender, KeyEventArgs args) => CursorKeyPress?.Invoke(sender, args); + public event StepRTBCursorMovementEvent CursorMovement; + private void OnCursorMovement(object sender, StepRTBCursorMovementEventArgs args) => CursorMovement?.Invoke(sender, args); - /// - /// This event is not raised during all the in-between changes for link deletions - /// - public event StepRTBEvent RTBTextChanged; - private void OnRTBTextChanged(object sender, EventArgs args) - { - if (RTBTextChanged != null) RTBTextChanged(sender, args); - } - #endregion - #region Properties and Variables - public bool IsRoFigure - { - get { return (MyItemInfo.IsFigure && MyItemInfo.MyContent.MyImage == null); } - } - public bool IsRoTable - { - get { return (Parent is VlnFlexGrid && (Parent as VlnFlexGrid).IsRoTable); } - } - public bool HasVScroll - { - get - { - return RTBAPI.HasVertScroll(this); - } - - } - public bool HasHScroll - { - get - { - return RTBAPI.HasHorzScroll(this); - } - - } - private bool _EditMode = true; + /// + /// This event is not raised during all the in-between changes for link deletions + /// + public event StepRTBEvent RTBTextChanged; + private void OnRTBTextChanged(object sender, EventArgs args) => RTBTextChanged?.Invoke(sender, args); + #endregion + #region Properties and Variables + public bool IsRoFigure => MyItemInfo.IsFigure && MyItemInfo.MyContent.MyImage == null; + public bool IsRoTable => Parent is VlnFlexGrid && (Parent as VlnFlexGrid).IsRoTable; + public bool HasVScroll => RTBAPI.HasVertScroll(this); + public bool HasHScroll => RTBAPI.HasHorzScroll(this); + private bool _EditMode = true; /// /// Allows insert of links. If false, don't allow selection of links. /// @@ -230,22 +123,16 @@ namespace Volian.Controls.Library { get { - ItemInfo procInfo = _MyItemInfo.MyProcedure as ItemInfo; - if (procInfo == null) - _MyDVI = null; - else - _MyDVI = procInfo.ActiveParent as DocVersionInfo; - return _MyDVI; + if (!(_MyItemInfo.MyProcedure is ItemInfo procInfo)) + _MyDVI = null; + else + _MyDVI = procInfo.ActiveParent as DocVersionInfo; + return _MyDVI; } } - private static UserInfo _MyUserInfo = null; - public static UserInfo MyUserInfo - { - get { return _MyUserInfo; } - set { _MyUserInfo = value; } - } - private static string _MySymbolFontName; + public static UserInfo MyUserInfo { get; set; } = null; + private static string _MySymbolFontName; public static string MySymbolFontName { get { return StepRTB._MySymbolFontName; } @@ -279,13 +166,9 @@ namespace Volian.Controls.Library } } } - private E_FieldToEdit _FieldToEdit = E_FieldToEdit.StepText; - public E_FieldToEdit FieldToEdit - { - get { return _FieldToEdit; } - set { _FieldToEdit = value; } - } - private string _RtfPrefix; // contains Font table and styles (bold/underline/italics) for rtb from step style + + public E_FieldToEdit FieldToEdit { get; set; } = E_FieldToEdit.StepText; + private string _RtfPrefix; // contains Font table and styles (bold/underline/italics) for rtb from step style public string RtfPrefixForSymbols { get @@ -294,7 +177,7 @@ namespace Volian.Controls.Library StringBuilder selectedRtfSB = new StringBuilder(); // B2021-100: if SelectionFont is null, use the FormatFont - AddFontTable(selectedRtfSB, SelectionFont==null?FormatFont:SelectionFont, FontIsFixed(FormatFont)); + AddFontTable(selectedRtfSB, SelectionFont ?? FormatFont, FontIsFixed(FormatFont)); _RtfPrefix = selectedRtfSB.ToString(); return _RtfPrefix + @"\f1\fs" + FormatFont.SizeInPoints * 2 + " "; @@ -313,43 +196,32 @@ namespace Volian.Controls.Library return _RtfPrefix;// +@"{\colortbl ;\red255\green0\blue0;}"; } } - // August 5, 2009 - KBR & RHM: - // Insert/Overwrite will be developed later if needed. various issues - // were found during initial development that made its scope larger than - // expected. Problems were related to having overstrike on in the following - // cases: - // 1) left arrow when on link - positions after link - // 2) left arrow and after link - does not move - // 3) shift left arrow does not move past links correctly and also, first - // shift left arrow looks more like insert mode. - // private bool _OverWrite; - // _IsDirty compares the original rtf to the current rtf from the - // richtextbox to see if a change was made. - public bool IsDirty - { - get { return OrigRTF != Rtf; } - } - private bool _InitializingRTB; - private bool _IsExperimenting = false; - public bool IsExperimenting - { - get { return _IsExperimenting; } - set { _IsExperimenting = value; } - } - private IContainer _Container = null; + // August 5, 2009 - KBR & RHM: + // Insert/Overwrite will be developed later if needed. various issues + // were found during initial development that made its scope larger than + // expected. Problems were related to having overstrike on in the following + // cases: + // 1) left arrow when on link - positions after link + // 2) left arrow and after link - does not move + // 3) shift left arrow does not move past links correctly and also, first + // shift left arrow looks more like insert mode. + // private bool _OverWrite; + // _IsDirty compares the original rtf to the current rtf from the + // richtextbox to see if a change was made. + public bool IsDirty => OrigRTF != Rtf; + private bool _InitializingRTB; + + public bool IsExperimenting { get; set; } = false; + private readonly IContainer _Container = null; private string _MyClassName=string.Empty; public string MyClassName { get { if (_MyClassName == string.Empty)_MyClassName = CreateParams.ClassName; return _MyClassName; } set { _MyClassName = value; } } - private E_ViewMode _vwMode = E_ViewMode.Edit; - public E_ViewMode VwMode - { - get { return _vwMode; } - set { _vwMode = value; } - } - private VE_Font _MyStyleFont; + + public E_ViewMode VwMode { get; set; } = E_ViewMode.Edit; + private VE_Font _MyStyleFont; public VE_Font MyStyleFont { get @@ -358,13 +230,9 @@ namespace Volian.Controls.Library return _MyStyleFont; } } - private bool _ActiveMode = false; - public bool ActiveMode - { - get { return _ActiveMode; } - set { _ActiveMode = value; } - } - private ItemInfo _MyItemInfo; + + public bool ActiveMode { get; set; } = false; + private ItemInfo _MyItemInfo; public ItemInfo MyItemInfo { get @@ -377,13 +245,9 @@ namespace Volian.Controls.Library } set { _MyItemInfo = value; } } - private string _OrigRTF; - public string OrigRTF - { - get { return _OrigRTF; } - set { _OrigRTF = value; } - } - private Font _FormatFont; + + public string OrigRTF { get; set; } + private Font _FormatFont; public Font FormatFont { get @@ -399,12 +263,7 @@ namespace Volian.Controls.Library _FormatFont = formatFont; else { - //if (VlnSettings.DebugMode || VlnSettings.ProductionMode) - _FormatFont = new Font(MyFontFamily == null ? formatFont.FontFamily : MyFontFamily, formatFont.Size, formatFont.Style); - //else - // _FormatFont = new Font("Bookman Old Style", formatFont.Size, formatFont.Style); - // TODO: Release Mode - //Font = _origDisplayText.TextFont.WindowsFont; // font defined in plant's format + _FormatFont = new Font(MyFontFamily ?? formatFont.FontFamily, formatFont.Size, formatFont.Style); } } // We found that the characters in the Letter Gothic font do not all use the same spacing. @@ -421,7 +280,6 @@ namespace Volian.Controls.Library } public void SetupRichText(string rtf, VE_Font vFont) { - //FormatFont = vFont.WindowsFont; DisplayText vlnText = new DisplayText(rtf, vFont, true); AddRtfText(vlnText.StartText); ReadOnly = true; @@ -470,7 +328,6 @@ namespace Volian.Controls.Library } OrigDisplayText = vlntxt; - //Volian.Base.Library.HWndCounter.GetWindowHandlesForCurrentProcess(this.Handle, "RefreshDisplay 4"); // RHM 20101201 - Don't reset the text. Calculate the text and compare it with the existing text in AddRTFText //Text = ""; // Initialize text before add text @@ -507,7 +364,7 @@ namespace Volian.Controls.Library } RTBAPI.SetLineSpacing(this, RTBAPI.ParaSpacing.PFS_EXACT); - bool readOnlyStep = MyItemInfo == null || MyItemInfo.FormatStepData == null ? false : MyItemInfo.FormatStepData.ReadOnly; + bool readOnlyStep = MyItemInfo != null && MyItemInfo.FormatStepData != null && MyItemInfo.FormatStepData.ReadOnly; if (!readOnlyStep) { StepConfig sc = new StepConfig(MyItemInfo.MyContent.Config); @@ -609,9 +466,10 @@ namespace Volian.Controls.Library //C2026-021 Expand Functionality of Viewing Mode //regex for finding Referenced object links - private static Regex regRefObj = new Regex(@"\#Link\:ReferencedObject:([0-9]*) ([0-9a-zA-Z]*) ([0-9]*)", RegexOptions.Singleline); + private static readonly Regex regRefObj = new Regex(@"\#Link\:ReferencedObject:([0-9]*) ([0-9a-zA-Z]*) ([0-9]*)", RegexOptions.Singleline); - //Replace the Default RO text with Unit Specific RO text + //Replace the Default RO text with Unit Specific RO text + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping Unitid for debugging")] private string RefreshROsWithUnitStartText(string startText, int unitID) { ROFSTLookup lookup = MyItemInfo.MyDocVersion.DocVersionAssociations[0].MyROFst.GetROFSTLookup(MyItemInfo.MyDocVersion); @@ -655,13 +513,9 @@ namespace Volian.Controls.Library return true; return false; } - private bool _ProcessKeystrokes = true; - public bool ProcessKeystrokes - { - get { return _ProcessKeystrokes; } - set { _ProcessKeystrokes = value; } - } - private Point ScrollPos + + public bool ProcessKeystrokes { get; set; } = true; + private Point ScrollPos { get { return RTBAPI.GetScrollLocation(this); } set { RTBAPI.SetScrollLocation(this, value); } @@ -681,11 +535,8 @@ namespace Volian.Controls.Library AdjustSizeForContents(false); } } - public Size ContentsSize - { - get { return _ContentsRectangle.Size; } - } - private Size _AdjustSize = new Size(0,0); // if 0,0 puts text right next to bottom of box. + public Size ContentsSize => _ContentsRectangle.Size; + private Size _AdjustSize = new Size(0,0); // if 0,0 puts text right next to bottom of box. public Size AdjustSize { get { return _AdjustSize; } @@ -696,15 +547,9 @@ namespace Volian.Controls.Library } } public System.Windows.Forms.AutoScaleMode AutoScaleMode; - private DisplayText _OrigDisplayText; - public DisplayText OrigDisplayText - { - get { return _OrigDisplayText; } - set { _OrigDisplayText = value; } - } - private RichTextBox _rtbTemp = new RichTextBox(); - private string _MyLinkText; + public DisplayText OrigDisplayText { get; set; } + private string _MyLinkText; public string MyLinkText { get { return _MyLinkText; } @@ -765,7 +610,7 @@ namespace Volian.Controls.Library this.RTBSelectionChanged -= new StepRTBEvent(StepRTB_RTBSelectionChanged); this.HandleCreated -= new EventHandler(StepRTB_HandleCreated); this.HandleDestroyed -= new EventHandler(StepRTB_HandleDestroyed); - _EventHandlersForKeyPress = _EventHandlersForKeyPress - 1; + _EventHandlersForKeyPress--; } private int _EventHandlersForKeyPress = 0; // When a border style is changed, the richtextbox's handle is 'destroyed', so that the handleDestroyed @@ -791,7 +636,7 @@ namespace Volian.Controls.Library this.RTBSelectionChanged += new StepRTBEvent(StepRTB_RTBSelectionChanged); this.HandleCreated += new EventHandler(StepRTB_HandleCreated); this.HandleDestroyed += new EventHandler(StepRTB_HandleDestroyed); - _EventHandlersForKeyPress = _EventHandlersForKeyPress+1; + _EventHandlersForKeyPress++; } private int _HandleCount = 0; void StepRTB_HandleCreated(object sender, EventArgs e) @@ -808,13 +653,9 @@ namespace Volian.Controls.Library this.KeyPress += new KeyPressEventHandler(StepRTB_KeyPress); _EventHandlersForKeyPress++; } - private bool _Closed = false; - public bool Closed - { - get { return _Closed; } - set { _Closed = value; } - } - void StepRTB_HandleDestroyed(object sender, EventArgs e) + + public bool Closed { get; set; } = false; + void StepRTB_HandleDestroyed(object sender, EventArgs e) { if (_HandleCount == 0) { @@ -891,12 +732,12 @@ namespace Volian.Controls.Library if (ReadOnly) return; } // B2019-161 When tracking timing time this action - private static VolianTimer _TimeActivity = new VolianTimer("StepRTB CloseWordApp_Tick", 902); + private static readonly VolianTimer _TimeActivity = new VolianTimer("StepRTB CloseWordApp_Tick", 902); void StepRTB_SelectionChanged(object sender, EventArgs e) { _TimeActivity.Open(); - if (_InitializingRTB || _IsExperimenting || (MyItemInfo!=null && MyItemInfo.IsRtfRaw)) return; + if (_InitializingRTB || IsExperimenting || (MyItemInfo!=null && MyItemInfo.IsRtfRaw)) return; HandleSelectionChange(); _TimeActivity.Close(); } @@ -977,14 +818,11 @@ namespace Volian.Controls.Library private void ToggleCase() { - char type = 'l'; - // do not change case on linked text - RangeStatus rs = FindRangeStatus(); - string tmp = null; - if (rs != RangeStatus.NoContainedLinks) + // do not change case on linked text + RangeStatus rs = FindRangeStatus(); + if (rs != RangeStatus.NoContainedLinks) { int start = SelectionStart; - int ostart = SelectionStart; int end = SelectionStart + SelectionLength; bool processed = false; while (!processed && start <= end) @@ -1007,20 +845,20 @@ namespace Volian.Controls.Library } string ostring = SelectedText; if (ostring.Length == 0) return; // nothing selected - if (ostring.Length == 1) - type = char.IsUpper(ostring, 0) ? 'l' : 'U'; - else if ((char.IsUpper(ostring, 0) && char.IsUpper(ostring, 1)) || - (char.IsLower(ostring, 0) && char.IsUpper(ostring, 1))) type = 'l'; // lower case - else if ((char.IsUpper(ostring, 0) && char.IsLower(ostring, 1))) type = 'U'; // upper case - else type = 'T'; // Title case - SetSelectedCase(type); + char type; + if (ostring.Length == 1) + type = char.IsUpper(ostring, 0) ? 'l' : 'U'; + else if ((char.IsUpper(ostring, 0) && char.IsUpper(ostring, 1)) || + (char.IsLower(ostring, 0) && char.IsUpper(ostring, 1))) type = 'l'; // lower case + else if ((char.IsUpper(ostring, 0) && char.IsLower(ostring, 1))) type = 'U'; // upper case + else type = 'T'; // Title case + SetSelectedCase(type); } public void SetSelectedCase(char type) { // do not change case on linked text RangeStatus rs = FindRangeStatus(); - string tmp = null; if (rs == RangeStatus.NoContainedLinks) SetCase(type); else @@ -1028,7 +866,6 @@ namespace Volian.Controls.Library int start = SelectionStart; int ostart = SelectionStart; int end = SelectionStart + SelectionLength; - StringBuilder sb = new StringBuilder(); while (start <= end) { bool processed = false; @@ -1066,7 +903,6 @@ namespace Volian.Controls.Library int ostart = SelectionStart; int olen = SelectionLength; string ostring = SelectedText; - string tmp = null; bool docap = true; // go character by character. Because of symbols, setting entire // to upper or lower set symbols incorrectly some of time (depending @@ -1097,15 +933,10 @@ namespace Volian.Controls.Library SelectionStart = ostart; SelectionLength = olen; } - #endregion - #region AddRtfTextAndStyles - private string _LastRtf = ""; - public string LastRtf - { - get { return _LastRtf; } - set { _LastRtf = value; } - } - private bool _lastReadOnly = false; + #endregion + #region AddRtfTextAndStyles + public string LastRtf { get; set; } = ""; + private bool _lastReadOnly = false; public override string ToString() { return string.Format("[StepRTB {0},{1},{2}]", MyItemInfo.ItemID, MyItemInfo.DisplayNumber, MyItemInfo.DisplayText); @@ -1114,7 +945,7 @@ namespace Volian.Controls.Library { if (MyItemInfo != null && MyItemInfo.IsRtfRaw) { - if (txt != null && txt != "") SelectedRtf = _LastRtf = txt; + if (txt != null && txt != "") SelectedRtf = LastRtf = txt; _lastReadOnly = ReadOnly; OrigRTF = txt; return; @@ -1124,8 +955,8 @@ namespace Volian.Controls.Library AddFontTable(selectedRtfSB, FormatFont, FontIsFixed(FormatFont)); _RtfPrefix = selectedRtfSB.ToString(); selectedRtfSB.Append(txt); - string newRtf = selectedRtfSB.ToString() + "}"; - if(newRtf != _LastRtf || ReadOnly != _lastReadOnly) + string newRtf = $"{selectedRtfSB}}}"; + if(newRtf != LastRtf || ReadOnly != _lastReadOnly) { //Console.WriteLine("ItemID:{0}\r\nOld:'{1}'\r\nNew:'{2}'\r\n", MyItemInfo.ItemID, Rtf, newRtf); this.ContentsResized -= new ContentsResizedEventHandler(StepRTB_ContentsResized); @@ -1143,7 +974,7 @@ namespace Volian.Controls.Library } // B2017-048, B2017-052, B2017-055 ROs sometimes have two start tokens which make them uneditable. newRtf = newRtf.Replace(" 0)HandleDeleteKeyWithSelectedText(new KeyEventArgs(Keys.None), null); + //For debugging - Add Watch: FontTable; + //For debugging - Add Watch: FontSize; + if (SelectionLength > 0)HandleDeleteKeyWithSelectedText(new KeyEventArgs(Keys.None), null); int position = SelectionStart; SelectionLength = 0; // B2026-036 fixed issue where numbers after a dash character (in an RO return value) were trucated // Needed to add a space after the \f0 in the string replace below. RTF was getting confused // when there are number right after the \f0. Note also remove the space charcter after // the \f1 command, as it is not needed since the \u commdn follows it. - // Here is the old code prior to when the foreach loop was added to handle symbols in RO value: - // - // linkValue = linkValue.Replace("\\u8209?", "\\f1\\u8209?\\f0 "); // dash character - // linkValue = linkValue.Replace("\\u9586?", "\\f1\\u9586?\\f0 "); // backslash symbol - // linkValue = linkValue.Replace("\\u916?", "\\f1\\u916?\\f0 "); // delta symbol var pattern = @"\\u([0-9]{1,4})\?"; // RO Editor add symbols C2022 - 003 foreach (Match match in Regex.Matches(linkValue, pattern, RegexOptions.IgnoreCase)) { - linkValue = linkValue.Replace(match.Value, "\\f1" + match.Value + "\\f0 "); + linkValue = linkValue.Replace(match.Value, $"\\f1{match.Value}\\f0 "); } linkValue = linkValue.Replace(@"{", @"\{"); linkValue = linkValue.Replace(@"}", @"\}"); - SelectedRtf = @"{\rtf1\ansi" + FontTable + @"{\colortbl ;\red255\green0\blue0;\red0\green0\blue255;}\v" + FontSize + @" \v0 }"; + SelectedRtf = $@"{{\rtf1\ansi{FontTable}{{\colortbl ;\red255\green0\blue0;\red0\green0\blue255;}}\v{FontSize} \v0 }}"; this.SelectionLength = 0; this.SelectionStart = position; FindAllLinks(); } private void AddLink50(string linkValue, string linkUrl) { - int position = SelectionStart; + //Debugging - Add Watch for: SelectionStart; SelectionLength = 0; SelectedRtf = string.Format(@"{{\rtf\field{{\*\fldinst{{HYPERLINK ""www.volian.com #{0}"" }}}}{{\fldrslt{{\cf2\ul {1}}}}}}}", linkUrl, linkValue); this.SelectionStart = this.TextLength; this.SelectionLength = 0; } - private void AddRtfStyles() - { - if ((OrigDisplayText.TextFont.Style & E_Style.Bold) > 0) - { - this.SelectAll(); - RTBAPI.ToggleBold(true, this, RTBAPI.RTBSelection.SCF_SELECTION); - this.Select(0, 0); - } - // Bug Fix - // The code below was changed to select all of the text and then - // apply the underlining to the selected text, because if the - // the underlining was applied to RTBAPI.RTBSelection.SCF_ALL - // the Links were changed so that they were no longer hidden. - if ((OrigDisplayText.TextFont.Style & E_Style.Underline) > 0) - // RTBAPI.ToggleUnderline(true, this, RTBAPI.RTBSelection.SCF_ALL); - { - this.SelectAll(); - RTBAPI.ToggleUnderline(true, this, RTBAPI.RTBSelection.SCF_SELECTION); - this.Select(0, 0); - } - // Bug Fix - // The code below was changed to select all of the text and then - // apply the italics to the selected text, because if the - // the italics was applied to RTBAPI.RTBSelection.SCF_ALL - // the Links were changed so that they were no longer hidden. - if ((OrigDisplayText.TextFont.Style & E_Style.Italics) > 0) - // RTBAPI.ToggleItalic(true, this, RTBAPI.RTBSelection.SCF_ALL); - { - this.SelectAll(); - RTBAPI.ToggleItalic(true, this, RTBAPI.RTBSelection.SCF_SELECTION); - this.Select(0, 0); - } - } #endregion #region HeightSupport public event StepRTBEvent HeightChanged; - private void OnHeightChanged(object sender, EventArgs args) - { - if (HeightChanged != null) HeightChanged(sender, args); - } - private void AdjustSizeForContents(bool adjustWidth) + private void OnHeightChanged(object sender, EventArgs args) => HeightChanged?.Invoke(sender, args); + private void AdjustSizeForContents(bool adjustWidth) { if (!_InitializingRTB) { @@ -1433,42 +1219,23 @@ namespace Volian.Controls.Library return g.MeasureString(strMeasureString, Font).Width; } } - private int Ceiling(float f) - { - return (int)(Math.Ceiling(f)); - } - public int MaxTextWidth - { - get - { - int maxWidth = 0; - for (int i = 0; i < TextLength; i++) - { - int w = GetPositionFromCharIndex(i).X; - maxWidth = Math.Max(maxWidth, w); - } - return maxWidth+10; // add 10 to account for the last character - } - } - public void AdjustWidthForContent() - { - AdjustWidthForContent(0); - } - public void AdjustWidthForContent(int count) + private int Ceiling(float f) => (int)(Math.Ceiling(f)); + public void AdjustWidthForContent() => AdjustWidthForContent(0); + public void AdjustWidthForContent(int count) { int widthNL = Ceiling(GetStringWidth("\n")); int widthMax = 0; int widthMaxWW = 0; int indexStart = 0; - int lineCountFromLines = Lines.Length; - int lineCountFromGet = GetLineFromCharIndex(TextLength)+1; - for (int i = 0; i < Lines.Length; i++) + //Debugging - Add Watch for: Lines.Length; + //Debugging - Add Watch for: int lineCountFromGet = GetLineFromCharIndex(TextLength)+1; + for (int i = 0; i < Lines.Length; i++) { int lineStart = GetLineFromCharIndex(indexStart); int indexEnd = indexStart + Lines[i].Length; int lineEnd = GetLineFromCharIndex(indexEnd); - Point pointStart = GetPositionFromCharIndex(indexStart); - Point pointEnd = GetPositionFromCharIndex(indexEnd); + //Debugging - Add Watch for: Point pointStart = GetPositionFromCharIndex(indexStart); + Point pointEnd = GetPositionFromCharIndex(indexEnd); int indexEndPos = GetCharIndexFromPosition(pointEnd); if (indexEndPos + 1 < indexEnd) // This indicates that the text is wider than the Rich Text Box { @@ -1479,8 +1246,8 @@ namespace Volian.Controls.Library if (lineEnd > lineStart)// this indicates that there was word-wrap on this line. { int w = pointEnd.X + Width * (lineEnd - lineStart); - if (w > widthMaxWW) - widthMaxWW = w; + if (w > widthMaxWW) + widthMaxWW = w; } else { @@ -1493,58 +1260,21 @@ namespace Volian.Controls.Library { int widthBorder = Width - ClientSize.Width; int w = widthMax + widthNL + widthBorder; - if (Width != w) + if (Width != w && (count < 5 || Width < w)) + { + Width = w; + AdjustWidthForContent(count + 1);// Try one more time + } + } + else + { + if (count < 5 || Width < widthMaxWW) { - if (count < 5 || Width < w) - { - Width = w; - AdjustWidthForContent(count + 1);// Try one more time - } + Width = widthMaxWW; + AdjustWidthForContent(count + 1); } } - else - { - if (count < 5 || Width < widthMaxWW) - { - Width = widthMaxWW; - AdjustWidthForContent(count + 1); - } - } } - public int CalculateHeight() - { - if (this.CreateParams.ClassName == "RICHEDIT50W") - return CalculateHeight50(); - else - return CalculateHeight20(); - } - private int CalculateHeight20() - { - Application.DoEvents(); - int yBottom = GetPositionFromCharIndex(TextLength).Y; - int yTop = GetPositionFromCharIndex(0).Y; - int heightFont = SelectionFont.Height; - int borderSize = this.Height - this.ClientSize.Height; - int heightNext = (yBottom - yTop) + heightFont + borderSize + 2;// 2 pixels - 1 at the top and 1 at the bottom - if (heightNext != Height) - { - Height = heightNext; - - OnHeightChanged(this, new EventArgs()); - ScrollPos = new Point(0, 0); // Scroll to make sure that the first line is displayed as the first line - } - return heightNext; - } - private int CalculateHeight50() - { - Application.DoEvents(); - int heightFont = SelectionFont.Height; - int borderSize = this.Height - this.ClientSize.Height; - int heightNext = (1 + GetLineFromCharIndex(TextLength)) * heightFont + borderSize + 2;// 2 pixels - 1 at the top and 1 at the bottom - return heightNext; - } - #endregion - #region ColorSupport - Not currently used. #endregion #region EventSupport #region LinkEvents @@ -1553,31 +1283,31 @@ namespace Volian.Controls.Library private void OnLinkChanged(object sender, StepPanelLinkEventArgs args) { _MyLinkClickedEventArgs = args; - if (LinkChanged != null) LinkChanged(sender, args); - } + LinkChanged?.Invoke(sender, args); + } public event StepRTBLinkEvent LinkGoTo; private void OnLinkGoTo(object sender, StepPanelLinkEventArgs args) { _MyLinkClickedEventArgs = args; - if (LinkGoTo != null) LinkGoTo(sender, args); - } + LinkGoTo?.Invoke(sender, args); + } public event StepRTBLinkEvent LinkModifyTran; private void OnLinkModifyTran(object sender, StepPanelLinkEventArgs args) { _MyLinkClickedEventArgs = args; - if (LinkModifyTran != null) LinkModifyTran(sender, args); - } + LinkModifyTran?.Invoke(sender, args); + } public event StepRTBLinkEvent LinkModifyRO; private void OnLinkModifyRO(object sender, StepPanelLinkEventArgs args) { _MyLinkClickedEventArgs = args; - if (LinkModifyRO != null) LinkModifyRO(sender, args); + LinkModifyRO?.Invoke(sender, args); } #endregion #region TextAndContentsEvents void StepRTB_TextChanged(object sender, EventArgs e) { - if (_InitializingRTB || _IsExperimenting) return; + if (_InitializingRTB || IsExperimenting) return; // Was setting _IsDirty to true here, but this was getting called from // 'dotnetbar' when text was NOT Changed. So _IsDirty was made into // a property and compared original rtf versus current richtextbox's @@ -1588,25 +1318,16 @@ namespace Volian.Controls.Library LastRtf = string.Empty; FindAllLinks(); } - private void ShowMyParentsFonts() - { - Console.WriteLine("\r\n--- Parents Fonts ---- For ----{0}", Text); - ShowMyParentsFonts(this); - Console.WriteLine("Selection Font".PadRight(31) + SelectionFont); - } private void ShowMyParentsFonts(Control ctrl) { if (ctrl.Parent is Control) ShowMyParentsFonts(ctrl.Parent); Console.WriteLine("{0} {1}", ctrl.GetType().Name.PadRight(30), ctrl.Font); } - public void StepRTB_ContentsResized(object sender, ContentsResizedEventArgs e) - { - ContentsRectangle = e.NewRectangle; - } - #endregion - #region Selection Handlers - bool _AdjustingSelection = false; + public void StepRTB_ContentsResized(object sender, ContentsResizedEventArgs e) => ContentsRectangle = e.NewRectangle; + #endregion + #region Selection Handlers + bool _AdjustingSelection = false; private bool _ProcessingDelete; private bool _HandlingCtrlA = false; private void HandleLocalSelectionChange() @@ -1686,7 +1407,7 @@ namespace Volian.Controls.Library if (SelectedText.EndsWith("Removing ending InsertCharBetweenLinks(ll, ' ', false); + private void InsertCharBetweenLinks(LinkLocation ll, string strToAdd) => InsertCharBetweenLinks(ll, strToAdd, true); + private void InsertCharBetweenLinks(LinkLocation ll, string strToAdd, bool setSelect) { Rtf = Rtf.Substring(0, ll.StartRtf) + @"\v0 " + strToAdd + @"\v " + Rtf.Substring(ll.StartRtf); if (setSelect) @@ -1830,11 +1545,8 @@ namespace Volian.Controls.Library SelectionStart = ll.Start - 6; // account for >>"); } - private void ExpandSelectionToIncludeStart() - { - SetSelection(SelectionStart - 7, SelectionLength + 7); // Expand selection to include start - } - public string GetSelectionForClipBoard() + private void ExpandSelectionToIncludeStart() => SetSelection(SelectionStart - 7, SelectionLength + 7); // Expand selection to include start + public string GetSelectionForClipBoard() { string selTxtRTF = SelectedRtf; LinkLocation llstart = FindLinkLocation(); @@ -1871,7 +1583,7 @@ namespace Volian.Controls.Library DebugPrint("vvvvvvvvvvvvxxxxxxxxxxxx>"); DebugSelection("Before X"); DebugPrint(keys == null ? "NULL" : "NOT NULL"); - SelectedText = keys==null?"X":keys; // replace text with X + SelectedText = keys ?? "X"; // replace text with X WasXDelete = (keys == null); DebugSelection("After X"); DebugPrint("------------xxxxxxxxxxxx>"); @@ -1891,38 +1603,31 @@ namespace Volian.Controls.Library } private void DeleteEndBetweenLinks(string keychars) { - _ProcessingKeys++; DebugSelection("DeleteEndBetweenLinks"); int sstart = SelectionStart; int slen = SelectionLength + 1 - 7; // This puts a space at the link that starts at the end of the selection InsertCharBetweenLinks(_RangeEndLink.NextLink); DeleteSelection(sstart, slen, keychars); - _ProcessingKeys--; } private void DeleteStartBetweenLinks(string keychars) { - _ProcessingKeys++; DebugSelection("DeleteStartBetweenLinks"); int slen = SelectionLength + 8; int sstart = SelectionStart - 7; InsertCharBetweenLinks(_RangeStartLink); DeleteSelection(sstart, slen, keychars); - _ProcessingKeys--; } private void DeleteFromStartOfBox(string keychars) { - _ProcessingKeys++; DebugSelection("DeleteFromStartOfBox"); int slen = SelectionLength; SetSelection(0, 0); SelectedText = " "; DeleteSelection(0, slen + 8, keychars); - _ProcessingKeys--; } private void DeleteFromStartOfBoxEndBetweenLinks(string keychars) { - _ProcessingKeys++; DebugSelection("DeleteFromStartOfBoxEndBetweenLinks"); // This puts a space at the link that starts at the end of the selection int sLen = SelectionStart + SelectionLength - 7 + 2;// -7 for = lastLine) { @@ -2361,7 +2063,7 @@ namespace Volian.Controls.Library { Point cpos = GetPositionFromCharIndex(SelectionStart); int addon = ClientRectangle.Height / (lastLine + 1); - cpos.Y = cpos.Y + addon; + cpos.Y += addon; int selend = GetCharIndexFromPosition(cpos); Select(7, selend - 7); e.Handled = true; @@ -2458,42 +2160,41 @@ namespace Volian.Controls.Library SendKeys.Send("%H{ESC}"); break; case Keys.Tab: - VlnFlexGrid myGrid = Parent as VlnFlexGrid; - if (myGrid == null) - { - e.SuppressKeyPress = true; - e.Handled = true; - Form frm = ParentForm(this); - if (frm != null) - frm.SelectNextControl(this, true, true, true, true); - else - StepRTB_ArrowPressed(e.Shift ? E_ArrowKeys.CtrlUp : E_ArrowKeys.CtrlRight); - } - else - { - if (e.Shift) - { - e.SuppressKeyPress = true; - e.Handled = true; - if (!myGrid.SelectPrevCell()) - { - // don't do anything if at top (for now) - } - } - else - { - e.SuppressKeyPress = true; - e.Handled = true; - if (!myGrid.SelectNextCell()) - { - myGrid.MyBorders.InsertRow(myGrid.Rows.Count - 1); - myGrid.MyShading.InsertRow(myGrid.Rows.Count - 1); // C2021-004 Table Cell Shading information - myGrid.Rows.Add(1); - myGrid.SelectNextCell(); - } - } - } - break; + if (!(Parent is VlnFlexGrid myGrid)) + { + e.SuppressKeyPress = true; + e.Handled = true; + Form frm = ParentForm(this); + if (frm != null) + frm.SelectNextControl(this, true, true, true, true); + else + StepRTB_ArrowPressed(e.Shift ? E_ArrowKeys.CtrlUp : E_ArrowKeys.CtrlRight); + } + else + { + if (e.Shift) + { + e.SuppressKeyPress = true; + e.Handled = true; + if (!myGrid.SelectPrevCell()) + { + // don't do anything if at top (for now) + } + } + else + { + e.SuppressKeyPress = true; + e.Handled = true; + if (!myGrid.SelectNextCell()) + { + myGrid.MyBorders.InsertRow(myGrid.Rows.Count - 1); + myGrid.MyShading.InsertRow(myGrid.Rows.Count - 1); // C2021-004 Table Cell Shading information + myGrid.Rows.Add(1); + myGrid.SelectNextCell(); + } + } + } + break; case Keys.Enter: if (!e.Control && !e.Shift && !e.Alt) { @@ -2622,19 +2323,16 @@ namespace Volian.Controls.Library if (MyItemInfo.IsProcedure || MyItemInfo.IsSection) return; // Cursor moves out of box only if control is pressed too - otherwise key is // handled in rtb. - //if (keyargs.Control)MyRTBItem.MyStepPanel.StepCursorKeys(this, keyargs); // Replaced with an event if (keyargs.Control) OnCursorKeyPress(this, keyargs); } private void StepRTB_PageKeyPressed(KeyEventArgs keyargs) { if (MyItemInfo.IsProcedure || MyItemInfo.IsSection) return; - //MyRTBItem.MyStepPanel.StepCursorKeys(this, keyargs); Replaced with an event OnCursorKeyPress(this, keyargs); } public void StepRTB_ArrowPressed(E_ArrowKeys key) { Point cp = PointToClient(Cursor.Position); - //MyRTBItem.MyStepPanel.CursorMovement(this, cp, key); Replaced with an event OnCursorMovement(this, new StepRTBCursorMovementEventArgs(cp, key)); } private void StepRTB_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) @@ -2666,7 +2364,7 @@ namespace Volian.Controls.Library if (ll != null && SelectionLength == 0) // SelectionLength = 0 means insert { // replacing between links, this is a special case - string strpressed = null; + string strpressed; if (e.KeyChar == '-') strpressed = GetAddSymbolText(@"\u8209?"); else if (e.KeyChar == '\\') @@ -2782,32 +2480,15 @@ namespace Volian.Controls.Library FlexibleMessageBox.Show("Replacing pasted characters that are not supported by Proms with a '?'."); return ptext; } - private void DoDeleteEndBetweenLinks() - { - DebugSelection("Beginning"); - int sstart = SelectionStart; - RtbSendKeys("{RIGHT} "); // open for space between links which separates END/START tokens - SetSelection(sstart, SelectionStart - sstart - 1); // 1 is accounting for typed space - DebugSelection("SetSelection"); - RtbSendKeys("{DELETE}"); // deletes text including link - RtbSendKeys("{RIGHT}{BS}"); // deletes space that was added - } - private void DoDeleteStartBetweenLinks() - { - int slen = SelectionLength; - RtbSendKeys("{LEFT} "); - SetSelection(SelectionStart, slen + 7); - RtbSendKeys("{DELETE}"); - RtbSendKeys("{BS}"); - } - #endregion - #region LinkSelectionAndHandling - public bool IsSelectionLinked(int index, int len) + #endregion + #region LinkSelectionAndHandling + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping len for Debugging")] + public bool IsSelectionLinked(int index, int len) { if (_LinkLocations == null)return false; int sel = index; - int selLength = len; - foreach (LinkLocation ll in _LinkLocations) + //Debugging - Add Watch for: len; + foreach (LinkLocation ll in _LinkLocations) { // When the selector moved to the right of a link, the GOTO button was still lit. // Removing the "+7" seems to have fixed this. - jsj 1/08/2010 @@ -2816,20 +2497,21 @@ namespace Volian.Controls.Library } return false; } - /// - /// For use in Find/Replace. - /// If text is found is part of the link information and not the link value, - /// then we want to continue searching. - /// - /// - /// - /// - public bool SkipLinkInfo(int index, int len) + /// + /// For use in Find/Replace. + /// If text is found is part of the link information and not the link value, + /// then we want to continue searching. + /// + /// + /// + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping len for debugging")] + public bool SkipLinkInfo(int index, int len) { if (_LinkLocations == null)return false; int sel = index; - int selLength = len; - foreach (LinkLocation ll in _LinkLocations) + //Debugging - Add Watch for: len; + foreach (LinkLocation ll in _LinkLocations) { if (sel >= ll.Start - 7 && sel < ll.Start + ll.Length) { @@ -2853,49 +2535,30 @@ namespace Volian.Controls.Library return _SelectionStack; } } - public void PushSelection() - { - SelectionStack.Push(new SelectionData(this)); - } - public void PopSelection() + public void PushSelection() => SelectionStack.Push(new SelectionData(this)); + public void PopSelection() { SelectionData selection = SelectionStack.Pop(); if (SelectionStack.Count == 0) _SelectionStack = null; Select(selection.SelectionStart, selection.SelectionLength); - selection = null; } public class SelectionData { - int _SelectionStart; - public int SelectionStart + public int SelectionStart { get; set; } + public int SelectionLength { get; set; } + public SelectionData(RichTextBox richTextBox) { - get { return _SelectionStart; } - set { _SelectionStart = value; } - } - int _SelectionLength; - public int SelectionLength - { - get { return _SelectionLength; } - set { _SelectionLength = value; } - } - public SelectionData(RichTextBox richTextBox) - { - _SelectionStart = richTextBox.SelectionStart; - _SelectionLength = richTextBox.SelectionLength; + SelectionStart = richTextBox.SelectionStart; + SelectionLength = richTextBox.SelectionLength; } } #endregion #region Link Support - int _ProcessingKeys = 0; List _LinkLocations; - public List LinkLocations - { - get { return _LinkLocations; } - } - private int _FALLevel = 0; - private bool _IdentifyingLinks = false; + public List LinkLocations => _LinkLocations; + private readonly bool _IdentifyingLinks = false; public void FindAllLinks() { if (_IdentifyingLinks || _ProcessingDelete) return; @@ -2933,11 +2596,8 @@ namespace Volian.Controls.Library _LinkLocations.Add(thisLink); } } - private LinkLocation FindBetweenLinks() - { - return FindBetweenLinks(SelectionStart); - } - private LinkLocation FindBetweenLinks(int start) + private LinkLocation FindBetweenLinks() => FindBetweenLinks(SelectionStart); + private LinkLocation FindBetweenLinks(int start) { DebugPrint("FL----------------Between>"); if (_LinkLocations == null) return null; @@ -2946,11 +2606,8 @@ namespace Volian.Controls.Library return ll; return null; } - private LinkLocation FindLinkLocation() - { - return FindLinkLocation(SelectionStart); - } - private LinkLocation FindLinkLocation(int sel) + private LinkLocation FindLinkLocation() => FindLinkLocation(SelectionStart); + private LinkLocation FindLinkLocation(int sel) { //DebugPrint("FL----------------Location>"); if (_LinkLocations == null) return null; @@ -2972,7 +2629,8 @@ namespace Volian.Controls.Library } return null; } - public DialogResult ReplaceText(string rpltxt, string fndstr, bool caseSensitive, bool matchWholeWord, bool reverse, bool prompt, IWin32Window fndrpldlg) + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping fndstr, caseSensitive, matchWholeWord, reverse for debugging")] + public DialogResult ReplaceText(string rpltxt, string fndstr, bool caseSensitive, bool matchWholeWord, bool reverse, bool prompt, IWin32Window fndrpldlg) { DialogResult dlgrslt = DialogResult.Yes; if (SelectionLength > 0) @@ -3052,31 +2710,6 @@ namespace Volian.Controls.Library return true; } } - private int FindStart() - { - foreach (LinkLocation ll in _LinkLocations) - { - if (SelectionStart == ll.End) return ll.Start; - if (SelectionStart == ll.Start) - { - if (ll.Start == 7) return 7; - return ll.Start - 8; - } - } - if (SelectionStart > 0) return SelectionStart - 1; - return 0; - } - private int FindEnd() - { - foreach (LinkLocation ll in _LinkLocations) - { - if (SelectionStart + SelectionLength + 7 == ll.Start) return ll.Length + 7; - // this is for in-between links - if (SelectionStart + SelectionLength == ll.Start) return ll.Length; - } - if (SelectionStart + SelectionLength < TextLength) return 1; - return 0; - } private int FindEndDown() { foreach (LinkLocation ll in _LinkLocations) @@ -3095,14 +2728,6 @@ namespace Volian.Controls.Library } return 0; } - private int FindStartUp() - { - foreach (LinkLocation ll in _LinkLocations) - { - if ((SelectionStart >= ll.Start) && (SelectionStart <= ll.End)) return ll.Start; - } - return -1; - } public void SetSelection(LinkLocation ll) { SetSelection(ll.Start, ll.Length); @@ -3221,78 +2846,47 @@ namespace Volian.Controls.Library } return RTBRangeStatus = (RangeStatus)((int)myStartStatus + (int)myEndStatus); } - #endregion - #region OutlineTable - private string _CheckRight = "-\u2500\u2011"; - public string CheckRight - { - get { return _CheckRight; } - set { _CheckRight = value; } - } - private string _CheckAbove = "|\u2502\u2514\u252c\u253c\u251c\u250c\u2534\u2510\u2524"; - public string CheckAbove - { - get { return _CheckAbove; } - set { _CheckAbove = value; } - } - private string _CheckLeft = "-\u2500\u2524\u252c\u251c\u253c\u250c\u2510\u2514\u2011"; - public string CheckLeft - { - get { return _CheckLeft; } - set { _CheckLeft = value; } - } - private string _CheckBelow = "|\u2502"; - public string CheckBelow - { - get { return _CheckBelow; } - set { _CheckBelow = value; } - } - // This is a table of graphics characters - // The index into this table (0-15) is a bitmask with each bit representing - // a different direction from the current character. - // Right is Bit 0 (0 or 1) - // Above is Bit 1 (0 or 2) - // Left is Bit 2 (0 or 4) - // Below is Bit 3 (0 or 8) - // The index is contolled in the following way: - // If there is a graphics character to the right, then you add 1 - // If there is a graphics character above, then you add 2 - // If there is a graphics character left, then you add 4 - // If there is a graphics character below, then you add 8 - // The total results in an index into this array and gives the appropriate character - // combining horizontal and vertical lines. + #endregion + #region OutlineTable + public string CheckRight { get; set; } = "-\u2500\u2011"; + public string CheckAbove { get; set; } = "|\u2502\u2514\u252c\u253c\u251c\u250c\u2534\u2510\u2524"; + public string CheckLeft { get; set; } = "-\u2500\u2524\u252c\u251c\u253c\u250c\u2510\u2514\u2011"; + public string CheckBelow { get; set; } = "|\u2502"; + // This is a table of graphics characters + // The index into this table (0-15) is a bitmask with each bit representing + // a different direction from the current character. + // Right is Bit 0 (0 or 1) + // Above is Bit 1 (0 or 2) + // Left is Bit 2 (0 or 4) + // Below is Bit 3 (0 or 8) + // The index is contolled in the following way: + // If there is a graphics character to the right, then you add 1 + // If there is a graphics character above, then you add 2 + // If there is a graphics character left, then you add 4 + // If there is a graphics character below, then you add 8 + // The total results in an index into this array and gives the appropriate character + // combining horizontal and vertical lines. - static private string [] TableCharsU = { - "\x0", // HEX"\x0", // No character - @"\u9472", // HEX@"\u2500",// - Horizontal line - 16-bit char: '\xC4' - @"\u9474", // HEX@"\u2502",// | Vertical line - 16-bit char: '\xB3' - @"\u9492", // HEX@"\u2514",// L Bottom Left corner - 16-bit char: '\xC0' - @"\u9472", // HEX@"\u2500",// - Horizontal line - 16-bit char: '\xC4' - @"\u9472", // HEX@"\u2500",// - Horizontal line - 16-bit char: '\xC4' - @"\u9496", // HEX@"\u2518",// Bottom Right Corner - 16-bit char: '\xD9' - @"\u9524", // HEX@"\u2534",// Bottom Tee - 16-bit char: '\xC1' - @"\u9474", // HEX@"\u2502",// | Vertical Bar - 16-bit char: '\xB3' - @"\u9484", // HEX@"\u250c",// Upper Left corner - 16-bit char: '\xDA' - @"\u9474", // HEX@"\u2502",// | Vertical Bar - 16-bit char: '\xB3' - @"\u9500", // HEX@"\u251c",// Left Tee - 16-bit char: '\xC3' - @"\u9488", // HEX@"\u2510",// Upper Right corner - 16-bit char: '\xBF' - @"\u9516", // HEX@"\u252c",// T Top Tee - 16-bit char: '\xC2' - @"\u9508", // HEX@"\u2524",// Right Tee - 16-bit char: '\xB4' - @"\u9532", // HEX@"\u253c" // + Plus - 16-bit char: '\xC5' - }; - private int MaxCharacterWidth() - { - // loop through lines and get the width in characters - int w = 0; - foreach (string line in Lines) - { - string cleanLine = RemoveLinkComments(line); - if (w < cleanLine.Length) - w = cleanLine.Length; - } - return w; - } + //For Reference + // private static readonly string [] TableCharsU = { + // "\x0", // HEX"\x0", // No character + // @"\u9472", // HEX@"\u2500",// - Horizontal line - 16-bit char: '\xC4' + // @"\u9474", // HEX@"\u2502",// | Vertical line - 16-bit char: '\xB3' + // @"\u9492", // HEX@"\u2514",// L Bottom Left corner - 16-bit char: '\xC0' + // @"\u9472", // HEX@"\u2500",// - Horizontal line - 16-bit char: '\xC4' + // @"\u9472", // HEX@"\u2500",// - Horizontal line - 16-bit char: '\xC4' + // @"\u9496", // HEX@"\u2518",// Bottom Right Corner - 16-bit char: '\xD9' + // @"\u9524", // HEX@"\u2534",// Bottom Tee - 16-bit char: '\xC1' + // @"\u9474", // HEX@"\u2502",// | Vertical Bar - 16-bit char: '\xB3' + // @"\u9484", // HEX@"\u250c",// Upper Left corner - 16-bit char: '\xDA' + // @"\u9474", // HEX@"\u2502",// | Vertical Bar - 16-bit char: '\xB3' + // @"\u9500", // HEX@"\u251c",// Left Tee - 16-bit char: '\xC3' + // @"\u9488", // HEX@"\u2510",// Upper Right corner - 16-bit char: '\xBF' + // @"\u9516", // HEX@"\u252c",// T Top Tee - 16-bit char: '\xC2' + // @"\u9508", // HEX@"\u2524",// Right Tee - 16-bit char: '\xB4' + // @"\u9532", // HEX@"\u253c" // + Plus - 16-bit char: '\xC5' + //}; internal static string RemoveLinkComments(string line) { StringBuilder sb = new StringBuilder(); @@ -3314,85 +2908,6 @@ namespace Volian.Controls.Library } return result; } - private void ReplaceLinesInTable(bool withBorder) - { - int rowWidth = Lines[0].Length; - for (int row=1;row", RegexOptions.Singleline);// this last parameter was commented out in 7/24/09 but it appears to be valid - if (matchCollection.Count == 0) matchCollection = Regex.Matches(line, @""); - Match match = matchCollection.Count > 0 ? matchCollection[0] : null; - int matchOffset = 0; - for (int col = 1; col < rowWidth - 1; col++) - { - if (match != null && match.Index == matchOffset + col) - { - matchOffset += match.Length - match.Groups[1].Length; // Increment the offset by the link comment length - col += match.Groups[1].Length; // increment the column by the link value length - if (col >= rowWidth - 1) break;// Don't continue if beyond the contents - match = match.NextMatch(); // Watch for the next match - } - int coll = matchOffset + col; - char chr = line[coll]; - char chrLast = line[coll - 1]; - char chrNext = line[coll + 1]; - char chrAbove = lineAbove[col]; - char chrBelow = lineBelow[col]; - // The following is all using symbol font (either unicode for proportional or - // VeSymbFix for fixed font): - // if this character is a table line draw character, i.e. a dash or vertical bar, or - // graphics characters for those, look around it to see what table character it is - // replaced with - - // Look for -||-- (last three are graphics chars or unicode dash) - if ("-|\u2500\u2502\u2011".IndexOf(chr) > -1) - { - bool horizontalCharacter = "-\u2500\u2011".IndexOf(chr) > -1; - int lineDrawRight = (CheckRight.IndexOf(chrNext) > -1 || (horizontalCharacter && "\u2502".IndexOf(chrNext) > -1)) ? 1 : 0; - int lineDrawAbove = (CheckAbove.IndexOf(chrAbove) > -1 || (!horizontalCharacter && "\u2500\u2011".IndexOf(chrAbove) > -1)) ? 2 : 0; - int lineDrawLeft = (CheckLeft.IndexOf(chrLast) > -1 || (horizontalCharacter && "\u2502".IndexOf(chrLast) > -1)) ? 4 : 0; - int lineDrawBelow = (CheckBelow.IndexOf(chrBelow) > -1 || (!horizontalCharacter && "-\u2500\u2011".IndexOf(chrBelow) > -1)) ? 8 : 0; - int tableCharIndx = lineDrawRight + lineDrawAbove + lineDrawLeft + lineDrawBelow; - if (tableCharIndx > 0) - { - SetTableChar(row, coll, tableCharIndx); - if (withBorder) // Adjust the border as it intersects with lines within the box - { - if (row == 1 && !horizontalCharacter ) SetTableChar(row - 1, col, 13); // Top Row - if (row == Lines.Length - 2 && !horizontalCharacter) SetTableChar(row + 1, col, 7); // Bottom Row - if (col == 1 && horizontalCharacter && ((tableCharIndx & 4)==4)) SetTableChar(row, col - 1, 11); // First Column - if (col == rowWidth - 2 && horizontalCharacter && ((tableCharIndx & 1) == 1)) SetTableChar(row, coll + 1, 14); // Last Column - } - } - } - } - } - } - private void SetTableChar(int row, int col, int tableCharIndx) - { - int rowOffset = GetFirstCharIndexFromLine(row); - Select(rowOffset + col, 1); - string charToBeReplaced = SelectedText; - if (Text.Length > (rowOffset + col + 7) && Text.Substring(rowOffset + col + 1, 6) != "#Link:") - SelectedRtf = RtfPrefixForSymbols + TableCharsU[tableCharIndx] + "?}"; - else - { - SelectionStart++; - int lenComment = 1 + SelectionStart - (rowOffset + col); - //Console.WriteLine("{0},{1},{2}", rowOffset + col, SelectionStart, SelectionLength); - Select(rowOffset + col, 0); - SelectedRtf = RtfPrefixForSymbols + TableCharsU[tableCharIndx] + "?}"; - Select(rowOffset + col, lenComment); - //Console.WriteLine("'{0}',{1},{2},{3}", SelectedText, lenComment, SelectionLength, SelectionStart); - //Console.WriteLine("'{0}'", SelectedRtf); - SelectedRtf = SelectedRtf.Replace(" " + charToBeReplaced, ""); - } - } #endregion #region SpellChecker private static bool _DoSpellCheck = true; @@ -3432,15 +2947,12 @@ namespace Volian.Controls.Library } - // the grid uses this to reference the same instance of the spell checker - public C1.Win.C1SpellChecker.C1SpellChecker SpellCheckerInstance - { - get { return C1SpellChecker2; } - } + // the grid uses this to reference the same instance of the spell checker + public C1.Win.C1SpellChecker.C1SpellChecker SpellCheckerInstance => C1SpellChecker2; - // Get or Save our context menu - // This is added to the the spell checker's context menu for a mis-spelled word - private static ContextMenuStrip _ThisContextMenuStrip; + // Get or Save our context menu + // This is added to the the spell checker's context menu for a mis-spelled word + private static ContextMenuStrip _ThisContextMenuStrip; public ContextMenuStrip ThisContextMenuStrip { get { return _ThisContextMenuStrip; } @@ -3492,23 +3004,19 @@ namespace Volian.Controls.Library static void spellcheckWord_Click(object sender, EventArgs e) { - ToolStripMenuItem tsmi = sender as ToolStripMenuItem; - if (tsmi != null) - { - // B2016-242: because this is a static method, the format flag for EditorialSpellCheck cannot be checked - // before setting 'DidEditorialSpellCheck'. But the format flag is checked before the 'DidEditorialSpellCheck' - // is actually used in rtbitem. - DidEditorialSpellCheck = true; - } - } + if (sender is ToolStripMenuItem) + { + // B2016-242: because this is a static method, the format flag for EditorialSpellCheck cannot be checked + // before setting 'DidEditorialSpellCheck'. But the format flag is checked before the 'DidEditorialSpellCheck' + // is actually used in rtbitem. + DidEditorialSpellCheck = true; + } + } - static void tsi2_Click(object sender, EventArgs e) - { - C1SpellChecker2.CheckControl(_ContextMenuStepRTB, true, MySpellCheckDlg); - } + static void tsi2_Click(object sender, EventArgs e) => C1SpellChecker2.CheckControl(_ContextMenuStepRTB, true, MySpellCheckDlg); - // Click event to display our "Edit Menu" (StepRTB context menu) - static void tsi_Click(object sender, EventArgs e) + // Click event to display our "Edit Menu" (StepRTB context menu) + static void tsi_Click(object sender, EventArgs e) { ToolStripMenuItem tsmi = sender as ToolStripMenuItem; _ContextMenuStepRTB.OnOpenContextMenu(sender, new StepRTBLocationEventArgs(tsmi.Owner.Location)); @@ -3544,16 +3052,13 @@ namespace Volian.Controls.Library DidEditorialSpellCheck = MySpellCheckDlg.DidCorrectSpelling; // B2015-024 spell checker in editoral mode return (nBad >= 0); // nBad = -1 means user pressed Cancel button } - - // This allows us to turn off/on the spell check context menu when we toggle in and out of View Mode. - // see btnToggleEditView_Click() in StepTabRibbon.cs - public void SpellCheckContextMenuOn(bool turnOnMenu) - { - C1SpellChecker2.Options.ShowSuggestionsInContextMenu = turnOnMenu; - } - #endregion - #region - public string DoNewLinkInGridCell() + + // This allows us to turn off/on the spell check context menu when we toggle in and out of View Mode. + // see btnToggleEditView_Click() in StepTabRibbon.cs + public void SpellCheckContextMenuOn(bool turnOnMenu) => C1SpellChecker2.Options.ShowSuggestionsInContextMenu = turnOnMenu; + #endregion + #region + public string DoNewLinkInGridCell() { // first find the new link and determine whether it's RO or transition. int indx = Rtf.IndexOf(@"#Link:ReferencedObject:"); @@ -3563,7 +3068,7 @@ namespace Volian.Controls.Library string linkstr = mro.Groups[2].Value; string[] roparts = linkstr.Split(" ".ToCharArray()); ContentRoUsage rousg = null; - int oldid = -1; + int oldid; using (Item itm = MyItemInfo.Get()) { using (RODb rodb = RODb.GetJustRoDb(Convert.ToInt32(roparts[2]))) @@ -3663,29 +3168,18 @@ namespace Volian.Controls.Library Select(sel, 0);// Move cursor to end of LINK Focus(); } - #endregion - #region Debug - private bool _ShowDebug = false; - public bool ShowDebug + #endregion + #region Debug + public bool ShowDebug { get; set; } = false; + private void DebugPrint(string where, string format, params object[] myParams) => DebugPrint(where + string.Format(format, myParams)); + private void DebugPrint(string format, params object[] myParams) { - get { return _ShowDebug; } - set { _ShowDebug = value; } - } - private void DebugPrint(string where, string format, params object[] myParams) - { - DebugPrint(where + string.Format(format, myParams)); - } - private void DebugPrint(string format, params object[] myParams) - { - if (_ShowDebug) + if (ShowDebug) Console.WriteLine(format, myParams); } - private void DebugSelection(string where) - { - DebugPrint(where, ": {0} {1} '{2}'", SelectionStart, SelectionLength, SelectedText); - } - #endregion - private bool _LastWasLeftArrow = false; + private void DebugSelection(string where) => DebugPrint(where, ": {0} {1} '{2}'", SelectionStart, SelectionLength, SelectedText); + #endregion + private bool _LastWasLeftArrow = false; private void StepRTB_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) { if ((e.KeyCode == Keys.Tab) && (!e.Alt && !e.Control)) @@ -3700,41 +3194,26 @@ namespace Volian.Controls.Library } public partial class StepRTBModeChangeEventArgs : EventArgs { - private E_ViewMode _ViewMode; - public E_ViewMode ViewMode + public E_ViewMode ViewMode { get; set; } + public StepRTBModeChangeEventArgs(E_ViewMode vmode) { - get { return _ViewMode; } - set { _ViewMode = value; } - } - public StepRTBModeChangeEventArgs(E_ViewMode vmode) - { - _ViewMode = vmode; + ViewMode = vmode; } } public partial class StepRTBMenuEventArgs { - private string _MenuGroup; - public string MenuGroup + public string MenuGroup { get; set; } + public StepRTBMenuEventArgs(string menuGroup) { - get { return _MenuGroup; } - set { _MenuGroup = value; } - } - public StepRTBMenuEventArgs(string menuGroup) - { - _MenuGroup = menuGroup; + MenuGroup = menuGroup; } } public partial class StepRTBTableWidthEventArgs { - bool _EditMode; - public bool EditMode + public bool EditMode { get; set; } + public StepRTBTableWidthEventArgs(bool editMode) { - get { return _EditMode; } - set { _EditMode = value; } - } - public StepRTBTableWidthEventArgs(bool editMode) - { - _EditMode = editMode; + EditMode = editMode; } } public class StepRTBCursorMovementEventArgs @@ -3745,16 +3224,12 @@ namespace Volian.Controls.Library get { return _CursorLocation; } set { _CursorLocation = value; } } - private E_ArrowKeys _Key; - public E_ArrowKeys Key - { - get { return _Key; } - set { _Key = value; } - } - public StepRTBCursorMovementEventArgs(Point pt, E_ArrowKeys key) + + public E_ArrowKeys Key { get; set; } + public StepRTBCursorMovementEventArgs(Point pt, E_ArrowKeys key) { _CursorLocation = pt; - _Key = key; + Key = key; } } public class StepRTBLocationEventArgs:EventArgs @@ -3772,87 +3247,33 @@ namespace Volian.Controls.Library } public partial class StepRTBRoEventArgs : EventArgs { - private string _ValText; - public string ValText + public string ValText { get; set; } + public string RawValText { get; set; } + public string LinkText { get; set; } + public string ROID { get; set; } + public int RODbID { get; set; } + public StepRTBRoEventArgs(string valtext, string rawvaltext, string linktext, string roid, int rodbid) { - get { return _ValText; } - set { _ValText = value; } - } - private string _RawValText; - public string RawValText - { - get { return _RawValText; } - set { _RawValText = value; } - } - private string _LinkText; - public string LinkText - { - get { return _LinkText; } - set { _LinkText = value; } - } - private string _ROID; - public string ROID - { - get { return _ROID; } - set { _ROID = value; } - } - private int _RODbID; - public int RODbID - { - get { return _RODbID; } - set { _RODbID = value; } - } - public StepRTBRoEventArgs(string valtext, string rawvaltext, string linktext, string roid, int rodbid) - { - _ValText = valtext; - _RawValText = rawvaltext; - _LinkText = linktext; - _ROID = roid; - _RODbID = rodbid; + ValText = valtext; + RawValText = rawvaltext; + LinkText = linktext; + ROID = roid; + RODbID = rodbid; } } #region LinkLocation Class public class LinkLocation { - private int _Start; - public int Start - { - get { return _Start; } - set { _Start = value; } - } - private int _Length; - public int Length - { - get { return _Length; } - set { _Length = value; } - } - public int End - { - get { return _Length + _Start; } - } - private int _StartRtf; - public int StartRtf - { - get { return _StartRtf; } - set { _StartRtf = value; } - } - private int _LengthRtf; - public int LengthRtf - { - get { return _LengthRtf; } - set { _LengthRtf = value; } - } - public int EndRtf - { - get { return _LengthRtf + _StartRtf; } - } - private string _Text; - public string Text - { - get { return _Text; } - set { _Text = value; } - } - private LinkLocation _PreviousLink = null; + public int Start { get; set; } + public int Length { get; set; } + public int End => Length + Start; + + public int StartRtf { get; set; } + public int LengthRtf { get; set; } + public int EndRtf => LengthRtf + StartRtf; + + public string Text { get; set; } + private LinkLocation _PreviousLink = null; public LinkLocation PreviousLink { get { return _PreviousLink; } @@ -3862,42 +3283,23 @@ namespace Volian.Controls.Library value.NextLink = this; } } - private LinkLocation _NextLink = null; - public LinkLocation NextLink + + public LinkLocation NextLink { get; set; } = null; + public int PreviousEnd => PreviousLink == null ? -1 : PreviousLink.End; + public bool StartsBetween => PreviousEnd == Start; + public int NextStart => NextLink == null ? -1 : NextLink.Start; + public bool EndsBetween => NextStart == End; + public LinkLocation(int start, int length, string text, int startRtf, int lengthRtf, LinkLocation previousLink) { - get { return _NextLink; } - set { _NextLink = value; } - } - public int PreviousEnd - { - get { return PreviousLink == null ? -1 : PreviousLink.End; } - } - public bool StartsBetween - { - get { return PreviousEnd == Start; } - } - public int NextStart - { - get { return NextLink == null ? -1 : NextLink.Start; } - } - public bool EndsBetween - { - get { return NextStart == End; } - } - public LinkLocation(int start, int length, string text, int startRtf, int lengthRtf, LinkLocation previousLink) - { - _Start = start; - _Length = length; - _Text = text; - _StartRtf = startRtf; - _LengthRtf = lengthRtf; + Start = start; + Length = length; + Text = text; + StartRtf = startRtf; + LengthRtf = lengthRtf; if (previousLink != null) PreviousLink = previousLink; } - public override string ToString() - { - return (string.Format("{0}, {1}", Start, End)); - } - public void Show(string str) + public override string ToString() => (string.Format("{0}, {1}", Start, End)); + public void Show(string str) { if (PreviousLink != null) Console.WriteLine("LinkLocation: {0}.PreviousLink {1}", str, PreviousLink); diff --git a/PROMS/Volian.Controls.Library/StepRTB.designer.cs b/PROMS/Volian.Controls.Library/StepRTB.designer.cs index b7e7683f..192175c1 100644 --- a/PROMS/Volian.Controls.Library/StepRTB.designer.cs +++ b/PROMS/Volian.Controls.Library/StepRTB.designer.cs @@ -15,7 +15,6 @@ namespace Volian.Controls.Library protected override void Dispose(bool disposing) { if (_Disposed) return; - _CountDisposed++; _Disposed = true; if (disposing && (components != null)) { diff --git a/PROMS/Volian.Controls.Library/StepTabPanel.cs b/PROMS/Volian.Controls.Library/StepTabPanel.cs index a6d501d0..094577a6 100644 --- a/PROMS/Volian.Controls.Library/StepTabPanel.cs +++ b/PROMS/Volian.Controls.Library/StepTabPanel.cs @@ -1,11 +1,5 @@ using System; -using System.ComponentModel; -using System.Collections.Generic; -using System.Diagnostics; -using System.Text; -using System.Drawing; using VEPROMS.CSLA.Library; -using Volian.Controls.Library; using System.Windows.Forms; using JR.Utils.GUI.Forms; @@ -14,45 +8,28 @@ namespace Volian.Controls.Library public partial class StepTabPanel : DevComponents.DotNetBar.PanelDockContainer { #region Private Fields - private DisplayTabControl _MyDisplayTabControl; - private StepTabRibbon _MyStepTabRibbon; - public StepTabRibbon MyStepTabRibbon - { - get { return _MyStepTabRibbon; } - set { _MyStepTabRibbon = value; } - } - private StepPanel _MyStepPanel; - private DisplayTabItem _MyDisplayTabItem; - #endregion - #region Properties - /// - /// Container - /// - public DisplayTabControl MyDisplayTabControl - { - get { return _MyDisplayTabControl; } - //set { _MyDisplayTabControl = value; } - } - /// - /// StepPanel contained in this control. - /// - public Volian.Controls.Library.StepPanel MyStepPanel - { - get { return _MyStepPanel; } - //set { _MyStepPanel = value; } - } - /// - /// related DisplayTabItem - /// - public DisplayTabItem MyDisplayTabItem - { - get { return _MyDisplayTabItem; } - set { _MyDisplayTabItem = value; } - } - /// - /// Currently Selected ItemInfo - /// - public ItemInfo SelectedItemInfo + private readonly DisplayTabControl _MyDisplayTabControl; + + public StepTabRibbon MyStepTabRibbon { get; set; } + private StepPanel _MyStepPanel; + #endregion + #region Properties + /// + /// Container + /// + public DisplayTabControl MyDisplayTabControl => _MyDisplayTabControl; + /// + /// StepPanel contained in this control. + /// + public Volian.Controls.Library.StepPanel MyStepPanel => _MyStepPanel; + /// + /// related DisplayTabItem + /// + public DisplayTabItem MyDisplayTabItem { get; set; } + /// + /// Currently Selected ItemInfo + /// + public ItemInfo SelectedItemInfo { get { return _MyStepPanel.SelectedItemInfo; } set @@ -63,22 +40,18 @@ namespace Volian.Controls.Library FlexibleMessageBox.Show("The selected item is not available in the editor. One possible cause is that the data is 'not editable', check the section properties 'Editable Data' checkbox.", "Inaccessible Data", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } - if (_MyStepPanel.SelectedEditItem != null) - _MyStepPanel.SelectedEditItem.ItemSelect(); + _MyStepPanel.SelectedEditItem?.ItemSelect(); if (!_MyStepPanel.ItemSelectionChangeShown) _MyStepPanel.OnItemSelectedChanged(this, new ItemSelectedChangedEventArgs(_MyStepPanel.SelectedEditItem)); } } - /// - /// Currently Selected EditItem - /// - public EditItem SelectedEditItem - { - get { return _MyStepPanel.SelectedEditItem; } - } - /// - /// Procedure ItemInfo - /// - public ItemInfo MyProcedureItemInfo + /// + /// Currently Selected EditItem + /// + public EditItem SelectedEditItem => _MyStepPanel.SelectedEditItem; + /// + /// Procedure ItemInfo + /// + public ItemInfo MyProcedureItemInfo { get { return _MyStepPanel.MyProcedureItemInfo; } set { _MyStepPanel.MyProcedureItemInfo = value; } @@ -120,14 +93,16 @@ namespace Volian.Controls.Library /// private void SetupStepTabRibbon() { - _MyStepTabRibbon = new StepTabRibbon(_MyDisplayTabControl.IsInEditorialMode); - _MyStepTabRibbon.Dock = System.Windows.Forms.DockStyle.Top; - _MyStepTabRibbon.Location = new System.Drawing.Point(0, 0); - _MyStepTabRibbon.Name = "displayTabRibbon1"; - //_MyTabRibbon.MyDisplayRTB = null; - _MyStepTabRibbon.MyEditItem = null; - this.Controls.Add(_MyStepTabRibbon); - _MyStepTabRibbon.Expanded = _MyDisplayTabControl.RibbonExpanded; + MyStepTabRibbon = new StepTabRibbon(_MyDisplayTabControl.IsInEditorialMode) + { + Dock = System.Windows.Forms.DockStyle.Top, + Location = new System.Drawing.Point(0, 0), + Name = "displayTabRibbon1", + //_MyTabRibbon.MyDisplayRTB = null; + MyEditItem = null + }; + this.Controls.Add(MyStepTabRibbon); + MyStepTabRibbon.Expanded = _MyDisplayTabControl.RibbonExpanded; } /// /// Setup this within control @@ -142,7 +117,6 @@ namespace Volian.Controls.Library /// private void SetupStepPanel() { - //this.Font = new Font("Microsoft Sans Serif", 8.25F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(0))); _MyStepPanel = new Volian.Controls.Library.StepPanel(this.components); this.Controls.Add(_MyStepPanel); // @@ -159,101 +133,73 @@ namespace Volian.Controls.Library _MyStepPanel.ItemClick +=new Volian.Controls.Library.StepPanelEvent(_MyStepPanel_ItemClick); _MyStepPanel.AttachmentClicked += new Volian.Controls.Library.StepPanelAttachmentEvent(_MyStepPanel_AttachmentClicked); _MyStepPanel.ItemSelectedChanged += new ItemSelectedChangedEvent(_MyStepPanel_ItemSelectedChanged); - //_MyStepPanel.ModeChange += new Volian.Controls.Library.StepPanelModeChangeEvent(_MyStepPanel_ModeChange); _MyStepPanel.TabDisplay += new Volian.Controls.Library.StepPanelTabDisplayEvent(_MyStepPanel_TabDisplay); _MyStepPanel.WordSectionClose += new StepPanelWordSectionCloseEvent(_MyStepPanel_WordSectionClose); _MyStepPanel.WordSectionDeleted += new StepPanelWordSectionDeletedEvent(_MyStepPanel_WordSectionDeleted); _MyStepPanel.ItemPasted += new StepPanelItemPastedEvent(_MyStepPanel_ItemPasted); } - - #endregion - #region Event Handlers - private bool _ShowingItem = false; - public bool ShowingItem + + #endregion + #region Event Handlers + public bool ShowingItem { get; set; } = false; + /// + /// Occurs when the user clicks on a StepTabPanel + /// + /// + /// + private void StepTabPanel_Enter(object sender, EventArgs e) { - get { return _ShowingItem; } - set { _ShowingItem = value; } - } - /// - /// Occurs when the user clicks on a StepTabPanel - /// - /// - /// - private void StepTabPanel_Enter(object sender, EventArgs e) - { - if (_ShowingItem) return; + if (ShowingItem) return; // B2019-029: added to save a dirty annotation when the btnsave was not clicked (user just moves to another steprtb but had added annotationi text): if (MyDisplayTabControl.MyAnnotationDetails.AnnotationDirty) MyDisplayTabControl.MyAnnotationDetails.SaveAnnotation(); - _ShowingItem = true; - //if (ItemSelected != null) + ShowingItem = true; _MyStepPanel.ItemShow(); - if (_MyStepPanel.MyStepTabPanel != null) // B2014-024 if MyStepTabPanel is null then we are in the process of closing the procedure in that step panel - _MyStepPanel.MyStepTabPanel.MyStepTabRibbon.SetUpdRoValBtn(_MyStepPanel.MyStepTabPanel.MyStepTabRibbon.NewerRoFst()); - _ShowingItem = false; + // B2014-024 if MyStepTabPanel is null then we are in the process of closing the procedure in that step panel + _MyStepPanel.MyStepTabPanel?.MyStepTabRibbon.SetUpdRoValBtn(_MyStepPanel.MyStepTabPanel.MyStepTabRibbon.NewerRoFst()); + ShowingItem = false; _MyDisplayTabControl.SelectedDisplayTabItem = MyDisplayTabItem; } - /// - /// Occurs when the cursor moves onto or off of a link - /// - /// - /// - void _MyStepPanel_LinkActiveChanged(object sender, StepPanelLinkEventArgs args) + /// + /// Occurs when the cursor moves onto or off of a link + /// + /// + /// + void _MyStepPanel_LinkActiveChanged(object sender, StepPanelLinkEventArgs args) => _MyDisplayTabControl.OnLinkActiveChanged(sender, args); + /// + /// Occurs when the user chooses to add a transition + /// + /// + /// + void _MyStepPanel_LinkInsertTran(object sender, StepPanelLinkEventArgs args) => _MyDisplayTabControl.OnLinkInsertTran(sender, args); + /// + /// Occurs when the user chooses to add an RO + /// + /// + /// + void _MyStepPanel_LinkInsertRO(object sender, StepPanelLinkEventArgs args) => _MyDisplayTabControl.OnLinkInsertRO(sender, args); + /// + /// Occurs when the user chosses to modify a transition + /// + /// + /// + void _MyStepPanel_LinkModifyTran(object sender, StepPanelLinkEventArgs args) => _MyDisplayTabControl.OnLinkModifyTran(sender, args); + /// + /// Occurs when the user chooses to Modify an RO + /// + /// + /// + void _MyStepPanel_LinkModifyRO(object sender, StepPanelLinkEventArgs args) => _MyDisplayTabControl.OnLinkModifyRO(sender, args); + /// + /// Occurs when the Selected Item changes + /// + /// + /// + void _MyStepPanel_ItemSelectedChanged(object sender, ItemSelectedChangedEventArgs args) { - _MyDisplayTabControl.OnLinkActiveChanged(sender, args); - } - /// - /// Occurs when the user chooses to add a transition - /// - /// - /// - void _MyStepPanel_LinkInsertTran(object sender, StepPanelLinkEventArgs args) - { - _MyDisplayTabControl.OnLinkInsertTran(sender, args); - } - /// - /// Occurs when the user chooses to add an RO - /// - /// - /// - void _MyStepPanel_LinkInsertRO(object sender, StepPanelLinkEventArgs args) - { - _MyDisplayTabControl.OnLinkInsertRO(sender, args); - } - /// - /// Occurs when the user chosses to modify a transition - /// - /// - /// - void _MyStepPanel_LinkModifyTran(object sender, StepPanelLinkEventArgs args) - { - _MyDisplayTabControl.OnLinkModifyTran(sender, args); - } - /// - /// Occurs when the user chooses to Modify an RO - /// - /// - /// - void _MyStepPanel_LinkModifyRO(object sender, StepPanelLinkEventArgs args) - { - _MyDisplayTabControl.OnLinkModifyRO(sender, args); - } - /// - /// Occurs when the Selected Item changes - /// - /// - /// - void _MyStepPanel_ItemSelectedChanged(object sender, ItemSelectedChangedEventArgs args) - { - _MyStepTabRibbon.MyEditItem = args.MyEditItem; + MyStepTabRibbon.MyEditItem = args.MyEditItem; _MyDisplayTabControl.OnItemSelectedChanged(sender, args); } - // Occurs when the Mode Changes - //void _MyStepPanel_ModeChange(object sender, StepRTBModeChangeEventArgs args) - //{ - // _MyDisplayTabControl.OnModeChange(sender, args); - //} - /// /// Occurs when the user clicks on the Attachment Expander /// @@ -302,27 +248,12 @@ namespace Volian.Controls.Library else Console.WriteLine("Bring Up roeditor"); //TODO: Need to bring up roeditor or infopanel } - void _MyStepPanel_TabDisplay(object sender, StepPanelTabDisplayEventArgs args) - { - _MyDisplayTabControl.OnPanelTabDisplay(sender, args); - } - void _MyStepPanel_WordSectionClose(object sender, WordSectionEventArgs args) - { - _MyDisplayTabControl.OnWordSectionClose(sender, args); - } - void _MyStepPanel_WordSectionDeleted(object sender, WordSectionEventArgs args) - { - _MyDisplayTabControl.OnWordSectionDeleted(sender, args); - } - void _MyStepPanel_ItemPasted(object sender, vlnTreeItemInfoPasteEventArgs args) - { - _MyDisplayTabControl.OnItemPaste(sender, args); - } - public override string ToString() - { - return string.Format("StepTabPanel Procedure Item {0} {1}", - MyDisplayTabItem.MyItemInfo.ItemID, MyDisplayTabItem.MyItemInfo.DisplayNumber); - } - #endregion - } + void _MyStepPanel_TabDisplay(object sender, StepPanelTabDisplayEventArgs args) => _MyDisplayTabControl.OnPanelTabDisplay(sender, args); + void _MyStepPanel_WordSectionClose(object sender, WordSectionEventArgs args) => _MyDisplayTabControl.OnWordSectionClose(sender, args); + void _MyStepPanel_WordSectionDeleted(object sender, WordSectionEventArgs args) => _MyDisplayTabControl.OnWordSectionDeleted(sender, args); + void _MyStepPanel_ItemPasted(object sender, vlnTreeItemInfoPasteEventArgs args) => _MyDisplayTabControl.OnItemPaste(sender, args); + public override string ToString() => string.Format("StepTabPanel Procedure Item {0} {1}", + MyDisplayTabItem.MyItemInfo.ItemID, MyDisplayTabItem.MyItemInfo.DisplayNumber); + #endregion + } } diff --git a/PROMS/Volian.Controls.Library/StepTabRibbon.cs b/PROMS/Volian.Controls.Library/StepTabRibbon.cs index 7baebb44..f3ba9b2d 100644 --- a/PROMS/Volian.Controls.Library/StepTabRibbon.cs +++ b/PROMS/Volian.Controls.Library/StepTabRibbon.cs @@ -1,10 +1,8 @@ using System; using System.Collections.Generic; -using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Text; -using System.Data; using System.Text; using System.Windows.Forms; using System.IO; @@ -25,25 +23,10 @@ namespace Volian.Controls.Library public partial class StepTabRibbon : UserControl { - private static string _SpecifiedVisioPath = null; - public static string SpecifiedVisioPath - { - get { return StepTabRibbon._SpecifiedVisioPath; } - set { StepTabRibbon._SpecifiedVisioPath = value; } - } - private static bool _PastePlainTextSetting = false; - public static bool PastePlainTextSetting - { - get { return _PastePlainTextSetting; } - set { _PastePlainTextSetting = value; } - } - private static bool _PasteNoReturnsSetting = false; - public static bool PasteNoReturnsSetting - { - get { return _PasteNoReturnsSetting; } - set { _PasteNoReturnsSetting = value; } - } - private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); + public static string SpecifiedVisioPath { get; set; } = null; + public static bool PastePlainTextSetting { get; set; } = false; + public static bool PasteNoReturnsSetting { get; set; } = false; + private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #region Properties private bool EnableROEdit; private VlnFlexGrid MyFlexGrid @@ -79,15 +62,13 @@ namespace Volian.Controls.Library } else MyStepRTB = null; - //if (rtabChgId.Visible) - // txtBxChgId.Text = (this.Parent as StepTabPanel).MyDisplayTabControl.ChgId; } } public void SetChangeId(string chgid, ItemInfo ii) { txtBxChgId.Text = chgid; - rtabChgId.Visible = (ii != null) ? ii.ActiveFormat.PlantFormat.FormatData.ProcData.ChangeBarData.ChangeIds : false; + rtabChgId.Visible = (ii != null) && ii.ActiveFormat.PlantFormat.FormatData.ProcData.ChangeBarData.ChangeIds; } // added jcb 20121221 to support set ro from word doc private ROFSTLookup MyLookup; @@ -99,9 +80,8 @@ namespace Volian.Controls.Library if (_Mydvi != null) return _Mydvi; if (_MyEditItem != null) { - ItemInfo procInfo = _MyEditItem.MyItemInfo.MyProcedure as ItemInfo; - if (procInfo == null) return null; - _Mydvi = procInfo.ActiveParent as DocVersionInfo; + if (!(_MyEditItem.MyItemInfo.MyProcedure is ItemInfo procInfo)) return null; + _Mydvi = procInfo.ActiveParent as DocVersionInfo; // added jcb 20121221 to support set ro from word doc if (_Mydvi.DocVersionAssociations != null && _Mydvi.DocVersionAssociations.Count > 0) MyLookup = _Mydvi.DocVersionAssociations[0].MyROFst.GetROFSTLookup(_Mydvi); @@ -121,28 +101,15 @@ namespace Volian.Controls.Library return null; } } - private static UserInfo _MyUserInfo = null; - public static UserInfo MyUserInfo - { - get { return _MyUserInfo; } - set { _MyUserInfo = value; } - } - private static SessionInfo _MySessionInfo; - public static SessionInfo MySessionInfo - { - get { return _MySessionInfo; } - set { _MySessionInfo = value; } - } - private DevComponents.DotNetBar.ButtonItem _DefaultContextMenu; + public static UserInfo MyUserInfo { get; set; } = null; + public static SessionInfo MySessionInfo { get; set; } + private DevComponents.DotNetBar.ButtonItem _DefaultContextMenu; - public void ClearContextMenu() - { - _ContextMenuBar.SetContextMenuEx(_MyStepRTB, null); - } + public void ClearContextMenu() => _ContextMenuBar.SetContextMenuEx(_MyStepRTB, null); - #region Save ROs from Word Document jcb 20121221 - private string MyLookupData; + #region Save ROs from Word Document jcb 20121221 + private string MyLookupData; private Dictionary MyAvailableROs; public void SetContextMenu(object sender) { @@ -157,14 +124,14 @@ namespace Volian.Controls.Library btnCMPaste.Enabled = false; btnCMPasteText.Enabled = false; btnCMRO.Enabled = false; - bool isInBuff = false; + bool isInBuff; try // image in clipboard - for 'paste' { System.Drawing.Image img = Clipboard.GetImage(); isInBuff = img != null; } - catch (Exception ex) - { + catch (Exception) + { isInBuff = false; } btnCMPasteImage.Enabled = isInBuff; @@ -200,7 +167,7 @@ namespace Volian.Controls.Library foreach (DVEnhancedDocument dved in dveds) { string buttonName = string.Format("btnEnhancedTo{0}", dved.Type); - DevComponents.DotNetBar.ButtonItem biEnhanced = new DevComponents.DotNetBar.ButtonItem(buttonName, "Go To " + dved.Name + " Document"); + DevComponents.DotNetBar.ButtonItem biEnhanced = new DevComponents.DotNetBar.ButtonItem(buttonName, $"Go To {dved.Name} Document"); biEnhanced.Click += btnEnhancedGoTo_Click; myButtonItem.SubItems.Add(biEnhanced); existingEnhancedButtons.Add(biEnhanced.Name); @@ -209,7 +176,7 @@ namespace Volian.Controls.Library { // add unlink buttons: buttonName = string.Format("btnEnhancedUnlink{0}", dved.Type); - biEnhanced = new DevComponents.DotNetBar.ButtonItem(buttonName, "Unlink " + dved.Name + " Document"); + biEnhanced = new DevComponents.DotNetBar.ButtonItem(buttonName, $"Unlink {dved.Name} Document"); biEnhanced.Click += btnEnhancedGoTo_Click; biEnhanced.BeginGroup = true; // C2019=003: add separator between go to & unlink myButtonItem.SubItems.Add(biEnhanced); @@ -241,7 +208,7 @@ namespace Volian.Controls.Library if (biEnhanced.Name.StartsWith("btnEnhancedTo")) { biEnhanced.Visible = true; - biEnhanced.Text = "Go To " + dveds.GetByType(ed.Type).Name + " Document"; + biEnhanced.Text = $"Go To {dveds.GetByType(ed.Type).Name} Document"; biEnhanced.Tag = ed.ItemID; itemHasLink = true; break; @@ -376,9 +343,11 @@ namespace Volian.Controls.Library DevComponents.DotNetBar.BaseItem btnSaveRO = null; if (!myButtonItem.SubItems.Contains("btnSaveRO")) { - btnSaveRO = new DevComponents.DotNetBar.ButtonItem("btnSaveRO", "Save RO"); - btnSaveRO.Visible = false; - myButtonItem.SubItems.Add(btnSaveRO); + btnSaveRO = new DevComponents.DotNetBar.ButtonItem("btnSaveRO", "Save RO") + { + Visible = false + }; + myButtonItem.SubItems.Add(btnSaveRO); } else btnSaveRO = myButtonItem.SubItems["btnSaveRO"]; @@ -393,15 +362,19 @@ namespace Volian.Controls.Library btnSaveRO.Text = "Save RO"; foreach (string k in MyAvailableROs.Keys) { - DevComponents.DotNetBar.BaseItem btn = new DevComponents.DotNetBar.ButtonItem(k, MyAvailableROs[k]); - btn.Tag = MyAvailableROs[k]; - btn.Click += new EventHandler(SaveRO_Click); + DevComponents.DotNetBar.BaseItem btn = new DevComponents.DotNetBar.ButtonItem(k, MyAvailableROs[k]) + { + Tag = MyAvailableROs[k] + }; + btn.Click += new EventHandler(SaveRO_Click); btnSaveRO.SubItems.Add(btn); if (MyStepRTB.SelectedText.Length > 0 && MyStepRTB.SelectedText.ToLower() != MyAvailableROs[k].ToLower()) { - btn = new DevComponents.DotNetBar.ButtonItem("_" + k, MyAvailableROs[k] + " with Annotation"); - btn.Tag = MyAvailableROs[k]; - btn.Click += new EventHandler(SaveROWithAnnotation_Click); + btn = new DevComponents.DotNetBar.ButtonItem($"_{k}", $"{MyAvailableROs[k]} with Annotation") + { + Tag = MyAvailableROs[k] + }; + btn.Click += new EventHandler(SaveROWithAnnotation_Click); btnSaveRO.SubItems.Add(btn); } } @@ -411,9 +384,11 @@ namespace Volian.Controls.Library { btnSaveRO.SubItems.Clear(); btnSaveRO.Text = "No RO Found"; - DevComponents.DotNetBar.BaseItem btn = new DevComponents.DotNetBar.ButtonItem("btnRONotFound", "Create Annotation"); - btn.Tag = string.Format("Text '{0}' has no corresponding RO", MyStepRTB.SelectedText); - btn.Click += new EventHandler(NoROFound_Click); + DevComponents.DotNetBar.BaseItem btn = new DevComponents.DotNetBar.ButtonItem("btnRONotFound", "Create Annotation") + { + Tag = string.Format("Text '{0}' has no corresponding RO", MyStepRTB.SelectedText) + }; + btn.Click += new EventHandler(NoROFound_Click); btnSaveRO.SubItems.Add(btn); btnSaveRO.Visible = true; } @@ -427,13 +402,6 @@ namespace Volian.Controls.Library MyAvailableROs = new Dictionary(); if (Mydvi != null) { - #region force arp without hi or lo jcb 20121221 - //if (data == "") - //{ - // data = data.Replace("-LO1", ""); - // Console.WriteLine("force null roc"); - //} - #endregion string accPageID = GetAccPageID(data); ROFSTLookup.rochild? roc = MyLookup.GetROChildByAccPageID(accPageID, Mydvi.DocVersionConfig.RODefaults_setpointprefix, Mydvi.DocVersionConfig.RODefaults_graphicsprefix); @@ -456,7 +424,7 @@ namespace Volian.Controls.Library //see if arp then try HI 1,2,3 and LO 1,2,3 if (accPageID.StartsWith("ARP")) { - string tmpAccPageID = string.Empty; + string tmpAccPageID; //try HI1,2,3 string suffix = "-HI"; for (int i = 1; i < 4; i++) @@ -502,7 +470,7 @@ namespace Volian.Controls.Library // // txt = txt.Replace(" {0} {1}", padroid, MyLookup.MyDocVersionInfo.DocVersionAssociations[0].MyROFst.MyRODb.RODbID); // Resolve symbols and scientific notation in the RO return value string valtxt = MyLookup.GetTranslatedRoValue(padroid, MyStepRTB.MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.ConvertCaretToDelta, MyStepRTB.MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.UseTildaPoundCharsForSuperSubScriptInROValues, @@ -581,7 +549,7 @@ 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 = (myroid.Length <= 12) ? myroid + "0000" : myroid; + string padroid = (myroid.Length <= 12) ? $"{myroid}0000" : myroid; string linktxt = string.Format(@"#Link:ReferencedObject: {0} {1}", padroid, MyLookup.MyDocVersionInfo.DocVersionAssociations[0].MyROFst.MyRODb.RODbID); // Resolve symbols and scientific notation in the RO return value string valtxt = MyLookup.GetTranslatedRoValue(padroid, MyStepRTB.MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.ConvertCaretToDelta, MyStepRTB.MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.UseTildaPoundCharsForSuperSubScriptInROValues, false, MyStepRTB.MyItemInfo); //ConvertSymbolsAndStuff(selectedChld.value); @@ -620,16 +588,9 @@ namespace Volian.Controls.Library } private int _MyLastFormatID = -1; private StepRTB _MyStepRTB; - private static int _OringFlg; - public static int OringFlg - { - get { return _OringFlg; } - set - { - _OringFlg = value; - } - } - public StepRTB MyStepRTB + + public static int OringFlg { get; set; } + public StepRTB MyStepRTB { get { return _MyStepRTB; } set @@ -667,14 +628,8 @@ namespace Volian.Controls.Library default: break; } - // The following two lines were replaced by the third line so that the Ribbon KeyTips will work properly. - // ex. Positon on a substep, press , to list the substep types - //_MyStepRTB.MouseUp += new MouseEventHandler(_MyStepRTB_MouseUp); //+= new MouseEventHandler(MyStepRTB_SelectionChanged); - //_MyStepRTB.KeyUp += new KeyEventHandler(_MyStepRTB_KeyUp); //+= new KeyEventHandler(MyStepRTB_SelectionChanged); _MyStepRTB.SelectionChanged += new EventHandler(_MyStepRTB_SelectionChanged); - //_MyStepRTB.ModeChange += new StepRTBModeChangeEvent(_MyStepRTB_ModeChange); if (_MyEditItem != null) _MyEditItem.Leave += new EventHandler(_MyEditItem_Leave); - //_MyStepRTB.Leave += new EventHandler(_MyStepRTB_Leave); _MyStepRTB.LinkChanged += new StepRTBLinkEvent(_MyStepRTB_LinkChanged); _MyStepRTB.TextChanged += new EventHandler(_MyStepRTB_TextChanged); if (MyFlexGrid != null) @@ -712,11 +667,8 @@ namespace Volian.Controls.Library return; } BuildSymbolGallery(sl, galleryContainerSymbolsCM, galleryContainerSymbolsCM3, galleryContainerSymbolsGrid, galleryContainerSymbolsCM4); - //BuildSymbolGallery(sl, galleryContainerSymbolsCM); - //BuildSymbolGallery(sl, galleryContainerSymbolsCM3); - //BuildSymbolGallery(sl, galleryContainerSymbolsGrid); } - SetButtonAndMenuEnabling(true); + SetButtonAndMenuEnabling(); SetStepButtonAndMenuEnabling(true); SetMenuEnablingForObjectsWOText(); _MyLastFormatID = MyItemInfo.ActiveFormat.FormatID; @@ -747,20 +699,8 @@ namespace Volian.Controls.Library // is only used for the Create Pdf button now - code has changed for any other use. bool allow = (_MyStepRTB.TextLength > 0); - //// turn ribbon items on/off base on whether there is text in the edit window - //rbnSiblings.Enabled = rbnParagraph.Enabled = rbnStepParts.Enabled = allow; - //// only turn on the Insert Before/After and the CopyStep buttons if on a step part - ////btnInsAftH.Enabled = btnInsBefH.Enabled = btnInsAfter.Enabled = btnInsBefore.Enabled = btnCpyStp.Enabled = - //// allow && !(MyItemInfo.IsProcedure || MyItemInfo.IsSection || MyItemInfo.IsFigure || MyItemInfo.IsTable || MyItemInfo.IsRNOPart); btnPdfCreate.Enabled = allow || (MyFlexGrid != null); // allways allow if on a table even if table cell is empty - //// toggle context menus used with the shortcut key - //btnCMInsHLS.Enabled = btnCMInsRNO.Enabled = btnCMInsSubStps.Enabled = btnCMInsCaution.Enabled = - // btnCMInsNote.Enabled = btnCMInsTable.Enabled = btnCMInsFigure.Enabled = allow; - // C2014-009 Commented out to allow for inserting Note/Caution - // if in Calvert Alarms Condition/Response, disable insert of Cautions and Notes - //if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm) - //btnInsCaut.Enabled = btnInsNote.Enabled = btnCMInsCaution.Enabled = btnCMInsNote.Enabled = allow && !MyItemInfo.IsInCalvertConditionResponse; // C2021 - 027: Procedure level PC/PC - if text changed, i.e. applicability may have changed, redo the print menus if (MyItemInfo != null && MyItemInfo.MyDocVersion.MultiUnitCount > 1) SetParentChildCreatePDFButton(MyItemInfo.MyDocVersion.UnitNames, MyItemInfo); @@ -778,16 +718,10 @@ namespace Volian.Controls.Library if (MyFlexGrid.Selection.c1 >= MyFlexGrid.Cols.Count || MyFlexGrid.Selection.r1 >= MyFlexGrid.Rows.Count) return; if ((MyEditItem as GridItem).Initializing) return; - //C1.Win.C1FlexGrid.CellRange cr = MyFlexGrid.GetEvenSelection(); - //rbnBorderSelectionPanel.InitializeBorder(MyFlexGrid.MyBorders, cr.r1, cr.c1, cr.r2, cr.c2); rbnBorderSelectionPanel.InitializeBorder(MyFlexGrid, MyFlexGrid.Selection); } void _MyEditItem_Leave(object sender, EventArgs e) { - // The following two lines were replaced by the third line so that the Ribbon KeyTips will work properly. - // ex. Positon on a substep, press , to list the substep types - //_MyStepRTB.KeyUp -=new KeyEventHandler(_MyStepRTB_KeyUp); - //_MyStepRTB.MouseUp -= new MouseEventHandler(_MyStepRTB_MouseUp); if (_MyEditItem != null) { _MyEditItem.Leave -= new EventHandler(_MyEditItem_Leave); @@ -805,38 +739,26 @@ namespace Volian.Controls.Library MyFlexGrid.SelChange -= new EventHandler(MyFlexGrid_SelChange); } } - public bool SiblingsButtonsEnabled + + // turn ribbon items on/off base on whether there is text in the edit window + public bool SiblingsButtonsEnabled + { + set => rbnSiblings.Enabled = rbnParagraph.Enabled = rbnStepParts.Enabled = value; + } + // only turn on the Insert Before/After and the CopyStep buttons if on a step part + public bool InsertButtonsEnabled + { + set => btnInsAftH.Enabled = btnInsBefH.Enabled = btnInsAfter.Enabled = btnInsBefore.Enabled = btnCpyStp.Enabled = value; + } + public void SetCopyStepButton(bool val) => btnCpyStp.Enabled = val; + void _MyEditItem_Enter(object sender, EventArgs e) { - set - { - // turn ribbon items on/off base on whether there is text in the edit window - rbnSiblings.Enabled = rbnParagraph.Enabled = rbnStepParts.Enabled =value; - } - } - public bool InsertButtonsEnabled - { - set - { - // only turn on the Insert Before/After and the CopyStep buttons if on a step part - btnInsAftH.Enabled = btnInsBefH.Enabled = btnInsAfter.Enabled = btnInsBefore.Enabled = btnCpyStp.Enabled = value; - } - } - public void SetCopyStepButton(bool val) - { - btnCpyStp.Enabled = val; - } - void _MyEditItem_Enter(object sender, EventArgs e) - { - // The following two lines were replaced by the third line so that the Ribbon KeyTips will work properly. - // ex. Positon on a substep, press , to list the substep types - //_MyStepRTB.KeyUp -=new KeyEventHandler(_MyStepRTB_KeyUp); - //_MyStepRTB.MouseUp -= new MouseEventHandler(_MyStepRTB_MouseUp); + // Positon on a substep, press , to list the substep types if (_MyEditItem != null) { _MyEditItem.Leave += new EventHandler(_MyEditItem_Leave); _MyEditItem.Enter -= new EventHandler(_MyEditItem_Enter); } - //_MyStepRTB.Leave -= new EventHandler(_MyStepRTB_Leave); if (_MyStepRTB != null) { _MyStepRTB.LinkChanged += new StepRTBLinkEvent(_MyStepRTB_LinkChanged); @@ -882,7 +804,7 @@ namespace Volian.Controls.Library private int lastLength = -1; private string lastText = null; // B2019-161 When tracking timing time this action - private static VolianTimer _TimeActivity = new VolianTimer("StepTabRibbon.cs _MyStepRTB_SelectionChanged",837); + private static readonly VolianTimer _TimeActivity = new VolianTimer("StepTabRibbon.cs _MyStepRTB_SelectionChanged",837); void _MyStepRTB_SelectionChanged(object sender, EventArgs e) { @@ -895,44 +817,29 @@ namespace Volian.Controls.Library lastStart = _MyStepRTB.SelectionStart; lastLength = _MyStepRTB.SelectionLength; lastText = _MyStepRTB.SelectedText; - SetButtonAndMenuEnabling(false); + SetButtonAndMenuEnabling(); _TimeActivity.Close(); } - //void _MyStepRTB_MouseUp(object sender, MouseEventArgs e) - //{ - // //SetButtonAndMenuEnabling(false); - //} + private Bitmap createTextBitmap(char ch) => createTextBitmap(ch, new Font("FreeMono", 18, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel)); - //void _MyStepRTB_KeyUp(object sender, KeyEventArgs e) - //{ - // //SetButtonAndMenuEnabling(false); - //} - private Bitmap createTextBitmap(char ch) - { - return createTextBitmap(ch, new Font("FreeMono", 18, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel)); - } - - private Bitmap createTextBitmap(char ch, Font objFont) + private Bitmap createTextBitmap(char ch, Font objFont) { string txt = string.Format("{0}", ch); Bitmap objBmpImage = new Bitmap(1, 1); - int intWidth = 0; - int intHeight = 0; + // Create the Font object for the image text drawing. + // later on, we could add logic to use either FreeMono or Arial Unicode MS based on the format being used + // but for now, we are going to use FreeMono to create the symbol list - // Create the Font object for the image text drawing. - // later on, we could add logic to use either FreeMono or Arial Unicode MS based on the format being used - // but for now, we are going to use FreeMono to create the symbol list + // Create a graphics object to measure the text's width and height. + Graphics objGraphics = Graphics.FromImage(objBmpImage); - // Create a graphics object to measure the text's width and height. - Graphics objGraphics = Graphics.FromImage(objBmpImage); + // This is where the bitmap size is determined. + int intWidth = (int)objGraphics.MeasureString(txt, objFont).Width; + int intHeight = (int)objGraphics.MeasureString(txt, objFont).Height; - // This is where the bitmap size is determined. - intWidth = (int)objGraphics.MeasureString(txt, objFont).Width; - intHeight = (int)objGraphics.MeasureString(txt, objFont).Height; - - // Create the bmpImage again with the correct size for the text and font. - objBmpImage = new Bitmap(objBmpImage, new Size(intWidth, intHeight)); + // Create the bmpImage again with the correct size for the text and font. + objBmpImage = new Bitmap(objBmpImage, new Size(intWidth, intHeight)); // Add the colors to the new bitmap. objGraphics = Graphics.FromImage(objBmpImage); @@ -953,16 +860,16 @@ namespace Volian.Controls.Library // get an image of the symbol character // found the we cannot change the font being used for the button text Bitmap symCharBtmp = createTextBitmap((char)sym.Unicode); - DevComponents.DotNetBar.ButtonItem btn = new DevComponents.DotNetBar.ButtonItem(); - btn.Image = symCharBtmp; - //btn.Text = string.Format("{0}", (char)sym.Unicode); + DevComponents.DotNetBar.ButtonItem btn = new DevComponents.DotNetBar.ButtonItem + { + Image = symCharBtmp, - // to name button use unicode rather than desc, desc may have spaces or odd chars - btn.Name = "btn" + sym.Unicode.ToString(); - btn.Tooltip = sym.Desc; - btn.Tag = string.Format(@"{0}", sym.Unicode); - //btn.FontBold = true; - btn.Click += new System.EventHandler(btnSym_Click); + // to name button use unicode rather than desc, desc may have spaces or odd chars + Name = $"btn{sym.Unicode}", + Tooltip = sym.Desc, + Tag = string.Format(@"{0}", sym.Unicode) + }; + btn.Click += new System.EventHandler(btnSym_Click); galleryContainerSymbols.SubItems.Add(btn); DevComponents.DotNetBar.ButtonItem btnCM1 = GetCMButton(sym); btnCM1.Image = symCharBtmp; @@ -985,19 +892,15 @@ namespace Volian.Controls.Library private static DevComponents.DotNetBar.ButtonItem GetCMButton(Symbol sym) { - DevComponents.DotNetBar.ButtonItem btnCM3 = new DevComponents.DotNetBar.ButtonItem(); - //btnCM3.Text = string.Format("{0}", (char)sym.Unicode); - // to name button use unicode rather than desc, desc may have spaces or odd chars - btnCM3.Name = "btnCM" + sym.Unicode.ToString(); - btnCM3.Tooltip = sym.Desc; - btnCM3.Tag = string.Format(@"{0}", sym.Unicode); - //btnCM3.FontBold = true; - return btnCM3; + DevComponents.DotNetBar.ButtonItem btnCM3 = new DevComponents.DotNetBar.ButtonItem + { + // to name button use unicode rather than desc, desc may have spaces or odd chars + Name = $"btnCM{sym.Unicode}", + Tooltip = sym.Desc, + Tag = string.Format(@"{0}", sym.Unicode) + }; + return btnCM3; } - //void _MyStepRTB_ModeChange(object sender, StepRTBModeChangeEventArgs args) - //{ - // SetButtonAndMenuEnabling(true); - //} #region Constructor public StepTabRibbon(bool? IsInEditorialMode = false) { @@ -1034,11 +937,8 @@ namespace Volian.Controls.Library public void SetEditorialMode(bool mode) => btnEditorialMode.Checked = btnCMEditorialMode.Checked = mode; - void _RibbonControl_SizeChanged(object sender, EventArgs e) - { - this.Size = _RibbonControl.Size; - } - public bool Expanded + void _RibbonControl_SizeChanged(object sender, EventArgs e) => this.Size = _RibbonControl.Size; + public bool Expanded { get { return _RibbonControl.Expanded; } set { _RibbonControl.Expanded = value; } @@ -1071,25 +971,13 @@ namespace Volian.Controls.Library } } public event StepTabRibbonEvent ContActionSummaryRequest; - private void OnContActionSummaryRequest(StepTabRibbonEventArgs args) - { - if (ContActionSummaryRequest != null) - ContActionSummaryRequest(this, args); - } - // F2022-024 Time Critical Action Summary - public event StepTabRibbonEvent TimeCriticalActionSummaryRequest; - private void OnTimeCriticalActionSummaryRequest(StepTabRibbonEventArgs args) - { - if (TimeCriticalActionSummaryRequest != null) - TimeCriticalActionSummaryRequest(this, args); - } - public event StepTabRibbonEvent AddProcToDVInTree; - private void OnAddProcToDVInTree(StepTabRibbonEventArgs args) - { - if (AddProcToDVInTree != null) - AddProcToDVInTree(this, args); - } - void _MyStepRTB_LinkChanged(object sender, StepPanelLinkEventArgs args) + private void OnContActionSummaryRequest(StepTabRibbonEventArgs args) => ContActionSummaryRequest?.Invoke(this, args); + // F2022-024 Time Critical Action Summary + public event StepTabRibbonEvent TimeCriticalActionSummaryRequest; + private void OnTimeCriticalActionSummaryRequest(StepTabRibbonEventArgs args) => TimeCriticalActionSummaryRequest?.Invoke(this, args); + public event StepTabRibbonEvent AddProcToDVInTree; + private void OnAddProcToDVInTree(StepTabRibbonEventArgs args) => AddProcToDVInTree?.Invoke(this, args); + void _MyStepRTB_LinkChanged(object sender, StepPanelLinkEventArgs args) { // do all Transition and ReferencedObject menu items/buttons based on whether a 'link is selected' and the link type. SetupGoToButton(); @@ -1124,10 +1012,7 @@ namespace Volian.Controls.Library } void _MyStepRTB_Leave(object sender, EventArgs e) { - // The following two lines were replaced by the third line so that the Ribbon KeyTips will work properly. - // ex. Positon on a substep, press , to list the substep types - //_MyStepRTB.KeyUp -=new KeyEventHandler(_MyStepRTB_KeyUp); - //_MyStepRTB.MouseUp -= new MouseEventHandler(_MyStepRTB_MouseUp); + // Positon on a substep, press , to list the substep types _MyStepRTB.SelectionChanged -= new EventHandler(_MyStepRTB_SelectionChanged); _MyStepRTB.Leave -= new EventHandler(_MyStepRTB_Leave); _MyStepRTB.LinkChanged -= new StepRTBLinkEvent(_MyStepRTB_LinkChanged); @@ -1153,7 +1038,7 @@ namespace Volian.Controls.Library string tabOrFigType = (insdata.Length == 3) ? insdata[2] : null; // if CautionNoteOrder format variable is set then use it to determine the placement of the // Caution, Note, Warning, or Message (calvert format) - if (cautNoteOrder != null && ("," + cautNoteOrder + ",").Contains("," + (contenttype % 10000).ToString() + ",") && (_MyEditItem.MyItemInfo.Cautions != null || _MyEditItem.MyItemInfo.Notes != null)) + if (cautNoteOrder != null && ($",{cautNoteOrder},").Contains($",{contenttype % 10000},") && (_MyEditItem.MyItemInfo.Cautions != null || _MyEditItem.MyItemInfo.Notes != null)) { EditItem stepBefore = FindStepBefore(cautNoteOrder, contenttype); if (stepBefore != null) @@ -1161,8 +1046,7 @@ namespace Volian.Controls.Library else { EditItem stepAfter = FindStepAfter(cautNoteOrder, contenttype); - if (stepAfter != null) - stepAfter.AddSiblingBefore((int?)contenttype, true); + stepAfter?.AddSiblingBefore((int?)contenttype, true); } } // if from type == 0, we've inserted a hls. @@ -1252,17 +1136,17 @@ namespace Volian.Controls.Library // the following launches the equation editor based on registry setting: private static string GetEqnEdt() { - string retval = null; + string retval; try { RegistryKey key = Registry.ClassesRoot; string rootName = key.Name; - string curVer = GetDefaultKeyValue(key.Name + "\\Equation\\CurVer"); - string clsid = GetDefaultKeyValue(key.Name + "\\" + curVer + "\\CLSID"); - retval = GetDefaultKeyValue(key.Name + "\\CLSID\\" + clsid + "\\LocalServer32"); + string curVer = GetDefaultKeyValue($"{key.Name}\\Equation\\CurVer"); + string clsid = GetDefaultKeyValue($"{key.Name}\\{curVer}\\CLSID"); + retval = GetDefaultKeyValue($"{key.Name}\\CLSID\\{clsid}\\LocalServer32"); } - catch (Exception ex) - { + catch (Exception) + { _MyLog.WarnFormat("Equation Editor is not correctly configured in the registry."); string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); folderPath += @"\Common Files\Microsoft Shared\EQUATION\EQNEDT32.EXE"; @@ -1284,16 +1168,16 @@ namespace Volian.Controls.Library // B2018-038 MathType Replacement for EQNEDT32.EXE private static string GetMathType() { - string retval = null; + string retval; try { RegistryKey key = Registry.ClassesRoot; string rootName = key.Name; - string clsid = GetDefaultKeyValue(key.Name + "\\DSEquations\\CLSID"); - retval = GetDefaultKeyValue(key.Name + "\\CLSID\\" + clsid + "\\LocalServer32"); + string clsid = GetDefaultKeyValue($"{key.Name}\\DSEquations\\CLSID"); + retval = GetDefaultKeyValue($"{key.Name}\\CLSID\\{clsid}\\LocalServer32"); } - catch (Exception ex) - { + catch (Exception) + { _MyLog.WarnFormat("MathType Equation Editor is not correctly configured in the registry."); string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); folderPath += @"\MathType\MathType.EXE"; @@ -1315,7 +1199,7 @@ namespace Volian.Controls.Library private static string GetVisio() // Added support for Visio { - string retval = _SpecifiedVisioPath; // use the Visio path specified by the user + string retval = SpecifiedVisioPath; // use the Visio path specified by the user if (!string.IsNullOrEmpty(retval)) { @@ -1333,8 +1217,8 @@ namespace Volian.Controls.Library try { RegistryKey regVersionString = Registry.ClassesRoot.OpenSubKey("Visio.Drawing\\CurVer"); - RegistryKey regClassId = Registry.ClassesRoot.OpenSubKey(regVersionString.GetValue("") + "\\CLSID"); - RegistryKey regInstallPath = Registry.ClassesRoot.OpenSubKey("CLSID\\" + regClassId.GetValue("") + "\\LocalServer32"); + RegistryKey regClassId = Registry.ClassesRoot.OpenSubKey($"{regVersionString.GetValue("")}\\CLSID"); + RegistryKey regInstallPath = Registry.ClassesRoot.OpenSubKey($"CLSID\\{regClassId.GetValue("")}\\LocalServer32"); retval = Path.GetFullPath(regInstallPath.GetValue("").ToString()); // this will convert a short file/folder names to long file/folder names } catch @@ -1346,16 +1230,10 @@ namespace Volian.Controls.Library return retval; } private static string _EqnEdtPath = null; - public static string EqnEdtPath - { - get { return StepTabRibbon._EqnEdtPath; } - } - private static string _VisioPath = null; - public static string VisioPath - { - get { return StepTabRibbon._VisioPath; } - } - private int _OleObjectEditors = -1; + public static string EqnEdtPath => StepTabRibbon._EqnEdtPath; + private static string _VisioPath = null; + public static string VisioPath => StepTabRibbon._VisioPath; + private int _OleObjectEditors = -1; public int OleObjectEditors { get @@ -1412,7 +1290,6 @@ namespace Volian.Controls.Library lOrder.Add(int.Parse(type)); if (int.Parse(type) == contenttype % 10000) found = true; } - //_MyEditItem.MyItemInfo.RefreshItemParts(); _MyEditItem.MyItemInfo.ResetParts(); if (_MyEditItem.MyItemInfo.Cautions != null) foreach (ItemInfo ii in _MyEditItem.MyItemInfo.Cautions) @@ -1440,7 +1317,6 @@ namespace Volian.Controls.Library break; } ItemInfo itemBefore = null; - //_MyEditItem.MyItemInfo.RefreshItemParts(); _MyEditItem.MyItemInfo.ResetParts(); if (_MyEditItem.MyItemInfo.Cautions != null) foreach (ItemInfo ii in _MyEditItem.MyItemInfo.Cautions) @@ -1523,8 +1399,8 @@ namespace Volian.Controls.Library if (_MyEditItem.MyItemInfo.IsTable) // B2018-005 Save Current Changes to the table if (_MyEditItem.MyParentEditItem != null)// B2018-055 Move to Parent if it exists _MyEditItem.MyParentEditItem.Select(); // Next - else if (_MyEditItem.MyPreviousEditItem != null)// B2018-055 Move to Previous if it exists - _MyEditItem.MyPreviousEditItem.Select(); + else// B2018-055 Move to Previous if it exists + _MyEditItem.MyPreviousEditItem?.Select(); } /// /// Using style for step type, enable/disable formatting buttons @@ -1553,7 +1429,6 @@ namespace Volian.Controls.Library btnCMCut.Enabled = btnCut.Enabled = setting; btnCMUndo.Enabled = btnUndo.Enabled = setting; btnCMRedo.Enabled = btnRedo.Enabled = setting; - //btnEdit3CMPaste.Enabled = btnPasteText.Enabled = btnCMPasteText.Enabled = btnCMPaste.Enabled = btnPaste.Enabled = setting; btnCMPaste.Enabled = btnCMPasteText.Enabled = btnPasteText.Enabled = btnPasteStepText.Enabled = btnPaste.Enabled = setting; btnCMCopy.Enabled = btnCopy.Enabled = setting; btnPasteAfter.Enabled = btnPasteBefore.Enabled = btnStepPaste.Enabled = btnPasteReplace.Enabled = setting; @@ -1582,17 +1457,13 @@ namespace Volian.Controls.Library btnInsNote.Enabled = true; btnInsCaut.Enabled = true; } - // C2014-009 Commented out to allow for inserting Note/Caution - // if in Calvert Alarms Condition/Response, disable insert of Cautions and Notes - //if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm) - //btnInsCaut.Enabled = btnInsNote.Enabled = btnCMInsCaution.Enabled = btnCMInsNote.Enabled = setting && !MyItemInfo.IsInCalvertConditionResponse; // B2016-237 added context menu item to change image size btnCMImgSz.Enabled = MyEditItem.MyItemInfo.IsFigure && (MyEditItem.MyItemInfo.MyContent.MyImage != null || MyEditItem.MyItemInfo.MyContent.Text.ToUpper().Contains("#LINK")); if (MyItemInfo.IsSupInfoPart) btnInsAfter.Enabled = btnInsAftH.Enabled = btnInsBefore.Enabled = btnInsBefH.Enabled = false; // C2018-005: disable the change step type button when on procedure or section: if (MyItemInfo.IsProcedure || MyItemInfo.IsSection) btnCMChgStep.Enabled = btnChgTyp.Enabled = false; } - public void SetButtonAndMenuEnabling(bool docontextmenus) + public void SetButtonAndMenuEnabling() { if (_MyStepRTB == null) return; // B2020-052: context menu items for setting text styles, fix for properties: @@ -1678,28 +1549,23 @@ namespace Volian.Controls.Library using (System.Windows.Forms.RichTextBox richTextBox1 = new System.Windows.Forms.RichTextBox()) { DataFormats.Format frm = DataFormats.GetFormat("Embed Source"); - //System.Windows.Forms.RichTextBox richTextBox1; - //richTextBox1 = new System.Windows.Forms.RichTextBox(); richTextBox1.Location = new System.Drawing.Point(35, 32); richTextBox1.Name = "richTextBox1"; richTextBox1.Size = new System.Drawing.Size(67, 58); richTextBox1.TabIndex = 0; richTextBox1.Text = ""; richTextBox1.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.None; - //bool noEquationData = true; try { richTextBox1.Paste(frm); if (richTextBox1.Rtf.ToUpper().Contains("OBJCLASS EQU")) noEquationData = false; if (richTextBox1.Rtf.ToUpper().Contains("OBJCLASS VIS")) noEquationData = false; } - catch (Exception ex) - { + catch (Exception) + { noEquationData = false; } } // end using - //btnEdit3CMPaste.Enabled = btnPasteText.Enabled = btnCMPasteText.Enabled = btnCMPaste.Enabled = btnPaste.Enabled = (iData.GetDataPresent(DataFormats.Text) || iData.GetDataPresent(DataFormats.Rtf)); - //btnPasteText.Enabled = btnPasteStepText.Enabled = btnPaste.Enabled = (iData.GetDataPresent(DataFormats.Text) || iData.GetDataPresent(DataFormats.Rtf)); btnPaste.Enabled = noEquationData && (iData.GetDataPresent(DataFormats.Text) || iData.GetDataPresent(DataFormats.Rtf)); btnCMPasteText.Enabled = btnPasteText.Enabled = noEquationData && iData.GetDataPresent(DataFormats.Text); btnCMPaste.Enabled = btnPasteStepText.Enabled = noEquationData && iData.GetDataPresent(DataFormats.Rtf); @@ -1719,7 +1585,6 @@ namespace Volian.Controls.Library SetPasteButtonEnabled(); // do all Transition and ReferencedObject menu items/buttons based on whether a 'link is selected' and the link type. - //btnCMGoTo.Enabled = btnGoTo.Enabled = _MyStepRTB.IsSelectionLinked(_MyStepRTB.SelectionStart, _MyStepRTB.SelectionLength); //(_MyStepRTB.MyLinkText != null); SetupGoToButton(); if (btnCMGoTo.Enabled == true && _MyStepRTB.MyLinkText != null) // must have some link test, use it to set edit of transition or ro... { @@ -1731,7 +1596,6 @@ namespace Volian.Controls.Library btnCMEditTran.Enabled = false; btnCMEditRO.Enabled = false; } - // OLD: SetStepButtonAndMenuEnabling(docontextmenus); SetMenuEnablingForObjectsWOText(); } @@ -1777,20 +1641,19 @@ namespace Volian.Controls.Library if (setting && MyItemInfo.IsStep && (eds == null || eds.Count == 0)) // this step is in enhanced, but not linked // B2018-112 and is allowed to edit allowDel = true; // allow delete if not linked btnCpyStp.Enabled = MyUserInfo.IsAllowedToEdit(Mydvi); // C2017-031: Support for paste/replace an enhanced step - //B20170-158 Allow a Unlinked Step to be pasted before or after a linked step. - StepTabPanel tmp = Parent as StepTabPanel; - //B2020-058: crash on null reference - if (tmp != null && tmp.MyDisplayTabControl != null && tmp.MyDisplayTabControl.MyCopyStep != null) - { - //B2017-180: The fix for B2017-158 also needed the 'HasEnhancedLinkedStep' to check if the copied step is a source step - if (!tmp.MyDisplayTabControl.MyCopyStep.IsEnhancedStep && !tmp.MyDisplayTabControl.MyCopyStep.HasEnhancedLinkedStep) - { - if (MyItemInfo.IsEnhancedStep) btnPasteReplace.Enabled = btnCMPasteReplace.Enabled = false; - } - } - else - btnStepPaste.Enabled = setting; - rbnCharacters.Enabled = rbnParagraph.Enabled = rbnLinks.Enabled = setting; + //B20170-158 Allow a Unlinked Step to be pasted before or after a linked step. + //B2020-058: crash on null reference + if (Parent is StepTabPanel tmp && tmp.MyDisplayTabControl != null && tmp.MyDisplayTabControl.MyCopyStep != null) + { + //B2017-180: The fix for B2017-158 also needed the 'HasEnhancedLinkedStep' to check if the copied step is a source step + if (!tmp.MyDisplayTabControl.MyCopyStep.IsEnhancedStep && !tmp.MyDisplayTabControl.MyCopyStep.HasEnhancedLinkedStep) + { + if (MyItemInfo.IsEnhancedStep) btnPasteReplace.Enabled = btnCMPasteReplace.Enabled = false; + } + } + else + btnStepPaste.Enabled = setting; + rbnCharacters.Enabled = rbnParagraph.Enabled = rbnLinks.Enabled = setting; btnCMEdit.Enabled = setting; btnDelStep.Enabled = setting; // context menu item btnDelelete.Enabled = setting; @@ -1811,7 +1674,7 @@ namespace Volian.Controls.Library } else { - btnCASCreate.Enabled = (MyEditItem != null) ? (MyEditItem.MyStepPanel.ApplDisplayMode > 0) : false; + btnCASCreate.Enabled = (MyEditItem != null) && (MyEditItem.MyStepPanel.ApplDisplayMode > 0); btnTCASCreate.Enabled = btnCASCreate.Enabled; // F2022-024 Time Critical Action Summary button } // B2016-237 added context menu item to change image size @@ -1831,131 +1694,76 @@ namespace Volian.Controls.Library btnPasteReplace.Enabled = btnCMPasteReplace.Enabled = enable; } private void SetPasteButtonEnabled() - { - #region new code - StepTabPanel tmp = Parent as StepTabPanel; - if (tmp == null) return; - //turn all on - SetPasteButtons(true); - //copy item is null, turn all off and return - if (tmp.MyDisplayTabControl.MyCopyStep == null) - { + { + if (!(Parent is StepTabPanel tmp)) return; + //turn all on + SetPasteButtons(true); + //copy item is null, turn all off and return + if (tmp.MyDisplayTabControl.MyCopyStep == null) + { SetPasteButtons(false); - return; - } + return; + } //if copy item is equation, can only paste if from an equation if ((tmp.MyDisplayTabControl.MyCopyStep.IsRtfRaw && !MyItemInfo.IsRtfRaw) || (!tmp.MyDisplayTabControl.MyCopyStep.IsRtfRaw && MyItemInfo.IsRtfRaw)) { SetPasteButtons(false); return; } - //copy item is procedure, turn all off and return must be done from tree - if(tmp.MyDisplayTabControl.MyCopyStep.IsProcedure) - { + //copy item is procedure, turn all off and return must be done from tree + if(tmp.MyDisplayTabControl.MyCopyStep.IsProcedure) + { SetPasteButtons(false); - return; - } - //copy item is section - if (tmp.MyDisplayTabControl.MyCopyStep.IsSection && !MyItemInfo.IsSection) - { + return; + } + //copy item is section + if (tmp.MyDisplayTabControl.MyCopyStep.IsSection && !MyItemInfo.IsSection) + { SetPasteButtons(false); - return; - } - if (tmp.MyDisplayTabControl.MyCopyStep.IsSection && MyItemInfo.IsSection && tmp.MyDisplayTabControl.MyCopyStep.ItemID == MyItemInfo.ItemID) - { - btnPasteReplace.Enabled = btnCMPasteReplace.Enabled = false; // don't replace itself - return; - } + return; + } + if (tmp.MyDisplayTabControl.MyCopyStep.IsSection && MyItemInfo.IsSection && tmp.MyDisplayTabControl.MyCopyStep.ItemID == MyItemInfo.ItemID) + { + btnPasteReplace.Enabled = btnCMPasteReplace.Enabled = false; // don't replace itself + return; + } // B2019-010 also don't allow paste step before/after if on an RNO step type (20040) if (MyItemInfo.IsSupInfoPart || ((int)MyItemInfo.MyContent.Type) == 20040) // before and after are always false: { btnPasteAfter.Enabled = btnCMPasteAfter.Enabled = false; btnPasteBefore.Enabled = btnCMPasteBefore.Enabled = false; } - // for now (Jan 2016 - initial implementation of enhanced document support) do NOT paste any step (MyCopyStep) that has enhanced data associated - // with it unless pasting within a enhanced source document. The reason is that code would need to handle clearing the pasted enhanced config - // data if it is pasted into a non-enhanced location. - StepConfig stepToCfg = null; - bool fromSourceHasEnhancedLinks = false; - bool toSourceHasEnhancedLinks = false; - if (tmp.MyDisplayTabControl.MyCopyStep.IsHigh) - { - stepToCfg = tmp.MyDisplayTabControl.MyCopyStep.MyConfig as StepConfig; - if (stepToCfg.MyEnhancedDocuments != null && stepToCfg.MyEnhancedDocuments.Count > 0 && stepToCfg.MyEnhancedDocuments[0].Type != 0) fromSourceHasEnhancedLinks = true; - if (MyItemInfo.IsHigh) - { - stepToCfg = MyItemInfo.MyConfig as StepConfig; - if (stepToCfg.MyEnhancedDocuments != null && stepToCfg.MyEnhancedDocuments.Count > 0 && stepToCfg.MyEnhancedDocuments[0].Type != 0) toSourceHasEnhancedLinks = true; - } - } - //copy item is high level step + //copy item is high level step // Allow a High Level step to be pasted to a sub-step, but not to a table, figure, section or procedure type - if (tmp.MyDisplayTabControl.MyCopyStep.IsHigh && (MyItemInfo.IsTable || MyItemInfo.IsFigure || MyItemInfo.IsSection || MyItemInfo.IsProcedure)) - { + if (tmp.MyDisplayTabControl.MyCopyStep.IsHigh && (MyItemInfo.IsTable || MyItemInfo.IsFigure || MyItemInfo.IsSection || MyItemInfo.IsProcedure)) + { // commenting these lines out allows us to use Copy Step to copy a High Level Step // to a sub-step level. - 05/18/2015 jsj // changed above if so the the high level step cannot be paste to a Table, Figure, Section (on the editor panel), Procedure (on the editor panel) - jsj 09/17/2015 SetPasteButtons(false); - return; - } + return; + } // don't allow a paste of a substep into a table, figure, sectino,or procedure type // this also allows a substep (text) to be copyed to a high level step type C2015-011 if (tmp.MyDisplayTabControl.MyCopyStep.IsSubStep && (MyItemInfo.IsTable || MyItemInfo.IsFigure || MyItemInfo.IsSection || MyItemInfo.IsProcedure)) - { + { SetPasteButtons(false); - return; - } + return; + } // copy item is a table of figure - don't allow pasting at High Level Step, Caution or Note level, as well as not at a section or procedure level) // Bug fix B2015-152 - if (tmp.MyDisplayTabControl.MyCopyStep.IsTable && !MyItemInfo.IsTable || tmp.MyDisplayTabControl.MyCopyStep.IsFigure && !MyItemInfo.IsFigure) - { + if (tmp.MyDisplayTabControl.MyCopyStep.IsTable && !MyItemInfo.IsTable || tmp.MyDisplayTabControl.MyCopyStep.IsFigure && !MyItemInfo.IsFigure) + { SetPasteButtons(false); - return; - } - //otherwise everything is ok except for same item prevent replace - if (tmp.MyDisplayTabControl.MyCopyStep.ItemID == MyItemInfo.ItemID) - { + return; + } + //otherwise everything is ok except for same item prevent replace + if (tmp.MyDisplayTabControl.MyCopyStep.ItemID == MyItemInfo.ItemID) + { btnPasteReplace.Enabled = btnCMPasteReplace.Enabled = false; // don't replace itself - return; - } - #endregion - #region original code - //// if there is no 'copied' step, or if a procedure is copied, just turn all buttons off, this can only - //// be done from the tree. - //StepTabPanel tmp = Parent as StepTabPanel; - //if (tmp.MyDisplayTabControl.MyCopyStep == null || tmp.MyDisplayTabControl.MyCopyStep.IsProcedurePart) - //{ - // btnPasteReplace.Enabled = btnPasteBefore.Enabled = btnPasteAfter.Enabled = btnStepPaste.Enabled = false; - // return; - //} - //// If a section is copied, it can be pasted as a section (before/after/replace). If can also - //// be pasted as a subsection if the format allows it. - //if (tmp.MyDisplayTabControl.MyCopyStep.IsSectionPart) - //{ - // btnPasteBefore.Enabled = btnPasteAfter.Enabled = btnPasteReplace.Enabled = MyItemInfo.IsSectionPart; - // // when doing 'substep' part of paste, need to check if format allows subsection. - //} - //else if (tmp.MyDisplayTabControl.MyCopyStep.IsCautionPart || tmp.MyDisplayTabControl.MyCopyStep.IsNotePart) - // // Part type of copied step must be same as Part type of destination, with exceptions of caution/note and step/rno - // // can be pasted into each other. - // // Part types are procedure - 1, section = 2, step = 6, caution = 3, note = 4, RNO (IsRNO), = 5 table/figure = 7. - // btnPasteBefore.Enabled = btnPasteAfter.Enabled = btnPasteReplace.Enabled = (MyItemInfo.IsCautionPart || MyItemInfo.IsNotePart); - //else if (tmp.MyDisplayTabControl.MyCopyStep.IsRNOPart || tmp.MyDisplayTabControl.MyCopyStep.IsStepPart) - // btnPasteBefore.Enabled = btnPasteAfter.Enabled = btnPasteReplace.Enabled = (MyItemInfo.IsRNOPart || MyItemInfo.IsStepPart); - //else if (tmp.MyDisplayTabControl.MyCopyStep.IsTable && MyItemInfo.IsTable) - //{ - // btnPasteBefore.Enabled = btnPasteAfter.Enabled = btnCMPasteBefore.Enabled = btnCMPasteAfter.Enabled = false; - // btnPasteReplace.Enabled = btnCMPasteReplace.Enabled = true; - //} - //else if (tmp.MyDisplayTabControl.MyCopyStep.IsTable && !MyItemInfo.IsTable) - //{ - // btnPasteBefore.Enabled = btnPasteAfter.Enabled = btnCMPasteBefore.Enabled = btnCMPasteAfter.Enabled = false; - // btnPasteReplace.Enabled = btnCMPasteReplace.Enabled = false; - //} - //// Can't replace step with same step - //if (tmp.MyDisplayTabControl.MyCopyStep.ItemID == MyItemInfo.ItemID) btnPasteReplace.Enabled = false; - #endregion - } + return; + } + } private void SetChangeIdRibbon() { if (MyItemInfo == null) @@ -2050,10 +1858,12 @@ namespace Volian.Controls.Library } private DevComponents.DotNetBar.ButtonItem MakeSubMenuButton(string s, object tag, EventHandler ehandler) { - DevComponents.DotNetBar.ButtonItem bi = new DevComponents.DotNetBar.ButtonItem(); - bi.Text = s; - bi.Tag = tag; - bi.Click += new System.EventHandler(ehandler); + DevComponents.DotNetBar.ButtonItem bi = new DevComponents.DotNetBar.ButtonItem + { + Text = s, + Tag = tag + }; + bi.Click += new System.EventHandler(ehandler); return bi; } @@ -2062,9 +1872,8 @@ namespace Volian.Controls.Library private void SetStepButtonAndMenuEnabling(bool docontextmenus) { if (MyEditItem == null) return; - DocVersionInfo dvi = MyEditItem.MyItemInfo.MyProcedure.ActiveParent as DocVersionInfo; - if (dvi == null) return; - if (dvi.VersionType > 127) + if (!(MyEditItem.MyItemInfo.MyProcedure.ActiveParent is DocVersionInfo dvi)) return; + if (dvi.VersionType > 127) btnCMEditMode1.Enabled = btnEditMode.Enabled = false; // in approved if (dvi.VersionType > 127 || MyEditItem.MyStepPanel.VwMode == E_ViewMode.View) { @@ -2085,9 +1894,8 @@ namespace Volian.Controls.Library // see if manual page break - only available on HLS if (MyItemInfo.IsHigh) { - StepConfig cfg = MyItemInfo.MyConfig as StepConfig; - btnInsPgBrk.Checked = cfg == null ? false : cfg.Step_NewManualPagebreak; - } + btnInsPgBrk.Checked = MyItemInfo.MyConfig is StepConfig cfg && cfg.Step_NewManualPagebreak; + } btnInsPgBrk.Enabled = MyItemInfo.IsHigh; btnPageBreak.Enabled = MyItemInfo.IsHigh; // edit context menu @@ -2095,14 +1903,14 @@ namespace Volian.Controls.Library btnEditMode.Checked = btnCMEditMode1.Checked = MyEditItem.MyStepPanel.VwMode == E_ViewMode.View; // if on procedure, 'Delete' buttons should be disabled. btnDelelete.Enabled = btnDelStep.Enabled = !MyItemInfo.IsProcedure; - // Only display the table edit tools if in a grid (table) and that grid (table) is not an RO Table. - GridItem tmpGridItm = MyEditItem as GridItem; - if (btnTblDgnAdjustSize.Checked) - { - btnTblDgnAdjustSize.Checked = false; - ToggleTableDesignButtons(true); - } - rtabTableGridTools.Visible = tmpGridItm != null; + // Only display the table edit tools if in a grid (table) and that grid (table) is not an RO Table. + if (btnTblDgnAdjustSize.Checked) + { + btnTblDgnAdjustSize.Checked = false; + ToggleTableDesignButtons(true); + } + + rtabTableGridTools.Visible = MyEditItem is GridItem; // If no longer on a table (grid) or the newly selectd table is an RO table // then select the Home tab (since the Table tab is not visable) if ((!(MyEditItem is GridItem) && rtabTableGridTools.Checked)) // || ((MyEditItem is GridItem) && !rtabTableGridTools.Visible)) @@ -2134,18 +1942,16 @@ namespace Volian.Controls.Library // disable buttons. Info panels for ROs and Transitions are made invisible in frmVEPROMS.cs btnInsTrans.Enabled = btnCMTransition.Enabled = btnInsRO.Enabled = btnCMRO.Enabled = false; btnInsAftH.Enabled = btnInsBefH.Enabled = false; - //btnInsHLS.Enabled = (!MyItemInfo.IsStepSection || (MyItemInfo.IsStepSection && MyItemInfo.IsEnhancedSection)) ? false : true; // allow hls from step section - btnInsHLS.Enabled = !MyItemInfo.IsStepSection ? false : true; // allow hls from step section + btnInsHLS.Enabled = MyItemInfo.IsStepSection; // allow hls from step section // if active item is a section and format has metasections, check that a hls can be added. if (MyItemInfo.IsStepSection) { if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.UseMetaSections) // The 'editable' data config must be set to allow new steps to be created. { - SectionConfig sc = MyItemInfo.MyConfig as SectionConfig; - if (sc != null && MyItemInfo.Sections != null && MyItemInfo.Sections.Count > 0 && sc.SubSection_Edit != "Y") - btnInsHLS.Enabled = false; - } + if (MyItemInfo.MyConfig is SectionConfig sc && MyItemInfo.Sections != null && MyItemInfo.Sections.Count > 0 && sc.SubSection_Edit != "Y") + btnInsHLS.Enabled = false; + } } if (btnInsHLS.Enabled) { @@ -2160,13 +1966,10 @@ namespace Volian.Controls.Library } btnChgTyp.Enabled = true; - - // set up insert buttons based on format - E_AccStep? actable = 0; - StepData sd = MyItemInfo.FormatStepData; - actable = sd.StepEditData.AcTable; - if (actable == null) actable = 0; - btnInsHLS.Enabled = MyItemInfo.MyHLS != null; + StepData sd = MyItemInfo.FormatStepData; + // set up insert buttons based on format + E_AccStep? actable = sd.StepEditData.AcTable ?? 0; + btnInsHLS.Enabled = MyItemInfo.MyHLS != null; btnInsCaut.Enabled = ((actable & E_AccStep.AddingCaution) > 0) && !MyItemInfo.IsEnhancedStep; btnInsNote.Enabled = ((actable & E_AccStep.AddingNote) > 0) && !MyItemInfo.IsEnhancedStep; btnInsRNO.Enabled = (actable & E_AccStep.AddingRNO) > 0; @@ -2263,11 +2066,13 @@ namespace Volian.Controls.Library // B2013-175: add the single substep type to the context menu too int cmtype = (int)ichld.MyContent.Type - 20000; // content type is the index into the stepdatalist StepData sdcm = MyItemInfo.ActiveFormat.PlantFormat.FormatData.StepDataList[cmtype]; - DevComponents.DotNetBar.ButtonItem cmbix = new DevComponents.DotNetBar.ButtonItem("cmbtn" + sdcm.Type, sdcm.Type); - cmbix.ButtonStyle = DevComponents.DotNetBar.eButtonStyle.TextOnlyAlways; - cmbix.Text = sdcm.StepEditData.TypeMenu.MenuItem; - cmbix.Tag = string.Format("{0} {1}", fromtype, sdcm.Index); // index of type to insert it when button is clicked - cmbix.Click += new System.EventHandler(btnInsStep_Click); + DevComponents.DotNetBar.ButtonItem cmbix = new DevComponents.DotNetBar.ButtonItem("cmbtn" + sdcm.Type, sdcm.Type) + { + ButtonStyle = DevComponents.DotNetBar.eButtonStyle.TextOnlyAlways, + Text = sdcm.StepEditData.TypeMenu.MenuItem, + Tag = string.Format("{0} {1}", fromtype, sdcm.Index) // index of type to insert it when button is clicked + }; + cmbix.Click += new System.EventHandler(btnInsStep_Click); cmbtn.SubItems.Add(cmbix); return; } @@ -2295,19 +2100,23 @@ namespace Volian.Controls.Library if (btn.Name == "btnInsSubstep" && MyItemInfo.Steps != null && MyItemInfo.Steps.Count > 0) addit = false; if (addit) { - DevComponents.DotNetBar.ButtonItem bi = new DevComponents.DotNetBar.ButtonItem("btn" + sd.Type, sd.Type); - bi.ButtonStyle = DevComponents.DotNetBar.eButtonStyle.TextOnlyAlways; - bi.Text = sdr.Name; - bi.Tag = string.Format("{0} {1}", fromtype, sdr.Index); // index of type to insert it when button is clicked - bi.Checked = (selType == null || (sd.Type == selType.Type)); - if (docontextmenus) + DevComponents.DotNetBar.ButtonItem bi = new DevComponents.DotNetBar.ButtonItem("btn" + sd.Type, sd.Type) + { + ButtonStyle = DevComponents.DotNetBar.eButtonStyle.TextOnlyAlways, + Text = sdr.Name, + Tag = string.Format("{0} {1}", fromtype, sdr.Index), // index of type to insert it when button is clicked + Checked = (selType == null || (sd.Type == selType.Type)) + }; + if (docontextmenus) { - DevComponents.DotNetBar.ButtonItem cmbi = new DevComponents.DotNetBar.ButtonItem("cmbtn" + sd.Type, sd.Type); - cmbi.ButtonStyle = DevComponents.DotNetBar.eButtonStyle.TextOnlyAlways; - cmbi.Text = sdr.Name; - cmbi.Tag = string.Format("{0} {1}", fromtype, sdr.Index); // index of type to insert it when button is clicked - cmbi.Checked = (selType == null || (sd.Type == selType.Type)); - if(!AddVisioOrEqnEdt(cmbi)) // Added support for Visio + DevComponents.DotNetBar.ButtonItem cmbi = new DevComponents.DotNetBar.ButtonItem("cmbtn" + sd.Type, sd.Type) + { + ButtonStyle = DevComponents.DotNetBar.eButtonStyle.TextOnlyAlways, + Text = sdr.Name, + Tag = string.Format("{0} {1}", fromtype, sdr.Index), // index of type to insert it when button is clicked + Checked = (selType == null || (sd.Type == selType.Type)) + }; + if (!AddVisioOrEqnEdt(cmbi)) // Added support for Visio cmbi.Click += new System.EventHandler(btnInsStep_Click); cmbtn.SubItems.Add(cmbi); } @@ -2328,7 +2137,7 @@ namespace Volian.Controls.Library } } //handle various cases for figures: - if (btn.Name == "btnInsFig" && docontextmenus) DoFigureMenuing(btn, cmbtn, sdl); + if (btn.Name == "btnInsFig" && docontextmenus) DoFigureMenuing(btn, cmbtn); // if this is a table, then need to add RO/Text table options if (btn.Name == "btnInsTable" && docontextmenus) @@ -2380,10 +2189,12 @@ namespace Volian.Controls.Library if (docontextmenus) { cmbtn.SubItems.Clear(); - DevComponents.DotNetBar.ButtonItem cmbi = new DevComponents.DotNetBar.ButtonItem("cmbtn" + sdc.Type, sdc.Type); - cmbi.ButtonStyle = DevComponents.DotNetBar.eButtonStyle.TextOnlyAlways; - cmbi.Text = btn.Text; - if (btn.Name == "btnInsRNO") + DevComponents.DotNetBar.ButtonItem cmbi = new DevComponents.DotNetBar.ButtonItem($"cmbtn{sdc.Type}", sdc.Type) + { + ButtonStyle = DevComponents.DotNetBar.eButtonStyle.TextOnlyAlways, + Text = btn.Text + }; + if (btn.Name == "btnInsRNO") cmbi.Tag = btn.Tag; else cmbi.Tag = string.Format("{0} {1}", fromtype, sdc.Index); // index of type to insert it when button is clicked @@ -2413,13 +2224,12 @@ namespace Volian.Controls.Library { DevComponents.DotNetBar.ButtonItem btn1 = new DevComponents.DotNetBar.ButtonItem("btnEquation", "Equation Editor"); btn1.Click += new System.EventHandler(btnInsStep_Click); - btn1.Tag = cmbi.Tag + " EqnEdt"; + btn1.Tag = $"{cmbi.Tag} EqnEdt"; btn1.ButtonStyle = DevComponents.DotNetBar.eButtonStyle.TextOnlyAlways; - //btn1.Tag = string.Format("Equation"); // index of type to insert it when button is clicked cmbi.SubItems.Add(btn1); DevComponents.DotNetBar.ButtonItem btn2 = new DevComponents.DotNetBar.ButtonItem("btnVisio", "Visio"); btn2.Click += new System.EventHandler(btnInsStep_Click); - btn2.Tag = cmbi.Tag + " Visio"; + btn2.Tag = $"{cmbi.Tag} Visio"; btn2.ButtonStyle = DevComponents.DotNetBar.eButtonStyle.TextOnlyAlways; cmbi.SubItems.Add(btn2); return true; @@ -2431,8 +2241,8 @@ namespace Volian.Controls.Library // // // - private int Centered = 36; // will always be top level. - private void DoFigureMenuing(ButtonItem btn, ButtonItem cmbtn, List sdl) + private readonly int Centered = 36; // will always be top level. + private void DoFigureMenuing(ButtonItem btn, ButtonItem cmbtn) { // Figure menuing: // Figure (from ribbon) @@ -2481,17 +2291,21 @@ namespace Volian.Controls.Library string[] insdata = btn.Tag.ToString().Split(sp); int ftype = Convert.ToInt32(insdata[0]); int sdtype = Convert.ToInt32(insdata[1]); - DevComponents.DotNetBar.ButtonItem cmbt = new DevComponents.DotNetBar.ButtonItem("cmbtnt" + sdtype + "CENT", "Centered"); - cmbt.ButtonStyle = DevComponents.DotNetBar.eButtonStyle.TextOnlyAlways; - cmbt.Text = "Centered"; - cmbt.Tag = string.Format("{0} {1} {2}", ftype, 36, "CENT"); - cmbt.Click += new System.EventHandler(btnInsStep_Click); + DevComponents.DotNetBar.ButtonItem cmbt = new DevComponents.DotNetBar.ButtonItem($"cmbtnt{sdtype}CENT", "Centered") + { + ButtonStyle = DevComponents.DotNetBar.eButtonStyle.TextOnlyAlways, + Text = "Centered", + Tag = string.Format("{0} {1} {2}", ftype, 36, "CENT") + }; + cmbt.Click += new System.EventHandler(btnInsStep_Click); btn.SubItems.Add(cmbt); - cmbt = new DevComponents.DotNetBar.ButtonItem("cmbtnt" + sdtype + "LT", "Left"); - cmbt.ButtonStyle = DevComponents.DotNetBar.eButtonStyle.TextOnlyAlways; - cmbt.Text = "Left"; - cmbt.Tag = string.Format("{0} {1} {2}", ftype, 37, "LT"); // Text table - cmbt.Click += new System.EventHandler(btnInsStep_Click); + cmbt = new DevComponents.DotNetBar.ButtonItem($"cmbtnt{sdtype}LT", "Left") + { + ButtonStyle = DevComponents.DotNetBar.eButtonStyle.TextOnlyAlways, + Text = "Left", + Tag = string.Format("{0} {1} {2}", ftype, 37, "LT") // Text table + }; + cmbt.Click += new System.EventHandler(btnInsStep_Click); btn.SubItems.Add(cmbt); btn.Tag = null; btn.Click -= new System.EventHandler(btnInsStep_Click); @@ -2510,19 +2324,23 @@ namespace Volian.Controls.Library int ftype = Convert.ToInt32(insdata[0]); int sdtype = Convert.ToInt32(insdata[1]); int with = sdtype == Centered ? 36 : 37; - DevComponents.DotNetBar.ButtonItem cmbt = new DevComponents.DotNetBar.ButtonItem("cmbtnt" + sdtype + "BD", "With Border"); - cmbt.ButtonStyle = DevComponents.DotNetBar.eButtonStyle.TextOnlyAlways; - cmbt.Text = "With Border"; - cmbt.Tag = string.Format("{0} {1} {2}", ftype, sdtype, "BD"); - cmbt.Click += new System.EventHandler(btnInsStep_Click); + DevComponents.DotNetBar.ButtonItem cmbt = new DevComponents.DotNetBar.ButtonItem($"cmbtnt{sdtype}BD", "With Border") + { + ButtonStyle = DevComponents.DotNetBar.eButtonStyle.TextOnlyAlways, + Text = "With Border", + Tag = string.Format("{0} {1} {2}", ftype, sdtype, "BD") + }; + cmbt.Click += new System.EventHandler(btnInsStep_Click); tabbtn.SubItems.Add(cmbt); DoFigureFromSubMenu(cmbt); int wo = sdtype == Centered ? 38 : 39; - cmbt = new DevComponents.DotNetBar.ButtonItem("cmbtnt" + wo + "NB", "Without Border"); - cmbt.ButtonStyle = DevComponents.DotNetBar.eButtonStyle.TextOnlyAlways; - cmbt.Text = "Without Border"; - cmbt.Tag = string.Format("{0} {1} {2}", ftype, wo, "NB"); - cmbt.Click += new System.EventHandler(btnInsStep_Click); + cmbt = new DevComponents.DotNetBar.ButtonItem($"cmbtnt{wo}NB", "Without Border") + { + ButtonStyle = DevComponents.DotNetBar.eButtonStyle.TextOnlyAlways, + Text = "Without Border", + Tag = string.Format("{0} {1} {2}", ftype, wo, "NB") + }; + cmbt.Click += new System.EventHandler(btnInsStep_Click); tabbtn.SubItems.Add(cmbt); DoFigureFromSubMenu(cmbt); tabbtn.Tag = null; @@ -2534,23 +2352,29 @@ namespace Volian.Controls.Library string[] insdata = tabbtn.Tag.ToString().Split(sp); int ftype = Convert.ToInt32(insdata[0]); int sdtype = Convert.ToInt32(insdata[1]); - DevComponents.DotNetBar.ButtonItem cmbt = new DevComponents.DotNetBar.ButtonItem("cmbtnt" + sdtype + "RO", "RO Figure"); - cmbt.ButtonStyle = DevComponents.DotNetBar.eButtonStyle.TextOnlyAlways; - cmbt.Text = "RO Figure"; - cmbt.Tag = string.Format("{0} {1} {2}", ftype, sdtype, "RO"); - cmbt.Click += new System.EventHandler(btnInsStep_Click); + DevComponents.DotNetBar.ButtonItem cmbt = new DevComponents.DotNetBar.ButtonItem($"cmbtnt{sdtype}RO", "RO Figure") + { + ButtonStyle = DevComponents.DotNetBar.eButtonStyle.TextOnlyAlways, + Text = "RO Figure", + Tag = string.Format("{0} {1} {2}", ftype, sdtype, "RO") + }; + cmbt.Click += new System.EventHandler(btnInsStep_Click); tabbtn.SubItems.Add(cmbt); - cmbt = new DevComponents.DotNetBar.ButtonItem("cmbtnt" + sdtype + "CL", "From Clipboard"); - cmbt.ButtonStyle = DevComponents.DotNetBar.eButtonStyle.TextOnlyAlways; - cmbt.Text = "From Clipboard"; - cmbt.Tag = string.Format("{0} {1} {2}", ftype, sdtype, "CL"); - cmbt.Click += new System.EventHandler(btnInsStep_Click); + cmbt = new DevComponents.DotNetBar.ButtonItem($"cmbtnt{sdtype}CL", "From Clipboard") + { + ButtonStyle = DevComponents.DotNetBar.eButtonStyle.TextOnlyAlways, + Text = "From Clipboard", + Tag = string.Format("{0} {1} {2}", ftype, sdtype, "CL") + }; + cmbt.Click += new System.EventHandler(btnInsStep_Click); tabbtn.SubItems.Add(cmbt); - cmbt = new DevComponents.DotNetBar.ButtonItem("cmbtnt" + sdtype + "FL", "From File"); - cmbt.ButtonStyle = DevComponents.DotNetBar.eButtonStyle.TextOnlyAlways; - cmbt.Text = "From File"; - cmbt.Tag = string.Format("{0} {1} {2}", ftype, sdtype, "FL"); // Text table - cmbt.Click += new System.EventHandler(btnInsStep_Click); + cmbt = new DevComponents.DotNetBar.ButtonItem($"cmbtnt{sdtype}FL", "From File") + { + ButtonStyle = DevComponents.DotNetBar.eButtonStyle.TextOnlyAlways, + Text = "From File", + Tag = string.Format("{0} {1} {2}", ftype, sdtype, "FL") // Text table + }; + cmbt.Click += new System.EventHandler(btnInsStep_Click); tabbtn.SubItems.Add(cmbt); tabbtn.Tag = null; tabbtn.Click -= new System.EventHandler(btnInsStep_Click); @@ -2561,19 +2385,23 @@ namespace Volian.Controls.Library string[] insdata = tabbtn.Tag.ToString().Split(sp); int ftype = Convert.ToInt32(insdata[0]); int sdtype = Convert.ToInt32(insdata[1]); - DevComponents.DotNetBar.ButtonItem cmbt = new DevComponents.DotNetBar.ButtonItem("cmbtnt" + sdtype + "RO", "RO Table"); - cmbt.ButtonStyle = DevComponents.DotNetBar.eButtonStyle.TextOnlyAlways; - cmbt.Text = "RO Table"; - cmbt.Tag = string.Format("{0} {1} {2}", ftype, sdtype, "RO"); - //cmbt.Checked = (sd.Type == selType.Type); - cmbt.Click += new System.EventHandler(btnInsStep_Click); + DevComponents.DotNetBar.ButtonItem cmbt = new DevComponents.DotNetBar.ButtonItem($"cmbtnt{sdtype}RO", "RO Table") + { + ButtonStyle = DevComponents.DotNetBar.eButtonStyle.TextOnlyAlways, + Text = "RO Table", + Tag = string.Format("{0} {1} {2}", ftype, sdtype, "RO") + }; + //cmbt.Checked = (sd.Type == selType.Type); + cmbt.Click += new System.EventHandler(btnInsStep_Click); tabbtn.SubItems.Add(cmbt); - cmbt = new DevComponents.DotNetBar.ButtonItem("cmbtnt" + sdtype + "TX", "Text Table"); - cmbt.ButtonStyle = DevComponents.DotNetBar.eButtonStyle.TextOnlyAlways; - cmbt.Text = "Text Table"; - cmbt.Tag = string.Format("{0} {1} {2}", ftype, sdtype, "TX"); // Text table - //cmbt.Checked = (sd.Type == selType.Type); - cmbt.Click += new System.EventHandler(btnInsStep_Click); + cmbt = new DevComponents.DotNetBar.ButtonItem($"cmbtnt{sdtype}TX", "Text Table") + { + ButtonStyle = DevComponents.DotNetBar.eButtonStyle.TextOnlyAlways, + Text = "Text Table", + Tag = string.Format("{0} {1} {2}", ftype, sdtype, "TX") // Text table + }; + //cmbt.Checked = (sd.Type == selType.Type); + cmbt.Click += new System.EventHandler(btnInsStep_Click); tabbtn.SubItems.Add(cmbt); tabbtn.Tag = null; tabbtn.Click -= new System.EventHandler(btnInsStep_Click); @@ -2674,7 +2502,7 @@ namespace Volian.Controls.Library applyStyle(); // not in a grid, apply style to current step type } //C2021-005 the font size for the selected table cell(s) - private float GetTableCellFontSize(SelectionOption selOpt) + private float GetTableCellFontSize() { // return 0 if there are multiple font sizes or just an invalid selection float rtnFontSize = -1; @@ -2685,10 +2513,6 @@ namespace Volian.Controls.Library if (ctrl == null) return rtnFontSize; // B2018-008 if a null is returned don't do anything if (ctrl is VlnFlexGrid) { - // Selected table cell is not in edit mode. Go into edit mode and position according - // to the pass in selOpt. - // B2021-090 don't try to get the font size on an RO table - // B2022-137 Table performance improvements if (MyFlexGrid != null && MyFlexGrid.Editor == null && !MyFlexGrid.IsRoTable) { rtnFontSize = StepRTB.GetRTFFontSize(MyFlexGrid.Selection.Clip); @@ -2790,14 +2614,10 @@ namespace Volian.Controls.Library } } - private void ToggleBold() - { - RTBAPI.ToggleBold(!RTBAPI.IsBold(_MyStepRTB), _MyStepRTB, _MyStepRTB.SelectionLength == 0 ? RTBAPI.RTBSelection.SCF_DEFAULT : RTBAPI.RTBSelection.SCF_SELECTION); - } + private void ToggleBold() => RTBAPI.ToggleBold(!RTBAPI.IsBold(_MyStepRTB), _MyStepRTB, _MyStepRTB.SelectionLength == 0 ? RTBAPI.RTBSelection.SCF_DEFAULT : RTBAPI.RTBSelection.SCF_SELECTION); - public void btnInsPgBrk_Click(object sender, EventArgs e) + public void btnInsPgBrk_Click(object sender, EventArgs e) { - //rtabInsert.Select(); // insert page break is no longer visible on the ribbon if (MyItemInfo.IsProcedure || MyItemInfo.IsSection || !MyItemInfo.IsHigh) return; MyEditItem.SaveContents(); // toggle manual page break @@ -2955,13 +2775,11 @@ namespace Volian.Controls.Library Control ctrl = FindActiveControl(); if (ctrl == null) return; // B2018-008 If a null is returned, don't do anything Clipboard.Clear(); - //if (_MyStepRTB == null) return; if (_MyStepRTB.SelectedText == null || _MyStepRTB.SelectedText == "") return; // nothing to copy onto clipboard, just return DataObject myDO = new DataObject(); ; if (ctrl is RichTextBox) { - //myDO = new DataObject("Rich Text Format", (ctrl as RichTextBox).SelectedRtf); string tmp2 = _MyStepRTB.SelectedText; string tmp = _MyStepRTB.GetSelectionForClipBoard(); tmp2 = Regex.Replace(tmp2, @"#Link:ReferencedObject:[0-9]+ +[0-9a-zA-Z]+ [0-9]+", @""); @@ -2970,19 +2788,16 @@ namespace Volian.Controls.Library tmp2 = tmp2.Replace("", ""); myDO.SetText(tmp2, TextDataFormat.Text); - //myDO.SetText(_MyStepRTB.SelectedRtf, TextDataFormat.Rtf); myDO.SetText(tmp, TextDataFormat.Rtf); if (isCut) (ctrl as RichTextBox).SelectedText = ""; } else if (ctrl is ComboBox) { - //myDO = new DataObject("Text Format", (ctrl as ComboBox).SelectedText); myDO.SetText((ctrl as ComboBox).SelectedText, TextDataFormat.Text); if (isCut) (ctrl as ComboBox).SelectedText = ""; } else if (ctrl is TextBox) { - //myDO = new DataObject("Text Format", (ctrl as TextBox).SelectedText); myDO.SetText((ctrl as TextBox).SelectedText, TextDataFormat.Text); if (isCut) (ctrl as TextBox).SelectedText = ""; } @@ -2991,28 +2806,6 @@ namespace Volian.Controls.Library SaveErrorInLogProblemWithType(ctrl); return; } - //DataObject myDO; - //if (ctrl is RichTextBox) - //{ - // myDO = new DataObject("Rich Text Format", (ctrl as RichTextBox).SelectedRtf); - // myDO.SetText(_MyStepRTB.SelectedText); - // if(isCut) (ctrl as RichTextBox).SelectedText = ""; - //} - //else if (ctrl is ComboBox) - //{ - // myDO = new DataObject("Text Format", (ctrl as ComboBox).SelectedText); - // if (isCut) (ctrl as ComboBox).SelectedText = ""; - //} - //else if (ctrl is TextBox) - //{ - // myDO = new DataObject("Text Format", (ctrl as TextBox).SelectedText); - // if (isCut) (ctrl as TextBox).SelectedText = ""; - //} - //else - //{ - // SaveErrorInLogProblemWithType(ctrl); - // return; - //} Clipboard.SetDataObject(myDO); } private void btnCopy_Click(object sender, EventArgs e) @@ -3035,11 +2828,8 @@ namespace Volian.Controls.Library btnCMItalics.Checked = btnItalics.Checked = RTBAPI.IsItalic(_MyStepRTB) && (MyFlexGrid == null || MyFlexGrid.TableCellEditor.EditMode); } - private void ToggleItalic() - { - RTBAPI.ToggleItalic(!RTBAPI.IsItalic(_MyStepRTB), _MyStepRTB, _MyStepRTB.SelectionLength == 0 ? RTBAPI.RTBSelection.SCF_DEFAULT : RTBAPI.RTBSelection.SCF_SELECTION); - } - private void btnUnderline_Click(object sender, EventArgs e) + private void ToggleItalic() => RTBAPI.ToggleItalic(!RTBAPI.IsItalic(_MyStepRTB), _MyStepRTB, _MyStepRTB.SelectionLength == 0 ? RTBAPI.RTBSelection.SCF_DEFAULT : RTBAPI.RTBSelection.SCF_SELECTION); + private void btnUnderline_Click(object sender, EventArgs e) { ApplyStyleToCurrentStepOrGridSelection(SelectionOption.All, ToggleUnderline); // B2017-208 toggle on/off attributes button checks when you edit table cells, going from one cell to another @@ -3047,12 +2837,9 @@ namespace Volian.Controls.Library btnCMUnderline.Checked = btnUnderline.Checked = RTBAPI.IsUnderline(_MyStepRTB) && (MyFlexGrid == null || MyFlexGrid.TableCellEditor.EditMode); } - private void ToggleUnderline() - { - RTBAPI.ToggleUnderline(!RTBAPI.IsUnderline(_MyStepRTB), _MyStepRTB, _MyStepRTB.SelectionLength == 0 ? RTBAPI.RTBSelection.SCF_DEFAULT : RTBAPI.RTBSelection.SCF_SELECTION); - } + private void ToggleUnderline() => RTBAPI.ToggleUnderline(!RTBAPI.IsUnderline(_MyStepRTB), _MyStepRTB, _MyStepRTB.SelectionLength == 0 ? RTBAPI.RTBSelection.SCF_DEFAULT : RTBAPI.RTBSelection.SCF_SELECTION); - public void btnSuperscript_Click(object sender, EventArgs e) + public void btnSuperscript_Click(object sender, EventArgs e) { StartGridEditing(SelectionOption.All); RTBAPI.ToggleSuperscript(!RTBAPI.IsSuperScript(_MyStepRTB), _MyStepRTB, _MyStepRTB.SelectionLength == 0 ? RTBAPI.RTBSelection.SCF_DEFAULT : RTBAPI.RTBSelection.SCF_SELECTION); @@ -3066,36 +2853,18 @@ namespace Volian.Controls.Library btnCMSubscript.Checked = btnSubscript.Checked = RTBAPI.IsSubScript(_MyStepRTB); } - private void btnUppercase_Click(object sender, EventArgs e) - { - ApplyStyleToCurrentStepOrGridSelection(SelectionOption.All, SetUpperCase); - } + private void btnUppercase_Click(object sender, EventArgs e) => ApplyStyleToCurrentStepOrGridSelection(SelectionOption.All, SetUpperCase); - private void SetUpperCase() - { - _MyStepRTB.SetSelectedCase('U'); - } + private void SetUpperCase() => _MyStepRTB.SetSelectedCase('U'); - private void btnLowercase_Click(object sender, EventArgs e) - { - ApplyStyleToCurrentStepOrGridSelection(SelectionOption.All, SetLowerCase); - } + private void btnLowercase_Click(object sender, EventArgs e) => ApplyStyleToCurrentStepOrGridSelection(SelectionOption.All, SetLowerCase); - private void SetLowerCase() - { - _MyStepRTB.SetSelectedCase('l'); - } + private void SetLowerCase() => _MyStepRTB.SetSelectedCase('l'); - private void btnTitleCase_Click(object sender, EventArgs e) - { - ApplyStyleToCurrentStepOrGridSelection(SelectionOption.All, SetTitleCase); - } + private void btnTitleCase_Click(object sender, EventArgs e) => ApplyStyleToCurrentStepOrGridSelection(SelectionOption.All, SetTitleCase); - private void SetTitleCase() - { - _MyStepRTB.SetSelectedCase('T'); - } - private void btnInsTrans_Click(object sender, EventArgs e) + private void SetTitleCase() => _MyStepRTB.SetSelectedCase('T'); + private void btnInsTrans_Click(object sender, EventArgs e) { StartGridEditing(SelectionOption.Start); // see if user is positioned 'on' a transition within the rtb, if so do a modify, otherwise, @@ -3200,16 +2969,15 @@ namespace Volian.Controls.Library FlexibleMessageBox.Show("Unit Information RO's cannot be edited", "Unit Information RO", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } - //string roapp = Environment.GetEnvironmentVariable("roapp"); string roapp = Volian.Base.Library.ExeInfo.GetROEditorPath(); // get the path to the RO Editor Executable - string args = "\"" + myRODB.FolderPath + "\" " + myROID; + string args = $"\"{myRODB.FolderPath}\" {myROID}"; if (!Directory.Exists(myRODB.FolderPath)) { FlexibleMessageBox.Show(string.Format("RO Database directory does not exist: {0}", myRODB.FolderPath)); return; } // C2017-003: ro data in sql server, check for sql connection string - if (myRODB.DBConnectionString != "cstring") args = args + " \"" + myRODB.DBConnectionString + "\""; + if (myRODB.DBConnectionString != "cstring") args = $"{args} \"{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 @@ -3217,13 +2985,12 @@ namespace Volian.Controls.Library DocVersionInfoList dvil = DocVersionInfoList.Get(); foreach (DocVersionInfo dvi in dvil) { - DocVersionConfig dvc = dvi.DocVersionConfig as DocVersionConfig; - if (dvc != null && dvc.Unit_Name != "" && dvc.Unit_Count > 1) // B2021-089 only pass in applicability info if defined for more than one unit - { - args += " \"PC=" + dvc.Unit_Name + "\""; - break; - } - } + if (dvi.DocVersionConfig is DocVersionConfig dvc && dvc.Unit_Name != "" && dvc.Unit_Count > 1) // B2021-089 only pass in applicability info if defined for more than one unit + { + args += $" \"PC={dvc.Unit_Name}\""; + break; + } + } System.Diagnostics.Process.Start(roapp, args); } } @@ -3255,49 +3022,6 @@ namespace Volian.Controls.Library MyEditItem.MyStepPanel.OnTabDisplay(sender, args); } #endregion - #region RHM debug - //#if DEBUG - // // The following code generates an XML output for the selected item for print testing. - // private void btnPageBreak_Click(object sender, EventArgs e) - // { - // // This is here temporarily to get a node and all of it's children for print testing. - // OutputAllChildren(MyRTBItem); - // } - // private void OutputAllChildren(RTBItem myRTBItem) - // { - // OutputAllChildren(myRTBItem.MyBeforeRTBItems); - // OutputStepInfo(myRTBItem); - // OutputAllChildren(myRTBItem.MyAfterRTBItems); - // OutputAllChildren(myRTBItem.MyRNORTBItems); - // } - // private void OutputStepInfo(RTBItem myRTBItem) - // { - // Label lbl = myRTBItem.MyLabel; - // if (lbl.Text.Trim() != "") - // Console.WriteLine("{4}", - // ToInches(myRTBItem.Left + lbl.Left), ToInches(myRTBItem.Top + lbl.Top), - // lbl.Font.FontFamily.Name,lbl.Font.SizeInPoints,lbl.Text); - // StepRTB rtb = myRTBItem.MyStepRTB; - // Console.WriteLine("{3}", - // ToInches(myRTBItem.Left + rtb.Left), ToInches(myRTBItem.Top + rtb.Top), ToInches(rtb.Width), myRTBItem.MyItemInfo.MyContent.Text); - //// ToInches(myRTBItem.Left + rtb.Left), ToInches(myRTBItem.Top + rtb.Top), ToInches(rtb.Width), rtb.Rtf); - // } - // private float ToInches(int val) - // { - // return Convert.ToSingle(val)/96F; - // } - - // private void OutputAllChildren(List list) - // { - // if(list != null) - // foreach (RTBItem itm in list) - // OutputAllChildren(itm); - // } - - - //#endif - #endregion // C2021-021 change the tool tip for the Find and Find/Replace button based on the user's accessibility to the procedure. // also change the text on the buttons to read either Find or Find/Replace public void ToggleFindReplaceToolTip(bool isReviewer) @@ -3342,19 +3066,17 @@ namespace Volian.Controls.Library } public void SetupSetAdminMode() { + //Used to Trigger Update/Refresh of Ribbon } public void SetupAdminMode() { - } + //Used to Trigger Update/Refresh of Ribbon + } - //C2019-036 View Only mode work with Checked Out Procedures - public event StepTabRibbonEvent EnableDisableStepProperties; - private void OnEnableDisableStepProperties(StepTabRibbonEventArgs args) - { - if (EnableDisableStepProperties != null) - EnableDisableStepProperties(this, args); - } - private void btnToggleEditView_Click(object sender, EventArgs e) + //C2019-036 View Only mode work with Checked Out Procedures + public event StepTabRibbonEvent EnableDisableStepProperties; + private void OnEnableDisableStepProperties(StepTabRibbonEventArgs args) => EnableDisableStepProperties?.Invoke(this, args); + private void btnToggleEditView_Click(object sender, EventArgs e) { if (MyEditItem == null) return; @@ -3391,22 +3113,19 @@ namespace Volian.Controls.Library //enable / disable the Step Properties Panel based on the ViewMode OnEnableDisableStepProperties(new StepTabRibbonEventArgs(MyEditItem.MyItemInfo, 0, MyEditItem.MyStepPanel.VwMode)); MyEditItem.ToggleEditView(MyEditItem.MyStepPanel.VwMode); - SetButtonAndMenuEnabling(true); + SetButtonAndMenuEnabling(); SetStepButtonAndMenuEnabling(true); SetMenuEnablingForObjectsWOText(); MyEditItem.MyStepPanel.MyStepTabPanel.MyDisplayTabControl.OnModeChange(this, new StepRTBModeChangeEventArgs(MyEditItem.MyStepPanel.VwMode)); btnEditMode.Checked = btnCMEditMode1.Checked = MyEditItem.MyStepPanel.VwMode == E_ViewMode.View; MyEditItem.MyStepRTB.SpellCheckContextMenuOn(MyEditItem.MyStepPanel.VwMode != E_ViewMode.View); } - //private void btnEnhancedDocSync_Click(object sender, System.EventArgs e) - //{ - // btnEnhancedDocSync.Checked = !btnEnhancedDocSync.Checked; - //} - //C2019-036 View Only mode work with Checked Out Procedures - // using a blocking collection to make it thread safe in case someone - // spams hitting the refresh button - private BlockingCollection blockingRefreshProcedure = new BlockingCollection(); + //C2019-036 View Only mode work with Checked Out Procedures + // using a blocking collection to make it thread safe in case someone + // spams hitting the refresh button + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private BlockingCollection blockingRefreshProcedure = new BlockingCollection(); //C2019-036 View Only mode work with Checked Out Procedures private void btnRefreshProcedure_Click(object sender, EventArgs e) @@ -3428,37 +3147,35 @@ namespace Volian.Controls.Library public void RefreshProcedure() { - StepTabPanel stab_Panel = Parent as StepTabPanel; - - if (MyEditItem != null) - { + if (MyEditItem != null) + { if (!MyEditItem.MyStepPanel.ContainsFocus) - this.Invoke((Action)(() => { MyEditItem.MyStepPanel.Focus(); })); + this.Invoke((Action)(() => { MyEditItem.MyStepPanel.Focus(); })); E_ViewMode mode = MyEditItem.MyStepPanel.VwMode; - Application.DoEvents(); - this.Invoke((Action)(() => {MyEditItem.MyStepPanel.ResetAll();})); - Application.DoEvents(); - this.Invoke((Action)(() => {MyEditItem.MyStepPanel.Refresh();})); - Application.DoEvents(); - MyEditItem.MyStepPanel.VwMode = mode; - Application.DoEvents(); - } - else if (stab_Panel != null) - { - if (!stab_Panel.MyStepPanel.ContainsFocus) - this.Invoke((Action)(() => {stab_Panel.MyStepPanel.Focus();})); + Application.DoEvents(); + this.Invoke((Action)(() => { MyEditItem.MyStepPanel.ResetAll(); })); + Application.DoEvents(); + this.Invoke((Action)(() => { MyEditItem.MyStepPanel.Refresh(); })); + Application.DoEvents(); + MyEditItem.MyStepPanel.VwMode = mode; + Application.DoEvents(); + } + else if (Parent is StepTabPanel stab_Panel) + { + if (!stab_Panel.MyStepPanel.ContainsFocus) + this.Invoke((Action)(() => { stab_Panel.MyStepPanel.Focus(); })); - E_ViewMode mode = stab_Panel.MyStepPanel.VwMode; - Application.DoEvents(); - this.Invoke((Action)(() => {stab_Panel.MyStepPanel.ResetAll();})); - Application.DoEvents(); - this.Invoke((Action)(() => {stab_Panel.MyStepPanel.Refresh();})); - Application.DoEvents(); - stab_Panel.MyStepPanel.VwMode = mode; - Application.DoEvents(); - } - } + E_ViewMode mode = stab_Panel.MyStepPanel.VwMode; + Application.DoEvents(); + this.Invoke((Action)(() => { stab_Panel.MyStepPanel.ResetAll(); })); + Application.DoEvents(); + this.Invoke((Action)(() => { stab_Panel.MyStepPanel.Refresh(); })); + Application.DoEvents(); + stab_Panel.MyStepPanel.VwMode = mode; + Application.DoEvents(); + } + } private void btnROEdit_Click(object sender, EventArgs e) { if (VlnSettings.ReleaseMode.Equals("DEMO")) @@ -3466,7 +3183,6 @@ 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 if (roapp == null || roapp == string.Empty) { @@ -3477,27 +3193,21 @@ namespace Volian.Controls.Library { string errtxt = string.Format("Could not find path to Referenced Objects Editor:\n\n roapp = {0}\n\n Verify the path assigned to the 'roapp' environment variable", roapp); FlexibleMessageBox.Show(errtxt, "Environment Variable Error"); - //MessageBox.Show("Could not find path to Ro Editor, check 'roapp' environment variable","Environment Variable Error"); return; } - //if (roapp == null) - //{ - // MessageBox.Show("Could not find path to Ro Editor, check 'roapp' environment variable"); - // return; - //} if (Mydvi == null || Mydvi.DocVersionAssociationCount < 1) { FlexibleMessageBox.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 + "\""; + string roloc = $"\"{Mydvi.DocVersionAssociations[0].MyROFst.MyRODb.FolderPath}\""; if (!Directory.Exists(Mydvi.DocVersionAssociations[0].MyROFst.MyRODb.FolderPath)) { FlexibleMessageBox.Show(string.Format("RO Database directory does not exist: {0}", Mydvi.DocVersionAssociations[0].MyROFst.MyRODb.FolderPath)); return; } // C2017-003: ro data in sql server, check for sql connection string - if (Mydvi.DocVersionAssociations[0].MyROFst.MyRODb.DBConnectionString != "cstring") roloc = roloc + " \"" + Mydvi.DocVersionAssociations[0].MyROFst.MyRODb.DBConnectionString + "\""; + if (Mydvi.DocVersionAssociations[0].MyROFst.MyRODb.DBConnectionString != "cstring") roloc = $"{roloc} \"{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 @@ -3505,13 +3215,12 @@ namespace Volian.Controls.Library DocVersionInfoList dvil = DocVersionInfoList.Get(); foreach (DocVersionInfo dvi in dvil) { - DocVersionConfig dvc = dvi.DocVersionConfig as DocVersionConfig; - if (dvc != null && dvc.Unit_Name != "" && dvc.Unit_Count > 1) // B2021-089 only pass in applicability info if defined for more than one unit - { - roloc += " \"PC=" + dvc.Unit_Name + "\""; - break; - } - } + if (dvi.DocVersionConfig is DocVersionConfig dvc && dvc.Unit_Name != "" && dvc.Unit_Count > 1) // B2021-089 only pass in applicability info if defined for more than one unit + { + roloc += $" \"PC={dvc.Unit_Name}\""; + break; + } + } System.Diagnostics.Process.Start(roapp, roloc); } @@ -3528,27 +3237,13 @@ namespace Volian.Controls.Library } ROFstInfo roFstInfo = Mydvi.DocVersionAssociations[0].MyROFst; - string rofstPath = roFstInfo.MyRODb.FolderPath + @"\ro.fst"; + string rofstPath = $@"{roFstInfo.MyRODb.FolderPath}\ro.fst"; if (!File.Exists(rofstPath)) { FinalProgressBarMessage = "No existing RO.FST"; - FlexibleMessageBox.Show("No existing ro.fst in path " + roFstInfo.MyRODb.FolderPath + ". Check for invalid path", "No existing RO.FST"); //B2017-125 added title to messagebox + FlexibleMessageBox.Show($"No existing ro.fst in path {roFstInfo.MyRODb.FolderPath}. Check for invalid path", "No existing RO.FST"); //B2017-125 added title to messagebox return; } - // B2017-130 code no longer needed. Was checking the DTS but always was different by miliseconds - //FileInfo fiRofst = new FileInfo(rofstPath); - //if (roFstInfo.DTS == fiRofst.LastWriteTimeUtc) - //{ - // FinalProgressBarMessage = "RO.FST up to date"; - // MessageBox.Show("ro.fst files are same for path " + roFstInfo.MyRODb.FolderPath + ", import of that ro.fst will not be done", "RO.FST up to date"); //B2017-125 added title to messagebox - // return; - //} - //if (roFstInfo.DTS > fiRofst.LastWriteTimeUtc) - //{ - // FinalProgressBarMessage = "RO.FST is older"; - // MessageBox.Show("Cannot copy older ro.fst from " + roFstInfo.MyRODb.FolderPath + ", import of that ro.fst will not be done", "RO.FST is older"); //B2017-125 added title to messagebox - // return; - //} Cursor = Cursors.WaitCursor; // C2023-001: Check whether docversion can be checked out before continuing with update of ro.fst string message = string.Empty; @@ -3614,13 +3309,8 @@ namespace Volian.Controls.Library 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)); } - private ProgressBarItem _ProgressBar = null; - public ProgressBarItem ProgressBar - { - get { return _ProgressBar; } - set { _ProgressBar = value; } - } - private void DoProgressBarRefresh(int value, int max, string text) + public ProgressBarItem ProgressBar { get; set; } = null; + private void DoProgressBarRefresh(int value, int max, string text) { if (ProgressBar == null) return; ProgressBar.Maximum = max; @@ -3653,51 +3343,9 @@ namespace Volian.Controls.Library } } - public List roFstInfo_ROTableUpdate(object sender, ROFstInfoROTableUpdateEventArgs args) - { - return VlnFlexGrid.ROTableUpdate(sender, args); - //string xml = null; - //string srchtxt = null; - //Content content = (Content)sender; - //using (VlnFlexGrid myGrid = new VlnFlexGrid(content.ContentItems[0])) - //{ - // using (StringReader sr = new StringReader(args.OldGridXml)) - // { - // myGrid.ReadXml(sr); - // sr.Close(); - // } - // string roid = content.ContentRoUsages[0].ROID; //myGrid.ROID; - // int rodbid = content.ContentRoUsages[0].RODbID; //myGrid.RODbId; - // ////Font GridFont = myGrid.Font; - // //myGrid.MergedRanges.Clear(); - // //myGrid.Clear(); - // //myGrid.ParseTableFromText(args.ROText); - // //myGrid.AutoSizeCols(); - // //myGrid.AutoSizeRows(); - // //myGrid.MakeRTFcells(); - // //myGrid.RODbId = rodbid; - // //myGrid.ROID = roid; - // //myGrid.IsRoTable = true; - // myGrid.Visible = false; - // myGrid.ConvertTableROToGrid(args.ROText, rodbid, roid); - // myGrid.FixTableCellsHeightWidth(); - // myGrid.AdjustGridControlSize(); - // myGrid.Visible = 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; - } + public List roFstInfo_ROTableUpdate(object sender, ROFstInfoROTableUpdateEventArgs args) => VlnFlexGrid.ROTableUpdate(sender, args); - private void rtabAdmin_Click(object sender, EventArgs e) + private void rtabAdmin_Click(object sender, EventArgs e) { ribbonTab_SingleClick(sender, e); btnUpdROVal.Enabled = false; @@ -3716,11 +3364,8 @@ namespace Volian.Controls.Library // only allow update if association, and the RO update was not done and/or not completed return !_Mydvi.ROfstLastCompleted || _Mydvi.NewerRoFst; } - public void SetUpdRoValBtn(bool en) - { - btnUpdROVal.Enabled = en; - } - private void btnBookmarks_Click(object sender, EventArgs e) + public void SetUpdRoValBtn(bool en) => btnUpdROVal.Enabled = en; + private void btnBookmarks_Click(object sender, EventArgs e) { StepPanelTabDisplayEventArgs args = new StepPanelTabDisplayEventArgs("Bookmarks"); MyEditItem.MyStepPanel.OnTabDisplay(sender, args); @@ -3737,12 +3382,9 @@ namespace Volian.Controls.Library StepPanelTabDisplayEventArgs args = new StepPanelTabDisplayEventArgs("LibDocs"); MyEditItem.MyStepPanel.OnTabDisplay(sender, args); } - // C2020-033: Support the Review/Incoming Transition button to bring up Search/Incoming Transitions panel - private void btnSearchIncTrans_Click(object sender, EventArgs e) - { - MyEditItem.MyStepPanel.MyStepTabPanel.MyDisplayTabControl.OnSearchIncTrans(this, new vlnTreeItemInfoEventArgs(MyStepRTB.MyItemInfo)); - } - public void btnAnnots_Click(object sender, EventArgs e) + // C2020-033: Support the Review/Incoming Transition button to bring up Search/Incoming Transitions panel + private void btnSearchIncTrans_Click(object sender, EventArgs e) => MyEditItem.MyStepPanel.MyStepTabPanel.MyDisplayTabControl.OnSearchIncTrans(this, new vlnTreeItemInfoEventArgs(MyStepRTB.MyItemInfo)); + public void btnAnnots_Click(object sender, EventArgs e) { StepPanelTabDisplayEventArgs args = new StepPanelTabDisplayEventArgs("Annots"); MyEditItem.MyStepPanel.OnTabDisplay(sender, args); @@ -3762,34 +3404,32 @@ namespace Volian.Controls.Library } bool surpressMessageBox = (e == null); - SectionInfo si = MyEditItem.MyItemInfo as SectionInfo; - if (si != null) - { - //C2020-026 specific description of what user is trying to delete - string msg = "Are you sure you want to delete this Section" + (si.HasChildren ? " and its steps?" : "?"); - DialogResult result = FlexibleMessageBox.Show(msg, "Verify Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question); - if (result == DialogResult.Yes) - { + if (MyEditItem.MyItemInfo is SectionInfo si) + { + //C2020-026 specific description of what user is trying to delete + string msg = "Are you sure you want to delete this Section" + (si.HasChildren ? " and its steps?" : "?"); + DialogResult result = FlexibleMessageBox.Show(msg, "Verify Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question); + if (result == DialogResult.Yes) + { - if (!si.IsStepSection) - { - WordSectionEventArgs args = new WordSectionEventArgs(si); - MyEditItem.MyStepPanel.OnWordSectionClose(sender, args); - } - MyEditItem.RemoveItem(); - } - return; - } - StepInfo stpi = MyEditItem.MyItemInfo as StepInfo; - if (stpi == null) // not sure that it will every get here! - { - FlexibleMessageBox.Show("Unknown type {0}, cannot delete!", MyEditItem.MyItemInfo.GetType().Name); - return; - } - if (!surpressMessageBox) + if (!si.IsStepSection) + { + WordSectionEventArgs args = new WordSectionEventArgs(si); + MyEditItem.MyStepPanel.OnWordSectionClose(sender, args); + } + MyEditItem.RemoveItem(); + } + return; + } + if (!(MyEditItem.MyItemInfo is StepInfo stpi)) // not sure that it will every get here! + { + FlexibleMessageBox.Show("Unknown type {0}, cannot delete!", MyEditItem.MyItemInfo.GetType().Name); + return; + } + if (!surpressMessageBox) { string typeDescription = MyEditItem.MyStepData.StepEditData.TypeMenu.MenuItem; - string msgs = ""; + string msgs; if (MyFlexGrid != null) MyEditItem.IdentifyMe(true); MyEditItem.IdentifyChildren(true); //C2020-026 specific description of what user is trying to delete @@ -3798,7 +3438,7 @@ namespace Volian.Controls.Library else msgs = string.Format("Are you sure you want to delete this \"{0}\"?", typeDescription); if (stpi.HasEnhancedLinkedStep) - msgs = msgs + "\n\n The linked Enhanced step will also be deleted!"; + msgs += "\n\n The linked Enhanced step will also be deleted!"; DialogResult results = FlexibleMessageBox.Show(msgs, "Verify Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (MyFlexGrid != null) { @@ -3829,12 +3469,9 @@ namespace Volian.Controls.Library } } - private void btnCMIns_PopupClose(object sender, EventArgs e) - { - _ContextMenuBar.SetContextMenuEx(_MyStepRTB, _DefaultContextMenu); - } + private void btnCMIns_PopupClose(object sender, EventArgs e) => _ContextMenuBar.SetContextMenuEx(_MyStepRTB, _DefaultContextMenu); - public void SetShortCutContextMenu(string menuName) + public void SetShortCutContextMenu(string menuName) { bool displayMenu = false; int moveDown = 0; @@ -3842,13 +3479,12 @@ namespace Volian.Controls.Library E_AccStep? actable = 0; if (menuName.Contains("PSI")) Console.WriteLine("menu = {0}", menuName); - StepData sd = MyItemInfo==null?null:MyItemInfo.FormatStepData; + StepData sd = MyItemInfo?.FormatStepData; if (sd != null) // will be null if section { actable = sd.StepEditData.AcTable; if (actable == null) actable = 0; } - //btnInsCaut.Enabled = (actable & E_AccStep.AddingCaution) > 0; switch (menuName) { case "OpenRtfRawContextMenu": @@ -3865,7 +3501,7 @@ namespace Volian.Controls.Library _ContextMenuBar.SetContextMenuEx(_MyStepRTB, btnCMInsHLS); string lookfor = "XXX"; if(_MyStepRTB.MyItemInfo.MyHLS != null) - lookfor = " " + (_MyStepRTB.MyItemInfo.MyHLS.MyContent.Type - 20000).ToString(); + lookfor = $" {_MyStepRTB.MyItemInfo.MyHLS.MyContent.Type - 20000}"; foreach (DevComponents.DotNetBar.ButtonItem bi in btnCMInsHLS.SubItems) { if (bi.Checked) @@ -3958,39 +3594,31 @@ namespace Volian.Controls.Library StepPanelTabDisplayEventArgs args = new StepPanelTabDisplayEventArgs("SpellChecker"); MyEditItem.MyStepPanel.OnTabDisplay(sender, args); } - private void btnTranRefresh_Click(object sender, System.EventArgs e) - { + private void btnTranRefresh_Click(object sender, System.EventArgs e) + { // This code is disabled - Button is not visible - this.Cursor = Cursors.WaitCursor; - ProcedureInfo.RefreshTransitions(MyItemInfo.MyProcedure as ProcedureInfo); - this.Cursor = Cursors.Default; + this.Cursor = Cursors.WaitCursor; + ProcedureInfo.RefreshTransitions(MyItemInfo.MyProcedure as ProcedureInfo); + this.Cursor = Cursors.Default; // B2018-002 - Invalid Transitions - Display Transition Refresh Statistics FlexibleMessageBox.Show(this, string.Format("Checked {0} transitions, modified {1} transitions, converted to text {2} transitions, {3} transitions unable to be fixed (Annotation: Bad Transition Link)", ProcedureInfo.TranCheckCount, ProcedureInfo.TranFixCount, ProcedureInfo.TranConvertCount, ProcedureInfo.TranCantFixCount), "Results of Refresh Transitions", MessageBoxButtons.OK, MessageBoxIcon.Information); - } - 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); - } - //private FindReplace dlgFindReplace = null; + } + void btnRefObjRefresh_Click(object sender, System.EventArgs e) + { + //Causes Refresh + } private void btnFindRplDlg_Click(object sender, EventArgs e) { - if (MyEditItem == null || MyEditItem.MyStepPanel == null) return; - StepPanelTabDisplayEventArgs args = new StepPanelTabDisplayEventArgs("FndRpl"); + if (MyEditItem == null || MyEditItem.MyStepPanel == null) return; + StepPanelTabDisplayEventArgs args = new StepPanelTabDisplayEventArgs("FndRpl"); MyEditItem.MyStepPanel.OnTabDisplay(sender, args); } private void InsertSiblingBeforeOrAfter(string b4aftr) { - E_AccStep? actable = 0; - StepData sd = MyItemInfo.FormatStepData; - actable = sd.StepEditData.AcTable; - if (actable == null) actable = 0; - switch (b4aftr) + StepData sd = MyItemInfo.FormatStepData; + E_AccStep? actable = sd.StepEditData.AcTable ?? 0; + switch (b4aftr) { case "after": if ((actable & E_AccStep.AddingNext) > 0) @@ -4256,12 +3884,9 @@ namespace Volian.Controls.Library // just return } - private void btnCpyStp_Click(object sender, EventArgs e) - { - DoCopyStep(); - } + private void btnCpyStp_Click(object sender, EventArgs e) => DoCopyStep(); - public void DoCopyStep() + public void DoCopyStep() { MyEditItem.SaveCurrentAndContents(); // B2025-038 copy step and text to another procedure in another screen. // highlight selected step(s) and prompt to see if selection is what user wants: @@ -4311,56 +3936,50 @@ namespace Volian.Controls.Library private void btnPdfCreate_Click(object sender, EventArgs e) { - // B2025-036 split screen print issue. if oringFlg == 1 the ctrl-p keys was pressed. - _OringFlg = 0; + // B2025-036 split screen print issue. if oringFlg == 1 the ctrl-p keys was pressed. + OringFlg = 0; DevComponents.DotNetBar.eEventSource oring = ((DevComponents.DotNetBar.Events.EventSourceArgs)e).Source; if (oring == eEventSource.Keyboard) - _OringFlg = 1; + OringFlg = 1; int selectedSlave = MyItemInfo.MyProcedure.ProcedureConfig.SelectedSlave; if (MyItemInfo == null) return; // if creating a pdf before rtb exists, return; - if (MyEditItem != null) MyEditItem.SaveCurrentAndContents(); + MyEditItem?.SaveCurrentAndContents(); MyItemInfo.MyProcedure.ProcedureConfig.SelectedSlave = selectedSlave; - OnPrintRequest(new StepTabRibbonEventArgs(MyItemInfo.MyProcedure, _OringFlg), 0); + OnPrintRequest(new StepTabRibbonEventArgs(MyItemInfo.MyProcedure, OringFlg), 0); } private void btnPdfQuickCreate_Click(object sender, EventArgs e) { int selectedSlave = MyItemInfo.MyProcedure.ProcedureConfig.SelectedSlave; if (MyItemInfo == null) return; // if creating a pdf before rtb exists, return; - if (MyEditItem != null) MyEditItem.SaveCurrentAndContents(); + MyEditItem?.SaveCurrentAndContents(); MyItemInfo.MyProcedure.ProcedureConfig.SelectedSlave = selectedSlave; - OnPrintRequest(new StepTabRibbonEventArgs(MyItemInfo.MyProcedure, _OringFlg), 1); + OnPrintRequest(new StepTabRibbonEventArgs(MyItemInfo.MyProcedure, OringFlg), 1); } private void btnCASCreate_Click(object sender, EventArgs e) { if (MyItemInfo == null) return; // if creating a Continuous Action Summary before rtb exists, return; - if (MyEditItem != null) MyEditItem.SaveCurrentAndContents(); + MyEditItem?.SaveCurrentAndContents(); OnContActionSummaryRequest(new StepTabRibbonEventArgs(MyItemInfo.MyProcedure)); } #region Table Grid #region TablePicker code - // TODO: for tables - //private void btnInsTable_Click(object sender, EventArgs e) - //{ - // Point loc = btnInsTable.DisplayRectangle.Location; - // loc.X += 300; - // int top = this.Top + (btnInsTable.Size.Height * 2); - // TablePickerDlg(sender, e, loc, top); - //} private VlnFlexGrid CreateNewTable() { Point pt = Cursor.Position; int left = pt.X; VlnFlexGrid grd = null; - TablePicker tpdlg = new TablePicker(); - tpdlg.Location = pt; - tpdlg.Left = left; - tpdlg.MaxCols = 20; - tpdlg.MaxRows = 30; - DialogResult dr = tpdlg.ShowDialog(); + TablePicker tpdlg = new TablePicker + { + Location = pt, + Left = left, + MaxCols = 20, + MaxRows = 30 + }; + DialogResult dr = tpdlg.ShowDialog(); while (tpdlg.Visible) { Application.DoEvents(); @@ -4378,86 +3997,59 @@ namespace Volian.Controls.Library } return grd; } - //private void InitializeNewGrid(C1FlexGrid grd) - //{ - // int numCols = grd.Cols.Count - 1; - // int numRows = grd.Rows.Count - 1; + #endregion + #region Table Grid Copy/Paste + private void btnTblDgnCopyRow_Click(object sender, EventArgs e) => MyFlexGrid.CopyRow(); - // string defText = ""; - // if (textBoxX1.Text.Length > 0) - // defText = textBoxX1.Text; - // else - // defText = textBoxX1.WatermarkText; - // grd.SetData(grd.GetCellRange(0, 0, numRows, numCols), defText); - //} - #endregion - #region Table Grid Copy/Paste - private void btnTblDgnCopyRow_Click(object sender, EventArgs e) - { - MyFlexGrid.CopyRow(); - } + private void btnTblDgnCopyColumn_Click(object sender, EventArgs e) => MyFlexGrid.CopyColumn(); - private void btnTblDgnCopyColumn_Click(object sender, EventArgs e) - { - MyFlexGrid.CopyColumn(); - } + private void btnTblDgnCopySelection_Click(object sender, EventArgs e) => MyFlexGrid.CopyCellSelection(); - private void btnTblDgnCopySelection_Click(object sender, EventArgs e) - { - MyFlexGrid.CopyCellSelection(); - } - - private void btnTblDgnPasteRowAbove_Click(object sender, EventArgs e) + private void btnTblDgnPasteRowAbove_Click(object sender, EventArgs e) { // create new rows before current position and copy clipboard data MyFlexGrid.PasteRows(VlnFlexGrid.enmPastePos.Before); - GridItem tmp = MyEditItem as GridItem; - if (tmp!=null) tmp.SavePastedCellRoTran(); - } + if (MyEditItem is GridItem tmp) tmp.SavePastedCellRoTran(); + } private void btnTblDgnPasteRowBelow_Click(object sender, EventArgs e) { // create new rows after current position and copy clipboard data MyFlexGrid.PasteRows(VlnFlexGrid.enmPastePos.After); GridItem tmp = MyEditItem as GridItem; - if (tmp != null) tmp.SavePastedCellRoTran(); + tmp?.SavePastedCellRoTran(); } private void btnTblDgnPasteReplaceRow_Click(object sender, EventArgs e) { // replace rows with current clipboard data starting as current row MyFlexGrid.PasteRows(VlnFlexGrid.enmPastePos.Replace); - GridItem tmp = MyEditItem as GridItem; - if (tmp != null) tmp.SavePastedCellRoTran(); - } + if (MyEditItem is GridItem tmp) tmp.SavePastedCellRoTran(); + } private void btnTblDgnPasteColumnLeft_Click(object sender, EventArgs e) { MyFlexGrid.PasteColumns(VlnFlexGrid.enmPastePos.Before); - GridItem tmp = MyEditItem as GridItem; - if (tmp != null) tmp.SavePastedCellRoTran(); - } + if (MyEditItem is GridItem tmp) tmp.SavePastedCellRoTran(); + } private void btnTblDgnPasteColumnRight_Click(object sender, EventArgs e) { MyFlexGrid.PasteColumns(VlnFlexGrid.enmPastePos.After); - GridItem tmp = MyEditItem as GridItem; - if (tmp != null) tmp.SavePastedCellRoTran(); - } + if (MyEditItem is GridItem tmp) tmp.SavePastedCellRoTran(); + } private void btnTblDgnPasteColumnReplace_Click(object sender, EventArgs e) { MyFlexGrid.PasteColumns(VlnFlexGrid.enmPastePos.Replace); - GridItem tmp = MyEditItem as GridItem; - if (tmp != null) tmp.SavePastedCellRoTran(); - } + if (MyEditItem is GridItem tmp) tmp.SavePastedCellRoTran(); + } private void btnTblDgnPasteIntoSelection_Click(object sender, EventArgs e) { MyFlexGrid.PasteCopiedCells(); - GridItem tmp = MyEditItem as GridItem; - if (tmp != null) tmp.SavePastedCellRoTran(); - } + if (MyEditItem is GridItem tmp) tmp.SavePastedCellRoTran(); + } #endregion #region Table Grid Delete @@ -4479,13 +4071,6 @@ namespace Volian.Controls.Library #endregion #region Table Grid Cell Style - - //private void cpHighlight_SelectedColorChanged(object sender, EventArgs e) - //{ - // string strColor = string.Format("{0}, {1}, {2};", cpTblDgnHighlight.SelectedColor.R, cpTblDgnHighlight.SelectedColor.G, cpTblDgnHighlight.SelectedColor.B); - // MyFlexGrid.ChangeBackgroundColor(strColor); - //} - private void btnTblDgnAlgnTxTopLeft_Click(object sender, EventArgs e) { MyFlexGrid.ChangeCellAlign(MyFlexGrid.Selection, C1.Win.C1FlexGrid.TextAlignEnum.LeftTop); @@ -4565,28 +4150,16 @@ namespace Volian.Controls.Library { MyFlexGrid.MergeSelection(); } - #endregion - #region Table Grid Design - private void btnTblDgnInsertRowAbove_Click(object sender, EventArgs e) - { - MyFlexGrid.InsertRowBefore(); - } + #endregion + #region Table Grid Design + private void btnTblDgnInsertRowAbove_Click(object sender, EventArgs e) => MyFlexGrid.InsertRowBefore(); - private void btnTblDgnInsertRowBelow_Click(object sender, EventArgs e) - { - MyFlexGrid.InsertRowAfter(); - } + private void btnTblDgnInsertRowBelow_Click(object sender, EventArgs e) => MyFlexGrid.InsertRowAfter(); - private void btnTblDgnInsertColumnBefore_Click(object sender, EventArgs e) - { - MyFlexGrid.InsertColumnBefore(); - } + private void btnTblDgnInsertColumnBefore_Click(object sender, EventArgs e) => MyFlexGrid.InsertColumnBefore(); - private void btnTblDgnInsertColumnAfter_Click(object sender, EventArgs e) - { - MyFlexGrid.InsertColumnAfter(); - } - public void ToggleTableFontSize(bool visible) + private void btnTblDgnInsertColumnAfter_Click(object sender, EventArgs e) => MyFlexGrid.InsertColumnAfter(); + public void ToggleTableFontSize(bool visible) { bool visl = visible; if (MyFlexGrid != null) @@ -4626,8 +4199,6 @@ namespace Volian.Controls.Library btnCmGridInsert.Enabled = enableContent; btnCmGridCopy.Enabled = enableContent; btnCmGridRemove.Enabled = enableContent; - //btnTblDgnGridStyle.Enabled = enable; - //rbTblBorder.Enabled = enable; rbnBorderlistBox.Enabled = enable; rbnBorderSelectionPanel.Enabled = enable; btnTblNoBorder.Enabled = enable; @@ -4650,16 +4221,11 @@ namespace Volian.Controls.Library if (_MyStepRTB != null) btnIndent.Checked = _MyStepRTB.SelectionHangingIndent != 0; } - public void SetRibbonForGridCellIndentClear() - { - btnIndent.Checked = false; - } - public void SetRibbonForGrid() + public void SetRibbonForGridCellIndentClear() => btnIndent.Checked = false; + public void SetRibbonForGrid() { // for paste, see if there is clipboard data, & if so, of a type we can use. IDataObject iData = Clipboard.GetDataObject(); - // set to true if editing cell, otherwise false for grids - //bool enable = (MyFlexGrid != null && MyFlexGrid.Editor != null); // B2017-208 toggle on/off attributes button checks when you edit table cells, going from one cell to another // Also don't keep the attributes buttons checked after setting a group of table cells all at one time @@ -4670,7 +4236,6 @@ namespace Volian.Controls.Library btnCMSuperscript.Checked = btnSuperscript.Checked = RTBAPI.IsSuperScript(_MyStepRTB) && (MyFlexGrid == null || MyFlexGrid.TableCellEditor.EditMode); bool enable = (MyFlexGrid != null && MyEditItem.MyStepPanel.VwMode == E_ViewMode.Edit); - //btnPasteText.Enabled = btnPasteStepText.Enabled = btnPaste.Enabled = enable; btnPaste.Enabled = (iData.GetDataPresent(DataFormats.Text) || iData.GetDataPresent(DataFormats.Rtf)) && enable; btnCMPasteText.Enabled = btnPasteText.Enabled = iData.GetDataPresent(DataFormats.Text) && enable; btnCMPaste.Enabled = btnPasteStepText.Enabled = iData.GetDataPresent(DataFormats.Rtf ) && enable; @@ -4693,7 +4258,7 @@ namespace Volian.Controls.Library // C2021-005 get the font size being used in the selected table cell(s) then ititialize the font dropdown public void SetFontSizeDropDown() { - float sz = GetTableCellFontSize(SelectionOption.All); + float sz = GetTableCellFontSize(); SetFontSizeDropDownText(sz); } // C2021-005 Initialize the font size dropdown @@ -4716,7 +4281,6 @@ namespace Volian.Controls.Library MyFlexGrid.Rows.Fixed = MyFlexGrid.Rows.Count; MyFlexGrid.StyleBackColor = MyFlexGrid.DefaultFixedBackgroundColor; // C2021-004 force the fixed background color ToggleTableDesignButtons(false); - //MyFlexGrid.ListStyles(); } else { @@ -4725,108 +4289,25 @@ namespace Volian.Controls.Library MyFlexGrid.Rows.Fixed = 0; MyFlexGrid.ShowTableCellShading(); // C2021-004 show the table cell colors ToggleTableDesignButtons(true); - //MyFlexGrid.ListStyles(); } } - #endregion - #region Table Grid Border - private void btnTblDgnTableBorderNone_Click(object sender, EventArgs e) - { - MyFlexGrid.SetTableBorder(C1.Win.C1FlexGrid.Util.BaseControls.BorderStyleEnum.None); - } + #endregion + private void rbnBorderlistBox_SelectedIndexChanged(object sender, EventArgs e) => rbnBorderSelectionPanel.SelectedBorder = rbnBorderlistBox.SelectedLinePattern; - private void btnTblDgnTableBorderFixedSingle_Click(object sender, EventArgs e) + private void rbnBorderSelectionPanel_BordersChanged(object sender, EventArgs args) { - MyFlexGrid.SetTableBorder(C1.Win.C1FlexGrid.Util.BaseControls.BorderStyleEnum.FixedSingle); - } - - private void btnTblDgnTableBorderFixed3D_Click(object sender, EventArgs e) - { - MyFlexGrid.SetTableBorder(C1.Win.C1FlexGrid.Util.BaseControls.BorderStyleEnum.Fixed3D); - } - - private void btnTblDgnTableBorderLight3D_Click(object sender, EventArgs e) - { - MyFlexGrid.SetTableBorder(C1.Win.C1FlexGrid.Util.BaseControls.BorderStyleEnum.Light3D); - } - - private void btnTblDgnTableBorderXPThemes_Click(object sender, EventArgs e) - { - MyFlexGrid.SetTableBorder(C1.Win.C1FlexGrid.Util.BaseControls.BorderStyleEnum.XpThemes); - } - #endregion - #region Table Grid Grid Style - private void btnTblDgnGridStyleNone_Click(object sender, EventArgs e) - { - MyFlexGrid.ChangeCellBorder(MyFlexGrid.Selection, C1.Win.C1FlexGrid.BorderStyleEnum.None); - } - - private void btnTblDgnGridStyleFlat_Click(object sender, EventArgs e) - { - MyFlexGrid.ChangeCellBorder(MyFlexGrid.Selection, C1.Win.C1FlexGrid.BorderStyleEnum.Flat); - } - - private void btnTblDgnGridStyleDouble_Click(object sender, EventArgs e) - { - MyFlexGrid.ChangeCellBorder(MyFlexGrid.Selection, C1.Win.C1FlexGrid.BorderStyleEnum.Double); - } - - private void btnTblDgnGridStyleRaised_Click(object sender, EventArgs e) - { - MyFlexGrid.ChangeCellBorder(MyFlexGrid.Selection, C1.Win.C1FlexGrid.BorderStyleEnum.Raised); - } - - private void btnTblDgnGridStyleInset_Click(object sender, EventArgs e) - { - MyFlexGrid.ChangeCellBorder(MyFlexGrid.Selection, C1.Win.C1FlexGrid.BorderStyleEnum.Inset); - } - - private void btnTblDgnGridStyleGroove_Click(object sender, EventArgs e) - { - MyFlexGrid.ChangeCellBorder(MyFlexGrid.Selection, C1.Win.C1FlexGrid.BorderStyleEnum.Groove); - } - - private void btnTblDgnGridStyleFillet_Click(object sender, EventArgs e) - { - MyFlexGrid.ChangeCellBorder(MyFlexGrid.Selection, C1.Win.C1FlexGrid.BorderStyleEnum.Fillet); - } - - private void btnTblDgnGridStyleDotted_Click(object sender, EventArgs e) - { - MyFlexGrid.ChangeCellBorder(MyFlexGrid.Selection, C1.Win.C1FlexGrid.BorderStyleEnum.Dotted); - } - #endregion - - private void rbnBorderlistBox_SelectedIndexChanged(object sender, EventArgs e) - { - rbnBorderSelectionPanel.SelectedBorder = rbnBorderlistBox.SelectedLinePattern; - } - - private void rbnBorderSelectionPanel_BordersChanged(object sender, EventArgs args) - { - //C1.Win.C1FlexGrid.CellRange cr = MyFlexGrid.GetEvenSelection(); MyFlexGrid.SetBorders(MyFlexGrid.Selection, rbnBorderSelectionPanel.TopBorder, rbnBorderSelectionPanel.InsideHorizontalBorder, rbnBorderSelectionPanel.BottomBorder, rbnBorderSelectionPanel.LeftBorder, rbnBorderSelectionPanel.InsideVerticalBorder, rbnBorderSelectionPanel.RightBorder); MyEditItem.Invalidate(); MyFlexGrid.Invalidate(); } - private void btnTblNoBorder_Click(object sender, EventArgs e) - { - rbnBorderSelectionPanel.AllBorders = GridLinePattern.None; - } - private void btnTblOutline_Click(object sender, EventArgs e) - { - rbnBorderSelectionPanel.OutlineBorder = rbnBorderlistBox.SelectedLinePattern; - } - private void btnTblInside_Click(object sender, EventArgs e) - { - rbnBorderSelectionPanel.InsideBorders = rbnBorderlistBox.SelectedLinePattern; - } - private void rbnBorderlistBox_Resize(object sender, EventArgs e) + private void btnTblNoBorder_Click(object sender, EventArgs e) => rbnBorderSelectionPanel.AllBorders = GridLinePattern.None; + private void btnTblOutline_Click(object sender, EventArgs e) => rbnBorderSelectionPanel.OutlineBorder = rbnBorderlistBox.SelectedLinePattern; + private void btnTblInside_Click(object sender, EventArgs e) => rbnBorderSelectionPanel.InsideBorders = rbnBorderlistBox.SelectedLinePattern; + private void rbnBorderlistBox_Resize(object sender, EventArgs e) { rbnBorderSelectionPanel.Size = rbnBorderlistBox.Size; _RibbonControl.Height = rbnBorderlistBox.Height + _RibbonControl.Height - _RibbonControl.ClientSize.Height; - //_RibbonControl.Height = rbnBorderlistBox.Height + _RibbonControl.Height - _RibbonControl.ClientSize.Height; } #region Expand/Collaspe Ribbon // In MS Word, a Double Click of a ribbon tab will toggle (Expand/Collapse) the ribbon. @@ -4907,11 +4388,8 @@ namespace Volian.Controls.Library fiwc.FormClosed += fiwc_FormClosed; fiwc.Show(); } - void fiwc_FormClosed(object sender, FormClosedEventArgs e) - { - fiwc = null; - } - private void btnCMImgSz_Click(object sender, EventArgs e) + void fiwc_FormClosed(object sender, FormClosedEventArgs e) => fiwc = null; + private void btnCMImgSz_Click(object sender, EventArgs e) { StepPanelTabDisplayEventArgs args = new StepPanelTabDisplayEventArgs("Change Image Size"); MyEditItem.MyStepPanel.OnTabDisplay(sender, args); @@ -4952,15 +4430,19 @@ namespace Volian.Controls.Library if (MyItemInfo == null || MyItemInfo.ActiveFormat.PlantFormat.FormatData.ShadingOptionList == null) return; //not shading options defined in format if (!_CustomButtonAdded) { - ButtonItem button = new ButtonItem(); - button.Text = "More Shading Options..."; - button.BeginGroup = true; - foreach (ShadingOption ShadeOpt in MyItemInfo.ActiveFormat.PlantFormat.FormatData.ShadingOptionList) + ButtonItem button = new ButtonItem + { + Text = "More Shading Options...", + BeginGroup = true + }; + foreach (ShadingOption ShadeOpt in MyItemInfo.ActiveFormat.PlantFormat.FormatData.ShadingOptionList) { - ButtonItem btn = new ButtonItem(); - btn.Tag = ShadeOpt; - btn.Text = ShadeOpt.ToString(); - btn.Click += new EventHandler(MoreShadingOptionsClick); + ButtonItem btn = new ButtonItem + { + Tag = ShadeOpt, + Text = ShadeOpt.ToString() + }; + btn.Click += new EventHandler(MoreShadingOptionsClick); button.SubItems.Add(btn); } btnCellShading.SubItems.Add(button); @@ -4985,7 +4467,7 @@ namespace Volian.Controls.Library private void btnTCASCreate_Click(object sender, EventArgs e) { if (MyItemInfo == null) return; // if creating a Time Critical Action Summary before rtb exists, return; - if (MyEditItem != null) MyEditItem.SaveCurrentAndContents(); + MyEditItem?.SaveCurrentAndContents(); OnTimeCriticalActionSummaryRequest(new StepTabRibbonEventArgs(MyItemInfo.MyProcedure)); } } @@ -4994,27 +4476,16 @@ namespace Volian.Controls.Library public StepTabRibbonEventArgs() { ; } public StepTabRibbonEventArgs(ItemInfo proc, int oringFlg = 0, E_ViewMode viewMode = E_ViewMode.Edit) { - _Proc = proc; + Proc = proc; OringFlg = oringFlg; ViewMode = viewMode; } - private ItemInfo _Proc; - public ItemInfo Proc - { - get { return _Proc; } - set { _Proc = value; } - } - // B2025-036 split screen print issue. if oringFlg == 1 the ctrl-p keys was pressed. - private int _OringFlg; - public int OringFlg - { - get { return _OringFlg; } - set { _OringFlg = value; } - } + public ItemInfo Proc { get; set; } + public int OringFlg { get; set; } - //C2019-036 View Only mode work with Checked Out Procedures - public E_ViewMode ViewMode { get; set; } + //C2019-036 View Only mode work with Checked Out Procedures + public E_ViewMode ViewMode { get; set; } } public delegate void StepTabRibbonEvent(object sender, StepTabRibbonEventArgs args); diff --git a/PROMS/Volian.Controls.Library/StepTabRibbon.designer.cs b/PROMS/Volian.Controls.Library/StepTabRibbon.designer.cs index a7dc72ad..91ff330b 100644 Binary files a/PROMS/Volian.Controls.Library/StepTabRibbon.designer.cs and b/PROMS/Volian.Controls.Library/StepTabRibbon.designer.cs differ diff --git a/PROMS/Volian.Controls.Library/TablePropertiesControl.cs b/PROMS/Volian.Controls.Library/TablePropertiesControl.cs index 42afccfd..d8b7accd 100644 --- a/PROMS/Volian.Controls.Library/TablePropertiesControl.cs +++ b/PROMS/Volian.Controls.Library/TablePropertiesControl.cs @@ -24,6 +24,7 @@ namespace Volian.Controls.Library }; private DataTable values; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping bindingSource flexible")] private BindingSource bindingSource = null; private int totalrows = 1; private int totalcols = 1; @@ -104,8 +105,10 @@ namespace Volian.Controls.Library void FormLoad_setDefaults(object sender, EventArgs e) { - BindingSource bindingSourceDropDown = new BindingSource(); - bindingSourceDropDown.DataSource = Enum.GetNames(typeof(EPinputtype)); + BindingSource bindingSourceDropDown = new BindingSource + { + DataSource = Enum.GetNames(typeof(EPinputtype)) + }; //in order to achieve a dropdown of possible values need //to remove the auto-inserted columns @@ -114,8 +117,10 @@ namespace Volian.Controls.Library for (int c = 0; c < totalcols; c++) { dataview.Columns.RemoveAt(c); - var cName = new DataGridViewComboBoxColumn(); - cName.DataSource = bindingSourceDropDown; + var cName = new DataGridViewComboBoxColumn + { + DataSource = bindingSourceDropDown + }; cName.DefaultCellStyle.NullValue = "none"; dataview.Columns.Insert(c, cName); } @@ -200,8 +205,10 @@ namespace Volian.Controls.Library int endNumCols = (int)NumCols.Value; int curNumCols = totalcols; - BindingSource bindingSourceDropDown = new BindingSource(); - bindingSourceDropDown.DataSource = Enum.GetNames(typeof(EPinputtype)); + BindingSource bindingSourceDropDown = new BindingSource + { + DataSource = Enum.GetNames(typeof(EPinputtype)) + }; //remove cols till equal while (curNumCols > endNumCols) @@ -215,8 +222,10 @@ namespace Volian.Controls.Library { values.Columns.Add(new DataColumn($"Column{curNumCols + 1}") { DefaultValue = "none"}); if (dataview.Columns.Count > curNumCols) dataview.Columns.RemoveAt(curNumCols); - var cName = new DataGridViewComboBoxColumn(); - cName.DataSource = bindingSourceDropDown; + var cName = new DataGridViewComboBoxColumn + { + DataSource = bindingSourceDropDown + }; cName.DefaultCellStyle.NullValue = "none"; dataview.Columns.Add(cName); diff --git a/PROMS/Volian.Controls.Library/TransPanel.cs b/PROMS/Volian.Controls.Library/TransPanel.cs index fa59f0c1..a84be058 100644 --- a/PROMS/Volian.Controls.Library/TransPanel.cs +++ b/PROMS/Volian.Controls.Library/TransPanel.cs @@ -1,9 +1,5 @@ -using System; using System.Drawing; -//using System.Collections; -using System.ComponentModel; using System.Windows.Forms; -//using System.Data; namespace Volian.Controls.Library { @@ -52,8 +48,6 @@ namespace Volian.Controls.Library { SizeF txtSize = e.Graphics.MeasureString(_Caption, this.Font); //Use a gray rectangle to show that the underlying control is inactive - //using (Brush b2 = new SolidBrush(Color.FromArgb(_Alpha, this.BackColor))) - // e.Graphics.FillRectangle(b2, this.ClientRectangle); using (Brush b = new SolidBrush(Color.FromArgb(_Alpha, this.ForeColor))) e.Graphics.DrawString(_Caption, this.Font, b, this.Width - txtSize.Width, 2); } diff --git a/PROMS/Volian.Controls.Library/VlnBorders.cs b/PROMS/Volian.Controls.Library/VlnBorders.cs index 41582d62..11e5ac84 100644 --- a/PROMS/Volian.Controls.Library/VlnBorders.cs +++ b/PROMS/Volian.Controls.Library/VlnBorders.cs @@ -1,10 +1,6 @@ using System; -using System.Collections.Generic; -using System.Text; -using System.IO; using System.Xml; using System.Xml.Serialization; -using System.Xml.Schema; using System.Drawing; using Volian.Base.Library; @@ -162,23 +158,14 @@ namespace Volian.Controls.Library HorizontalLines.DeleteColumns(column, count); VerticalLines.DeleteColumns(column, count); } - #endregion - #region Serialize - public string ConvertToString() - { - return GenericSerializer.StringSerialize(this); - } - public override string ToString() - { - return "Volian Custom Borders"; - } - public static VlnBorders Get(string xml) - { - return GenericSerializer.StringDeserialize(xml); - } - #endregion - #region Line Pattern Static Methods - public static int LineWidth(GridLinePattern linePattern) + #endregion + #region Serialize + public string ConvertToString() => GenericSerializer.StringSerialize(this); + public override string ToString() => "Volian Custom Borders"; + public static VlnBorders Get(string xml) => GenericSerializer.StringDeserialize(xml); + #endregion + #region Line Pattern Static Methods + public static int LineWidth(GridLinePattern linePattern) { switch (linePattern) { @@ -320,13 +307,10 @@ namespace Volian.Controls.Library } set { Lines[r * Columns + c] = value; } } - #endregion - #region Insert and Delete Rows and Columns - public void InsertRow(int row) - { - InsertRows(row, 1); - } - public void InsertRows(int row, int count) + #endregion + #region Insert and Delete Rows and Columns + public void InsertRow(int row) => InsertRows(row, 1); + public void InsertRows(int row, int count) { // Create a new Array of the correct size GridLinePattern[] newLines = new GridLinePattern[(Rows + count) * Columns]; @@ -343,11 +327,8 @@ namespace Volian.Controls.Library Lines = newLines; Rows = newRows; } - public void DeleteRow(int row) - { - DeleteRows(row, 1); - } - public void DeleteRows(int row, int count) + public void DeleteRow(int row) => DeleteRows(row, 1); + public void DeleteRows(int row, int count) { GridLinePattern[] newLines = new GridLinePattern[(Rows - count) * Columns]; int newRows = Rows - count; @@ -362,11 +343,8 @@ namespace Volian.Controls.Library Lines = newLines; Rows = newRows; } - public void InsertColumn(int column) - { - InsertColumns(column, 1); - } - public void InsertColumns(int column, int count) + public void InsertColumn(int column) => InsertColumns(column, 1); + public void InsertColumns(int column, int count) { // Create a new Array of the correct size GridLinePattern[] newLines = new GridLinePattern[Rows * (Columns + count)]; @@ -382,11 +360,8 @@ namespace Volian.Controls.Library Lines = newLines; Columns = newColumns; } - public void DeleteColumn(int column) - { - DeleteColumns(column, 1); - } - public void DeleteColumns(int column, int count) + public void DeleteColumn(int column) => DeleteColumns(column, 1); + public void DeleteColumns(int column, int count) { GridLinePattern[] newLines = new GridLinePattern[Rows * (Columns - count)]; int newColumns = Columns - count; diff --git a/PROMS/Volian.Controls.Library/VlnFlexGrid.Designer.cs b/PROMS/Volian.Controls.Library/VlnFlexGrid.Designer.cs index 95fa1523..8335b80e 100644 --- a/PROMS/Volian.Controls.Library/VlnFlexGrid.Designer.cs +++ b/PROMS/Volian.Controls.Library/VlnFlexGrid.Designer.cs @@ -49,12 +49,11 @@ namespace Volian.Controls.Library protected override void Dispose(bool disposing) { if (_Disposed) return; - _CountDisposed++; _Disposed = true; _MyBorders = null; _MyShading = null; - _SpellChecker = null; - _tableCellEditor = null; + SpellChecker = null; + TableCellEditor = null; if (disposing && (components != null)) { components.Dispose(); diff --git a/PROMS/Volian.Controls.Library/VlnFlexGrid.cs b/PROMS/Volian.Controls.Library/VlnFlexGrid.cs index f7f2310f..1826d480 100644 --- a/PROMS/Volian.Controls.Library/VlnFlexGrid.cs +++ b/PROMS/Volian.Controls.Library/VlnFlexGrid.cs @@ -2,14 +2,12 @@ using System; using System.ComponentModel; using System.Collections; using System.Collections.Generic; -using System.Diagnostics; using System.Text; using System.Windows.Forms; using System.Drawing; using System.Runtime.InteropServices; using System.Xml; using System.IO; -using Volian.Controls.Library; using VEPROMS.CSLA.Library; using C1.Win.C1FlexGrid; using C1.Win.C1SpellChecker; @@ -26,13 +24,6 @@ namespace Volian.Controls.Library public delegate void VlnFlexGridkeyEvent(object sender, KeyEventArgs args); public partial class vlnPanel : Panel { - private int _Opacity = 128; - //public int Opacity - //{ - // get { return _Opacity; } - // set { _Opacity = value; } - //} - public vlnPanel() { InitializeComponent(); @@ -43,88 +34,29 @@ namespace Volian.Controls.Library container.Add(this); InitializeComponent(); } - //protected override CreateParams CreateParams - //{ - // get - // { - // CreateParams prams = base.CreateParams; - // prams.ExStyle |= 0x020; // transparent - // return prams; - // } - //} - //protected override void OnPaint(PaintEventArgs pe) - //{ - // pe.Graphics.FillRectangle(new SolidBrush(Color.FromArgb(_Opacity, this.BackColor)), this.ClientRectangle); - //} } public partial class VlnFlexGrid : C1.Win.C1FlexGrid.C1FlexGrid { private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private bool _Disposed = false; - 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; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } private bool _Finalized = false; - ~VlnFlexGrid() - { - if(!_Finalized) _CountFinalized++; + ~VlnFlexGrid() + { _Finalized = true; } - private C1SpellChecker _SpellChecker; - public C1SpellChecker SpellChecker - { - get { return _SpellChecker; } - set { _SpellChecker = value; } - } - //public string GridStackTrace - //{ - // get - // { - // string st = Volian.Base.Library.vlnStackTrace.GetStack(); - // st = StripFunnyCharacters(st); - // return st; - // Console.WriteLine(st); - // return st.Replace(@"\","|"); - // } - // set - // { - // ; - // } - //} - //private string StripFunnyCharacters(string st) - //{ - // StringBuilder sb = new StringBuilder(); - // foreach (char c in st) - // { - // if ((c < ' ' || c > 255) && !"\r\n\t".Contains(c.ToString())) - // sb.Append(string.Format("x{0:X4}", (int)c)); - // else - // sb.Append(c); - // } - // return sb.ToString(); - //} - private DocVersionInfo _MyDVI = null; + public C1SpellChecker SpellChecker { get; set; } + private DocVersionInfo _MyDVI = null; public DocVersionInfo MyDVI { get { - ItemInfo procInfo = _MyItemInfo.MyProcedure as ItemInfo; //_MyEditItem.MyItemInfo.MyProcedure as ItemInfo; - if (procInfo == null) - _MyDVI = null; - else - _MyDVI = procInfo.ActiveParent as DocVersionInfo; - return _MyDVI; + if (!(_MyItemInfo.MyProcedure is ItemInfo procInfo)) + _MyDVI = null; + else + _MyDVI = procInfo.ActiveParent as DocVersionInfo; + return _MyDVI; } } private static UserInfo _MyUserInfo = null; @@ -155,19 +87,13 @@ namespace Volian.Controls.Library } } - public bool IsDirty - { - get - { - return IsGridChanged(this._MyItemInfo.MyContent.MyGrid.Data, this.GetXMLData(), true); - } - } - private bool IsGridChanged(string oldXml, string newXml, bool checkFormat) + public bool IsDirty => IsGridChanged(this._MyItemInfo.MyContent.MyGrid.Data, this.GetXMLData(), true); + private bool IsGridChanged(string oldXml, string newXml, bool checkFormat) { if (this.TableCellEditor.Text.Contains("")) return false; XmlDocument XdOld = new XmlDocument(); - oldXml = _ReplaceTextFont.Replace(oldXml, "$1" + FontChangeFmt + "$4"); // B2021-032: use original font + oldXml = _ReplaceTextFont.Replace(oldXml, $"$1{FontChangeFmt}$4"); // B2021-032: use original font XdOld.LoadXml(AdjustHeightAndWidthForDPI(oldXml)); XmlDocument XdNew = new XmlDocument(); XdNew.LoadXml(AdjustHeightAndWidthForDPI(newXml)); @@ -241,7 +167,7 @@ namespace Volian.Controls.Library private int ColumnCount(XmlDocument xd) { XmlNode xn = xd.SelectSingleNode("C1FlexGrid/ColumnInfo/Count"); - int cols = 0; + int cols; if (xn != null) cols = int.Parse(xn.InnerText); else @@ -254,7 +180,7 @@ namespace Volian.Controls.Library private int RowCount(XmlDocument xd) { XmlNode xn = xd.SelectSingleNode("C1FlexGrid/RowInfo/Count"); - int rows = 0; + int rows; if (xn != null) rows = int.Parse(xn.InnerText); else @@ -302,9 +228,11 @@ namespace Volian.Controls.Library string data = string.Empty; foreach (XmlNode xn in nl) { - RichTextBox rtb = new RichTextBox(); - rtb.Rtf = xn.InnerText; - XmlAttribute xa = xn.ParentNode.Attributes.GetNamedItem("index") as XmlAttribute; + RichTextBox rtb = new RichTextBox + { + Rtf = xn.InnerText + }; + XmlAttribute xa = xn.ParentNode.Attributes.GetNamedItem("index") as XmlAttribute; string[] rc = xa.InnerText.Split(','); int r = int.Parse(rc[0]); int c = int.Parse(rc[1]); @@ -350,20 +278,14 @@ namespace Volian.Controls.Library return _MyCopyInfo; } } - private Color _DefaultCellBackgroundcolor; + private Color _DefaultCellBackgroundcolor; - public Color DefaultCellBackgroundcolor - { - get { return _DefaultCellBackgroundcolor; } - } - private Color _DefaultFixedBackgroundColor; + public Color DefaultCellBackgroundcolor => _DefaultCellBackgroundcolor; + private Color _DefaultFixedBackgroundColor; - public Color DefaultFixedBackgroundColor - { - get { return _DefaultFixedBackgroundColor; } - } - public void CopyToCopiedFlexGrid(GridCopyOption myCopyOption) - { + public Color DefaultFixedBackgroundColor => _DefaultFixedBackgroundColor; + public void CopyToCopiedFlexGrid(GridCopyOption myCopyOption) + { MyCopyInfo.MyCopiedFlexGrid = new VlnFlexGrid(); //make a copy of the grid being copied using (StringReader sr = new StringReader(this.GetXMLData())) { @@ -389,12 +311,9 @@ namespace Volian.Controls.Library } } public event VlnFlexGridEvent CopyOptionChanged; - public void OnCopyOptionChanged(object sender, EventArgs args) - { - if (CopyOptionChanged != null) CopyOptionChanged(sender, args); - } + public void OnCopyOptionChanged(object sender, EventArgs args) => CopyOptionChanged?.Invoke(sender, args); - [XmlElement("MyBorders")] + [XmlElement("MyBorders")] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public string MyBorderDetailString @@ -423,25 +342,17 @@ namespace Volian.Controls.Library } set { _MyBorders = value; } } - private ItemInfo _MyItemInfo; - public ItemInfo GetMyItemInfo() + private ItemInfo _MyItemInfo; + public ItemInfo GetMyItemInfo() => _MyItemInfo; + public bool TopRowHasBorder() { - return _MyItemInfo; - } - //public ItemInfo MyItemInfo - //{ - // get { return _MyItemInfo; } - // set { _MyItemInfo = value; } - //} - public bool TopRowHasBorder() - { for (int c = 0; c < Cols.Count; c++) if (MyBorders.HorizontalLines[0, c] != GridLinePattern.None) return true; return false; - } + } public void SetBorders(CellRange myRange, - GridLinePattern top, GridLinePattern middle, GridLinePattern bottom, - GridLinePattern left, GridLinePattern center, GridLinePattern right) + GridLinePattern top, GridLinePattern middle, GridLinePattern bottom, + GridLinePattern left, GridLinePattern center, GridLinePattern right) { for (int r = myRange.r1; r <= myRange.r2; r++) for (int c = myRange.c1; c <= myRange.c2; c++) @@ -549,61 +460,28 @@ namespace Volian.Controls.Library cr.StyleNew.BackColor = clr; } } - public void PasteShading(int r, int c, int sr, int sc) - { - MyShading.TableShadingInfo[r, c] = MyCopyInfo.MyCopiedFlexGrid.MyShading.TableShadingInfo[sr, sc]; - } - #endregion[XmlIgnore] - public bool HasVScroll - { - get - { - return RTBAPI.HasVertScroll(this); - } - } - [XmlIgnore] - public bool HasHScroll - { - get - { - return RTBAPI.HasHorzScroll(this); - } - } - public event VlnFlexGridEvent OpenAnnotations; - public void OnOpenAnnotations(object sender, EventArgs args) - { - if (OpenAnnotations != null) OpenAnnotations(sender, args); - } - public event VlnFlexGridCursorMovementEvent CursorMovement; - internal void OnCursorMovement(object sender, VlnFlexGridCursorMovementEventArgs args) - { - if (CursorMovement != null) CursorMovement(sender, args); - } - public event VlnFlexGridPasteEvent AdjustPastedText; - internal string OnAdjustPastedText(object sender, VlnFlexGridPasteEventArgs args) + public void PasteShading(int r, int c, int sr, int sc) => MyShading.TableShadingInfo[r, c] = MyCopyInfo.MyCopiedFlexGrid.MyShading.TableShadingInfo[sr, sc]; + #endregion[XmlIgnore] + public bool HasVScroll => RTBAPI.HasVertScroll(this); + [XmlIgnore] + public bool HasHScroll => RTBAPI.HasHorzScroll(this); + public event VlnFlexGridEvent OpenAnnotations; + public void OnOpenAnnotations(object sender, EventArgs args) => OpenAnnotations?.Invoke(sender, args); + public event VlnFlexGridCursorMovementEvent CursorMovement; + internal void OnCursorMovement(object sender, VlnFlexGridCursorMovementEventArgs args) => CursorMovement?.Invoke(sender, args); + public event VlnFlexGridPasteEvent AdjustPastedText; + internal string OnAdjustPastedText(object sender, VlnFlexGridPasteEventArgs args) { if (AdjustPastedText != null) return AdjustPastedText(sender, args); return args.Text; } - public event VlnFlexGridkeyEvent EnterKeyPressed; - public void OnEnterKeyPressed(object sender, KeyEventArgs args) - { - if (EnterKeyPressed != null) EnterKeyPressed(sender, args); - } + public event VlnFlexGridkeyEvent EnterKeyPressed; + public void OnEnterKeyPressed(object sender, KeyEventArgs args) => EnterKeyPressed?.Invoke(sender, args); - private TableCellEditor _tableCellEditor; + public TableCellEditor TableCellEditor { get; set; } + private TableClipBoardFuncts _clpbrdCpyPste; + private readonly int _minColSplitWidth = 10; - public TableCellEditor TableCellEditor - { - get { return _tableCellEditor; } - set { _tableCellEditor = value; } - } - private TableClipBoardFuncts _clpbrdCpyPste; - private int _minColSplitWidth = 10; - //private int _minRowSplitHeight = 23; - - //private int _minSplitColWidth = 10; - //private int _minSplitRowHeight = 20; private E_ViewMode _vwMode = E_ViewMode.Edit; [XmlIgnore] internal E_ViewMode VwMode @@ -615,26 +493,12 @@ namespace Volian.Controls.Library AllowEditing = _vwMode == E_ViewMode.Edit; } } - private bool _IsRoTable = false; - public bool IsRoTable - { - get { return _IsRoTable; } - set { _IsRoTable = value; } - } - private int _RODbId; - public int RODbId - { - get { return _RODbId; } - set { _RODbId = value; } - } - private string _ROID; - public string ROID - { - get { return _ROID; } - set { _ROID = value; } - } - private float? _DPI = null; + public bool IsRoTable { get; set; } = false; + public int RODbId { get; set; } + + public string ROID { get; set; } + private float? _DPI = null; public float? DPI { get @@ -671,63 +535,15 @@ namespace Volian.Controls.Library InitializeComponent(); SetupGrid(1, 1); } - public VlnFlexGrid(ContentItem ci) - { + public VlnFlexGrid(ContentItem ci) + { InitializeComponent(); SetupGrid(4, 3); // use a default row and column count _MyItemInfo = ci.MyItem.MyItemInfo; - } - //public VlnFlexGrid(IContainer container) - //{ - // container.Add(this); + } + private int GetCellHeight(int row, int col) => GetRangeHeight(GetMergedRange(row, col)) - 3; - // InitializeComponent(); - // _tableCellEditor = new TableCellEditor(this); - // _tableCellEditor.ContentsResized += new ContentsResizedEventHandler(_tableCellEditor_ContentsResized); - //} - - //void _tableCellEditor_ContentsResized(object sender, ContentsResizedEventArgs e) - //{ - // if (_tableCellEditor._initializingEdit) return; - // CellRange cr = GetMergedRange(Row, Col); - // int oH = cr.UserData == null? 0 : (int)cr.UserData; - // int nH = _tableCellEditor.ContentsRectangle.Height; - // int Hadj = (nH - oH); - // cr.UserData = _tableCellEditor.ContentsRectangle.Height; - // int cellHeight = GetCellHeight(Row,Col); - // int cellheightNLines = cellHeight / (Rows.DefaultSize - 3); - // int nHNLines = nH / (Rows.DefaultSize - 3); - // if (Hadj != 0) - // { - // int curHeight = (Rows[Row].Height == -1) ? Rows.DefaultSize : Rows[Row].Height; - // //if (Hadj > 0 && cellHeight <= oH) - // if (Hadj > 0 && cellheightNLines < nHNLines) - // curHeight += (Rows.DefaultSize - 3); - // if (Hadj < 0 && CanReduceRow()) - // curHeight -= (Rows.DefaultSize-3); - // Rows[Row].Height = curHeight; - // AdjustGridControlSize(); - // } - // //cr.UserData = _tableCellEditor.ContentsRectangle.Height; - // //int mh = GetMaxRowHeight(); - // ////Rows[Row].Height = mh + 2; - // //int h = 0; - // //if (cr.r1 == cr.r2 && cr.c1 == cr.c2) - // // h = Rows[Row].Height - 2; - // //else - // //{ - // // for (int r = cr.r1; r <= cr.r2; r++) - // // h += Rows[r].Height - 2; - // //} - // //Rows[Row].Height += (mh - h); - // ////AdjustGridControlSize(); - //} - private int GetCellHeight(int row, int col) - { - return GetRangeHeight(GetMergedRange(row, col))-3; - } - - public int GetRangeHeight(CellRange cr) + public int GetRangeHeight(CellRange cr) { int height = 0; for (int r = cr.r1; r <= cr.r2; r++) @@ -856,9 +672,6 @@ namespace Volian.Controls.Library { int cellHeight = GetCellHeight(Row, c); int dataHeight = (cr.UserData == null) ? cellHeight : (int)cr.UserData; - int ud = dataHeight / (Rows.DefaultSize - 3); - //if (cellHeight < dataHeight) - // Console.WriteLine("r {0}, c {1}, cell{2}, data{3}", Row, c, cellHeight, dataHeight); blankRowSpace = Math.Min(blankRowSpace, Math.Max(0,cellHeight - dataHeight)); } } @@ -880,7 +693,6 @@ namespace Volian.Controls.Library private int BlankColSpace() { int curColWidth = (Cols[Col].Width == -1) ? Cols.DefaultSize - 3 : Cols[Col].Width-3; - //int curRowHeightNLines = curRowHeight / (Rows.DefaultSize - 3); if (curColWidth <= Cols.DefaultSize - 3) return 0; // never have col less than default width int blankColSpace = curColWidth; for (int r = 0; r < Rows.Count; r++) @@ -892,15 +704,11 @@ namespace Volian.Controls.Library if (Col >= cr.c1 && Col <= cr.c2) { int cellWidth = GetCellWidth(r, Col); - //srtb.Width = cellWidth; srtb.AdjustWidthForContent(); - //Application.DoEvents(); - //int mergeCellHeightNLines = cellHeight / (Rows.DefaultSize - 3); + //For Debug //int dataHeight = (cr.UserData == null) ? cellHeight : (int)cr.UserData; - //int ud = dataHeight / (Rows.DefaultSize - 3); //if (cellHeight < dataHeight) // Console.WriteLine("r {0}, c {1}, cell{2}, data{3}", Row, c, cellHeight, dataHeight); - //blankColSpace = Math.Min(blankColSpace, Math.Max(0, cellWidth - srtb.MaxTextWidth)); blankColSpace = Math.Min(blankColSpace, Math.Max(0, cellWidth - srtb.Width)); } } @@ -908,67 +716,17 @@ namespace Volian.Controls.Library //Console.WriteLine("BlankRowSpace {0}", blankRowSpace); return blankColSpace; } - //private bool CanReduceRow() - //{ - // int curRowHeight = (Rows[Row].Height == -1) ? Rows.DefaultSize - 3 : Rows[Row].Height - 3; - // int curRowHeightNLines = curRowHeight / (Rows.DefaultSize - 3); - // bool bReduce = (curRowHeight > (Rows.DefaultSize - 3)); - // if (bReduce) - // { - // for (int c = 0; c < Cols.Count; c++) - // { - // CellRange cr = GetMergedRange(Row, c); - // if (Row >= cr.r1 && Row <= cr.r2) - // { - // int mergeCellHeightNLines = GetCellHeight(Row, c) / (Rows.DefaultSize - 3); - // //int ud = (cr.UserData == null) ? 0 : (int)cr.UserData; - // //if ((c != Col) && curRowHeight <= ud && ud >= mergeCellHeight) - // // bReduce = false; - // int ud = ((cr.UserData == null) ? 0 : (int)cr.UserData) / (Rows.DefaultSize - 3); - // if ((c != Col) && curRowHeightNLines <= ud && ud >= mergeCellHeightNLines) - // bReduce = false; - // } - // } - // } - // //Console.WriteLine("canreduce {0}, {1}", Row, bReduce); - // return bReduce; - //} - //private int GetMaxRowHeight() - //{ - // int maxRTFHeight = _minRowSplitHeight; //Rows.DefaultSize;// the smallest a row can be - // Console.WriteLine("================================================================="); - // for (int c = 0; c < Cols.Count; c++) - // { - // CellRange cr = GetMergedRange(Row, c);//GetCellRange(Row, c); - // maxRTFHeight = Math.Max(maxRTFHeight, (int)cr.UserData); - // if (c == 0) - // Console.WriteLine("Height in Row[{0}] = {1}", Row, Rows[Row].Height); - // Console.WriteLine("UserData Cell[{0},{1}] = {2}", Row, c, cr.UserData); - // } - // return maxRTFHeight; - //} - - private bool IsInMergeRange(int row, int col) - { - //foreach (CellRange cr in this.MergedRanges) - //{ - // if (cr.Contains(row, col)) - // return true; // in a merged range - //} - CellRange cr = GetMergedRange(row, col); - return (cr.r1 == row && cr.c1 == col); - } private bool _ReadingXml = false; public bool ReadingXml { get { return _ReadingXml; } } - private static Regex _ReplaceVESymbFix = new Regex(@"({\\f[0-9]+[^ ]* )(FreeMono)(;})"); // FreeMono is now used for the edit screen only. VESymbFix and Consolas are used for printing - private static Regex _ReplaceArialUnicodeMS = new Regex(@"({\\f[0-9]+[^ ]* )(" + Volian.Base.Library.vlnFont.ProportionalSymbolFont + @")(;})"); // C2017-036 get best available proportional font for symbols + private static readonly Regex _ReplaceVESymbFix = new Regex(@"({\\f[0-9]+[^ ]* )(FreeMono)(;})"); // FreeMono is now used for the edit screen only. VESymbFix and Consolas are used for printing + private static readonly Regex _ReplaceArialUnicodeMS = new Regex(@"({\\f[0-9]+[^ ]* )(" + Volian.Base.Library.vlnFont.ProportionalSymbolFont + @")(;})"); // C2017-036 get best available proportional font for symbols // B2017-173 VESymFix font was being replaced by the table's default font, causing empty squares for the symbols (pre FreeMono font) in tables //C2017-036 Added FreeSerif which may be used if Arial Unicode MS is not available - private static Regex _ReplaceTextFont = new Regex(@"({\\f[0-9]+[^ ]* )(?((?!FreeMono)(?!FreeSerif)(?!Arial Unicode MS)(?!VESymbFix))([^;]*)|(!!!!))(;})"); // FreeMono is now used for the edit screen only. VESymbFix and Consolas are used for printing + private static readonly Regex _ReplaceTextFont = new Regex(@"({\\f[0-9]+[^ ]* )(?((?!FreeMono)(?!FreeSerif)(?!Arial Unicode MS)(?!VESymbFix))([^;]*)|(!!!!))(;})"); // FreeMono is now used for the edit screen only. VESymbFix and Consolas are used for printing private bool FontIsFixed(Font myFont) { Graphics grph = Graphics.FromHwnd(this.Handle); @@ -993,31 +751,31 @@ namespace Volian.Controls.Library string str = itemInfo.MyContent.MyGrid.Data; VE_Font vefont = _MyItemInfo.GetItemFont(); - // the following code is used to be sure that the font used for symbols is the correct font - // based on whether the font for non-symbol text is fixed or proportional. Each steprtb has - // a font for the non-symbol AND the symbol text, and these must be the correct association, i.e. - // for fixed fonts, the symbol font is 'VESymbFix', for proportional fonts, the symbol font is - // 'Arial Unicode MS'. The underlying flexgrid stores the fonts, and if the table font was - // reset for some reason (for example from the drop-down font selection in the user interface), - // this code 'cleans' up if there is a mismatch. - FontFamily ff = null; - if (StepRTB.MyFontFamily != null) + // the following code is used to be sure that the font used for symbols is the correct font + // based on whether the font for non-symbol text is fixed or proportional. Each steprtb has + // a font for the non-symbol AND the symbol text, and these must be the correct association, i.e. + // for fixed fonts, the symbol font is 'VESymbFix', for proportional fonts, the symbol font is + // 'Arial Unicode MS'. The underlying flexgrid stores the fonts, and if the table font was + // reset for some reason (for example from the drop-down font selection in the user interface), + // this code 'cleans' up if there is a mismatch. + FontFamily ff; + if (StepRTB.MyFontFamily != null) { ff = StepRTB.MyFontFamily; if (StepRTB.MySymbolFontName != "FreeMono") // FreeMono is now used for the edit screen only. VESymbFix and Consolas are used for printing - str = _ReplaceVESymbFix.Replace(str, "$1" + StepRTB.MySymbolFontName + "$3"); + str = _ReplaceVESymbFix.Replace(str, $"$1{StepRTB.MySymbolFontName}$3"); if (StepRTB.MySymbolFontName != Volian.Base.Library.vlnFont.ProportionalSymbolFont) // C2017-036 get best available proportional font for symbols - str = _ReplaceArialUnicodeMS.Replace(str, "$1" + StepRTB.MySymbolFontName + "$3"); - str = _ReplaceTextFont.Replace(str, "$1" + ff.Name + "$4"); + str = _ReplaceArialUnicodeMS.Replace(str, $"$1{StepRTB.MySymbolFontName}$3"); + str = _ReplaceTextFont.Replace(str, $"$1{ff.Name}$4"); } else { ff = vefont.WindowsFont.FontFamily; if (FontIsFixed(vefont.WindowsFont)) - str = _ReplaceArialUnicodeMS.Replace(str, "$1" + "FreeMono" + "$3"); // FreeMono is now used for the edit screen only. VESymbFix and Consolas are used for printing + str = _ReplaceArialUnicodeMS.Replace(str, "$1FreeMono$3"); // FreeMono is now used for the edit screen only. VESymbFix and Consolas are used for printing else - str = _ReplaceVESymbFix.Replace(str, "$1" + Volian.Base.Library.vlnFont.ProportionalSymbolFont + "$3"); // C2017-036 get best available proportional font for symbols - str = _ReplaceTextFont.Replace(str, "$1" + ff.Name + "$4"); + str = _ReplaceVESymbFix.Replace(str, $"$1{Volian.Base.Library.vlnFont.ProportionalSymbolFont}$3"); // C2017-036 get best available proportional font for symbols + str = _ReplaceTextFont.Replace(str, $"$1{ff.Name}$4"); } FontChangeFmt = ff.Name; // B2021-032 @@ -1038,8 +796,8 @@ namespace Volian.Controls.Library gr.DrawImage(img, Left, Top); } } - catch (Exception ex) - { + catch (Exception) + { _MyLog.WarnFormat("Table Content Corrupted"); } } @@ -1055,7 +813,7 @@ namespace Volian.Controls.Library ProfileTimer.Pop(profileDepth); } - private void ReadXml(string str) + private new void ReadXml(string str) { // Get the height/width adjusted for the DPI. Depending on if the DPI setting for the current user's // monitor is different than the DPI setting saved in the grid record, table height/width of rows/columns @@ -1146,8 +904,6 @@ namespace Volian.Controls.Library this.Styles.Normal.Border.Color = Color.Black; this.Styles.Normal.TextAlign = C1.Win.C1FlexGrid.TextAlignEnum.LeftTop; - //SetupCellStyles(); - this.FocusRect = FocusRectEnum.Solid; this.Styles.Highlight.BackColor = Color.LightCyan; this.Styles.Highlight.ForeColor = Color.Black; @@ -1161,10 +917,10 @@ namespace Volian.Controls.Library this.AllowResizing = C1.Win.C1FlexGrid.AllowResizingEnum.Both; - _tableCellEditor = new TableCellEditor(this); - _tableCellEditor.HeightChanged += new StepRTBEvent(_tableCellEditor_HeightChanged); + TableCellEditor = new TableCellEditor(this); + TableCellEditor.HeightChanged += new StepRTBEvent(_tableCellEditor_HeightChanged); _clpbrdCpyPste = new TableClipBoardFuncts(); - _SpellChecker = _tableCellEditor.SpellCheckerInstance; + SpellChecker = TableCellEditor.SpellCheckerInstance; this.AfterResizeRow += new C1.Win.C1FlexGrid.RowColEventHandler(this.Grid_AfterResize); this.StartEdit += new C1.Win.C1FlexGrid.RowColEventHandler(this._StartEdit); @@ -1182,14 +938,11 @@ namespace Volian.Controls.Library this.DoubleClick += VlnFlexGrid_DoubleClick; } private bool _DoubleClickedCell = false; // C2021-005 need to know if user double-clicked on a cell - private void VlnFlexGrid_DoubleClick(object sender, EventArgs e) - { - // if user did a double click then don't try to get the font size - go directly to editing the table cell text - _DoubleClickedCell = true; - } + // if user did a double click then don't try to get the font size - go directly to editing the table cell text + private void VlnFlexGrid_DoubleClick(object sender, EventArgs e) => _DoubleClickedCell = true; - // C2021-005 needed the mouseup event to control the table cell selecting and grabbing of the font size - public bool _GettingFontSize = false; + // C2021-005 needed the mouseup event to control the table cell selecting and grabbing of the font size + public bool _GettingFontSize = false; private void VlnFlexGrid_MouseUp(object sender, MouseEventArgs e) { // C2021-005 Get the font size if user didn't double click and on a table @@ -1197,15 +950,9 @@ namespace Volian.Controls.Library (Parent as GridItem).MyStepPanel.MyStepTabPanel.MyStepTabRibbon.SetFontSizeDropDown(); } - private bool _FirstEntry = false; + public bool FirstEntry { get; set; } = false; - public bool FirstEntry - { - get { return _FirstEntry; } - set { _FirstEntry = value; } - } - - void VlnFlexGrid_MouseDown(object sender, MouseEventArgs e) + void VlnFlexGrid_MouseDown(object sender, MouseEventArgs e) { int left = 0; int top = 0; @@ -1231,45 +978,33 @@ namespace Volian.Controls.Library //Console.WriteLine("Mousedown Row, Col [{0},{1}]", row, col); erow = Math.Max(erow, row); ecol = Math.Max(ecol, col); - if (_FirstEntry) + if (FirstEntry) Select(row, col); else Select(strow, stcol, erow, ecol); - _FirstEntry = false; + FirstEntry = false; } void _tableCellEditor_HeightChanged(object sender, EventArgs args) { // B2022-028: images in table cells - don't come into this code if it is an image in a table cell: - if (_tableCellEditor is StepRTB && (_tableCellEditor as StepRTB).ImageWidth > 0) return; + if (TableCellEditor is StepRTB && (TableCellEditor as StepRTB).ImageWidth > 0) return; - if (_tableCellEditor._initializingEdit || !_tableCellEditor.Visible) return; - int curHeight = GetCellHeight(Row, Col);//(Rows[Row].Height == -1) ? Rows.DefaultSize : Rows[Row].Height; + if (TableCellEditor._initializingEdit || !TableCellEditor.Visible) return; + int curHeight = GetCellHeight(Row, Col); CellRange cr = GetMergedRange(Row, Col); - int oH = cr.UserData == null ? curHeight : (int)cr.UserData; - int nH = _tableCellEditor.Height; //.ContentsRectangle.Height; - int nW = _tableCellEditor.Width; // Width - int Hadj = (nH - curHeight);//oH); - cr.UserData = _tableCellEditor.Height; //.ContentsRectangle.Height; - //int cellHeight = GetCellHeight(Row, Col); - //int cellheightNLines = cellHeight / (Rows.DefaultSize - 3); - //int nHNLines = nH / (Rows.DefaultSize - 3); + int nH = TableCellEditor.Height; + int Hadj = (nH - curHeight); + cr.UserData = TableCellEditor.Height; if (Hadj != 0) { - //if (Hadj > 0 && cellHeight <= oH) - //if (Hadj > 0 && cellheightNLines < nHNLines) - // curHeight += (Rows.DefaultSize - 3); - //if (Hadj < 0 && CanReduceRow()) - // curHeight -= (Rows.DefaultSize - 3); + int blankRowSpace = BlankRowSpace(); if (Hadj < 0) Hadj = -Math.Min(-Hadj, blankRowSpace); - //if (Hadj > 0) - // Console.WriteLine("r {0}, nh {1}, curh{2}", Row, nH, curHeight); if (Hadj != 0) { int newHeight = Hadj + ((Rows[Row].Height < 0) ? Rows.DefaultSize : Rows[Row].Height); - //Rows[Row].Height += Hadj;//= curHeight; Rows[Row].Height = newHeight; AdjustGridControlSize(); } @@ -1299,24 +1034,24 @@ namespace Volian.Controls.Library { case Keys.Left: if (e.Shift) return; - _tableCellEditor.StepRTB_ArrowPressed(e.Control ? E_ArrowKeys.CtrlLeft : E_ArrowKeys.Left); + TableCellEditor.StepRTB_ArrowPressed(e.Control ? E_ArrowKeys.CtrlLeft : E_ArrowKeys.Left); e.Handled = true; break; case Keys.Up: if (e.Shift) return; - _tableCellEditor.StepRTB_ArrowPressed(e.Control ? E_ArrowKeys.CtrlUp : E_ArrowKeys.Up); + TableCellEditor.StepRTB_ArrowPressed(e.Control ? E_ArrowKeys.CtrlUp : E_ArrowKeys.Up); e.Handled = true; break; case Keys.Right: if (e.Shift) return; if (IsRoTable) Select(Rows.Count - 1, Cols.Count - 1); - _tableCellEditor.StepRTB_ArrowPressed(e.Control ? E_ArrowKeys.CtrlRight : E_ArrowKeys.Right); + TableCellEditor.StepRTB_ArrowPressed(e.Control ? E_ArrowKeys.CtrlRight : E_ArrowKeys.Right); e.Handled = true; break; case Keys.Down: if (e.Shift) return; if (IsRoTable) Select(Rows.Count - 1, 0); - _tableCellEditor.StepRTB_ArrowPressed(e.Control ? E_ArrowKeys.CtrlDown : E_ArrowKeys.Down); + TableCellEditor.StepRTB_ArrowPressed(e.Control ? E_ArrowKeys.CtrlDown : E_ArrowKeys.Down); e.Handled = true; break; case Keys.Enter: @@ -1328,25 +1063,20 @@ namespace Volian.Controls.Library { // if a Reviewer, then do a . Don't allow changes to a table if (IsRoTable) Select(Rows.Count - 1, 0); - _tableCellEditor.StepRTB_ArrowPressed(e.Control ? E_ArrowKeys.CtrlDown : E_ArrowKeys.Down); + TableCellEditor.StepRTB_ArrowPressed(e.Control ? E_ArrowKeys.CtrlDown : E_ArrowKeys.Down); e.Handled = true; } } break; } } - //void VlnFlexGrid_LeaveEdit(object sender, RowColEventArgs e) - //{ - // //Console.WriteLine("LeaveEdit Style = {0}", this.GetCellRange(e.Row, e.Col).Style.Name); - // this.GetCellRange(e.Row, e.Col).Style.ForeColor = Color.Black; - //} private void Grid_OwnerDrawCell(object sender, C1.Win.C1FlexGrid.OwnerDrawCellEventArgs e) { using (RTF _rtf = new RTF()) { - // use nearest solid color - // (the RTF control doesn't dither, and doesn't support transparent backgrounds) - Color solid = e.Graphics.GetNearestColor(e.Style.BackColor); + // use nearest solid color + // (the RTF control doesn't dither, and doesn't support transparent backgrounds) + Color solid = e.Graphics.GetNearestColor(e.Style.BackColor); DPI = e.Graphics.DpiX; if (e.Style.BackColor != solid) e.Style.BackColor = solid; @@ -1357,14 +1087,13 @@ namespace Volian.Controls.Library // Also convert \~ to a hard spece. Again RTF is automatically converting \u160? to \~ but will then convert // the \~ to a regular space! string rtfText = RtfTools.RTFConvertedSymbolsToUnicode(this.GetDataDisplay(e.Row, e.Col));//.Replace(@"\~", @"\u160?").Replace(@"\'99", @"\u8482?"); - GridItem gi = Parent as GridItem; - if (gi != null) - { - DisplayText dt = new DisplayText(gi.MyItemInfo, rtfText, true); - rtfText = dt.StartText; - } - // it does, so draw background - e.DrawCell(DrawCellFlags.Background); + if (Parent is GridItem gi) + { + DisplayText dt = new DisplayText(gi.MyItemInfo, rtfText, true); + rtfText = dt.StartText; + } + // it does, so draw background + e.DrawCell(DrawCellFlags.Background); if (rtfText.StartsWith(@"{\rtf")) { // Please add a comment if this value needs to be changed @@ -1427,7 +1156,6 @@ namespace Volian.Controls.Library { CharacterRange[] ranges = new CharacterRange[1]; ranges[0] = new CharacterRange(0, 1); - Pen pn = new Pen(Color.Green, 2); StringFormat sf = new StringFormat(e.Style.StringFormat); sf.SetMeasurableCharacterRanges(ranges); Rectangle rc = e.Style.GetTextRectangle(e.Bounds, null); @@ -1484,9 +1212,7 @@ namespace Volian.Controls.Library CellRange cr = GetMergedRange(row, col); GridLinePattern topSide = MyBorders.HorizontalLines[cr.r1,cr.c1]; GridLinePattern rightOfTopSide = cr.c2 == Cols.Count - 1 ? GridLinePattern.None : MyBorders.HorizontalLines[cr.r1, cr.c2 + 1]; - GridLinePattern leftOfTopSide = cr.c1 == 0? GridLinePattern.None : MyBorders.HorizontalLines[cr.r1, cr.c1 - 1]; GridLinePattern leftSide = MyBorders.VerticalLines[cr.r1, cr.c1]; - GridLinePattern aboveLeftSide = cr.r1 == 0 ? GridLinePattern.None : MyBorders.VerticalLines[cr.r1 - 1, cr.c1]; GridLinePattern belowLeftSide = cr.r2 == Rows.Count - 1 ? GridLinePattern.None : MyBorders.VerticalLines[cr.r2 + 1, cr.c1]; GridLinePattern bottomSide = MyBorders.HorizontalLines[cr.r2+1, cr.c2]; GridLinePattern rightOfBottomSide = cr.c2 == Cols.Count - 1 ? GridLinePattern.None : MyBorders.HorizontalLines[cr.r2 + 1, cr.c2 + 1]; @@ -1538,11 +1264,8 @@ namespace Volian.Controls.Library Pen pn = VlnBorders.LinePen(pattern, BorderColor); DrawLine(gr, pn, pattern, x1, y1, x2, y2); } - private static void DrawLine(Graphics gr, Pen pn, int x1, int y1, int x2, int y2) - { - DrawLine(gr, pn, GridLinePattern.Single, x1, y1, x2, y2); - } - private static void DrawLine(Graphics gr, Pen pn, GridLinePattern pattern, int x1, int y1, int x2, int y2) + private static void DrawLine(Graphics gr, Pen pn, int x1, int y1, int x2, int y2) => DrawLine(gr, pn, GridLinePattern.Single, x1, y1, x2, y2); + private static void DrawLine(Graphics gr, Pen pn, GridLinePattern pattern, int x1, int y1, int x2, int y2) { int dx = 0; int dy = 0; @@ -1601,8 +1324,8 @@ namespace Volian.Controls.Library if (left == GridLinePattern.Double) DrawIntersectionOneDoubleOrLess(gr, x, y, up, right, down, left); else DrawIntersectionOneDoubleOrLess(gr, x, y, up, right, down, left); } - private static Pen pnDouble = VlnBorders.LinePen(GridLinePattern.Double, BorderColor); - private static Pen pnThick = VlnBorders.LinePen(GridLinePattern.Thick, BorderColor); + private static readonly Pen pnDouble = VlnBorders.LinePen(GridLinePattern.Double, BorderColor); + private static readonly Pen pnThick = VlnBorders.LinePen(GridLinePattern.Thick, BorderColor); private static void DrawIntersectionAllDoubles(Graphics gr, int x, int y) { DrawLine(gr, pnDouble, x-1, y, x, y); @@ -1792,7 +1515,7 @@ namespace Volian.Controls.Library { CellRange tmp = this.GetCellRange(rw, col, rw, col); string StyleName = string.Format("R{0}C{1}Style", rw, col); - CellStyle cs = null; + CellStyle cs; if (Styles.Contains(StyleName)) cs = Styles[StyleName]; else @@ -1811,7 +1534,7 @@ namespace Volian.Controls.Library { CellRange tmp = this.GetCellRange(rw, col, rw, col); string StyleName = string.Format("R{0}C{1}Style", rw, col); - CellStyle cs = null; + CellStyle cs; if (Styles.Contains(StyleName)) cs = Styles[StyleName]; else @@ -1832,95 +1555,6 @@ namespace Volian.Controls.Library } } } - //public void VerticalCenterText() - //{ - // StepRTB myStepRTB = new StepRTB(); - // CellRange selRange = this.Selection; - // for (int r = selRange.r1; r <= selRange.r2; r++) - // for (int c = selRange.c1; c <= selRange.c2; c++) - // { - // CellRange mr = this.GetMergedRange(r, c); - // if (mr.r1 == r) - // { - // int editHeight = (int)mr.UserData; - // int cellHeight = GetCellHeight(mr.r1, mr.c1); - // if (editHeight < cellHeight) - // { - // myStepRTB.Rtf = (string)mr.Data; - // RTBAPI.SetSpaceBefore(myStepRTB, (cellHeight - editHeight) / 2); - // PutCellRTFString(mr.r1, mr.c1, myStepRTB.Rtf); - // } - // } - // } - //} - //public void VerticalTopText() - //{ - // StepRTB myStepRTB = new StepRTB(); - // CellRange selRange = this.Selection; - // for (int r = selRange.r1; r <= selRange.r2; r++) - // for (int c = selRange.c1; c <= selRange.c2; c++) - // { - // CellRange mr = this.GetMergedRange(r, c); - // if (mr.r1 == r) - // { - // myStepRTB.Rtf = (string)mr.Data; - // RTBAPI.SetSpaceBefore(myStepRTB, 0); - // PutCellRTFString(mr.r1, mr.c1, myStepRTB.Rtf); - // } - // } - //} - //public void VerticalBottomText() - //{ - // StepRTB myStepRTB = new StepRTB(); - // CellRange selRange = this.Selection; - // for (int r = selRange.r1; r <= selRange.r2; r++) - // for (int c = selRange.c1; c <= selRange.c2; c++) - // { - // CellRange mr = this.GetMergedRange(r, c); - // if (mr.r1 == r) - // { - // int editHeight = (int)mr.UserData; - // int cellHeight = GetCellHeight(mr.r1, mr.c1); - // if (editHeight < cellHeight) - // { - // myStepRTB.Rtf = (string)mr.Data; - // RTBAPI.SetSpaceBefore(myStepRTB, (cellHeight - editHeight)); - // PutCellRTFString(mr.r1, mr.c1, myStepRTB.Rtf); - // } - // } - // } - //} - - //public void SetupCellStyles() - //{ - // //CellStyle cs; - - // //cs = this.Styles.Add("Dotted"); - // //cs.Border.Style = BorderStyleEnum.Dotted; - // //cs = this.Styles.Add("Double"); - // //cs.Border.Style = BorderStyleEnum.Double; - // //cs = this.Styles.Add("Fillet"); - // //cs.Border.Style = BorderStyleEnum.Fillet; - // //cs = this.Styles.Add("Flat"); - // //cs.Border.Style = BorderStyleEnum.Flat; - // //cs = this.Styles.Add("Groove"); - // //cs.Border.Style = BorderStyleEnum.Groove; - // //cs = this.Styles.Add("Inset"); - // //cs.Border.Style = BorderStyleEnum.Inset; - // //cs = this.Styles.Add("None"); - // //cs.Border.Style = BorderStyleEnum.None; - // //cs = this.Styles.Add("Raised"); - // //cs.Border.Style = BorderStyleEnum.Raised; - // //cs = this.Styles.Add("CenterRight"); - // //cs.TextAlign = TextAlignEnum.RightCenter; //.LeftCenter; // this is being ignored - probably due to RTF conversion - // //cs = this.Styles.Add("Yellow"); - // //cs.BackColor = Color.Yellow; - // //cs = this.Styles.Add("Margins"); - // //cs.Margins.Bottom = 5; - // //cs.Margins.Top = 10; - // //cs.Margins.Left = 15; - // //cs.Margins.Right = 20; - //} #endregion //Grid and Cell Styles #region Grid Size Adjustments @@ -1930,7 +1564,7 @@ namespace Volian.Controls.Library /// public void AdjustGridControlSize() { - if (Parent is GridItem ? (Parent as GridItem).Initializing : false ) return; + if (Parent is GridItem && (Parent as GridItem).Initializing) return; int difW = this.Width - this.ClientSize.Width; int difH = this.Height - this.ClientSize.Height; int wid = 0; @@ -1961,27 +1595,12 @@ namespace Volian.Controls.Library trtb.Font = this.Font; if (tstr != null && tstr.Length > 0) { - string tsave = tstr; // regular text has special characters to toggle Bold, Underline, and Italics // we need to subtract the width of these characters (allow column/row to shrink) - //AllowWidthShrink = RemoveBoldUlineItalicChars(trtb.Rtf); AllowWidthShrink = tstr.Contains("#Link:"); // this will convert the special characters for Bold, Underline, and Italics // into RTF commands - //trtb.Rtf = trtb.RtfPrefix + ConvertTableText(trtb.Rtf) + "}"; - //string fromRTF = trtb.Rtf; - //string prefix = trtb.RtfPrefix; - //if (tstr.Contains("#Link:")) prefix += @"{\colortbl ;\red255\green0\blue0;}"; - //if (tstr.Contains("#Link:")) - // Console.WriteLine("here"); - //string jText = trtb.RtfPrefix + ConvertTableText(tstr) + @"\par}"; - //trtb.Rtf = jText; trtb.Rtf = trtb.RtfPrefix + ConvertTableText(tstr) + @"\par}"; - //string fromStr = trtb.Rtf; - //if (fromRTF.Contains("SimSun")) - // Console.WriteLine("SimSun"); - //else - // Compare(fromRTF, fromStr, tsave); } else { @@ -1992,125 +1611,21 @@ namespace Volian.Controls.Library // find the needed cell width trtb.AdjustWidthForContent(); - // B2019-162 Allow grids to not automatically adjust the cell widths + // B2019-162 Allow grids to not automatically adjust the cell widths if(adjustWidth)trtb.AdjustWidthForContent(); if (dummyCharWidth) { trtb.Text = ""; // clear out the dummy character before saving - dummyCharWidth = false; } this[r, c] = trtb.Rtf; // save the cleaned up and processed cell text as RTF this.Select(r, c, false); - CellRange sel = this.Selection; - //sel.UserData = trtb.ContentsRectangle.Height; // Now adjust the Height and Width in the defined merge ranges - // B2019-162 Allow grids to not automatically adjust the cell widths + // B2019-162 Allow grids to not automatically adjust the cell widths AdjustMergeRangeHeightWidth(r, c, trtb, tstr, AllowWidthShrink,adjustWidth); - //// Now see the the selected row,col is in the defined merge ranges - //bool mrgrows = false; - //bool mrgcols = false; - //foreach (CellRange cr in this.MergedRanges) - //{ - // if (cr.Contains(r, c)) - // { - // if (cr.c1 != cr.c2) - // mrgcols = true; // in a range of merged columns - // if (cr.r1 != cr.r2) - // mrgrows = true; // in a range of merged rows - // continue; - // } - //} - //if (!mrgcols || !mrgrows) - //{ - // // IF the row of the selected cell is NOT in merged range - // // then go ahead and adjust the row height (if needed) - // if (!mrgrows) - // { - // // add adjustment for grid and cell borders - // int newheight = trtb.Height + 3; - - // //Console.WriteLine("{0} {1} {2} '{3}'", r, c, newheight,trtb.Text); - // if (newheight > this.Rows[r].Height) - // { - // //Console.WriteLine("1 Row {0} Old Height = {1}, New Height = {2}", r, Rows[r].Height, newheight); - // this.Rows[r].Height = newheight; - // } - // } - // // IF the column of the selected cell is NOT in merged range - // // then go ahead and adjust the column width (if needed) - // if (!mrgcols) - // { - // // add adjustment for grid and cell borders - // int newwidth = trtb.Width + 2; - - // if (newwidth > this.Cols[c].Width || AllowWidthShrink || r == 0) - // this.Cols[c].Width = newwidth; - // } - //} - //if (mrgrows && tstr != null) - //{ - // CellRange cr = GetMergedRange(r, c); - // //Console.WriteLine("grid[{0},{1}] merge = {2}", r, c,cr); - // if (cr.r1 == r && cr.c1 == c) - // { - // // if in merged rows, then make sure the cell's height is large enough - // string[] strary = tstr.Split("\n".ToCharArray()); - // // count number of lines of text - // int nlines = strary.Length; - // // count number of rows in merge range - // int nrows = (cr.r2 - cr.r1) + 1; - // //Console.WriteLine("2 Row {0} Height = {1}", cr.r1, Rows[cr.r1].Height); - // while (nlines > nrows) - // { - // // add length to first row in merged range - // int h = this.Rows[cr.r1].Height; - // int defH = Rows.DefaultSize - 3; - // //h = (h == -1) ? _minRowHeight * 2 : h + _minRowHeight; - // h = (h == -1) ? (defH * 2) + 3 : h + defH; - // //h = (h == -1) ? (Rows.DefaultSize + 2) * 2 : h + Rows.DefaultSize + 2; - // //Console.WriteLine("3 Row {0} Old Height = {1}, New Height = {2}", cr.r1, Rows[cr.r1].Height, h); - // this.Rows[cr.r1].Height = h; - // nrows++; - // } - // } - //} } } - //private void AdjustCellHeightWidth(int r, int c) - //{ - // using (StepRTB trtb = new StepRTB()) - // { - // string tstr = null; - // bool dummyCharWidth = false; - // bool AllowWidthShrink = false; - // trtb.SetTableGridCellRTFPrefix(this.Font); - // trtb.Clear(); - // trtb.Font = this.Font; - // trtb.Rtf = (string)this[r, c]; - // tstr = trtb.Text; - // if (tstr != null && tstr.Length > 0) - // AllowWidthShrink = tstr.Contains("#Link:"); - // else - // { - // trtb.Text = "X"; // this is to trick steprtf in giving a char width to fit one character - // // note that a space character was too small. - // dummyCharWidth = true; - // } - // // find the needed cell width - // trtb.AdjustWidthForContent(); - // if (dummyCharWidth) - // { - // trtb.Text = ""; // clear out the dummy character before saving - // dummyCharWidth = false; - // } - - - // // Now adjust the Height and Width in the defined merge ranges - // AdjustMergeRangeHeightWidth(r, c, trtb, tstr, AllowWidthShrink,true); - // } - //} // B2019-162 Allow grids to not automatically adjust the cell widths private void AdjustMergeRangeHeightWidth(int r, int c, StepRTB trtb, string tstr, bool AllowWidthShrink, bool adjustWidth) @@ -2213,146 +1728,40 @@ namespace Volian.Controls.Library } } } - //private void AdjustCellHeightWidth(int r, int c) - //{ - // StepRTB trtb = new StepRTB(); - // string tstr = null; - // bool dummyCharWidth = false; - // bool AllowWidthShrink = false; - // trtb.SetTableGridCellRTFPrefix(this.Font); - // trtb.Clear(); - // trtb.Font = this.Font; - // trtb.Rtf = (string)this[r, c]; - // tstr = trtb.Text; - // if (tstr != null && tstr.Length > 0) - // AllowWidthShrink = tstr.Contains("#Link:"); - // else - // { - // trtb.Text = "X"; // this is to trick steprtf in giving a char width to fit one character - // // note that a space character was too small. - // dummyCharWidth = true; - // } - // // find the needed cell width - // trtb.AdjustWidthForContent(); + #region DEBUG + //These Subs Are For Debugging + public void ShowRawString(string str, string title) + { + Console.WriteLine("Raw Start --{0}:\n", title); + foreach (char c in str) + { + int ic = (int)c; + if (c != '\n' && (ic > 126 || ic < 32)) + Console.Write("<<{0:x4}>>", ic); + else + Console.Write(c); + } + Console.WriteLine("\n-- Raw End:{0}", title); + } + public void Debug_WritelineMySelection() + { + int r1 = MySelection[0].r1; + int r2 = MySelection[0].r2; + int c1 = MySelection[0].c1; + int c2 = MySelection[0].c2; + Console.WriteLine("Initial MySelection[0] {0}", MySelection[0]); + foreach (CellRange cr in MySelection) + { + r1 = Math.Min(r1, cr.r1); + c1 = Math.Min(c1, cr.c1); + r2 = Math.Max(r2, cr.r2); + c2 = Math.Max(c2, cr.c2); + Console.WriteLine("Foreach range ({0},{1}) - ({2},{3})", r1, c1, r2, c2); + } + } + #endregion - // if (dummyCharWidth) - // { - // trtb.Text = ""; // clear out the dummy character before saving - // dummyCharWidth = false; - // } - - // this.Select(r, c, false); - // CellRange sel = this.Selection; - - // // Now see the the selected row,col is in the defined merge ranges - // bool mrgrows = false; - // bool mrgcols = false; - // foreach (CellRange cr in this.MergedRanges) - // { - // if (cr.Contains(r, c)) - // { - // if (cr.c1 != cr.c2) - // mrgcols = true; // in a range of merged columns - // if (cr.r1 != cr.r2) - // mrgrows = true; // in a range of merged rows - // continue; - // } - // } - // if (!mrgcols || !mrgrows) - // { - // // IF the row of the selected cell is NOT in merged range - // // then go ahead and adjust the row height (if needed) - // if (!mrgrows) - // { - // // add adjustment for grid and cell borders - // int newheight = trtb.Height + 3; - - // //Console.WriteLine("{0} {1} {2} '{3}'", r, c, newheight,trtb.Text); - // if (newheight > this.Rows[r].Height) - // { - // //Console.WriteLine("1 Row {0} Old Height = {1}, New Height = {2}", r, Rows[r].Height, newheight); - // this.Rows[r].Height = newheight; - // } - // } - // // IF the column of the selected cell is NOT in merged range - // // then go ahead and adjust the column width (if needed) - // if (!mrgcols) - // { - // // add adjustment for grid and cell borders - // int newwidth = trtb.Width + 2; - - // if (newwidth > this.Cols[c].Width || AllowWidthShrink || r == 0) - // this.Cols[c].Width = newwidth; - // } - // } - // if (mrgrows && tstr != null) - // { - // CellRange cr = GetMergedRange(r, c); - // if (cr.r1 == r && cr.c1 == c) - // { - // // if in merged rows, then make sure the cell's height is large enough - // string[] strary = tstr.Split("\n".ToCharArray()); - // // count number of lines of text - // int nlines = strary.Length; - // // count number of rows in merge range - // int nrows = (cr.r2 - cr.r1) + 1; - // //Console.WriteLine("2 Row {0} Height = {1}", cr.r1, Rows[cr.r1].Height); - // while (nlines > nrows) - // { - // // add length to first row in merged range - // int h = this.Rows[cr.r1].Height; - // int defH = Rows.DefaultSize - 3; - // h = (h == -1) ? (defH * 2) + 3 : h + defH; - // this.Rows[cr.r1].Height = h; - // nrows++; - // } - // } - // } - //} - - //private void Compare(string fromRTF, string fromStr, string rawstr) - //{ - // int istart = fromRTF.IndexOf(" ",fromRTF.IndexOf("viewkind")); - // int jstart = fromStr.IndexOf(" ",fromStr.IndexOf("viewkind")); - // for (int i = istart; i < fromRTF.Length; i++) - // { - // int j = i - istart + jstart; - // //else if (fromRTF[i] != fromStr[j]) - // if (fromRTF[i] != fromStr[j]) - // { - // if (fromRTF.Substring(i, 1) == @"~" && fromStr.Substring(j, 3) == @"'a0") - // { - // //i++; - // jstart += 2; - // } - // else - // { - // Console.WriteLine("fromStr:\r\n'{0}'\r\nfromRTF:\r\n'{1}'", fromStr, fromRTF); - // ShowRawString(rawstr, "rawstr"); - // Console.WriteLine("Str:'{0}' , RTF:'{1}'", fromStr.Substring(j, Math.Min(10,fromStr.Length-j-1)), fromRTF.Substring(i, Math.Min(10,fromRTF.Length-i-1))); - // return; - // } - // } - // } - //} - - #region DEBUG - //private void ShowRawString(string str, string title) - //{ - // Console.WriteLine("Raw Start --{0}:\n", title); - // foreach (char c in str) - // { - // int ic= (int)c; - // if (c!='\n'&&( ic > 126 || ic < 32)) - // Console.Write("<<{0:x4}>>", ic); - // else - // Console.Write(c); - // } - // Console.WriteLine("\n-- Raw End:{0}", title); - //} - #endregion - - private void Grid_AfterResize(object sender, C1.Win.C1FlexGrid.RowColEventArgs e) + private void Grid_AfterResize(object sender, C1.Win.C1FlexGrid.RowColEventArgs e) { this.AdjustGridControlSize(); } @@ -2444,47 +1853,20 @@ namespace Volian.Controls.Library } return curColWidth; } - - //private bool RemoveBoldUlineItalicChars(string str) - //{ - // int rtn = 0; - - // // Underline next word - // rtn += str.IndexOf(@"\'17"); - - // // Bold next word - // rtn += str.IndexOf(@"\'13"); - - // // Italics On - // rtn += str.IndexOf(@"\'1B4"); - - // // Italics Off - // rtn += str.IndexOf(@"\'1B5"); - - // // underline On - // rtn += str.IndexOf(@"\'ab"); - // // underline Off - // rtn += str.IndexOf(@"\'bb"); - - // return rtn > 0; - - //} - private string ConvertTableText(string str) { string rtn = str; string pattern = @"\\u([0-9]{1,4})\?"; - - string mValue, mValue2 = ""; + string mValue; foreach (Match match in Regex.Matches(rtn, pattern, RegexOptions.IgnoreCase)) { mValue = match.Value; - mValue2 = $"\\f1 {mValue}\\f0"; - rtn = rtn.Replace(match.Value, mValue2); + string mValue2 = $"\\f1 {mValue}\\f0"; + rtn = rtn.Replace(match.Value, mValue2); } - //ShowRawString(str, "ConvertTableText IN"); + //ShowRawString(str, "ConvertTableText IN"); //For Debugging rtn = rtn.Replace(@"START]\v0", @"START]\cf1\v0"); rtn = rtn.Replace(@"\v #Link:", @"\cf0\v #Link:"); rtn = rtn.Replace("\n", "\\par\r\n"); @@ -2529,47 +1911,14 @@ namespace Volian.Controls.Library rtn = rtn.Replace("\xd5", @"\b"); rtn = rtn.Replace("\xd6", @"\b0"); - //ShowRawString(rtn, "ConvertTableText OUT"); + //ShowRawString(rtn, "ConvertTableText OUT"); //For Debugging return rtn; } - - private static string SomethingNextWord(string str, string nxtwordcmd, string cmdOn, string cmdOff) - { - string rtn = ""; - int bidx = 0; - int fidx = str.IndexOf(nxtwordcmd, bidx); - char[] term = " \r\n\x02".ToCharArray(); - while (fidx > 0) - { - rtn += str.Substring(bidx, fidx - bidx) + cmdOn; - bidx = fidx + 4; - - if (bidx < str.Length) - { - fidx = str.IndexOfAny(term, bidx); - if (fidx > 0) - { - rtn += str.Substring(bidx, fidx - bidx) + cmdOff + str.Substring(fidx, 1); - bidx = fidx + 1; - } - } - - if (bidx < str.Length) - fidx = str.IndexOf(nxtwordcmd, bidx); - else - fidx = -1; - } - if (bidx < str.Length) - rtn += str.Substring(bidx); - - return rtn; - } - private void _StartEdit(object sender, C1.Win.C1FlexGrid.RowColEventArgs e) { // start editing the cell with the custom editor if(!IsRoTable ) - _tableCellEditor.StartEditing(e.Row, e.Col, _GettingFontSize); // C2021-005 added _GettingFontSize to prevent showing the editor + TableCellEditor.StartEditing(e.Row, e.Col, _GettingFontSize); // C2021-005 added _GettingFontSize to prevent showing the editor e.Cancel = true; } @@ -2584,19 +1933,19 @@ namespace Volian.Controls.Library // if the custom editor is visible, make it follow the cell being edited private void _AfterScroll(object sender, C1.Win.C1FlexGrid.RangeEventArgs e) { - this._tableCellEditor.UpdatePosition(); + this.TableCellEditor.UpdatePosition(); } // save last key pressed for the custom editor private void _KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { - this._tableCellEditor.SetPendingKey(e.KeyChar); + this.TableCellEditor.SetPendingKey(e.KeyChar); } public string GetCellRTFString(int row, int col) { - string rtnstr = ""; - foreach (CellRange r in this.MergedRanges) + string rtnstr; + foreach (CellRange r in this.MergedRanges) { if (r.ContainsRow(row) && r.ContainsCol(col)) { @@ -2662,35 +2011,11 @@ namespace Volian.Controls.Library } public void SplitSelection(bool bSplitCols) { - //Console.WriteLine("SplitSelection this.selection {0}", this.Selection); - //Debug_WritelineMySelection(); - //C1.Win.C1FlexGrid.CellRange sel = this.GetMergedRange(this.Selection.r1, this.Selection.c1); - //Console.WriteLine("SplitSelection myselection {0}", MySelection); - //foreach (CellRange sel in MySelection) - //{ - // //Console.WriteLine("SplitSelection foreach sel {0}", sel); - // if (sel.IsSingleCell) - // this.MergedRanges.Remove(sel); - // if (!(this.MergedRanges.Contains(sel)) && !didit) - // if (bSplitCols) - // SplitSelectionColumns(); - // else - // SplitSelectionRows(); - // didit = true; - //} if (bSplitCols) SplitSelectionColumns(); else SplitSelectionRows(); - //Debug_WritelineMySelection(); - //foreach (CellRange sel in MySelection) - //{ - // //Console.WriteLine("SplitSelection foreach sel {0}", sel); - // if (this.MergedRanges.Contains(sel)) - // SplitMergedRange(sel, bSplitCols); - //} - //this.Refresh(); - //RefreshMergeRangeCollection(); + this.AdjustGridControlSize(); } @@ -2727,15 +2052,9 @@ namespace Volian.Controls.Library Select(saveSelection); } } - private bool IsMergedRows(CellRange sel) - { - return (sel.r1 != sel.r2); - } - private bool IsMergedCols(CellRange sel) - { - return (sel.c1 != sel.c2); - } - private void SplitSelectionColumns() + private bool IsMergedRows(CellRange sel) => (sel.r1 != sel.r2); + private bool IsMergedCols(CellRange sel) => (sel.c1 != sel.c2); + private void SplitSelectionColumns() { bool hasNonMergedColumn = false; //Console.WriteLine("SplitSelectionColumns this.selection {0}", this.Selection); @@ -2786,8 +2105,6 @@ namespace Volian.Controls.Library this.MergedRanges.Add(tcr); this.Invalidate(); } - //CellRange tcr = this.GetCellRange(r, c, r, c + 1); - //this.MergedRanges.Add(tcr); } } // Adjust selected column widths @@ -2865,19 +2182,15 @@ namespace Volian.Controls.Library { int recHeight = this.GetCellRect(r, cr.c1).Height; this.Rows[r].Height = Math.Max(recHeight / 2, Rows.DefaultSize); - //this.Rows[r].Height = Math.Max(recHeight / 2, _minRowSplitHeight); //Console.WriteLine("Cell[{0},{1}].Height = {2}", r, cr.c1, recHeight); } } //foreach (CellRange crng in this.MergedRanges) // Console.WriteLine("merge ranges [{0},{1}] - [{2},{3}]", crng.r1, crng.c1, crng.r2, crng.c2); } - private void AdjustMergedRows(int row, bool above, bool removing) - { - AdjustMergedRows(row, 1, above, removing); - } + private void AdjustMergedRows(int row, bool above, bool removing) => AdjustMergedRows(row, 1, above, removing); - private void AdjustMergedRows(int row, int cnt, bool above, bool removing) + private void AdjustMergedRows(int row, int cnt, bool above, bool removing) { CellRangeCollection crc = new CellRangeCollection(this); if (removing) @@ -2920,8 +2233,8 @@ namespace Volian.Controls.Library if ((above && cr.r1 == inspos) || (!above && cr.r2 == inspos)) { string tstr = ""; - int newrow = 0; - if (above) + int newrow; + if (above) { if (this[cr.r1 + cnt, cr.c1] != null) tstr = this[cr.r1 + cnt, cr.c1].ToString(); @@ -2958,12 +2271,9 @@ namespace Volian.Controls.Library } } - private void AdjustMergedColumns(int col, bool left, bool removing) - { - AdjustMergedColumns(col, 1, left, removing); //adjusting for just one column - } + private void AdjustMergedColumns(int col, bool left, bool removing) => AdjustMergedColumns(col, 1, left, removing); //adjusting for just one column - private void AdjustMergedColumns(int col, int cnt, bool left, bool removing) + private void AdjustMergedColumns(int col, int cnt, bool left, bool removing) { CellRangeCollection crc = new CellRangeCollection(this); if (removing) @@ -2999,8 +2309,8 @@ namespace Volian.Controls.Library for (int insCnt = 0; insCnt < cnt; insCnt++) { string tstr = ""; - int newcol = 0; - if (left) + int newcol; + if (left) { if (inspos == cr.c1) tstr = (this[cr.r1, cr.c1 + 1] == null) ? "" : this[cr.r1, cr.c1 + 1].ToString(); @@ -3034,43 +2344,6 @@ namespace Volian.Controls.Library this.MergedRanges.Add(r); } } - - private bool RowIsInMergeRange(int row) - { - bool rtn = false; - if (row >= 0) - { - CellRange cr = this.Selection; - //rtn = true; // KBR: is this wrong, i.e. should it be like ColIsInMergeRange - int c = cr.c1; - while (!rtn && (c <= cr.c2)) - { - int idx = this.MergedRanges.IndexOf(row, c); - rtn = (idx > -1); - c++; - } - } - return rtn; - } - - private bool ColIsInMergeRange(int col) - { - bool rtn = false; - if (col >= 0) - { - CellRange cr = this.Selection; - //rtn = true; - int r = cr.r1; - while (!rtn && (r <= cr.r2)) - { - int idx = this.MergedRanges.IndexOf(r, col); - rtn = (idx > -1); - r++; - } - } - return rtn; - } - #endregion //Merged / Split Range #region Grid Add and Remove Row / Column @@ -3186,56 +2459,55 @@ namespace Volian.Controls.Library public void RemoveSelectedColumn() { - string msg = ""; - string title = ""; - CellRange saveCR = Selection; - this.SelectionMode = SelectionModeEnum.ColumnRange; - //this.Select(this.Selection.r1, this.Selection.c1); + CellRange saveCR = Selection; + this.SelectionMode = SelectionModeEnum.ColumnRange; this.Select(0, Selection.c1, Rows.Count - 1, Selection.c2); this.SelectionMode = SelectionModeEnum.Default; - if (Selection.c1 != Selection.c2) - { - msg = "Remove selected columns?"; - title = "Delete Columns"; - } - else - { - msg = "Remove this column?"; - title = "Delete Column"; - } - DialogResult dr = FlexibleMessageBox.Show(msg, title, MessageBoxButtons.YesNo); + string msg; + string title; + if (Selection.c1 != Selection.c2) + { + msg = "Remove selected columns?"; + title = "Delete Columns"; + } + else + { + msg = "Remove this column?"; + title = "Delete Column"; + } + DialogResult dr = FlexibleMessageBox.Show(msg, title, MessageBoxButtons.YesNo); if (dr == DialogResult.Yes) - RemoveColumns(this.Selection.r1, this.Selection.c1, 1+this.Selection.c2-this.Selection.c1); + RemoveColumns(this.Selection.c1, 1+this.Selection.c2-this.Selection.c1); else Select(saveCR); } public void RemoveSelectedRow() { - string msg = ""; - string title = ""; - CellRange saveCR = Selection; - this.SelectionMode = SelectionModeEnum.RowRange; + CellRange saveCR = Selection; + this.SelectionMode = SelectionModeEnum.RowRange; this.Select(Selection.r1, 0, Selection.r2, Cols.Count - 1); this.SelectionMode = SelectionModeEnum.Default; - if (Selection.r1 != Selection.r2) - { - msg = "Remove selected rows?"; - title = "Delete Rows"; - } - else - { - msg = "Remove this row?"; - title = "Delete Row"; - } - DialogResult dr = FlexibleMessageBox.Show(msg, title, MessageBoxButtons.YesNo); + string msg; + string title; + if (Selection.r1 != Selection.r2) + { + msg = "Remove selected rows?"; + title = "Delete Rows"; + } + else + { + msg = "Remove this row?"; + title = "Delete Row"; + } + DialogResult dr = FlexibleMessageBox.Show(msg, title, MessageBoxButtons.YesNo); if (dr == DialogResult.Yes) - this.RemoveRows(this.Selection.r1, this.Selection.c1, 1 + this.Selection.r2 - this.Selection.r1); + this.RemoveRows(this.Selection.r1, 1 + this.Selection.r2 - this.Selection.r1); else Select(saveCR); } - private void RemoveRows(int strow, int stcol, int cnt) + private void RemoveRows(int strow, int cnt) { bool mergedRow = false; for (int i = 0; i < cnt; i++) @@ -3260,7 +2532,7 @@ namespace Volian.Controls.Library this.AdjustGridControlSize(); } - private void RemoveColumns(int strow, int stcol, int cnt) + private void RemoveColumns(int stcol, int cnt) { bool mergedCol = false; for (int i = 0; i < cnt; i++) @@ -3289,18 +2561,18 @@ namespace Volian.Controls.Library public void CopyRow() { - _tableCellEditor.Hide(); // B2017-200 force save of changes from active edit session + TableCellEditor.Hide(); // B2017-200 force save of changes from active edit session DialogResult dr = DialogResult.Yes; SelectRow(); if (Selection.r1 != Selection.r2) { - //dr = MessageBox.Show("You selected a row that includes merged cells.\n\nThese additional rows must be included.\n\nCopy these rows?", "Copy Rows", MessageBoxButtons.YesNo); dr = FlexibleMessageBox.Show("Your selection was expanded due to merged cell regions.\n\nContinue with the copy?", "Copy Rows", MessageBoxButtons.YesNo); } if (dr == DialogResult.Yes) CopyToCopiedFlexGrid(GridCopyOption.Row); //TestSetBackgroundColor(); } + //For Debugging: //public void TestSetBackgroundColor() //{ // for (int r = Selection.r1; r <= Selection.r2; r++) @@ -3318,12 +2590,11 @@ namespace Volian.Controls.Library //} public void CopyColumn() { - _tableCellEditor.Hide(); // B2017-200 force save of changes from active edit session + TableCellEditor.Hide(); // B2017-200 force save of changes from active edit session SelectCol(); DialogResult dr = DialogResult.Yes; if (Selection.c1 != Selection.c2) { - //dr = MessageBox.Show("You selected a column that includes merged cells.\n\nThese additional columns must be included.\n\nCopy these columns?", "Copy Columns", MessageBoxButtons.YesNo); dr = FlexibleMessageBox.Show("Your selection was expanded due to merged cell regions.\n\nContinue with the copy?", "Copy Columns", MessageBoxButtons.YesNo); } if (dr == DialogResult.Yes) @@ -3332,7 +2603,7 @@ namespace Volian.Controls.Library public void CopyCellSelection() { - _tableCellEditor.Hide(); // B2017-200 force save of changes from active edit session + TableCellEditor.Hide(); // B2017-200 force save of changes from active edit session DialogResult dr = DialogResult.Yes; CellRange cr = Selection; MakeSelectionEven(); @@ -3441,10 +2712,6 @@ namespace Volian.Controls.Library ChangeCellAlign(cr, crm.Style.TextAlign); ChangeCellBorder(cr, crm.Style.Border.Style); } - //else - //{ - // cr.Style = null; // - didn't like the null - //} } private void RemoveMergedRanges(int r1, int c1, int r2, int c2) @@ -3635,7 +2902,7 @@ namespace Volian.Controls.Library c = cr.c2 + 1; if (c >= this.Cols.Count) { - r = r + 1; + r++; c = 0; if (r >= this.Rows.Count) return false; } @@ -3654,7 +2921,7 @@ namespace Volian.Controls.Library c = cr.c1 - 1; if (c < 0) { - r = r - 1; + r--; c = this.Cols.Count-1; if (r < 0) return false; } @@ -3686,11 +2953,11 @@ namespace Volian.Controls.Library } sb.Append("\r\n"); } - c = c + 1; + c++; if (c == w) { c = 0; - r = r + 1; + r++; } } return sb.ToString(); @@ -3705,13 +2972,14 @@ namespace Volian.Controls.Library /// public void ExportToXML(string initDir) { - SaveFileDialog sfd = new SaveFileDialog(); - sfd.DefaultExt = ".xml"; - sfd.Filter = "XML files (*.xml)|*.xml|All files (*.*)|*.* "; - //sfd.InitialDirectory = @"C:\Development\SampleTableData"; - sfd.InitialDirectory = initDir; - sfd.Title = "Save XML File"; - sfd.ShowDialog(); + SaveFileDialog sfd = new SaveFileDialog + { + DefaultExt = ".xml", + Filter = "XML files (*.xml)|*.xml|All files (*.*)|*.* ", + InitialDirectory = initDir, + Title = "Save XML File" + }; + sfd.ShowDialog(); this.WriteXml(sfd.FileName); } public string GetXMLData() @@ -3725,22 +2993,6 @@ namespace Volian.Controls.Library } return retstr; } - /// - /// Prompts user with Save File dialog. - /// Grid will be saved to an Excel file. - /// - /// - //public void ExportToExcel(string initDir) - //{ - // SaveFileDialog sfd = new SaveFileDialog(); - // sfd.DefaultExt = ".xls"; - // sfd.Filter = "Excel files (*.xls)|*.xls|All files (*.*)|*.* "; - // //sfd.InitialDirectory = @"C:\Development\SampleTableData"; - // sfd.InitialDirectory = initDir; - // sfd.Title = "Save Excel File"; - // sfd.ShowDialog(); - // this.SaveExcel(sfd.FileName); - //} /// /// Prompts user with Open File dialog. @@ -3750,50 +3002,25 @@ namespace Volian.Controls.Library /// public string ImportXML(string initDir) { - string rtn = ""; - OpenFileDialog ofd = new OpenFileDialog(); - ofd.DefaultExt = ".xml"; - ofd.Filter = "XML files (*.xml)|*.xml|All files (*.*)|*.* "; - //ofd.InitialDirectory = @"C:\Development\SampleTableData"; - ofd.InitialDirectory = initDir; - ofd.Multiselect = false; - ofd.Title = "Select XML File"; - ofd.ShowDialog(); + OpenFileDialog ofd = new OpenFileDialog + { + DefaultExt = ".xml", + Filter = "XML files (*.xml)|*.xml|All files (*.*)|*.* ", + InitialDirectory = initDir, + Multiselect = false, + Title = "Select XML File" + }; + ofd.ShowDialog(); this.Clear(); this.MergedRanges.Clear(); this.ReadXml(ofd.FileName); this.BorderStyle = C1.Win.C1FlexGrid.Util.BaseControls.BorderStyleEnum.None; this.KeyActionTab = KeyActionEnum.MoveAcross; this.AdjustGridControlSize(); - rtn = ofd.SafeFileName; - return rtn; + string rtn = ofd.SafeFileName; + return rtn; } - /// - /// Prompts user with Open File dialog. - /// Excel file will be imported to a table grid. - /// - /// - /// - //public string ImportExcel(string initDir) - //{ - // string rtn = ""; - // //VlnFlexGrid grd = rbtDefaultTable.Checked ? vlnFlexGrid2 : vlnFlexGrid3; //GetActiveGrid(); - // OpenFileDialog ofd = new OpenFileDialog(); - // ofd.DefaultExt = ".xls"; - // ofd.Filter = "Excel files (*.xls)|*.xls|All files (*.*)|*.*"; - // //ofd.InitialDirectory = @"C:\Development\SampleTableData"; - // ofd.InitialDirectory = initDir; - // ofd.Multiselect = false; - // ofd.Title = "Select Excel File"; - // ofd.ShowDialog(); - // this.Clear(); - // this.MergedRanges.Clear(); - // this.LoadExcel(ofd.FileName); - // this.AdjustGridControlSize(); - // rtn = ofd.SafeFileName; - // return rtn; - //} public static List ROTableUpdate(object sender, ROFstInfoROTableUpdateEventArgs args) { string xml = null; @@ -3807,8 +3034,8 @@ namespace Volian.Controls.Library myGrid.ReadXml(sr); sr.Close(); } - string roid = content.ContentRoUsages[0].ROID; //myGrid.ROID; - int rodbid = content.ContentRoUsages[0].RODbID; //myGrid.RODbId; + string roid = content.ContentRoUsages[0].ROID; + int rodbid = content.ContentRoUsages[0].RODbID; myGrid.Visible = false; myGrid.ConvertTableROToGrid(args.ROText, rodbid, roid); myGrid.FixTableCellsHeightWidth(); @@ -3823,8 +3050,10 @@ namespace Volian.Controls.Library srchtxt = myGrid.GetSearchableText(); isdirty = myGrid.IsGridChanged(args.OldGridXml, xml, false); } - List retlist = new List(); - retlist.Add(srchtxt); + List retlist = new List + { + srchtxt + }; if(isdirty) retlist.Add(xml); else @@ -3846,9 +3075,9 @@ namespace Volian.Controls.Library this.ROID = roid; } - private Regex _ReplaceSpaceNewLine = new Regex(@"(?<=\\[^' \\?\r\n\t]*) (?=\r\n)"); - private Regex _ReplaceTokenSpaceToken = new Regex(@"(?<=\\[^' \\?\r\n\t]*) (?=\\)"); - private Regex _RemoveComments = new Regex(@"\\v .*?\\v0( |$)"); + private readonly Regex _ReplaceSpaceNewLine = new Regex(@"(?<=\\[^' \\?\r\n\t]*) (?=\r\n)"); + private readonly Regex _ReplaceTokenSpaceToken = new Regex(@"(?<=\\[^' \\?\r\n\t]*) (?=\\)"); + private readonly Regex _RemoveComments = new Regex(@"\\v .*?\\v0( |$)"); private string PrepROTableText(string stepText) { @@ -3990,13 +3219,14 @@ namespace Volian.Controls.Library return rtnStr; } - /// - /// This will parse a string containing the ascii text of the old style VE-PROMS (16-bit) tables. - /// It will find the number of rows and columns base on newlines, vertical bars, and dashes. - /// Then it will parse the the text, place them in cells, and attempt to merge cells were needed. - /// - /// - public void ParseTableFromText(string buff,GridLinePattern border) + /// + /// This will parse a string containing the ascii text of the old style VE-PROMS (16-bit) tables. + /// It will find the number of rows and columns base on newlines, vertical bars, and dashes. + /// Then it will parse the the text, place them in cells, and attempt to merge cells were needed. + /// + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0059:Unnecessary assignment of a value", Justification = "This could possibly use a rewrite. Staying AS-IS for now. Variables reused inside loops.")] + public void ParseTableFromText(string buff,GridLinePattern border) { string txtbuff = PrepROTableText(buff); if (IsRoTable) txtbuff = _RemoveComments.Replace(txtbuff, ""); @@ -4139,26 +3369,7 @@ namespace Volian.Controls.Library jstr = tstr; else jstr += ((cl==curCol)? "\n" : "") + tstr; // multi line cell - //jstr += "\n" + tstr; // multi line cell - //this[rw, curCol] = jstr; this[rw, cl] = jstr; - //// take a peek at the start of the next piece of table text to parse - //// if it starts with a '-' char, then flag to merge the columns up to - //// this point with the same columns in the next row - //if (idx < txtbuff.Length - 1 && txtbuff[idx + 1] == '-') - //{ - // for (int c = curCol; c >= 0; c--) - // if (!tci[curRow, c].ColEnd) - // tci[curRow, c].MergeRowBellow = true; - //} - //int tcol = dicCols[idx]; - //// if were are that the end of the 16-bit text line, but not in the last column, - //// merge the remaining columns to the right - //if (curCol < tcol) - //{ - // for (int i = curCol; i <= tcol; i++) - // tci[curRow, i].MergeColRight = true; - //} } else // parsed text contains all dashes { @@ -4171,9 +3382,6 @@ namespace Volian.Controls.Library int nextCol = (curCol + 1 > this.Cols.Count) ? curCol : curCol + 1; if (!tci[curRow, nextCol].ColEnd) tci[curRow, nextCol].MergeRowBellow = true; - //for (int c = nextCol; c >= 0; c--) - // if (!tci[curRow, c].ColEnd) - // tci[curRow, c].MergeRowBellow = true; } tci[curRow, curCol].ColEnd = true; incRow = true; @@ -4189,14 +3397,12 @@ namespace Volian.Controls.Library tstr = txtbuff.Substring(idxst, idx - idxst); if (tstr.EndsWith("\r")) // strip off carrage return tstr = tstr.Substring(0, tstr.Length - 1); - //tstr = tstr.TrimEnd(" ".ToCharArray()); if (tstr.Length == 0) tstr += " "; // test for a string of '-' characters for (tstidx = 0; (tstidx < tstr.Length) && (tstr[tstidx] == '-'); tstidx++) ; if (tstidx < tstr.Length) // not a full line (row) of '-' chars { - //curCol = dicCols[colPos]; while (curCol > prevCol + 1) { tci[curRow, prevCol].MergeColRight = true; @@ -4215,9 +3421,7 @@ namespace Volian.Controls.Library jstr = tstr; else jstr += ((cl == curCol) ? "\n" : "") + tstr; // multi line cell - //jstr += "\n" + tstr; // multi line cell - //this[rw, curCol] = jstr; this[rw, cl] = jstr; } else if (tstr.Length > 0) // parsed text is all dash characters @@ -4255,7 +3459,6 @@ namespace Volian.Controls.Library } // parse out the remaining text tstr = txtbuff.Substring(idxst); - //tstr = tstr.TrimEnd(" ".ToCharArray()); if (tstr.Length == 0) tstr += " "; // test for a string of '-' characters @@ -4269,14 +3472,11 @@ namespace Volian.Controls.Library while (rw - 1 >= 0 && tci[rw - 1, curCol].MergeRowBellow) rw--; int cl = curCol; while (cl - 1 >= 0 && tci[rw, cl-1].MergeColRight) cl--; - //string jstr = (string)this[rw, curCol]; string jstr = (string)this[rw, cl]; if (jstr == null) jstr = tstr; else jstr += ((cl == curCol) ? "\n" : "") + tstr; // multi line cell - //jstr += "\n" + tstr; // multi line cell - //this[rw, curCol] = jstr; this[rw, cl] = jstr; } } @@ -4423,21 +3623,6 @@ namespace Volian.Controls.Library } #endregion //Bug Work Around - //public void CenterTheCellText() - //{ - // // Cannot use this type of text allignment with RTF text cells - // CellRange cr = this.Selection; - // for (int rw = cr.r1; rw <= cr.r2; rw++) - // for (int col = cr.c1; col <= cr.c2; col++) - // { - // CellRange tmp = this.GetCellRange(rw, col, rw, col); - // string StyleName = string.Format("R{0}C{1}Style", rw, col); - // CellStyle cs = this.Styles.Add(StyleName, tmp.Style); - // cs.TextAlign = TextAlignEnum.CenterCenter; - // tmp.Style = cs; - // } - - //} #region Uneven Selections /// /// True if the top and bottom row of the selection is the same for every column @@ -4478,36 +3663,27 @@ namespace Volian.Controls.Library if (Selection.IsSingleCell) return; // One cell by definition is Even MakeSelectionEven(Selection.r1, Selection.c1, Selection.r2, Selection.c2); } - public void SelectRow() - { - MakeSelectionEven(Selection.r1, 0, Selection.r2, Cols.Count - 1); - } - public void SelectCol() - { - MakeSelectionEven(0, Selection.c1, Rows.Count - 1, Selection.c2); - } - public void MakeSelectionEven(int r1,int c1, int r2, int c2) + public void SelectRow() => MakeSelectionEven(Selection.r1, 0, Selection.r2, Cols.Count - 1); + public void SelectCol() => MakeSelectionEven(0, Selection.c1, Rows.Count - 1, Selection.c2); + public void MakeSelectionEven(int r1,int c1, int r2, int c2) { if (c1 < 0 || c2 < 0 || r1 < 0 || r2 < 0) return; // if there is no selection don't bother CellRange cr = GetEvenSelection(r1, c1, r2, c2); Select(cr); } - public CellRange GetEvenSelection() - { - return GetEvenSelection(Selection.r1, Selection.c1, Selection.r2, Selection.c2); - } + public CellRange GetEvenSelection() => GetEvenSelection(Selection.r1, Selection.c1, Selection.r2, Selection.c2); - public CellRange GetEvenSelection(int r1, int c1, int r2, int c2) + public CellRange GetEvenSelection(int r1, int c1, int r2, int c2) { int cMinNew = MinimumColumn(r1, c1); // Get the left column of the top row int cMaxNew = MaximumColumn(r1, c2); // Get the right column of the top row int rMinNew = MinimumRow(r1, c1); // Get the top row of the left column int rMaxNew = MaximumRow(r2, c1); // Get the bottom row of the left column - int cMin = cMinNew; - int cMax = cMaxNew; - int rMin = rMinNew; - int rMax = rMaxNew; + int cMin; + int cMax; + int rMin; + int rMax; do { cMin = cMinNew; @@ -4541,24 +3717,12 @@ namespace Volian.Controls.Library CellRange cr = GetCellRange(rMinNew, cMinNew, rMaxNew, cMaxNew); return cr; } - private int MinimumColumn(int r, int c) - { - return GetMergedRange(r, c).c1; - } - private int MaximumColumn(int r, int c) - { - return GetMergedRange(r, c).c2; - } - private int MinimumRow(int r, int c) - { - return GetMergedRange(r, c).r1; - } - private int MaximumRow(int r, int c) - { - return GetMergedRange(r, c).r2; - } - public Color StyleBackColor - { + private int MinimumColumn(int r, int c) => GetMergedRange(r, c).c1; + private int MaximumColumn(int r, int c) => GetMergedRange(r, c).c2; + private int MinimumRow(int r, int c) => GetMergedRange(r, c).r1; + private int MaximumRow(int r, int c) => GetMergedRange(r, c).r2; + public Color StyleBackColor + { get {return Styles.Normal.BackColor;} set { @@ -4627,23 +3791,6 @@ namespace Volian.Controls.Library Select(r1,c1,r2,c2); } - public void Debug_WritelineMySelection() - { - int r1 = MySelection[0].r1; - int r2 = MySelection[0].r2; - int c1 = MySelection[0].c1; - int c2 = MySelection[0].c2; - Console.WriteLine("Initial MySelection[0] {0}", MySelection[0]); - foreach (CellRange cr in MySelection) - { - r1 = Math.Min(r1, cr.r1); - c1 = Math.Min(c1, cr.c1); - r2 = Math.Max(r2, cr.r2); - c2 = Math.Max(c2, cr.c2); - Console.WriteLine("Foreach range ({0},{1}) - ({2},{3})", r1, c1, r2, c2); - } - } - #endregion } /// @@ -4740,35 +3887,14 @@ namespace Volian.Controls.Library # region TableCellInfo for text parse class TableCellInfo { - private bool _MergeRowBellow; + public bool MergeRowBellow { get; set; } - public bool MergeRowBellow - { - get { return _MergeRowBellow; } - set { _MergeRowBellow = value; } - } - private bool _MergeColRight; + public bool MergeColRight { get; set; } - public bool MergeColRight - { - get { return _MergeColRight; } - set { _MergeColRight = value; } - } - private bool _ColEnd; + public bool ColEnd { get; set; } - public bool ColEnd - { - get { return _ColEnd; } - set { _ColEnd = value; } - } - private string _Text; - - public string Text - { - get { return _Text; } - set { _Text = value; } - } - } + public string Text { get; set; } + } #endregion //TableCellInfo for text parse #region TableCellEditor /// @@ -4777,7 +3903,7 @@ namespace Volian.Controls.Library /// public class TableCellEditor : StepRTB //System.Windows.Forms.RichTextBox //System.Windows.Forms.TextBox // System.Windows.Forms.ComboBox { - private VlnFlexGrid _owner; + private readonly VlnFlexGrid _owner; private int _row, _col; private char _pendingKey; private bool _cancel; @@ -4800,7 +3926,6 @@ namespace Volian.Controls.Library this.CursorKeyPress += new StepRTBCursorKeysEvent(TableCellEditor_CursorKeyPress); this.Leave += new EventHandler(_editor_Leave); this.SelectionChanged += TableCellEditor_SelectionChanged; - //this.HeightChanged += new StepRTBEvent(_HeightChanged); } // C2021-005 selecting characters in the cell text editor @@ -4815,22 +3940,17 @@ namespace Volian.Controls.Library } } - protected override void Dispose(bool disposing) + protected override void Dispose(bool disposing) => base.Dispose(disposing); + // start editing: move to cell and activate + // C2021-005 added the showEditor - set to true when we are getting the font size of the text + public void StartEditing(int row, int col, bool showEditor) { - base.Dispose(disposing); - } - // start editing: move to cell and activate - // C2021-005 added the showEditor - set to true when we are getting the font size of the text - public void StartEditing(int row, int col, bool showEditor) - { - ItemInfo pinfo = MyItemInfo.MyProcedure as ItemInfo; - DocVersionInfo dvi = (pinfo == null) ? null : pinfo.ActiveParent as DocVersionInfo; - _initializingEdit = true; + DocVersionInfo dvi = (!(MyItemInfo.MyProcedure is ItemInfo pinfo)) ? null : pinfo.ActiveParent as DocVersionInfo; + _initializingEdit = true; ReadOnly = IsRoTable || !UserInfo.CanEdit(MyUserInfo, dvi); // reviewer cannot make changes to a table // save coordinates of cell being edited _row = row; _col = col; - //this.Clear(); //jsj // assume we'll save the edits _cancel = false; // move editor over the current cell @@ -4862,9 +3982,6 @@ namespace Volian.Controls.Library } Select(Text.Length, 0); - Size sz = new Size(rc.Width, rc.Height); - - //this.Size = sz; this.Width = rc.Width; if (!showEditor) // C2021-005 if we are getting the font size don't show the editor @@ -4873,9 +3990,8 @@ namespace Volian.Controls.Library Visible = true; } - // and get the focus - //Select(); - Focus(); + // and get the focus + Focus(); _initializingEdit = false; } @@ -4892,12 +4008,6 @@ namespace Volian.Controls.Library //Console.WriteLine("keystroke {0} selection {1},{2}", args.Key, row, col); //vlnStackTrace.ShowStack("keystroke {0} selection {1},{2}", args.Key, row, col); _owner.Select(); - // See if we are in a merged range of cells. - // if so, use the merged range instead of the selected range - // so that we can jump to the top/bottom/left/right of the range - // before attempting the move to the next grid cell. - //int idx = _owner.MergedRanges.IndexOf(row, col); - //if (idx > -1) cr = _owner.MergedRanges[idx]; switch (args.Key) { @@ -4949,7 +4059,6 @@ namespace Volian.Controls.Library break; } //Console.WriteLine("selection {0}", _owner.Selection); - //_owner.Focus(); // focus was jumping out of the grid this keeps it in. } // after edit handler (custom editor) @@ -4958,10 +4067,6 @@ namespace Volian.Controls.Library _owner.Invalidate(); _owner.AdjustGridControlSize(); } - //void _HeightChanged(object sender, EventArgs args) - //{ - // _owner.Invalidate(); - //} // save key that started the editing mode public void SetPendingKey(char chr) @@ -5022,84 +4127,14 @@ namespace Volian.Controls.Library if (keyData == Keys.Tab) return true; return base.IsInputKey(keyData); } - - //// some keys end the editing - //override protected void OnKeyDown(System.Windows.Forms.KeyEventArgs e) - //{ - // switch (e.KeyCode) - // { - // case Keys.Escape: // cancel edits - // _cancel = true; - // _owner.Select(); - // e.Handled = true; - // return; - - // case Keys.Enter: // finish editing - // case Keys.Tab: - // case Keys.Up: - // case Keys.Down: - // case Keys.PageUp: - // case Keys.PageDown: - // _owner.Select(); - // e.Handled = true; - // MoveCursor(e.KeyCode); - // return; - - // default: // default processing - // base.OnKeyDown(e); - // return; - // } - //} - - //// move cursor after done editing - //protected void MoveCursor(Keys key) - //{ - // int row = _owner.Row; - // int col = _owner.Col; - // switch (key) - // { - // case Keys.Tab: col++; break; - // case Keys.Up: row--; break; - // //case Keys.Return: row++; break; - // case Keys.Down: row++; break; - // //case Keys.PageUp: row -= 10; break; - // //case Keys.PageDown: row += 10; break; - // } - - // // validate new selection - // if (row < _owner.Rows.Fixed) row = _owner.Rows.Fixed; - // if (col < _owner.Cols.Fixed) col = _owner.Cols.Fixed; - // if (row > _owner.Rows.Count - 1) row = _owner.Rows.Count - 1; - // if (col > _owner.Cols.Count - 1) col = _owner.Cols.Count - 1; - - // // apply new selection - // _owner.Select(row, col); - //} - - //// suppress some keys to avoid annoying beep - //override protected void OnKeyPress(System.Windows.Forms.KeyPressEventArgs e) - //{ - // switch (e.KeyChar) - // { - // case (char)27: // Keys.Escape: - // case (char)13: // Keys.Enter: - // case (char)9: // Keys.Tab: - // e.Handled = true; - // return; - // } - // base.OnKeyPress(e); - //} } #endregion // TableCellEditor #region TableClipBoardFuncts Class class TableClipBoardFuncts { - DataFormats.Format dfmtTableCellRange = DataFormats.GetFormat("TableCellRange"); - private SelectedTableCells mySeldTableCellsObject; - private DataObject myDataObject; public TableClipBoardFuncts() { - //mySeldTableCellsObject = new DataObject(dfmtTableCellRange.Name, seldTableCells); + } public void Put(CellRange cr) @@ -5107,20 +4142,7 @@ namespace Volian.Controls.Library // Copies myObject into the clipboard. // Clip get the value (text) of all the cells in the selected range // This is saved as one RTF string. - Clipboard.SetDataObject(cr.Clip, true); // the "true" make the copy persistent - //Console.WriteLine("\nClip: '{0}' \n'{1}'", cr.Clip,cr.DataDisplay); - //mySeldTableCellsObject = new SelectedTableCells(); - //mySeldTableCellsObject.CpbrdCellRange = cr; - // myDataObject = new DataObject(dfmtTableCellRange.Name, mySeldTableCellsObject); - // try - // { - // Clipboard.SetDataObject(myDataObject); //,true); - // } - // catch (Exception ex) - // { - // Console.WriteLine(ex.Message); - // } - + Clipboard.SetDataObject(cr.Clip, true); // the "true" makes the copy persistent } public ArrayList Get() @@ -5130,28 +4152,6 @@ namespace Volian.Controls.Library string jj = (string)myRetrievedObject.GetData(DataFormats.Text); return GetCellStrings(jj); } - - //public CellRange get_cr_Paste() - //{ - // mySeldTableCellsObject = new SelectedTableCells(); - // CellRange cr = new CellRange(); - // SelectedTableCells sc; - // IDataObject myRetrievedObject = Clipboard.GetDataObject(); - // try - // { - // //object obj = myRetrievedObject.GetData(dfmtTableCellRange.Name); - // object obj = myRetrievedObject.GetData("TableCellRange"); - // //sc = (SelectedTableCells)myRetrievedObject.GetData(dfmtTableCellRange.Name); - // sc = (SelectedTableCells)obj; - // cr = sc.CpbrdCellRange; - // } - // catch (Exception ex) - // { - // Console.WriteLine(ex.Message); - // } - // return cr; - //} - private ArrayList GetCellStrings(string instr) { // The table cells placed on the clipboard is saved as one long RTF string. @@ -5164,10 +4164,9 @@ namespace Volian.Controls.Library // Bug fix: the CellRange.Clip (see cr.clip in the Put() function above) is replacing // new lines with spaces. We need to put them back. instr = instr.Replace(@"}} \", "}}\r\n\\"); - string tstr = ""; // this will contain the parsed out cell text + string tstr; // this will contain the parsed out cell text ArrayList arylstCellStrings = new ArrayList(); int sidx = 0; // start index - int tidx = 0; if (instr != null) { int idx = instr.IndexOf(@"{\rtf",sidx+1); // cell boarder @@ -5188,49 +4187,6 @@ namespace Volian.Controls.Library } return arylstCellStrings; } - - //private ArrayList GetCellStrings(string instr) - //{ - // // The table cells placed on the clipboard is saved as one long RTF string. - // // "\r\n\t" defines a cell border - // // "\r\n\r" defines beginning of next line (row) - // // This function will separate each cell text and place them in an array. - // // This allow the clipboard information to be pasted independently from - // // how it was selected. - - // string tstr = ""; // this will contain the parsed out cell text - // ArrayList arylstCellStrings = new ArrayList(); - // int sidx = 0; // start index - // int tidx = 0; - // if (instr != null) - // { - // int idx = instr.IndexOf("\r\n\t"); // cell boarder - // if (idx < 0) idx = instr.IndexOf("\r\n\r"); // new line (needed for multiple lines in one cell) - // while (idx > 0) - // { - // tstr = instr.Substring(sidx, idx - sidx); - // tidx = tstr.IndexOf("\r\n\r"); - // if (tidx > 0) - // { - // idx = instr.IndexOf("\r\n\r", sidx); - // tstr = instr.Substring(sidx, idx - sidx); - // } - // arylstCellStrings.Add(tstr.Substring(tstr.IndexOf("{\\rtf"))); - // sidx = idx + 3; - // if (sidx < instr.Length) - // { - // idx = instr.IndexOf("\r\n\t", sidx); - // if (idx < 0) idx = instr.IndexOf("\r\n\r", sidx); - // } - // } - // if (sidx < instr.Length) - // { - // tstr = instr.Substring(sidx); - // arylstCellStrings.Add(tstr.Substring(tstr.IndexOf("{\\rtf"))); - // } - // } - // return arylstCellStrings; - //} } [Serializable] @@ -5250,55 +4206,28 @@ namespace Volian.Controls.Library #endregion // TableClipBoardFuncts Class public class VlnFlexGridCursorMovementEventArgs { - private E_ArrowKeys _Key; - public E_ArrowKeys Key + public E_ArrowKeys Key { get; set; } + public VlnFlexGridCursorMovementEventArgs(E_ArrowKeys key) { - get { return _Key; } - set { _Key = value; } - } - public VlnFlexGridCursorMovementEventArgs(E_ArrowKeys key) - { - _Key = key; + Key = key; } } public class VlnFlexGridPasteEventArgs { - private string _Text; - public string Text + public string Text { get; set; } + public VlnFlexGridPasteEventArgs(string text) { - get { return _Text; } - set { _Text = value; } - } - public VlnFlexGridPasteEventArgs(string text) - { - _Text = text; + Text = text; } } public class GridCopyInfo { - private GridCopyOption _MyCopyOption = GridCopyOption.Selection; + public GridCopyOption MyCopyOption { get; set; } = GridCopyOption.Selection; - public GridCopyOption MyCopyOption - { - get { return _MyCopyOption; } - set - { - //Console.WriteLine("MyCopyOption = {0}", _MyCopyOption); - //if (_MyCopyOption != value) - // Console.WriteLine("Changed Option to {0}", value); - _MyCopyOption = value; - } - } - private VlnFlexGrid _MyCopiedFlexGrid = null; + public VlnFlexGrid MyCopiedFlexGrid { get; set; } = null; + private CellRange _MyCopiedCellRange; - public VlnFlexGrid MyCopiedFlexGrid - { - get { return _MyCopiedFlexGrid; } - set { _MyCopiedFlexGrid = value; } - } - private CellRange _MyCopiedCellRange; - - public CellRange MyCopiedCellRange + public CellRange MyCopiedCellRange { get { return _MyCopiedCellRange; } set { _MyCopiedCellRange = value; } diff --git a/PROMS/Volian.Controls.Library/VlnGridCellShading.cs b/PROMS/Volian.Controls.Library/VlnGridCellShading.cs index f172aecf..3c725a37 100644 --- a/PROMS/Volian.Controls.Library/VlnGridCellShading.cs +++ b/PROMS/Volian.Controls.Library/VlnGridCellShading.cs @@ -1,11 +1,6 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; -using System.Xml.Schema; using System.Drawing; using Volian.Base.Library; @@ -89,69 +84,26 @@ namespace Volian.Controls.Library string strARGB = string.Format("[A={0}, R={1}, G={2}, B={3}]", clr.A, clr.R, clr.G, clr.B); return strARGB; } - public void SetColor(int row, int col, Color CellColor) - { - // Set the table cell to the ARGB representation of the passed in color - string cellShadeColor = GetARGBstring(CellColor); - TableShadingInfo[row, col] = cellShadeColor; - return; - } - #endregion - #region Insert and Remove Rows and Columns - public void InsertRow(int row) - { - TableShadingInfo.InsertRow(row); - } - public void InsertRows(int row, int count) - { - TableShadingInfo.InsertRows(row, count); - } - public void DeleteRow(int row) - { - TableShadingInfo.DeleteRow(row); - } - public void DeleteRows(int row, int count) - { - TableShadingInfo.DeleteRows(row, count); - } - public void InsertColumn(int column) - { - TableShadingInfo.InsertColumn(column); - } - public void InsertColumns(int column, int count) - { - TableShadingInfo.InsertColumns(column, count); - } - public void DeleteColumn(int column) - { - TableShadingInfo.DeleteColumn(column); - } - public void DeleteColumns(int column, int count) - { - TableShadingInfo.DeleteColumns(column, count); - } - #endregion - #region Serialize - public string ConvertToString() + #endregion + #region Insert and Remove Rows and Columns + public void InsertRow(int row) => TableShadingInfo.InsertRow(row); + public void InsertRows(int row, int count) => TableShadingInfo.InsertRows(row, count); + public void DeleteRow(int row) => TableShadingInfo.DeleteRow(row); + public void DeleteRows(int row, int count) => TableShadingInfo.DeleteRows(row, count); + public void InsertColumn(int column) => TableShadingInfo.InsertColumn(column); + public void InsertColumns(int column, int count) => TableShadingInfo.InsertColumns(column, count); + public void DeleteColumns(int column, int count) => TableShadingInfo.DeleteColumns(column, count); + #endregion + #region Serialize + public string ConvertToString() { return GenericSerializer.StringSerialize(this); } - public override string ToString() - { - return "Volian Custom Cell Shading"; - } public static VlnGridCellShading Get(string xml) { return GenericSerializer.StringDeserialize(xml); } #endregion - // Adjust the cell shading array if needed - public void CheckAndFixShadingArraySize(int grdRows, int grdCols, Color defaultCellShading) - { - if (TableShadingInfo.Columns != grdCols || TableShadingInfo.Rows != grdRows) - TableShadingInfo = new CellShadingArray(defaultCellShading, grdRows, grdCols, TableShadingInfo.CellShadingColor); - } - } [Serializable] public class CellShadingArray @@ -200,22 +152,6 @@ namespace Volian.Controls.Library for (int c = 0; c < Columns; c++) CellShadingColor[r * Columns + c] = defaultShadingColorARGB; } - // Used to automatically adjust the cell shading color array - public CellShadingArray(Color defaultShadingColor, int rows, int columns, string[] shadeAry) - { - Rows = rows; - Columns = columns; - CellShadingColor = new string[rows * columns]; - for (int r = 0; r < Rows; r++) - for (int c = 0; c < Columns; c++) - { - int idx = r * Columns + c; - if (idx < shadeAry.Length) - CellShadingColor[idx] = shadeAry[idx]; - else - CellShadingColor[idx] = defaultShadingColor.ToString(); - } - } #endregion #region Array Access public string this[int r, int c] @@ -232,13 +168,10 @@ namespace Volian.Controls.Library CellShadingColor[r * Columns + c] = value; } } - #endregion - #region Insert and Delete Rows and Columns - public void InsertRow(int row) - { - InsertRows(row, 1); - } - public void InsertRows(int row, int count) + #endregion + #region Insert and Delete Rows and Columns + public void InsertRow(int row) => InsertRows(row, 1); + public void InsertRows(int row, int count) { // Create a new Array of the correct size string[] newLines = new string[(Rows + count) * Columns]; @@ -255,11 +188,8 @@ namespace Volian.Controls.Library CellShadingColor = newLines; Rows = newRows; } - public void DeleteRow(int row) - { - DeleteRows(row, 1); - } - public void DeleteRows(int row, int count) + public void DeleteRow(int row) => DeleteRows(row, 1); + public void DeleteRows(int row, int count) { string[] newLines = new string[(Rows - count) * Columns]; int newRows = Rows - count; @@ -274,11 +204,8 @@ namespace Volian.Controls.Library CellShadingColor = newLines; Rows = newRows; } - public void InsertColumn(int column) - { - InsertColumns(column, 1); - } - public void InsertColumns(int column, int count) + public void InsertColumn(int column) => InsertColumns(column, 1); + public void InsertColumns(int column, int count) { // Create a new Array of the correct size string[] newLines = new string[Rows * (Columns + count)]; @@ -294,11 +221,8 @@ namespace Volian.Controls.Library CellShadingColor = newLines; Columns = newColumns; } - public void DeleteColumn(int column) - { - DeleteColumns(column, 1); - } - public void DeleteColumns(int column, int count) + public void DeleteColumn(int column) => DeleteColumns(column, 1); + public void DeleteColumns(int column, int count) { string[] newLines = new string[Rows * (Columns - count)]; int newColumns = Columns - count; diff --git a/PROMS/Volian.Controls.Library/VlnSpellCheck.cs b/PROMS/Volian.Controls.Library/VlnSpellCheck.cs index e9a71054..86b9dac6 100644 --- a/PROMS/Volian.Controls.Library/VlnSpellCheck.cs +++ b/PROMS/Volian.Controls.Library/VlnSpellCheck.cs @@ -1,24 +1,13 @@ -using System; -using System.Collections.Generic; -using System.Text; using VEPROMS.CSLA.Library; namespace Volian.Controls.Library { public class VlnSpellCheck { - private EditItem _MyEditItem; - public EditItem MyEditItem - { - get { return _MyEditItem; } - set - { - _MyEditItem = value; - } - } + public EditItem MyEditItem { get; set; } - public VlnSpellCheck() + public VlnSpellCheck() { } diff --git a/PROMS/Volian.Controls.Library/VlnSpellCheckDlg.cs b/PROMS/Volian.Controls.Library/VlnSpellCheckDlg.cs index b02f9476..2ac136f0 100644 --- a/PROMS/Volian.Controls.Library/VlnSpellCheckDlg.cs +++ b/PROMS/Volian.Controls.Library/VlnSpellCheckDlg.cs @@ -1,11 +1,6 @@ using System; using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; using System.Windows.Forms; -using DevComponents.DotNetBar; using C1.Win.C1SpellChecker; namespace Volian.Controls.Library @@ -19,31 +14,26 @@ namespace Volian.Controls.Library private int _ErrorCount; private int _ErrorIndex = -1; // current error index private bool _AutoSuggest = true; - private string _NoSuggestionsText = "(no suggestions)"; + private readonly string _NoSuggestionsText = "(no suggestions)"; - Dictionary _changeAll = new Dictionary(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + Dictionary _changeAll = new Dictionary(); - /// - /// Gets the object that represents the error currently - /// displayed in the dialog. - /// - public CharRange CurrentError - { - get { return _Errors[_ErrorIndex]; } - } - public bool DidCorrectSpelling = false; // B2015-024 have Spell Checker text changes be in editorial mode (not assign a change bar but keep existing change bar) + /// + /// Gets the object that represents the error currently + /// displayed in the dialog. + /// + public CharRange CurrentError => _Errors[_ErrorIndex]; + public bool DidCorrectSpelling = false; // B2015-024 have Spell Checker text changes be in editorial mode (not assign a change bar but keep existing change bar) - public VlnSpellCheckDlg() - { - InitializeComponent(); - } - /// - /// Initializes the dialog to use the given parameters. - /// - /// to use for spelling. - /// that contains the text to spell-check. - /// that contains the initial error list. - public void Initialize(C1SpellChecker spell, ISpellCheckableEditor editor, CharRangeList errors) + public VlnSpellCheckDlg() => InitializeComponent(); + /// + /// Initializes the dialog to use the given parameters. + /// + /// to use for spelling. + /// that contains the text to spell-check. + /// that contains the initial error list. + public void Initialize(C1SpellChecker spell, ISpellCheckableEditor editor, CharRangeList errors) { _Spell = spell; _Editor = editor; @@ -55,18 +45,15 @@ namespace Volian.Controls.Library _ErrorCount += _Errors.Count; btnAddToDictionary.Visible = _Spell.UserDictionary.Enabled; } - /// - /// Gets the total number of errors detected in the control. - /// - public int ErrorCount - { - get { return _ErrorCount; } - } + /// + /// Gets the total number of errors detected in the control. + /// + public int ErrorCount => _ErrorCount; - /// - /// Gets or sets the index of the current error into the list. - /// - public int ErrorIndex + /// + /// Gets or sets the index of the current error into the list. + /// + public int ErrorIndex { get { return _ErrorIndex; } set @@ -105,7 +92,7 @@ namespace Volian.Controls.Library { // fire load event base.OnLoad(e); - //AddHandle(); + //AddHandle(); //For Debugging // show first error (after firing load event) ErrorIndex = 0; } @@ -204,8 +191,6 @@ namespace Volian.Controls.Library // show 'Add' button only if user dictionary is enabled btnAddToDictionary.Visible = _Spell.UserDictionary.Enabled; - // all ready, fire ErrorDisplayed event - //OnErrorDisplayed(EventArgs.Empty); } private void SetupSuggestions(string badWord) @@ -251,23 +236,17 @@ namespace Volian.Controls.Library return false; } - private void btnChange_Click(object sender, EventArgs e) - { - UpdateEditor(txbBadWord.Text); - } + private void btnChange_Click(object sender, EventArgs e) => UpdateEditor(txbBadWord.Text); - private void btnChangeAll_Click(object sender, EventArgs e) + private void btnChangeAll_Click(object sender, EventArgs e) { _changeAll[CurrentError.Text] = txbBadWord.Text; UpdateEditor(txbBadWord.Text); } - private void btnIgnore_Click(object sender, EventArgs e) - { - ErrorIndex++; - } + private void btnIgnore_Click(object sender, EventArgs e) => ErrorIndex++; - private void btnIgnoreAll_Click(object sender, EventArgs e) + private void btnIgnoreAll_Click(object sender, EventArgs e) { //Console.WriteLine("handle: {0}", this.Handle); _Spell.IgnoreList.Add(CurrentError.Text); @@ -299,9 +278,6 @@ namespace Volian.Controls.Library } } - private void btnRemove_Click(object sender, EventArgs e) - { - UpdateEditor(""); - } - } + private void btnRemove_Click(object sender, EventArgs e) => UpdateEditor(""); + } } \ No newline at end of file diff --git a/PROMS/Volian.Controls.Library/Volian.Controls.Library.csproj b/PROMS/Volian.Controls.Library/Volian.Controls.Library.csproj index c840ed21..5b1f3b56 100644 --- a/PROMS/Volian.Controls.Library/Volian.Controls.Library.csproj +++ b/PROMS/Volian.Controls.Library/Volian.Controls.Library.csproj @@ -126,7 +126,6 @@ - UserControl @@ -238,6 +237,9 @@ FindReplace.cs + + Component + Form @@ -269,6 +271,7 @@ frmViewTextFile.cs + UserControl @@ -368,9 +371,6 @@ DSOTabPanel.cs - - Component - @@ -443,12 +443,6 @@ vlnTreeView3.cs - - Form - - - WebBrowser.cs - @@ -557,10 +551,6 @@ VlnSpellCheckDlg.cs Designer - - WebBrowser.cs - Designer - diff --git a/PROMS/Volian.Controls.Library/WebBrowser.Designer.cs b/PROMS/Volian.Controls.Library/WebBrowser.Designer.cs deleted file mode 100644 index 71620404..00000000 --- a/PROMS/Volian.Controls.Library/WebBrowser.Designer.cs +++ /dev/null @@ -1,63 +0,0 @@ -namespace Volian.Controls.Library -{ - partial class WebBrowser - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.WebBrowserWindow = new System.Windows.Forms.WebBrowser(); - this.SuspendLayout(); - // - // WebBrowserWindow - // - this.WebBrowserWindow.Dock = System.Windows.Forms.DockStyle.Fill; - this.WebBrowserWindow.Location = new System.Drawing.Point(0, 0); - this.WebBrowserWindow.MinimumSize = new System.Drawing.Size(20, 20); - this.WebBrowserWindow.Name = "WebBrowserWindow"; - this.WebBrowserWindow.Size = new System.Drawing.Size(1039, 723); - this.WebBrowserWindow.TabIndex = 0; - //this.WebBrowserWindow.Url = new System.Uri("http://www.volian.com", System.UriKind.Absolute); - //this.WebBrowserWindow.Url = new System.Uri(_currentURL, System.UriKind.Absolute); - //this.WebBrowserWindow.Navigate(_currentURL); - // - // WebBrowser - // - this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(1039, 723); - this.Controls.Add(this.WebBrowserWindow); - this.Name = "WebBrowser"; - this.ShowIcon = false; - this.Text = "WebBrowser"; - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.WebBrowser WebBrowserWindow; - } -} \ No newline at end of file diff --git a/PROMS/Volian.Controls.Library/WebBrowser.cs b/PROMS/Volian.Controls.Library/WebBrowser.cs deleted file mode 100644 index 6f9ccf67..00000000 --- a/PROMS/Volian.Controls.Library/WebBrowser.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; - -namespace Volian.Controls.Library -{ - public partial class WebBrowser : DevComponents.DotNetBar.Office2007Form //Form - { - private string _currentURL = @"http:/www.volian.com"; // default to volain web site - - /// - /// Display an instance of the default internet web browser. - /// Note that besides a web site address, you can pass in a PDF file name (include the path). - /// This assumes that the user's web browser can display PDF files. - /// If nothing is passed in, then this will default to displaying the Volian Web Site. - /// - /// The URL of the web site you want to display - public WebBrowser(string url) - { - _currentURL = url; - //this.Text = url; - InitializeComponent(); - this.WebBrowserWindow.Navigate(_currentURL); - this.TitleText = _currentURL; - } - public WebBrowser() - { - InitializeComponent(); - this.WebBrowserWindow.Navigate(_currentURL); - this.TitleText = _currentURL; - } - - } -} \ No newline at end of file diff --git a/PROMS/Volian.Controls.Library/WebBrowser.resx b/PROMS/Volian.Controls.Library/WebBrowser.resx deleted file mode 100644 index 19dc0dd8..00000000 --- a/PROMS/Volian.Controls.Library/WebBrowser.resx +++ /dev/null @@ -1,120 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/PROMS/Volian.Controls.Library/dlgChgId.cs b/PROMS/Volian.Controls.Library/dlgChgId.cs index 74bdb7c2..95e563c6 100644 --- a/PROMS/Volian.Controls.Library/dlgChgId.cs +++ b/PROMS/Volian.Controls.Library/dlgChgId.cs @@ -1,16 +1,11 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; using System.Windows.Forms; namespace Volian.Controls.Library { public partial class dlgChgId : Form { - DisplayTabControl TabControl; + readonly DisplayTabControl TabControl; public dlgChgId(DisplayTabControl tc) { InitializeComponent(); diff --git a/PROMS/Volian.Controls.Library/dlgDelProcReason.cs b/PROMS/Volian.Controls.Library/dlgDelProcReason.cs index e616b2bd..f84ceb2d 100644 --- a/PROMS/Volian.Controls.Library/dlgDelProcReason.cs +++ b/PROMS/Volian.Controls.Library/dlgDelProcReason.cs @@ -1,9 +1,4 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; using System.Windows.Forms; namespace Volian.Controls.Library @@ -12,11 +7,11 @@ namespace Volian.Controls.Library // (a few users said that procedures 'disappeared' but this could not be reproduced) public partial class dlgDelProcReason : Form { - vlnTreeView VTreeView; + readonly vlnTreeView VTreeView; public dlgDelProcReason(vlnTreeView tv) { InitializeComponent(); - this.Text = "Verify Delete By " + Volian.Base.Library.VlnSettings.UserID; + this.Text = $"Verify Delete By {Volian.Base.Library.VlnSettings.UserID}"; VTreeView = tv; tbDelProcReason.Focus(); } diff --git a/PROMS/Volian.Controls.Library/dlgEnhMissingItem.cs b/PROMS/Volian.Controls.Library/dlgEnhMissingItem.cs index 26a5568f..73f331e6 100644 --- a/PROMS/Volian.Controls.Library/dlgEnhMissingItem.cs +++ b/PROMS/Volian.Controls.Library/dlgEnhMissingItem.cs @@ -1,10 +1,4 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; using System.Windows.Forms; using VEPROMS.CSLA.Library; using JR.Utils.GUI.Forms; @@ -13,10 +7,10 @@ namespace Volian.Controls.Library { public partial class dlgEnhMissingItem : Form { - StepTabRibbon STRibbon = null; - private ItemInfo _SourceItem = null; - private int _EnhType = -1; - private bool _Initializing = false; + readonly StepTabRibbon STRibbon = null; + private readonly ItemInfo _SourceItem = null; + private readonly int _EnhType = -1; + private readonly bool _Initializing = false; public bool OKSelected = false; public dlgEnhMissingItem(StepTabRibbon strbn, ItemInfo srcItem, int enhType) { @@ -40,7 +34,7 @@ namespace Volian.Controls.Library cbUnlinkedEnhancedItems.SelectedIndex = -1; cbUnlinkedEnhancedItems.Enabled = false; } - if (srcItem.IsProcedure) this.Text = "Create Missing Enhanced Item for " + srcItem.DisplayNumber; + if (srcItem.IsProcedure) this.Text = $"Create Missing Enhanced Item for {srcItem.DisplayNumber}"; else this.Text = "Create Missing Enhanced Item"; _Initializing = false; } @@ -90,9 +84,8 @@ namespace Volian.Controls.Library // convert the data. If so, convert all items within it that can be linked. If not, just link as before. if (_SourceItem.IsProcedure) { - ItemInfo ii = cbUnlinkedEnhancedItems.SelectedItem as ItemInfo; - if (ii == null) return; - ContentInfoList cil = ContentInfoList.Get16BitEnhancedContents(_SourceItem.ItemID, ii.ItemID, _EnhType); + if (!(cbUnlinkedEnhancedItems.SelectedItem is ItemInfo ii)) return; + ContentInfoList cil = ContentInfoList.Get16BitEnhancedContents(_SourceItem.ItemID, ii.ItemID, _EnhType); bool foundSubItem = false; // in returned list, see if there are any sections/steps. If none, don't prompt foreach (ContentInfo ci in cil) { diff --git a/PROMS/Volian.Controls.Library/frmEPAnnotationDetails.cs b/PROMS/Volian.Controls.Library/frmEPAnnotationDetails.cs index 518e63c7..88d1f16c 100644 --- a/PROMS/Volian.Controls.Library/frmEPAnnotationDetails.cs +++ b/PROMS/Volian.Controls.Library/frmEPAnnotationDetails.cs @@ -1,12 +1,9 @@ using System; using System.Collections.Generic; -using System.ComponentModel; using System.Data; using System.Drawing; -using System.Text; using System.Windows.Forms; using VEPROMS.CSLA.Library; -using Volian.Controls.Library; using System.Linq; namespace Volian.Controls.Library diff --git a/PROMS/Volian.Controls.Library/frmEnhanced.cs b/PROMS/Volian.Controls.Library/frmEnhanced.cs index 0cf70801..8ee800f2 100644 --- a/PROMS/Volian.Controls.Library/frmEnhanced.cs +++ b/PROMS/Volian.Controls.Library/frmEnhanced.cs @@ -1,9 +1,6 @@ using System; using System.Collections.Generic; -using System.ComponentModel; -using System.Data; using System.Drawing; -using System.Text; using System.Windows.Forms; using VEPROMS.CSLA.Library; @@ -16,34 +13,25 @@ namespace Volian.Controls.Library get { return tc.MySessionInfo; } set { tc.MySessionInfo = value; } } - private ItemInfo _MyItemInfo; - public ItemInfo MyItemInfo + public ItemInfo MyItemInfo { get; set; } + public frmEnhanced(ItemInfo ii) { - get { return _MyItemInfo; } - set { _MyItemInfo = value; } - } - public frmEnhanced(ItemInfo ii) - { - _MyItemInfo = ii; + MyItemInfo = ii; InitializeComponent(); SetCaption(); } public void OpenItem() { - tc.OpenItem(_MyItemInfo); + tc.OpenItem(MyItemInfo); } private void frmEnhanced_Load(object sender, EventArgs e) { OpenItem(); } - public DisplayTabControl MyDisplayTabClntrol - { - get { return this.tc; } - } private void SetCaption() { - FolderInfo myfolder = _MyItemInfo.MyDocVersion.MyFolder; + FolderInfo myfolder = MyItemInfo.MyDocVersion.MyFolder; string sep = ""; string fPath = ""; while (myfolder.FolderID != myfolder.ParentID) @@ -57,19 +45,9 @@ namespace Volian.Controls.Library } public class VersionWindow { - private int _VersionID; - public int VersionID - { - get { return _VersionID; } - set { _VersionID = value; } - } - private int _DBId; - public int DBId - { - get { return _DBId; } - set { _DBId = value; } - } - private Rectangle _MyRectangle; + public int VersionID { get; set; } + public int DBId { get; set; } + private Rectangle _MyRectangle; public Rectangle MyRectangle { get { return _MyRectangle; } @@ -78,12 +56,12 @@ namespace Volian.Controls.Library public override string ToString() { RectangleConverter rc = new RectangleConverter(); - return string.Format("{0}~{1}", _VersionID, rc.ConvertToString(_MyRectangle)); + return string.Format("{0}~{1}", VersionID, rc.ConvertToString(_MyRectangle)); } public VersionWindow(string str) { string[] parts = str.Split('~'); - _VersionID = int.Parse(parts[0]); + VersionID = int.Parse(parts[0]); RectangleConverter rc = new RectangleConverter(); _MyRectangle = (Rectangle)rc.ConvertFromString(parts[1]); } diff --git a/PROMS/Volian.Controls.Library/frmImportWordContents.cs b/PROMS/Volian.Controls.Library/frmImportWordContents.cs index 4669154a..ade8d997 100644 --- a/PROMS/Volian.Controls.Library/frmImportWordContents.cs +++ b/PROMS/Volian.Controls.Library/frmImportWordContents.cs @@ -1,7 +1,5 @@ - using System; -using System.Collections.Generic; +using System; using System.ComponentModel; -using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; @@ -109,7 +107,6 @@ namespace Volian.Controls.Library // C2019-021 RHM 5/15/2019 Added new methods and properties for Import Word Content _WordApp.Selection.MoveUp(LBWdUnits.wdParagraph, 1, 0); // Move to previous paragraph _WordApp.Selection.MoveUp(LBWdUnits.wdParagraph, 1, 1); // Select paragraph - //_WordApp.Selection.MoveEnd(LBWdUnits.wdCharacter, -1); // Move 1 Character Back try { // C2019-021 Use generic function CopyWordText @@ -294,34 +291,6 @@ namespace Volian.Controls.Library // incase user manually closed word } } - //C2019-021 Remove old method. - //private void btnNextIns_Click(object sender, EventArgs e) - //{ - // if (MyStepRTB != null) - // { - // if (MyStepRTB.MyItemInfo.IsSection) - // { - // MyStepRTB.RtbSendKeys("^{DOWN}"); // - next edit window - // MyStepRTB.RtbSendKeys("^+b"); // insert previous - // } - // else - // MyStepRTB.RtbSendKeys("^+i"); // insert next (same type and level) - // MyStepRTB.RtbSendKeys("^v"); // clipboard paste - // Application.DoEvents(); - // } - // this.Focus(); // set focus back to this form - //} - //private void btnNextRpl_Click(object sender, EventArgs e) - //{ - // if (MyStepRTB != null) - // { - // MyStepRTB.RtbSendKeys("^{DOWN}"); // - next edit window - // MyStepRTB.RtbSendKeys("^a"); // select all - // MyStepRTB.RtbSendKeys("^v"); // clipboard paste - // Application.DoEvents(); - // } - // this.Focus(); // set focus back to this form - //} // C2019-021 New function to replace the PROMS text with the word text and move to the next paragraph in word. private void btnReplaceNext_Click(object sender, EventArgs e) { @@ -382,7 +351,6 @@ namespace Volian.Controls.Library if (MyStepRTB.Parent is VlnFlexGrid) { VlnFlexGrid vg = MyStepRTB.Parent as VlnFlexGrid; - //vg.FinishEditing(false); vg.SelectNextCell(); } else @@ -498,9 +466,6 @@ namespace Volian.Controls.Library private void btnCurrent_Click(object sender, EventArgs e) { // B2019-108 Corrected curent button code - //_WordApp.Selection.MoveUp(LBWdUnits.wdParagraph, 1, 0); // Select paragraph - //_WordApp.Selection.MoveDown(LBWdUnits.wdParagraph, 1, 1); // Select paragraph - //_WordApp.Selection.MoveEnd(LBWdUnits.wdCharacter, -1); // Exclude the last character try { _WordApp.Selection.Cells[1].Range.Select(); @@ -514,9 +479,6 @@ namespace Volian.Controls.Library // C2019-021 Use Generic CopyWordText CopyWordText(); // C2019-021If the word text only contains whitespace skip to next - //if (txbWrdText.Text.TrimEnd("\f\r\n\a".ToCharArray()) == "") - // btnNext_Click(sender, e); - //else Clipboard.SetText(txbWrdText.Text); } catch @@ -524,16 +486,6 @@ namespace Volian.Controls.Library // Ask RHM what to do here 2/28/2020 JBS } } - //private void btnTest_Click(object sender, EventArgs e) - //{ - // if (!MoveToNextCell()) - // { - // _WordApp.Selection.MoveDown(LBWdUnits.wdParagraph, 2, 0); - // _WordApp.Selection.MoveDown(LBWdUnits.wdParagraph, 1, 1); - // } - // _WordApp.Activate(); - // //int cols = _WordApp.Selection.Tables[1].Columns.Count; - //} // B2019-108 Show special Characters private void txbWrdText_TextChanged(object sender, EventArgs e) @@ -562,9 +514,6 @@ namespace Volian.Controls.Library private void frmImportWordContents_Activated(object sender, EventArgs e) { // B2019-108 Corrected curent button code - //_WordApp.Selection.MoveUp(LBWdUnits.wdParagraph, 1, 0); // Select paragraph - //_WordApp.Selection.MoveDown(LBWdUnits.wdParagraph, 1, 1); // Select paragraph - //_WordApp.Selection.MoveEnd(LBWdUnits.wdCharacter, -1); // Exclude the last character try { if (_WordApp != null || _WordApp.WindowState == LBWdWindowState.wdWindowStateMinimize) @@ -576,16 +525,6 @@ namespace Volian.Controls.Library disableButtons(); } } - //private void btnTest_Click(object sender, EventArgs e) - //{ - // if (!MoveToNextCell()) - // { - // _WordApp.Selection.MoveDown(LBWdUnits.wdParagraph, 2, 0); - // _WordApp.Selection.MoveDown(LBWdUnits.wdParagraph, 1, 1); - // } - // _WordApp.Activate(); - // //int cols = _WordApp.Selection.Tables[1].Columns.Count; - //} private void btnTableConvert_Click(object sender, EventArgs e) { @@ -613,12 +552,11 @@ namespace Volian.Controls.Library else sb.Append(c); } - MessageBox.Show(ex.Message + "\r\n" + sb.ToString(), ex.GetType().Name); + MessageBox.Show($"{ex.Message}\r\n{sb}", ex.GetType().Name); return; } LoadTable2(xd.DocumentElement); int type = 20008; - ItemInfo myTable; if(MyStepRTB.MyItemInfo.IsTable) { using( Item itm = MyStepRTB.MyItemInfo.Get()) @@ -633,12 +571,6 @@ namespace Volian.Controls.Library } else { - //using (Step stp = Step.MakeStep(MyStepRTB.MyItemInfo, null, null, TblFlexGrid.GetSearchableText() , 20008, E_FromType.Table)) - //{ - // myTable = ItemInfo.Get(stp.ItemID); - // Grid.MakeGrid(stp.MyContent, TblFlexGrid.GetXMLData(), ""); - //} - //MyStepRTB.MyItemInfo.MyContent.RefreshContentParts(); EditItem ei = MyStepRTB.Parent as EditItem; ei.AddChild(E_FromType.Table, 20008, TblFlexGrid); if (ei != null) ei.SetAllTabs(); @@ -671,7 +603,6 @@ namespace Volian.Controls.Library // capture widths for valid cells for (int i = 1; i <= tbl.Range.Cells.Count; i++) { - //LBCell myCell = tbl.Range.Cells[i]; // convert points to pixels and save value int w = (int)(tbl.Range.Cells[i].Width * 8 / 6); iC = tbl.Range.Cells[i].ColumnIndex - 1; @@ -774,16 +705,16 @@ namespace Volian.Controls.Library iC = myCell.ColumnIndex - 1 + offset; if (SpanR[iR, iC] > 1) { - sXML += " rowspan=\"" + SpanR[iR, iC] + "\""; + sXML += $" rowspan=\"{SpanR[iR, iC]}\""; } if (SpanC[iR, iC] > 1) { - sXML += " colspan=\"" + SpanC[iR, iC] + "\""; + sXML += $" colspan=\"{SpanC[iR, iC]}\""; offset += SpanC[iR, iC] - 1; } else if (Wcol[iC] > 0) { - sXML += " width=\"" + Wcol[iC] + "\""; + sXML += $" width=\"{Wcol[iC]}\""; Wcol[iC] = Wcol[iC] * -1; } string textalign = ""; @@ -815,7 +746,7 @@ namespace Volian.Controls.Library textalign += "Top"; break; } - sXML += " textalign=\"" + textalign + "\""; + sXML += $" textalign=\"{textalign}\""; sXML += ">"; // select text from current cell _WordApp.Selection.Start = myCell.Range.Start; @@ -830,7 +761,6 @@ namespace Volian.Controls.Library rtbStep.SelectAll(); Console.WriteLine("RTF before {0}", rtbStep.Rtf); Console.WriteLine("RTF after {0}", rtbStep.Rtf); - // rtbStep.Rtf.Replace("\\f1 P\\f0 ", "\\u10004?"); // check mark within parenthesis string strp = rtbStep.Rtf.Replace("\\par\r\n", "!!!"); strp = DisplayText.StaticStripRtfCommands(strp, true); Console.WriteLine("RTF clean {0}", strp); @@ -849,11 +779,9 @@ namespace Volian.Controls.Library sb.Replace("\x201D", "\"");// Space sb.Replace("\x09INITIAL", "");// Space sb.Replace("\x09_____", ""); // Tab Signoff - //sb.Replace("(P)", "(\\u10004?)"); // check mark within parenthesis - //sb.Replace("\\u9633?", "□"); //box } // save resulting text in xml structure - sXML += "

" + ha + sb + "

"; + sXML += $"

{ha}{sb}

"; } else { diff --git a/PROMS/Volian.Controls.Library/frmSendErrorLog.cs b/PROMS/Volian.Controls.Library/frmSendErrorLog.cs index ee687638..e11323f3 100644 --- a/PROMS/Volian.Controls.Library/frmSendErrorLog.cs +++ b/PROMS/Volian.Controls.Library/frmSendErrorLog.cs @@ -1,8 +1,4 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; using System.Text; using System.Windows.Forms; using LBOutlookLibrary; @@ -82,10 +78,8 @@ namespace Volian.Controls.Library MailMessage mm = new MailMessage(); mm.From = new MailAddress(SMTPUser); mm.To.Add("support@volian.com"); - //mm.To.Add("rmark@epix.net"); - //mm.To.Add("jcbodine@gmail.com"); - mm.Subject = "PROMS Error Log " + DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss"); - mm.Body = Header + "\r\n\r\n" + tbContent.Text; + mm.Subject = $"PROMS Error Log {DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss")}"; + mm.Body = $"{Header}\r\n\r\n{tbContent.Text}"; fs = File.Open(_ErrorLogPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); mm.Attachments.Add(new Attachment(fs, "ErrorLog.txt")); SmtpClient sc = new SmtpClient(SMTPServer); @@ -109,7 +103,6 @@ namespace Volian.Controls.Library get { StringBuilder sb = new StringBuilder(); - //sb.Append("PROMS\t\tVersion: "); sb.AppendLine("PROMS"); sb.Append("Version: "); sb.Append(AssemblyVersion); @@ -118,10 +111,9 @@ namespace Volian.Controls.Library string connectionString = Database.VEPROMS_Connection; Match mServer = Regex.Match(connectionString, ".*Data Source=([^;]*).*"); string server = (mServer.Success) ? mServer.Groups[1].Value : "unknown"; - if (server.StartsWith(@".\")) server = @"Local \ " + server.Substring(2); + if (server.StartsWith(@".\")) server = $@"Local \ {server.Substring(2)}"; string databaseName = string.Format("{0}[SQL:{1:yyMM.ddHH}]", Database.ActiveDatabase, Database.RevDate); sb.Append(string.Format("SQL Server: {0}", server)); - //if (databaseName == null) databaseName = Regex.Replace(connectionString, "^.*Initial Catalog=([^;]*);.*$", "$1", RegexOptions.IgnoreCase); sb.AppendLine(string.Format("\t\tDatabase: {0}", databaseName)); if (OutlookEmail) sb.AppendLine("sent via outlook"); @@ -137,13 +129,9 @@ namespace Volian.Controls.Library LBApplicationClass app = new LBApplicationClass(); LBMailItemClass msg = app.CreateMailItem(); msg.Recipients.Add("support@volian.com"); - //msg.Recipients.Add("rmark@epix.net"); - //msg.Recipients.Add("jcbodine@gmail.com"); - //msg.To = "jcbodine@gmail.com";//"rmark@epix.net"; - //msg.Recipients.Add("jcbodine@gmail.com"); - msg.Subject = "PROMS Error Log " + DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss"); + msg.Subject = $"PROMS Error Log {DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss")}"; msg.BodyFormat = LBOlBodyFormat.olFormatPlain; - msg.Body = Header + "\r\n\r\n" + tbContent.Text; + msg.Body = $"{Header}\r\n\r\n{tbContent.Text}"; msg.AddAttachment(_ErrorLogPath); msg.Send(); return true; @@ -162,7 +150,6 @@ namespace Volian.Controls.Library get { return Application.ProductVersion; - //return Assembly.GetExecutingAssembly().GetName().Version.ToString(); } } } diff --git a/PROMS/Volian.Controls.Library/frmViewTextFile.cs b/PROMS/Volian.Controls.Library/frmViewTextFile.cs index 6460a802..d1fe8eb8 100644 --- a/PROMS/Volian.Controls.Library/frmViewTextFile.cs +++ b/PROMS/Volian.Controls.Library/frmViewTextFile.cs @@ -1,9 +1,4 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; using System.Windows.Forms; using System.IO; @@ -13,11 +8,6 @@ namespace Volian.Controls.Library { string _FileName; RichTextBoxStreamType _RTBType; - //public string FileName - //{ - // get { return _FileName; } - // set { _FileName = value; } - //} public string ButtonText { get { return buttonX1.Text; } diff --git a/PROMS/Volian.Controls.Library/vlnExpander.cs b/PROMS/Volian.Controls.Library/vlnExpander.cs index d5beef86..4d5c73de 100644 --- a/PROMS/Volian.Controls.Library/vlnExpander.cs +++ b/PROMS/Volian.Controls.Library/vlnExpander.cs @@ -1,9 +1,5 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; using System.Drawing; -using System.Data; -using System.Text; using System.Windows.Forms; namespace Volian.Controls.Library @@ -137,7 +133,6 @@ namespace Volian.Controls.Library Color c1 = Color.FromArgb(_Trans1, _Color1); Color c2 = Color.FromArgb(_Trans2, _Color2); Brush b = new System.Drawing.Drawing2D.LinearGradientBrush(ClientRectangle, c1, c2, _GradientAngle); - //Brush b2 = new System.Drawing.Drawing2D.LinearGradientBrush(ClientRectangle, c2, c2, _GradientAngle); Pen p = new Pen(ForeColor); Brush b2 = p.Brush; float smallest = this.Width; @@ -152,11 +147,6 @@ namespace Volian.Controls.Library switch (_MyExpanderStyle) { case ExpanderStyle.Round: - //e.Graphics.FillEllipse(Brushes.Gray, 0F, 0F, diameter, diameter); - //e.Graphics.DrawRectangle(p, new Rectangle(0, 0, leg * 2 + penWidth * 3, leg * 2 + penWidth * 3)); - // Draw a white cross-hair - //e.Graphics.FillRectangle(Brushes.White, 2 * weight , radius - weight, diameter - 4 * weight, weight * 2); - //e.Graphics.FillRectangle(Brushes.White, radius - weight, 2 * weight, weight * 2, diameter - 4 * weight); if(!Attachment) e.Graphics.FillEllipse(b, 0F, 0F, diameter, diameter); DrawInterior(e, b, b2, weight, radius, diameter); e.Graphics.DrawEllipse(p, 0, 0, diameter, diameter); @@ -165,21 +155,13 @@ namespace Volian.Controls.Library b2.Dispose(); break; case ExpanderStyle.Square: - //c1 = Color.FromArgb(_Trans1, _Color1); - //c2 = Color.FromArgb(_Trans2, _Color2); - //b = new System.Drawing.Drawing2D.LinearGradientBrush(ClientRectangle, c1, c2, _GradientAngle); int leg = ((ClientRectangle.Width - 3 * penWidth) / 2) - 1; if (!Attachment) e.Graphics.FillRectangle(b, new Rectangle(0, 0, leg * 2 + penWidth * 3, leg * 2 + penWidth * 3)); int center = leg + penWidth; int limit = 2 * (penWidth + leg); p = new Pen(_BorderColor, _PenWidth); e.Graphics.DrawRectangle(p, new Rectangle(0, 0, leg * 2 + penWidth * 3, leg * 2 + penWidth * 3)); - //b = new SolidBrush(this.ForeColor); DrawInterior(e, b, b2, weight, radius, diameter); - //e.Graphics.FillRectangle(b, new Rectangle(penWidth, center, leg * 2 + penWidth, penWidth)); - //if (!_Expanded) e.Graphics.FillRectangle(b, new Rectangle(center, penWidth, penWidth, leg * 2 + penWidth)); - ////pe.Graphics.DrawLine(p, new Point(penWidth, center), new Point(limit, center)); - ////if (!Expanded) pe.Graphics.DrawLine(p, new Point(center, penWidth), new Point(center, limit)); p.Dispose(); b.Dispose(); break; diff --git a/PROMS/Volian.Controls.Library/vlnTreeCombo.cs b/PROMS/Volian.Controls.Library/vlnTreeCombo.cs index 11e2abc9..fb683080 100644 --- a/PROMS/Volian.Controls.Library/vlnTreeCombo.cs +++ b/PROMS/Volian.Controls.Library/vlnTreeCombo.cs @@ -1,4 +1,3 @@ -using System; using System.ComponentModel; using System.Windows.Forms; diff --git a/PROMS/Volian.Controls.Library/vlnTreeView.Designer.cs b/PROMS/Volian.Controls.Library/vlnTreeView.Designer.cs index 98e486b8..1428834d 100644 --- a/PROMS/Volian.Controls.Library/vlnTreeView.Designer.cs +++ b/PROMS/Volian.Controls.Library/vlnTreeView.Designer.cs @@ -11,7 +11,7 @@ namespace Volian.Controls.Library /// Clean up any resources being used. ///
/// true if managed resources should be disposed; otherwise, false. - protected void Dispose(bool disposing) + protected override void Dispose(bool disposing) { if (disposing && (components != null)) { diff --git a/PROMS/Volian.Controls.Library/vlnTreeView.cs b/PROMS/Volian.Controls.Library/vlnTreeView.cs index 97f03838..c2543339 100644 --- a/PROMS/Volian.Controls.Library/vlnTreeView.cs +++ b/PROMS/Volian.Controls.Library/vlnTreeView.cs @@ -1,20 +1,17 @@ using System; using System.Collections.Generic; -using System.ComponentModel; -using System.Data; using System.Drawing; using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms; using System.Runtime.InteropServices; // For DragHelper -using System.Reflection; -using Csla; using Csla.Validation; using VEPROMS.CSLA.Library; using System.IO; using Volian.Base.Library; using DevComponents.DotNetBar; -using JR.Utils.GUI.Forms; //C2018-026 show notes entered during approval or workflow stage +using JR.Utils.GUI.Forms; +using System.Linq; //C2018-026 show notes entered during approval or workflow stage namespace Volian.Controls.Library { @@ -41,53 +38,28 @@ namespace Volian.Controls.Library public delegate ItemInfo vlnTreeViewSearchIncTransEvent(object sender, vlnTreeItemInfoEventArgs args); public partial class vlnTreeSectionInfoEventArgs { - private bool _IsDeleting = false; - public bool IsDeleting + public bool IsDeleting { get; set; } = false; + public SectionInfo MySectionInfo { get; set; } + public vlnTreeSectionInfoEventArgs(SectionInfo mySectionInfo) { - get { return _IsDeleting; } - set { _IsDeleting = value; } - } - private SectionInfo _MySectionInfo; - public SectionInfo MySectionInfo - { - get { return _MySectionInfo; } - set { _MySectionInfo = value; } - } - public vlnTreeSectionInfoEventArgs(SectionInfo mySectionInfo) - { - _MySectionInfo = mySectionInfo; + MySectionInfo = mySectionInfo; } public vlnTreeSectionInfoEventArgs(SectionInfo mySectionInfo, bool isDeleting) { - _MySectionInfo = mySectionInfo; - _IsDeleting = isDeleting; + MySectionInfo = mySectionInfo; + IsDeleting = isDeleting; } } public partial class vlnTreeViewPdfArgs { - private string _MyFilename; - public string MyFilename + public string MyFilename { get; set; } + public byte[] MyBuffer { get; set; } + public string MyWatermark { get; set; } + public vlnTreeViewPdfArgs(string filename, byte[] buffer, string watermark) { - get { return _MyFilename; } - set { _MyFilename = value; } - } - private byte[] _MyBuffer; - public byte[] MyBuffer - { - get { return _MyBuffer; } - set { _MyBuffer = value; } - } - private string _MyWatermark; - public string MyWatermark - { - get { return _MyWatermark; } - set { _MyWatermark = value; } - } - public vlnTreeViewPdfArgs(string filename, byte[] buffer, string watermark) - { - _MyFilename = filename; - _MyBuffer = buffer; - _MyWatermark = watermark; + MyFilename = filename; + MyBuffer = buffer; + MyWatermark = watermark; } } public partial class vlnTreeTimeEventArgs @@ -98,13 +70,9 @@ namespace Volian.Controls.Library get { return _myTimeSpan; } set { _myTimeSpan = value; } } - private string _MyMessage; - public string MyMessage - { - get { return _MyMessage; } - set { _MyMessage = value; } - } - public vlnTreeTimeEventArgs(DateTime dtStart, string message) + + public string MyMessage { get; set; } + public vlnTreeTimeEventArgs(DateTime dtStart, string message) { MyTimeSpan = TimeSpan.FromTicks(DateTime.Now.Ticks - dtStart.Ticks); MyMessage = message; @@ -112,20 +80,10 @@ namespace Volian.Controls.Library } public partial class vlnTreeStatusEventArgs { - private bool _MyStatus; - public bool MyStatus - { - get { return _MyStatus; } - set { _MyStatus = value; } - } - private string _MyMessage; - public string MyMessage - { - get { return _MyMessage; } - set { _MyMessage = value; } - } + public bool MyStatus { get; set; } + public string MyMessage { get; set; } - public vlnTreeStatusEventArgs(bool status, string message) + public vlnTreeStatusEventArgs(bool status, string message) { MyStatus = status; MyMessage = message; @@ -133,117 +91,75 @@ namespace Volian.Controls.Library } public partial class vlnTreeEventArgs { - #region Business Methods - private TreeNode _Node; - public TreeNode Node - { - get { return _Node; } - set { _Node = value; } - } - private TreeNode _Destination = null; - public TreeNode Destination - { - get { return _Destination; } - set { _Destination = value; } - } - private int _Index; - public int Index - { - get { return _Index; } - set { _Index = value; } - } - - //C2025-024 Electronic Procedures - Phase 2 (PROMS XML output) - //AnnotationType that would be doing an export for - private int _AnnotationTypeId = -1; - public int AnnotationTypeId - { - get { return _AnnotationTypeId; } - set { _AnnotationTypeId = value; } - } - //jcb multiunit - private string _Unit; - public string Unit - { - get { return _Unit; } - set { _Unit = value; } - } - private int _UnitIndex = -1; - public int UnitIndex - { - get { return _UnitIndex; } - set { _UnitIndex = value; } - } - //end jcb multiunit - #endregion - #region Factory Methods - private vlnTreeEventArgs() {; } + #region Business Methods + public TreeNode Node { get; set; } + public TreeNode Destination { get; set; } = null; + public int Index { get; set; } + public int AnnotationTypeId { get; set; } = -1; + public string Unit { get; set; } + public int UnitIndex { get; set; } = -1; + //end jcb multiunit + #endregion + #region Factory Methods + private vlnTreeEventArgs() {; } public vlnTreeEventArgs(TreeNode node) { - _Node = node; + Node = node; } public vlnTreeEventArgs(TreeNode node, TreeNode destination, int index) { - _Node = node; - _Destination = destination; - _Index = index; + Node = node; + Destination = destination; + Index = index; } public vlnTreeEventArgs(TreeNode node, TreeNode destination, int index, int annTypeId) { - _Node = node; - _Destination = destination; - _Index = index; - _AnnotationTypeId = annTypeId; + Node = node; + Destination = destination; + Index = index; + AnnotationTypeId = annTypeId; } //jcb multiunit public vlnTreeEventArgs(TreeNode node, TreeNode destination, int index, string unit, int unitIndex) { - _Node = node; - _Destination = destination; - _Index = index; - _Unit = unit; - _UnitIndex = unitIndex; + Node = node; + Destination = destination; + Index = index; + Unit = unit; + UnitIndex = unitIndex; } public vlnTreeEventArgs(TreeNode node, TreeNode destination, int index, string unit, int unitIndex, int annTypeId) { - _Node = node; - _Destination = destination; - _Index = index; - _Unit = unit; - _UnitIndex = unitIndex; - _AnnotationTypeId = annTypeId; - } - //end jcb multiunit - #endregion - public override string ToString() - { - return string.Format("Node={0},Destination={1},Index={2},Unit={3},UnitIndex={4}", NodePath(this.Node), this.Destination, this.Index, this.Unit, this.UnitIndex); + Node = node; + Destination = destination; + Index = index; + Unit = unit; + UnitIndex = unitIndex; + AnnotationTypeId = annTypeId; } + //end jcb multiunit + #endregion + public override string ToString() => string.Format("Node={0},Destination={1},Index={2},Unit={3},UnitIndex={4}", NodePath(this.Node), this.Destination, this.Index, this.Unit, this.UnitIndex); - private string NodePath(TreeNode node) + private string NodePath(TreeNode node) { string retval = ""; if (node.Parent != null) - retval = NodePath(node.Parent) + ":"; + retval = $"{NodePath(node.Parent)}:"; retval += node.Text; return retval; } } public partial class vlnTreeItemInfoEventArgs { - #region Business Methods - private ItemInfo _MyItemInfo; - public ItemInfo MyItemInfo - { - get { return _MyItemInfo; } - set { _MyItemInfo = value; } - } - #endregion - #region Factory Methods - private vlnTreeItemInfoEventArgs() {; } + #region Business Methods + public ItemInfo MyItemInfo { get; set; } + #endregion + #region Factory Methods + private vlnTreeItemInfoEventArgs() {; } public vlnTreeItemInfoEventArgs(ItemInfo myItemInfo) { - _MyItemInfo = myItemInfo; + MyItemInfo = myItemInfo; } #endregion } @@ -259,93 +175,48 @@ namespace Volian.Controls.Library public enum E_InsertType { Before, After, Child }; public partial class vlnTreeItemInfoInsertEventArgs { - #region Business Methods - private ItemInfo _MyItemInfo; - public ItemInfo MyItemInfo - { - get { return _MyItemInfo; } - set { _MyItemInfo = value; } - } - private E_InsertType _InsertType; - public E_InsertType InsertType - { - get { return _InsertType; } - set { _InsertType = value; } - } - private int _Type; - public int Type - { - get { return _Type; } - set { _Type = value; } - } - private E_FromType _FromType; - public E_FromType FromType - { - get { return _FromType; } - set { _FromType = value; } - } - private string _StepText; - public string StepText - { - get { return _StepText; } - set { _StepText = value; } - } - #endregion - #region Factory Methods - private vlnTreeItemInfoInsertEventArgs() {; } + #region Business Methods + public ItemInfo MyItemInfo { get; set; } + public E_InsertType InsertType { get; set; } + public int Type { get; set; } + public E_FromType FromType { get; set; } + public string StepText { get; set; } + #endregion + #region Factory Methods + private vlnTreeItemInfoInsertEventArgs() {; } public vlnTreeItemInfoInsertEventArgs(ItemInfo myItemInfo, E_InsertType insertType, string stepText) { - _MyItemInfo = myItemInfo; - _InsertType = insertType; - _StepText = stepText; + MyItemInfo = myItemInfo; + InsertType = insertType; + StepText = stepText; } public vlnTreeItemInfoInsertEventArgs(ItemInfo myItemInfo, E_InsertType insertType, string stepText, int type, E_FromType fromType) { - _MyItemInfo = myItemInfo; - _InsertType = insertType; - _StepText = stepText; - _Type = type; - _FromType = fromType; + MyItemInfo = myItemInfo; + InsertType = insertType; + StepText = stepText; + Type = type; + FromType = fromType; } #endregion } #region PasteEventArgs public partial class vlnTreeItemInfoPasteEventArgs { - #region Business Methods - private ItemInfo _MyItemInfo; - public ItemInfo MyItemInfo - { - get { return _MyItemInfo; } - set { _MyItemInfo = value; } - } - private int _CopyStartID; - public int CopyStartID - { - get { return _CopyStartID; } - set { _CopyStartID = value; } - } - private ItemInfo.EAddpingPart _PasteType; - public ItemInfo.EAddpingPart PasteType - { - get { return _PasteType; } - set { _PasteType = value; } - } - private int? _Type; - public int? Type - { - get { return _Type; } - set { _Type = value; } - } - #endregion - #region Factory Methods - private vlnTreeItemInfoPasteEventArgs() {; } + #region Business Methods + public ItemInfo MyItemInfo { get; set; } + public int CopyStartID { get; set; } + public ItemInfo.EAddpingPart PasteType { get; set; } + public int? Type { get; set; } + #endregion + #region Factory Methods + private vlnTreeItemInfoPasteEventArgs() {; } public vlnTreeItemInfoPasteEventArgs(ItemInfo myItemInfo, int copyStartId, ItemInfo.EAddpingPart pasteType, int? type) { - _MyItemInfo = myItemInfo; - _CopyStartID = copyStartId; - _PasteType = pasteType; - _Type = type; + MyItemInfo = myItemInfo; + CopyStartID = copyStartId; + PasteType = pasteType; + Type = type; } #endregion @@ -353,61 +224,51 @@ namespace Volian.Controls.Library #endregion public partial class vlnTreePropertyEventArgs : EventArgs { - private string _Title; - public string Title - { - get { return _Title; } - set { _Title = value; } - } - private object _ConfigObject; - public object ConfigObject - { - get { return _ConfigObject; } - set { _ConfigObject = value; } - } - private FolderConfig _FolderConfig; + public string Title { get; set; } + public object ConfigObject { get; set; } + private FolderConfig _FolderConfig; public FolderConfig FolderConfig { get { return _FolderConfig; } - set { _ConfigObject = _FolderConfig = value; } + set { ConfigObject = _FolderConfig = value; } } private DocVersionConfig _DocVersionConfig; public DocVersionConfig DocVersionConfig { get { return _DocVersionConfig; } - set { _ConfigObject = _DocVersionConfig = value; } + set { ConfigObject = _DocVersionConfig = value; } } private ProcedureConfig _ProcedureConfig; public ProcedureConfig ProcedureConfig { get { return _ProcedureConfig; } - set { _ConfigObject = _ProcedureConfig = value; } + set { ConfigObject = _ProcedureConfig = value; } } private SectionConfig _SectionConfig; public SectionConfig SectionConfig { get { return _SectionConfig; } - set { _ConfigObject = _SectionConfig = value; } + set { ConfigObject = _SectionConfig = value; } } private vlnTreePropertyEventArgs() {; } public vlnTreePropertyEventArgs(string title, FolderConfig folderConfig) { - _Title = title; + Title = title; FolderConfig = folderConfig; } public vlnTreePropertyEventArgs(string title, DocVersionConfig docVersionConfig) { - _Title = title; + Title = title; DocVersionConfig = docVersionConfig; } public vlnTreePropertyEventArgs(string title, ProcedureConfig procedureConfig) { - _Title = title; + Title = title; ProcedureConfig = procedureConfig; } public vlnTreePropertyEventArgs(string title, SectionConfig sectionConfig) { - _Title = title; + Title = title; DocStyleListConverter.MySection = sectionConfig.MySection; SectionConfig = sectionConfig; } @@ -416,26 +277,12 @@ namespace Volian.Controls.Library public partial class vlnTreeView : TreeView { private ProcedureInfo _currentPri = null; // used to get child name to append to approved export filename -AddApprovedRevisionsMultiUnit() & ImportProcedure_Click() - private SessionInfo _MySessionInfo; - public SessionInfo MySessionInfo - { - get { return _MySessionInfo; } - set { _MySessionInfo = value; } - } - private UserInfo _MyUserInfo; - public UserInfo MyUserInfo - { - get { return _MyUserInfo; } - set { _MyUserInfo = value; } - } - private string _DelProcReason; // C2020-038: request reason for delete procedure so this can be saved in database - public string DelProcReason - { - get { return _DelProcReason; } - set { _DelProcReason = value; } - } - #region Local Vars - private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); + + public SessionInfo MySessionInfo { get; set; } + public UserInfo MyUserInfo { get; set; } + public string DelProcReason { get; set; } + #region Local Vars + private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); FolderInfo _LastFolderInfo = null; ProcedureInfo _LastProcedureInfo = null; @@ -447,46 +294,20 @@ namespace Volian.Controls.Library #endregion #region Events public event vlnTreeViewGetChangeIdEvent GetChangeId; - private string OnGetChangeId(object sender, vlnTreeItemInfoEventArgs args) - { - if (GetChangeId != null) return GetChangeId(sender, args); - return null; - } - public event vlnTreeViewPdfEvent ViewPDF; - private void OnViewPDF(object sender, vlnTreeViewPdfArgs args) - { - if (ViewPDF != null) ViewPDF(sender, args); - } - public event vlnTreeViewItemInfoDeleteEvent DeleteItemInfo; - private bool OnDeleteItemInfo(object sender, vlnTreeItemInfoEventArgs args) - { - if (DeleteItemInfo != null) return DeleteItemInfo(sender, args); - return false; - } - public event vlnTreeViewItemInfoDeleteFolderEvent DeleteFolder; - private bool OnDeleteFolder(object sender, vlnTreeFolderDeleteEventArgs args) - { - if (DeleteItemInfo != null) return DeleteFolder(sender, args); - return false; - } - public event vlnTreeViewItemInfoInsertEvent InsertItemInfo; - private bool OnInsertItemInfo(object sender, vlnTreeItemInfoInsertEventArgs args) - { - if (InsertItemInfo != null) return InsertItemInfo(sender, args); - return false; - } - public event vlnTreeViewItemInfoPasteEvent PasteItemInfo; - private bool OnPasteItemInfo(object sender, vlnTreeItemInfoPasteEventArgs args) - { - if (PasteItemInfo != null) return PasteItemInfo(sender, args); - return false; - } - public event vlnTreeViewEvent NodeMove; - private void OnNodeMove(object sender, vlnTreeEventArgs args) - { - if (NodeMove != null) NodeMove(sender, args); - } - public event vlnTreeViewClipboardStatusEvent ClipboardStatus; + private string OnGetChangeId(object sender, vlnTreeItemInfoEventArgs args) => GetChangeId != null ? GetChangeId(sender, args) : null; + public event vlnTreeViewPdfEvent ViewPDF; + private void OnViewPDF(object sender, vlnTreeViewPdfArgs args) => ViewPDF?.Invoke(sender, args); + public event vlnTreeViewItemInfoDeleteEvent DeleteItemInfo; + private bool OnDeleteItemInfo(object sender, vlnTreeItemInfoEventArgs args) => DeleteItemInfo != null && DeleteItemInfo(sender, args); + public event vlnTreeViewItemInfoDeleteFolderEvent DeleteFolder; + private bool OnDeleteFolder(object sender, vlnTreeFolderDeleteEventArgs args) => DeleteItemInfo != null && DeleteFolder(sender, args); + public event vlnTreeViewItemInfoInsertEvent InsertItemInfo; + private bool OnInsertItemInfo(object sender, vlnTreeItemInfoInsertEventArgs args) => InsertItemInfo != null && InsertItemInfo(sender, args); + public event vlnTreeViewItemInfoPasteEvent PasteItemInfo; + private bool OnPasteItemInfo(object sender, vlnTreeItemInfoPasteEventArgs args) => PasteItemInfo != null && PasteItemInfo(sender, args); + public event vlnTreeViewEvent NodeMove; + private void OnNodeMove(object sender, vlnTreeEventArgs args) => NodeMove?.Invoke(sender, args); + public event vlnTreeViewClipboardStatusEvent ClipboardStatus; private ItemInfo OnClipboardStatus(object sender, vlnTreeEventArgs args) { ItemInfo rv = null; @@ -494,179 +315,79 @@ namespace Volian.Controls.Library return rv; } public event vlnTreeViewEvent NodeCopy; - private void OnNodeCopy(object sender, vlnTreeEventArgs args) - { - if (NodeCopy != null) NodeCopy(sender, args); - } - public event vlnTreeViewPropertyEvent NodeOpenProperty; - private DialogResult OnNodeOpenProperty(object sender, vlnTreePropertyEventArgs args) - { - if (NodeOpenProperty != null) return NodeOpenProperty(sender, args); - return DialogResult.Cancel; - } - public event vlnTreeViewPSIEvent NodePSI; - private DialogResult OnNodePSI(object sender, vlnTreeEventArgs args) - { - if (NodePSI != null) return NodePSI(sender, args); - return DialogResult.Cancel; - } - // C2020-033: Support the menu item to bring up Search/Incoming Transitions panel - public event vlnTreeViewSearchIncTransEvent SearchIncTrans; - private ItemInfo OnSearchIncTransIn(object sender, vlnTreeItemInfoEventArgs args) - { - if (SearchIncTrans != null) return SearchIncTrans(sender, args); - return args.MyItemInfo; - } - public event vlnTreeViewSIEvent NodeSI; - private DialogResult OnNodeSI(object sender, vlnTreeEventArgs args) - { - if (NodeSI != null) return NodeSI(sender, args); - return DialogResult.Cancel; - } - public event vlnTreeViewEvent NodeSelect; - private void OnNodeSelect(object sender, vlnTreeEventArgs args) - { - if (NodeSelect != null) NodeSelect(sender, args); - } - public event vlnTreeViewEvent CreateContinuousActionSummary; - private void OnCreateContinuousActionSummary(object sender, vlnTreeEventArgs args) - { - if (CreateContinuousActionSummary != null) CreateContinuousActionSummary(sender, args); - } - public event vlnTreeViewEvent CreateTimeCriticalActionSummary; - private void OnCreateTimeCriticalActionSummary(object sender, vlnTreeEventArgs args) - { - if (CreateTimeCriticalActionSummary != null) CreateTimeCriticalActionSummary(sender, args); - } - public event vlnTreeViewEvent PrintProcedure; - private void OnPrintProcedure(object sender, vlnTreeEventArgs args) - { - if (PrintProcedure != null) PrintProcedure(sender, args); - } - public event vlnTreeViewEvent QPrintProcedure; - private void OnQPrintProcedure(object sender, vlnTreeEventArgs args) - { - if (QPrintProcedure != null) QPrintProcedure(sender, args); - } - public event vlnTreeViewEvent PrintSection; - private void OnPrintSection(object sender, vlnTreeEventArgs args) - { - if (PrintSection != null) PrintSection(sender, args); - } - public event vlnTreeViewEvent QPrintSection; - private void OnQPrintSection(object sender, vlnTreeEventArgs args) - { - if (QPrintSection != null) QPrintSection(sender, args); - } - public event vlnTreeViewEvent PrintAllProcedures; - private void OnPrintAllProcedures(object sender, vlnTreeEventArgs args) - { - if (PrintAllProcedures != null) PrintAllProcedures(sender, args); - } - public event vlnTreeViewEvent PrintAllApprovedProcedures; //C2025-017 print all approved procedures - private void OnPrintAllApprovedProcedures(object sender, vlnTreeEventArgs args) - { - if (PrintAllApprovedProcedures != null) PrintAllApprovedProcedures(sender, args); - } - public event vlnTreeViewEvent SelectDateToStartChangeBars; - private void OnSelectDateToStartChangeBars(object sender, vlnTreeEventArgs args) - { - if (SelectDateToStartChangeBars != null) SelectDateToStartChangeBars(sender, args); - } - public event vlnTreeViewEvent ApproveProcedure; - private void OnApproveProcedure(object sender, vlnTreeEventArgs args) - { - if (ApproveProcedure != null) ApproveProcedure(sender, args); - } - public event vlnTreeViewEvent ApproveAllProcedures; - private void OnApproveAllProcedures(object sender, vlnTreeEventArgs args) - { - if (ApproveAllProcedures != null) ApproveAllProcedures(sender, args); - } - public event vlnTreeViewEvent ApproveSomeProcedures; - private void OnApproveSomeProcedures(object sender, vlnTreeEventArgs args) - { - if (ApproveSomeProcedures != null) ApproveSomeProcedures(sender, args); - } - public event vlnTreeViewEvent ReportAllProceduresInconsistencies; - private void OnReportAllProceduresInconsistencies(object sender, vlnTreeEventArgs args) - { - if (ReportAllProceduresInconsistencies != null) ReportAllProceduresInconsistencies(sender, args); - } - public event vlnTreeViewEvent RefreshCheckedOutProcedures; - private void OnRefreshCheckedOutProcedures(object sender, vlnTreeEventArgs args) - { - if (RefreshCheckedOutProcedures != null) RefreshCheckedOutProcedures(sender, args); - } - public event vlnTreeViewEvent ProcedureCheckedOutTo; - private void OnProcedureCheckedOutTo(object sender, vlnTreeEventArgs args) - { - if (ProcedureCheckedOutTo != null) ProcedureCheckedOutTo(sender, args); - } - public event vlnTreeViewEvent ExportImportProcedureSets; - private void OnExportImportProcedureSets(object sender, vlnTreeEventArgs args) - { - if (ExportImportProcedureSets != null) ExportImportProcedureSets(sender, args); - } - public event vlnTreeViewEvent PrintTransitionReport; - private void OnPrintTransitionReport(object sender, vlnTreeEventArgs args) - { - if (PrintTransitionReport != null) PrintTransitionReport(sender, args); - } - public event vlnTreeViewEvent NodeNew; - private void OnNodeNew(object sender, vlnTreeEventArgs args) - { - if (NodeNew != null) NodeNew(sender, args); - } - /// - /// Raised after a new step is added. - /// - public event vlnTreeViewEvent NodeInsert; - private void OnNodeInsert(object sender, vlnTreeEventArgs args) - { - if (NodeInsert != null) NodeInsert(sender, args); - } - public event vlnTreeViewEvent NodeSelectionChange; - private void OnNodeSelectionChange(object sender, vlnTreeEventArgs args) - { - if (NodeSelectionChange != null) NodeSelectionChange(sender, args); - } - public event vlnTreeViewSectionInfoEvent SectionShouldClose; - private void OnSectionShouldClose(object sender, vlnTreeSectionInfoEventArgs args) - { - if (SectionShouldClose != null) SectionShouldClose(sender, args); - } - public event vlnTreeViewSectionInfoEvent PauseRefresh; - private void OnPauseRefresh(object sender, vlnTreeSectionInfoEventArgs args) - { - if (PauseRefresh != null) PauseRefresh(sender, args); - } - public event vlnTreeViewSectionInfoEvent UnPauseRefresh; - private void OnUnPauseRefresh(object sender, vlnTreeSectionInfoEventArgs args) - { - if (UnPauseRefresh != null) UnPauseRefresh(sender, args); - } - public event WordSectionDeletedEvent WordSectionDeleted; - internal void OnWordSectionDeleted(object sender, WordSectionEventArgs args) - { - WordSectionDeleted(sender, args); - } - public event vlnTreeViewItemInfoEvent OpenItem; - private void OnOpenItem(object sender, vlnTreeItemInfoEventArgs args) - { - if (OpenItem != null) OpenItem(sender, args); - } - // This event was added to update the Step Properties/RO & Tools/Search RO & Reports - // when an update of ro.fst is done & the ro trees on those panels needs refreshed. - // (bug fix B2015-226) - public event StepPanelTabDisplayEvent TabDisplay; - private void OnTabDisplay(object sender, StepPanelTabDisplayEventArgs args) - { - if (TabDisplay != null) TabDisplay(sender, args); - } - #endregion - #region Constructors - public vlnTreeView() + private void OnNodeCopy(object sender, vlnTreeEventArgs args) => NodeCopy?.Invoke(sender, args); + public event vlnTreeViewPropertyEvent NodeOpenProperty; + private DialogResult OnNodeOpenProperty(object sender, vlnTreePropertyEventArgs args) => NodeOpenProperty != null ? NodeOpenProperty(sender, args) : DialogResult.Cancel; + public event vlnTreeViewPSIEvent NodePSI; + private DialogResult OnNodePSI(object sender, vlnTreeEventArgs args) => NodePSI != null ? NodePSI(sender, args) : DialogResult.Cancel; + // C2020-033: Support the menu item to bring up Search/Incoming Transitions panel + public event vlnTreeViewSearchIncTransEvent SearchIncTrans; + private ItemInfo OnSearchIncTransIn(object sender, vlnTreeItemInfoEventArgs args) => SearchIncTrans != null ? SearchIncTrans(sender, args) : args.MyItemInfo; + public event vlnTreeViewSIEvent NodeSI; + private DialogResult OnNodeSI(object sender, vlnTreeEventArgs args) => NodeSI != null ? NodeSI(sender, args) : DialogResult.Cancel; + public event vlnTreeViewEvent NodeSelect; + private void OnNodeSelect(object sender, vlnTreeEventArgs args) => NodeSelect?.Invoke(sender, args); + public event vlnTreeViewEvent CreateContinuousActionSummary; + private void OnCreateContinuousActionSummary(object sender, vlnTreeEventArgs args) => CreateContinuousActionSummary?.Invoke(sender, args); + public event vlnTreeViewEvent CreateTimeCriticalActionSummary; + private void OnCreateTimeCriticalActionSummary(object sender, vlnTreeEventArgs args) => CreateTimeCriticalActionSummary?.Invoke(sender, args); + public event vlnTreeViewEvent PrintProcedure; + private void OnPrintProcedure(object sender, vlnTreeEventArgs args) => PrintProcedure?.Invoke(sender, args); + public event vlnTreeViewEvent QPrintProcedure; + private void OnQPrintProcedure(object sender, vlnTreeEventArgs args) => QPrintProcedure?.Invoke(sender, args); + public event vlnTreeViewEvent PrintSection; + private void OnPrintSection(object sender, vlnTreeEventArgs args) => PrintSection?.Invoke(sender, args); + public event vlnTreeViewEvent QPrintSection; + private void OnQPrintSection(object sender, vlnTreeEventArgs args) => QPrintSection?.Invoke(sender, args); + public event vlnTreeViewEvent PrintAllProcedures; + private void OnPrintAllProcedures(object sender, vlnTreeEventArgs args) => PrintAllProcedures?.Invoke(sender, args); + public event vlnTreeViewEvent PrintAllApprovedProcedures; //C2025-017 print all approved procedures + private void OnPrintAllApprovedProcedures(object sender, vlnTreeEventArgs args) => PrintAllApprovedProcedures?.Invoke(sender, args); + public event vlnTreeViewEvent SelectDateToStartChangeBars; + private void OnSelectDateToStartChangeBars(object sender, vlnTreeEventArgs args) => SelectDateToStartChangeBars?.Invoke(sender, args); + public event vlnTreeViewEvent ApproveProcedure; + private void OnApproveProcedure(object sender, vlnTreeEventArgs args) => ApproveProcedure?.Invoke(sender, args); + public event vlnTreeViewEvent ApproveAllProcedures; + private void OnApproveAllProcedures(object sender, vlnTreeEventArgs args) => ApproveAllProcedures?.Invoke(sender, args); + public event vlnTreeViewEvent ApproveSomeProcedures; + private void OnApproveSomeProcedures(object sender, vlnTreeEventArgs args) => ApproveSomeProcedures?.Invoke(sender, args); + public event vlnTreeViewEvent ReportAllProceduresInconsistencies; + private void OnReportAllProceduresInconsistencies(object sender, vlnTreeEventArgs args) => ReportAllProceduresInconsistencies?.Invoke(sender, args); + public event vlnTreeViewEvent RefreshCheckedOutProcedures; + private void OnRefreshCheckedOutProcedures(object sender, vlnTreeEventArgs args) => RefreshCheckedOutProcedures?.Invoke(sender, args); + public event vlnTreeViewEvent ProcedureCheckedOutTo; + private void OnProcedureCheckedOutTo(object sender, vlnTreeEventArgs args) => ProcedureCheckedOutTo?.Invoke(sender, args); + public event vlnTreeViewEvent ExportImportProcedureSets; + private void OnExportImportProcedureSets(object sender, vlnTreeEventArgs args) => ExportImportProcedureSets?.Invoke(sender, args); + public event vlnTreeViewEvent PrintTransitionReport; + private void OnPrintTransitionReport(object sender, vlnTreeEventArgs args) => PrintTransitionReport?.Invoke(sender, args); + public event vlnTreeViewEvent NodeNew; + private void OnNodeNew(object sender, vlnTreeEventArgs args) => NodeNew?.Invoke(sender, args); + /// + /// Raised after a new step is added. + /// + public event vlnTreeViewEvent NodeInsert; + private void OnNodeInsert(object sender, vlnTreeEventArgs args) => NodeInsert?.Invoke(sender, args); + public event vlnTreeViewEvent NodeSelectionChange; + private void OnNodeSelectionChange(object sender, vlnTreeEventArgs args) => NodeSelectionChange?.Invoke(sender, args); + public event vlnTreeViewSectionInfoEvent SectionShouldClose; + private void OnSectionShouldClose(object sender, vlnTreeSectionInfoEventArgs args) => SectionShouldClose?.Invoke(sender, args); + public event vlnTreeViewSectionInfoEvent PauseRefresh; + private void OnPauseRefresh(object sender, vlnTreeSectionInfoEventArgs args) => PauseRefresh?.Invoke(sender, args); + public event vlnTreeViewSectionInfoEvent UnPauseRefresh; + private void OnUnPauseRefresh(object sender, vlnTreeSectionInfoEventArgs args) => UnPauseRefresh?.Invoke(sender, args); + public event WordSectionDeletedEvent WordSectionDeleted; + internal void OnWordSectionDeleted(object sender, WordSectionEventArgs args) => WordSectionDeleted(sender, args); + public event vlnTreeViewItemInfoEvent OpenItem; + private void OnOpenItem(object sender, vlnTreeItemInfoEventArgs args) => OpenItem?.Invoke(sender, args); + // This event was added to update the Step Properties/RO & Tools/Search RO & Reports + // when an update of ro.fst is done & the ro trees on those panels needs refreshed. + // (bug fix B2015-226) + public event StepPanelTabDisplayEvent TabDisplay; + private void OnTabDisplay(object sender, StepPanelTabDisplayEventArgs args) => TabDisplay?.Invoke(sender, args); + #endregion + #region Constructors + public vlnTreeView() { InitializeComponent(); this.AllowDrop = true; @@ -706,655 +427,606 @@ namespace Volian.Controls.Library bool isSectNode = false; bool isFolderNode = false; bool isWrkDftNode = false; - VETreeNode tn = this.GetNodeAt(new Point(e.X, e.Y)) as VETreeNode; - if (tn != null) - { - this.SelectedNode = tn as TreeNode; - Application.DoEvents(); - // Display Menu - ToolStripMenuItem mi = new ToolStripMenuItem(); - ContextMenu cm = new ContextMenu(); - //_MyLog.WarnFormat("Context Menu 1 - {0}",GC.GetTotalMemory(true)); - UserInfo ui = UserInfo.GetByUserID(VlnSettings.UserID); - //_MyLog.WarnFormat("Context Menu 1a - {0}", GC.GetTotalMemory(true)); + if (this.GetNodeAt(new Point(e.X, e.Y)) is VETreeNode tn) + { + this.SelectedNode = tn as TreeNode; + Application.DoEvents(); + // Display Menu + ToolStripMenuItem mi = new ToolStripMenuItem(); + ContextMenu cm = new ContextMenu(); + //_MyLog.WarnFormat("Context Menu 1 - {0}",GC.GetTotalMemory(true)); + UserInfo ui = UserInfo.GetByUserID(VlnSettings.UserID); + //_MyLog.WarnFormat("Context Menu 1a - {0}", GC.GetTotalMemory(true)); - if (ui == null) - { - FlexibleMessageBox.Show("Security has not been defined for PROMS. All functionality has been defaulted to the lowest level for all users until security is defined.", "no security defined", MessageBoxButtons.OK, MessageBoxIcon.Warning); - return; - } - this.Cursor = Cursors.WaitCursor; - #region Menu_New - if (tn.VEObject as FolderInfo != null) - { - isFolderNode = true; - // For Folders, if no children, can add either docversion or folder. If children are - // folders then can only add another folder, and if children are docversions can only - // add docversion. - fi = tn.VEObject as FolderInfo; - bool DoSpecificInfo = fi.ActiveFormat.PlantFormat.FormatData.SpecificInfo; - if (ui.IsAdministrator() || ui.IsSetAdministrator(fi))// && fi.MyParent == null) //VEPROMS level - { - if (fi.HasWorkingDraft) - { - cm.MenuItems.Add("Export Procedure Set", new EventHandler(mi_Click)); - //AddEPExport(cm.MenuItems, 0, null); - } - else - cm.MenuItems.Add("Import Procedure Set", new EventHandler(mi_Click)); - if (DoSpecificInfo) - cm.MenuItems.Add("Folder Specific Information", new EventHandler(mi_Click)); // C2020-008: change to 'Folder' - } - //_MyLog.WarnFormat("Context Menu 1b - {0}", GC.GetTotalMemory(true)); - if (ui.IsAdministrator() || ui.IsSetAdministrator(fi)) - { - if (fi.MyParent != null) // don't allow insert before/after if at top node - { - if (!ui.IsAdministrator() && DoSpecificInfo) cm.MenuItems.Add("Procedure Set Specific Information", new EventHandler(mi_Click)); - // B2020-111 only allow Set Administrator to add new folders inside folders they admininstrate - if (ui.IsAdministrator() || ui.IsSetAdministrator(fi.MyParent)) - { - cm.MenuItems.Add("Insert Folder Before", new EventHandler(mi_Click)); - cm.MenuItems.Add("Insert Folder After", new EventHandler(mi_Click)); - } - } - // B2020-111 only allow Set Administrator to add new folders inside folders they admininstrate - if ((ui.IsAdministrator() || ui.IsSetAdministrator(fi.MyParent)) && fi.FolderDocVersionCount == 0) - cm.MenuItems.Add("New Folder", new EventHandler(mi_Click)); - if (fi.ChildFolderCount == 0 && !fi.HasWorkingDraft) - cm.MenuItems.Add("Create Working Draft", new EventHandler(mi_Click)); - } - if (fi.HasWorkingDraft) - cm.MenuItems.Add("Print Transition Report", new EventHandler(mi_Click)); - } - else if (tn.VEObject as DocVersionInfo != null) // DocVersions can only contain procs - { - isWrkDftNode = true; - //_MyLog.WarnFormat("Context Menu 1c - {0}", GC.GetTotalMemory(true)); - DocVersionInfo dvi = tn.VEObject as DocVersionInfo; - if (ui.IsAdministrator() || ui.IsSetAdministrator(dvi)) - { - cm.MenuItems.Add("Import Procedure", mi_Click); - } - if (ui.IsAdministrator() || ui.IsSetAdministrator(dvi) || ui.IsWriter(dvi)) - { - OwnerInfoList.Reset(); - oil = OwnerInfoList.GetByVersionID(dvi.VersionID); - if (dvi.ActiveFormat.PlantFormat.FormatData.SpecificInfo) - cm.MenuItems.Add("Procedure Set Specific Information", new EventHandler(mi_Click)); - cm.MenuItems.Add("Refresh Checked Out Procedures", new EventHandler(mi_Click)); - cm.MenuItems.Add("New Procedure", new EventHandler(mi_Click)); - if (dvi.MultiUnitCount > 1) - { - MenuItem mip = new MenuItem("Print All Procedures for"); - MenuItem mia = new MenuItem("Approve All Procedures for"); - MenuItem mis = new MenuItem("Approve Some Procedures for"); - MenuItem mir = new MenuItem("Print All Approved Procedures for"); // C2025-017 print all approved procedures - int k = 0; - foreach (string s in dvi.UnitNames) - { - k++; - MenuItem mp = mip.MenuItems.Add(s, new EventHandler(miMultiUnit_Click)); - mp.Tag = k; - MenuItem ma = mia.MenuItems.Add(s, new EventHandler(miMultiUnit_Click)); - ma.Tag = k; - MenuItem ms = mis.MenuItems.Add(s, new EventHandler(miMultiUnit_Click)); - ms.Tag = k; - MenuItem mr = mir.MenuItems.Add(s, new EventHandler(miMultiUnit_Click)); // C2025-017 print all approved procedures - mr.Tag = k; - } - //MenuItem mmp = mip.MenuItems.Add("All Units", new EventHandler(miMultiUnit_Click)); - //mmp.Tag = 0; - //MenuItem mma = mia.MenuItems.Add("All Units", new EventHandler(miMultiUnit_Click)); - //mma.Tag = 0; - //MenuItem mms = mis.MenuItems.Add("All Units", new EventHandler(miMultiUnit_Click)); - //mms.Tag = 0; - cm.MenuItems.Add(mip); - cm.MenuItems.Add(mia); - cm.MenuItems.Add(mis); - cm.MenuItems.Add(mir); // C2025-017 print all approved procedures - } - else - { - //_MyLog.WarnFormat("Context Menu 1d - {0}", GC.GetTotalMemory(true)); - cm.MenuItems.Add("Print All Procedures", new EventHandler(mi_Click)); - cm.MenuItems.Add("Approve All Procedures", new EventHandler(mi_Click)); - cm.MenuItems.Add("Approve Some Procedures", new EventHandler(mi_Click)); - cm.MenuItems.Add("Print All Approved Procedures", new EventHandler(mi_Click)); - } - cm.MenuItems.Add("Report All Procedures Inconsistencies", new EventHandler(mi_Click)); - } - else - { - //_MyLog.WarnFormat("Context Menu 1e - {0}", GC.GetTotalMemory(true)); - OwnerInfoList.Reset(); - oil = OwnerInfoList.GetByVersionID(dvi.VersionID); - cm.MenuItems.Add("Refresh Checked Out Procedures", new EventHandler(mi_Click)); - if (dvi.MultiUnitCount > 1) - { - MenuItem mip = new MenuItem("Print All Procedures for"); - int k = 0; - foreach (string s in dvi.UnitNames) - { - k++; - MenuItem mp = mip.MenuItems.Add(s, new EventHandler(miMultiUnit_Click)); - mp.Tag = k; - } - //MenuItem mmp = mip.MenuItems.Add("All Units", new EventHandler(miMultiUnit_Click)); - //mmp.Tag = 0; - //MenuItem mma = mia.MenuItems.Add("All Units", new EventHandler(miMultiUnit_Click)); - //mma.Tag = 0; - //MenuItem mms = mis.MenuItems.Add("All Units", new EventHandler(miMultiUnit_Click)); - //mms.Tag = 0; - cm.MenuItems.Add(mip); - } - else - { - //_MyLog.WarnFormat("Context Menu 1f - {0}", GC.GetTotalMemory(true)); - cm.MenuItems.Add("Print All Procedures", new EventHandler(mi_Click)); - } - } - //if (ui.IsAdministrator() || ui.IsSetAdministrator(dvi)) - //{ - // cm.MenuItems.Add("Check Out Procedure Set", new EventHandler(mi_Click)); - // cm.MenuItems.Add("Check In Procedure Set", new EventHandler(mi_Click)); - //} - if (ui.IsAdministrator() || ui.IsSetAdministrator(dvi) || ui.IsROEditor(dvi)) - { - //_MyLog.WarnFormat("Context Menu 1g - {0}", GC.GetTotalMemory(true)); - cm.MenuItems.Add("Run RO Editor", new EventHandler(mi_Click)); - } - if (ui.IsAdministrator() || ui.IsSetAdministrator(dvi)) - { - //_MyLog.WarnFormat("Context Menu 1h - {0}", GC.GetTotalMemory(true)); - MenuItem urv = cm.MenuItems.Add("Update RO Values", new EventHandler(mi_Click)); - // only allow update if association, and the RO update was not done and/or not completed - urv.Enabled = !dvi.ROfstLastCompleted || dvi.NewerRoFst; - } - } - else if (tn.VEObject as ProcedureInfo != null) // Procs can only contain sections - { - isProcNode = true; - ProcedureInfo pri = tn.VEObject as ProcedureInfo; - oi = OwnerInfo.GetByItemID(pri.ItemID, CheckOutType.Procedure); - if (ui.IsAdministrator() || ui.IsSetAdministrator(pri.MyDocVersion)) - { - cm.MenuItems.Add("Export Procedure", mi_Click); - //C2025-024 Proms XML Output - if have any EP Format files, add dropdown menu for exporting EP formats - if (pri.ActiveFormat.PlantFormat.EPFormatFiles.Count > 0) - AddEPExport(cm.MenuItems, pri.MyDocVersion.MultiUnitCount, pri.MyDocVersion.UnitNames, pri.ActiveFormat.PlantFormat.EPFormatFiles); - } - if (ui.IsAdministrator() || ui.IsSetAdministrator(pri.MyDocVersion) || ui.IsWriter(pri.MyDocVersion)) - { - if (oi != null && oi.SessionID != MySessionInfo.SessionID) - cm.MenuItems.Add(string.Format("Procedure Checked Out to {0}", oi.SessionUserID), new EventHandler(mi_Click)); - if (pri.ActiveFormat.PlantFormat.FormatData.ProcData.PSI.Caption != null) cm.MenuItems.Add("Procedure Specific Information", new EventHandler(mi_Click)); - cm.MenuItems.Add("Insert Procedure Before", new EventHandler(mi_Click)); - cm.MenuItems.Add("Insert Procedure After", new EventHandler(mi_Click)); + if (ui == null) + { + FlexibleMessageBox.Show("Security has not been defined for PROMS. All functionality has been defaulted to the lowest level for all users until security is defined.", "no security defined", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return; + } + this.Cursor = Cursors.WaitCursor; + #region Menu_New + if (tn.VEObject as FolderInfo != null) + { + isFolderNode = true; + // For Folders, if no children, can add either docversion or folder. If children are + // folders then can only add another folder, and if children are docversions can only + // add docversion. + fi = tn.VEObject as FolderInfo; + bool DoSpecificInfo = fi.ActiveFormat.PlantFormat.FormatData.SpecificInfo; + if (ui.IsAdministrator() || ui.IsSetAdministrator(fi))// + { + if (fi.HasWorkingDraft) + { + cm.MenuItems.Add("Export Procedure Set", new EventHandler(mi_Click)); + } + else + cm.MenuItems.Add("Import Procedure Set", new EventHandler(mi_Click)); + if (DoSpecificInfo) + cm.MenuItems.Add("Folder Specific Information", new EventHandler(mi_Click)); // C2020-008: change to 'Folder' + } + //_MyLog.WarnFormat("Context Menu 1b - {0}", GC.GetTotalMemory(true)); + if (ui.IsAdministrator() || ui.IsSetAdministrator(fi)) + { + if (fi.MyParent != null) // don't allow insert before/after if at top node + { + if (!ui.IsAdministrator() && DoSpecificInfo) cm.MenuItems.Add("Procedure Set Specific Information", new EventHandler(mi_Click)); + // B2020-111 only allow Set Administrator to add new folders inside folders they admininstrate + if (ui.IsAdministrator() || ui.IsSetAdministrator(fi.MyParent)) + { + cm.MenuItems.Add("Insert Folder Before", new EventHandler(mi_Click)); + cm.MenuItems.Add("Insert Folder After", new EventHandler(mi_Click)); + } + } + // B2020-111 only allow Set Administrator to add new folders inside folders they admininstrate + if ((ui.IsAdministrator() || ui.IsSetAdministrator(fi.MyParent)) && fi.FolderDocVersionCount == 0) + cm.MenuItems.Add("New Folder", new EventHandler(mi_Click)); + if (fi.ChildFolderCount == 0 && !fi.HasWorkingDraft) + cm.MenuItems.Add("Create Working Draft", new EventHandler(mi_Click)); + } + if (fi.HasWorkingDraft) + cm.MenuItems.Add("Print Transition Report", new EventHandler(mi_Click)); + } + else if (tn.VEObject as DocVersionInfo != null) // DocVersions can only contain procs + { + isWrkDftNode = true; + //_MyLog.WarnFormat("Context Menu 1c - {0}", GC.GetTotalMemory(true)); + DocVersionInfo dvi = tn.VEObject as DocVersionInfo; + if (ui.IsAdministrator() || ui.IsSetAdministrator(dvi)) + { + cm.MenuItems.Add("Import Procedure", mi_Click); + } + if (ui.IsAdministrator() || ui.IsSetAdministrator(dvi) || ui.IsWriter(dvi)) + { + OwnerInfoList.Reset(); + oil = OwnerInfoList.GetByVersionID(dvi.VersionID); + if (dvi.ActiveFormat.PlantFormat.FormatData.SpecificInfo) + cm.MenuItems.Add("Procedure Set Specific Information", new EventHandler(mi_Click)); + cm.MenuItems.Add("Refresh Checked Out Procedures", new EventHandler(mi_Click)); + cm.MenuItems.Add("New Procedure", new EventHandler(mi_Click)); + if (dvi.MultiUnitCount > 1) + { + MenuItem mip = new MenuItem("Print All Procedures for"); + MenuItem mia = new MenuItem("Approve All Procedures for"); + MenuItem mis = new MenuItem("Approve Some Procedures for"); + MenuItem mir = new MenuItem("Print All Approved Procedures for"); // C2025-017 print all approved procedures + int k = 0; + foreach (string s in dvi.UnitNames) + { + k++; + MenuItem mp = mip.MenuItems.Add(s, new EventHandler(miMultiUnit_Click)); + mp.Tag = k; + MenuItem ma = mia.MenuItems.Add(s, new EventHandler(miMultiUnit_Click)); + ma.Tag = k; + MenuItem ms = mis.MenuItems.Add(s, new EventHandler(miMultiUnit_Click)); + ms.Tag = k; + MenuItem mr = mir.MenuItems.Add(s, new EventHandler(miMultiUnit_Click)); // C2025-017 print all approved procedures + mr.Tag = k; + } + cm.MenuItems.Add(mip); + cm.MenuItems.Add(mia); + cm.MenuItems.Add(mis); + cm.MenuItems.Add(mir); // C2025-017 print all approved procedures + } + else + { + //_MyLog.WarnFormat("Context Menu 1d - {0}", GC.GetTotalMemory(true)); + cm.MenuItems.Add("Print All Procedures", new EventHandler(mi_Click)); + cm.MenuItems.Add("Approve All Procedures", new EventHandler(mi_Click)); + cm.MenuItems.Add("Approve Some Procedures", new EventHandler(mi_Click)); + cm.MenuItems.Add("Print All Approved Procedures", new EventHandler(mi_Click)); + } + cm.MenuItems.Add("Report All Procedures Inconsistencies", new EventHandler(mi_Click)); + } + else + { + //_MyLog.WarnFormat("Context Menu 1e - {0}", GC.GetTotalMemory(true)); + OwnerInfoList.Reset(); + oil = OwnerInfoList.GetByVersionID(dvi.VersionID); + cm.MenuItems.Add("Refresh Checked Out Procedures", new EventHandler(mi_Click)); + if (dvi.MultiUnitCount > 1) + { + MenuItem mip = new MenuItem("Print All Procedures for"); + int k = 0; + foreach (string s in dvi.UnitNames) + { + k++; + MenuItem mp = mip.MenuItems.Add(s, new EventHandler(miMultiUnit_Click)); + mp.Tag = k; + } + cm.MenuItems.Add(mip); + } + else + { + //_MyLog.WarnFormat("Context Menu 1f - {0}", GC.GetTotalMemory(true)); + cm.MenuItems.Add("Print All Procedures", new EventHandler(mi_Click)); + } + } + if (ui.IsAdministrator() || ui.IsSetAdministrator(dvi) || ui.IsROEditor(dvi)) + { + //_MyLog.WarnFormat("Context Menu 1g - {0}", GC.GetTotalMemory(true)); + cm.MenuItems.Add("Run RO Editor", new EventHandler(mi_Click)); + } + if (ui.IsAdministrator() || ui.IsSetAdministrator(dvi)) + { + //_MyLog.WarnFormat("Context Menu 1h - {0}", GC.GetTotalMemory(true)); + MenuItem urv = cm.MenuItems.Add("Update RO Values", new EventHandler(mi_Click)); + // only allow update if association, and the RO update was not done and/or not completed + urv.Enabled = !dvi.ROfstLastCompleted || dvi.NewerRoFst; + } + } + else if (tn.VEObject as ProcedureInfo != null) // Procs can only contain sections + { + isProcNode = true; + ProcedureInfo pri = tn.VEObject as ProcedureInfo; + oi = OwnerInfo.GetByItemID(pri.ItemID, CheckOutType.Procedure); + if (ui.IsAdministrator() || ui.IsSetAdministrator(pri.MyDocVersion)) + { + cm.MenuItems.Add("Export Procedure", mi_Click); + //C2025-024 Proms XML Output - if have any EP Format files, add dropdown menu for exporting EP formats + if (pri.ActiveFormat.PlantFormat.EPFormatFiles.Count > 0) + AddEPExport(cm.MenuItems, pri.MyDocVersion.MultiUnitCount, pri.MyDocVersion.UnitNames, pri.ActiveFormat.PlantFormat.EPFormatFiles); + } + if (ui.IsAdministrator() || ui.IsSetAdministrator(pri.MyDocVersion) || ui.IsWriter(pri.MyDocVersion)) + { + if (oi != null && oi.SessionID != MySessionInfo.SessionID) + cm.MenuItems.Add(string.Format("Procedure Checked Out to {0}", oi.SessionUserID), new EventHandler(mi_Click)); + if (pri.ActiveFormat.PlantFormat.FormatData.ProcData.PSI.Caption != null) cm.MenuItems.Add("Procedure Specific Information", new EventHandler(mi_Click)); + cm.MenuItems.Add("Insert Procedure Before", new EventHandler(mi_Click)); + cm.MenuItems.Add("Insert Procedure After", new EventHandler(mi_Click)); - // if this format has change ids that were added from edit, allow removal of - // change ids for this procedure: - //FolderInfo fi = FolderInfo.Get(1); - //FormatInfo frmI = FormatInfo.Get(fi.FormatID ?? 1); - //if (frmI.PlantFormat.FormatData.ProcData.ChangeBarData.ChgBarMessageFromEdit) - // cm.MenuItems.Add("Remove Change Ids", new EventHandler(mi_Click)); - cm.MenuItems.Add("New Section", new EventHandler(mi_Click)); - if (pri.MyDocVersion.MultiUnitCount > 1) - { - MenuItem micas = new MenuItem("Create Continuous Action Summary"); - MenuItem mitcas = new MenuItem("Create Time Critical Action Summary"); //F2022-024 added menu option - MenuItem mip = new MenuItem("Print"); - MenuItem miqp = new MenuItem("Quick Print"); - //MenuItem mips = new MenuItem("Print Section"); - MenuItem mia = new MenuItem("Approve"); + cm.MenuItems.Add("New Section", new EventHandler(mi_Click)); + if (pri.MyDocVersion.MultiUnitCount > 1) + { + MenuItem micas = new MenuItem("Create Continuous Action Summary"); + MenuItem mitcas = new MenuItem("Create Time Critical Action Summary"); //F2022-024 added menu option + MenuItem mip = new MenuItem("Print"); + MenuItem miqp = new MenuItem("Quick Print"); + //MenuItem mips = new MenuItem("Print Section"); + MenuItem mia = new MenuItem("Approve"); - int k = 0; - foreach (string s in pri.MyDocVersion.UnitNames) - { - // C2021-027: Procedure level PC/PC - see if menu items for unit should be enabled - bool procAppl = pri.ApplIncludeFromStr(s); - k++; - MenuItem mp = mip.MenuItems.Add(s, new EventHandler(miMultiUnit_Click)); - mp.Enabled = procAppl; - mp.Tag = k; - MenuItem mqp = miqp.MenuItems.Add(s, new EventHandler(miMultiUnit_Click)); - mqp.Enabled = procAppl; - mqp.Tag = k; - //MenuItem mps = mips.MenuItems.Add(s, new EventHandler(miMultiUnit_Click)); - //mps.Enabled = procAppl; - //mps.Tag = k; - MenuItem ma = mia.MenuItems.Add(s, new EventHandler(miMultiUnit_Click)); - ma.Enabled = procAppl; - ma.Tag = k; - MenuItem mc = micas.MenuItems.Add(s, new EventHandler(miMultiUnit_Click)); - mc.Enabled = procAppl; - mc.Tag = k; - MenuItem mtc = mitcas.MenuItems.Add(s, new EventHandler(miMultiUnit_Click)); - mtc.Enabled = procAppl; - mtc.Tag = k; - } - cm.MenuItems.Add(micas); - cm.MenuItems.Add(mitcas); - cm.MenuItems.Add(mip); - cm.MenuItems.Add(miqp); - //cm.MenuItems.Add(mips); - AddShowChangeBarsAfterMenuItem(cm.MenuItems, pri); - cm.MenuItems.Add(mia); - AddApprovedRevisionsMultiUnit(cm.MenuItems, pri); - } - else - { - cm.MenuItems.Add("Create Continuous Action Summary", new EventHandler(mi_Click)); - cm.MenuItems.Add("Create Time Critical Action Summary", new EventHandler(mi_Click)); - cm.MenuItems.Add("Print", new EventHandler(mi_Click)); - cm.MenuItems.Add("Quick Print", new EventHandler(mi_Click)); - //cm.MenuItems.Add("Print Section", new EventHandler(mi_Click)); - //MenuItem miqp = new MenuItem("Print"); - AddShowChangeBarsAfterMenuItem(cm.MenuItems, pri); - cm.MenuItems.Add("Approve", new EventHandler(mi_Click)); - //_MyLog.WarnFormat("Context Menu 1 before - {0}", GC.GetTotalMemory(true)); - AddApprovedRevisions(cm.MenuItems, pri); - //_MyLog.WarnFormat("Context Menu 1 after - {0}", GC.GetTotalMemory(true)); - } - } - else - { - if (oi != null && oi.SessionID != MySessionInfo.SessionID) - cm.MenuItems.Add(string.Format("Procedure Checked Out to {0}", oi.SessionUserID), new EventHandler(mi_Click)); - if (pri.MyDocVersion.MultiUnitCount > 1) - { - MenuItem mip = new MenuItem("Print"); - MenuItem miqp = new MenuItem("Quick Print"); - int k = 0; - foreach (string s in pri.MyDocVersion.UnitNames) - { - k++; - MenuItem mp = mip.MenuItems.Add(s, new EventHandler(miMultiUnit_Click)); - mp.Tag = k; - MenuItem mqp = miqp.MenuItems.Add(s, new EventHandler(miMultiUnit_Click)); - mqp.Tag = k; - } - cm.MenuItems.Add(mip); - cm.MenuItems.Add(miqp); - AddApprovedRevisionsMultiUnit(cm.MenuItems, pri); - } - else - { - cm.MenuItems.Add("Print", new EventHandler(mi_Click)); - cm.MenuItems.Add("Quick Print", new EventHandler(mi_Click)); - AddApprovedRevisions(cm.MenuItems, pri); - } - } - cm.MenuItems.Add("Print Transition Report", new EventHandler(mi_Click)); - } - else if (tn.VEObject as SectionInfo != null) - { - isSectNode = true; - // A step Section can contain other steps or can contain subsections (either step section - // or word doc section). Also note that there can be a mix. - // A word doc section can contain another subsection (either step section or word doc section), - // but cannot contain steps. - SectionInfo si = tn.VEObject as SectionInfo; - // if this is an enhanced section, don't do 'New Step' - if (ui.IsAdministrator() || ui.IsSetAdministrator(si.MyProcedure.MyDocVersion) || ui.IsWriter(si.MyProcedure.MyDocVersion)) - { - if (si.HasWordContent) - { - oi = OwnerInfo.GetByItemID(si.MyContent.MyEntry.DocID, CheckOutType.Document); - } - si.MyConfig = null; - // Do not need step versus Word doc options, user enters this in property page during - // insert process. - if (oi != null && oi.SessionID != MySessionInfo.SessionID) - cm.MenuItems.Add(string.Format("Document Checked Out to {0}", oi.SessionUserID), new EventHandler(mi_Click)); - cm.MenuItems.Add("Insert Section Before", new EventHandler(mi_Click)); - cm.MenuItems.Add("Insert Section After", new EventHandler(mi_Click)); - if (!si.IsAutoTOCSection && si.IsStepSection) // B2016-282: Don't allow insert of subsections off Word Section. - { - bool meta = si.ActiveFormat.PlantFormat.FormatData.SectData.UseMetaSections; - if (meta) cm.MenuItems.Add("New Subsection", new EventHandler(mi_Click)); - // if this section has subsections, then be sure that the 'editable' data config - // is set to allow new step creation. - if (si.IsStepSection) - { - SectionConfig sc = si.MyConfig as SectionConfig; - if (!si.IsEnhancedSection && (si.Sections == null || si.Sections.Count == 0 || (meta && sc != null && si.Sections != null && si.Sections.Count > 0 && sc.SubSection_Edit == "Y"))) - cm.MenuItems.Add("New Step", new EventHandler(mi_Click)); + int k = 0; + foreach (string s in pri.MyDocVersion.UnitNames) + { + // C2021-027: Procedure level PC/PC - see if menu items for unit should be enabled + bool procAppl = pri.ApplIncludeFromStr(s); + k++; + MenuItem mp = mip.MenuItems.Add(s, new EventHandler(miMultiUnit_Click)); + mp.Enabled = procAppl; + mp.Tag = k; + MenuItem mqp = miqp.MenuItems.Add(s, new EventHandler(miMultiUnit_Click)); + mqp.Enabled = procAppl; + mqp.Tag = k; + MenuItem ma = mia.MenuItems.Add(s, new EventHandler(miMultiUnit_Click)); + ma.Enabled = procAppl; + ma.Tag = k; + MenuItem mc = micas.MenuItems.Add(s, new EventHandler(miMultiUnit_Click)); + mc.Enabled = procAppl; + mc.Tag = k; + MenuItem mtc = mitcas.MenuItems.Add(s, new EventHandler(miMultiUnit_Click)); + mtc.Enabled = procAppl; + mtc.Tag = k; + } + cm.MenuItems.Add(micas); + cm.MenuItems.Add(mitcas); + cm.MenuItems.Add(mip); + cm.MenuItems.Add(miqp); + AddShowChangeBarsAfterMenuItem(cm.MenuItems, pri); + cm.MenuItems.Add(mia); + AddApprovedRevisionsMultiUnit(cm.MenuItems, pri); + } + else + { + cm.MenuItems.Add("Create Continuous Action Summary", new EventHandler(mi_Click)); + cm.MenuItems.Add("Create Time Critical Action Summary", new EventHandler(mi_Click)); + cm.MenuItems.Add("Print", new EventHandler(mi_Click)); + cm.MenuItems.Add("Quick Print", new EventHandler(mi_Click)); + AddShowChangeBarsAfterMenuItem(cm.MenuItems, pri); + cm.MenuItems.Add("Approve", new EventHandler(mi_Click)); + //_MyLog.WarnFormat("Context Menu 1 before - {0}", GC.GetTotalMemory(true)); + AddApprovedRevisions(cm.MenuItems, pri); + //_MyLog.WarnFormat("Context Menu 1 after - {0}", GC.GetTotalMemory(true)); + } + } + else + { + if (oi != null && oi.SessionID != MySessionInfo.SessionID) + cm.MenuItems.Add(string.Format("Procedure Checked Out to {0}", oi.SessionUserID), new EventHandler(mi_Click)); + if (pri.MyDocVersion.MultiUnitCount > 1) + { + MenuItem mip = new MenuItem("Print"); + MenuItem miqp = new MenuItem("Quick Print"); + int k = 0; + foreach (string s in pri.MyDocVersion.UnitNames) + { + k++; + MenuItem mp = mip.MenuItems.Add(s, new EventHandler(miMultiUnit_Click)); + mp.Tag = k; + MenuItem mqp = miqp.MenuItems.Add(s, new EventHandler(miMultiUnit_Click)); + mqp.Tag = k; + } + cm.MenuItems.Add(mip); + cm.MenuItems.Add(miqp); + AddApprovedRevisionsMultiUnit(cm.MenuItems, pri); + } + else + { + cm.MenuItems.Add("Print", new EventHandler(mi_Click)); + cm.MenuItems.Add("Quick Print", new EventHandler(mi_Click)); + AddApprovedRevisions(cm.MenuItems, pri); + } + } + cm.MenuItems.Add("Print Transition Report", new EventHandler(mi_Click)); + } + else if (tn.VEObject as SectionInfo != null) + { + isSectNode = true; + // A step Section can contain other steps or can contain subsections (either step section + // or word doc section). Also note that there can be a mix. + // A word doc section can contain another subsection (either step section or word doc section), + // but cannot contain steps. + SectionInfo si = tn.VEObject as SectionInfo; + // if this is an enhanced section, don't do 'New Step' + if (ui.IsAdministrator() || ui.IsSetAdministrator(si.MyProcedure.MyDocVersion) || ui.IsWriter(si.MyProcedure.MyDocVersion)) + { + if (si.HasWordContent) + { + oi = OwnerInfo.GetByItemID(si.MyContent.MyEntry.DocID, CheckOutType.Document); + } + si.MyConfig = null; + // Do not need step versus Word doc options, user enters this in property page during + // insert process. + if (oi != null && oi.SessionID != MySessionInfo.SessionID) + cm.MenuItems.Add(string.Format("Document Checked Out to {0}", oi.SessionUserID), new EventHandler(mi_Click)); + cm.MenuItems.Add("Insert Section Before", new EventHandler(mi_Click)); + cm.MenuItems.Add("Insert Section After", new EventHandler(mi_Click)); + if (!si.IsAutoTOCSection && si.IsStepSection) // B2016-282: Don't allow insert of subsections off Word Section. + { + bool meta = si.ActiveFormat.PlantFormat.FormatData.SectData.UseMetaSections; + if (meta) cm.MenuItems.Add("New Subsection", new EventHandler(mi_Click)); + // if this section has subsections, then be sure that the 'editable' data config + // is set to allow new step creation. + if (si.IsStepSection) + { + SectionConfig sc = si.MyConfig as SectionConfig; + if (!si.IsEnhancedSection && (si.Sections == null || si.Sections.Count == 0 || (meta && sc != null && si.Sections != null && si.Sections.Count > 0 && sc.SubSection_Edit == "Y"))) + cm.MenuItems.Add("New Step", new EventHandler(mi_Click)); - //ProcedureInfo pri = tn as SectionInfo; - SectionInfo si2 = (tn as VETreeNode).VEObject as SectionInfo; - if (si2.MyDocVersion.MultiUnitCount > 1) - { - if (!si2.IsSubsection) - { - MenuItem mps = new MenuItem("Print Section"); - int k = 0; - foreach (string s in si2.MyDocVersion.UnitNames) - { - k++; - MenuItem mp = mps.MenuItems.Add(s, new EventHandler(miMultiUnit_Click)); - mp.Tag = k; - } - cm.MenuItems.Add(mps); + //ProcedureInfo pri = tn as SectionInfo; + SectionInfo si2 = (tn as VETreeNode).VEObject as SectionInfo; + if (si2.MyDocVersion.MultiUnitCount > 1) + { + if (!si2.IsSubsection) + { + MenuItem mps = new MenuItem("Print Section"); + int k = 0; + foreach (string s in si2.MyDocVersion.UnitNames) + { + k++; + MenuItem mp = mps.MenuItems.Add(s, new EventHandler(miMultiUnit_Click)); + mp.Tag = k; + } + cm.MenuItems.Add(mps); - //C2025-028 Add a Quick Print Section option - MenuItem mps_qp = new MenuItem("Quick Print Section"); - int k_qp = 0; - foreach (string s in si2.MyDocVersion.UnitNames) - { - k_qp++; - MenuItem mp_qp = mps_qp.MenuItems.Add(s, new EventHandler(miMultiUnit_Click)); - mp_qp.Tag = k_qp; - } - cm.MenuItems.Add(mps_qp); - } - } - else - { - if (!si2.IsSubsection) - { - cm.MenuItems.Add("Print Section", new EventHandler(mi_Click)); - cm.MenuItems.Add("Quick Print Section", new EventHandler(mi_Click)); - } - } - } - } - } - } - else if (tn.VEObject as StepInfo != null) - { - // check the format for allowable inserts, and also, - ItemInfo i = tn.VEObject as ItemInfo; - if (ui.IsAdministrator() || ui.IsSetAdministrator(i.MyProcedure.MyDocVersion) || ui.IsWriter(i.MyProcedure.MyDocVersion)) - { - //oi = OwnerInfo.GetByItemID(i.MyProcedure.ItemID); - if (AddToInsertMenu(i, 0)) cm.MenuItems.Add("Insert Step Before", new EventHandler(mi_Click)); - if (AddToInsertMenu(i, 1)) cm.MenuItems.Add("Insert Step After", new EventHandler(mi_Click)); - } - } - #endregion - //_MyLog.WarnFormat("Context Menu 2 - {0}", GC.GetTotalMemory(true)); - //#region Print_Section - //if (!tn.IsExpanded && tn.VEObject as SectionInfo != null) - //{ - // SectionInfo si = tn.VEObject as SectionInfo; - // if (si.IsStepSection) cm.MenuItems.Add("Print Section", new EventHandler(mi_Click)); - //} - //#endregion - #region Menu_Open - if (!tn.IsExpanded && tn.VEObject as SectionInfo != null) - { - SectionInfo si = tn.VEObject as SectionInfo; - if (si.IsStepSection) cm.MenuItems.Add("Open", new EventHandler(mi_Click)); - } - else if (!tn.IsExpanded && tn.VEObject as StepInfo != null) - { - StepInfo stpi = tn.VEObject as StepInfo; - if (stpi.HasChildren) cm.MenuItems.Add("Open", new EventHandler(mi_Click)); - } - else if (!tn.IsExpanded) - cm.MenuItems.Add("Open", new EventHandler(mi_Click)); - else - { // B2016-058 customize the "Collapse" menu text based on tree node type - string mtext = "Collapse"; // only the step or substep (RNOs, Cautions, Notes as well) will be collapsed - if (isFolderNode || isWrkDftNode) - mtext += " All Procedures"; // all expanded procedure nodes in all procedure sets are collapsed (folder and working draft nodes remain expanded) - else if (isProcNode) - mtext += " Procedure"; // only the current procedure node is collapsed - else if (isSectNode) - mtext += " Section"; // only the current section node is collapsed - cm.MenuItems.Add(mtext, new EventHandler(mi_Click)); - } - #endregion - //_MyLog.WarnFormat("Context Menu 3 - {0}", GC.GetTotalMemory(true)); + //C2025-028 Add a Quick Print Section option + MenuItem mps_qp = new MenuItem("Quick Print Section"); + int k_qp = 0; + foreach (string s in si2.MyDocVersion.UnitNames) + { + k_qp++; + MenuItem mp_qp = mps_qp.MenuItems.Add(s, new EventHandler(miMultiUnit_Click)); + mp_qp.Tag = k_qp; + } + cm.MenuItems.Add(mps_qp); + } + } + else + { + if (!si2.IsSubsection) + { + cm.MenuItems.Add("Print Section", new EventHandler(mi_Click)); + cm.MenuItems.Add("Quick Print Section", new EventHandler(mi_Click)); + } + } + } + } + } + } + else if (tn.VEObject as StepInfo != null) + { + // check the format for allowable inserts, and also, + ItemInfo i = tn.VEObject as ItemInfo; + if (ui.IsAdministrator() || ui.IsSetAdministrator(i.MyProcedure.MyDocVersion) || ui.IsWriter(i.MyProcedure.MyDocVersion)) + { + if (AddToInsertMenu(i, 0)) cm.MenuItems.Add("Insert Step Before", new EventHandler(mi_Click)); + if (AddToInsertMenu(i, 1)) cm.MenuItems.Add("Insert Step After", new EventHandler(mi_Click)); + } + } + #endregion + //_MyLog.WarnFormat("Context Menu 2 - {0}", GC.GetTotalMemory(true)); + #region Menu_Open + if (!tn.IsExpanded && tn.VEObject as SectionInfo != null) + { + SectionInfo si = tn.VEObject as SectionInfo; + if (si.IsStepSection) cm.MenuItems.Add("Open", new EventHandler(mi_Click)); + } + else if (!tn.IsExpanded && tn.VEObject as StepInfo != null) + { + StepInfo stpi = tn.VEObject as StepInfo; + if (stpi.HasChildren) cm.MenuItems.Add("Open", new EventHandler(mi_Click)); + } + else if (!tn.IsExpanded) + cm.MenuItems.Add("Open", new EventHandler(mi_Click)); + else + { // B2016-058 customize the "Collapse" menu text based on tree node type + string mtext = "Collapse"; // only the step or substep (RNOs, Cautions, Notes as well) will be collapsed + if (isFolderNode || isWrkDftNode) + mtext += " All Procedures"; // all expanded procedure nodes in all procedure sets are collapsed (folder and working draft nodes remain expanded) + else if (isProcNode) + mtext += " Procedure"; // only the current procedure node is collapsed + else if (isSectNode) + mtext += " Section"; // only the current section node is collapsed + cm.MenuItems.Add(mtext, new EventHandler(mi_Click)); + } + #endregion + //_MyLog.WarnFormat("Context Menu 3 - {0}", GC.GetTotalMemory(true)); - #region Menu_CutCopy - // For initial release, copy is not available for folders or docversions - if (tn.VEObject as ItemInfo != null) - { - ItemInfo i = tn.VEObject as ItemInfo; - // in the following, 'Copy' is not allowed for any procedure/section/step that is enhanced. Note that this may be - // changed later, but for the initial enhanced development it was decided to not allow copy of enhanced since paste would - // require clearing of all enhanced config data or mapping it to existing data (quite complicated) - if ((ui.IsAdministrator() || ui.IsSetAdministrator(i.MyProcedure.MyDocVersion) || ui.IsWriter(i.MyProcedure.MyDocVersion)) && (!i.IsEnhancedStep && !i.IsEnhancedProcedure && !i.IsEnhancedSection && !i.IsRtfRaw && !i.IsFigure)) - cm.MenuItems.Add("Copy", new EventHandler(mi_Click)); - //if (i.HasWordContent) - //{ - // cm.MenuItems.Add("Print Section", new EventHandler(mi_Click)); - // cm.MenuItems.Add("Quick Print Section", new EventHandler(mi_Click)); - //} - if (i.HasWordContent) - { - if (i.MyDocVersion.MultiUnitCount > 1) - { - if (!i.IsSubsection) - { - MenuItem mps = new MenuItem("Print Section"); - MenuItem mqps = new MenuItem("Quick Print Section"); - int k = 0; - foreach (string s in i.MyDocVersion.UnitNames) - { - k++; - MenuItem mp = mps.MenuItems.Add(s, new EventHandler(miMultiUnit_Click)); - mp.Tag = k; - MenuItem mqp = mqps.MenuItems.Add(s, new EventHandler(miMultiUnit_Click)); - mqp.Tag = k; - } - cm.MenuItems.Add(mps); - cm.MenuItems.Add(mqps); - } - } - else - { - cm.MenuItems.Add("Print Section", new EventHandler(mi_Click)); - cm.MenuItems.Add("Quick Print Section", new EventHandler(mi_Click)); - } - } - } - #endregion - //_MyLog.WarnFormat("Context Menu 4 - {0}", GC.GetTotalMemory(true)); + #region Menu_CutCopy + // For initial release, copy is not available for folders or docversions + if (tn.VEObject as ItemInfo != null) + { + ItemInfo i = tn.VEObject as ItemInfo; + // in the following, 'Copy' is not allowed for any procedure/section/step that is enhanced. Note that this may be + // changed later, but for the initial enhanced development it was decided to not allow copy of enhanced since paste would + // require clearing of all enhanced config data or mapping it to existing data (quite complicated) + if ((ui.IsAdministrator() || ui.IsSetAdministrator(i.MyProcedure.MyDocVersion) || ui.IsWriter(i.MyProcedure.MyDocVersion)) && (!i.IsEnhancedStep && !i.IsEnhancedProcedure && !i.IsEnhancedSection && !i.IsRtfRaw && !i.IsFigure)) + cm.MenuItems.Add("Copy", new EventHandler(mi_Click)); + if (i.HasWordContent) + { + if (i.MyDocVersion.MultiUnitCount > 1) + { + if (!i.IsSubsection) + { + MenuItem mps = new MenuItem("Print Section"); + MenuItem mqps = new MenuItem("Quick Print Section"); + int k = 0; + foreach (string s in i.MyDocVersion.UnitNames) + { + k++; + MenuItem mp = mps.MenuItems.Add(s, new EventHandler(miMultiUnit_Click)); + mp.Tag = k; + MenuItem mqp = mqps.MenuItems.Add(s, new EventHandler(miMultiUnit_Click)); + mqp.Tag = k; + } + cm.MenuItems.Add(mps); + cm.MenuItems.Add(mqps); + } + } + else + { + cm.MenuItems.Add("Print Section", new EventHandler(mi_Click)); + cm.MenuItems.Add("Quick Print Section", new EventHandler(mi_Click)); + } + } + } + #endregion + //_MyLog.WarnFormat("Context Menu 4 - {0}", GC.GetTotalMemory(true)); - #region Menu_Paste - bool ok = false; - if (tn.VEObject is FolderInfo && (ui.IsAdministrator() || ui.IsSetAdministrator(tn.VEObject as FolderInfo))) - ok = true; - else if (tn.VEObject is DocVersionInfo && (ui.IsAdministrator() || ui.IsSetAdministrator(tn.VEObject as DocVersionInfo))) - ok = true; - else if (tn.VEObject is ItemInfo && (ui.IsAdministrator() || ui.IsSetAdministrator((tn.VEObject as ItemInfo).MyProcedure.MyDocVersion) || ui.IsWriter((tn.VEObject as ItemInfo).MyProcedure.MyDocVersion))) - ok = true; - if (ok) - Menu_Paste(tn, cm); - #endregion - //_MyLog.WarnFormat("Context Menu 5 - {0}", GC.GetTotalMemory(true)); + #region Menu_Paste + bool ok = false; + if (tn.VEObject is FolderInfo && (ui.IsAdministrator() || ui.IsSetAdministrator(tn.VEObject as FolderInfo))) + ok = true; + else if (tn.VEObject is DocVersionInfo && (ui.IsAdministrator() || ui.IsSetAdministrator(tn.VEObject as DocVersionInfo))) + ok = true; + else if (tn.VEObject is ItemInfo && (ui.IsAdministrator() || ui.IsSetAdministrator((tn.VEObject as ItemInfo).MyProcedure.MyDocVersion) || ui.IsWriter((tn.VEObject as ItemInfo).MyProcedure.MyDocVersion))) + ok = true; + if (ok) + Menu_Paste(tn, cm); + #endregion + //_MyLog.WarnFormat("Context Menu 5 - {0}", GC.GetTotalMemory(true)); - #region Menu_Delete - if (ok) + #region Menu_Delete + if (ok) + { + // Add delete to the menu unless at the very 'top' node, on a grouping (partinfo) + // node (RNOs, Steps, Cautions, Notes) or Folder/DocVersion that contains any items. + PartInfo pi = tn.VEObject as PartInfo; + if (pi == null && tn.Parent != null) // it's not a part and it's not the top.... + { + fi = tn.VEObject as FolderInfo; + if (fi == null || tn.Nodes.Count == 0) // it's not a folder or it has no children + { + if (!(tn.VEObject is DocVersionInfo di) || tn.Nodes.Count == 0) // it's not a docversion or it has no children + { + // if it's an enhanced step that was linked from a source, don't allow delete + bool canDoDel = true; + ItemInfo iienh = tn.VEObject as ItemInfo; + if (iienh != null && iienh.IsProcedure && iienh.IsEnhancedProcedure) canDoDel = false; + if (iienh != null && iienh.IsSection && iienh.IsEnhancedSection && !iienh.IsEnhancedSectionTitleOnly) canDoDel = false; + if (iienh != null && iienh.IsEnhancedStep) canDoDel = false; + if (canDoDel) cm.MenuItems.Add("Delete", new EventHandler(mi_Click)); + } + } + } + } + #endregion + //_MyLog.WarnFormat("Context Menu 6 - {0}", GC.GetTotalMemory(true)); + #region Menu_ExternalTransitions + // C2020-033: Support the menu item to bring up Search/Incoming Transitions panel + if (tn.VEObject is ItemInfo iix) + { + cm.MenuItems.Add("Incoming Transitions", new EventHandler(mi_Click)); + } + #endregion + #region Menu_UnLinkEnhanced + // B2022-049: provide for way to unlink a procedure from the tree view. Also unlinks procedure if no + // connected (linked) procedure. + if (tn.VEObject is ProcedureInfo) + { + ItemInfo prc = (ItemInfo)tn.VEObject; + if (ui.IsAdministrator() || ui.IsSetAdministrator(prc.MyDocVersion) || ui.IsWriter(prc.MyDocVersion)) + { + DVEnhancedDocuments dveds = prc.MyDocVersion.DocVersionConfig.MyEnhancedDocuments; + EnhancedDocuments eds = prc.GetMyEnhancedDocuments(); + // if just one link, add single menu item to unlink. If more than one, need a list with all. + if (eds != null && eds.Count == 1) + { + // Get menu string, must start with 'Unlink Source ' + string doclink = null; + doclink = dveds.GetByType(eds[0].Type).Name; // need background/dev if on source + if (eds[0].Type == 0) + { + ItemInfo prl = ItemInfo.Get(eds[0].ItemID); + DVEnhancedDocuments dvedsl = prl.MyDocVersion.DocVersionConfig.MyEnhancedDocuments; + foreach (DVEnhancedDocument dvel in dvedsl) if (dvel.VersionID == prc.MyDocVersion.VersionID) doclink = dvel.Name; + } + doclink = string.Format("Unlink Source and {0} Procedure", doclink); + MenuItem mix = cm.MenuItems.Add(doclink, new EventHandler(miEnhanced_Click)); + mix.Tag = -1; // NOTE this is what flags what gets processed on menu click, i.e. -1 + } + // if this is a source procedure that has enhanced, for example Background and/or deviation, ask which should be unlinked including all + else if (eds != null && eds.Count > 1) + { + MenuItem miu = new MenuItem("Unlink Enhanced Procedure(s) from Source") + { + Tag = -2 // this menu item doesn't get used. + }; + int k = 0; + foreach (EnhancedDocument ed in eds) + { + // add submenu item for it + k++; + MenuItem mp = miu.MenuItems.Add(dveds.GetByType(ed.Type).Name, new EventHandler(miEnhanced_Click)); + mp.Tag = k; + } + // add all submenu item + MenuItem mp1 = miu.MenuItems.Add("All", new EventHandler(miEnhanced_Click)); + mp1.Tag = 0; // Tag of 0 flags All + cm.MenuItems.Add(miu); + } + } + } + #endregion + #region Menu_Properties + // Add Properties to the menu unless at the very 'top' node or on a grouping (partinfo) + // node (RNOs, Steps, Cautions, Notes) or at the step level. + // B2020-105 Allow Set Administrators to rename folder's (sets of procedures) to which they have been given access. + if (tn.VEObject is FolderInfo) ok = (ui.IsAdministrator() || ui.IsSetAdministrator(tn.VEObject as FolderInfo)); + else ok = (tn.VEObject is DocVersionInfo) ? (ui.IsAdministrator() || ui.IsSetAdministrator(tn.VEObject as DocVersionInfo)) + : (ui.IsAdministrator() || (tn.VEObject is ItemInfo) && (ui.IsSetAdministrator((tn.VEObject as ItemInfo).MyProcedure.MyDocVersion) + || ui.IsWriter((tn.VEObject as ItemInfo).MyProcedure.MyDocVersion))); + PartInfo pia = tn.VEObject as PartInfo; + ItemInfo ii = tn.VEObject as ItemInfo; + if (ok) + if (pia == null && tn.VEObject as StepInfo == null) cm.MenuItems.Add("Properties...", new EventHandler(mi_Click)); + #endregion + #region Refresh_Tree + //C2021-035 Add Refresh Tree Option at highest level + if (tn == (VETreeNode)Nodes[0]) + cm.MenuItems.Add("Refresh Tree", new EventHandler(mi_Click)); + #endregion + //_MyLog.WarnFormat("Context Menu 7 - {0}", GC.GetTotalMemory(true)); - - - { - // Add delete to the menu unless at the very 'top' node, on a grouping (partinfo) - // node (RNOs, Steps, Cautions, Notes) or Folder/DocVersion that contains any items. - PartInfo pi = tn.VEObject as PartInfo; - if (pi == null && tn.Parent != null) // it's not a part and it's not the top.... - { - fi = tn.VEObject as FolderInfo; - if (fi == null || tn.Nodes.Count == 0) // it's not a folder or it has no children - { - DocVersionInfo di = tn.VEObject as DocVersionInfo; - if (di == null || tn.Nodes.Count == 0) // it's not a docversion or it has no children - { - // if it's an enhanced step that was linked from a source, don't allow delete - bool canDoDel = true; - ItemInfo iienh = tn.VEObject as ItemInfo; - if (iienh != null && iienh.IsProcedure && iienh.IsEnhancedProcedure) canDoDel = false; - if (iienh != null && iienh.IsSection && iienh.IsEnhancedSection && !iienh.IsEnhancedSectionTitleOnly) canDoDel = false; - if (iienh != null && iienh.IsEnhancedStep) canDoDel = false; - if (canDoDel) cm.MenuItems.Add("Delete", new EventHandler(mi_Click)); - } - } - } - } - - #endregion - //_MyLog.WarnFormat("Context Menu 6 - {0}", GC.GetTotalMemory(true)); - #region Menu_ExternalTransitions - // C2020-033: Support the menu item to bring up Search/Incoming Transitions panel - ItemInfo iix = tn.VEObject as ItemInfo; - if (iix != null) - { - cm.MenuItems.Add("Incoming Transitions", new EventHandler(mi_Click)); - } - #endregion - #region Menu_UnLinkEnhanced - // B2022-049: provide for way to unlink a procedure from the tree view. Also unlinks procedure if no - // connected (linked) procedure. - if (tn.VEObject is ProcedureInfo) - { - ItemInfo prc = (ItemInfo)tn.VEObject; - if (ui.IsAdministrator() || ui.IsSetAdministrator(prc.MyDocVersion) || ui.IsWriter(prc.MyDocVersion)) - { - DVEnhancedDocuments dveds = prc.MyDocVersion.DocVersionConfig.MyEnhancedDocuments; - EnhancedDocuments eds = prc.GetMyEnhancedDocuments(); - - // if just one link, add single menu item to unlink. If more than one, need a list with all. - if (eds != null && eds.Count == 1) - { - // Get menu string, must start with 'Unlink Source ' - string doclink = null; - doclink = dveds.GetByType(eds[0].Type).Name; // need background/dev if on source - if (eds[0].Type == 0) - { - ItemInfo prl = ItemInfo.Get(eds[0].ItemID); - DVEnhancedDocuments dvedsl = prl.MyDocVersion.DocVersionConfig.MyEnhancedDocuments; - foreach (DVEnhancedDocument dvel in dvedsl) if (dvel.VersionID == prc.MyDocVersion.VersionID) doclink = dvel.Name; - } - doclink = string.Format("Unlink Source and {0} Procedure", doclink); - MenuItem mix = cm.MenuItems.Add(doclink, new EventHandler(miEnhanced_Click)); - mix.Tag = -1; // NOTE this is what flags what gets processed on menu click, i.e. -1 - } - // if this is a source procedure that has enhanced, for example Background and/or deviation, ask which should be unlinked including all - else if (eds != null && eds.Count > 1) - { - MenuItem miu = new MenuItem("Unlink Enhanced Procedure(s) from Source"); - miu.Tag = -2; // this menu item doesn't get used. - int k = 0; - foreach (EnhancedDocument ed in eds) - { - // add submenu item for it - k++; - MenuItem mp = miu.MenuItems.Add(dveds.GetByType(ed.Type).Name, new EventHandler(miEnhanced_Click)); - mp.Tag = k; - } - // add all submenu item - MenuItem mp1 = miu.MenuItems.Add("All", new EventHandler(miEnhanced_Click)); - mp1.Tag = 0; // Tag of 0 flags All - cm.MenuItems.Add(miu); - } - } - } - #endregion - #region Menu_Properties - // Add Properties to the menu unless at the very 'top' node or on a grouping (partinfo) - // node (RNOs, Steps, Cautions, Notes) or at the step level. - // B2020-105 Allow Set Administrators to rename folder's (sets of procedures) to which they have been given access. - if (tn.VEObject is FolderInfo) ok = (ui.IsAdministrator() || ui.IsSetAdministrator(tn.VEObject as FolderInfo)); - else ok = (tn.VEObject is DocVersionInfo) ? (ui.IsAdministrator() || ui.IsSetAdministrator(tn.VEObject as DocVersionInfo)) - : (ui.IsAdministrator() || (tn.VEObject is ItemInfo) && (ui.IsSetAdministrator((tn.VEObject as ItemInfo).MyProcedure.MyDocVersion) - || ui.IsWriter((tn.VEObject as ItemInfo).MyProcedure.MyDocVersion))); - PartInfo pia = tn.VEObject as PartInfo; - ItemInfo ii = tn.VEObject as ItemInfo; - if (ok) - if (pia == null && tn.VEObject as StepInfo == null) cm.MenuItems.Add("Properties...", new EventHandler(mi_Click)); - #endregion - #region Refresh_Tree - //C2021-035 Add Refresh Tree Option at highest level - if (tn == (VETreeNode)Nodes[0]) - cm.MenuItems.Add("Refresh Tree", new EventHandler(mi_Click)); - #endregion - //_MyLog.WarnFormat("Context Menu 7 - {0}", GC.GetTotalMemory(true)); - - if (fi != null && fi.HasWorkingDraft) - { - /* + if (fi != null && fi.HasWorkingDraft) + { + /* --Folder level see if we need to disable "Export Procedure Set" or "Folder Specific Information" */ - if (tn.MovedToSeparateWindow) - { - foreach (MenuItem itm in cm.MenuItems) - { - if (!itm.Text.StartsWith("Insert")) // C2015-022 only enable insert folder before/after if in the main window and the procedures of this folder are in a child window - itm.Enabled = false; - } - } - else if (tn.InChildWindow) - { - foreach (MenuItem itm in cm.MenuItems) - { - if (itm.Text.StartsWith("Insert")) // C2015-022 disable insert folder before/after if doing a properties on a folder in a child window - itm.Enabled = false; - } - } - else - { - if (!tn.ChildrenLoaded) tn.LoadChildren(); - VETreeNode wrkdrft = (VETreeNode)tn.LastNode; - DocVersionInfo docver = wrkdrft.VEObject as DocVersionInfo; - OwnerInfoList.Reset(); - oil = OwnerInfoList.GetByVersionID(docver.VersionID); - bool greyOut = false; - foreach (OwnerInfo own in oil) - { - if (own.SessionID != MySessionInfo.SessionID) - { - greyOut = true; - break; - } - } - if (greyOut) - { - foreach (MenuItem itm in cm.MenuItems) - { - if (itm.Text == "Export Procedure Set" || itm.Text == "Folder Specific Information") // C2020-008: change to 'Folder' - itm.Enabled = false; - } - } - } - } - if (oil != null && oil.Count > 0 && tn.VEObject as DocVersionInfo != null) - { - /* + if (tn.MovedToSeparateWindow) + { + foreach (MenuItem itm in cm.MenuItems) + { + if (!itm.Text.StartsWith("Insert")) // C2015-022 only enable insert folder before/after if in the main window and the procedures of this folder are in a child window + itm.Enabled = false; + } + } + else if (tn.InChildWindow) + { + foreach (MenuItem itm in cm.MenuItems) + { + if (itm.Text.StartsWith("Insert")) // C2015-022 disable insert folder before/after if doing a properties on a folder in a child window + itm.Enabled = false; + } + } + else + { + if (!tn.ChildrenLoaded) tn.LoadChildren(); + VETreeNode wrkdrft = (VETreeNode)tn.LastNode; + DocVersionInfo docver = wrkdrft.VEObject as DocVersionInfo; + OwnerInfoList.Reset(); + oil = OwnerInfoList.GetByVersionID(docver.VersionID); + bool greyOut = false; + foreach (OwnerInfo own in oil) + { + if (own.SessionID != MySessionInfo.SessionID) + { + greyOut = true; + break; + } + } + if (greyOut) + { + foreach (MenuItem itm in cm.MenuItems) + { + if (itm.Text == "Export Procedure Set" || itm.Text == "Folder Specific Information") // C2020-008: change to 'Folder' + itm.Enabled = false; + } + } + } + } + if (oil != null && oil.Count > 0 && tn.VEObject as DocVersionInfo != null) + { + /* --docversion level Approve All Procedures Report All Procedures Inconsistencies */ - bool greyOut = false; - foreach (OwnerInfo own in oil) - { - if (own.SessionID != MySessionInfo.SessionID) - { - greyOut = true; - break; - } - } - if (greyOut) - { - foreach (MenuItem itm in cm.MenuItems) - { - if (itm.Text == "Approve All Procedures" || itm.Text == "Report All Procedures Inconsistencies" || - itm.Text == "Procedure Set Specific Information" || itm.Text == "Approve All Procedures for" || - itm.Text == "Approve Some Procedures" || itm.Text == "Approve Some Procedures for") - itm.Enabled = false; + bool greyOut = false; + foreach (OwnerInfo own in oil) + { + if (own.SessionID != MySessionInfo.SessionID) + { + greyOut = true; + break; + } + } + if (greyOut) + { + foreach (MenuItem itm in cm.MenuItems) + { + if (itm.Text == "Approve All Procedures" || itm.Text == "Report All Procedures Inconsistencies" || + itm.Text == "Procedure Set Specific Information" || itm.Text == "Approve All Procedures for" || + itm.Text == "Approve Some Procedures" || itm.Text == "Approve Some Procedures for") + itm.Enabled = false; - } - } - } - if (oi != null && oi.SessionID != MySessionInfo.SessionID) - { - /* + } + } + } + if (oi != null && oi.SessionID != MySessionInfo.SessionID) + { + /* --procedure level Procedure Specific Information New Section @@ -1370,35 +1042,35 @@ namespace Volian.Controls.Library --step level all of them */ - //_MyLog.WarnFormat("Context Menu 8 - {0}", GC.GetTotalMemory(true)); + //_MyLog.WarnFormat("Context Menu 8 - {0}", GC.GetTotalMemory(true)); - if (tn.VEObject as ProcedureInfo != null) - { - // F2022-024 added Time Critical Action Summary option - foreach (MenuItem itm in cm.MenuItems) - { - if (itm.Text == "Procedure Specific Information" || itm.Text == "New Section" || itm.Text == "Approve" || itm.Text == "Open" || - itm.Text == "Copy" || itm.Text == "Delete" || itm.Text == "Properties..." || itm.Text == "Replace Existing Procedure" || - itm.Text.StartsWith("Showing Change Bars Starting") || itm.Text == "Create Continuous Action Summary" || - itm.Text == "Create Time Critical Action Summary" || itm.Text == "Export Procedure") - itm.Enabled = false; - } - } - if (tn.VEObject as SectionInfo != null || tn.VEObject as StepInfo != null) - { - foreach (MenuItem itm in cm.MenuItems) - { - if (!itm.Text.StartsWith("Document Checked Out")) - itm.Enabled = false; - } - } - } - this.Cursor = Cursors.Default; - //_MyLog.WarnFormat("Context Menu 9 - {0}", GC.GetTotalMemory(true)); + if (tn.VEObject as ProcedureInfo != null) + { + // F2022-024 added Time Critical Action Summary option + foreach (MenuItem itm in cm.MenuItems) + { + if (itm.Text == "Procedure Specific Information" || itm.Text == "New Section" || itm.Text == "Approve" || itm.Text == "Open" || + itm.Text == "Copy" || itm.Text == "Delete" || itm.Text == "Properties..." || itm.Text == "Replace Existing Procedure" || + itm.Text.StartsWith("Showing Change Bars Starting") || itm.Text == "Create Continuous Action Summary" || + itm.Text == "Create Time Critical Action Summary" || itm.Text == "Export Procedure") + itm.Enabled = false; + } + } + if (tn.VEObject as SectionInfo != null || tn.VEObject as StepInfo != null) + { + foreach (MenuItem itm in cm.MenuItems) + { + if (!itm.Text.StartsWith("Document Checked Out")) + itm.Enabled = false; + } + } + } + this.Cursor = Cursors.Default; + //_MyLog.WarnFormat("Context Menu 9 - {0}", GC.GetTotalMemory(true)); - cm.Show(this, new Point(e.X, e.Y)); - } - } + cm.Show(this, new Point(e.X, e.Y)); + } + } } //C2025-024 Electronic Procedures - Phase 2 (PROMS XML output) @@ -1516,8 +1188,6 @@ namespace Volian.Controls.Library lastApprovedRevisionID = ri.RevisionID; addImportMI = true; } - //mir.Click += new EventHandler(ApprovedRevision_Click); - //added jcb 20111031 //_MyLog.WarnFormat("Context Menu 1 b4ViewProc- {0}", GC.GetTotalMemory(true)); if (ri.Notes.Length > 0) //C2018-026 add the ability to show notes entered during approval or workflow stage in the sub-menu { @@ -1563,9 +1233,8 @@ namespace Volian.Controls.Library { if (ril.Count == 0 || MyUserInfo.IsAdministrator() || MyUserInfo.IsSetAdministrator(pri.MyDocVersion)) { - ProcedureConfig pc = pri.MyConfig as ProcedureConfig; - string currentChgBarDateTime = ""; - if (pc != null) + string currentChgBarDateTime = ""; + if (pri.MyConfig is ProcedureConfig pc) currentChgBarDateTime = pc.Print_ChangeBarDate; // Current change bar date time before if (currentChgBarDateTime == "") currentChgBarDateTime = "(date not set)"; @@ -1583,17 +1252,17 @@ namespace Volian.Controls.Library RevisionConfig rc = ri.MyConfig as RevisionConfig; // bug fix: B2016-183 - add the child's name (ex Unit 1) to the export file name for Parent/Child procedures. int applIdx = rc.Applicability_Index; - string str = (applIdx > 0) ? _currentPri.MyDocVersion.UnitNames[applIdx - 1] + "_" : ""; // if parent/child get the defined child name to inlcude the export filename + string str = (applIdx > 0) ? $"{_currentPri.MyDocVersion.UnitNames[applIdx - 1]}_" : ""; // if parent/child get the defined child name to inlcude the export filename System.Xml.XmlDocument xd = new System.Xml.XmlDocument(); xd.LoadXml(ri.LatestVersion.ApprovedXML); string PEIPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\VEPROMS\PEI_" + Database.VEPROMS_SqlConnection.Database; DirectoryInfo di = new DirectoryInfo(PEIPath); if (!di.Exists) di.Create(); // B2022-048: Crash when creating Procedure to Import from versions. Couldn't handle '/' in proc number. - string fNametmp = xd.SelectSingleNode("procedure/content/@number").InnerText.Replace(" ", "_").Replace(@"\u8209?", "-").Replace(@"\u9586?", "_").Replace("/", "-") + ".pxml"; + string fNametmp = $"{xd.SelectSingleNode("procedure/content/@number").InnerText.Replace(" ", "_").Replace(@"\u8209?", "-").Replace(@"\u9586?", "_").Replace("/", "-")}.pxml"; // B2022-112: If applicability, need to resolve the '<' and '>' characters. Just use the UnitNames, i.e. str, from above. if (applIdx > 0) fNametmp = Regex.Replace(fNametmp, @"\", str, RegexOptions.IgnoreCase); - string fileName = PEIPath + "\\" + str + "Approved_Rev_" + ri.RevisionNumber.Replace(" ", "_").Replace("\\", "-").Replace("/", "-") + "_" + fNametmp; + string fileName = $"{PEIPath}\\{str}Approved_Rev_{ri.RevisionNumber.Replace(" ", "_").Replace("\\", "-").Replace("/", "-")}_{fNametmp}"; xd.Save(fileName); FlexibleMessageBox.Show("Approved procedure saved to import file " + fileName, "Creating Export of Approved Procedure", MessageBoxButtons.OK, MessageBoxIcon.Information); } @@ -1605,14 +1274,14 @@ namespace Volian.Controls.Library RevisionConfig rc = ri.MyConfig as RevisionConfig; // bug fix: B2016-183 - add the child's name (ex Unit 1) to the export file name for Parent/Child procedures. int applIdx = rc.Applicability_Index; - string str = (applIdx > 0) ? _currentPri.MyDocVersion.UnitNames[applIdx - 1] + "_" : ""; // if parent/child get the defined child name to include the export filename + string str = (applIdx > 0) ? $"{_currentPri.MyDocVersion.UnitNames[applIdx - 1]}_" : ""; // if parent/child get the defined child name to include the export filename System.Xml.XmlDocument xd = new System.Xml.XmlDocument(); xd.LoadXml(ri.LatestVersion.ApprovedXML); string PEIPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\VEPROMS\PEI_" + Database.VEPROMS_SqlConnection.Database; DirectoryInfo di = new DirectoryInfo(PEIPath); if (!di.Exists) di.Create(); // B2022-048: Crash when creating Procedure to Import from versions. Couldn't handle '/' in proc number. - string fNametmp = xd.SelectSingleNode("procedure/content/@number").InnerText.Replace(" ", "_").Replace(@"\u8209?", "-").Replace(@"\u9586?", "_").Replace("/", "-") + ".pxml"; + string fNametmp = $"{xd.SelectSingleNode("procedure/content/@number").InnerText.Replace(" ", "_").Replace(@"\u8209?", "-").Replace(@"\u9586?", "_").Replace("/", "-")}.pxml"; // B2022-112: If applicability, need to resolve the '<' and '>' characters. Just use the UnitNames, i.e. str, from above. if (applIdx > 0) { @@ -1620,7 +1289,7 @@ namespace Volian.Controls.Library fNametmp = Regex.Replace(fNametmp, @"\", str, RegexOptions.IgnoreCase); } - string fileName = PEIPath + "\\" + str + "Approved_Rev_" + ri.RevisionNumber.Replace(" ", "_").Replace("\\", "-").Replace("/", "-") + "_" + fNametmp; + string fileName = $"{PEIPath}\\{str}Approved_Rev_{ri.RevisionNumber.Replace(" ", "_").Replace("\\", "-").Replace("/", "-")}_{fNametmp}"; xd.Save(fileName); FlexibleMessageBox.Show("Approved procedure saved to import file " + fileName, "Creating Export of Approved Procedure", MessageBoxButtons.OK, MessageBoxIcon.Information); } @@ -1628,8 +1297,8 @@ namespace Volian.Controls.Library //C2025-015 Get a partial folder path. This will be used in building the PDF file name when viewing Approved procedures string ProcFolderPathforApprovedPDF(string fullPath) { - string rtnStr = ""; - try + string rtnStr; + try { // the fullPath string that is passed in ends with the Working Draft node. We want to trim that off string[] strParts = fullPath.Substring(0, fullPath.LastIndexOf("\\")).Split('\\'); //fullPath.Replace("\\Working Draft","").Split('\\'); @@ -1637,7 +1306,7 @@ namespace Volian.Controls.Library rtnStr = strParts[lastPart]; if (rtnStr.ToUpper().StartsWith("UNIT")) { - rtnStr = strParts[lastPart - 1] + "_" + rtnStr; + rtnStr = $"{strParts[lastPart - 1]}_{rtnStr}"; } } catch @@ -1650,9 +1319,8 @@ namespace Volian.Controls.Library void ApprovedRevision_Click(object sender, EventArgs e) { bool superceded = false; - MenuItem mi = sender as MenuItem; - if (mi == null) return; - RevisionInfo ri = mi.Tag as RevisionInfo; + if (!(sender is MenuItem mi)) return; + RevisionInfo ri = mi.Tag as RevisionInfo; { MenuItem mip = mi.Parent as MenuItem; //B2021-086 Added the check for the last revision stage is an Approved stage @@ -1664,14 +1332,12 @@ namespace Volian.Controls.Library string approvedPDFName = string.Format("{0}_{1} Revision {2}", ProcFolderPathforApprovedPDF(prcInfo.SearchDVPath_clean), prcInfo.PDFNumber,ri.RevisionNumber); vlnTreeViewPdfArgs args = new vlnTreeViewPdfArgs(Volian.Base.Library.TmpFile.CreateFileName(approvedPDFName), ri.LatestVersion.PDF, superceded ? "Superceded" : ""); OnViewPDF(sender, args); - // System.Diagnostics.Process pp = System.Diagnostics.Process.Start(GetDocPdf(ri, superceded)); } void MultiUnitApprovedRevision_Click(object sender, EventArgs e) { bool superceded = false; - MenuItem mi = sender as MenuItem; - if (mi == null) return; - string childName = ""; + if (!(sender is MenuItem mi)) return; + string childName = ""; //RevisionInfo ri = mi.Tag as RevisionInfo; RevisionInfo ri = RevisionInfo.Get(int.Parse(mi.Tag.ToString())); { @@ -1698,67 +1364,32 @@ namespace Volian.Controls.Library } void SummaryOfChanges_Click(object sender, EventArgs e) { - MenuItem mi = sender as MenuItem; - if (mi == null) return; - RevisionInfo ri = mi.Tag as RevisionInfo; - vlnTreeViewPdfArgs args = new vlnTreeViewPdfArgs(Volian.Base.Library.TmpFile.CreateFileName(ProcedureInfo.Get(ri.ItemID).PDFNumber + " Summary of Changes"), ri.LatestVersion.SummaryPDF, ""); + if (!(sender is MenuItem mi)) return; + RevisionInfo ri = mi.Tag as RevisionInfo; + vlnTreeViewPdfArgs args = new vlnTreeViewPdfArgs(Volian.Base.Library.TmpFile.CreateFileName($"{ProcedureInfo.Get(ri.ItemID).PDFNumber} Summary of Changes"), ri.LatestVersion.SummaryPDF, ""); OnViewPDF(sender, args); - // System.Diagnostics.Process pps = System.Diagnostics.Process.Start(GetDocSummaryPdf(ri)); } void MultiUnitSummaryOfChanges_Click(object sender, EventArgs e) { - MenuItem mi = sender as MenuItem; - if (mi == null) return; - //RevisionInfo ri = mi.Tag as RevisionInfo; - RevisionInfo ri = RevisionInfo.Get(int.Parse(mi.Tag.ToString())); + if (!(sender is MenuItem mi)) return; + //RevisionInfo ri = mi.Tag as RevisionInfo; + RevisionInfo ri = RevisionInfo.Get(int.Parse(mi.Tag.ToString())); ItemInfo ii = ItemInfo.Get(ri.ItemID); ii.MyDocVersion.DocVersionConfig.SelectedSlave = ri.MyConfig.Applicability_Index; - vlnTreeViewPdfArgs args = new vlnTreeViewPdfArgs(Volian.Base.Library.TmpFile.CreateFileName(ProcedureInfo.Get(ri.ItemID).PDFNumber + " Summary of Changes"), ri.LatestVersion.SummaryPDF, ""); + vlnTreeViewPdfArgs args = new vlnTreeViewPdfArgs(Volian.Base.Library.TmpFile.CreateFileName($"{ProcedureInfo.Get(ri.ItemID).PDFNumber} Summary of Changes"), ri.LatestVersion.SummaryPDF, ""); OnViewPDF(sender, args); - // System.Diagnostics.Process pps = System.Diagnostics.Process.Start(GetDocSummaryPdf(ri)); } //C2018-026 show notes entered during approval or workflow stage private void ViewRevisonStageNotes_Click(object sender, EventArgs e) { - MenuItem mi = sender as MenuItem; - if (mi == null) return; - RevisionInfo ri = mi.Tag as RevisionInfo; + if (!(sender is MenuItem mi)) return; + RevisionInfo ri = mi.Tag as RevisionInfo; FlexibleMessageBox.Show(ri.Notes, "Revison Stage Notes", MessageBoxButtons.OK); } - //private string GetDocPdf(RevisionInfo ri, bool superceded) - //{ - // string fileName = Volian.Base.Library.TmpFile.CreateFileName(ItemInfo.Get(ri.ItemID).DisplayNumber); - // FileInfo fi = new FileInfo(VlnSettings.TemporaryFolder + @"\" + fileName); - // FileStream fs = fi.Create(); - // byte[] myPdf = ri.LatestVersion.PDF; - // if (myPdf != null) fs.Write(myPdf, 0, myPdf.Length); - // fs.Close(); - // if (superceded) - // AddSupercededWatermark(VlnSettings.TemporaryFolder + @"\" + fileName); - // return VlnSettings.TemporaryFolder + @"\" + fileName; - //} - - //private void AddSupercededWatermark(string p) - //{ - // MessageBox.Show("superceded"); - //} - //private string GetDocSummaryPdf(RevisionInfo ri) - //{ - // string fileName = Volian.Base.Library.TmpFile.CreateFileName(ItemInfo.Get(ri.ItemID).DisplayNumber + " Summary of Changes"); - // FileInfo fi = new FileInfo(VlnSettings.TemporaryFolder + @"\" + fileName); - // FileStream fs = fi.Create(); - // byte[] myPdf = ri.LatestVersion.SummaryPDF; - // if (myPdf != null) fs.Write(myPdf, 0, myPdf.Length); - // fs.Close(); - // return VlnSettings.TemporaryFolder + @"\" + fileName; - //} - - private bool AddToInsertMenu(ItemInfo ii, int ba) // 0 = before, 1 = after { // set up insert buttons based on format - bool retB = true; E_AccStep? actable = 0; StepData sd = ii.FormatStepData; if (sd != null) actable = sd.StepEditData.AcTable; @@ -1823,12 +1454,11 @@ namespace Volian.Controls.Library } else { - ItemInfo iiPasteHere = tn.VEObject as ItemInfo; - if (iiPasteHere == null) return; - bool okToReplace = iiClipboard.ItemID != iiPasteHere.ItemID; + if (!(tn.VEObject is ItemInfo iiPasteHere)) return; + bool okToReplace = iiClipboard.ItemID != iiPasteHere.ItemID; if (iiPasteHere != null) { - SectionInfo si = (tn.VEObject as SectionInfo != null) ? tn.VEObject as SectionInfo : null; + SectionInfo si = tn.VEObject as SectionInfo ?? null; #region Menu_Paste_ToFromProcedure if (iiPasteHere.IsProcedure && iiClipboard.IsProcedure) // procedure can be pasted before/replace/after { @@ -2135,11 +1765,10 @@ namespace Volian.Controls.Library } void mi_Click(object sender, EventArgs e) { - MenuItem mi = sender as MenuItem; - if (mi == null) - return; - // B2019-076: make folder/working draft level proc set specific info consistent (various places in this file were changed from Folder Specific & Working Draft Specific) - if (mi.Text == "Procedure Set Specific Information" || mi.Text == "Folder Specific Information") // C2020-008: change to 'Folder' + if (!(sender is MenuItem mi)) + return; + // B2019-076: make folder/working draft level proc set specific info consistent (various places in this file were changed from Folder Specific & Working Draft Specific) + if (mi.Text == "Procedure Set Specific Information" || mi.Text == "Folder Specific Information") // C2020-008: change to 'Folder' { VETreeNode tn = SelectedNode as VETreeNode; OnNodeSI(this, new vlnTreeEventArgs(tn, null, 0)); @@ -2264,7 +1893,6 @@ namespace Volian.Controls.Library if (ovewriteEx == DialogResult.Cancel) break; else { - TreeNode treenodeDirectory = SelectedNode.Parent; tv_NodePaste(mi.Text); break; } @@ -2281,29 +1909,27 @@ namespace Volian.Controls.Library break; case "Incoming Transitions": // C2020-033: Support the menu item to bring up Search/Incoming Transitions panel VETreeNode tnx = SelectedNode as VETreeNode; - ItemInfo iii = tnx.VEObject as ItemInfo; - if (iii != null) - { - this.Cursor = Cursors.WaitCursor; // B2023-103 add spinner when searching for incoming transitions - OnSearchIncTransIn(this, new vlnTreeItemInfoEventArgs(iii)); - this.Cursor = Cursors.Default; - } - break; + if (tnx.VEObject is ItemInfo iii) + { + this.Cursor = Cursors.WaitCursor; // B2023-103 add spinner when searching for incoming transitions + OnSearchIncTransIn(this, new vlnTreeItemInfoEventArgs(iii)); + this.Cursor = Cursors.Default; + } + break; case "Properties..."://Show the properties for the selected node SetLastValues((VETreeNode)SelectedNode); SetupNodeProperties(); break; case "Procedure Specific Information": VETreeNode tn = SelectedNode as VETreeNode; - ProcedureInfo pi = tn.VEObject as ProcedureInfo; - if (pi != null) - { - using (Procedure proc = pi.Get()) - { - OnNodePSI(this, new vlnTreeEventArgs(tn, null, 0)); - } - } - break; + if (tn.VEObject is ProcedureInfo pi) + { + using (Procedure proc = pi.Get()) + { + OnNodePSI(this, new vlnTreeEventArgs(tn, null, 0)); + } + } + break; case "Print": OnPrintProcedure(this, new vlnTreeEventArgs(SelectedNode as VETreeNode, null, 0)); break; @@ -2352,12 +1978,6 @@ namespace Volian.Controls.Library FlexibleMessageBox.Show("You have copied a document that is NOT linked to an Enhanced Document.\n\n" + "You cannot paste a Non-Enhanced Procedure into an Enhanced Procedure Set.", "Cannot Paste Here"); break; - //case "Check Out Procedure Set": - // CheckOutDocVersion(SelectedNode as VETreeNode); - // break; - //case "Check In Procedure Set": - // CheckInDocVersion(SelectedNode as VETreeNode); - // break; case "Print All Approved Procedures": //C2025-017 print all approved procedures OnPrintAllApprovedProcedures(this, new vlnTreeEventArgs(SelectedNode as VETreeNode, null, 0)); break; @@ -2415,13 +2035,6 @@ namespace Volian.Controls.Library { //Console.WriteLine("HERE"); // add code/query to clear change ids in config. } - private Dictionary MyCheckedOutDocVersions; - private void CheckInDocVersion(VETreeNode tn) - { - DocVersionInfo MyDVI = tn.VEObject as DocVersionInfo; - MySessionInfo.CheckInItem(MyCheckedOutDocVersions[MyDVI.VersionID]); - MyCheckedOutDocVersions.Remove(MyDVI.VersionID); - } private void UpdateROValues(VETreeNode tn) { @@ -2436,23 +2049,23 @@ namespace Volian.Controls.Library return; } ROFstInfo roFstInfo = MyDVI.DocVersionAssociations[0].MyROFst; - string rofstPath = roFstInfo.MyRODb.FolderPath + @"\ro.fst"; + string rofstPath = $@"{roFstInfo.MyRODb.FolderPath}\ro.fst"; if (!File.Exists(rofstPath)) { - FlexibleMessageBox.Show("No existing ro.fst in path " + roFstInfo.MyRODb.FolderPath + ". Check for invalid path", "No existing RO.FST"); //B2017-125 added title to messagebox + FlexibleMessageBox.Show($"No existing ro.fst in path {roFstInfo.MyRODb.FolderPath}. Check for invalid path", "No existing RO.FST"); //B2017-125 added title to messagebox FinalProgressBarMessage = "No existing RO.FST"; return; } FileInfo fiRofst = new FileInfo(rofstPath); if (roFstInfo.DTS == fiRofst.LastWriteTimeUtc) { - FlexibleMessageBox.Show("ro.fst files are same for path " + roFstInfo.MyRODb.FolderPath + ", import of that ro.fst will not be done", "RO.FST up to date"); //B2017-125 added title to messagebox + FlexibleMessageBox.Show($"ro.fst files are same for path {roFstInfo.MyRODb.FolderPath}, import of that ro.fst will not be done", "RO.FST up to date"); //B2017-125 added title to messagebox FinalProgressBarMessage = "RO.FST up to date"; return; } if (roFstInfo.DTS > fiRofst.LastWriteTimeUtc) { - FlexibleMessageBox.Show("Cannot copy older ro.fst from " + roFstInfo.MyRODb.FolderPath + ", import of that ro.fst will not be done", "Older RO.FST"); //B2017-125 added title to messagebox + FlexibleMessageBox.Show($"Cannot copy older ro.fst from {roFstInfo.MyRODb.FolderPath}, import of that ro.fst will not be done", "Older RO.FST"); //B2017-125 added title to messagebox FinalProgressBarMessage = "Older RO.FST"; return; } @@ -2520,13 +2133,8 @@ namespace Volian.Controls.Library 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)); } - private ProgressBarItem _ProgressBar = null; - public ProgressBarItem ProgressBar - { - get { return _ProgressBar; } - set { _ProgressBar = value; } - } - private void DoProgressBarRefresh(int value, int max, string text) + public ProgressBarItem ProgressBar { get; set; } = null; + private void DoProgressBarRefresh(int value, int max, string text) { if (ProgressBar == null) return; ProgressBar.Maximum = max; @@ -2556,54 +2164,16 @@ namespace Volian.Controls.Library Application.DoEvents(); } } - public List roFstInfo_ROTableUpdate(object sender, ROFstInfoROTableUpdateEventArgs args) - { - return VlnFlexGrid.ROTableUpdate(sender, 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; - } + public List roFstInfo_ROTableUpdate(object sender, ROFstInfoROTableUpdateEventArgs args) => VlnFlexGrid.ROTableUpdate(sender, args); - private void RunROEditor(VETreeNode tn) + private void RunROEditor(VETreeNode tn) { - DocVersionInfo MyDVI = tn.VEObject as DocVersionInfo; - 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 + 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 if (roapp == null || roapp == string.Empty) { FlexibleMessageBox.Show("The 'roapp' environment variable needs to be set to the path of the RO Editor\n\n Ex: C:\\VE-PROMS.NET\\Bin\\roeditor.exe", "Environment Variable Error"); @@ -2613,20 +2183,14 @@ namespace Volian.Controls.Library { string errtxt = string.Format("Could not find path to Referenced Objects Editor:\n\n roapp = {0}\n\n Verify the path assigned to the 'roapp' environment variable", roapp); FlexibleMessageBox.Show(errtxt, "Environment Variable Error"); - //MessageBox.Show("Could not find path to Ro Editor, check 'roapp' environment variable","Environment Variable Error"); return; } - //if (roapp == null) - //{ - // MessageBox.Show("Could not find path to Ro Editor, check 'roapp' environment variable"); - // return; - //} - if (MyDVI == null || MyDVI.DocVersionAssociationCount < 1) + if (!(tn.VEObject is DocVersionInfo MyDVI) || MyDVI.DocVersionAssociationCount < 1) { FlexibleMessageBox.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 + "\""; + string roloc = $"\"{MyDVI.DocVersionAssociations[0].MyROFst.MyRODb.FolderPath}\""; if (!Directory.Exists(MyDVI.DocVersionAssociations[0].MyROFst.MyRODb.FolderPath)) { FlexibleMessageBox.Show(string.Format("RO Database directory does not exist: {0}", MyDVI.DocVersionAssociations[0].MyROFst.MyRODb.FolderPath)); @@ -2634,7 +2198,7 @@ namespace Volian.Controls.Library } // C2017-003: ro data in sql server, check for sql connection string if (MyDVI.DocVersionAssociations[0].MyROFst.MyRODb.DBConnectionString != "cstring") - roloc = roloc + " \"" + MyDVI.DocVersionAssociations[0].MyROFst.MyRODb.DBConnectionString + "\""; + roloc = $"{roloc} \"{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 @@ -2642,13 +2206,12 @@ namespace Volian.Controls.Library DocVersionInfoList dvil = DocVersionInfoList.Get(); foreach (DocVersionInfo dvi in dvil) { - DocVersionConfig dvc = dvi.DocVersionConfig as DocVersionConfig; - if (dvc != null && dvc.Unit_Name != "" && dvc.Unit_Count > 1) // B2021-089 only pass in applicability info if defined for more than one unit - { - roloc += " \"PC=" + dvc.Unit_Name + "\""; - break; - } - } + if (dvi.DocVersionConfig is DocVersionConfig dvc && dvc.Unit_Name != "" && dvc.Unit_Count > 1) // B2021-089 only pass in applicability info if defined for more than one unit + { + roloc += $" \"PC={dvc.Unit_Name}\""; + break; + } + } System.Diagnostics.Process.Start(roapp, roloc); } @@ -2685,36 +2248,34 @@ namespace Volian.Controls.Library } VETreeNode tn = SelectedNode as VETreeNode; - DocVersionInfo dvi = tn.VEObject as DocVersionInfo; - // Check for paste into a docversion - queries/code is different than paste related to an item (into a proc or section) - if (dvi != null) - { - // If the docversion has procedures (children), change to a 'paste-after the last procedure'. - if (tn.Nodes.Count > 0) - { - // if the node count is 1, children may not have been loaded yet - load if necessary: - if (tn.Nodes.Count == 1 && tn.Nodes[0].Text.ToUpper().Contains("DUMMY VETREENODE")) - tn.LoadChildren(); + // Check for paste into a docversion - queries/code is different than paste related to an item (into a proc or section) + if (tn.VEObject is DocVersionInfo) + { + // If the docversion has procedures (children), change to a 'paste-after the last procedure'. + if (tn.Nodes.Count > 0) + { + // if the node count is 1, children may not have been loaded yet - load if necessary: + if (tn.Nodes.Count == 1 && tn.Nodes[0].Text.ToUpper().Contains("DUMMY VETREENODE")) + tn.LoadChildren(); - // assume that item to paste is a procedure, otherwise the menuing would not have - // included the paste options - tn = (VETreeNode)tn.Nodes[tn.Nodes.Count - 1]; - p = "After"; - } - else // this is an empty docversion: - { - // First check if the doc version has RO's - // Paste as a child to the doc version: - this.Cursor = Cursors.WaitCursor; - PasteAsDocVersionChild(tn, iiClipboard.ItemID); - this.Cursor = Cursors.Default; - return; - } - } + // assume that item to paste is a procedure, otherwise the menuing would not have + // included the paste options + tn = (VETreeNode)tn.Nodes[tn.Nodes.Count - 1]; + p = "After"; + } + else // this is an empty docversion: + { + // First check if the doc version has RO's + // Paste as a child to the doc version: + this.Cursor = Cursors.WaitCursor; + PasteAsDocVersionChild(tn, iiClipboard.ItemID); + this.Cursor = Cursors.Default; + return; + } + } - ItemInfo iiPaste = tn.VEObject as ItemInfo; - if (iiPaste == null) return; - this.Cursor = Cursors.WaitCursor; + if (!(tn.VEObject is ItemInfo iiPaste)) return; + this.Cursor = Cursors.WaitCursor; if (p.IndexOf("Before") > -1) PasteBeforeOrAfter(MenuSelections.StepBefore, tn, iiClipboard.ItemID); else if (p.IndexOf("After") > -1) @@ -2725,9 +2286,8 @@ namespace Volian.Controls.Library VETreeNode tmp = null; if (OnlyProc) { - VETreeNode tnp = SelectedNode as VETreeNode; - tmp = tnp == null ? null : tnp.Parent as VETreeNode; - } + tmp = !(SelectedNode is VETreeNode tnp) ? null : tnp.Parent as VETreeNode; + } ItemInfo repitem = PasteReplace(tn, iiClipboard.ItemID); // B2024-045, 049 and 050: The treenode was passed into the business object's replace but sometimes it was null. And this // wasn't working if it was a single procedure in a working Draft. Adjust the tree here if single procedure in working draft. @@ -2755,8 +2315,8 @@ namespace Volian.Controls.Library // Set docversionassociation to the copied docversion association // so that the rofst for ro's can be found. (if there is no association set) ROFstInfo rfi = GetAssociationRofstId(copyStartID); - Association myAs = Association.MakeAssociation(dvi.Get(), rfi.GetJustROFst(), ""); - dvi.RefreshDocVersionAssociations(); + _ = Association.MakeAssociation(dvi.Get(), rfi.GetJustROFst(), ""); + dvi.RefreshDocVersionAssociations(); } ItemInfo newProc = dvi.PasteChild(copyStartID); VETreeNode tn1 = new VETreeNode(newProc); @@ -2786,14 +2346,13 @@ namespace Volian.Controls.Library // The parent step was not open in the step editor, just paste step (in data) and add treenode. // first, check if a changeid is required. string chgId = OnGetChangeId(this, new vlnTreeItemInfoEventArgs(ii)); - ItemInfo newItemInfo = null; - newItemInfo = ii.PasteChild(copyStartID, chgId); + ItemInfo newItemInfo = ii.PasteChild(copyStartID, chgId); if (newItemInfo != null) { // paste enhanced steps if applicable (this code is only run if a step is pasted, not for a section). ItemInfo.EAddpingPart addpart = ItemInfo.EAddpingPart.Child; - ItemInfo newEnhStep = newItemInfo.PasteEnhancedItems(copyStartID, ii, addpart, chgId); - } + _ = newItemInfo.PasteEnhancedItems(copyStartID, ii, addpart, chgId); + } } if (pasteSectIntoEmptySect) { @@ -2808,11 +2367,11 @@ namespace Volian.Controls.Library // to the step editor panel. ItemInfo ii = tn.VEObject as ItemInfo; ItemInfo.EAddpingPart pasteOpt = newtype == MenuSelections.StepBefore ? ItemInfo.EAddpingPart.Before : ItemInfo.EAddpingPart.After; - // If parent step is open in step editor, the 'OnPasteItemInfo' event will cause - // the item to be pasted in the step editor and the tree. - ItemInfo newItemInfo = null; - // F2021-009 display a message if pasting step will results in more sub-step levels than are defined in the format - if (!ii.IsProcedure) + // If parent step is open in step editor, the 'OnPasteItemInfo' event will cause + // the item to be pasted in the step editor and the tree. + ItemInfo newItemInfo; + // F2021-009 display a message if pasting step will results in more sub-step levels than are defined in the format + if (!ii.IsProcedure) ItemInfo.PasteStepIsWithinDefinedSubStepLevels(copyStartID, ii, false); if (ii.IsProcedure || !OnPasteItemInfo(this, new vlnTreeItemInfoPasteEventArgs(ii, copyStartID, pasteOpt, ii.MyContent.Type))) { @@ -2828,8 +2387,8 @@ namespace Volian.Controls.Library // paste enhanced steps if applicable (this code is only run if a step is pasted, not for a section). ItemInfo.EAddpingPart addpart = ItemInfo.EAddpingPart.After; if (newtype == MenuSelections.StepBefore) addpart = ItemInfo.EAddpingPart.Before; - ItemInfo newEnhStep = newItemInfo.PasteEnhancedItems(copyStartID, ii, addpart, chgId); - } + _ = newItemInfo.PasteEnhancedItems(copyStartID, ii, addpart, chgId); + } } SelectedNode = (VETreeNode)((newtype == MenuSelections.StepAfter) ? tn.NextNode : tn.PrevNode); } @@ -2847,10 +2406,12 @@ namespace Volian.Controls.Library string chgId = OnGetChangeId(this, new vlnTreeItemInfoEventArgs(ii)); replItemInfo = Item.PasteReplace(ii, copyStartID, chgId); - StepConfig replItemConfig = ii.MyConfig as StepConfig; - if (replItemInfo != null) + #pragma warning disable IDE0059 // Unnecessary assignment of a - For Debugging/To save preexisting config + StepConfig replItemConfig = ii.MyConfig as StepConfig; + #pragma warning restore IDE0059 // Unnecessary assignment of a value + if (replItemInfo != null) { - ItemInfo newEnhStep = replItemInfo.PasteEnhancedItems(copyStartID, ii, ItemInfo.EAddpingPart.Replace, chgId); + _ = replItemInfo.PasteEnhancedItems(copyStartID, ii, ItemInfo.EAddpingPart.Replace, chgId); } } // B2018-047: was crashing on the following line (before change it was casting the result to a VETreeNote when the partn.FirstNode was just a TreeNode) @@ -2867,8 +2428,8 @@ namespace Volian.Controls.Library // Set docversionassociation to the copied docversion association // so that the rofst for ro's can be found. (if there is no association set) ROFstInfo rfi = GetAssociationRofstId(copyStartID); - Association myAs = Association.MakeAssociation(dvi.Get(), rfi.GetJustROFst(), ""); - dvi.RefreshDocVersionAssociations(); + _ = Association.MakeAssociation(dvi.Get(), rfi.GetJustROFst(), ""); + dvi.RefreshDocVersionAssociations(); } ItemInfo newProc = dvi.PasteChild(copyStartID); VETreeNode tn1 = new VETreeNode(newProc); @@ -2886,10 +2447,9 @@ namespace Volian.Controls.Library #region PropertyPagesInterface private void SetupNodeProperties() { - VETreeNode tn = SelectedNode as VETreeNode; - if (tn == null) return; + if (!(SelectedNode is VETreeNode tn)) return; - if ((tn.VEObject as FolderInfo) != null) + if ((tn.VEObject as FolderInfo) != null) OpenProperties(tn.VEObject as FolderInfo); else if ((tn.VEObject as DocVersionInfo) != null) { @@ -2943,12 +2503,6 @@ namespace Volian.Controls.Library OnNodeOpenProperty(this, new vlnTreePropertyEventArgs(title, sect.SectionConfig)); } } - private void OpenProperties(StepInfo stpinfo) - { - using (Step stp = stpinfo.Get()) - { - } - } #endregion #region OpenNode @@ -2962,22 +2516,21 @@ namespace Volian.Controls.Library } public void OpenNode() { - VETreeNode tn = SelectedNode as VETreeNode; - if (tn != null) - { - if (tn.VEObject.GetType() == typeof(FolderInfo) || tn.VEObject.GetType() == typeof(DocVersionInfo) || tn.VEObject.GetType() == typeof(PartInfo)) - { - if (tn.Nodes.Count > 0) - { - tn.Expand(); - SelectedNode = tn.Nodes[0]; - Focus(); - } - } - else - OnNodeSelect(this, new vlnTreeEventArgs(SelectedNode)); - } - } + if (SelectedNode is VETreeNode tn) + { + if (tn.VEObject.GetType() == typeof(FolderInfo) || tn.VEObject.GetType() == typeof(DocVersionInfo) || tn.VEObject.GetType() == typeof(PartInfo)) + { + if (tn.Nodes.Count > 0) + { + tn.Expand(); + SelectedNode = tn.Nodes[0]; + Focus(); + } + } + else + OnNodeSelect(this, new vlnTreeEventArgs(SelectedNode)); + } + } #endregion #region InsertAllLevels public void tv_NodeNew(MenuSelections newtype) @@ -3079,7 +2632,7 @@ namespace Volian.Controls.Library tn = new VETreeNode(_LastProcedureInfo); SelectedNode.Nodes.Add(tn); // add tree node to end of list. // The following line will allow for a refresh of the procedure list on the Working Draft's treenodes docversion (B2016-034) - if (((SelectedNode as VETreeNode).VEObject as DocVersionInfo) != null) ((SelectedNode as VETreeNode).VEObject as DocVersionInfo).ResetProcedures(); + ((SelectedNode as VETreeNode).VEObject as DocVersionInfo)?.ResetProcedures(); if (procedure.MyProcedureInfo.CreateEnhanced) { procedure.MyProcedureInfo.CreateEnhanced = false; @@ -3110,7 +2663,7 @@ namespace Volian.Controls.Library TreeNode par = SelectedNode.Parent; par.Nodes.Insert(tvindex + ((newtype == MenuSelections.ProcedureBefore) ? 0 : 1), tn); // The following line will allow for a refresh of the procedure list on the Working Draft's treenodes docversion (B2016-034) - if (((par as VETreeNode).VEObject as DocVersionInfo) != null) ((par as VETreeNode).VEObject as DocVersionInfo).ResetProcedures(); + ((par as VETreeNode).VEObject as DocVersionInfo)?.ResetProcedures(); if (procedure.MyProcedureInfo.CreateEnhanced) { procedure.MyProcedureInfo.CreateEnhanced = false; @@ -3199,7 +2752,6 @@ namespace Volian.Controls.Library { // may have to add a 'steps' node if a step(s) already exist... ItemInfo ii = (SelectedNode as VETreeNode).VEObject as ItemInfo; - int cpindx = 0; if (SelectedNode.Nodes.Count > 0) { VETreeNode vtn = SelectedNode.Nodes[0] as VETreeNode; @@ -3336,10 +2888,11 @@ namespace Volian.Controls.Library return; } } - // do the following code if insert the procedure from docverion, or if no linked procedure was found above while doing an insert section from before/after - DocVersionConfig dvc = sourceProc.MyProcedureInfo.MyDocVersion.MyConfig as DocVersionConfig; - ProcedureConfig sourcecfg = sourceProc.ProcedureConfig; - if (dvc != null) + // do the following code if insert the procedure from docverion, or if no linked procedure was found above while doing an insert section from before/after + #pragma warning disable IDE0059 // Unnecessary assignment of a value - For Debugging/To save preexisting config + ProcedureConfig sourcecfg = sourceProc.ProcedureConfig; + #pragma warning restore IDE0059 // Unnecessary assignment of a value + if (sourceProc.MyProcedureInfo.MyDocVersion.MyConfig is DocVersionConfig dvc) { foreach (DVEnhancedDocument ded in dvc.MyEnhancedDocuments) { @@ -3413,10 +2966,11 @@ namespace Volian.Controls.Library return; } } - // do the following code if insert the section from the procedure, or if no linked section was found above while doing an insert section from before/after - ProcedureConfig pc = sourceSect.MyItemInfo.MyProcedure.MyConfig as ProcedureConfig; - SectionConfig sourcecfg = sourceSect.SectionConfig; - if (pc != null) + // do the following code if insert the section from the procedure, or if no linked section was found above while doing an insert section from before/after + #pragma warning disable IDE0059 // Unnecessary assignment of a value - For Debugging/To save preexisting config + SectionConfig sourcecfg = sourceSect.SectionConfig; + #pragma warning restore IDE0059 // Unnecessary assignment of a value + if (sourceSect.MyItemInfo.MyProcedure.MyConfig is ProcedureConfig pc) { foreach (EnhancedDocument ed in pc.MyEnhancedDocuments) { @@ -3463,19 +3017,18 @@ namespace Volian.Controls.Library private Section CreateNewSection() { - // B2020-087 the config for SubSection_Edit was sometimes set even when there wasn't any subsections, - // so make sure it's cleared if there are no existing subsections - SectionConfig sc = _LastItemInfo.MyConfig as SectionConfig; - if (sc != null && sc.SubSection_Edit == "Y" && _LastItemInfo.Sections == null) - { - sc.SubSection_Edit = null; - using (Section mysect = Section.Get(_LastItemInfo.ItemID)) - { - mysect.MyContent.Config = sc.ToString(); - mysect.Save(); - } - } - if (_LastItemInfo.LastChild(E_FromType.Section) != null) + // B2020-087 the config for SubSection_Edit was sometimes set even when there wasn't any subsections, + // so make sure it's cleared if there are no existing subsections + if (_LastItemInfo.MyConfig is SectionConfig sc && sc.SubSection_Edit == "Y" && _LastItemInfo.Sections == null) + { + sc.SubSection_Edit = null; + using (Section mysect = Section.Get(_LastItemInfo.ItemID)) + { + mysect.MyContent.Config = sc.ToString(); + mysect.Save(); + } + } + if (_LastItemInfo.LastChild(E_FromType.Section) != null) return Section.MakeSection(_LastItemInfo, _LastItemInfo.LastChild(E_FromType.Section), null, "New Section", 10000); ItemInfo iii = _LastItemInfo.InsertChild(E_FromType.Section, 10000, "New Section", null); return Section.Get(iii.ItemID); @@ -3503,8 +3056,7 @@ namespace Volian.Controls.Library int topType = ii.GetSmartTemplateTopLevelIndxOfThisType(20002); if (topType != -1) { - ItemInfo tmp = null; - tmp = ii.InsertSmartTemplateSubStep("New Step", null, null, ItemInfo.EAddpingPart.Child, 20002, E_FromType.Step); + ItemInfo tmp = ii.InsertSmartTemplateSubStep("New Step", null, null, ItemInfo.EAddpingPart.Child, 20002, E_FromType.Step); newId = tmp.ItemID; } else @@ -3525,34 +3077,33 @@ namespace Volian.Controls.Library par.Nodes.Insert(0, tn); } - // see if enhanced related steps need created: - SectionConfig scfgE = _LastItemInfo.ActiveSection.MyConfig as SectionConfig; // C2018-003 fixed use of getting the active section - if (scfgE != null && scfgE.Section_LnkEnh == "Y") - { - // set up which item to insert from based on whether editor was open (see comment from 11/17 above). - EnhancedDocuments enhdocs = null; - ItemInfo.EAddpingPart addpart = ItemInfo.EAddpingPart.Child; - if (_LastItemInfo.MyPrevious != null) // the code above will do the MakeStep regardless of whether editor is up if this is the only step. - { - addpart = ItemInfo.EAddpingPart.After; - ItemInfo lstSrc = _LastItemInfo.MyPrevious; - StepConfig stcfg = lstSrc.MyConfig as StepConfig; - if (stcfg == null) enhdocs = scfgE.MyEnhancedDocuments; - else enhdocs = stcfg.MyEnhancedDocuments; - } - else - { - enhdocs = scfgE.MyEnhancedDocuments; - } - foreach (EnhancedDocument ed in enhdocs) - { - // the new source step's item is passed in to know what type & what to link to. - // The ed.Type & itemid show what type of enhanced document (used to create new - // config Type) - _LastItemInfo.DoAddEnhancedSteps(ed.Type, ed.ItemID, addpart); - } - } - return tn; + // see if enhanced related steps need created: + // C2018-003 fixed use of getting the active section + if (_LastItemInfo.ActiveSection.MyConfig is SectionConfig scfgE && scfgE.Section_LnkEnh == "Y") + { + // set up which item to insert from based on whether editor was open (see comment from 11/17 above). + EnhancedDocuments enhdocs; + ItemInfo.EAddpingPart addpart = ItemInfo.EAddpingPart.Child; + if (_LastItemInfo.MyPrevious != null) // the code above will do the MakeStep regardless of whether editor is up if this is the only step. + { + addpart = ItemInfo.EAddpingPart.After; + ItemInfo lstSrc = _LastItemInfo.MyPrevious; + if (!(lstSrc.MyConfig is StepConfig stcfg)) enhdocs = scfgE.MyEnhancedDocuments; + else enhdocs = stcfg.MyEnhancedDocuments; + } + else + { + enhdocs = scfgE.MyEnhancedDocuments; + } + foreach (EnhancedDocument ed in enhdocs) + { + // the new source step's item is passed in to know what type & what to link to. + // The ed.Type & itemid show what type of enhanced document (used to create new + // config Type) + _LastItemInfo.DoAddEnhancedSteps(ed.Type, ed.ItemID, addpart); + } + } + return tn; } private VETreeNode InsertBeforeOrAfter(MenuSelections newtype, VETreeNode tn) @@ -3636,7 +3187,7 @@ namespace Volian.Controls.Library return false; } //C2020-026 specific description of what user is trying to delete - typeDescription = "\"" + _LastStepInfo.FormatStepData.StepEditData.TypeMenu.MenuItem + "\""; + typeDescription = $"\"{_LastStepInfo.FormatStepData.StepEditData.TypeMenu.MenuItem}\""; if (_LastStepInfo.HasChildren) typeDescription += " and its substeps"; } if (_LastSectionInfo != null) @@ -3662,7 +3213,7 @@ namespace Volian.Controls.Library if (_LastDocVersionInfo != null) { StringBuilder sb = new StringBuilder(); - foreach (ProcedureInfo pi in _LastDocVersionInfo.Procedures) + foreach (ProcedureInfo pi in _LastDocVersionInfo.Procedures.OfType()) { if (!MySessionInfo.CanCheckOutItem(pi.ItemID, CheckOutType.Procedure, ref message)) sb.AppendLine(message); @@ -3682,7 +3233,7 @@ namespace Volian.Controls.Library { foreach (DocVersionInfo dvi in _LastFolderInfo.FolderDocVersions) { - foreach (ProcedureInfo pi in dvi.Procedures) + foreach (ProcedureInfo pi in dvi.Procedures.OfType()) { if (!MySessionInfo.CanCheckOutItem(pi.ItemID, CheckOutType.Procedure, ref message)) sb.AppendLine(message); @@ -3701,7 +3252,7 @@ namespace Volian.Controls.Library DialogResult result = DialogResult.No; if (_LastProcedureInfo == null) { - result = FlexibleMessageBox.Show("Are you sure you want to delete this " + typeDescription + "?", "Verify Delete", + result = FlexibleMessageBox.Show($"Are you sure you want to delete this {typeDescription}?", "Verify Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question); } if (_LastProcedureInfo != null || result == DialogResult.Yes) @@ -3714,32 +3265,31 @@ namespace Volian.Controls.Library } else if (_LastDocVersionInfo != null) { - // if this has enhanced linked DocVersions, delete them first. - DocVersionConfig dvc = _LastDocVersionInfo.MyConfig as DocVersionConfig; - if (dvc != null && dvc.MyEnhancedDocuments != null && dvc.MyEnhancedDocuments.Count > 0) - { - foreach (DVEnhancedDocument dve in dvc.MyEnhancedDocuments) - { - if (dve.Type != 0) - DocVersion.Delete(dve.VersionID); - else - { - // B2018-025: for the input source docversion (id), clear out its enhanced document link information - // dvi is the source, remove this (_LastDocVersionInfo) background link from the source's config - DocVersionInfo dvi = DocVersionInfo.Get(dve.VersionID); - DocVersionConfig dvci = dvi.MyConfig as DocVersionConfig; - dvci.RemoveEnhancedLink(_LastDocVersionInfo.VersionID); - string dvccfg = dvci.ToString(); - using (DocVersion dv = dvi.Get()) - { - dv.Config = dvccfg; - dv.Save(); - DocVersionInfo.Refresh(dv); - } - } - } - } - DocVersion.Delete(_LastDocVersionInfo.VersionID); + // if this has enhanced linked DocVersions, delete them first. + if (_LastDocVersionInfo.MyConfig is DocVersionConfig dvc && dvc.MyEnhancedDocuments != null && dvc.MyEnhancedDocuments.Count > 0) + { + foreach (DVEnhancedDocument dve in dvc.MyEnhancedDocuments) + { + if (dve.Type != 0) + DocVersion.Delete(dve.VersionID); + else + { + // B2018-025: for the input source docversion (id), clear out its enhanced document link information + // dvi is the source, remove this (_LastDocVersionInfo) background link from the source's config + DocVersionInfo dvi = DocVersionInfo.Get(dve.VersionID); + DocVersionConfig dvci = dvi.MyConfig as DocVersionConfig; + dvci.RemoveEnhancedLink(_LastDocVersionInfo.VersionID); + string dvccfg = dvci.ToString(); + using (DocVersion dv = dvi.Get()) + { + dv.Config = dvccfg; + dv.Save(); + DocVersionInfo.Refresh(dv); + } + } + } + } + DocVersion.Delete(_LastDocVersionInfo.VersionID); _LastDocVersionInfo = null; (((VETreeNode)SelectedNode.Parent).VEObject as FolderInfo).RefreshFolderDocVersions(); // B2018-082 tell tree node that it no longer has a working draft return true; @@ -3869,34 +3419,29 @@ namespace Volian.Controls.Library public void RemoveFolder(int folderId) { TreeNode nodeToRemove = FindNodeById(folderId, this.Nodes); - if (nodeToRemove != null) - { - // Perform the removal logic - nodeToRemove.Remove(); // This removes the node from its parent - } - } + // Perform the removal logic + nodeToRemove?.Remove(); // This removes the node from its parent + } private TreeNode FindNodeById(int folderId, TreeNodeCollection nodes) { foreach (TreeNode node in nodes) { - VETreeNode vetNode = node as VETreeNode; - if (vetNode != null) - { - FolderInfo folderInfo = vetNode.VEObject as FolderInfo; - if (folderInfo != null && folderInfo.FolderID == folderId) - { - return node; - } - else - { - TreeNode foundNode = FindNodeById(folderId, node.Nodes); - if (foundNode != null) - { - return foundNode; - } - } - } - } + if (node is VETreeNode vetNode) + { + if (vetNode.VEObject is FolderInfo folderInfo && folderInfo.FolderID == folderId) + { + return node; + } + else + { + TreeNode foundNode = FindNodeById(folderId, node.Nodes); + if (foundNode != null) + { + return foundNode; + } + } + } + } return null; } @@ -3918,18 +3463,17 @@ namespace Volian.Controls.Library OnProcessingComplete(dtStart, "Deleted"); if (deletedSection) { - // B2020-087 if we deleted the last sub section, then clear the SubSection_Edit in the parent's config - SectionConfig sc = pii.MyConfig as SectionConfig; - if (sc != null && sc.SubSection_Edit == "Y" && pii.Sections == null) // B2020-103: Added null check - { - sc.SubSection_Edit = null; - using (Section mysect = Section.Get(pii.ItemID)) - { - mysect.MyContent.Config = sc.ToString(); - mysect.Save(); - } - } - } + // B2020-087 if we deleted the last sub section, then clear the SubSection_Edit in the parent's config + if (pii.MyConfig is SectionConfig sc && sc.SubSection_Edit == "Y" && pii.Sections == null) // B2020-103: Added null check + { + sc.SubSection_Edit = null; + using (Section mysect = Section.Get(pii.ItemID)) + { + mysect.MyContent.Config = sc.ToString(); + mysect.Save(); + } + } + } return true; } catch (System.Data.SqlClient.SqlException ex) @@ -3941,8 +3485,10 @@ namespace Volian.Controls.Library { ItemInfo iis = ItemInfo.Get(ii.ItemID); OnSearchIncTransIn(this, new vlnTreeItemInfoEventArgs(iis)); - iis = ii.HandleSqlExceptionOnDelete(ex); - } + #pragma warning disable IDE0059 // Unnecessary assignment of a value - For Dubugging + iis = ii.HandleSqlExceptionOnDelete(ex); + #pragma warning restore IDE0059 // Unnecessary assignment of a value + } else { ItemInfo iii = ii.HandleSqlExceptionOnDelete(ex); @@ -3952,27 +3498,15 @@ namespace Volian.Controls.Library } } public event vlnTreeViewTimeEvent ProcessingComplete; - private void OnProcessingComplete(DateTime dtStart, string message) - { - if (ProcessingComplete != null) - ProcessingComplete(this, new vlnTreeTimeEventArgs(dtStart, message)); - } - public event vlnTreeViewStatusEvent Processing; - private void OnProcessing(bool status, string message) - { - if (Processing != null) - Processing(this, new vlnTreeStatusEventArgs(status, message)); - } - //C2021-035 Add Refresh Tree Option at highest level - public event vlnTreeViewStatusEvent RefreshFormats; - private void OnRefreshFormats(bool status, string message) - { - if (RefreshFormats != null) - RefreshFormats(this, new vlnTreeStatusEventArgs(status, message)); - } - #endregion - #region SetLastValuesAndSaveIfChangedStuff - private void SetLastValues(VETreeNode node) + private void OnProcessingComplete(DateTime dtStart, string message) => ProcessingComplete?.Invoke(this, new vlnTreeTimeEventArgs(dtStart, message)); + public event vlnTreeViewStatusEvent Processing; + private void OnProcessing(bool status, string message) => Processing?.Invoke(this, new vlnTreeStatusEventArgs(status, message)); + //C2021-035 Add Refresh Tree Option at highest level + public event vlnTreeViewStatusEvent RefreshFormats; + private void OnRefreshFormats(bool status, string message) => RefreshFormats?.Invoke(this, new vlnTreeStatusEventArgs(status, message)); + #endregion + #region SetLastValuesAndSaveIfChangedStuff + private void SetLastValues(VETreeNode node) { _LastTreeNode = node; SetLastValues(node.VEObject); @@ -4008,7 +3542,6 @@ namespace Volian.Controls.Library // Draw node label into bitmap gfx.DrawString(tn.Text, this.Font, new SolidBrush(this.ForeColor), - // new SolidBrush(Color.Blue), (float)this.Indent, 1.0f); // Add bitmap to imagelist @@ -4049,8 +3582,7 @@ namespace Volian.Controls.Library FlexibleMessageBox.Show("Cannot drag/drop a grouping node."); return; } - // don't put up message, message kept coming up on any selection of node (to copy, properties, etc) - //if (iidrag != null && iidrag.IsStep) return; + // don't put up message, message kept coming up on any selection of node (to copy, properties, etc) if (SetupDragCursor(_dragImageList, dragNode)) { this.DoDragDrop(dragNode, DragDropEffects.Move | DragDropEffects.Copy);// Begin dragging @@ -4062,86 +3594,65 @@ namespace Volian.Controls.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("tv_ItemDrag", ex); } } - #endregion - #region DragDrop - ImageList _dragImageList = new ImageList(); + #endregion + #region DragDrop + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + ImageList _dragImageList = new ImageList(); public enum DropPosition : int { Child = 0, Before = 1, After = 2 } private class DropLocation { - #region Business Methods - private TreeNode _dropNode; - public TreeNode DropNode - { - get { return _dropNode; } - set { _dropNode = value; } - } - private int _index; - public int Index - { - get { return _index; } - set { _index = value; } - } - private DropPosition _position; - public DropPosition Position - { - get { return _position; } - set { _position = value; } - } - DateTime _lastScroll; - public DateTime LastScroll - { - get { return _lastScroll; } - } - private string _location = string.Empty; + #region Business Methods + public TreeNode DropNode { get; set; } + public int Index { get; set; } + public DropPosition Position { get; set; } + DateTime _lastScroll; + public DateTime LastScroll => _lastScroll; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "For Dubugging")] + private string _location; //Holds location for Dubugging #endregion #region Constructors public DropLocation(TreeView tv, System.Windows.Forms.DragEventArgs e, DateTime lastScroll) { _lastScroll = lastScroll; - _dropNode = tv.GetNodeAt(tv.PointToClient(new Point(e.X, e.Y))); - if (_dropNode == null) return; - int OffsetY = tv.PointToClient(Cursor.Position).Y - _dropNode.Bounds.Top; - if (OffsetY < _dropNode.Bounds.Height / 3) // First Third - Before + DropNode = tv.GetNodeAt(tv.PointToClient(new Point(e.X, e.Y))); + if (DropNode == null) return; + int OffsetY = tv.PointToClient(Cursor.Position).Y - DropNode.Bounds.Top; + if (OffsetY < DropNode.Bounds.Height / 3) // First Third - Before { - _index = _dropNode.Index; - _dropNode = _dropNode.Parent; - _position = DropPosition.Before; - _location = string.Format("Before1 {0}[{1}] y={2}", _dropNode.Text, _index, OffsetY); + Index = DropNode.Index; + DropNode = DropNode.Parent; + Position = DropPosition.Before; + _location = string.Format("Before1 {0}[{1}] y={2}", DropNode.Text, Index, OffsetY); } - else if ((OffsetY / 2) < _dropNode.Bounds.Height / 3) // Second Third - Child + else if ((OffsetY / 2) < DropNode.Bounds.Height / 3) // Second Third - Child { - _location = string.Format("Child {0} y={1}", _dropNode.Text, OffsetY); - _position = DropPosition.Child; - _index = 0; - //if (_dropNode.Parent == null) - //{ - // if(_MyLog.IsInfoEnabled)_MyLog.Info("Root Node"); - //} + _location = string.Format("Child {0} y={1}", DropNode.Text, OffsetY); + Position = DropPosition.Child; + Index = 0; } else // Last Third - After Now I need to check the X value { - if (_dropNode.NextVisibleNode != null && _dropNode.Nodes.Count > 0 && _dropNode.IsExpanded)// Has Children & Expanded - Insert first child + if (DropNode.NextVisibleNode != null && DropNode.Nodes.Count > 0 && DropNode.IsExpanded)// Has Children & Expanded - Insert first child { - // _dropNode = _dropNode.Nodes[0]; - _index = 0; - _position = DropPosition.Before; - _location = string.Format("Before2 {0}[{1}] y={2}", _dropNode.Text, _index, OffsetY); + Index = 0; + Position = DropPosition.Before; + _location = string.Format("Before2 {0}[{1}] y={2}", DropNode.Text, Index, OffsetY); } else // No Children or Children Collapsed - Insert Next at various levels depending upon horizontal location. { Point pt = tv.PointToClient(new Point(e.X, e.Y)); - TreeNode nextParent = _dropNode.NextNode; + TreeNode nextParent = DropNode.NextNode; if (nextParent != null) nextParent = nextParent.Parent; do { - _index = _dropNode.Index; - _dropNode = _dropNode.Parent; - } while (pt.X < _dropNode.Bounds.X && _dropNode != nextParent); - _location = string.Format("After {0}[{1}] y={2}", _dropNode.Text, _index, OffsetY); - _position = DropPosition.After; + Index = DropNode.Index; + DropNode = DropNode.Parent; + } while (pt.X < DropNode.Bounds.X && DropNode != nextParent); + _location = string.Format("After {0}[{1}] y={2}", DropNode.Text, Index, OffsetY); + Position = DropPosition.After; } } LimitMoves(e); @@ -4150,33 +3661,31 @@ namespace Volian.Controls.Library { if ((e.KeyState & 8) == 0) { - //TreeNode dragNode = (TreeNode)e.Data.GetData("System.Windows.Forms.TreeNode"); - //TreeNode dragNode = (TreeNode)e.Data.GetData("TreeTest.FolderTreeNode"); TreeNode dragNode = vlnTreeView.GetTreeNodeFromData(e.Data); - switch (_position) + switch (Position) { case DropPosition.Before: - if (dragNode == _dropNode.Nodes[_index] || dragNode == _dropNode.Nodes[_index].PrevNode) + if (dragNode == DropNode.Nodes[Index] || dragNode == DropNode.Nodes[Index].PrevNode) { // if(_MyLog.IsInfoEnabled)_MyLog.InfoFormat("Before {0} {1} {2} {3} {4}", dragNode.Text ,_position.ToString() , _dropNode.Nodes[_index].Text // ,_dropNode.Nodes[_index].PrevNode,_dropNode.Nodes[_index].NextNode); - _dropNode = null; + DropNode = null; } break; case DropPosition.Child: - if (dragNode.Parent == _dropNode) + if (dragNode.Parent == DropNode) { // if(_MyLog.IsInfoEnabled)_MyLog.InfoFormat("Child {0} {1} {2} {3} {4} {5}", dragNode.Text ,_position.ToString() , _dropNode.Nodes[_index].Text // ,_dropNode.Nodes[_index].PrevNode,_dropNode.Nodes[_index].NextNode,DateTime.Now); - _dropNode = null; + DropNode = null; } break; case DropPosition.After: - if (dragNode == _dropNode.Nodes[_index] || dragNode == _dropNode.Nodes[_index].NextNode) + if (dragNode == DropNode.Nodes[Index] || dragNode == DropNode.Nodes[Index].NextNode) { // if(_MyLog.IsInfoEnabled)_MyLog.InfoFormat("After {0} {1} {2} {3} {4}", dragNode.Text ,_position.ToString() , _dropNode.Nodes[_index].Text // ,_dropNode.Nodes[_index].PrevNode,_dropNode.Nodes[_index].NextNode); - _dropNode = null; + DropNode = null; } break; } @@ -4185,12 +3694,12 @@ namespace Volian.Controls.Library #endregion public override string ToString() { - return string.Format("{0}[{1}].{2}", _dropNode.Text, _index, _position.ToString()); + return string.Format("{0}[{1}].{2}", DropNode.Text, Index, Position.ToString()); } #region Drawing private void TreeNodeTriangle(Graphics g) { - Rectangle r = _dropNode.Bounds; + Rectangle r = DropNode.Bounds; int RightPos = r.Right + 6; Point[] RightTriangle = new Point[]{ new Point(RightPos, r.Y ), @@ -4202,10 +3711,10 @@ namespace Volian.Controls.Library } private void InsertPointer(TreeNode tn, Graphics g) { - TreeView tv = _dropNode.TreeView; - Rectangle r2 = _dropNode.Nodes[_index].Bounds; + TreeView tv = DropNode.TreeView; + Rectangle r2 = DropNode.Nodes[Index].Bounds; Rectangle r3 = tn.Bounds; - int y = (_position == DropPosition.Before ? r2.Y : r3.Bottom); + int y = (Position == DropPosition.Before ? r2.Y : r3.Bottom); int x = r2.Left; if (y == 0) @@ -4214,10 +3723,10 @@ namespace Volian.Controls.Library } //if(_MyLog.IsInfoEnabled)_MyLog.InfoFormat("Line at {0} Node {1}[{2}] {3}", _location, _dropNode.Text, _index, _position.ToString()); // Changed the color of the drag indicator to always be red - Color lc = (_position == DropPosition.After ? Color.Red : Color.Red); - Brush lb = (_position == DropPosition.After ? Brushes.Red : Brushes.Red); + Color lc = (Position == DropPosition.After ? Color.Red : Color.Red); + Brush lb = (Position == DropPosition.After ? Brushes.Red : Brushes.Red); Point[] RightTriangle; - if (_position == DropPosition.After) + if (Position == DropPosition.After) { RightTriangle = new Point[]{ new Point(x, y ), @@ -4236,37 +3745,27 @@ namespace Volian.Controls.Library } public void ShowLocation(System.Windows.Forms.DragEventArgs e, bool ScrollOnly) { - //if (e.Effect == DragDropEffects.None) return; - if (_dropNode != null) + if (DropNode != null) { // if(_MyLog.IsInfoEnabled)_MyLog.InfoFormat("ShowLocation1 {0} {1}", e.Effect.ToString(), DateTime.Now.Millisecond); DragHelper.ImageList_DragShowNolock(false); - TreeView tv = _dropNode.TreeView; + TreeView tv = DropNode.TreeView; TreeNode tmp = tv.GetNodeAt(tv.PointToClient(new Point(e.X, e.Y))); - // if (!ScrollOnly) - // { if (ScrollTreeView(tmp) || !ScrollOnly) { //if(_MyLog.IsInfoEnabled)_MyLog.InfoFormat("ShowLocation2 {0} {1}", e.Effect.ToString(), DateTime.Now.Millisecond); tv.Refresh(); if (e.Effect != DragDropEffects.None) { - //tv.SelectedNode = dropNode; Graphics g = tv.CreateGraphics(); TreeNodeTriangle(g); - if (_position != DropPosition.Child) InsertPointer(tmp, g); + if (Position != DropPosition.Child) InsertPointer(tmp, g); } } - // } - // else ScrollTreeView(tmp); DragHelper.ImageList_DragShowNolock(true); } } #endregion - public void ShowLocation() - { - //if(_MyLog.IsInfoEnabled)_MyLog.InfoFormat("{0}[{1}] {2}", _dropNode.Text, _index, _position.ToString()); - } #region AutoScroll private bool ScrollTreeView(TreeNode tn) { @@ -4286,17 +3785,13 @@ namespace Volian.Controls.Library if (tn.PrevVisibleNode != null && tn.PrevVisibleNode.IsVisible == false) tn.PrevVisibleNode.EnsureVisible();// Make sure that the previous node is visible retval = (top != tn.Bounds.Top); - // if (retval) if(_MyLog.IsInfoEnabled)_MyLog.Info("Scroll"); } return retval; } - #endregion - public bool Equals(DropLocation dl) - { - return (dl != null && _lastScroll.Equals(dl.LastScroll) && _dropNode.Equals(dl.DropNode) && - _position.Equals(dl.Position)); - } - } + #endregion + public bool Equals(DropLocation dl) => dl != null && _lastScroll.Equals(dl.LastScroll) && DropNode.Equals(dl.DropNode) && + Position.Equals(dl.Position); + } private DropLocation _LastDropLocation = null; private void tv_DragOver(object sender, System.Windows.Forms.DragEventArgs e) { @@ -4326,17 +3821,15 @@ namespace Volian.Controls.Library ee = DragDropEffects.None; else if (IsFolder((VETreeNode)dragNode)) // Folder move is only valid if moving to folder with NO docversions { - FolderInfo fdropi = ((VETreeNode)dl.DropNode).VEObject as FolderInfo; - if (fdropi == null || fdropi.FolderDocVersionCount > 0) ee = DragDropEffects.None; - } + if (!(((VETreeNode)dl.DropNode).VEObject is FolderInfo fdropi) || fdropi.FolderDocVersionCount > 0) ee = DragDropEffects.None; + } else if (IsSection((VETreeNode)dragNode)) { - // A section can be moved within a procedure or to a section within the same procedure... - // For HLP, just move within the same procedure - // TODO: allow for section move within subsections. - ProcedureInfo pdropi = ((VETreeNode)dl.DropNode).VEObject as ProcedureInfo; - if (pdropi == null || (dragNode.Parent != dl.DropNode)) ee = DragDropEffects.None; - } + // A section can be moved within a procedure or to a section within the same procedure... + // For HLP, just move within the same procedure + // TODO: allow for section move within subsections. + if (!(((VETreeNode)dl.DropNode).VEObject is ProcedureInfo pdropi) || (dragNode.Parent != dl.DropNode)) ee = DragDropEffects.None; + } else if (!IsFolder((VETreeNode)dragNode) && (dragNode.Parent != dl.DropNode)) ee = DragDropEffects.None; if (e.Effect != ee) e.Effect = ee; @@ -4350,25 +3843,10 @@ namespace Volian.Controls.Library } } - private bool IsSection(VETreeNode vETreeNode) - { - SectionInfo sectInfo = vETreeNode.VEObject as SectionInfo; - if (sectInfo != null) return true; - return false; - } - private bool IsProcedure(VETreeNode vETreeNode) - { - ProcedureInfo procInfo = vETreeNode.VEObject as ProcedureInfo; - if (procInfo != null) return true; - return false; - } - private bool IsDocVersion(VETreeNode dragNode) - { - DocVersionInfo dvInfo = dragNode.VEObject as DocVersionInfo; - if (dvInfo != null) return true; - return false; - } - private bool AllowedToMove(VETreeNode dragNode) + private bool IsSection(VETreeNode vETreeNode) => vETreeNode.VEObject is SectionInfo; + private bool IsProcedure(VETreeNode vETreeNode) => vETreeNode.VEObject is ProcedureInfo; + private bool IsDocVersion(VETreeNode dragNode) => dragNode.VEObject is DocVersionInfo; + private bool AllowedToMove(VETreeNode dragNode) { DocVersionInfo dvInfo = null; if (IsFolder(dragNode)) @@ -4405,11 +3883,8 @@ namespace Volian.Controls.Library } return null; } - private bool IsFolder(VETreeNode veTreeNode) - { - return (veTreeNode.VEObject.GetType() == typeof(FolderInfo)); - } - private void tv_DragDrop(object sender, System.Windows.Forms.DragEventArgs e) + private bool IsFolder(VETreeNode veTreeNode) => veTreeNode.VEObject.GetType() == typeof(FolderInfo); + private void tv_DragDrop(object sender, System.Windows.Forms.DragEventArgs e) { try { @@ -4424,28 +3899,25 @@ namespace Volian.Controls.Library dragNode = Clone(dragNode); _LastDropLocation.DropNode.Nodes.Insert(index, dragNode); this.SelectedNode = dragNode; - FolderInfo fdragi = ((VETreeNode)dragNode).VEObject as FolderInfo; - FolderInfo fdropi = ((VETreeNode)_LastDropLocation.DropNode).VEObject as FolderInfo; - if (fdragi != null && fdropi != null && fdropi.FolderDocVersionCount == 0) - { - using (Folder fdrag = fdragi.Get()) - { - using (Folder fdrop = fdropi.Get()) - { - fdrag.ManualOrder = fdropi.NewManualOrder(myIndex); - fdrag.MyParent = fdrop; - fdrag.Save(); - } - } - return; - } - // No drag/drop supported for document versions. + if (((VETreeNode)dragNode).VEObject is FolderInfo fdragi && ((VETreeNode)_LastDropLocation.DropNode).VEObject is FolderInfo fdropi && fdropi.FolderDocVersionCount == 0) + { + using (Folder fdrag = fdragi.Get()) + { + using (Folder fdrop = fdropi.Get()) + { + fdrag.ManualOrder = fdropi.NewManualOrder(myIndex); + fdrag.MyParent = fdrop; + fdrag.Save(); + } + } + return; + } + // No drag/drop supported for document versions. - // Allow drag/drop of procedures within a Document Version (must have same parent). Note that drop location - // may either be a document version or a procedure depending on where the user wants to position the procedure. - ProcedureInfo pdragi = ((VETreeNode)dragNode).VEObject as ProcedureInfo; - ProcedureInfo pdropi = null; - if (pdragi != null) // moving a procedure + // Allow drag/drop of procedures within a Document Version (must have same parent). Note that drop location + // may either be a document version or a procedure depending on where the user wants to position the procedure. + ProcedureInfo pdropi = null; + if (((VETreeNode)dragNode).VEObject is ProcedureInfo pdragi) // moving a procedure { pdropi = ((VETreeNode)_LastDropLocation.DropNode).VEObject as ProcedureInfo; if (pdropi != null && pdragi.ActiveParent == pdropi.ActiveParent) @@ -4453,19 +3925,17 @@ namespace Volian.Controls.Library pdragi.MoveProcedure(pdragi.ActiveParent, myIndex); return; } - DocVersionInfo dvdropi = ((VETreeNode)_LastDropLocation.DropNode).VEObject as DocVersionInfo; - DocVersionInfo dvdragpar = pdragi.ActiveParent as DocVersionInfo; - if (dvdropi != null && dvdragpar.VersionID == dvdropi.VersionID) + DocVersionInfo dvdragpar = pdragi.ActiveParent as DocVersionInfo; + if (((VETreeNode)_LastDropLocation.DropNode).VEObject is DocVersionInfo dvdropi && dvdragpar.VersionID == dvdropi.VersionID) { pdragi.MoveProcedure(dvdropi, myIndex); return; } } - // Allow drag/drop of sections within the same procedure or same section (if subsection) (must have same parent) - SectionInfo sdragi = ((VETreeNode)dragNode).VEObject as SectionInfo; - SectionInfo sdropi = null; - if (sdragi != null) // moving a section + // Allow drag/drop of sections within the same procedure or same section (if subsection) (must have same parent) + SectionInfo sdropi = null; + if (((VETreeNode)dragNode).VEObject is SectionInfo sdragi) // moving a section { sdropi = ((VETreeNode)_LastDropLocation.DropNode).VEObject as SectionInfo; if (sdropi != null && sdragi.ActiveParent == sdropi.ActiveParent) @@ -4483,10 +3953,9 @@ namespace Volian.Controls.Library } } - // Allow drag/drop of steps within the same parent only - StepInfo stdragi = ((VETreeNode)dragNode).VEObject as StepInfo; - StepInfo stdropi = null; - if (stdragi != null) // moving a step + // Allow drag/drop of steps within the same parent only + StepInfo stdropi = null; + if (((VETreeNode)dragNode).VEObject is StepInfo stdragi) // moving a step { stdropi = ((VETreeNode)_LastDropLocation.DropNode).VEObject as StepInfo; if (stdropi != null && stdragi.ActiveParent == stdropi.ActiveParent) @@ -4513,28 +3982,6 @@ namespace Volian.Controls.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("tv_DragDrop", ex); } } - // private void DumpMembers(object o) - // { - // Type t = o.GetType(); - // //if(_MyLog.IsInfoEnabled)_MyLog.InfoFormat("\r\n\r\nMembers for type {0}", t.ToString()); - // MemberInfo[] mis = t.GetMembers(); - // int i = 0; - // foreach (MemberInfo mi in mis) - // { - // i++; - // try - // { - // //if(mi.MemberType != MemberTypes.Method) - // //if(_MyLog.IsInfoEnabled)_MyLog.InfoFormat("{0} {1} {2}", i, mi.Name, mi.MemberType); - //// if (fi.Name == "TreeView") - //// fi.SetValue(o, null); - // } - // catch (Exception ex) - // { - // if(_MyLog.IsErrorEnabled)_MyLog.Error("DumpMembers", ex); - // } - // } - // } private TreeNode Clone(TreeNode tn) { @@ -4553,11 +4000,8 @@ namespace Volian.Controls.Library dragNode.Remove(); this.SelectedNode = cloneNode; } - private void tv_DragEnter(object sender, System.Windows.Forms.DragEventArgs e) - { - DragHelper.ImageList_DragEnter(this.Handle, e.X - this.Left, e.Y - this.Top); - } - private void tv_DragLeave(object sender, System.EventArgs e) + private void tv_DragEnter(object sender, System.Windows.Forms.DragEventArgs e) => DragHelper.ImageList_DragEnter(this.Handle, e.X - this.Left, e.Y - this.Top); + private void tv_DragLeave(object sender, System.EventArgs e) { DragHelper.ImageList_DragLeave(this.Handle); this.Refresh(); @@ -4637,30 +4081,27 @@ namespace Volian.Controls.Library // B2021-066: refresh the procedure numbers within Working Draft (docversion) for applicability changed public void RefreshDocVersion() { - VETreeNode vetn = SelectedNode as VETreeNode; - if (vetn != null) - { - DocVersionInfo dvi = vetn.VEObject as DocVersionInfo; - if (dvi != null) - { - if (SelectedNode.Nodes != null && SelectedNode.Nodes.Count > 0 && SelectedNode.Nodes[0] is VETreeNode) - { - foreach (VETreeNode tn in SelectedNode.Nodes) - { - tn.RefreshNode(); - } - } - } - } - } + if (SelectedNode is VETreeNode vetn) + { + if (vetn.VEObject is DocVersionInfo) + { + if (SelectedNode.Nodes != null && SelectedNode.Nodes.Count > 0 && SelectedNode.Nodes[0] is VETreeNode) + { + foreach (VETreeNode tn in SelectedNode.Nodes) + { + tn.RefreshNode(); + } + } + } + } + } private VETreeNode GetChildNode(IVEDrillDownReadOnly selectedItem, VETreeNode parent) { foreach (TreeNode childNode in parent.Nodes) { - VETreeNode child = childNode as VETreeNode; - if (child != null && CompareVEObject(child.VEObject, selectedItem)) - return child; - } + if (childNode is VETreeNode child && CompareVEObject(child.VEObject, selectedItem)) + return child; + } foreach (TreeNode childNode in parent.Nodes) { VETreeNode child = childNode as VETreeNode; @@ -4675,22 +4116,17 @@ namespace Volian.Controls.Library { if (obj1.GetType().Name != obj2.GetType().Name) { - // see if both can be cast as ItemInfo, because 1st check may be comparing ItemInfo & ProcedureInfo and returns - // false even though they are same base object type (fixes bug B2016-094) - ItemInfo ii1 = obj1 as ItemInfo; - ItemInfo ii2 = obj2 as ItemInfo; - if (ii1 == null || ii2 == null) return false; - } - ItemInfo myItem = obj1 as ItemInfo; - if (myItem != null) - if (myItem.ItemID == ((ItemInfo)obj2).ItemID) return true; - DocVersionInfo myDV = obj1 as DocVersionInfo; - if (myDV != null) - if (myDV.VersionID == ((DocVersionInfo)obj2).VersionID) return true; - FolderInfo myFolder = obj1 as FolderInfo; - if (myFolder != null) - if (myFolder.FolderID == ((FolderInfo)obj2).FolderID) return true; - return false; + // see if both can be cast as ItemInfo, because 1st check may be comparing ItemInfo & ProcedureInfo and returns + // false even though they are same base object type (fixes bug B2016-094) + if (!(obj1 is ItemInfo) || !(obj2 is ItemInfo)) return false; + } + if (obj1 is ItemInfo myItem) + if (myItem.ItemID == ((ItemInfo)obj2).ItemID) return true; + if (obj1 is DocVersionInfo myDV) + if (myDV.VersionID == ((DocVersionInfo)obj2).VersionID) return true; + if (obj1 is FolderInfo myFolder) + if (myFolder.FolderID == ((FolderInfo)obj2).FolderID) return true; + return false; } //C2021-035 Add Refresh Tree Option at highest level @@ -4710,15 +4146,14 @@ namespace Volian.Controls.Library DocVersionInfo.ResetAllProcedures(); FolderInfo.ClearFolderInfoCache(); - //Refresh the base VEPROMS object - var fldr = tbase.VEObject as FolderInfo; - if (fldr != null) - { - Invoke((Action)(() => { tbase.VEObject = FolderInfo.Get(fldr.FolderID); })); - } + //Refresh the base VEPROMS object + if (tbase.VEObject is FolderInfo fldr) + { + Invoke((Action)(() => { tbase.VEObject = FolderInfo.Get(fldr.FolderID); })); + } - //refresh the tree - Invoke((Action)(() => { tbase.RefreshNode(); })); + //refresh the tree + Invoke((Action)(() => { tbase.RefreshNode(); })); this.Invoke((Action)(() => { this.Update(); })); } diff --git a/PROMS/Volian.Controls.Library/vlnTreeView3.cs b/PROMS/Volian.Controls.Library/vlnTreeView3.cs index 7c2d2b19..d8b12077 100644 --- a/PROMS/Volian.Controls.Library/vlnTreeView3.cs +++ b/PROMS/Volian.Controls.Library/vlnTreeView3.cs @@ -1,63 +1,24 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Text; using System.Windows.Forms; -using VEPROMS.CSLA.Library; namespace Volian.Controls.Library { - //public delegate void vlnTreeViewEvent(object sender, vlnTreeEventArgs args); - //public delegate bool vlnTreeViewBoolEvent(object sender, vlnTreeEventArgs args); - //public delegate TreeNode vlnTreeViewTreeNodeEvent(object sender, vlnTreeEventArgs args); - //public delegate void vlnTreeViewDDEvent(object sender, System.Windows.Forms.DragEventArgs args); public partial class vlnTreeView3 : TreeView { - private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #region Events public event vlnTreeViewEvent NodeSelectionChange; - private void OnNodeSelectionChange(object sender, vlnTreeEventArgs args) - { - if (NodeSelectionChange != null) NodeSelectionChange(sender, args); - } - #endregion - #region Business Methods - #endregion - #region Constructors - public vlnTreeView3() + private void OnNodeSelectionChange(object sender, vlnTreeEventArgs args) => NodeSelectionChange?.Invoke(sender, args); + #endregion + #region Business Methods + #endregion + #region Constructors + public vlnTreeView3() { InitializeComponent(); base.AfterSelect += new TreeViewEventHandler(tv_AfterSelect); } - private void tv_AfterSelect(object sender, TreeViewEventArgs e) - { - OnNodeSelectionChange(sender, new vlnTreeEventArgs(e.Node)); - } - #endregion - private static TreeNode GetTreeNodeFromData(IDataObject datobj) - { - foreach (string s in datobj.GetFormats()) - { - try - { - return (TreeNode)datobj.GetData(s); - } - catch (Exception ex) - { - if (_MyLog.IsErrorEnabled) _MyLog.Error("GetTreeNodeFromData", ex); - } - } - return null; - } - private TreeNode Clone(TreeNode tn) - { - - TreeNode tmp = (TreeNode)tn.Clone(); - ExpandMatch(tmp, tn); - return tmp; - } - private void ExpandMatch(TreeNode tn1, TreeNode tn2) + private void tv_AfterSelect(object sender, TreeViewEventArgs e) => OnNodeSelectionChange(sender, new vlnTreeEventArgs(e.Node)); + #endregion + private void ExpandMatch(TreeNode tn1, TreeNode tn2) { if (tn2.IsExpanded) tn1.Expand(); foreach (TreeNode tc in tn2.Nodes) ExpandMatch(tn1.Nodes[tc.Index], tc);